diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml new file mode 100644 index 0000000..38a3f35 --- /dev/null +++ b/.github/workflows/android.yml @@ -0,0 +1,41 @@ +name: Android launcher + +on: + push: + branches: [main] + paths: ["android/**", "examples/launcher/**", ".github/workflows/android.yml"] + pull_request: + paths: ["android/**", "examples/launcher/**", ".github/workflows/android.yml"] + workflow_dispatch: + +permissions: + contents: write + +jobs: + apk: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 17 + - uses: gradle/actions/setup-gradle@v4 + - name: Build the APK + working-directory: android + run: ./gradlew --no-daemon assembleDebug + - uses: actions/upload-artifact@v4 + with: + name: ultra-launcher-apk + path: android/app/build/outputs/apk/debug/app-debug.apk + # Keep a "launcher-latest" prerelease with the newest APK, so a phone can download it directly. + - name: Publish the launcher-latest release + if: github.event_name != 'pull_request' + env: + GH_TOKEN: ${{ github.token }} + run: | + cp android/app/build/outputs/apk/debug/app-debug.apk ultra-launcher.apk + gh release delete launcher-latest --yes --cleanup-tag || true + gh release create launcher-latest ultra-launcher.apk --prerelease --target "$GITHUB_SHA" \ + --title "ultra launcher (latest build)" \ + --notes "Debug-signed APK of android/ built from $GITHUB_SHA. Install it, press Home, and pick ultra Home." diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100644 index 0000000..9248185 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,37 @@ +plugins { + id "com.android.application" +} + +android { + namespace "dev.ultra.launcher" + compileSdk 35 + + defaultConfig { + applicationId "dev.ultra.launcher" + minSdk 26 + targetSdk 35 + versionCode 1 + versionName "0.1" + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + + sourceSets { + // The home screen UI is the ultra app in examples/launcher, served from assets. + main.assets.srcDirs = ["$rootDir/../examples/launcher"] + } + + androidResources { + // app.py is the LPython source and apps.json is the browser demo's stand-in. + ignoreAssetsPattern = "!app.py:!apps.json:!__pycache__:!.*" + } + + buildTypes { + release { + minifyEnabled false + } + } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..2881322 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,36 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/java/dev/ultra/launcher/MainActivity.java b/android/app/src/main/java/dev/ultra/launcher/MainActivity.java new file mode 100644 index 0000000..a8ebc95 --- /dev/null +++ b/android/app/src/main/java/dev/ultra/launcher/MainActivity.java @@ -0,0 +1,329 @@ +package dev.ultra.launcher; + +import android.app.Activity; +import android.content.ActivityNotFoundException; +import android.content.ComponentName; +import android.content.Intent; +import android.content.pm.LauncherActivityInfo; +import android.content.pm.LauncherApps; +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Insets; +import android.graphics.drawable.Drawable; +import android.net.Uri; +import android.os.Build; +import android.os.Bundle; +import android.os.Handler; +import android.os.Looper; +import android.os.Process; +import android.os.UserHandle; +import android.provider.Settings; +import android.text.format.DateFormat; +import android.view.View; +import android.view.Window; +import android.view.WindowInsets; +import android.webkit.JavascriptInterface; +import android.webkit.RenderProcessGoneDetail; +import android.webkit.WebResourceRequest; +import android.webkit.WebResourceResponse; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import android.widget.Toast; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.text.Collator; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The home screen activity. The UI is the ultra app in examples/launcher (LPython compiled + * to wasm), packaged as assets and served to a transparent WebView from a virtual https + * origin. This class answers the two dynamic URLs the app fetches: + * + * apps.json {"apps": [{"label", "component", "icon"}]}, every launchable activity + * icon?c=COMP the activity's icon as a PNG + * + * and exposes window.Android (launch, appInfo, openSettings, pickWallpaper, is24Hour) for + * the app's @jscall imports. Package changes, the home button, back and resume are passed + * to the page as window.ultraHome.reload() / home() / back() / tick(). + */ +public class MainActivity extends Activity { + static final String HOST = "appassets.androidplatform.net"; + static final String ORIGIN = "https://" + HOST + "/"; + static final int ICON_DP = 56; + + private WebView web; + private boolean ready; + private int insetTop, insetBottom; // CSS px + private LauncherApps launcher; + private final UserHandle user = Process.myUserHandle(); + private final Map icons = new ConcurrentHashMap<>(); + private final Handler main = new Handler(Looper.getMainLooper()); + + private final LauncherApps.Callback packages = new LauncherApps.Callback() { + @Override public void onPackageRemoved(String pkg, UserHandle u) { reload(); } + @Override public void onPackageAdded(String pkg, UserHandle u) { reload(); } + @Override public void onPackageChanged(String pkg, UserHandle u) { reload(); } + @Override public void onPackagesAvailable(String[] pkgs, UserHandle u, boolean replacing) { reload(); } + @Override public void onPackagesUnavailable(String[] pkgs, UserHandle u, boolean replacing) { reload(); } + }; + + @Override + protected void onCreate(Bundle state) { + super.onCreate(state); + launcher = getSystemService(LauncherApps.class); + launcher.registerCallback(packages, main); + + Window w = getWindow(); + if (Build.VERSION.SDK_INT >= 30) { + w.setDecorFitsSystemWindows(false); + } else { + w.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE + | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION); + } + createWebView(); + } + + private void createWebView() { + ready = false; + web = new WebView(this); + web.setBackgroundColor(Color.TRANSPARENT); + web.setVerticalScrollBarEnabled(false); + web.setOverScrollMode(View.OVER_SCROLL_NEVER); + WebSettings s = web.getSettings(); + s.setJavaScriptEnabled(true); + s.setDomStorageEnabled(true); // the dock is saved in localStorage + s.setAllowFileAccess(false); + s.setAllowContentAccess(false); + web.addJavascriptInterface(new Bridge(), "Android"); + web.setWebViewClient(new Client()); + web.setOnApplyWindowInsetsListener((v, insets) -> { + int top, bottom; + if (Build.VERSION.SDK_INT >= 30) { + Insets bars = insets.getInsets(WindowInsets.Type.systemBars() | WindowInsets.Type.displayCutout()); + Insets ime = insets.getInsets(WindowInsets.Type.ime()); + top = bars.top; + bottom = Math.max(bars.bottom, ime.bottom); + } else { + top = insets.getSystemWindowInsetTop(); + bottom = insets.getSystemWindowInsetBottom(); + } + float d = getResources().getDisplayMetrics().density; + insetTop = Math.round(top / d); + insetBottom = Math.round(bottom / d); + pushInsets(); + return insets; + }); + setContentView(web); + web.loadUrl(ORIGIN + "index.html"); + } + + @Override + protected void onDestroy() { + launcher.unregisterCallback(packages); + web.destroy(); + super.onDestroy(); + } + + // The home button while we are already in front. + @Override + protected void onNewIntent(Intent intent) { + super.onNewIntent(intent); + js("home()"); + } + + @Override + protected void onResume() { + super.onResume(); + js("tick()"); + } + + // A home screen has nowhere to go back to; let the page clear its search or edit mode. + @Override + @SuppressWarnings("deprecation") + public void onBackPressed() { + js("back()"); + } + + private void js(String call) { + if (ready) web.evaluateJavascript("window.ultraHome && ultraHome." + call, null); + } + + private void pushInsets() { + if (!ready) return; + web.evaluateJavascript("(s => { s.setProperty('--inset-top', '" + insetTop + "px');" + + " s.setProperty('--inset-bottom', '" + insetBottom + "px'); })" + + "(document.documentElement.style)", null); + } + + private void reload() { + icons.clear(); + js("reload()"); + } + + // ------------------------------------------------------------ apps + + private String appsJson() throws JSONException { + List list = new ArrayList<>(launcher.getActivityList(null, user)); + Map labels = new HashMap<>(); + for (LauncherActivityInfo a : list) labels.put(a, String.valueOf(a.getLabel())); + Collator by = Collator.getInstance(); + list.sort((a, b) -> by.compare(labels.get(a), labels.get(b))); + JSONArray apps = new JSONArray(); + for (LauncherActivityInfo a : list) { + ComponentName cn = a.getComponentName(); + if (cn.getPackageName().equals(getPackageName())) continue; + String c = cn.flattenToShortString(); + apps.put(new JSONObject() + .put("label", labels.get(a)) + .put("component", c) + .put("icon", "icon?c=" + Uri.encode(c))); + } + return new JSONObject().put("apps", apps).toString(); + } + + private byte[] iconPng(String c) { + byte[] png = icons.get(c); + if (png != null) return png; + ComponentName cn = c == null ? null : ComponentName.unflattenFromString(c); + if (cn == null) return null; + LauncherActivityInfo info = launcher.resolveActivity( + new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(cn), user); + if (info == null) return null; + int dpi = getResources().getDisplayMetrics().densityDpi; + Drawable d = info.getIcon(dpi); + int size = Math.round(ICON_DP * dpi / 160f); + Bitmap bmp = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888); + d.setBounds(0, 0, size, size); + d.draw(new Canvas(bmp)); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + bmp.compress(Bitmap.CompressFormat.PNG, 100, out); + bmp.recycle(); + png = out.toByteArray(); + icons.put(c, png); + return png; + } + + private void start(String component) { + ComponentName cn = ComponentName.unflattenFromString(component); + try { + launcher.startMainActivity(cn, user, null, null); + } catch (ActivityNotFoundException | SecurityException | NullPointerException e) { + Toast.makeText(this, "Can't open " + component, Toast.LENGTH_SHORT).show(); + } + } + + private void startIntent(Intent i) { + try { + startActivity(i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + } catch (ActivityNotFoundException e) { + Toast.makeText(this, "Not available on this device", Toast.LENGTH_SHORT).show(); + } + } + + /** window.Android: called from the page's @jscall imports on a binder thread. */ + final class Bridge { + @JavascriptInterface public void launch(String component) { + main.post(() -> start(component)); + } + + @JavascriptInterface public void appInfo(String component) { + main.post(() -> { + ComponentName cn = ComponentName.unflattenFromString(component); + if (cn != null) launcher.startAppDetailsActivity(cn, user, null, null); + }); + } + + @JavascriptInterface public void openSettings() { + main.post(() -> startIntent(new Intent(Settings.ACTION_SETTINGS))); + } + + @JavascriptInterface public void pickWallpaper() { + main.post(() -> startIntent(Intent.createChooser(new Intent(Intent.ACTION_SET_WALLPAPER), "Wallpaper"))); + } + + @JavascriptInterface public boolean is24Hour() { + return DateFormat.is24HourFormat(MainActivity.this); + } + } + + // ------------------------------------------------------------ serving + + final class Client extends WebViewClient { + @Override + public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest req) { + Uri u = req.getUrl(); + if (!HOST.equals(u.getHost())) return notFound(); + String path = u.getPath() == null ? "/" : u.getPath(); + try { + switch (path) { + case "/apps.json": + return respond("application/json", + new ByteArrayInputStream(appsJson().getBytes(StandardCharsets.UTF_8))); + case "/icon": + byte[] png = iconPng(u.getQueryParameter("c")); + return png == null ? notFound() : respond("image/png", new ByteArrayInputStream(png)); + default: + String name = path.equals("/") ? "index.html" : path.substring(1); + return respond(mime(name), getAssets().open(name)); + } + } catch (IOException | JSONException | RuntimeException e) { + return notFound(); + } + } + + @Override + public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest req) { + return true; // the home screen never navigates away + } + + @Override + public void onPageFinished(WebView view, String url) { + ready = true; + pushInsets(); + } + + @Override + public boolean onRenderProcessGone(WebView view, RenderProcessGoneDetail detail) { + // The renderer was killed (e.g. under memory pressure): start over with a new WebView. + web.destroy(); + createWebView(); + return true; + } + } + + private static WebResourceResponse respond(String mime, InputStream body) { + Map headers = new HashMap<>(); + headers.put("Cache-Control", "no-cache"); + return new WebResourceResponse(mime, null, 200, "OK", headers, body); + } + + private static WebResourceResponse notFound() { + return new WebResourceResponse("text/plain", null, 404, "Not Found", new HashMap<>(), + new ByteArrayInputStream(new byte[0])); + } + + private static String mime(String name) { + if (name.endsWith(".html")) return "text/html"; + if (name.endsWith(".js")) return "text/javascript"; + if (name.endsWith(".css")) return "text/css"; + if (name.endsWith(".wasm")) return "application/wasm"; + if (name.endsWith(".json")) return "application/json"; + if (name.endsWith(".png")) return "image/png"; + if (name.endsWith(".svg")) return "image/svg+xml"; + return "application/octet-stream"; + } +} diff --git a/android/app/src/main/res/drawable/ic_launcher_background.xml b/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..ebba2d9 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + + diff --git a/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/android/app/src/main/res/drawable/ic_launcher_foreground.xml new file mode 100644 index 0000000..d1f97a6 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_launcher_foreground.xml @@ -0,0 +1,8 @@ + + + + + diff --git a/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..6b78462 --- /dev/null +++ b/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..ecacc41 --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + ultra Home + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..9449e95 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,11 @@ + + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..48d2fa1 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,3 @@ +plugins { + id "com.android.application" version "8.7.3" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..5d8fa4a --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +android.useAndroidX=false +android.nonTransitiveRClass=true diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e2847c8 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 0000000..5eed7ee --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100644 index 0000000..22536db --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,16 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = "ultra-launcher" +include ":app" diff --git a/tests/e2e.cjs b/tests/e2e.cjs index 43a87a9..b97d6a5 100644 --- a/tests/e2e.cjs +++ b/tests/e2e.cjs @@ -178,5 +178,32 @@ const BASE = process.env.BASE || "http://localhost:8000"; assert.ok(await p.$(".page.dark")); console.log("ui ok"); + // launcher: the Android home screen, against the demo apps.json + await p.goto(BASE + "/examples/launcher/"); + await p.evaluate(() => localStorage.clear()); + await p.reload(); + await p.waitForSelector(".tile"); + const names = () => p.$$eval(".tile .name", (ns) => ns.map((n) => n.textContent)); + assert.equal((await names()).length, 16); + assert.match(await p.textContent(".clock .time"), /^\d{1,2}:\d\d$/); + await p.fill(".search input", "ca"); await tick(); + assert.deepEqual(await names(), ["Calculator", "Calendar", "Camera"]); + await p.press(".search input", "Enter"); await tick(); + assert.equal(await p.textContent("#toast"), "Open com.example.calculator/.MainActivity"); + assert.equal(await p.inputValue(".search input"), "", "launching clears the search"); + await p.click("text=Edit dock"); await tick(); + await p.click(".tile:nth-child(4)", { force: true }); await p.click(".tile:nth-child(8)", { force: true }); await tick(); + assert.equal(await p.$$eval(".tile.pinned", (ts) => ts.length), 2); + await p.click("text=Done"); await tick(); + await p.reload(); await p.waitForSelector(".dock-app"); + assert.deepEqual(await p.$$eval(".dock-app", (ds) => ds.map((d) => d.getAttribute("aria-label"))), ["Chrome", "Gmail"]); + await p.click(".dock-app:first-child"); await tick(); + assert.equal(await p.textContent("#toast"), "Open com.example.chrome/.MainActivity"); + await p.fill(".search input", "zzz"); await tick(); + assert.equal(await p.textContent(".empty"), "No apps match."); + await p.evaluate(() => window.ultraHome.back()); await tick(); + assert.equal((await names()).length, 16, "back clears the search"); + console.log("launcher ok"); + await b.close(); })().catch((e) => { console.error(e); process.exit(1); }); diff --git a/web/app.py b/web/app.py new file mode 100644 index 0000000..0a10b69 --- /dev/null +++ b/web/app.py @@ -0,0 +1,369 @@ +from lpython import i32, Const +from numpy import empty, int32 +from ultra import (el, end, text, text_ref, cls, cls_if, attr, attr_ref, key, + on_click, on_enter, on_escape, after, div, + s_new, s_dup, s_clear, s_free, s_copy, s_eq, s_has, s_len, + s_save_at, s_load_at, store_i32, load_i32, + http_get, j_ok, j_err, j_at, j_idx, j_len, j_str, j_free) +from ui import btn_open, input_open, alert + +# An Android home screen. The native shell (android/) serves this folder in a +# WebView, answers apps.json with the installed launchable activities, and +# provides the imports below. In a desktop browser index.html supplies stand-ins. + +@jscall +def launch(component: i32) -> None: + """Start the activity named by a "pkg/cls" string handle.""" + pass + +@jscall +def app_info(component: i32) -> None: + pass + +@jscall +def open_settings() -> None: + pass + +@jscall +def pick_wallpaper() -> None: + pass + +@jscall +def clock_time(dst: i32) -> None: + """Write the local time ("15:04") into dst.""" + pass + +@jscall +def clock_date(dst: i32) -> None: + """Write the local date ("Tuesday, October 21") into dst.""" + pass + +# ---- Msg (index.html and MainActivity.java send RELOAD, HOME, BACK and TICK) +LOADED: Const[i32] = 1 +QUERY: Const[i32] = 2 +CLEAR: Const[i32] = 3 +OPEN: Const[i32] = 4 +OPEN_FIRST: Const[i32] = 5 +EDIT: Const[i32] = 6 +PIN: Const[i32] = 7 +INFO: Const[i32] = 8 +SETTINGS: Const[i32] = 9 +WALLPAPER: Const[i32] = 10 +TICK: Const[i32] = 11 +RELOAD: Const[i32] = 12 +HOME: Const[i32] = 13 +BACK: Const[i32] = 14 + +CAP: Const[i32] = 512 +DOCK: Const[i32] = 5 + +# ---- Model +# One row per launchable activity, as parallel columns of string handles. +labels: i32[512] = empty(512, dtype=int32) +comps: i32[512] = empty(512, dtype=int32) +icons: i32[512] = empty(512, dtype=int32) +n: i32 = 0 +# Dock: pinned activities, kept by component name so they survive reloads. +pins: i32[5] = empty(5, dtype=int32) +npin: i32 = 0 +query: i32 = 0 +now: i32 = 0 +today: i32 = 0 +err: i32 = 0 +loading: i32 = 1 +editing: i32 = 0 +pending: i32 = 0 # JSON handle of the apps.json request in flight + + +def init() -> None: + global query, now, today, err, npin, pending + i: i32 + h: i32 + query = s_new() + now = s_new() + today = s_new() + err = s_new() + count: i32 = load_i32("ultra.launcher.npin", 0) + for i in range(count): + h = s_new() + if s_load_at("ultra.launcher.pin", i, h) == 1 and npin < DOCK: + pins[npin] = h + npin += 1 + else: + s_free(h) + clock_time(now) + clock_date(today) + after(5000, TICK, 0) + pending = http_get("apps.json", LOADED) + + +def save_pins() -> None: + i: i32 + store_i32("ultra.launcher.npin", npin) + for i in range(npin): + s_save_at("ultra.launcher.pin", i, pins[i]) + + +def clear_apps() -> None: + global n + i: i32 + for i in range(n): + s_free(labels[i]) + s_free(comps[i]) + s_free(icons[i]) + n = 0 + + +def load(doc: i32) -> None: + global n, loading + arr: i32 + item: i32 + cnt: i32 + i: i32 + ok: i32 + loading = 0 + if j_ok(doc) == 0: + j_err(doc, err) + j_free(doc) + return + s_clear(err) + clear_apps() + arr = j_at(doc, "apps") + cnt = j_len(doc, "apps") + if cnt > CAP: + cnt = CAP + for i in range(cnt): + item = j_idx(arr, i) + labels[n] = s_new() + comps[n] = s_new() + icons[n] = s_new() + ok = j_str(item, "label", labels[n]) + ok = j_str(item, "component", comps[n]) + ok = j_str(item, "icon", icons[n]) + j_free(item) + n += 1 + j_free(arr) + j_free(doc) + + +def pin_of(i: i32) -> i32: + """Dock slot holding app i, or -1.""" + p: i32 + for p in range(npin): + if s_eq(pins[p], comps[i]) == 1: + return p + return -1 + + +def app_of(p: i32) -> i32: + """App row for dock slot p, or -1 if it is not installed (any more).""" + i: i32 + for i in range(n): + if s_eq(pins[p], comps[i]) == 1: + return i + return -1 + + +def toggle_pin(i: i32) -> None: + global npin + p: i32 = pin_of(i) + j: i32 + if p >= 0: + s_free(pins[p]) + for j in range(p, npin - 1): + pins[j] = pins[j + 1] + npin -= 1 + elif npin < DOCK: + pins[npin] = s_dup(comps[i]) + npin += 1 + save_pins() + + +def matches(i: i32) -> bool: + return s_has(labels[i], query) == 1 + + +def first_match() -> i32: + i: i32 + for i in range(n): + if matches(i): + return i + return -1 + + +def reset() -> None: + global editing + s_clear(query) + editing = 0 + + +# ---- Update +def update(msg: i32, arg: i32) -> None: + global loading, editing, pending + i: i32 + if msg == LOADED: + load(arg) + elif msg == QUERY: + s_copy(query, arg) + elif msg == CLEAR: + s_clear(query) + elif msg == OPEN: + if editing == 1: + toggle_pin(arg) + else: + launch(comps[arg]) + reset() + elif msg == OPEN_FIRST: + i = first_match() + if i >= 0 and s_len(query) > 0: + launch(comps[i]) + reset() + elif msg == EDIT: + editing = 1 - editing + elif msg == PIN: + toggle_pin(arg) + elif msg == INFO: + app_info(comps[arg]) + elif msg == SETTINGS: + open_settings() + elif msg == WALLPAPER: + pick_wallpaper() + elif msg == TICK: + clock_time(now) + clock_date(today) + if arg == 0: + after(5000, TICK, 0) + elif msg == RELOAD: + pending = http_get("apps.json", LOADED) + elif msg == HOME: + reset() + elif msg == BACK: + if editing == 1 or s_len(query) > 0: + reset() + + +# ---- View +def view_icon(i: i32) -> None: + el("img") + cls("icon") + attr("alt", "") + attr("loading", "lazy") + attr_ref("src", icons[i]) + end() + + +def view_tile(i: i32) -> None: + el("li") + key(i + 1) + cls("tile") + cls_if("pinned", editing == 1 and pin_of(i) >= 0) + on_click(OPEN, i) + view_icon(i) + el("span") + cls("name") + text_ref(labels[i]) + end() + if editing == 1: + el("button") + cls("info") + attr("aria-label", "App info") + on_click(INFO, i) + text("i") + end() + end() + + +def view_dock() -> None: + p: i32 + i: i32 + el("nav") + cls("dock") + for p in range(npin): + i = app_of(p) + if i >= 0: + el("button") + key(p + 1) + cls("dock-app") + attr_ref("aria-label", labels[i]) + on_click(OPEN, i) + view_icon(i) + end() + end() + + +def small_btn(s: str, msg: i32) -> None: + btn_open("ghost", msg, 0) + cls("sm") + text(s) + end() + + +def view() -> None: + i: i32 + shown: i32 = 0 + div("home") + cls_if("editing", editing == 1) + + el("header") + cls("clock") + div("time") + text_ref(now) + end() + div("date") + text_ref(today) + end() + end() + + div("search") + input_open("Search apps", query, QUERY) + attr("type", "search") + attr("enterkeyhint", "go") + on_enter(OPEN_FIRST, 0) + on_escape(CLEAR, 0) + end() + end() + + if s_len(err) > 0: + alert("Could not list apps", "", "destructive") + + el("ul") + cls("grid") + for i in range(n): + if matches(i): + view_tile(i) + shown += 1 + end() + if loading == 1: + el("p") + cls("empty") + text("Loading apps…") + end() + elif shown == 0: + el("p") + cls("empty") + text("No apps match.") + end() + + if editing == 1: + el("p") + cls("hint") + text("Tap apps to pin them to the dock (up to 5).") + end() + + div("bar") + if s_len(query) == 0: + view_dock() + div("actions") + btn_open("ghost", EDIT, 0) + cls("sm") + if editing == 1: + text("Done") + else: + text("Edit dock") + end() + small_btn("Wallpaper", WALLPAPER) + small_btn("Settings", SETTINGS) + end() + end() + + end() diff --git a/web/app.wasm b/web/app.wasm new file mode 100644 index 0000000..6b0c424 Binary files /dev/null and b/web/app.wasm differ diff --git a/web/apps.json b/web/apps.json new file mode 100644 index 0000000..974869a --- /dev/null +++ b/web/apps.json @@ -0,0 +1,84 @@ +{ + "apps": [ + { + "label": "Calculator", + "component": "com.example.calculator/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f59e0b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Calendar", + "component": "com.example.calendar/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%233b82f6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Camera", + "component": "com.example.camera/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2364748b%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Chrome", + "component": "com.example.chrome/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2322c55e%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Clock", + "component": "com.example.clock/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%230ea5e9%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Contacts", + "component": "com.example.contacts/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%236366f1%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EC%3C/text%3E%3C/svg%3E" + }, + { + "label": "Files", + "component": "com.example.files/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23eab308%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EF%3C/text%3E%3C/svg%3E" + }, + { + "label": "Gmail", + "component": "com.example.gmail/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ef4444%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EG%3C/text%3E%3C/svg%3E" + }, + { + "label": "Maps", + "component": "com.example.maps/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2310b981%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Messages", + "component": "com.example.messages/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%238b5cf6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Music", + "component": "com.example.music/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23ec4899%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EM%3C/text%3E%3C/svg%3E" + }, + { + "label": "Phone", + "component": "com.example.phone/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2314b8a6%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Photos", + "component": "com.example.photos/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%23f97316%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Play Store", + "component": "com.example.playstore/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2306b6d4%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EP%3C/text%3E%3C/svg%3E" + }, + { + "label": "Settings", + "component": "com.example.settings/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2371717a%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3ES%3C/text%3E%3C/svg%3E" + }, + { + "label": "Weather", + "component": "com.example.weather/.MainActivity", + "icon": "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2048%2048%22%3E%3Ccircle%20cx%3D%2224%22%20cy%3D%2224%22%20r%3D%2224%22%20fill%3D%22%2338bdf8%22/%3E%3Ctext%20x%3D%2224%22%20y%3D%2231%22%20font-family%3D%22sans-serif%22%20font-size%3D%2220%22%20font-weight%3D%22600%22%20fill%3D%22%23fff%22%20text-anchor%3D%22middle%22%3EW%3C/text%3E%3C/svg%3E" + } + ] +} \ No newline at end of file diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..651a262 --- /dev/null +++ b/web/index.html @@ -0,0 +1,62 @@ + + + + + + ultra · Launcher + + + + +
+
+ + + diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..7e90c6a --- /dev/null +++ b/web/style.css @@ -0,0 +1,66 @@ +/* Home screen layout; the components come from ui.css. The page is transparent so the + system wallpaper shows through the WebView. MainActivity sets --inset-top and + --inset-bottom to the status and navigation bar heights. */ +:root { + --top: var(--inset-top, env(safe-area-inset-top, 0px)); + --bottom: var(--inset-bottom, env(safe-area-inset-bottom, 0px)); +} +html, body { background: transparent; } +html.demo { background: linear-gradient(160deg, #1e293b, #4c1d95 55%, #0f172a) fixed; } +body { margin: 0; min-height: 100vh; color: #fff; -webkit-tap-highlight-color: transparent; + user-select: none; overscroll-behavior: none; } +#app { max-width: 560px; margin: 0 auto; } + +.home { min-height: 100vh; display: flex; flex-direction: column; box-sizing: border-box; + padding: calc(var(--top) + 2.5rem) 16px calc(var(--bottom) + 7.5rem); } + +.clock { text-align: center; text-shadow: 0 1px 8px rgb(0 0 0 / .45); margin-bottom: 1.5rem; } +.clock .time { font-size: 4rem; font-weight: 200; line-height: 1; letter-spacing: -.02em; + font-variant-numeric: tabular-nums; } +.clock .date { margin-top: .5rem; font-size: 1rem; opacity: .9; } + +.search { margin-bottom: 1.25rem; } +.search .input { height: 2.75rem; border-radius: 999px; padding: 0 1.25rem; font-size: 1rem; + background: rgb(0 0 0 / .35); border-color: rgb(255 255 255 / .15); color: #fff; + backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); } +.search .input::placeholder { color: rgb(255 255 255 / .65); } +.search .input::-webkit-search-cancel-button { filter: invert(1); } + +.grid { list-style: none; margin: 0; padding: 0; display: grid; gap: 1.25rem .5rem; + grid-template-columns: repeat(4, minmax(0, 1fr)); } +@media (min-width: 480px) { .grid { grid-template-columns: repeat(5, minmax(0, 1fr)); } } +.tile { position: relative; display: flex; flex-direction: column; align-items: center; gap: .4rem; + padding: .35rem .15rem; border-radius: calc(var(--radius) + 4px); cursor: pointer; } +.tile:active { background: rgb(255 255 255 / .12); } +.icon { width: 3.25rem; height: 3.25rem; object-fit: contain; pointer-events: none; + filter: drop-shadow(0 2px 4px rgb(0 0 0 / .3)); } +.name { max-width: 100%; font-size: .75rem; line-height: 1.2; text-align: center; + text-shadow: 0 1px 4px rgb(0 0 0 / .6); overflow: hidden; text-overflow: ellipsis; + white-space: nowrap; } +.editing .tile { animation: wiggle .3s ease-in-out infinite alternate; } +.editing .tile.pinned { background: rgb(255 255 255 / .18); outline: 2px solid rgb(255 255 255 / .6); } +.info { position: absolute; top: -.2rem; right: .15rem; width: 1.4rem; height: 1.4rem; padding: 0; + border: 0; border-radius: 999px; background: #fff; color: #111; font: italic 600 .8rem/1 serif; + box-shadow: 0 1px 3px rgb(0 0 0 / .4); } +@keyframes wiggle { from { transform: rotate(-1.2deg); } to { transform: rotate(1.2deg); } } +@media (prefers-reduced-motion: reduce) { .editing .tile { animation: none; } } + +.empty, .hint { text-align: center; opacity: .85; text-shadow: 0 1px 4px rgb(0 0 0 / .6); } +.hint { font-size: .875rem; margin-top: 1.25rem; } + +.bar { position: fixed; left: 0; right: 0; bottom: 0; display: grid; gap: .5rem; justify-items: center; + padding: .75rem 16px calc(var(--bottom) + .5rem); + background: linear-gradient(to top, rgb(0 0 0 / .45), transparent); } +.dock { display: flex; gap: 1rem; padding: .6rem 1rem; border-radius: 1.75rem; + background: rgb(255 255 255 / .14); backdrop-filter: blur(16px); -webkit-backdrop-filter: blur(16px); } +.dock:empty { display: none; } +.dock-app { padding: 0; border: 0; background: none; cursor: pointer; } +.dock-app:active { transform: scale(.92); } +.actions { display: flex; gap: .25rem; } +.actions .btn.ghost { color: #fff; text-shadow: 0 1px 4px rgb(0 0 0 / .6); } +.actions .btn.ghost:hover { background: rgb(255 255 255 / .12); color: #fff; } + +#toast { position: fixed; left: 50%; bottom: calc(var(--bottom) + 9rem); transform: translate(-50%, 1rem); + padding: .5rem 1rem; border-radius: 999px; background: rgb(0 0 0 / .8); color: #fff; + font-size: .875rem; opacity: 0; transition: opacity .2s, transform .2s; pointer-events: none; } +#toast.show { opacity: 1; transform: translate(-50%, 0); } diff --git a/web/ui.css b/web/ui.css new file mode 100644 index 0000000..98ef863 --- /dev/null +++ b/web/ui.css @@ -0,0 +1,224 @@ +/* ultra/ui.css: shadcn/ui's look as plain CSS, for the helpers in ui.py. + * + * The tokens are shadcn's "neutral" theme (https://ui.shadcn.com/docs/theming) + * and the component rules follow its Tailwind classes. Override any token on + * :root to retheme. Dark mode follows the OS, or force it with class="dark" + * (or "light") on any element; this needs CSS light-dark() (2024+ browsers). + * `build` copies this file next to app.wasm. + */ +/* Each token is light-dark(light, dark), so it follows color-scheme. */ +:root { + color-scheme: light dark; + --radius: .625rem; + --background: light-dark(oklch(1 0 0), oklch(.145 0 0)); + --foreground: light-dark(oklch(.145 0 0), oklch(.985 0 0)); + --card: light-dark(oklch(1 0 0), oklch(.205 0 0)); + --card-foreground: var(--foreground); + --popover: var(--card); + --popover-foreground: var(--foreground); + --primary: light-dark(oklch(.205 0 0), oklch(.922 0 0)); + --primary-foreground: light-dark(oklch(.985 0 0), oklch(.205 0 0)); + --secondary: light-dark(oklch(.97 0 0), oklch(.269 0 0)); + --secondary-foreground: light-dark(oklch(.205 0 0), oklch(.985 0 0)); + --muted: var(--secondary); + --muted-foreground: light-dark(oklch(.556 0 0), oklch(.708 0 0)); + --accent: var(--secondary); + --accent-foreground: var(--secondary-foreground); + --destructive: light-dark(oklch(.577 .245 27.325), oklch(.704 .191 22.216)); + --border: light-dark(oklch(.922 0 0), oklch(1 0 0 / 10%)); + --input: light-dark(oklch(.922 0 0), oklch(1 0 0 / 15%)); + --input-bg: light-dark(transparent, oklch(1 0 0 / 4.5%)); + --ring: light-dark(oklch(.708 0 0), oklch(.556 0 0)); + --shadow-xs: 0 1px 2px 0 rgb(0 0 0 / .05); + --shadow-sm: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1); + --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1); + --font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + --font-mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; +} +.light { color-scheme: light; } +.dark { color-scheme: dark; } + +/* ---------------------------------------------------------------- base */ +*, ::before, ::after { box-sizing: border-box; } +body { + margin: 0; background: var(--background); color: var(--foreground); + font: 14px/1.5 var(--font-sans); -webkit-font-smoothing: antialiased; +} +.light, .dark { background: var(--background); color: var(--foreground); } +button, input { font: inherit; color: inherit; margin: 0; } +button { border: 0; background: none; padding: 0; } +:focus-visible { outline: none; } +.muted { color: var(--muted-foreground); } +.mono { font-family: var(--font-mono); } +.stack { display: grid; gap: 1rem; } +.row { display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; } +.grow { flex: 1; } + +/* ---------------------------------------------------------------- button */ +.btn { + display: inline-flex; align-items: center; justify-content: center; gap: .5rem; + height: 2.25rem; padding: .5rem 1rem; border-radius: calc(var(--radius) - 2px); + font-size: .875rem; font-weight: 500; line-height: 1; white-space: nowrap; + border: 1px solid transparent; cursor: pointer; user-select: none; + background: var(--primary); color: var(--primary-foreground); box-shadow: var(--shadow-xs); + transition: background-color .15s, color .15s, box-shadow .15s, opacity .15s; +} +.btn:hover { background: color-mix(in oklab, var(--primary) 90%, transparent); } +.btn:disabled { opacity: .5; pointer-events: none; } +.btn:focus-visible, .input:focus-visible, .checkbox:focus-visible, .switch:focus-visible, +.tab:focus-visible, .toggle:focus-visible { + border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent); +} +.btn.secondary { background: var(--secondary); color: var(--secondary-foreground); } +.btn.secondary:hover { background: color-mix(in oklab, var(--secondary) 80%, transparent); } +.btn.outline { + background: light-dark(var(--background), var(--input-bg)); color: var(--foreground); + border-color: light-dark(var(--border), var(--input)); +} +.btn.outline:hover, .btn.ghost:hover { background: var(--accent); color: var(--accent-foreground); } +.btn.ghost { background: transparent; color: var(--foreground); box-shadow: none; } +.btn.destructive { background: light-dark(var(--destructive), color-mix(in oklab, var(--destructive) 60%, transparent)); color: #fff; } +.btn.destructive:hover { background: color-mix(in oklab, var(--destructive) 90%, transparent); } +.btn.link { background: none; color: var(--primary); box-shadow: none; text-underline-offset: 4px; } +.btn.link:hover { text-decoration: underline; } +.btn.sm { height: 2rem; padding: 0 .75rem; gap: .375rem; } +.btn.lg { height: 2.5rem; padding: 0 1.5rem; } +.btn.icon { width: 2.25rem; padding: 0; } +.btn.icon.sm { width: 2rem; } + +/* ---------------------------------------------------------------- card */ +.card { + display: flex; flex-direction: column; gap: 1.5rem; padding: 1.5rem 0; + background: var(--card); color: var(--card-foreground); + border: 1px solid var(--border); border-radius: calc(var(--radius) + 4px); box-shadow: var(--shadow-sm); +} +.card-header { display: grid; gap: .375rem; padding: 0 1.5rem; } +.card-title { margin: 0; font-size: 1rem; font-weight: 600; line-height: 1; } +.card-description { margin: 0; font-size: .875rem; color: var(--muted-foreground); } +.card-content { padding: 0 1.5rem; } +.card-footer { display: flex; align-items: center; gap: .5rem; padding: 0 1.5rem; } + +/* ---------------------------------------------------------------- input, label */ +.input { + display: flex; width: 100%; min-width: 0; height: 2.25rem; padding: .25rem .75rem; + border: 1px solid var(--input); border-radius: calc(var(--radius) - 2px); + background: var(--input-bg); box-shadow: var(--shadow-xs); font-size: .875rem; + transition: box-shadow .15s, border-color .15s; +} +.input::placeholder { color: var(--muted-foreground); } +.label { display: flex; align-items: center; gap: .5rem; font-size: .875rem; font-weight: 500; line-height: 1; user-select: none; } +.field { display: inline-flex; align-items: center; gap: .5rem; cursor: pointer; } + +/* ---------------------------------------------------------------- badge */ +.badge { + display: inline-flex; align-items: center; justify-content: center; gap: .25rem; width: fit-content; + padding: .125rem .5rem; border: 1px solid transparent; border-radius: calc(var(--radius) - 2px); + font-size: .75rem; font-weight: 500; white-space: nowrap; + background: var(--primary); color: var(--primary-foreground); +} +.badge.secondary { background: var(--secondary); color: var(--secondary-foreground); } +.badge.destructive { background: light-dark(var(--destructive), color-mix(in oklab, var(--destructive) 60%, transparent)); color: #fff; } +.badge.outline { background: none; color: var(--foreground); border-color: var(--border); } + +/* ---------------------------------------------------------------- checkbox, switch */ +.checkbox { + position: relative; flex: none; width: 1rem; height: 1rem; padding: 0; cursor: pointer; + border: 1px solid var(--input); border-radius: 4px; background: var(--input-bg); box-shadow: var(--shadow-xs); + transition: box-shadow .15s; +} +.checkbox[aria-checked="true"] { background: var(--primary); border-color: var(--primary); } +.checkbox[aria-checked="true"]::after { + content: ""; position: absolute; left: 4.5px; top: 1.5px; width: 4px; height: 8px; + border: solid var(--primary-foreground); border-width: 0 2px 2px 0; transform: rotate(45deg); +} +.switch { + display: inline-flex; flex: none; align-items: center; width: 2rem; height: 1.15rem; padding: 0; + border: 1px solid transparent; border-radius: 999px; background: var(--input); cursor: pointer; + box-shadow: var(--shadow-xs); transition: background-color .15s; +} +.switch::after { + content: ""; width: 1rem; height: 1rem; border-radius: 999px; background: var(--background); + transition: transform .15s; +} +.switch:not([aria-checked="true"])::after { background: light-dark(var(--background), var(--foreground)); } +.switch[aria-checked="true"] { background: var(--primary); } +.switch[aria-checked="true"]::after { transform: translateX(calc(100% - 2px)); } + +/* ---------------------------------------------------------------- tabs, toggle group */ +.tabs-list { + display: inline-flex; align-items: center; height: 2.25rem; width: fit-content; padding: 3px; + border-radius: var(--radius); background: var(--muted); color: var(--muted-foreground); +} +.tab { + display: inline-flex; flex: 1; align-items: center; justify-content: center; height: 100%; + padding: .25rem .5rem; border: 1px solid transparent; border-radius: calc(var(--radius) - 2px); + background: none; font-size: .875rem; font-weight: 500; white-space: nowrap; cursor: pointer; + color: light-dark(var(--foreground), var(--muted-foreground)); transition: color .15s, box-shadow .15s; +} +.tab[aria-selected="true"] { + background: light-dark(var(--background), var(--input-bg)); border-color: light-dark(transparent, var(--input)); + color: var(--foreground); box-shadow: var(--shadow-sm); +} +.toggle-group { display: inline-flex; width: fit-content; border-radius: calc(var(--radius) - 2px); box-shadow: var(--shadow-xs); } +.toggle { + display: inline-flex; align-items: center; justify-content: center; height: 2.25rem; min-width: 2.25rem; + padding: 0 .75rem; border: 1px solid var(--input); background: none; font-size: .875rem; font-weight: 500; + cursor: pointer; transition: background-color .15s; +} +.toggle:hover { background: var(--muted); color: var(--muted-foreground); } +.toggle[aria-pressed="true"] { background: var(--accent); color: var(--accent-foreground); } +.toggle-group .toggle { border-radius: 0; } +.toggle-group .toggle + .toggle { border-left: 0; } +.toggle-group .toggle:first-child { border-radius: calc(var(--radius) - 2px) 0 0 calc(var(--radius) - 2px); } +.toggle-group .toggle:last-child { border-radius: 0 calc(var(--radius) - 2px) calc(var(--radius) - 2px) 0; } + +/* ---------------------------------------------------------------- dialog */ +.dialog-overlay { position: fixed; inset: 0; z-index: 50; background: rgb(0 0 0 / .5); animation: ui-fade .15s; } +.dialog { + position: fixed; z-index: 50; top: 50%; left: 50%; transform: translate(-50%, -50%); + display: grid; gap: 1rem; width: calc(100% - 2rem); max-width: 32rem; padding: 1.5rem; + border: 1px solid var(--border); border-radius: var(--radius); box-shadow: var(--shadow-lg); + background: var(--background); color: var(--foreground); animation: ui-zoom .15s; +} +.dialog-header { display: grid; gap: .5rem; } +.dialog-title { margin: 0; font-size: 1.125rem; font-weight: 600; line-height: 1; } +.dialog-description { margin: 0; font-size: .875rem; color: var(--muted-foreground); } +.dialog-footer { display: flex; flex-wrap: wrap-reverse; justify-content: flex-end; gap: .5rem; } +.dialog-close { + position: absolute; top: 1rem; right: 1rem; width: 1.25rem; height: 1.25rem; padding: 0; + border-radius: 4px; background: none; font-size: 1.125rem; line-height: 1; opacity: .7; cursor: pointer; +} +.dialog-close:hover { opacity: 1; } +@keyframes ui-fade { from { opacity: 0; } } +@keyframes ui-zoom { from { opacity: 0; transform: translate(-50%, -50%) scale(.95); } } + +/* ---------------------------------------------------------------- alert, separator, progress, kbd */ +.alert { + display: grid; gap: .125rem; width: 100%; padding: .75rem 1rem; font-size: .875rem; + border: 1px solid var(--border); border-radius: var(--radius); background: var(--card); color: var(--card-foreground); +} +.alert-title { font-weight: 500; } +.alert-description { color: var(--muted-foreground); } +.alert.destructive { color: var(--destructive); } +.alert.destructive .alert-description { color: color-mix(in oklab, var(--destructive) 90%, transparent); } +.separator { flex: none; height: 1px; width: 100%; margin: 0; border: 0; background: var(--border); } +.progress { + display: block; width: 100%; height: .5rem; overflow: hidden; border: 0; border-radius: 999px; + appearance: none; background: color-mix(in oklab, var(--primary) 20%, transparent); +} +.progress::-webkit-progress-bar { background: transparent; } +.progress::-webkit-progress-value { background: var(--primary); transition: width .2s; } +.progress::-moz-progress-bar { background: var(--primary); } +.kbd { + display: inline-flex; align-items: center; justify-content: center; height: 1.25rem; min-width: 1.25rem; + padding: 0 .25rem; border-radius: 4px; background: var(--muted); color: var(--muted-foreground); + font: 500 .75rem var(--font-sans); +} + +/* ---------------------------------------------------------------- table */ +.table { width: 100%; border-collapse: collapse; font-size: .875rem; } +.table th { height: 2.5rem; padding: 0 .5rem; text-align: left; font-weight: 500; white-space: nowrap; } +.table td { padding: .5rem; } +.table tr { border-bottom: 1px solid var(--border); } +.table tbody tr:hover { background: color-mix(in oklab, var(--muted) 50%, transparent); } +.table tr[aria-selected="true"] { background: var(--muted); } diff --git a/web/ultra.js b/web/ultra.js new file mode 100644 index 0000000..30ccb7f --- /dev/null +++ b/web/ultra.js @@ -0,0 +1,387 @@ +// ultra.js: the DOM glue for ultra apps written in LPython. +// +// The wasm module calls into the "js" imports below while view() runs; those +// calls build a lightweight vnode tree. After view() returns we diff the new +// tree against the last one and patch the DOM. Events are delegated from the +// mount point and turned into update(msg, arg) calls. + +const EVENT = 0; + +export async function mount(root, url, opts = {}) { + if (typeof root === "string") root = document.querySelector(root); + + let mem, ex; + const td = new TextDecoder(); + const cache = new Map(); + + // LPython strings are a pointer to { data: i32, len: i32 }. + // Literals live in static data, so decoding is cached by (data, len). + let dv = null; + const str = (p) => { + if (dv === null || dv.buffer !== mem.buffer) dv = new DataView(mem.buffer); + const a = dv.getInt32(p, true), l = dv.getInt32(p + 4, true); + const k = a * 4096 + l; + let s = cache.get(k); + if (s === undefined) { + s = td.decode(new Uint8Array(mem.buffer, a, l)); + if (l < 4096) cache.set(k, s); + } + return s; + }; + + const K = (k) => (typeof k === "object" ? k.k : str(k)); // storage key + + // ------------------------------------------------------------ string store + const strs = [""]; + const free = []; + const sNew = (v = "") => { + if (free.length) { const h = free.pop(); strs[h] = v; return h; } + strs.push(v); return strs.length - 1; + }; + + // ------------------------------------------------------------ vnode builder + // vnode: { t, k, a, cls, p, ev, c, n } text: { t: "#", s, n } + let stack, cur; + const node = (t) => ({ t, k: null, a: null, cls: "", p: null, ev: null, c: [], n: null }); + let nodes = 0; + const push = (v) => { nodes++; cur.c.push(v); }; + const txt = (s) => push({ t: "#", k: null, s: String(s), n: null }); + const setA = (k, v) => ((cur.a ||= {})[k] = v); + const setP = (k, v) => ((cur.p ||= {})[k] = v); + const setEv = (k, v) => ((cur.ev ||= {})[k] = v); + + // ------------------------------------------------------------ scheduling + // Messages are applied immediately; the re-render is batched onto the next + // animation frame. frame(msg, arg) messages are held until that frame and + // applied just before view(), so an animation steps once per rendered frame. + let queued = false; + let frameQ = []; + let since = 0, tUpdate = 0; // first dispatch since the last render, time in update() + const schedule = () => { + if (queued) return; + queued = true; + if (!since) since = performance.now(); + requestAnimationFrame(render); + }; + const dispatch = (msg, arg) => { + const t = performance.now(); + if (!since) since = t; + ex.update(msg, arg); + tUpdate += performance.now() - t; + schedule(); + }; + + // ------------------------------------------------------------ json store + // Decoded JSON values live here too; LPython holds i32 handles and reads + // fields by dotted path ("repos.3.did"). Handle 0 is "nothing". + const vals = [undefined]; + const vfree = []; + const vNew = (v) => { + if (v === undefined) return 0; + if (vfree.length) { const h = vfree.pop(); vals[h] = v; return h; } + vals.push(v); return vals.length - 1; + }; + const walk = (h, p) => { + let v = vals[h]; + const path = str(p); + if (path) for (const k of path.split(".")) { if (v == null) return undefined; v = v[k]; } + return v; + }; + const asText = (v) => (typeof v === "string" ? v : JSON.stringify(v, null, 2)); + const httpGet = (url, msg) => { + const h = vNew(null); + fetch(url, { headers: { accept: "application/json" } }) + .then(async (r) => { + const body = await r.json().catch(() => null); + vals[h] = r.ok ? body + : { __error: (body && (body.message || body.error)) || "HTTP " + r.status }; + }) + .catch((e) => { vals[h] = { __error: String(e.message || e) }; }) + .then(() => dispatch(msg, h)); + return h; + }; + + const js = { + el: (p) => { const v = node(str(p)); push(v); stack.push(cur); cur = v; }, + end: () => { cur = stack.pop(); }, + text: (p) => txt(str(p)), + num: (x) => txt(x), + fnum: (x, d) => txt(x.toFixed(d)), + text_ref: (h) => txt(strs[h] ?? ""), + + attr: (k, v) => setA(str(k), str(v)), + attr_num: (k, v) => setA(str(k), String(v)), + attr_ref: (k, h) => setA(str(k), strs[h] ?? ""), + cls: (p) => { const c = str(p); if (c) cur.cls = cur.cls ? cur.cls + " " + c : c; }, + cls_if: (p, on) => { if (on) js.cls(p); }, + key: (k) => { cur.k = k; }, + value_ref: (h) => setP("value", strs[h] ?? ""), + checked: (on) => setP("checked", !!on), + autofocus: () => setP("__focus", true), + + on_click: (m, a) => setEv("click", [m, a]), + on_dblclick: (m, a) => setEv("dblclick", [m, a]), + on_input: (m) => setEv("input", [m, EVENT]), + on_enter: (m, a) => setEv("enter", [m, a]), + on_escape: (m, a) => setEv("escape", [m, a]), + + after: (ms, m, a) => setTimeout(() => dispatch(m, a), ms), + frame: (m, a) => { frameQ.push(m, a); schedule(); }, + now_ms: () => performance.now(), + log: (x) => console.log("[ultra]", x), + + s_new: () => sNew(), + s_dup: (h) => sNew(strs[h]), + s_copy: (d, s) => { strs[d] = strs[s]; }, + s_clear: (h) => { strs[h] = ""; }, + s_free: (h) => { if (h > 0) { strs[h] = ""; free.push(h); } }, + s_len: (h) => (strs[h] ?? "").trim().length, + s_set: (h, p) => { strs[h] = str(p); }, + s_add: (h, p) => { strs[h] += str(p); }, + s_add_ref: (h, s) => { strs[h] += strs[s] ?? ""; }, + s_add_num: (h, x) => { strs[h] += String(x); }, + s_eq: (a, b) => (strs[a] === strs[b] ? 1 : 0), + s_has: (h, n) => ((strs[h] ?? "").toLowerCase().includes((strs[n] ?? "").trim().toLowerCase()) ? 1 : 0), + s_save: (k, h) => { try { localStorage.setItem(K(k), strs[h]); } catch {} }, + s_load: (k, h) => { + let v = null; + try { v = localStorage.getItem(K(k)); } catch {} + if (v === null) return 0; + strs[h] = v; return 1; + }, + store_i32: (k, v) => { try { localStorage.setItem(K(k), String(v)); } catch {} }, + load_i32: (k, d) => { + let v = null; + try { v = localStorage.getItem(K(k)); } catch {} + return v === null ? d : v | 0; + }, + + http_get: (p, m) => httpGet(str(p), m), + http_get_ref: (h, m) => httpGet(strs[h], m), + j_ok: (h) => (vals[h] != null && !(typeof vals[h] === "object" && "__error" in vals[h]) ? 1 : 0), + j_err: (h, d) => { const v = vals[h]; strs[d] = v && v.__error ? v.__error : v == null ? "no response" : ""; }, + j_at: (h, p) => vNew(walk(h, p)), + j_idx: (h, i) => vNew((vals[h] ?? [])[i]), + j_has: (h, p) => (walk(h, p) != null ? 1 : 0), + j_len: (h, p) => { + const v = walk(h, p); + return Array.isArray(v) || typeof v === "string" ? v.length : v && typeof v === "object" ? Object.keys(v).length : 0; + }, + j_int: (h, p) => { const v = walk(h, p); return typeof v === "boolean" ? +v : Number(v) | 0; }, + j_str: (h, p, d) => { const v = walk(h, p); strs[d] = v == null ? "" : asText(v); return v == null ? 0 : 1; }, + j_key: (h, i, d) => { strs[d] = Object.keys(vals[h] ?? {})[i] ?? ""; }, + j_free: (h) => { if (h > 0) { vals[h] = undefined; vfree.push(h); } }, + }; + + // Apps can declare their own @jscall imports and supply them here. + if (opts.imports) Object.assign(js, opts.imports({ str, strs, vals, sNew, dispatch, text: txt })); + + for (const f of ["s_save", "s_load", "store_i32", "load_i32"]) { + const base = js[f]; + js[f + "_at"] = (k, i, x) => base({ k: str(k) + "." + i }, x); + } + + // Minimal WASI so print() works and _start-style exits don't crash. + const wasi = { + proc_exit: () => {}, + fd_write: (fd, iovs, n, out) => { + const dv = new DataView(mem.buffer); + let s = "", total = 0; + for (let i = 0; i < n; i++) { + const p = dv.getInt32(iovs + i * 8, true), l = dv.getInt32(iovs + i * 8 + 4, true); + s += td.decode(new Uint8Array(mem.buffer, p, l)); total += l; + } + (fd === 2 ? console.error : console.log)(s.replace(/\n$/, "")); + dv.setInt32(out, total, true); + return 0; + }, + }; + + const imports = { js, wasi_snapshot_preview1: wasi }; + let instance; + if (typeof url === "string") { + const res = await fetch(url); + // Streaming compile needs the application/wasm MIME type; fall back if absent. + ({ instance } = (res.headers.get("content-type") || "").startsWith("application/wasm") + ? await WebAssembly.instantiateStreaming(res, imports) + : await WebAssembly.instantiate(await res.arrayBuffer(), imports)); + } else { + ({ instance } = await WebAssembly.instantiate(url, imports)); + } + ex = instance.exports; + mem = ex.memory; + + // ------------------------------------------------------------ diff / patch + const create = (v) => { + if (v.t === "#") return (v.n = document.createTextNode(v.s)); + const n = (v.n = document.createElement(v.t)); + if (v.cls) n.className = v.cls; + if (v.a) for (const k in v.a) n.setAttribute(k, v.a[k]); + if (v.p) setProps(n, null, v.p); + n.__ev = v.ev; + for (const c of v.c) n.appendChild(create(c)); + return n; + }; + + const setProps = (n, o, p) => { + for (const k in p) { + if (k === "__focus") { if (!o || !o.__focus) queueMicrotask(() => n.focus()); continue; } + if (n[k] !== p[k]) n[k] = p[k]; + } + }; + + const patch = (o, v) => { + if (o.t !== v.t || o.k !== v.k) { + const n = create(v); + o.n.replaceWith(n); + return; + } + const n = (v.n = o.n); + if (v.t === "#") { if (o.s !== v.s) n.data = v.s; return; } + if (o.cls !== v.cls) n.className = v.cls; + if (o.a !== v.a) { + const oa = o.a || {}, va = v.a || {}; + for (const k in oa) if (!(k in va)) n.removeAttribute(k); + for (const k in va) if (oa[k] !== va[k]) n.setAttribute(k, va[k]); + } + if (v.p) setProps(n, o.p, v.p); + n.__ev = v.ev; + patchChildren(n, o.c, v.c); + }; + + const patchChildren = (parent, oc, vc) => { + if (oc.length === 0 && vc.length === 0) return; + const keyed = vc.length > 0 && vc[0].k !== null && oc.length > 0 && oc[0].k !== null; + if (vc.length === 0 && parent.childNodes.length === oc.length) { + parent.textContent = ""; // clearing a whole list: one DOM op + return; + } + if (!keyed) { + const m = Math.min(oc.length, vc.length); + for (let i = 0; i < m; i++) patch(oc[i], vc[i]); + for (let i = m; i < vc.length; i++) parent.appendChild(create(vc[i])); + for (let i = m; i < oc.length; i++) oc[i].n.remove(); + return; + } + patchKeyed(parent, oc, vc); + }; + + // Keyed children: skip the common prefix and suffix, then match the middle by + // key and move only the nodes outside the longest increasing subsequence of + // old positions. Swapping two rows of 1,000 moves 2 nodes, not 998. + const patchKeyed = (parent, oc, vc) => { + let os = 0, oe = oc.length - 1, vs = 0, ve = vc.length - 1; + while (os <= oe && vs <= ve && oc[os].k === vc[vs].k) patch(oc[os++], vc[vs++]); + while (os <= oe && vs <= ve && oc[oe].k === vc[ve].k) patch(oc[oe--], vc[ve--]); + const anchor = ve + 1 < vc.length ? vc[ve + 1].n : null; + if (os > oe) { + for (let i = vs; i <= ve; i++) parent.insertBefore(create(vc[i]), anchor); + return; + } + if (vs > ve) { + for (let i = os; i <= oe; i++) oc[i].n.remove(); + return; + } + const at = new Map(); + for (let i = vs; i <= ve; i++) at.set(vc[i].k, i); + if (os === 0 && oe === oc.length - 1 && parent.childNodes.length === oc.length && + !oc.some((o) => at.has(o.k))) { + // Nothing reused (e.g. replacing every row): drop all, build all. + parent.textContent = ""; + for (const v of vc) parent.appendChild(create(v)); + return; + } + const src = new Int32Array(ve - vs + 1).fill(-1); // new slot -> old index + let moved = false, last = -1; + for (let i = os; i <= oe; i++) { + const o = oc[i], j = at.get(o.k); + if (j === undefined) { o.n.remove(); continue; } + src[j - vs] = i; + patch(o, vc[j]); + if (j < last) moved = true; else last = j; + } + const keep = moved ? lis(src) : null; + let li = keep ? keep.length - 1 : -1; + let next = anchor; + for (let j = ve; j >= vs; j--) { + const v = vc[j], p = j - vs; + if (src[p] === -1) parent.insertBefore(create(v), next); + else if (moved) { + if (li >= 0 && keep[li] === p) li--; + else parent.insertBefore(v.n, next); + } + next = v.n; + } + }; + + // Positions (into a) of a longest strictly increasing subsequence, skipping -1. + const lis = (a) => { + const prev = new Int32Array(a.length), tails = []; + for (let i = 0; i < a.length; i++) { + const x = a[i]; + if (x === -1) continue; + let lo = 0, hi = tails.length; + while (lo < hi) { const m = (lo + hi) >> 1; if (a[tails[m]] < x) lo = m + 1; else hi = m; } + prev[i] = lo > 0 ? tails[lo - 1] : -1; + tails[lo] = i; + } + const out = new Array(tails.length); + for (let k = tails.length - 1, i = tails[k]; k >= 0; k--, i = prev[i]) out[k] = i; + return out; + }; + + // ------------------------------------------------------------ render + let prev = null; + // opts.onRender(stats) runs after each patch with timings in ms: + // { start, update, view, patch, end, nodes } + // where start is the first dispatch since the previous render. + function render() { + queued = false; + const t0 = performance.now(); + if (frameQ.length) { + const q = frameQ; frameQ = []; + for (let i = 0; i < q.length; i += 2) ex.update(q[i], q[i + 1]); + } + const t1 = performance.now(); + const top = node("#root"); + stack = []; cur = top; nodes = 0; + ex.view(); + const t2 = performance.now(); + if (prev === null) { + root.textContent = ""; + for (const c of top.c) root.appendChild(create(c)); + } else { + patchChildren(root, prev.c, top.c); + } + prev = top; + const t3 = performance.now(); + const stats = { start: since || t0, update: tUpdate + (t1 - t0), + view: t2 - t1, patch: t3 - t2, end: t3, nodes }; + since = 0; tUpdate = 0; + if (opts.onRender) opts.onRender(stats); + } + + // ------------------------------------------------------------ events + const find = (t, kind) => { + for (let n = t; n && n !== root; n = n.parentNode) if (n.__ev && n.__ev[kind]) return n.__ev[kind]; + return null; + }; + const on = (type, kind, pre) => + root.addEventListener(type, (e) => { + if (pre && !pre(e)) return; + const h = find(e.target, kind); + if (!h) return; + if (kind === "input") strs[EVENT] = e.target.value; + dispatch(h[0], h[1]); + }); + on("click", "click"); + on("dblclick", "dblclick"); + on("input", "input"); + on("keydown", "enter", (e) => e.key === "Enter" && !e.isComposing); + on("keydown", "escape", (e) => e.key === "Escape"); + + // Run module-level code (which calls init()), then first render. + ex.__main__global_stmts(); + render(); + return { dispatch, render, exports: ex, strs, vals }; +}