Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
tray: the wrapper apps become document hosts, and Android gets one
nyblnet19d2110dfa54
diff --git a/.gitignore b/.gitignoreindex d8cac51f..a6cb7ba5 100644--- a/.gitignore+++ b/.gitignore@@ -43,15 +43,6 @@ release-key.json# make-og.mjs intermediate (the SVG rasterised into site-src/og.png)scripts/.cache/-# native wrapper apps (native/)-native/*/build/-native/android/.gradle/-native/android/app/build/-native/android/local.properties-native/android/keystore.properties-native/ios/Bento/Resources/bento.html-native/android/app/src/main/assets/bento.html-native/PR-BODY.md*.xcuserdatad/# tray: generated by xcodegen and by the slides build. The paths moved when@@ -63,6 +54,17 @@ native/PR-BODY.md**/*.xcodeproj/**/Resources/starter.bento.html+# tray/android: Gradle's own state, and the two files that hold local identity.+# Matched by FILENAME for the same reason as the secrets above — `local.properties`+# carries an absolute SDK path and `keystore.properties` the release signing+# passwords, and neither may become committable by moving a directory.+local.properties+keystore.properties+.gradle/+.kotlin/+tray/android/build/+tray/android/*/build/+# per-session git worktrees (docs/PARALLEL-WORK.md §2.1). Inside the repo on# purpose: ~/.zshrc picks the personal gh account by directory, and /tmp gets# reaped — seven worktrees were lost from it in one day.diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex c70c6d08..4094e03b 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -14,6 +14,59 @@ Decision. Why. Pointers.---+## 2026-08-16 — bento/tray gets an Android host (PR #87, rearchitected)++**Decision.** `tray/android/` is a document host, written against the same two+decisions as `tray/ios`: the document is served through an origin we control,+and the app ships **file access only** — no bundled runtime, no OTA channel of+its own.++It lands as **PR #87** (savrum, opened 2026-07-26), which asked the right+question first: Android needs a native host for the same reason iOS does. The+branch keeps that original commit and builds on it. Its `native/ios` half is+superseded by `tray/ios`, which arrived in the meantime; its Gradle and keystore+scaffolding is the shape used here; and the `isElementFullscreenEnabled` flag+`tray/ios` briefly used was found there.++What did NOT survive is the **architecture**, which is the one tray deliberately+rejected:++- it BUNDLES a deck and OTA-fetches a newer one from the GitHub releases API on+ every launch. tray's whole thesis is the opposite (`tray/README.md`, "What it+ is, and what it deliberately is not"), and an unsigned OTA — which the PR's own+ README flags — contradicts `docs/PLATFORM.md` §1 as well as the signed-update+ invariant.+- every save calls `ACTION_CREATE_DOCUMENT`, so Bento's 2.5s autosave write-back+ would open a file picker on a loop. It has no in-place path at all.+- the page is loaded from `file://` (opaque origin: unreliable `localStorage`+ and IndexedDB) and the shim is injected from `onPageStarted`, which races the+ boot-time capability check.++**Three Android-specific findings worth not rediscovering.**++1. **Write access is not implied by receiving a document.** `ACTION_VIEW` from a+ file manager grants READ ONLY; only the app's own `ACTION_OPEN_DOCUMENT`+ yields a persistable read+write grant. Checked per document+ (`canWriteInPlace`), and when false every save becomes a Save-As — the+ "when in doubt, prompt" rule the whole project already follows.+2. **`androidx.webkit` is a required dependency, not a convenience.**+ `addDocumentStartJavaScript` is the only true `.atDocumentStart` equivalent,+ and `addWebMessageListener` is **origin-scoped** where `addJavascriptInterface`+ is injected into every frame — a remote iframe in an untrusted document would+ otherwise be handed a channel that writes the user's file.+3. **`fitsSystemWindows = true` REPLACES a view's padding, it does not add to+ it** — and from targetSdk 35 edge-to-edge is mandatory, so insets must be+ applied by hand. Same for `enableOnBackInvokedCallback`: it stops+ `onBackPressed` being called at all on API 33+, so an override alone compiles,+ runs, and silently does nothing.++**`tray/bridge.js` is now SHARED** by both native hosts (was+`tray/ios/Resources/bridge.js`). The transport is ~15 lines at the top; the rest+is `FileSystemWritableFileStream` semantics whose comments record the bug that+wrote documents out as zero bytes. Forking that file forks that bug.++Details and verification state: `tray/README.md` § Android.+## 2026-08-06 — The tree is DERIVED at read time, in one function, and it cannot cycle**Decision.** `model.ts effectiveParents(page)` is the only answer to "what isdiff --git a/native/README.md b/native/README.mddeleted file mode 100644index 19347a47..00000000--- a/native/README.md+++ /dev/null@@ -1,110 +0,0 @@-# native — iOS and Android wrapper apps for bento/slides--Minimal native shells that make a bento deck a first-class document on iPhone,-iPad, and Android. No framework: plain Swift + WKWebView and plain Kotlin +-WebView, zero third-party dependencies, ~500 KB installed per platform.--Why a wrapper at all, when the file already runs in any browser: mobile-browsers cap exactly the things that make bento bento.--| Capability | Mobile browser | Wrapper |-|---|---|---|-| File System Access API ("it saves itself") | absent — every save is a new download | in-place saves via native file APIs |-| Fullscreen presenting on iPhone | not available to web pages | native element fullscreen |-| Opening a `.bento.html` from Files/Mail | sandboxed preview at best | registered editor, open-in-place |-| Offline | needs a service worker + a hosted origin | bundled deck + OTA updates |--## Layout--```-native/ios/ Swift app (Xcode project, no dependencies)-native/android/ Kotlin app (Gradle, no AndroidX, no dependencies)-native/scripts/ fetch-deck.sh (build input), gen_icons.py (iOS icon set)-```--The bundled `bento.html` is a **build input, not source** — `make` fetches it-via `scripts/fetch-deck.sh`, which prefers a locally built-`slides/dist-single/Bento_Slides.bento.html` and falls back to the latest-GitHub release.--## Build & run--Via npm (from `native/`):--```sh-npm run run:android # build debug APK, pick a device, install, launch-npm run run:ios # same for a simulator / iPhone / iPad-npm run build:apk # release APK-npm run build:aab # Play Store bundle (needs keystore.properties)-TEAM=<teamid> npm run build:ipa # App Store .ipa → ios/build/Bento.ipa-```--Device pickers prompt when more than one target is connected; skip the prompt-with `device=<udid|serial> npm run run:ios` (or `run:android`). The npm-scripts are a facade over per-platform Makefiles — `make -C native/ios run`-and friends work identically, and `npm run deck` / `npm run icons` refresh the-bundled deck and the icon set.--## How the shells work--Both are one screen: a WebView rendering the deck, plus an injected shim.-Bento's own UI drives everything — there is no native chrome.--1. **Bundled deck + OTA.** The app ships a copy of the single-file build and- checks the GitHub releases feed on launch; a newer deck is swapped in- atomically and used from the next launch.-2. **File System Access shim** (`showSaveFilePicker`), injected at document- start. Bento's retained-handle save flow works unchanged: the handle's- `createWritable()` round-trips content to native code.-3. **The document cycle (iOS).** A deck opened from Files/Mail (registered- `public.html` editor, `LSSupportsOpeningDocumentsInPlace`) or the document- picker becomes the *backing document*, held as a security-scoped bookmark.- Saves are written back in place under `NSFileCoordinator` — same behavior as- desktop Chrome with a retained handle. With no backing file, the first save- creates one in the app's Documents (visible in the Files app); a changed- suggested name falls back to an export sheet (save-as).-4. **Native dialogs.** `alert`/`confirm`/`prompt` map to native alerts; the- logo tap opens a native menu (save / save as / open / settings — settings- passes through to bento's own project settings).-5. **Touch affordances (iOS).** A floating ✎ edit pill appears when a text- element is selected and dispatches the `dblclick` bento expects;- double-tap-to-zoom is disabled natively; a WebKit focus workaround lets- bento's programmatic focus raise the keyboard (see- `allowProgrammaticKeyboard()` — the long-standing Ionic/Cordova approach,- no-op if WebKit renames the internal selector).-6. **localStorage bridge (iOS).** WKWebView storage for `file://` documents is- unreliable, and several runtime `localStorage` reads are unguarded — the- shim replaces it with a UserDefaults-backed store seeded before each load.--## The soft DOM contract--The integration points reference runtime markup. Everything degrades-gracefully — if a selector stops matching, the feature silently detaches and-stock behavior remains — but renaming these will detach features until the-wrapper is updated:--| Selector / behavior | Used for |-|---|---|-| `.ed-topbar .ed-logo` | logo-tap → native document menu |-| save button tooltip containing `⌘S` | native "Save" menu action |-| `.ed-topbar .ed-split-caret` | native "Save As…" menu action |-| `.bento-el-text` + stage `dblclick` → `startTextEdit` | ✎ edit pill |-| `showSaveFilePicker` capability check at save time | the whole save bridge |--A stable, documented `window.bento` hook (or `data-bento-*` attributes on-these controls) would let the wrappers drop every selector above — happy to do-that refactor if wanted.--## Status & known gaps--- **iOS is the mature shell** (document cycle, keyboard, gestures, storage- bridge — tested on iPad Pro / iPhone simulators and tablet-first by design).- **Android is the minimal shell** (WebView + save/open via SAF + OTA); it- needs the same document-cycle treatment with persistable URI grants.-- **OTA updates are not yet signature-verified.** The updater trusts- HTTPS + GitHub. It should verify the release signature (or hand verification- to the runtime's own signed-update path, or a future bento/vault channel)- before swapping the deck.-- Store metadata (listing copy, screenshots, privacy policy) is deliberately- not included — distribution identity is a maintainer decision, as are the- bundle ids (`slides.bento.app` used as a placeholder throughout).diff --git a/native/android/Makefile b/native/android/Makefiledeleted file mode 100644index 84098da4..00000000--- a/native/android/Makefile+++ /dev/null@@ -1,30 +0,0 @@-JAVA_HOME ?= /opt/homebrew/opt/openjdk@17-ADB := $(HOME)/Library/Android/sdk/platform-tools/adb--.PHONY: run devices build release bundle icons deck--## make run — build debug APK, pick a device, install + launch-## make run device=X — skip the prompt (X = adb serial)-run: deck- @./run.sh $(device)--devices:- @$(ADB) devices -l--build: deck- @JAVA_HOME=$(JAVA_HOME) ./gradlew assembleDebug--release: deck- @JAVA_HOME=$(JAVA_HOME) ./gradlew assembleRelease- @ls -la app/build/outputs/apk/release/app-release.apk--## Play Store upload artifact (.aab) — needs keystore.properties for a real signature-bundle: deck- @JAVA_HOME=$(JAVA_HOME) ./gradlew bundleRelease- @ls -la app/build/outputs/bundle/release/app-release.aab--icons:- @python3 ../scripts/gen_icons.py--deck:- @../scripts/fetch-deck.shdiff --git a/native/android/app/build.gradle.kts b/native/android/app/build.gradle.ktsdeleted file mode 100644index 7bf6b5db..00000000--- a/native/android/app/build.gradle.kts+++ /dev/null@@ -1,61 +0,0 @@-import java.util.Properties--plugins {- id("com.android.application")- id("org.jetbrains.kotlin.android")-}--// Store signing: copy keystore.properties.example to keystore.properties and fill it in.-val keystoreProps = Properties().apply {- val f = rootProject.file("keystore.properties")- if (f.exists()) f.inputStream().use { load(it) }-}--android {- namespace = "slides.bento.app"- compileSdk = 36-- defaultConfig {- applicationId = "slides.bento.app"- minSdk = 26- targetSdk = 36- versionCode = 1- versionName = "1.0"- }-- if (keystoreProps.isNotEmpty()) {- signingConfigs {- create("release") {- storeFile = rootProject.file(keystoreProps.getProperty("storeFile"))- storePassword = keystoreProps.getProperty("storePassword")- keyAlias = keystoreProps.getProperty("keyAlias")- keyPassword = keystoreProps.getProperty("keyPassword")- }- }- }-- buildTypes {- release {- isMinifyEnabled = true- isShrinkResources = true- proguardFiles(- getDefaultProguardFile("proguard-android-optimize.txt"),- "proguard-rules.pro"- )- // Debug-signed fallback keeps the release APK installable while developing.- signingConfig = if (keystoreProps.isNotEmpty())- signingConfigs.getByName("release")- else- signingConfigs.getByName("debug")- }- }-- compileOptions {- sourceCompatibility = JavaVersion.VERSION_17- targetCompatibility = JavaVersion.VERSION_17- }-- kotlinOptions {- jvmTarget = "17"- }-}diff --git a/native/android/app/proguard-rules.pro b/native/android/app/proguard-rules.prodeleted file mode 100644index 7396a207..00000000--- a/native/android/app/proguard-rules.pro+++ /dev/null@@ -1,4 +0,0 @@-# The JS bridge is called reflectively from WebView JS — keep its methods.--keepclassmembers class slides.bento.app.MainActivity$Bridge {- @android.webkit.JavascriptInterface <methods>;-}diff --git a/native/android/app/src/main/AndroidManifest.xml b/native/android/app/src/main/AndroidManifest.xmldeleted file mode 100644index 45ffb15f..00000000--- a/native/android/app/src/main/AndroidManifest.xml+++ /dev/null@@ -1,22 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android">-- <uses-permission android:name="android.permission.INTERNET" />-- <application- android:label="bento"- android:icon="@mipmap/ic_launcher"- android:theme="@android:style/Theme.Material.Light.NoActionBar"- android:allowBackup="true">-- <activity- android:name=".MainActivity"- android:exported="true"- android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|keyboard|uiMode|density|smallestScreenSize">- <intent-filter>- <action android:name="android.intent.action.MAIN" />- <category android:name="android.intent.category.LAUNCHER" />- </intent-filter>- </activity>- </application>-</manifest>diff --git a/native/android/app/src/main/java/slides/bento/app/MainActivity.kt b/native/android/app/src/main/java/slides/bento/app/MainActivity.ktdeleted file mode 100644index 6bb441aa..00000000--- a/native/android/app/src/main/java/slides/bento/app/MainActivity.kt+++ /dev/null@@ -1,215 +0,0 @@-package slides.bento.app--import android.annotation.SuppressLint-import android.app.Activity-import android.content.Intent-import android.net.Uri-import android.os.Bundle-import android.webkit.JavascriptInterface-import android.webkit.ValueCallback-import android.webkit.WebChromeClient-import android.webkit.WebView-import android.webkit.WebViewClient-import org.json.JSONObject-import java.io.File-import java.net.HttpURLConnection-import java.net.URL--class MainActivity : Activity() {-- private lateinit var webView: WebView- private var pendingSaveContent: String? = null- private var pendingFileChooser: ValueCallback<Array<Uri>>? = null-- private val localDeck get() = File(filesDir, "bento.html")-- @SuppressLint("SetJavaScriptEnabled")- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)-- webView = WebView(this)- setContentView(webView)-- webView.settings.apply {- javaScriptEnabled = true- domStorageEnabled = true- allowFileAccess = true- mediaPlaybackRequiresUserGesture = false- }-- webView.addJavascriptInterface(Bridge(), "BentoNative")-- webView.webViewClient = object : WebViewClient() {- override fun onPageStarted(view: WebView, url: String?, favicon: android.graphics.Bitmap?) {- view.evaluateJavascript(SHIM_JS, null)- }-- override fun onPageFinished(view: WebView, url: String?) {- view.evaluateJavascript(SHIM_JS, null)- }- }-- webView.webChromeClient = object : WebChromeClient() {- override fun onShowFileChooser(- view: WebView,- callback: ValueCallback<Array<Uri>>,- params: FileChooserParams- ): Boolean {- pendingFileChooser?.onReceiveValue(null)- pendingFileChooser = callback- startActivityForResult(params.createIntent(), REQ_OPEN)- return true- }- }-- val url = if (localDeck.exists()) Uri.fromFile(localDeck).toString()- else "file:///android_asset/bento.html"- webView.loadUrl(url)-- checkForUpdate()- }-- /** Fetches the latest bento release; the new deck is used on next launch. */- private fun checkForUpdate() {- Thread {- try {- val prefs = getSharedPreferences("ota", MODE_PRIVATE)- val api = URL("https://api.github.com/repos/nyblnet/bento/releases/latest")- .openConnection() as HttpURLConnection- api.setRequestProperty("Accept", "application/vnd.github+json")- api.connectTimeout = 15000- api.readTimeout = 15000- val json = JSONObject(api.inputStream.bufferedReader().use { it.readText() })-- val tag = json.getString("tag_name")- if (tag == prefs.getString("tag", null)) return@Thread-- var assetUrl: String? = null- val assets = json.getJSONArray("assets")- for (i in 0 until assets.length()) {- val a = assets.getJSONObject(i)- if (a.getString("name").endsWith(".html")) {- assetUrl = a.getString("browser_download_url")- break- }- }- if (assetUrl == null) return@Thread-- val dl = URL(assetUrl).openConnection() as HttpURLConnection- dl.connectTimeout = 15000- dl.readTimeout = 60000- val body = dl.inputStream.use { it.readBytes() }-- // Sanity check before swapping in the new deck.- if (body.size < 100_000 || !String(body, 0, 4096).contains("<")) return@Thread-- val tmp = File(filesDir, "bento.html.tmp")- tmp.writeBytes(body)- if (tmp.renameTo(localDeck)) {- prefs.edit().putString("tag", tag).apply()- }- } catch (_: Exception) {- // Offline or API hiccup — keep the current deck.- }- }.start()- }-- override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {- when (requestCode) {- REQ_SAVE -> {- val content = pendingSaveContent- pendingSaveContent = null- val uri = data?.data- if (resultCode == RESULT_OK && uri != null && content != null) {- try {- contentResolver.openOutputStream(uri, "wt")?.use {- it.write(content.toByteArray())- }- } catch (_: Exception) {- }- }- }- REQ_OPEN -> {- val callback = pendingFileChooser- pendingFileChooser = null- val uri = data?.data- callback?.onReceiveValue(- if (resultCode == RESULT_OK && uri != null) arrayOf(uri) else null- )- }- else -> super.onActivityResult(requestCode, resultCode, data)- }- }-- inner class Bridge {- @JavascriptInterface- fun saveFile(name: String, content: String) {- pendingSaveContent = content- val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {- addCategory(Intent.CATEGORY_OPENABLE)- type = "text/html"- putExtra(Intent.EXTRA_TITLE, name)- }- runOnUiThread { startActivityForResult(intent, REQ_SAVE) }- }- }-- companion object {- private const val REQ_SAVE = 1- private const val REQ_OPEN = 2-- // Bridges the File System Access API (absent in WebView) to native dialogs.- private val SHIM_JS = """- (function () {- if (window.__bentoShim) return;- window.__bentoShim = true;-- window.showSaveFilePicker = function (opts) {- var name = (opts && opts.suggestedName) || 'presentation.bento.html';- return Promise.resolve({- kind: 'file',- name: name,- createWritable: function () {- var parts = [];- return Promise.resolve({- write: function (d) {- if (d && typeof d === 'object' && d.data !== undefined &&- !(d instanceof Blob) && !(d instanceof ArrayBuffer) && !ArrayBuffer.isView(d)) {- d = d.data;- }- parts.push(d);- return Promise.resolve();- },- truncate: function () { return Promise.resolve(); },- seek: function () { return Promise.resolve(); },- close: function () {- return new Blob(parts).text().then(function (t) {- BentoNative.saveFile(name, t);- });- }- });- }- });- };-- window.showOpenFilePicker = function () {- return new Promise(function (resolve, reject) {- var inp = document.createElement('input');- inp.type = 'file';- inp.accept = '.html,text/html';- inp.onchange = function () {- var f = inp.files && inp.files[0];- if (!f) { reject(new DOMException('Aborted', 'AbortError')); return; }- resolve([{- kind: 'file',- name: f.name,- getFile: function () { return Promise.resolve(f); }- }]);- };- inp.click();- });- };- })();- """- }-}diff --git a/native/android/app/src/main/res/drawable/ic_launcher_fg.xml b/native/android/app/src/main/res/drawable/ic_launcher_fg.xmldeleted file mode 100644index 403590b1..00000000--- a/native/android/app/src/main/res/drawable/ic_launcher_fg.xml+++ /dev/null@@ -1,18 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<!-- The bento logo (docs/assets/bento-logo.svg, 32-unit grid) scaled into the- adaptive-icon safe zone: slate, coral, cream on the navy background. -->-<vector xmlns:android="http://schemas.android.com/apk/res/android"- android:width="108dp"- android:height="108dp"- android:viewportWidth="108"- android:viewportHeight="108">- <path- android:fillColor="#5E7699"- android:pathData="M36.15,30.9 h4.2 a5.25,5.25 0 0 1 5.25,5.25 v35.7 a5.25,5.25 0 0 1 -5.25,5.25 h-4.2 a5.25,5.25 0 0 1 -5.25,-5.25 v-35.7 a5.25,5.25 0 0 1 5.25,-5.25 z" />- <path- android:fillColor="#FF9E8A"- android:pathData="M55.05,30.9 h16.8 a5.25,5.25 0 0 1 5.25,5.25 v10.5 a5.25,5.25 0 0 1 -5.25,5.25 h-16.8 a5.25,5.25 0 0 1 -5.25,-5.25 v-10.5 a5.25,5.25 0 0 1 5.25,-5.25 z" />- <path- android:fillColor="#F0EBE0"- android:pathData="M55.05,56.1 h16.8 a5.25,5.25 0 0 1 5.25,5.25 v10.5 a5.25,5.25 0 0 1 -5.25,5.25 h-16.8 a5.25,5.25 0 0 1 -5.25,-5.25 v-10.5 a5.25,5.25 0 0 1 5.25,-5.25 z" />-</vector>diff --git a/native/android/app/src/main/res/drawable/ic_launcher_mono.xml b/native/android/app/src/main/res/drawable/ic_launcher_mono.xmldeleted file mode 100644index b791a0a5..00000000--- a/native/android/app/src/main/res/drawable/ic_launcher_mono.xml+++ /dev/null@@ -1,17 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<!-- Monochrome layer for Android 13+ themed icons (system supplies the tint) -->-<vector xmlns:android="http://schemas.android.com/apk/res/android"- android:width="108dp"- android:height="108dp"- android:viewportWidth="108"- android:viewportHeight="108">- <path- android:fillColor="#FFFFFF"- android:pathData="M36.15,30.9 h4.2 a5.25,5.25 0 0 1 5.25,5.25 v35.7 a5.25,5.25 0 0 1 -5.25,5.25 h-4.2 a5.25,5.25 0 0 1 -5.25,-5.25 v-35.7 a5.25,5.25 0 0 1 5.25,-5.25 z" />- <path- android:fillColor="#FFFFFF"- android:pathData="M55.05,30.9 h16.8 a5.25,5.25 0 0 1 5.25,5.25 v10.5 a5.25,5.25 0 0 1 -5.25,5.25 h-16.8 a5.25,5.25 0 0 1 -5.25,-5.25 v-10.5 a5.25,5.25 0 0 1 5.25,-5.25 z" />- <path- android:fillColor="#FFFFFF"- android:pathData="M55.05,56.1 h16.8 a5.25,5.25 0 0 1 5.25,5.25 v10.5 a5.25,5.25 0 0 1 -5.25,5.25 h-16.8 a5.25,5.25 0 0 1 -5.25,-5.25 v-10.5 a5.25,5.25 0 0 1 5.25,-5.25 z" />-</vector>diff --git a/native/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/native/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmldeleted file mode 100644index b6a0d175..00000000--- a/native/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml+++ /dev/null@@ -1,6 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">- <background android:drawable="@color/ic_launcher_bg" />- <foreground android:drawable="@drawable/ic_launcher_fg" />- <monochrome android:drawable="@drawable/ic_launcher_mono" />-</adaptive-icon>diff --git a/native/android/app/src/main/res/values/colors.xml b/native/android/app/src/main/res/values/colors.xmldeleted file mode 100644index c609e2a0..00000000--- a/native/android/app/src/main/res/values/colors.xml+++ /dev/null@@ -1,4 +0,0 @@-<?xml version="1.0" encoding="utf-8"?>-<resources>- <color name="ic_launcher_bg">#16273E</color>-</resources>diff --git a/native/android/gradle/wrapper/gradle-wrapper.jar b/native/android/gradle/wrapper/gradle-wrapper.jardeleted file mode 100644index 9bbc975c..00000000Binary files a/native/android/gradle/wrapper/gradle-wrapper.jar and /dev/null differdiff --git a/native/android/keystore.properties.example b/native/android/keystore.properties.exampledeleted file mode 100644index 54f1b513..00000000--- a/native/android/keystore.properties.example+++ /dev/null@@ -1,8 +0,0 @@-# Copy to keystore.properties (gitignored) and fill in.-# Create a keystore with:-# keytool -genkeypair -v -keystore release.keystore -alias bento \-# -keyalg RSA -keysize 2048 -validity 10000-storeFile=release.keystore-storePassword=-keyAlias=bento-keyPassword=diff --git a/native/android/run.sh b/native/android/run.shdeleted file mode 100755index 3a599a79..00000000--- a/native/android/run.sh+++ /dev/null@@ -1,35 +0,0 @@-#!/bin/bash-# Build, install and launch the debug APK on a chosen device/emulator.-# Usage: ./run.sh [adb-serial]-set -e-cd "$(dirname "$0")"--[ -f app/src/main/assets/bento.html ] || ../scripts/fetch-deck.sh--JAVA_HOME="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17}"-ADB="$HOME/Library/Android/sdk/platform-tools/adb"-APP_ID=slides.bento.app--devices=()-while IFS= read -r line; do devices+=("$line"); done < <(- "$ADB" devices | awk 'NR>1 && $2=="device" {print $1}'-)--if [ -n "$1" ]; then- serial="$1"-elif [ ${#devices[@]} -eq 0 ]; then- echo "No devices/emulators connected. Start an emulator or plug in a device."- echo " (list: $ADB devices)"- exit 1-elif [ ${#devices[@]} -eq 1 ]; then- serial="${devices[0]}"- echo "Using only connected device: $serial"-else- echo "Connected devices:"- select d in "${devices[@]}"; do serial="$d"; break; done-fi--JAVA_HOME="$JAVA_HOME" ./gradlew -q assembleDebug-"$ADB" -s "$serial" install -r app/build/outputs/apk/debug/app-debug.apk-"$ADB" -s "$serial" shell am start -n "$APP_ID/.MainActivity"-echo "Launched $APP_ID on $serial"diff --git a/native/ios/Bento.xcodeproj/project.pbxproj b/native/ios/Bento.xcodeproj/project.pbxprojdeleted file mode 100644index 1e3cb4ed..00000000--- a/native/ios/Bento.xcodeproj/project.pbxproj+++ /dev/null@@ -1,243 +0,0 @@-// !$*UTF8*$!-{- archiveVersion = 1;- classes = {- };- objectVersion = 56;- objects = {--/* Begin PBXBuildFile section */- 0B0000000000000000000001 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A0000000000000000000001 /* AppDelegate.swift */; };- 0B0000000000000000000002 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A0000000000000000000002 /* ViewController.swift */; };- 0B0000000000000000000003 /* bento.html in Resources */ = {isa = PBXBuildFile; fileRef = 0A0000000000000000000004 /* bento.html */; };- 0B0000000000000000000004 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 0A0000000000000000000005 /* Assets.xcassets */; };-/* End PBXBuildFile section */--/* Begin PBXFileReference section */- 0A0000000000000000000001 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };- 0A0000000000000000000002 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = "<group>"; };- 0A0000000000000000000003 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };- 0A0000000000000000000004 /* bento.html */ = {isa = PBXFileReference; lastKnownFileType = text.html; path = "Resources/bento.html"; sourceTree = "<group>"; };- 0A0000000000000000000005 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };- 0A0000000000000000000006 /* Bento.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Bento.app; sourceTree = BUILT_PRODUCTS_DIR; };-/* End PBXFileReference section */--/* Begin PBXFrameworksBuildPhase section */- 0D0000000000000000000002 /* Frameworks */ = {- isa = PBXFrameworksBuildPhase;- buildActionMask = 2147483647;- files = (- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXFrameworksBuildPhase section */--/* Begin PBXGroup section */- 0C0000000000000000000001 = {- isa = PBXGroup;- children = (- 0C0000000000000000000002 /* Bento */,- 0C0000000000000000000003 /* Products */,- );- sourceTree = "<group>";- };- 0C0000000000000000000002 /* Bento */ = {- isa = PBXGroup;- children = (- 0A0000000000000000000001 /* AppDelegate.swift */,- 0A0000000000000000000002 /* ViewController.swift */,- 0A0000000000000000000003 /* Info.plist */,- 0A0000000000000000000004 /* bento.html */,- 0A0000000000000000000005 /* Assets.xcassets */,- );- path = Bento;- sourceTree = "<group>";- };- 0C0000000000000000000003 /* Products */ = {- isa = PBXGroup;- children = (- 0A0000000000000000000006 /* Bento.app */,- );- name = Products;- sourceTree = "<group>";- };-/* End PBXGroup section */--/* Begin PBXNativeTarget section */- 0E0000000000000000000001 /* Bento */ = {- isa = PBXNativeTarget;- buildConfigurationList = 1A0000000000000000000002 /* Build configuration list for PBXNativeTarget "Bento" */;- buildPhases = (- 0D0000000000000000000001 /* Sources */,- 0D0000000000000000000002 /* Frameworks */,- 0D0000000000000000000003 /* Resources */,- );- buildRules = (- );- dependencies = (- );- name = Bento;- productName = Bento;- productReference = 0A0000000000000000000006 /* Bento.app */;- productType = "com.apple.product-type.application";- };-/* End PBXNativeTarget section */--/* Begin PBXProject section */- 0F0000000000000000000001 /* Project object */ = {- isa = PBXProject;- attributes = {- BuildIndependentTargetsInParallel = 1;- LastUpgradeCheck = 1500;- TargetAttributes = {- 0E0000000000000000000001 = {- CreatedOnToolsVersion = 15.0;- };- };- };- buildConfigurationList = 1A0000000000000000000001 /* Build configuration list for PBXProject "Bento" */;- compatibilityVersion = "Xcode 14.0";- developmentRegion = en;- hasScannedForEncodings = 0;- knownRegions = (- en,- Base,- );- mainGroup = 0C0000000000000000000001;- productRefGroup = 0C0000000000000000000003 /* Products */;- projectDirPath = "";- projectRoot = "";- targets = (- 0E0000000000000000000001 /* Bento */,- );- };-/* End PBXProject section */--/* Begin PBXResourcesBuildPhase section */- 0D0000000000000000000003 /* Resources */ = {- isa = PBXResourcesBuildPhase;- buildActionMask = 2147483647;- files = (- 0B0000000000000000000003 /* bento.html in Resources */,- 0B0000000000000000000004 /* Assets.xcassets in Resources */,- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXResourcesBuildPhase section */--/* Begin PBXSourcesBuildPhase section */- 0D0000000000000000000001 /* Sources */ = {- isa = PBXSourcesBuildPhase;- buildActionMask = 2147483647;- files = (- 0B0000000000000000000001 /* AppDelegate.swift in Sources */,- 0B0000000000000000000002 /* ViewController.swift in Sources */,- );- runOnlyForDeploymentPostprocessing = 0;- };-/* End PBXSourcesBuildPhase section */--/* Begin XCBuildConfiguration section */- 1B0000000000000000000001 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ALWAYS_SEARCH_USER_PATHS = NO;- CLANG_ENABLE_MODULES = YES;- CLANG_ENABLE_OBJC_ARC = YES;- DEBUG_INFORMATION_FORMAT = dwarf;- ENABLE_TESTABILITY = YES;- GCC_OPTIMIZATION_LEVEL = 0;- GCC_PREPROCESSOR_DEFINITIONS = (- "DEBUG=1",- "$(inherited)",- );- IPHONEOS_DEPLOYMENT_TARGET = 15.0;- ONLY_ACTIVE_ARCH = YES;- SDKROOT = iphoneos;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;- SWIFT_OPTIMIZATION_LEVEL = "-Onone";- };- name = Debug;- };- 1B0000000000000000000002 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ALWAYS_SEARCH_USER_PATHS = NO;- CLANG_ENABLE_MODULES = YES;- CLANG_ENABLE_OBJC_ARC = YES;- COPY_PHASE_STRIP = NO;- DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";- ENABLE_NS_ASSERTIONS = NO;- IPHONEOS_DEPLOYMENT_TARGET = 15.0;- SDKROOT = iphoneos;- SWIFT_COMPILATION_MODE = wholemodule;- SWIFT_OPTIMIZATION_LEVEL = "-O";- VALIDATE_PRODUCT = YES;- };- name = Release;- };- 1B0000000000000000000003 /* Debug */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 1;- GENERATE_INFOPLIST_FILE = NO;- INFOPLIST_FILE = Bento/Info.plist;- LD_RUNPATH_SEARCH_PATHS = (- "$(inherited)",- "@executable_path/Frameworks",- );- MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = slides.bento.app;- PRODUCT_NAME = "$(TARGET_NAME)";- SWIFT_VERSION = 5.0;- TARGETED_DEVICE_FAMILY = "1,2";- };- name = Debug;- };- 1B0000000000000000000004 /* Release */ = {- isa = XCBuildConfiguration;- buildSettings = {- ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;- CODE_SIGN_STYLE = Automatic;- CURRENT_PROJECT_VERSION = 1;- GENERATE_INFOPLIST_FILE = NO;- INFOPLIST_FILE = Bento/Info.plist;- LD_RUNPATH_SEARCH_PATHS = (- "$(inherited)",- "@executable_path/Frameworks",- );- MARKETING_VERSION = 1.0;- PRODUCT_BUNDLE_IDENTIFIER = slides.bento.app;- PRODUCT_NAME = "$(TARGET_NAME)";- SWIFT_VERSION = 5.0;- TARGETED_DEVICE_FAMILY = "1,2";- };- name = Release;- };-/* End XCBuildConfiguration section */--/* Begin XCConfigurationList section */- 1A0000000000000000000001 /* Build configuration list for PBXProject "Bento" */ = {- isa = XCConfigurationList;- buildConfigurations = (- 1B0000000000000000000001 /* Debug */,- 1B0000000000000000000002 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Release;- };- 1A0000000000000000000002 /* Build configuration list for PBXNativeTarget "Bento" */ = {- isa = XCConfigurationList;- buildConfigurations = (- 1B0000000000000000000003 /* Debug */,- 1B0000000000000000000004 /* Release */,- );- defaultConfigurationIsVisible = 0;- defaultConfigurationName = Release;- };-/* End XCConfigurationList section */- };- rootObject = 0F0000000000000000000001 /* Project object */;-}diff --git a/native/ios/Bento.xcodeproj/xcshareddata/xcschemes/Bento.xcscheme b/native/ios/Bento.xcodeproj/xcshareddata/xcschemes/Bento.xcschemedeleted file mode 100644index 33ec0bd3..00000000--- a/native/ios/Bento.xcodeproj/xcshareddata/xcschemes/Bento.xcscheme+++ /dev/null@@ -1,50 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<Scheme- LastUpgradeVersion = "1500"- version = "1.7">- <BuildAction- parallelizeBuildables = "YES"- buildImplicitDependencies = "YES">- <BuildActionEntries>- <BuildActionEntry- buildForTesting = "YES"- buildForRunning = "YES"- buildForProfiling = "YES"- buildForArchiving = "YES"- buildForAnalyzing = "YES">- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "0E0000000000000000000001"- BuildableName = "Bento.app"- BlueprintName = "Bento"- ReferencedContainer = "container:Bento.xcodeproj">- </BuildableReference>- </BuildActionEntry>- </BuildActionEntries>- </BuildAction>- <LaunchAction- buildConfiguration = "Debug"- selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"- selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"- launchStyle = "0"- useCustomWorkingDirectory = "NO"- ignoresPersistentStateOnLaunch = "NO"- debugDocumentVersioning = "YES"- debugServiceExtension = "internal"- allowLocationSimulation = "YES">- <BuildableProductRunnable- runnableDebuggingMode = "0">- <BuildableReference- BuildableIdentifier = "primary"- BlueprintIdentifier = "0E0000000000000000000001"- BuildableName = "Bento.app"- BlueprintName = "Bento"- ReferencedContainer = "container:Bento.xcodeproj">- </BuildableReference>- </BuildableProductRunnable>- </LaunchAction>- <ArchiveAction- buildConfiguration = "Release"- revealArchiveInOrganizer = "YES">- </ArchiveAction>-</Scheme>diff --git a/native/ios/Bento/AppDelegate.swift b/native/ios/Bento/AppDelegate.swiftdeleted file mode 100644index d7bdb6be..00000000--- a/native/ios/Bento/AppDelegate.swift+++ /dev/null@@ -1,24 +0,0 @@-import UIKit--@main-class AppDelegate: UIResponder, UIApplicationDelegate {- var window: UIWindow?-- func application(- _ application: UIApplication,- didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?- ) -> Bool {- window = UIWindow(frame: UIScreen.main.bounds)- window?.rootViewController = ViewController()- window?.makeKeyAndVisible()- return true- }-- // Deck files tapped in Files/Mail/AirDrop land here.- func application(_ app: UIApplication, open url: URL,- options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {- guard let vc = window?.rootViewController as? ViewController else { return false }- vc.openExternal(url: url)- return true- }-}diff --git a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/Contents.json b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/Contents.jsondeleted file mode 100644index a690abe7..00000000--- a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/Contents.json+++ /dev/null@@ -1,38 +0,0 @@-{- "images" : [- {- "filename" : "icon.png",- "idiom" : "universal",- "platform" : "ios",- "size" : "1024x1024"- },- {- "appearances" : [- {- "appearance" : "luminosity",- "value" : "dark"- }- ],- "filename" : "icon-dark.png",- "idiom" : "universal",- "platform" : "ios",- "size" : "1024x1024"- },- {- "appearances" : [- {- "appearance" : "luminosity",- "value" : "tinted"- }- ],- "filename" : "icon-tinted.png",- "idiom" : "universal",- "platform" : "ios",- "size" : "1024x1024"- }- ],- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-dark.png b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-dark.pngdeleted file mode 100644index 441d8182..00000000Binary files a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-dark.png and /dev/null differdiff --git a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-tinted.png b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-tinted.pngdeleted file mode 100644index ba0bfc2b..00000000Binary files a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-tinted.png and /dev/null differdiff --git a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon.png b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon.pngdeleted file mode 100644index 441d8182..00000000Binary files a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon.png and /dev/null differdiff --git a/native/ios/Bento/Assets.xcassets/Contents.json b/native/ios/Bento/Assets.xcassets/Contents.jsondeleted file mode 100644index 73c00596..00000000--- a/native/ios/Bento/Assets.xcassets/Contents.json+++ /dev/null@@ -1,6 +0,0 @@-{- "info" : {- "author" : "xcode",- "version" : 1- }-}diff --git a/native/ios/Bento/Info.plist b/native/ios/Bento/Info.plistdeleted file mode 100644index d58c6e74..00000000--- a/native/ios/Bento/Info.plist+++ /dev/null@@ -1,56 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>CFBundleDevelopmentRegion</key>- <string>en</string>- <key>CFBundleDocumentTypes</key>- <array>- <dict>- <key>CFBundleTypeName</key>- <string>bento presentation</string>- <key>CFBundleTypeRole</key>- <string>Editor</string>- <key>LSHandlerRank</key>- <string>Alternate</string>- <key>LSItemContentTypes</key>- <array>- <string>public.html</string>- </array>- </dict>- </array>- <key>CFBundleExecutable</key>- <string>$(EXECUTABLE_NAME)</string>- <key>CFBundleIdentifier</key>- <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>- <key>CFBundleInfoDictionaryVersion</key>- <string>6.0</string>- <key>CFBundleDisplayName</key>- <string>bento</string>- <key>CFBundleName</key>- <string>bento</string>- <key>ITSAppUsesNonExemptEncryption</key>- <false/>- <key>CFBundlePackageType</key>- <string>APPL</string>- <key>CFBundleShortVersionString</key>- <string>1.0</string>- <key>CFBundleVersion</key>- <string>1</string>- <key>LSRequiresIPhoneOS</key>- <true/>- <key>LSSupportsOpeningDocumentsInPlace</key>- <true/>- <key>UIFileSharingEnabled</key>- <true/>- <key>UILaunchScreen</key>- <dict/>- <key>UISupportedInterfaceOrientations</key>- <array>- <string>UIInterfaceOrientationPortrait</string>- <string>UIInterfaceOrientationLandscapeLeft</string>- <string>UIInterfaceOrientationLandscapeRight</string>- <string>UIInterfaceOrientationPortraitUpsideDown</string>- </array>-</dict>-</plist>diff --git a/native/ios/Bento/ViewController.swift b/native/ios/Bento/ViewController.swiftdeleted file mode 100644index 9d82dac2..00000000--- a/native/ios/Bento/ViewController.swift+++ /dev/null@@ -1,581 +0,0 @@-import UIKit-import UniformTypeIdentifiers-import WebKit--/// WKWebView only shows the keyboard for focus caused directly by a user tap on-/// the element; bento focuses its text editors from its own tap handling, which-/// WebKit classes as programmatic → no keyboard. This rewrites the internal-/// focus call to always count as user-interactive (the long-standing-/// Ionic/Cordova workaround). If the selector ever disappears, this is a no-op.-private func allowProgrammaticKeyboard() {- guard let contentView = NSClassFromString("WKContentView") else { return }- let sel = sel_getUid(- "_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:")- guard let method = class_getInstanceMethod(contentView, sel) else { return }- typealias Original = @convention(c)- (Any, Selector, UnsafeRawPointer, Bool, Bool, Int, Any?) -> Void- let original = unsafeBitCast(method_getImplementation(method), to: Original.self)- let block: @convention(block) (Any, UnsafeRawPointer, Bool, Bool, Int, Any?) -> Void = {- me, node, _, blurPrevious, activityState, userObject in- original(me, sel, node, true, blurPrevious, activityState, userObject)- }- method_setImplementation(method, imp_implementationWithBlock(block))-}--/// Hosts bento full-screen with no native chrome. Bento's own buttons drive the-/// native document cycle through the injected File System Access shim:-/// open → injected toolbar button / Files tap → native picker, the picked-/// file becomes the backing document-/// save → written back to the backing document in place (no dialog);-/// Files export sheet when there is no backing file (save-as)-/// localStorage is bridged to UserDefaults so bento's preferences survive-/// regardless of WKWebView's file-origin storage quirks.-class ViewController: UIViewController, WKScriptMessageHandler, WKUIDelegate,- WKNavigationDelegate, UIDocumentPickerDelegate {-- private var webView: WKWebView!-- /// Security-scoped bookmark of the deck file backing the current session.- /// nil while running the default (bundled/OTA) deck.- private var backingBookmark: Data?- private var backingName: String?- /// The sandboxed file actually rendered by the web view.- private var renderURL: URL!-- private enum PickerMode { case none, open, export }- private var pickerMode: PickerMode = .none- private var pendingOpenURL: URL?-- private var documentsDir: URL {- FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]- }- private var otaDeck: URL { documentsDir.appendingPathComponent("bento.html") }- private var externalCopy: URL { documentsDir.appendingPathComponent("opened.bento.html") }-- private var defaultDeck: URL {- FileManager.default.fileExists(atPath: otaDeck.path)- ? otaDeck- : Bundle.main.url(forResource: "bento", withExtension: "html")!- }-- override func viewDidLoad() {- super.viewDidLoad()- view.backgroundColor = .systemBackground- allowProgrammaticKeyboard()-- let controller = WKUserContentController()- controller.add(self, name: "bento")-- let config = WKWebViewConfiguration()- config.userContentController = controller- config.mediaTypesRequiringUserActionForPlayback = []- if #available(iOS 15.4, *) {- config.preferences.isElementFullscreenEnabled = true- }-- webView = WKWebView(frame: .zero, configuration: config)- webView.uiDelegate = self- webView.navigationDelegate = self- webView.scrollView.contentInsetAdjustmentBehavior = .never- view.addSubview(webView)-- webView.translatesAutoresizingMaskIntoConstraints = false- NSLayoutConstraint.activate([- webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),- webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),- webView.trailingAnchor.constraint(equalTo: view.trailingAnchor),- webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),- ])-- if let pending = pendingOpenURL {- pendingOpenURL = nil- openExternal(url: pending)- } else {- loadDefaultDeck()- }-- checkForUpdate()- }-- // MARK: - Deck loading-- private func loadDefaultDeck() {- backingBookmark = nil- backingName = nil- load(render: defaultDeck)- }-- private func load(render url: URL) {- renderURL = url- refreshUserScripts()- webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent())- }-- /// Load a deck file from outside the sandbox (Files tap, Mail, AirDrop, or- /// the injected Open button). A sandboxed copy is rendered for a stable- /// file origin; saves are written back to the original in place.- func openExternal(url: URL) {- guard webView != nil else {- pendingOpenURL = url // launched cold via a file tap- return- }- let scoped = url.startAccessingSecurityScopedResource()- defer { if scoped { url.stopAccessingSecurityScopedResource() } }- guard let data = try? Data(contentsOf: url),- (try? data.write(to: externalCopy, options: .atomic)) != nil- else { return }- backingBookmark = try? url.bookmarkData()- backingName = url.lastPathComponent- load(render: externalCopy)- }-- /// User scripts are rebuilt before every load so the localStorage seed- /// reflects the latest persisted state.- private func refreshUserScripts() {- let store = UserDefaults.standard.dictionary(forKey: "bentoLS") as? [String: String] ?? [:]- let seed = (try? JSONSerialization.data(withJSONObject: store))- .flatMap { String(data: $0, encoding: .utf8) } ?? "{}"-- let ucc = webView.configuration.userContentController- ucc.removeAllUserScripts()- ucc.addUserScript(WKUserScript(- source: Self.storageJS.replacingOccurrences(of: "__SEED__", with: seed),- injectionTime: .atDocumentStart, forMainFrameOnly: true))- ucc.addUserScript(WKUserScript(- source: Self.shimJS, injectionTime: .atDocumentStart, forMainFrameOnly: true))- ucc.addUserScript(WKUserScript(- source: Self.logoMenuJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))- // Removes the 350ms tap delay; the double-tap zoom itself is killed- // natively in disableDoubleTapZoom().- ucc.addUserScript(WKUserScript(- source: """- (function () {- var s = document.createElement('style');- s.textContent = 'html { touch-action: manipulation; }';- document.documentElement.appendChild(s);- })();- """,- injectionTime: .atDocumentStart, forMainFrameOnly: true))- ucc.addUserScript(WKUserScript(- source: Self.editButtonJS, injectionTime: .atDocumentEnd, forMainFrameOnly: true))- }-- // MARK: - Shim messages-- func userContentController(_ userContentController: WKUserContentController,- didReceive message: WKScriptMessage) {- guard message.name == "bento",- let body = message.body as? [String: Any],- let action = body["action"] as? String- else { return }-- switch action {- case "save":- let name = (body["name"] as? String).map { ($0 as NSString).lastPathComponent }- ?? "presentation.bento.html"- save(name: name, text: body["text"] as? String ?? "")- case "open":- presentOpenPicker()- case "menu":- let rect = CGRect(x: body["x"] as? Double ?? 20,- y: body["y"] as? Double ?? 20,- width: body["w"] as? Double ?? 44,- height: body["h"] as? Double ?? 32)- presentDocumentMenu(anchor: rect)- case "ls":- var store = UserDefaults.standard.dictionary(forKey: "bentoLS") as? [String: String] ?? [:]- if let key = body["key"] as? String {- store[key] = body["value"] as? String // nil value removes- } else {- store = [:] // clear()- }- UserDefaults.standard.set(store, forKey: "bentoLS")- default:- break- }- }-- // MARK: - Document menu (logo tap)-- private func presentOpenPicker() {- pickerMode = .open- let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.html])- picker.delegate = self- present(picker, animated: true)- }-- /// Native action sheet replacing bento's logo tap. Save / Save As drive- /// bento's own handlers; Settings passes the tap through to what the logo- /// would normally show.- private func presentDocumentMenu(anchor: CGRect) {- let menu = UIAlertController(title: backingName ?? "Bento",- message: nil, preferredStyle: .actionSheet)-- menu.addAction(UIAlertAction(title: "Save", style: .default) { [weak self] _ in- // Bento's save button carries "(⌘S)" in its tooltip in every locale;- // fall back to the keyboard shortcut if the topbar changed.- self?.webView.evaluateJavaScript("""- (function () {- var bar = document.querySelector('.ed-topbar');- var btn = bar && Array.prototype.find.call(- bar.querySelectorAll('button'),- function (b) { return (b.title || '').indexOf('\\u2318S') >= 0; });- if (btn) { btn.click(); return; }- document.dispatchEvent(new KeyboardEvent('keydown',- { key: 's', code: 'KeyS', keyCode: 83, metaKey: true,- bubbles: true, cancelable: true }));- })();- """)- })-- menu.addAction(UIAlertAction(title: "Save As…", style: .default) { [weak self] _ in- // Opens bento's own save-as dropdown (copy, new deck, password…).- self?.webView.evaluateJavaScript(- "document.querySelector('.ed-topbar .ed-split-caret')?.click()")- })-- menu.addAction(UIAlertAction(title: "Open…", style: .default) { [weak self] _ in- self?.presentOpenPicker()- })-- menu.addAction(UIAlertAction(title: "Settings…", style: .default) { [weak self] _ in- self?.webView.evaluateJavaScript("""- (function () {- var logo = document.querySelector('.ed-logo');- if (logo) { window.__bentoAllowLogo = true; logo.click(); }- })();- """)- })-- menu.addAction(UIAlertAction(title: "Cancel", style: .cancel))-- if let popover = menu.popoverPresentationController {- let zoom = webView.pageZoom- popover.sourceView = webView- popover.sourceRect = CGRect(x: anchor.minX * zoom, y: anchor.minY * zoom,- width: anchor.width * zoom, height: anchor.height * zoom)- }- present(menu, animated: true)- }-- /// In-place save to the backing document; export sheet when there is none- /// or the deck was renamed (save-as).- private func save(name: String, text: String) {- if let bookmark = backingBookmark, name == backingName,- writeBack(bookmark: bookmark, text: text) {- if renderURL == externalCopy {- try? text.write(to: externalCopy, atomically: true, encoding: .utf8)- }- return- }- if backingBookmark == nil {- // First save of the default deck: it becomes the user's own file in- // Documents (visible in Files ▸ Bento) and saves in place from then- // on. Kept separate from the OTA engine copy so updates can never- // clobber user edits.- let dst = documentsDir.appendingPathComponent(name)- if (try? text.write(to: dst, atomically: true, encoding: .utf8)) != nil {- backingBookmark = try? dst.bookmarkData()- backingName = name- return- }- }- exportSheet(name: name, text: text)- }-- private func writeBack(bookmark: Data, text: String) -> Bool {- var stale = false- guard let url = try? URL(resolvingBookmarkData: bookmark, bookmarkDataIsStale: &stale)- else { return false }- let scoped = url.startAccessingSecurityScopedResource()- defer { if scoped { url.stopAccessingSecurityScopedResource() } }-- var ok = false- NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing,- error: nil) { dst in- ok = (try? text.write(to: dst, atomically: true, encoding: .utf8)) != nil- }- if ok, stale { backingBookmark = try? url.bookmarkData() }- return ok- }-- private func exportSheet(name: String, text: String) {- let tmp = FileManager.default.temporaryDirectory.appendingPathComponent(name)- guard (try? text.write(to: tmp, atomically: true, encoding: .utf8)) != nil else { return }- pickerMode = .export- let picker = UIDocumentPickerViewController(forExporting: [tmp], asCopy: true)- picker.delegate = self- present(picker, animated: true)- }-- // MARK: - Document picker results-- func documentPicker(_ controller: UIDocumentPickerViewController,- didPickDocumentsAt urls: [URL]) {- let mode = pickerMode- pickerMode = .none- guard mode == .open, let url = urls.first else { return }- openExternal(url: url)- }-- func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {- pickerMode = .none- }-- // MARK: - Gestures-- /// WKWebView's double-tap-to-zoom is a native recognizer that ignores CSS- /// touch-action; disabling it is the only reliable off switch. WebKit can- /// re-arm recognizers after layout, so this is re-applied after each load- /// (with a delayed second pass).- private func disableDoubleTapZoom() {- for sub in webView.scrollView.subviews {- for recognizer in sub.gestureRecognizers ?? [] {- if let tap = recognizer as? UITapGestureRecognizer,- tap.numberOfTapsRequired >= 2 {- tap.isEnabled = false- }- }- }- }-- func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {- disableDoubleTapZoom()- DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) { [weak self] in- self?.disableDoubleTapZoom()- }- }-- // MARK: - Resilience-- /// The web content process can be killed under memory pressure (heavy- /// rotations included); a blank view otherwise stays blank forever.- func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {- if let url = renderURL {- load(render: url)- }- }-- // MARK: - OTA update (applies on next launch)-- private func checkForUpdate() {- let api = URL(string: "https://api.github.com/repos/nyblnet/bento/releases/latest")!- URLSession.shared.dataTask(with: api) { [weak self] data, _, _ in- guard let self,- let data,- let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],- let tag = json["tag_name"] as? String,- tag != UserDefaults.standard.string(forKey: "otaTag"),- let assets = json["assets"] as? [[String: Any]],- let asset = assets.first(where: { ($0["name"] as? String)?.hasSuffix(".html") == true }),- let urlString = asset["browser_download_url"] as? String,- let assetURL = URL(string: urlString)- else { return }-- URLSession.shared.dataTask(with: assetURL) { body, _, _ in- guard let body,- body.count > 100_000,- String(data: body.prefix(4096), encoding: .utf8)?.contains("<") == true- else { return }- do {- try body.write(to: self.otaDeck, options: .atomic)- UserDefaults.standard.set(tag, forKey: "otaTag")- } catch {}- }.resume()- }.resume()- }-- // MARK: - JS dialogs → native alerts-- func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String,- initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {- let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)- alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler() })- present(alert, animated: true)- }-- func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String,- initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {- let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)- alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(false) })- alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in completionHandler(true) })- present(alert, animated: true)- }-- func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String,- defaultText: String?, initiatedByFrame frame: WKFrameInfo,- completionHandler: @escaping (String?) -> Void) {- let alert = UIAlertController(title: nil, message: prompt, preferredStyle: .alert)- alert.addTextField { $0.text = defaultText }- alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in completionHandler(nil) })- alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in- completionHandler(alert.textFields?.first?.text)- })- present(alert, animated: true)- }-- // MARK: - Injected scripts-- /// localStorage bridged to UserDefaults: immune to WKWebView's file/opaque- /// origin storage quirks. Seeded synchronously, persisted via the bridge.- private static let storageJS = """- (function () {- var data = __SEED__;- function post(k, v) {- webkit.messageHandlers.bento.postMessage({ action: 'ls', key: k, value: v });- }- var shim = {- getItem: function (k) {- return Object.prototype.hasOwnProperty.call(data, k) ? data[k] : null;- },- setItem: function (k, v) { v = String(v); data[k] = v; post(k, v); },- removeItem: function (k) { delete data[k]; post(k, null); },- clear: function () { data = {}; post(null, null); },- key: function (i) {- var keys = Object.keys(data);- return i >= 0 && i < keys.length ? keys[i] : null;- }- };- Object.defineProperty(shim, 'length', {- get: function () { return Object.keys(data).length; }- });- try {- Object.defineProperty(window, 'localStorage', { value: shim, configurable: true });- } catch (e) {}- })();- """-- // Bridges the File System Access API (absent in WKWebView) to native.- private static let shimJS = """- (function () {- if (window.__bentoShim) return;- window.__bentoShim = true;-- function post(msg) { webkit.messageHandlers.bento.postMessage(msg); }-- function makeWritable(onClose) {- return function () {- var parts = [];- return Promise.resolve({- write: function (d) {- if (d && typeof d === 'object' && d.data !== undefined &&- !(d instanceof Blob) && !(d instanceof ArrayBuffer) && !ArrayBuffer.isView(d)) {- d = d.data;- }- parts.push(d);- return Promise.resolve();- },- truncate: function () { return Promise.resolve(); },- seek: function () { return Promise.resolve(); },- close: function () {- return new Blob(parts).text().then(onClose);- }- });- };- }-- window.showSaveFilePicker = function (opts) {- var name = (opts && opts.suggestedName) || 'presentation.bento.html';- return Promise.resolve({- kind: 'file',- name: name,- createWritable: makeWritable(function (t) {- post({ action: 'save', name: name, text: t });- }),- queryPermission: function () { return Promise.resolve('granted'); },- requestPermission: function () { return Promise.resolve('granted'); }- });- };- })();- """-- /// Touch affordance for text editing: bento enters text edit on dblclick- /// (stage listener → startTextEdit on the closest .bento-el-text), which is- /// awkward on touch. When a text element is tapped (= selected), a floating- /// ✎ Edit pill appears beside it; tapping the pill dispatches a synthetic- /// dblclick on the element, entering bento's text editor (the keyboard- /// swizzle then brings up the keyboard).- private static let editButtonJS = """- (function () {- var btn = null, target = null;-- function hide() {- if (btn) btn.style.display = 'none';- target = null;- }-- function ensureBtn() {- if (btn) return btn;- btn = document.createElement('button');- btn.textContent = '\\u270E Edit';- btn.setAttribute('style',- 'position:fixed;z-index:99999;display:none;padding:7px 14px;' +- 'background:#fff;color:#1a1a2e;border:1px solid #d8dce4;' +- 'border-radius:999px;font:600 13px -apple-system,sans-serif;' +- 'box-shadow:0 2px 10px rgba(0,0,0,.18);pointer-events:auto;');- btn.addEventListener('click', function (e) {- e.stopPropagation();- if (!target) return;- var el = target;- hide();- var r = el.getBoundingClientRect();- el.dispatchEvent(new MouseEvent('dblclick', {- bubbles: true, cancelable: true, view: window,- clientX: r.left + r.width / 2, clientY: r.top + r.height / 2- }));- });- document.documentElement.appendChild(btn);- return btn;- }-- function show(el) {- target = el;- var b = ensureBtn();- var r = el.getBoundingClientRect();- b.style.display = 'block';- b.style.left = Math.min(Math.max(8, r.right - 30), window.innerWidth - 90) + 'px';- b.style.top = Math.max(8, r.top - 44) + 'px';- }-- document.addEventListener('pointerup', function (e) {- if (e.target === btn) return;- var el = e.target && e.target.closest && e.target.closest('.bento-el-text');- if (el && !el.isContentEditable &&- !(document.activeElement && document.activeElement.isContentEditable)) {- setTimeout(function () { show(el); }, 50);- } else {- hide();- }- }, true);- window.addEventListener('scroll', hide, true);- window.addEventListener('resize', hide);- })();- """-- /// Tapping bento's logo normally opens project settings. Intercept it (at- /// capture phase, so nothing else sees the tap) and show the native- /// document menu instead; the Settings action re-clicks the logo with- /// __bentoAllowLogo set, letting the original behavior through. If the- /// topbar markup ever changes, interception silently doesn't attach and- /// bento behaves as stock.- private static let logoMenuJS = """- (function () {- var tries = 0;- var timer = setInterval(function () {- tries++;- if (tries > 100) { clearInterval(timer); return; }- var logo = document.querySelector('.ed-topbar .ed-logo');- if (!logo) return;- clearInterval(timer);- logo.addEventListener('click', function (e) {- if (window.__bentoAllowLogo) { window.__bentoAllowLogo = false; return; }- e.preventDefault();- e.stopImmediatePropagation();- var r = logo.getBoundingClientRect();- webkit.messageHandlers.bento.postMessage(- { action: 'menu', x: r.left, y: r.top, w: r.width, h: r.height });- }, true);- }, 200);- })();- """-}diff --git a/native/ios/ExportOptions.plist b/native/ios/ExportOptions.plistdeleted file mode 100644index 652f67b3..00000000--- a/native/ios/ExportOptions.plist+++ /dev/null@@ -1,10 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">-<plist version="1.0">-<dict>- <key>method</key>- <string>app-store-connect</string>- <key>uploadSymbols</key>- <true/>-</dict>-</plist>diff --git a/native/ios/Makefile b/native/ios/Makefiledeleted file mode 100644index 4185dff6..00000000--- a/native/ios/Makefile+++ /dev/null@@ -1,35 +0,0 @@-.PHONY: run devices build archive icons deck--## make run — pick a simulator or device, build, install + launch-## make run device=UDID — skip the prompt-## make run TEAM=ABC123 — signing team (required for physical devices)-run: deck- @TEAM=$(TEAM) ./run.sh $(device)--devices:- @echo "-- Simulators (available):"- @xcrun simctl list devices available | grep -E 'iPhone|iPad' || true- @echo "-- Physical devices:"- @xcrun devicectl list devices 2>/dev/null || true--build: deck- @xcodebuild -project Bento.xcodeproj -target Bento -configuration Debug \- -sdk iphonesimulator build CODE_SIGNING_ALLOWED=NO -quiet- @echo "Built build/Debug-iphonesimulator/Bento.app"--## App Store artifact: make archive TEAM=YOURTEAMID → build/Bento.ipa-archive: deck- @test -n "$(TEAM)" || { echo "Usage: make archive TEAM=YOURTEAMID"; exit 1; }- @xcodebuild -project Bento.xcodeproj -scheme Bento -configuration Release \- -destination "generic/platform=iOS" -archivePath build/Bento.xcarchive \- archive DEVELOPMENT_TEAM=$(TEAM) -allowProvisioningUpdates -quiet- @xcodebuild -exportArchive -archivePath build/Bento.xcarchive \- -exportPath build -exportOptionsPlist ExportOptions.plist \- -allowProvisioningUpdates -quiet- @ls -la build/Bento.ipa--icons:- @python3 ../scripts/gen_icons.py--deck:- @../scripts/fetch-deck.shdiff --git a/native/ios/run.sh b/native/ios/run.shdeleted file mode 100755index d055ca7c..00000000--- a/native/ios/run.sh+++ /dev/null@@ -1,83 +0,0 @@-#!/bin/bash-# Build, install and launch on a chosen simulator or physical device.-# Usage: ./run.sh [udid] (TEAM=YOURTEAMID required for physical devices)-set -e-cd "$(dirname "$0")"--[ -f Bento/Resources/bento.html ] || ../scripts/fetch-deck.sh--APP_ID=slides.bento.app-PROJECT=Bento.xcodeproj-TARGET=Bento--# Collect targets as "kind|udid|label" — booted simulators first, then physical devices.-entries=()-while IFS= read -r line; do [ -n "$line" ] && entries+=("$line"); done < <(- xcrun simctl list devices available --json | python3 -c '-import json, sys-data = json.load(sys.stdin)-rows = []-for runtime, devs in data["devices"].items():- ver = runtime.rsplit(".", 1)[-1].replace("iOS-", "iOS ").replace("-", ".")- for d in devs:- if "iPhone" in d["name"] or "iPad" in d["name"]:- booted = d["state"] == "Booted"- rows.append((not booted, "sim|%s|%s (%s)%s" % (- d["udid"], d["name"], ver, " [booted]" if booted else "")))-rows.sort()-print("\n".join(r[1] for r in rows))'-- tmp=$(mktemp)- if xcrun devicectl list devices --json-output "$tmp" >/dev/null 2>&1; then- python3 -c '-import json, sys-data = json.load(open(sys.argv[1]))-for d in data.get("result", {}).get("devices", []):- name = d.get("deviceProperties", {}).get("name", "device")- udid = d.get("identifier")- if udid:- print("dev|%s|%s [physical]" % (udid, name))' "$tmp"- fi- rm -f "$tmp"-)--if [ ${#entries[@]} -eq 0 ]; then- echo "No simulators or devices found."- exit 1-fi--if [ -n "$1" ]; then- choice=""- for e in "${entries[@]}"; do- case "$e" in *"|$1|"*) choice="$e" ;; esac- done- if [ -z "$choice" ]; then echo "UDID $1 not found."; exit 1; fi-else- echo "Available targets:"- labels=()- for e in "${entries[@]}"; do labels+=("${e#*|*|}"); done- select l in "${labels[@]}"; do choice="${entries[$((REPLY-1))]}"; break; done-fi--kind="${choice%%|*}"; rest="${choice#*|}"; udid="${rest%%|*}"; label="${rest#*|}"-echo "Target: $label ($udid)"--if [ "$kind" = "sim" ]; then- xcodebuild -project "$PROJECT" -target "$TARGET" -configuration Debug \- -sdk iphonesimulator build CODE_SIGNING_ALLOWED=NO -quiet- xcrun simctl boot "$udid" 2>/dev/null || true- open -a Simulator- xcrun simctl install "$udid" "build/Debug-iphonesimulator/$TARGET.app"- xcrun simctl launch "$udid" "$APP_ID"-else- if [ -z "$TEAM" ]; then- echo "Physical device needs a signing team: make run TEAM=YOURTEAMID"- exit 1- fi- xcodebuild -project "$PROJECT" -target "$TARGET" -configuration Debug \- -destination "id=$udid" -allowProvisioningUpdates \- DEVELOPMENT_TEAM="$TEAM" CODE_SIGN_STYLE=Automatic build -quiet- xcrun devicectl device install app --device "$udid" "build/Debug-iphoneos/$TARGET.app"- xcrun devicectl device process launch --device "$udid" "$APP_ID"-fi-echo "Launched $APP_ID on $label"diff --git a/native/package.json b/native/package.jsondeleted file mode 100644index 8d5bd555..00000000--- a/native/package.json+++ /dev/null@@ -1,14 +0,0 @@-{- "name": "bento-native",- "private": true,- "description": "npm facade over the native shells' Makefiles — see native/README.md",- "scripts": {- "deck": "scripts/fetch-deck.sh",- "icons": "python3 scripts/gen_icons.py",- "build:apk": "make -C android release",- "build:aab": "make -C android bundle",- "build:ipa": "make -C ios archive",- "run:android": "make -C android run",- "run:ios": "make -C ios run"- }-}diff --git a/native/scripts/fetch-deck.sh b/native/scripts/fetch-deck.shdeleted file mode 100755index 5a327406..00000000--- a/native/scripts/fetch-deck.sh+++ /dev/null@@ -1,34 +0,0 @@-#!/bin/bash-# Provision the bento.html the native shells bundle as their offline fallback.-# Prefers a locally built single-file (slides/npm run build:single); falls back-# to the latest signed GitHub release. The artifact is gitignored — it is a-# build input, not source.-set -e-cd "$(dirname "$0")/../.."--LOCAL=slides/dist-single/Bento_Slides.bento.html-TARGETS=(- native/ios/Bento/Resources/bento.html- native/android/app/src/main/assets/bento.html-)--if [ -f "$LOCAL" ]; then- SRC="$LOCAL"- echo "fetch-deck: using locally built $LOCAL"-else- SRC=$(mktemp)- URL=$(curl -s https://api.github.com/repos/nyblnet/bento/releases/latest |- python3 -c 'import json,sys; d=json.load(sys.stdin); print(next(a["browser_download_url"] for a in d["assets"] if a["name"].endswith(".html")))')- echo "fetch-deck: downloading $URL"- curl -sL -o "$SRC" "$URL"- head -c 4096 "$SRC" | grep -q '<!DOCTYPE html>' || {- echo "fetch-deck: downloaded file does not look like a bento deck" >&2- exit 1- }-fi--for t in "${TARGETS[@]}"; do- mkdir -p "$(dirname "$t")"- cp "$SRC" "$t"- echo "fetch-deck: → $t"-donediff --git a/native/scripts/gen_icons.py b/native/scripts/gen_icons.pydeleted file mode 100644index 95e88b4d..00000000--- a/native/scripts/gen_icons.py+++ /dev/null@@ -1,85 +0,0 @@-#!/usr/bin/env python3-"""Generate the iOS app icon set from the bento logo (pure python, no deps).--Geometry and palette come from docs/assets/bento-logo.svg:-a #16273E rounded square with three blocks — slate, coral, cream — on a 32-unit-grid. The Android launcher icons are hand-authored vector XML with the same-geometry (native/android/.../res/drawable/).-"""-import os-import struct-import zlib--ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))--NAVY = (0x16, 0x27, 0x3E)-SLATE = (0x5E, 0x76, 0x99)-CORAL = (0xFF, 0x9E, 0x8A)-CREAM = (0xF0, 0xEB, 0xE0)--# (x, y, w, h, color) on the logo's 32-unit grid, radius 2-RECTS = [- (5, 5, 7, 22, SLATE),- (14, 5, 13, 10, CORAL),- (14, 17, 13, 10, CREAM),-]-RADIUS = 2.5---def in_rounded_rect(px, py, x0, y0, x1, y1, r):- if px < x0 or px >= x1 or py < y0 or py >= y1:- return False- cx = min(max(px, x0 + r), x1 - r)- cy = min(max(py, y0 + r), y1 - r)- return (px - cx) ** 2 + (py - cy) ** 2 <= r * r or (- x0 + r <= px < x1 - r or y0 + r <= py < y1 - r)---def render(size, bg, rects, alpha=False):- scale = size / 32.0- base = (0, 0, 0) if bg is None else bg- srects = [(x * scale, y * scale, (x + w) * scale, (y + h) * scale, c)- for x, y, w, h, c in rects]- r = RADIUS * scale- rows = bytearray()- for y in range(size):- rows.append(0)- py = y + 0.5- for x in range(size):- px = x + 0.5- color, a = base, (0 if bg is None else 255)- for x0, y0, x1, y1, c in srects:- if in_rounded_rect(px, py, x0, y0, x1, y1, r):- color, a = c, 255- break- rows += bytes(color) + (bytes([a]) if alpha else b'')- return encode_png(size, size, bytes(rows), alpha)---def encode_png(w, h, raw, alpha):- def chunk(tag, data):- return struct.pack('>I', len(data)) + tag + data + \- struct.pack('>I', zlib.crc32(tag + data))- png = b'\x89PNG\r\n\x1a\n'- png += chunk(b'IHDR', struct.pack('>IIBBBBB', w, h, 8, 6 if alpha else 2, 0, 0, 0))- png += chunk(b'IDAT', zlib.compress(raw, 9))- png += chunk(b'IEND', b'')- return png---def write(path, data):- os.makedirs(os.path.dirname(path), exist_ok=True)- with open(path, 'wb') as f:- f.write(data)- print('%7d %s' % (len(data), os.path.relpath(path, ROOT)))---iconset = os.path.join(ROOT, 'ios/Bento/Assets.xcassets/AppIcon.appiconset')--# Light and dark share the navy tile (it already is a dark design).-write(os.path.join(iconset, 'icon.png'), render(1024, NAVY, RECTS))-write(os.path.join(iconset, 'icon-dark.png'), render(1024, NAVY, RECTS))-# Tinted: grayscale blocks on transparency; the system supplies the backdrop.-tint = [(x, y, w, h, {SLATE: (150,) * 3, CORAL: (255,) * 3, CREAM: (210,) * 3}[c])- for x, y, w, h, c in RECTS]-write(os.path.join(iconset, 'icon-tinted.png'), render(1024, None, tint, alpha=True))diff --git a/tray/README.md b/tray/README.mdindex abfd5ce6..51fa0e22 100644--- a/tray/README.md+++ b/tray/README.md@@ -1,13 +1,27 @@-# bento/tray — iOS+# bento/tray-A thin native host that runs **any self-contained HTML document** and lets it-**save itself in place** on iOS.+Thin native hosts that run **any self-contained HTML document** and let it+**save itself in place**, on platforms where a browser will not.-Bento decks are the reason it exists, but nothing in the Swift is Bento-specific-— it never parses the document, it is a courier. Any single-file HTML app that-saves itself through the File System Access API works the same way, which on iOS-is otherwise impossible: every browser there is WebKit and none of them ship-that API.+Three of them, under `tray/<platform>/`:++| | what it hosts | why it exists |+|---|---|---|+| `ios/` | UIDocument + WKWebView | every iOS browser is WebKit, and none ship the File System Access API |+| `android/` | Storage Access Framework + WebView | Chrome on Android has no File System Access API either |+| `webext/` | a directory grant, in the browser | `file://` pages get no persistent handle |++Bento decks are the reason they exist, but nothing in the Swift or the Kotlin is+Bento-specific — neither ever parses the document, both are couriers. Any+single-file HTML app that saves itself through the File System Access API works+the same way.++**The web-side half is ONE file, `tray/bridge.js`,** shared by iOS and Android.+It polyfills the single call Bento tests for, and the interesting part of it is+not the transport but the `FileSystemWritableFileStream` semantics — whose+comments record a bug that wrote users' documents out as zero bytes. A second+copy would be a second chance to reintroduce exactly that, so the per-platform+part is the ~15 lines of transport at the top and nothing else.## Why this exists@@ -64,8 +78,8 @@ doubt, prompt.**Pinned by `scripts/test-savepurpose.ts`.-So `Resources/bridge.js` polyfills that over a `UIDocument` bridge — three-methods. Two consequences:+So `tray/bridge.js` polyfills that — over `UIDocument` on iOS, over the Storage+Access Framework on Android, from the one shared file. Two consequences:- **No web-side changes at all.** Every in-place path (⌘S, autosave write-back,self-update, the capability-aware messaging) already routes through that one@@ -247,21 +261,15 @@ back to downloading the rollback copy, which is where it used to go.set to `.never`; left at its default UIKit insets the scroll view by the safearea, which in landscape left visible bands down the left, right and bottom ofa slideshow. The document owns its margins; the host adds none.-- **The host shows nothing while the page presents.** `webView.fullscreenState`- is observed, and entering fullscreen hides both the nav bar and the floating- exit — a control sitting over a slideshow is exactly the chrome presenting is- meant to shed. (Contrary to one analysis, `fullscreenState` IS usable here,- because element fullscreen genuinely works — see below.)-- **Element fullscreen is enabled** (`preferences.isElementFullscreenEnabled`).- iPhone Safari has never offered element fullscreen to web pages, which is why- Bento's present mode falls back to filling its view in a browser — but- WKWebView exposes it as an opt-in. So a hosted document presents properly- where the very same file in Safari cannot: verified on an iPhone 17 Pro Max,- the status bar, the nav bar and Bento's own toolbar all disappear, the deck- letterboxes on black with a native ✕, and swiping advances slides. This is a- case where the wrapper is not merely restoring parity with desktop but doing- something the browser cannot. Credit to #87 for finding the flag.-- **`bridge.js` is injected `.atDocumentStart`.** Bento decides whether it can+- **The host shows nothing while the page presents.** The floating exit fades out+ when nothing is happening and comes back on touch — a control sitting over a+ slideshow is exactly the chrome presenting is meant to shed. It is done by idle+ timer rather than by observing `fullscreenState`, because the host no longer+ takes element fullscreen at all: see "Element fullscreen is DECLINED" below,+ which is the authoritative account. (An earlier version of this list claimed+ the opt-in was enabled and credited #87 for finding the flag. The flag is real+ and the credit stands; the conclusion did not survive being measured.)+- **`bridge.js` is injected at document start.** Bento decides whether it cansave during boot; injected later, the editor has already concluded it cannot.## Getting documents in@@ -421,3 +429,133 @@ Still to do:- App icon, launch screen, signing, an Apple Developer account ($99/yr).- Decide whether a `.bento.html` UTI is worth declaring over plain `public.html`.++## Android++Same thesis as iOS, and for the same reason: Chrome on Android does not ship the+File System Access API either, so a deck opened in a browser there can only ever+hand back downloaded copies. `tray/android/` is ~700 lines of Kotlin with one+dependency, and it keeps both of the decisions the iOS host is built on — the+document is served through an origin we control, and the app bundles no runtime+for rendering.++**Origin: [#87](https://github.com/nyblnet/bento/pull/87), by+[savrum](https://github.com/savrum)**, which asked for native wrapper apps+before either host existed and is the branch this landed on. The Gradle layout,+the `keystore.properties` pattern and the device-picker ergonomics come from+there; so did `isElementFullscreenEnabled`, which `tray/ios` used until+measurement sent it the other way. The architecture changed — a host that+bundles a deck and updates itself over the air is the thing tray exists not to+be — but the question it asked was the right one, and it was asked first.++### What is genuinely different++Three things, and none of them are stylistic.++**There is no document browser to host.** iOS hands over+`UIDocumentBrowserViewController` — a whole file browser, showing iCloud and+every File Provider on the device. Android's picker is a one-shot dialog that+returns a URI and closes. So the root screen is the app's own list of documents+it holds **persistable URI permissions** for, which is Android's analogue of a+security-scoped bookmark. On iOS the app is a lens onto the filesystem; on+Android it is a keyring. Both end at the same place.++**Write access is not implied by being handed a document.** A document opened+through the app's own picker (`ACTION_OPEN_DOCUMENT`) carries a persistable+read+write grant. A document arriving by `ACTION_VIEW` — tapped in a file+manager, opened from Drive or Gmail — usually carries **read only**, because+that is all the sender chose to grant, and no API lets the receiver ask for+more. So `canWriteInPlace` is checked rather than assumed, and when it is false+every save becomes a Save-As and the user is told once, up front. This follows+the rule stated above for the whole project: **when in doubt, prompt** — a+silently failing save is the worst outcome available.++`ACTION_GET_CONTENT` is never used. It hands back a *copy*, which is the entire+problem this app exists to solve.++**The origin is an `https://` host that never resolves.** iOS registers a custom+`bento-tray://` scheme; Android has no equivalent hook, so the document is served+from `https://<sha256-of-uri>.bento-tray.invalid/` and every request to it is+answered from memory in `shouldInterceptRequest`. `.invalid` is reserved by+RFC 6761 and can never resolve, so a missed intercept fails dead rather than+quietly reaching somebody's server. Per-document for the same reason as iOS: a+shared origin would let one document read another's `localStorage`.++### The one dependency++`androidx.webkit`, and it earns its place twice:++- **`addDocumentStartJavaScript`** is the exact equivalent of+ `WKUserScript(.atDocumentStart)`. Bento decides whether it can save *during+ boot*, so a bridge injected from `onPageStarted`/`onPageFinished` races the+ page — and the symptom is not a crash, it is an editor that quietly believes+ it cannot save.+- **`addWebMessageListener`** is **origin-scoped**. `addJavascriptInterface`, the+ dependency-free alternative that most WebView wrappers reach for, is injected+ into *every frame*, so a remote iframe inside an untrusted document would be+ handed a channel that writes the user's file.++It also removes a hazard the iOS host still carries: replies travel as JSON over+a message channel rather than as an evaluated JS call, so there is no+string-literal encoding step to get wrong. (On iOS a raw newline in a `read`+reply — which returns the *whole document* — is a syntax error that hangs the+page's promise forever. That is handled there; here it cannot arise.)++### Building++Needs a JDK 17 and the Android SDK; no Android Studio required.++```sh+brew install openjdk@17 && brew install --cask android-commandlinetools+sdkmanager "platform-tools" "platforms;android-36" "build-tools;36.0.0"+```++```sh+cd tray/android && ./gradlew :app:assembleDebug+```++`ANDROID_HOME` must point at the SDK (`/opt/homebrew/share/android-commandlinetools`+for the cask above) and `JAVA_HOME` at the JDK. AGP 8.x **cannot run on Gradle+9.6+**, so the wrapper is pinned to 8.14.3 — use `./gradlew`, never a system+`gradle`.++The starter shell and `bridge.js` are staged into assets by the build+(`stageTrayAssets`), mirroring the iOS pre-build step. Neither is committed: a+587KB binary in git would churn on every release, and the seed ages harmlessly+because a new deck self-updates through the normal signed channel.++The launcher icon is generated from the same mark as iOS. The tray is **56 units+of the 108 canvas, not the full 72 safe zone** — at 72 it exactly filled the+visible area, so every launcher mask cut its corners off and the navy frame that+makes the mark read was never drawn. Regenerate the path data with:++```sh+node -e 'const f=n=>+n.toFixed(2),rr=(x,y,w,h,r)=>`M${f(x+r)},${f(y)} H${f(x+w-r)} A${f(r)},${f(r)} 0 0 1 ${f(x+w)},${f(y+r)} V${f(y+h-r)} A${f(r)},${f(r)} 0 0 1 ${f(x+w-r)},${f(y+h)} H${f(x+r)} A${f(r)},${f(r)} 0 0 1 ${f(x)},${f(y+h-r)} V${f(y+r)} A${f(r)},${f(r)} 0 0 1 ${f(x+r)},${f(y)} Z`,S=56/23.6,O=26,m=v=>O+(v-4.2)*S;console.log(rr(O,O,56,56,4.8*S));console.log(rr(m(6.8),m(6.8),5.855*S,18.4*S,2.091*S));console.log(rr(m(14.327),m(6.8),10.873*S,8.364*S,2.091*S));console.log(rr(m(14.327),m(16.836),10.873*S,8.364*S,2.091*S))'+```++### State: the document cycle works, on an emulator only++Verified end to end on a Pixel 7 / Android 16 emulator, driven through the real+UI rather than a harness:++- **New** creates a document where the user chooses, seeds it from the bundled+ shell, and opens it — the full Bento editor renders in the WebView+- the document's own runtime is live: its update check reached the network and+ reported v1.0.18+- **a save lands in place, with no picker** — 686,232 → 908,246 bytes, the+ activity never left `EditorActivity`+- the written file is a valid deck: `id="bento-doc"` present, preview markers+ present, well-formed from `<!DOCTYPE html>` to `</body></html>`, `docId` minted+- the document reopens from the recents list on its persisted grant+- the adaptive icon renders correctly under a circular launcher mask++Not yet verified:++- **anything on real hardware**, and no signing keystore exists yet+- the `ACTION_VIEW` route in (opening from a file manager, Drive, Gmail) and the+ read-only path it usually implies — the branch is written, not exercised+- Save-As / export, and the `<a download>` + `blob:` readback path+- a third-party self-saving app (TiddlyWiki) through the polyfill's params branch+- presenting: element fullscreen is declined, as on iOS, but Android's+ `onShowCustomView` gives a host full control of the fullscreen chrome — unlike+ WebKit's un-hideable ✕ — so this is worth revisiting rather than settlingdiff --git a/tray/android/app/build.gradle.kts b/tray/android/app/build.gradle.ktsnew file mode 100644index 00000000..886955eb--- /dev/null+++ b/tray/android/app/build.gradle.kts@@ -0,0 +1,133 @@+import java.util.Properties++plugins {+ id("com.android.application")+ id("org.jetbrains.kotlin.android")+}++// Release signing. Copy keystore.properties.example to keystore.properties and+// fill it in; the file is gitignored, because a keystore path and its passwords+// identify a publisher. Absent, the release build is debug-signed so it stays+// installable while developing — it just cannot go to Play.+val keystoreProps = Properties().apply {+ val f = rootProject.file("keystore.properties")+ if (f.exists()) f.inputStream().use { load(it) }+}++/**+ * Stages everything the app ships that is generated rather than written.+ *+ * Two inputs, for two reasons:+ *+ * - `tray/bridge.js` is the File System Access polyfill, SHARED with tray/ios.+ * One copy of semantics whose comments record a bug that wrote users'+ * documents out as zero bytes; a second copy would be a second chance to+ * reintroduce it.+ * - the starter shell is COPIED FROM THE CURRENT BUILD, never committed: a+ * 587KB binary in git would churn on every release. It ages harmlessly — a+ * new deck self-updates through Bento's normal signed channel the first time+ * it checks.+ *+ * Mirrors the "Stage starter shell" step in tray/ios/project.yml.+ */+abstract class StageTrayAssets : DefaultTask() {+ @get:InputFiles abstract val bridge: ConfigurableFileCollection+ @get:InputFiles abstract val seed: ConfigurableFileCollection+ @get:OutputDirectory abstract val outputDir: DirectoryProperty++ @TaskAction+ fun stage() {+ val out = outputDir.get().asFile+ out.deleteRecursively()+ out.mkdirs()+ bridge.singleFile.copyTo(out.resolve("bridge.js"), overwrite = true)++ // Resolved at EXECUTION time, not configuration time: the seed is a+ // build artefact of a different project, so it routinely appears after+ // this build was last configured.+ val shell = seed.files.firstOrNull { it.exists() }+ if (shell != null) {+ shell.copyTo(out.resolve("starter.bento.html"), overwrite = true)+ } else {+ logger.warn(+ "warning: no starter shell — run 'npm run build:single' in slides/; " ++ "New document will be unavailable in this build"+ )+ }+ }+}++val stageAssets = tasks.register<StageTrayAssets>("stageTrayAssets") {+ bridge.from(rootProject.file("../bridge.js"))+ seed.from(rootProject.file("../../slides/dist-single/Bento_Slides.bento.html"))+ outputDir.set(layout.buildDirectory.dir("staged-assets"))+}++android {+ namespace = "page.bento.tray"+ compileSdk = 36++ defaultConfig {+ applicationId = "page.bento.tray"+ // 26 covers ~98% of devices and is where the storage APIs this app is+ // built on behave consistently. Below it, ACTION_OPEN_DOCUMENT exists+ // but persistable write grants across providers do not.+ minSdk = 26+ targetSdk = 36+ versionCode = 1+ versionName = "0.1.0"+ }++ if (keystoreProps.isNotEmpty()) {+ signingConfigs {+ create("release") {+ storeFile = rootProject.file(keystoreProps.getProperty("storeFile"))+ storePassword = keystoreProps.getProperty("storePassword")+ keyAlias = keystoreProps.getProperty("keyAlias")+ keyPassword = keystoreProps.getProperty("keyPassword")+ }+ }+ }++ buildTypes {+ release {+ isMinifyEnabled = true+ isShrinkResources = true+ proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")+ signingConfig = if (keystoreProps.isNotEmpty())+ signingConfigs.getByName("release")+ else+ signingConfigs.getByName("debug")+ }+ }++ compileOptions {+ sourceCompatibility = JavaVersion.VERSION_17+ targetCompatibility = JavaVersion.VERSION_17+ }++ kotlinOptions { jvmTarget = "17" }+}++androidComponents {+ onVariants { variant ->+ variant.sources.assets?.addGeneratedSourceDirectory(stageAssets, StageTrayAssets::outputDir)+ }+}++dependencies {+ // The ONLY dependency, and it earns its place twice over:+ //+ // - addDocumentStartJavaScript is the exact equivalent of WebKit's+ // WKUserScript(.atDocumentStart). Bento decides whether it can save+ // DURING BOOT, so a bridge injected from onPageStarted/onPageFinished+ // races the page and loses often enough to matter.+ // - addWebMessageListener is ORIGIN-SCOPED. addJavascriptInterface, the+ // dependency-free alternative, injects into every frame in the WebView,+ // so a remote iframe inside an untrusted document would be handed a+ // channel that writes the user's file.+ //+ // Both are WebView-side features rather than app-side ones, so the library+ // is a thin façade over what the installed WebView already implements.+ implementation("androidx.webkit:webkit:1.17.0")+}diff --git a/tray/android/app/proguard-rules.pro b/tray/android/app/proguard-rules.pronew file mode 100644index 00000000..0a2c3135--- /dev/null+++ b/tray/android/app/proguard-rules.pro@@ -0,0 +1,9 @@+# The app is a courier: two activities, a URI list, and a WebView. There is+# nothing here reflection reaches that R8 cannot see, and no @JavascriptInterface+# to keep — the page talks to native code through addWebMessageListener, which is+# an ordinary Kotlin lambda.+#+# Line numbers, though, are worth the ~10KB: a stack trace from a device is the+# only diagnostic this app will ever get.+-keepattributes SourceFile,LineNumberTable+-renamesourcefileattribute SourceFilediff --git a/tray/android/app/src/main/AndroidManifest.xml b/tray/android/app/src/main/AndroidManifest.xmlnew file mode 100644index 00000000..ee2ea496--- /dev/null+++ b/tray/android/app/src/main/AndroidManifest.xml@@ -0,0 +1,67 @@+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android">++ <!-- For the DOCUMENT, never for the host. The app itself makes no network+ request of any kind — no update check, no telemetry, no phoning home.+ But the document it hosts carries its own runtime, and that runtime+ syncs with the collab relay and checks Bento's signed update channel,+ exactly as it would in a browser tab. Withholding this would silently+ break live collaboration and self-update inside every deck. -->+ <uses-permission android:name="android.permission.INTERNET" />++ <application+ android:label="@string/app_name"+ android:icon="@mipmap/ic_launcher"+ android:roundIcon="@mipmap/ic_launcher_round"+ android:theme="@style/Theme.Tray"+ android:hardwareAccelerated="true"+ android:usesCleartextTraffic="false"+ android:enableOnBackInvokedCallback="true"+ android:supportsRtl="true"+ android:allowBackup="false">++ <!-- allowBackup is off deliberately. The only thing worth backing up is+ the recents list, and it is a list of URI permission grants — which+ are held by the system per install and cannot be restored to a new+ one. A restored list would be entirely dead entries. -->++ <activity+ android:name=".DocumentsActivity"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />+ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <activity+ android:name=".EditorActivity"+ android:exported="true"+ android:parentActivityName=".DocumentsActivity"+ android:documentLaunchMode="intoExisting"+ android:configChanges="orientation|screenSize|screenLayout|keyboardHidden|keyboard|uiMode|density|smallestScreenSize|navigation">++ <!-- configChanges is not an optimisation here. Without it a rotation+ destroys and recreates the WebView, which reloads the document+ from scratch and throws away everything the page held in+ memory: undo history, selection, an in-progress text edit, and+ the live collab session's actor state. -->++ <!-- Opening a document from a file manager, Drive, Gmail, a share+ sheet. LSHandlerRank has no Android equivalent — the chooser+ ranks by user habit — so this simply adds Bento Tray to the+ list of apps offered for an HTML file rather than claiming it.++ An ACTION_VIEW grant is usually READ-ONLY, which is why this is+ the second-best route in and the app says so: see+ EditorActivity.canWriteInPlace. -->+ <intent-filter android:label="@string/open_with_label">+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="content" android:mimeType="text/html" />+ <data android:scheme="file" android:mimeType="text/html" />+ </intent-filter>+ </activity>+ </application>+</manifest>diff --git a/tray/android/app/src/main/java/page/bento/tray/DocumentsActivity.kt b/tray/android/app/src/main/java/page/bento/tray/DocumentsActivity.ktnew file mode 100644index 00000000..ef2036db--- /dev/null+++ b/tray/android/app/src/main/java/page/bento/tray/DocumentsActivity.kt@@ -0,0 +1,307 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++package page.bento.tray++import android.app.Activity+import android.app.AlertDialog+import android.content.Intent+import android.graphics.Color+import android.graphics.Typeface+import android.net.Uri+import android.os.Build+import android.os.Bundle+import android.text.format.DateUtils+import android.util.Log+import android.util.TypedValue+import android.view.Gravity+import android.view.View+import android.view.ViewGroup+import android.view.WindowInsets+import android.widget.BaseAdapter+import android.widget.Button+import android.widget.LinearLayout+import android.widget.ListView+import android.widget.TextView++/**+ * The app's root: the documents this app can reach.+ *+ * iOS gets `UIDocumentBrowserViewController` — a whole file browser, hostable,+ * showing iCloud and every File Provider on the device. Android has nothing to+ * host: its picker is a one-shot dialog that returns a URI and closes. So the+ * root is a list of documents the user has already granted, plus the two ways in.+ *+ * That difference is worth stating plainly rather than apologising for. On iOS+ * the app is a lens onto the filesystem; on Android it is a keyring. Both end at+ * the same place — a document opened where it already lives, with edits going+ * back to that same file.+ */+class DocumentsActivity : Activity() {++ companion object {+ private const val TAG = "BentoTray"+ private const val REQ_OPEN = 1+ private const val REQ_NEW = 2+ private const val SEED = "starter.bento.html"+ }++ private lateinit var list: ListView+ private lateinit var empty: TextView+ private var entries: List<Recents.Entry> = emptyList()++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ setContentView(buildUi())+ }++ override fun onResume() {+ super.onResume()+ refresh()+ }++ private fun refresh() {+ entries = Recents.prune(this)+ (list.adapter as RecentsAdapter).notifyDataSetChanged()+ empty.visibility = if (entries.isEmpty()) View.VISIBLE else View.GONE+ list.visibility = if (entries.isEmpty()) View.GONE else View.VISIBLE+ }++ // MARK: - getting documents in++ /**+ * ACTION_OPEN_DOCUMENT, not ACTION_GET_CONTENT.+ *+ * GET_CONTENT hands back a COPY, which is the whole problem this app exists+ * to solve — every save would land somewhere other than the file the user+ * opened. OPEN_DOCUMENT returns a durable, writable reference to the document+ * itself, and it is the only Android API that does.+ */+ private fun openDocument() {+ val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {+ addCategory(Intent.CATEGORY_OPENABLE)+ // Permissive on type, deliberate about it: providers disagree about+ // what a .bento.html is, and several report octet-stream. A filter+ // that hides the user's own document is worse than one that shows+ // too much.+ type = "*/*"+ putExtra(Intent.EXTRA_MIME_TYPES, arrayOf("text/html", "application/octet-stream"))+ addFlags(+ Intent.FLAG_GRANT_READ_URI_PERMISSION or+ Intent.FLAG_GRANT_WRITE_URI_PERMISSION or+ Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION+ )+ }+ startActivityForResult(intent, REQ_OPEN)+ }++ /**+ * A new document is seeded from the bundled starter shell.+ *+ * The user chooses where it goes, which is not a compromise: it means the new+ * document is a real file in the user's own storage from its first byte, with+ * a persistable write grant already attached. There is no app-private staging+ * copy to migrate later, and no file the user cannot find.+ */+ private fun newDocument() {+ if (!hasSeed()) {+ AlertDialog.Builder(this)+ .setMessage(getString(R.string.err_no_seed))+ .setPositiveButton(android.R.string.ok, null)+ .show()+ return+ }+ val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {+ addCategory(Intent.CATEGORY_OPENABLE)+ type = "text/html"+ putExtra(Intent.EXTRA_TITLE, "Untitled.bento.html")+ addFlags(+ Intent.FLAG_GRANT_READ_URI_PERMISSION or+ Intent.FLAG_GRANT_WRITE_URI_PERMISSION or+ Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION+ )+ }+ startActivityForResult(intent, REQ_NEW)+ }++ private fun hasSeed() = try {+ assets.list("")?.contains(SEED) == true+ } catch (_: Exception) { false }++ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {+ val uri = data?.data+ if (resultCode != RESULT_OK || uri == null) {+ return super.onActivityResult(requestCode, resultCode, data)+ }+ Recents.persist(contentResolver, uri, data.flags)++ when (requestCode) {+ REQ_OPEN -> open(uri)+ REQ_NEW -> seedThenOpen(uri)+ else -> super.onActivityResult(requestCode, resultCode, data)+ }+ }++ private fun seedThenOpen(uri: Uri) {+ Thread {+ val ok = try {+ assets.open(SEED).use { input ->+ contentResolver.openOutputStream(uri, "wt")?.use { input.copyTo(it) }+ ?: throw IllegalStateException("no output stream")+ }+ true+ } catch (e: Exception) {+ Log.w(TAG, "seed failed", e); false+ }+ runOnUiThread {+ if (isFinishing || isDestroyed) return@runOnUiThread+ if (ok) open(uri) else AlertDialog.Builder(this)+ .setMessage(getString(R.string.err_create))+ .setPositiveButton(android.R.string.ok, null)+ .show()+ }+ }.start()+ }++ private fun open(uri: Uri) {+ startActivity(Intent(this, EditorActivity::class.java).putExtra(EditorActivity.EXTRA_URI, uri))+ }++ // MARK: - a plain UI, built in code+ //+ // No layout XML and no AndroidX UI libraries: this screen is a title, two+ // buttons and a list. Every dependency it does not have is one that cannot+ // drift out of step with the WebView work, which is where all the difficulty+ // in this app actually lives.++ private fun buildUi(): View {+ val dp = { v: Int -> (v * resources.displayMetrics.density).toInt() }+ val root = LinearLayout(this).apply {+ orientation = LinearLayout.VERTICAL+ setBackgroundColor(Color.parseColor("#F0EBE0"))+ }++ // Insets are applied by hand, and both halves of that are deliberate.+ //+ // `fitsSystemWindows = true` was the first attempt and it is a trap: it+ // does not ADD the system insets to a view's padding, it REPLACES the+ // padding outright. The screen lost its 20dp side margin and the title+ // sat flush against the edge of the display.+ //+ // Doing nothing is not an option either — from targetSdk 35 an app draws+ // edge to edge whether it asks to or not, so the header would sit under+ // the status bar. This is the only way to have both.+ val pad = intArrayOf(dp(20), dp(28), dp(20), dp(12))+ root.setOnApplyWindowInsetsListener { v, insets ->+ val l: Int; val t: Int; val r: Int; val b: Int+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ val bars = insets.getInsets(WindowInsets.Type.systemBars())+ l = bars.left; t = bars.top; r = bars.right; b = bars.bottom+ } else {+ @Suppress("DEPRECATION")+ run {+ l = insets.systemWindowInsetLeft; t = insets.systemWindowInsetTop+ r = insets.systemWindowInsetRight; b = insets.systemWindowInsetBottom+ }+ }+ v.setPadding(pad[0] + l, pad[1] + t, pad[2] + r, pad[3] + b)+ insets+ }++ root.addView(TextView(this).apply {+ text = getString(R.string.app_name)+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 26f)+ setTypeface(typeface, Typeface.BOLD)+ setTextColor(Color.parseColor("#16273E"))+ })+ root.addView(TextView(this).apply {+ text = getString(R.string.tagline)+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)+ setTextColor(Color.parseColor("#5E7699"))+ setPadding(0, dp(4), 0, dp(20))+ })++ val buttons = LinearLayout(this).apply {+ orientation = LinearLayout.HORIZONTAL+ val lp = LinearLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)+ lp.bottomMargin = dp(16)+ layoutParams = lp+ }+ val half = { LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f) }+ buttons.addView(Button(this).apply {+ text = getString(R.string.open_document)+ layoutParams = half().also { it.rightMargin = dp(8) }+ setOnClickListener { openDocument() }+ })+ buttons.addView(Button(this).apply {+ text = getString(R.string.new_document)+ layoutParams = half()+ setOnClickListener { newDocument() }+ })+ root.addView(buttons)++ empty = TextView(this).apply {+ text = getString(R.string.empty_hint)+ setTextColor(Color.parseColor("#5E7699"))+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 15f)+ gravity = Gravity.CENTER+ setPadding(dp(8), dp(48), dp(8), dp(8))+ visibility = View.GONE+ }+ root.addView(empty)++ list = ListView(this).apply {+ divider = null+ adapter = RecentsAdapter()+ layoutParams = LinearLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT, 0, 1f)+ setOnItemClickListener { _, _, i, _ -> open(entries[i].uri) }+ setOnItemLongClickListener { _, _, i, _ ->+ val e = entries[i]+ AlertDialog.Builder(this@DocumentsActivity)+ .setTitle(e.name)+ // "Remove" is emphatically not "delete". The app hands back+ // its key; the document stays exactly where it is.+ .setMessage(getString(R.string.forget_explain))+ .setPositiveButton(R.string.forget) { _, _ ->+ Recents.forget(this@DocumentsActivity, e.uri); refresh()+ }+ .setNegativeButton(android.R.string.cancel, null)+ .show()+ true+ }+ }+ root.addView(list)+ return root+ }++ private inner class RecentsAdapter : BaseAdapter() {+ override fun getCount() = entries.size+ override fun getItem(i: Int) = entries[i]+ override fun getItemId(i: Int) = i.toLong()++ override fun getView(i: Int, convert: View?, parent: ViewGroup): View {+ val dp = { v: Int -> (v * resources.displayMetrics.density).toInt() }+ val row = (convert as? LinearLayout) ?: LinearLayout(this@DocumentsActivity).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(dp(14), dp(14), dp(14), dp(14))+ addView(TextView(context).apply {+ id = 1+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)+ setTextColor(Color.parseColor("#16273E"))+ })+ addView(TextView(context).apply {+ id = 2+ setTextSize(TypedValue.COMPLEX_UNIT_SP, 13f)+ setTextColor(Color.parseColor("#5E7699"))+ })+ }+ val e = entries[i]+ row.findViewById<TextView>(1).text = e.name+ row.findViewById<TextView>(2).text =+ DateUtils.getRelativeTimeSpanString(e.openedAt, System.currentTimeMillis(), 0)+ return row+ }+ }+}diff --git a/tray/android/app/src/main/java/page/bento/tray/EditorActivity.kt b/tray/android/app/src/main/java/page/bento/tray/EditorActivity.ktnew file mode 100644index 00000000..6ddf36a0--- /dev/null+++ b/tray/android/app/src/main/java/page/bento/tray/EditorActivity.kt@@ -0,0 +1,637 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++package page.bento.tray++import android.app.Activity+import android.app.AlertDialog+import android.content.Intent+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Build+import android.os.Bundle+import android.os.Process+import android.provider.OpenableColumns+import android.util.Log+import android.view.View+import android.view.ViewGroup+import android.view.WindowInsets+import android.widget.FrameLayout+import android.window.OnBackInvokedDispatcher+import android.webkit.WebResourceRequest+import android.webkit.WebResourceResponse+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.webkit.JavaScriptReplyProxy+import androidx.webkit.WebViewCompat+import androidx.webkit.WebViewFeature+import org.json.JSONObject+import java.io.ByteArrayInputStream+import java.security.MessageDigest++/**+ * Hosts one open document in a WebView and bridges saving to the Storage Access+ * Framework.+ *+ * This is the Android counterpart of `tray/ios/EditorViewController.swift`, and+ * it keeps that file's two load-bearing decisions:+ *+ * 1. The document is served through an ORIGIN WE CONTROL, never `file://`. A+ * `file://` page gets an opaque origin, which makes `localStorage` and+ * IndexedDB unreliable — that would silently break the autosave backstop, the+ * per-device collab member key, and the language and reduce-motion+ * preferences. Here the origin is a real `https://` one that never leaves the+ * device: every request to it is answered from memory by+ * [shouldInterceptRequest], and the host ends in `.invalid`, which RFC 6761+ * guarantees will never resolve — so the failure mode of a missed intercept+ * is a dead load, never a silent request to somebody's server.+ *+ * The host is PER DOCUMENT, derived from the document's own URI. This app+ * opens ANY self-contained HTML document, so a shared origin would let one+ * document read another's `localStorage` and IndexedDB — fine when every file+ * is yours, a real leak between unrelated third-party apps. Derived rather+ * than random because the origin IS the storage boundary: a fresh host per+ * launch would wipe that storage on every open.+ *+ * 2. The web content is the DOCUMENT'S OWN runtime. The app bundles no shell for+ * rendering and has no opinion about which version a document carries, so a+ * deck self-updates through Bento's normal signed channel and Android users+ * get the same release as everyone else on the same day. What the app ships+ * is file access.+ */+class EditorActivity : Activity() {++ companion object {+ const val EXTRA_URI = "page.bento.tray.URI"+ private const val TAG = "BentoTray"+ private const val REQ_EXPORT = 1++ /** Reduce a page-supplied filename to ONE plain component, or refuse it.+ *+ * The name arrives from the document, and this host treats documents as+ * mutually untrusted (that is why the origin is per-document). It ends up+ * as `EXTRA_TITLE` on a create-document intent, where a path separator is+ * at best meaningless and at worst a provider's problem. Refused rather+ * than repaired: a legitimate export name is already a single filename. */+ fun safeFileName(raw: String?): String? {+ if (raw.isNullOrEmpty()) return null+ val name = raw.substringAfterLast('/').substringAfterLast('\\')+ if (name.isEmpty() || name.startsWith(".")) return null+ return name+ }+ }++ private lateinit var web: WebView+ private var docUri: Uri? = null+ private var docName: String = "document.bento.html"+ private var bytes: ByteArray = ByteArray(0)++ /**+ * Can saves land on the open document, or must every one become a Save-As?+ *+ * This has no iOS counterpart, and it is the sharpest difference between the+ * two platforms. A document opened through the app's own picker+ * (ACTION_OPEN_DOCUMENT) carries a persistable read+write grant. A document+ * arriving by ACTION_VIEW — tapped in a file manager, opened from Drive or+ * Gmail — usually carries READ ONLY, because that is all the sender chose to+ * grant, and no API lets the receiver ask for more.+ *+ * So this is checked rather than assumed, and when it is false the first save+ * prompts instead of writing. Silently failing a save is the worst outcome+ * available; prompting costs a dialog. `tray/README.md` states the rule for+ * the whole project: when in doubt, prompt.+ */+ private var canWriteInPlace = false++ /**+ * Has the open document been handed to the web app yet? Bento only reaches a+ * picker when it holds no handle — afterwards ⌘S, autosave write-back and+ * in-place update all reuse it. So the FIRST request targets this document+ * and needs no UI; any later one is a genuine Save-As or export and must not+ * overwrite it. Deciding that from the suggested name instead would fail:+ * Bento derives it from the deck TITLE, so it rarely matches, and every save+ * would wrongly prompt.+ */+ private var openDocumentVended = false++ private var replyProxy: JavaScriptReplyProxy? = null++ /** An export whose bytes are held while the user chooses where it goes. */+ private class PendingExport(val id: Int, val text: String)+ private var pendingExport: PendingExport? = null++ /** Stable per-document host: a truncated SHA-256 of the document's URI.+ * Hex only, so it is always a valid host component. */+ private val originHost: String by lazy {+ val digest = MessageDigest.getInstance("SHA-256")+ .digest((docUri?.toString() ?: "unsaved").toByteArray())+ digest.joinToString("") { "%02x".format(it) }.take(24) + ".bento-tray.invalid"+ }++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)++ val uri = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)+ intent.getParcelableExtra(EXTRA_URI, Uri::class.java)+ else+ @Suppress("DEPRECATION") intent.getParcelableExtra<Uri>(EXTRA_URI)) ?: intent.data+ if (uri == null) { finish(); return }+ docUri = uri++ // An ACTION_VIEW sender grants for the life of this task only, so take+ // what durability is on offer before anything else can drop it.+ if (intent.action == Intent.ACTION_VIEW) {+ Recents.persist(contentResolver, uri, intent.flags)+ }+ canWriteInPlace = checkUriPermission(+ uri, Process.myPid(), Process.myUid(), Intent.FLAG_GRANT_WRITE_URI_PERMISSION+ ) == PackageManager.PERMISSION_GRANTED++ docName = displayName(uri) ?: "document.bento.html"++ // Read off the main thread: a document is the whole app, and decks run+ // to megabytes.+ Thread {+ val data = try {+ contentResolver.openInputStream(uri)?.use { it.readBytes() }+ } catch (e: Exception) {+ Log.w(TAG, "open failed", e); null+ }+ runOnUiThread {+ if (isFinishing || isDestroyed) return@runOnUiThread+ if (data == null) {+ fatal(getString(R.string.err_open))+ } else {+ bytes = data+ Recents.touch(this, uri, docName)+ startWebView()+ }+ }+ }.start()+ }++ private fun startWebView() {+ web = WebView(this)++ // The web view lives in a container whose PADDING carries the system+ // insets, rather than being inset itself: padding on a WebView insets its+ // scrollbars and its own content box, which a document then has to+ // account for.+ //+ // Reserve exactly what the system says is unsafe at the top, and nothing+ // else — so a document's own toolbar is reachable but never gives up a+ // pixel it did not have to. Done NATIVELY rather than by asking the page+ // to pad itself, because `--tray-safe-*` only helps a page that has heard+ // of this host; a third-party HTML file has no way to know, and its top+ // controls would sit under the status bar unreachable.+ val frame = FrameLayout(this)+ frame.addView(web, FrameLayout.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))+ setContentView(frame, ViewGroup.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))++ frame.setOnApplyWindowInsetsListener { v, insets ->+ val top: Int; val left: Int; val right: Int; val bottom: Int+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {+ val bars = insets.getInsets(WindowInsets.Type.systemBars())+ top = bars.top; left = bars.left; right = bars.right; bottom = bars.bottom+ } else {+ @Suppress("DEPRECATION")+ run {+ top = insets.systemWindowInsetTop; left = insets.systemWindowInsetLeft+ right = insets.systemWindowInsetRight; bottom = insets.systemWindowInsetBottom+ }+ }+ v.setPadding(0, top, 0, 0)+ // Report top as 0: the container is already inset by it, and a page+ // that DOES read these would otherwise pad twice.+ publishSafeArea(0, right, bottom, left)+ insets+ }++ web.settings.apply {+ javaScriptEnabled = true+ domStorageEnabled = true+ mediaPlaybackRequiresUserGesture = false+ // The document is served from memory and is self-contained. Nothing+ // it holds should be reachable through the filesystem, and turning+ // these off costs it nothing.+ allowFileAccess = false+ allowContentAccess = false+ // Bento sets its own viewport; letting WebView second-guess it made+ // the deck render at desktop width and scale down.+ useWideViewPort = true+ loadWithOverviewMode = false+ }++ web.webViewClient = object : WebViewClient() {+ override fun shouldInterceptRequest(+ view: WebView, request: WebResourceRequest+ ): WebResourceResponse? {+ val u = request.url+ if (u.host != originHost) return null+ // ANY path under our origin serves the document, matching the+ // iOS scheme handler. A self-contained document has no+ // subresources by definition, and diverging here would mean a+ // file that works on one host and not the other.+ return WebResourceResponse(+ "text/html", "utf-8", 200, "OK",+ mapOf("Content-Length" to bytes.size.toString()),+ ByteArrayInputStream(bytes)+ )+ }++ override fun shouldOverrideUrlLoading(+ view: WebView, request: WebResourceRequest+ ): Boolean {+ // The document may not navigate away from itself. A link to the+ // web opens in the browser, where it belongs; anything else on+ // our own origin is served above.+ val u = request.url+ if (u.host == originHost) return false+ if (u.scheme == "http" || u.scheme == "https" || u.scheme == "mailto") {+ try { startActivity(Intent(Intent.ACTION_VIEW, u)) } catch (_: Exception) {}+ }+ return true+ }+ }++ installBridge()++ // `<a download>` and blob: saves — the older, commoner idiom that is not+ // File System Access at all (TiddlyWiki, and most "export this page"+ // tools). WebView drops these silently without a listener, so the button+ // appears to do nothing, which is the worst possible failure for a save.+ web.setDownloadListener { url, _, contentDisposition, _, _ ->+ startDownload(url, contentDisposition)+ }++ registerBackHandling()+ web.loadUrl("https://$originHost/index.html")+ }++ /**+ * Inject the polyfill and open the reply channel.+ *+ * Both halves are androidx.webkit APIs rather than the framework's own, and+ * both choices are deliberate:+ *+ * - `addDocumentStartJavaScript` is the exact equivalent of WebKit's+ * `WKUserScript(.atDocumentStart)`. Bento decides whether it can save+ * DURING BOOT, so a script injected from `onPageStarted` or+ * `onPageFinished` has already lost the race some of the time — and the+ * symptom is not a crash, it is an editor that quietly believes it cannot+ * save.+ * - `addWebMessageListener` is ORIGIN-SCOPED. `addJavascriptInterface` — the+ * dependency-free alternative, and what most WebView wrappers reach for —+ * is injected into EVERY frame, so a remote iframe inside an untrusted+ * document would be handed a channel that overwrites the user's file.+ */+ private fun installBridge() {+ val rules = setOf("https://$originHost")++ if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER) ||+ !WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {+ // Both shipped in WebView 83 (2020) and it updates through Play, so+ // this is close to unreachable — but "close to" is not "never", and+ // the honest failure is to say the app cannot save rather than to+ // open a document that silently will not.+ fatal(getString(R.string.err_webview_old))+ return+ }++ WebViewCompat.addWebMessageListener(web, "__bentoTrayNative", rules) { _, message, _, isMainFrame, proxy ->+ if (!isMainFrame) return@addWebMessageListener+ replyProxy = proxy+ message.data?.let { onBridgeMessage(it) }+ }++ val src = assets.open("bridge.js").use { it.readBytes().toString(Charsets.UTF_8) }+ WebViewCompat.addDocumentStartJavaScript(web, src, rules)+ }++ /**+ * Hand the real insets to the page as CSS custom properties.+ *+ * The same `--tray-safe-*` contract the iOS host publishes, for the same+ * reason: a document that knows about this host can keep its own chrome clear+ * of the status bar and the gesture pill, and one that has never heard of it+ * is unaffected — the variables simply go unread.+ *+ * Density matters here. `WindowInsets` are in physical pixels and CSS is in+ * device-independent ones, so the raw numbers would be roughly three times+ * too large on a modern phone — a page reading them would push its toolbar+ * most of the way down the screen.+ */+ private fun publishSafeArea(top: Int, right: Int, bottom: Int, left: Int) {+ if (!this::web.isInitialized) return+ val d = resources.displayMetrics.density+ val css = { px: Int -> (px / d).toInt() }+ val js = "(function(){var r=document.documentElement.style;" ++ "r.setProperty('--tray-safe-top','${css(top)}px');" ++ "r.setProperty('--tray-safe-right','${css(right)}px');" ++ "r.setProperty('--tray-safe-bottom','${css(bottom)}px');" ++ "r.setProperty('--tray-safe-left','${css(left)}px');})();"+ web.evaluateJavascript(js, null)+ }++ // MARK: - the save bridge++ private fun onBridgeMessage(raw: String) {+ val m = try { JSONObject(raw) } catch (e: Exception) {+ Log.w(TAG, "unparseable bridge message", e); return+ }+ val id = m.optInt("id", -1)+ when (m.optString("op")) {+ "begin" -> {+ if (!openDocumentVended && canWriteInPlace) {+ openDocumentVended = true+ reply(id, true, docName)+ } else {+ // Either a copy/template/read-only export, or a document we+ // hold no write grant on. Both must end at a picker, and+ // neither may land on the open file.+ //+ // Normalised HERE as well as at the write, because this name+ // is handed back to the page and comes straight back as the+ // write target: sanitising only one end would leave the two+ // disagreeing about what file the handle refers to.+ reply(id, true, exportName(m.optString("suggestedName")))+ }+ }++ "read" -> {+ // getFile() and createWritable({keepExistingData}) need the bytes+ // currently on disk. Only the OPEN document is readable — an+ // export target is somewhere we were handed once and do not hold.+ if (targetsOpenDocument(m.optString("name"))) {+ reply(id, true, bytes.toString(Charsets.UTF_8))+ } else {+ reply(id, true, null)+ }+ }++ "write" -> {+ val text = m.optString("text")+ if (targetsOpenDocument(m.optString("name"))) {+ writeInPlace(id, text)+ } else {+ beginExport(id, m.optString("name"), text)+ }+ }++ "download" -> {+ // The readback half of the `<a download>` path — see+ // startDownload(). No reply: nothing is waiting on it.+ pendingExport = PendingExport(-1, m.optString("text"))+ launchCreateDocument(safeFileName(m.optString("name")) ?: "download.html")+ }++ else -> reply(id, false, "unknown op")+ }+ }++ /**+ * The name to vend for an export handle: sanitised, and never the open+ * document's.+ *+ * The vended name IS the handle as far as this bridge is concerned — read and+ * write carry nothing else to tell two handles apart — so an export vended+ * under the open document's filename would BE the open document's handle, and+ * its close() would overwrite the original in place. That is not exotic:+ * Bento suggests an export name derived from the deck TITLE, so a deck saved+ * under its own title makes "Duplicate as new deck…" suggest exactly the open+ * file's name.+ *+ * Prefixed rather than numbered, because ".bento.html" is a DOUBLE extension+ * that splitting on the last dot cuts down the middle ("Notes.bento 2.html").+ */+ private fun exportName(suggested: String?): String {+ val name = safeFileName(suggested) ?: "deck.bento.html"+ return if (name == docName) "copy of $name" else name+ }++ /**+ * Does a read/write from the page address the OPEN document, or an export?+ *+ * Both halves are load-bearing. Comparing names is only sound because+ * [exportName] guarantees no export handle is ever vended under this name;+ * requiring that the document was actually vended means a name the page+ * produced on its own — no handle for it ever handed out — cannot address the+ * file the user opened.+ */+ private fun targetsOpenDocument(name: String?) = openDocumentVended && name == docName++ private fun writeInPlace(id: Int, text: String) {+ val uri = docUri ?: return reply(id, false, "no document")+ val data = text.toByteArray()+ Thread {+ val err = try {+ // "wt" TRUNCATES. Plain "w" leaves any bytes past the new length+ // in place, so saving a document that got shorter would leave the+ // tail of the previous version glued to the end of the new one —+ // and for a Bento shell that tail contains a second, stale+ // #bento-doc block.+ contentResolver.openOutputStream(uri, "wt")?.use { it.write(data) }+ ?: "no output stream"+ null+ } catch (e: Exception) {+ Log.w(TAG, "write failed", e); e.message ?: "write failed"+ }+ runOnUiThread {+ if (err == null) bytes = data+ reply(id, err == null, err)+ }+ }.start()+ }++ private fun beginExport(id: Int, name: String?, text: String) {+ val safe = safeFileName(name) ?: return reply(id, false, "unsafe name")+ pendingExport = PendingExport(id, text)+ launchCreateDocument(safe)+ }++ private fun launchCreateDocument(name: String) {+ val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {+ addCategory(Intent.CATEGORY_OPENABLE)+ type = "text/html"+ putExtra(Intent.EXTRA_TITLE, name)+ }+ try {+ startActivityForResult(intent, REQ_EXPORT)+ } catch (e: Exception) {+ val p = pendingExport; pendingExport = null+ if (p != null && p.id >= 0) reply(p.id, false, "no picker available")+ }+ }++ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {+ if (requestCode != REQ_EXPORT) return super.onActivityResult(requestCode, resultCode, data)+ val p = pendingExport+ pendingExport = null+ val target = data?.data++ // A cancelled picker is a save that did not happen, and the page is told+ // so. Reporting success would leave Bento believing a copy exists.+ if (p == null) return+ if (resultCode != RESULT_OK || target == null) {+ if (p.id >= 0) reply(p.id, false, "cancelled")+ return+ }++ val payload = p.text.toByteArray()+ Thread {+ val err = try {+ contentResolver.openOutputStream(target, "wt")?.use { it.write(payload) }+ ?: "no output stream"+ null+ } catch (e: Exception) {+ Log.w(TAG, "export failed", e); e.message ?: "export failed"+ }+ runOnUiThread {+ if (p.id >= 0) reply(p.id, err == null, err)+ if (err != null) notify(getString(R.string.err_export))+ }+ }.start()+ }++ /**+ * Replies travel as JSON through the same origin-scoped channel.+ *+ * Worth noting against the iOS host, which replies by evaluating a JS call+ * and therefore has to encode the payload as a JavaScript string literal by+ * hand — a `read` reply carries the WHOLE document, and a raw newline in it+ * is a syntax error that hangs the page's promise forever. Here the payload+ * is data, not code, so that whole class of bug does not exist.+ */+ private fun reply(id: Int, ok: Boolean, value: String?) {+ if (id < 0) return+ val o = JSONObject().put("id", id).put("ok", ok)+ if (value != null) o.put("value", value) else o.put("value", JSONObject.NULL)+ try { replyProxy?.postMessage(o.toString()) } catch (e: Exception) {+ Log.w(TAG, "reply failed", e)+ }+ }++ // MARK: - downloads++ /**+ * `<a download>` and blob: saves.+ *+ * Unlike iOS, every download ends at a picker rather than in an app folder.+ * Android has no equivalent of "the app's Documents folder, visible in+ * Files" that a user would ever find — the app-private external directory is+ * effectively invisible — so a silent write would be a file the user cannot+ * locate. A document that saves OFTEN should be using the File System Access+ * path above, which prompts once and never again.+ *+ * A blob: URL cannot be fetched by native code at all: it exists only inside+ * the page's own origin. So the page is asked to read it back through the+ * bridge, which is the same trick every WebView-based browser uses.+ */+ private fun startDownload(url: String, contentDisposition: String?) {+ val name = safeFileName(fileNameFrom(contentDisposition)) ?: "download.html"+ if (url.startsWith("blob:") || url.startsWith("data:")) {+ val js = """+ (function(){+ fetch(${JSONObject.quote(url)})+ .then(function(r){ return r.blob() })+ .then(function(b){ return b.text() })+ .then(function(t){+ __bentoTrayNative.postMessage(JSON.stringify(+ { op: 'download', name: ${JSONObject.quote(name)}, text: t }))+ })+ .catch(function(){})+ })();+ """.trimIndent()+ web.evaluateJavascript(js, null)+ return+ }+ // An ordinary URL the page linked to. Let the browser have it: it has the+ // download UI, the notification and the resume logic already.+ try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } catch (_: Exception) {+ notify(getString(R.string.err_download))+ }+ }++ private fun fileNameFrom(contentDisposition: String?): String? {+ val cd = contentDisposition ?: return null+ val m = Regex("""filename\*?=(?:UTF-8'')?"?([^";]+)"?""", RegexOption.IGNORE_CASE).find(cd)+ return m?.groupValues?.get(1)?.let { Uri.decode(it) }+ }++ // MARK: - odds and ends++ private fun displayName(uri: Uri): String? = try {+ contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null)+ ?.use { if (it.moveToFirst()) it.getString(0) else null }+ } catch (e: Exception) {+ Log.w(TAG, "name lookup failed", e); null+ }++ override fun onResume() {+ super.onResume()+ // Said once, on the first resume, and only when it is true. A document+ // that cannot be saved back is still worth opening — reading and+ // presenting work — but the user has to know before they edit it.+ if (!canWriteInPlace && !warnedReadOnly) {+ warnedReadOnly = true+ notify(getString(R.string.notice_read_only))+ }+ }+ private var warnedReadOnly = false++ private fun notify(message: String) {+ AlertDialog.Builder(this)+ .setMessage(message)+ .setPositiveButton(android.R.string.ok, null)+ .show()+ }++ private fun fatal(message: String) {+ AlertDialog.Builder(this)+ .setMessage(message)+ .setCancelable(false)+ .setPositiveButton(android.R.string.ok) { _, _ -> finish() }+ .show()+ }++ override fun onDestroy() {+ // A WebView outlives its activity if anything still references it, and+ // it holds the whole document. Detach and destroy explicitly.+ if (this::web.isInitialized) {+ (web.parent as? ViewGroup)?.removeView(web)+ web.destroy()+ }+ super.onDestroy()+ }++ /**+ * The document owns the back gesture while it has history of its own —+ * present mode, a dialog, a state slide. Only when it has none does back mean+ * "leave the document".+ *+ * Registered TWO ways, and both are needed. The manifest opts this app into+ * the predictive back gesture (`enableOnBackInvokedCallback`), and that opt-in+ * stops `onBackPressed` from being called at all on Android 13+ — so an+ * override alone would compile, run, and silently do nothing on every current+ * device, dropping the user out of a document on the first back gesture.+ */+ private fun handleBack() {+ if (this::web.isInitialized && web.canGoBack()) web.goBack() else finish()+ }++ private fun registerBackHandling() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ onBackInvokedDispatcher.registerOnBackInvokedCallback(+ OnBackInvokedDispatcher.PRIORITY_DEFAULT+ ) { handleBack() }+ }+ }++ @Deprecated("Superseded by OnBackInvokedCallback above; still the path below API 33")+ override fun onBackPressed() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) return+ handleBack()+ }+}diff --git a/tray/android/app/src/main/java/page/bento/tray/Recents.kt b/tray/android/app/src/main/java/page/bento/tray/Recents.ktnew file mode 100644index 00000000..82a9e048--- /dev/null+++ b/tray/android/app/src/main/java/page/bento/tray/Recents.kt@@ -0,0 +1,117 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++package page.bento.tray++import android.content.ContentResolver+import android.content.Context+import android.content.Intent+import android.net.Uri+import org.json.JSONArray+import org.json.JSONObject++/**+ * The documents this app has been given durable access to.+ *+ * iOS gets a system document browser for free — `UIDocumentBrowserViewController`+ * shows the whole Files hierarchy and hands back security-scoped URLs. Android+ * has no hostable equivalent: the system picker is a one-shot dialog, not a+ * surface an app can live in. So the app keeps its own list, and each entry is+ * backed by a **persistable URI permission** — the Android analogue of a+ * security-scoped bookmark, and the thing that makes reopening a document+ * tomorrow work without asking again.+ *+ * The list is a CACHE OF GRANTS, never a store of documents. Nothing here is+ * authoritative: the grant lives in the system, the bytes live wherever the user+ * put them, and [prune] drops any entry whose grant the system no longer holds.+ */+object Recents {+ private const val PREFS = "recents"+ private const val KEY = "documents"+ private const val LIMIT = 40++ data class Entry(val uri: Uri, val name: String, val openedAt: Long)++ private fun prefs(c: Context) = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++ fun list(c: Context): List<Entry> {+ val raw = prefs(c).getString(KEY, null) ?: return emptyList()+ val out = ArrayList<Entry>()+ try {+ val arr = JSONArray(raw)+ for (i in 0 until arr.length()) {+ val o = arr.getJSONObject(i)+ out += Entry(Uri.parse(o.getString("uri")), o.getString("name"), o.optLong("at"))+ }+ } catch (_: Exception) {+ return emptyList()+ }+ return out.sortedByDescending { it.openedAt }+ }++ /** Record a document as opened, moving an existing entry to the top. */+ fun touch(c: Context, uri: Uri, name: String) {+ val kept = list(c).filter { it.uri != uri }+ val next = (listOf(Entry(uri, name, System.currentTimeMillis())) + kept).take(LIMIT)+ save(c, next)+ }++ fun forget(c: Context, uri: Uri) {+ save(c, list(c).filter { it.uri != uri })+ // Hand the grant back. Keeping it would spend one of the system's+ // per-app persisted-permission slots on a document the user has said+ // they are done with.+ try {+ c.contentResolver.releasePersistableUriPermission(+ uri,+ Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION+ )+ } catch (_: SecurityException) {+ // Already gone — the grant is the system's to hold, not ours.+ }+ }++ /**+ * Drop entries whose grant no longer exists.+ *+ * Grants die for ordinary reasons — the user cleared app storage, revoked+ * access, deleted the file, or the provider was uninstalled — and a dead+ * entry that still looks alive is worse than no entry: it opens to an error+ * instead of a document.+ */+ fun prune(c: Context): List<Entry> {+ val held = c.contentResolver.persistedUriPermissions.map { it.uri }.toHashSet()+ val alive = list(c).filter { it.uri in held }+ if (alive.size != list(c).size) save(c, alive)+ return alive+ }++ /**+ * Take a durable grant on a URI the user has just picked.+ *+ * Returns whether WRITE survived. Read is assumed — an incoming URI we+ * cannot read is not a document — but write is the interesting half, since+ * it decides whether this document can be saved in place at all.+ */+ fun persist(resolver: ContentResolver, uri: Uri, flags: Int): Boolean {+ val wanted = flags and+ (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)+ return try {+ resolver.takePersistableUriPermission(uri, wanted)+ wanted and Intent.FLAG_GRANT_WRITE_URI_PERMISSION != 0+ } catch (_: SecurityException) {+ // Not every provider offers persistable grants, and an ACTION_VIEW+ // sender usually does not flag them persistable at all. The document+ // still opens for this session; it just will not be in recents.+ false+ }+ }++ private fun save(c: Context, entries: List<Entry>) {+ val arr = JSONArray()+ entries.forEach {+ arr.put(JSONObject().put("uri", it.uri.toString()).put("name", it.name).put("at", it.openedAt))+ }+ prefs(c).edit().putString(KEY, arr.toString()).apply()+ }+}diff --git a/tray/android/app/src/main/res/drawable/ic_launcher_foreground.xml b/tray/android/app/src/main/res/drawable/ic_launcher_foreground.xmlnew file mode 100644index 00000000..63aa5a3a--- /dev/null+++ b/tray/android/app/src/main/res/drawable/ic_launcher_foreground.xml@@ -0,0 +1,37 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ The bento/tray mark, from tray/assets/tray-icon.svg.++ The navy frame is the BACKGROUND layer and the cream tray is the foreground.+ That split is what an adaptive icon wants — the system parallaxes the two+ layers against each other, and a frame drawn into the foreground would slide+ away from its own edge.++ The tray is 56 wide on the 108 canvas, not the full 72 safe zone. At 72 it+ exactly filled the visible area, so every launcher mask cut its corners off and+ the navy frame — the thing that makes the mark read as bento — was never drawn+ at all. At 56 the frame survives a circle mask, which is the tightest one in+ use, and the tray still sits inside the 66dp guaranteed-visible circle apart+ from its own rounded corners.++ Rounded rects are paths because Android vector drawables have no <rect>.+ Regenerate rather than editing the numbers — the snippet is in tray/README.md.+-->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp"+ android:height="108dp"+ android:viewportWidth="108"+ android:viewportHeight="108">+ <path+ android:fillColor="#F0EBE0"+ android:pathData="M37.39,26 H70.61 A11.39,11.39 0 0 1 82,37.39 V70.61 A11.39,11.39 0 0 1 70.61,82 H37.39 A11.39,11.39 0 0 1 26,70.61 V37.39 A11.39,11.39 0 0 1 37.39,26 Z" />+ <path+ android:fillColor="#5E7699"+ android:pathData="M37.13,32.17 H41.1 A4.96,4.96 0 0 1 46.06,37.13 V70.87 A4.96,4.96 0 0 1 41.1,75.83 H37.13 A4.96,4.96 0 0 1 32.17,70.87 V37.13 A4.96,4.96 0 0 1 37.13,32.17 Z" />+ <path+ android:fillColor="#FF9E8A"+ android:pathData="M54.99,32.17 H70.87 A4.96,4.96 0 0 1 75.83,37.13 V47.05 A4.96,4.96 0 0 1 70.87,52.02 H54.99 A4.96,4.96 0 0 1 50.03,47.05 V37.13 A4.96,4.96 0 0 1 54.99,32.17 Z" />+ <path+ android:fillColor="#16273E"+ android:pathData="M54.99,55.98 H70.87 A4.96,4.96 0 0 1 75.83,60.95 V70.87 A4.96,4.96 0 0 1 70.87,75.83 H54.99 A4.96,4.96 0 0 1 50.03,70.87 V60.95 A4.96,4.96 0 0 1 54.99,55.98 Z" />+</vector>diff --git a/tray/android/app/src/main/res/drawable/ic_launcher_monochrome.xml b/tray/android/app/src/main/res/drawable/ic_launcher_monochrome.xmlnew file mode 100644index 00000000..f2708d72--- /dev/null+++ b/tray/android/app/src/main/res/drawable/ic_launcher_monochrome.xml@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="utf-8"?>+<!--+ The themed-icon layer (Android 13+): one shape, tinted by the system to match+ the user's wallpaper.++ Colour cannot carry the mark here, so geometry has to. The three compartments+ become HOLES in the tray via evenOdd fill — the same rhythm as the full-colour+ icon (left tall, right split in two), legible as a silhouette.+-->+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="108dp"+ android:height="108dp"+ android:viewportWidth="108"+ android:viewportHeight="108">+ <path+ android:fillColor="#FFFFFF"+ android:fillType="evenOdd"+ android:pathData="M37.39,26 H70.61 A11.39,11.39 0 0 1 82,37.39 V70.61 A11.39,11.39 0 0 1 70.61,82 H37.39 A11.39,11.39 0 0 1 26,70.61 V37.39 A11.39,11.39 0 0 1 37.39,26 Z M37.13,32.17 H41.1 A4.96,4.96 0 0 1 46.06,37.13 V70.87 A4.96,4.96 0 0 1 41.1,75.83 H37.13 A4.96,4.96 0 0 1 32.17,70.87 V37.13 A4.96,4.96 0 0 1 37.13,32.17 Z M54.99,32.17 H70.87 A4.96,4.96 0 0 1 75.83,37.13 V47.05 A4.96,4.96 0 0 1 70.87,52.02 H54.99 A4.96,4.96 0 0 1 50.03,47.05 V37.13 A4.96,4.96 0 0 1 54.99,32.17 Z M54.99,55.98 H70.87 A4.96,4.96 0 0 1 75.83,60.95 V70.87 A4.96,4.96 0 0 1 70.87,75.83 H54.99 A4.96,4.96 0 0 1 50.03,70.87 V60.95 A4.96,4.96 0 0 1 54.99,55.98 Z" />+</vector>diff --git a/tray/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/tray/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xmlnew file mode 100644index 00000000..6f8d6179--- /dev/null+++ b/tray/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/tray_navy" />+ <foreground android:drawable="@drawable/ic_launcher_foreground" />+ <monochrome android:drawable="@drawable/ic_launcher_monochrome" />+</adaptive-icon>diff --git a/tray/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/tray/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xmlnew file mode 100644index 00000000..6f8d6179--- /dev/null+++ b/tray/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml@@ -0,0 +1,6 @@+<?xml version="1.0" encoding="utf-8"?>+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">+ <background android:drawable="@color/tray_navy" />+ <foreground android:drawable="@drawable/ic_launcher_foreground" />+ <monochrome android:drawable="@drawable/ic_launcher_monochrome" />+</adaptive-icon>diff --git a/tray/android/app/src/main/res/values/colors.xml b/tray/android/app/src/main/res/values/colors.xmlnew file mode 100644index 00000000..d1b4313a--- /dev/null+++ b/tray/android/app/src/main/res/values/colors.xml@@ -0,0 +1,8 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- The Bento palette, from tray/assets/tray-logo.svg. -->+<resources>+ <color name="tray_navy">#16273E</color>+ <color name="tray_cream">#F0EBE0</color>+ <color name="tray_steel">#5E7699</color>+ <color name="tray_peach">#FF9E8A</color>+</resources>diff --git a/tray/android/app/src/main/res/values/strings.xml b/tray/android/app/src/main/res/values/strings.xmlnew file mode 100644index 00000000..b569b9de--- /dev/null+++ b/tray/android/app/src/main/res/values/strings.xml@@ -0,0 +1,22 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <string name="app_name">Bento Tray</string>+ <string name="tagline">Documents that save themselves</string>+ <string name="open_with_label">Edit with Bento Tray</string>++ <string name="open_document">Open…</string>+ <string name="new_document">New</string>+ <string name="empty_hint">No documents yet.\n\nOpen a .bento.html file — or any self-contained HTML document — and it will save itself back to where it lives.</string>++ <string name="forget">Remove</string>+ <string name="forget_explain">Remove this from the list? The document itself is not deleted — this app just gives back its access to it.</string>++ <string name="err_open">That document could not be opened.</string>+ <string name="err_create">The new document could not be written.</string>+ <string name="err_export">That copy could not be saved.</string>+ <string name="err_download">That download could not be saved.</string>+ <string name="err_no_seed">This build has no starter document. Run “npm run build:single” in slides/ and rebuild the app.</string>+ <string name="err_webview_old">This device’s WebView is too old to save documents. Update Android System WebView from the Play Store.</string>++ <string name="notice_read_only">This document was opened read-only, so saves will ask where to put a copy. To edit it in place, open it from Bento Tray’s own “Open…” button instead.</string>+</resources>diff --git a/tray/android/app/src/main/res/values/themes.xml b/tray/android/app/src/main/res/values/themes.xmlnew file mode 100644index 00000000..da83d2dc--- /dev/null+++ b/tray/android/app/src/main/res/values/themes.xml@@ -0,0 +1,14 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <!-- The document owns the screen, so the app's own theme is only ever seen+ on the documents list. Light, because the editor a deck ships is light+ and a dark shell around it would flash on every open. -->+ <style name="Theme.Tray" parent="@android:style/Theme.Material.Light.NoActionBar">+ <item name="android:colorPrimary">@color/tray_navy</item>+ <item name="android:colorAccent">@color/tray_steel</item>+ <item name="android:statusBarColor">@color/tray_cream</item>+ <item name="android:windowLightStatusBar">true</item>+ <item name="android:navigationBarColor">@color/tray_cream</item>+ <item name="android:windowBackground">@color/tray_cream</item>+ </style>+</resources>diff --git a/native/android/build.gradle.kts b/tray/android/build.gradle.ktssimilarity index 55%rename from native/android/build.gradle.ktsrename to tray/android/build.gradle.ktsindex 71b0bfbf..a917d74d 100644--- a/native/android/build.gradle.kts+++ b/tray/android/build.gradle.kts@@ -1,4 +1,4 @@plugins {- id("com.android.application") version "8.11.1" apply false+ id("com.android.application") version "8.13.2" apply falseid("org.jetbrains.kotlin.android") version "2.1.21" apply false}diff --git a/native/android/gradle.properties b/tray/android/gradle.propertiessimilarity index 65%rename from native/android/gradle.propertiesrename to tray/android/gradle.propertiesindex 1a5e754b..411c0ef4 100644--- a/native/android/gradle.properties+++ b/tray/android/gradle.properties@@ -1,3 +1,6 @@org.gradle.jvmargs=-Xmx2gorg.gradle.configuration-cache=true+org.gradle.caching=true++android.useAndroidX=trueandroid.nonTransitiveRClass=truediff --git a/tray/android/gradle/wrapper/gradle-wrapper.jar b/tray/android/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 00000000..eddabd2eBinary files /dev/null and b/tray/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/native/android/gradle/wrapper/gradle-wrapper.properties b/tray/android/gradle/wrapper/gradle-wrapper.propertiessimilarity index 73%rename from native/android/gradle/wrapper/gradle-wrapper.propertiesrename to tray/android/gradle/wrapper/gradle-wrapper.propertiesindex c6f00302..fec70bd6 100644--- a/native/android/gradle/wrapper/gradle-wrapper.properties+++ b/tray/android/gradle/wrapper/gradle-wrapper.properties@@ -1,6 +1,9 @@distributionBase=GRADLE_USER_HOMEdistributionPath=wrapper/dists-distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip+distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zipnetworkTimeout=10000+retries=0+retryBackOffMs=500+validateDistributionUrl=truezipStoreBase=GRADLE_USER_HOMEzipStorePath=wrapper/distsdiff --git a/native/android/gradlew b/tray/android/gradlewsimilarity index 93%rename from native/android/gradlewrename to tray/android/gradlewindex d24fc200..249efbb0 100755--- a/native/android/gradlew+++ b/tray/android/gradlew@@ -1,7 +1,7 @@#!/bin/sh#-# Copyright © 2015-2021 the original authors.+# Copyright © 2015 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.@@ -20,7 +20,7 @@###############################################################################-# Gradle start up script for POSIX generated by Gradle.+# gradlew start up script for POSIX generated by Gradle.## Important for running:#@@ -29,7 +29,7 @@# bash, then to run this script, type that shell name before the whole# command line, like:#-# ksh Gradle+# ksh gradlew## Busybox and similar reduced shells will NOT work, because this script# requires all of these POSIX shell features:@@ -57,7 +57,7 @@# 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+# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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/.@@ -114,7 +114,6 @@ case "$( uname )" in #(NONSTOP* ) nonstop=true ;;esac-CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar# Determine the Java command to use to start the JVM.@@ -172,7 +171,6 @@ fi# For Cygwin or MSYS, switch paths to Windows format before running javaif "$cygwin" || "$msys" ; thenAPP_HOME=$( cygpath --path --mixed "$APP_HOME" )- CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )JAVACMD=$( cygpath --unix "$JAVACMD" )@@ -202,7 +200,7 @@ 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='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'+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,@@ -212,8 +210,7 @@ DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'set -- \"-Dorg.gradle.appname=$APP_BASE_NAME" \- -classpath "$CLASSPATH" \- org.gradle.wrapper.GradleWrapperMain \+ -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \"$@"# Stop when "xargs" is not available.diff --git a/tray/android/gradlew.bat b/tray/android/gradlew.batnew file mode 100644index 00000000..8508ef68--- /dev/null+++ b/tray/android/gradlew.bat@@ -0,0 +1,82 @@+@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 gradlew startup script for Windows+@rem+@rem ##########################################################################++@rem Set local scope for the variables, and ensure extensions are enabled+setlocal EnableExtensions++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++"%COMSPEC%" /c exit 1++: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++"%COMSPEC%" /c exit 1++:execute+@rem Setup the command line++++@rem Execute gradlew+@rem endlocal doesn't take effect until after the line is parsed and variables are expanded+@rem which allows us to clear the local environment before executing the java command+endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel++:exitWithErrorLevel+@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts+"%COMSPEC%" /c exit %ERRORLEVEL%diff --git a/tray/android/keystore.properties.example b/tray/android/keystore.properties.examplenew file mode 100644index 00000000..2f1ae06c--- /dev/null+++ b/tray/android/keystore.properties.example@@ -0,0 +1,17 @@+# Release signing for Play. Copy to keystore.properties (gitignored) and fill in.+#+# A keystore path and its passwords identify a publisher, so none of this is ever+# committed — the same rule as BENTO_TEAM_ID on iOS, which comes from the+# environment at project-generation time.+#+# Create a keystore with:+# keytool -genkeypair -v -keystore ~/.bento/bento-tray.jks \+# -alias bento-tray -keyalg RSA -keysize 4096 -validity 10000+#+# Keep it offline and backed up: Play identifies an app by its signing key, and+# losing it means never shipping an update to this listing again.++storeFile=/Users/you/.bento/bento-tray.jks+storePassword=+keyAlias=bento-tray+keyPassword=diff --git a/native/android/settings.gradle.kts b/tray/android/settings.gradle.ktssimilarity index 88%rename from native/android/settings.gradle.ktsrename to tray/android/settings.gradle.ktsindex ec06ebff..4ae1cd0b 100644--- a/native/android/settings.gradle.kts+++ b/tray/android/settings.gradle.kts@@ -13,5 +13,5 @@ dependencyResolutionManagement {}}-rootProject.name = "bento"+rootProject.name = "BentoTray"include(":app")diff --git a/tray/ios/Resources/bridge.js b/tray/bridge.jssimilarity index 68%rename from tray/ios/Resources/bridge.jsrename to tray/bridge.jsindex 93dc5502..b603fed5 100644--- a/tray/ios/Resources/bridge.js+++ b/tray/bridge.js@@ -1,10 +1,10 @@// SPDX-License-Identifier: MIT// Copyright (c) 2026 The Bento authors//-// The ENTIRE web-side surface of the iOS host: a polyfill of the one File-// System Access call Bento tests for. Injected at .atDocumentStart, because-// capability is read during boot — inject it later and the editor has already-// decided it cannot save.+// The ENTIRE web-side surface of a bento/tray native host: a polyfill of the+// one File System Access call Bento tests for. Injected at document start,+// because capability is read during boot — inject it later and the editor has+// already decided it cannot save.//// Bento needs exactly this much of the API (kernel/src/save.ts):// showSaveFilePicker({suggestedName}) -> { name, createWritable() }@@ -15,15 +15,42 @@// any past version: every in-place path (⌘S, autosave write-back, self-update)// already routes through this one function. A bespoke `window.__bentoHost`// bridge would only have helped decks re-saved after it shipped.+//+// ONE FILE, EVERY HOST. This used to live in tray/ios/Resources/ and iOS was+// the only caller. It is shared now because the interesting part of it is not+// the transport — it is the FileSystemWritableFileStream semantics below, whose+// comments record a bug that wrote users' documents out as zero bytes. A second+// host with its own copy is a second chance to reintroduce exactly that. The+// per-platform half is the ~15 lines of transport immediately below; everything+// after it is identical on every host, by construction.(function () {- const bridge = window.webkit && window.webkit.messageHandlers+ // ---------------------------------------------------------------- transport+ //+ // WebKit hands the page a message handler that takes a structured-cloneable+ // object and replies by evaluating JS in the frame.+ //+ // Android's WebMessageListener hands over a named JS object with+ // `postMessage(string)` and an `onmessage` event, so the payload is JSON in+ // both directions and the reply arrives as an event instead of an injected+ // call. It is used in preference to addJavascriptInterface precisely because+ // it is ORIGIN-SCOPED: an interface added the old way is injected into every+ // frame, so a remote iframe inside an untrusted document would have been+ // handed the user's file.+ const wk = window.webkit && window.webkit.messageHandlers&& window.webkit.messageHandlers.bentoFile- if (!bridge) return // plain browser: leave the real API (or its absence) alone+ const droid = window.__bentoTrayNative++ const send = wk ? (m) => wk.postMessage(m)+ : droid ? (m) => droid.postMessage(JSON.stringify(m))+ : null++ if (!send) return // plain browser: leave the real API (or its absence) alonelet seq = 0const pending = new Map()- // native calls back into this+ // native calls back into this — directly on WebKit, via the event below on+ // Android. Kept as a global on both so there is one reply path to reason about.window.__bentoNativeReply = (id, ok, value) => {const p = pending.get(id)if (!p) return@@ -31,12 +58,25 @@ok ? p.resolve(value) : p.reject(new Error(value || 'cancelled'))}+ if (droid) {+ droid.onmessage = (e) => {+ let r+ // A malformed reply must not take the listener down with it, or every+ // later save on this page hangs waiting for a callback that can no+ // longer arrive.+ try { r = JSON.parse(e.data) } catch (_) { return }+ window.__bentoNativeReply(r.id, r.ok, r.value)+ }+ }+const call = (op, payload) => new Promise((resolve, reject) => {const id = ++seqpending.set(id, { resolve, reject })- bridge.postMessage(Object.assign({ id, op }, payload))+ send(Object.assign({ id, op }, payload))})+ // ------------------------------------------------------- the polyfill proper+window.showSaveFilePicker = async (opts) => {const want = (opts && opts.suggestedName) || ''// Native decides what this call targets; the rule is DETERMINISTIC and livesdiff --git a/tray/ios/project.yml b/tray/ios/project.ymlindex b5beef2c..e1ffa627 100644--- a/tray/ios/project.yml+++ b/tray/ios/project.yml@@ -13,6 +13,12 @@ targets:sources:- path: .excludes: [project.yml]+ # The File System Access polyfill is SHARED with tray/android — one copy+ # of the semantics that once wrote documents out as zero bytes. It lands+ # flat in the bundle, so `Bundle.main.url(forResource: "bridge",+ # withExtension: "js")` finds it exactly as it did under Resources/.+ - path: ../bridge.js+ buildPhase: resourcespreBuildScripts:# The seed shell for "new document". Copied from the current build rather# than committed: a 587KB binary in git would churn on every release, and