Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
Add native wrapper apps for iOS and Android (native/)
savrum3a41d272b45d
diff --git a/.gitignore b/.gitignoreindex d7194101..20351893 100644--- a/.gitignore+++ b/.gitignore@@ -26,3 +26,14 @@ working/# 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+*.xcuserdatad/+native/PR-BODY.mddiff --git a/native/README.md b/native/README.mdnew file mode 100644index 00000000..19347a47--- /dev/null+++ b/native/README.md@@ -0,0 +1,110 @@+# 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/Makefilenew file mode 100644index 00000000..84098da4--- /dev/null+++ b/native/android/Makefile@@ -0,0 +1,30 @@+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.ktsnew file mode 100644index 00000000..7bf6b5db--- /dev/null+++ b/native/android/app/build.gradle.kts@@ -0,0 +1,61 @@+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.pronew file mode 100644index 00000000..7396a207--- /dev/null+++ b/native/android/app/proguard-rules.pro@@ -0,0 +1,4 @@+# 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.xmlnew file mode 100644index 00000000..45ffb15f--- /dev/null+++ b/native/android/app/src/main/AndroidManifest.xml@@ -0,0 +1,22 @@+<?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.ktnew file mode 100644index 00000000..6bb441aa--- /dev/null+++ b/native/android/app/src/main/java/slides/bento/app/MainActivity.kt@@ -0,0 +1,215 @@+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.xmlnew file mode 100644index 00000000..403590b1--- /dev/null+++ b/native/android/app/src/main/res/drawable/ic_launcher_fg.xml@@ -0,0 +1,18 @@+<?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.xmlnew file mode 100644index 00000000..b791a0a5--- /dev/null+++ b/native/android/app/src/main/res/drawable/ic_launcher_mono.xml@@ -0,0 +1,17 @@+<?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.xmlnew file mode 100644index 00000000..b6a0d175--- /dev/null+++ b/native/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/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.xmlnew file mode 100644index 00000000..c609e2a0--- /dev/null+++ b/native/android/app/src/main/res/values/colors.xml@@ -0,0 +1,4 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+ <color name="ic_launcher_bg">#16273E</color>+</resources>diff --git a/native/android/build.gradle.kts b/native/android/build.gradle.ktsnew file mode 100644index 00000000..71b0bfbf--- /dev/null+++ b/native/android/build.gradle.kts@@ -0,0 +1,4 @@+plugins {+ id("com.android.application") version "8.11.1" apply false+ id("org.jetbrains.kotlin.android") version "2.1.21" apply false+}diff --git a/native/android/gradle.properties b/native/android/gradle.propertiesnew file mode 100644index 00000000..1a5e754b--- /dev/null+++ b/native/android/gradle.properties@@ -0,0 +1,3 @@+org.gradle.jvmargs=-Xmx2g+org.gradle.configuration-cache=true+android.nonTransitiveRClass=truediff --git a/native/android/gradle/wrapper/gradle-wrapper.jar b/native/android/gradle/wrapper/gradle-wrapper.jarnew file mode 100644index 00000000..9bbc975cBinary files /dev/null and b/native/android/gradle/wrapper/gradle-wrapper.jar differdiff --git a/native/android/gradle/wrapper/gradle-wrapper.properties b/native/android/gradle/wrapper/gradle-wrapper.propertiesnew file mode 100644index 00000000..c6f00302--- /dev/null+++ b/native/android/gradle/wrapper/gradle-wrapper.properties@@ -0,0 +1,6 @@+distributionBase=GRADLE_USER_HOME+distributionPath=wrapper/dists+distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip+networkTimeout=10000+zipStoreBase=GRADLE_USER_HOME+zipStorePath=wrapper/distsdiff --git a/native/android/gradlew b/native/android/gradlewnew file mode 100755index 00000000..d24fc200--- /dev/null+++ b/native/android/gradlew@@ -0,0 +1,251 @@+#!/bin/sh++#+# Copyright © 2015-2021 the original authors.+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# https://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#+# SPDX-License-Identifier: Apache-2.0+#++##############################################################################+#+# Gradle start up script for POSIX generated by Gradle.+#+# Important for running:+#+# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is+# noncompliant, but you have some other compliant shell such as ksh or+# bash, then to run this script, type that shell name before the whole+# command line, like:+#+# ksh Gradle+#+# Busybox and similar reduced shells will NOT work, because this script+# requires all of these POSIX shell features:+# * functions;+# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,+# «${var#prefix}», «${var%suffix}», and «$( cmd )»;+# * compound commands having a testable exit status, especially «case»;+# * various built-in commands including «command», «set», and «ulimit».+#+# Important for patching:+#+# (2) This script targets any POSIX shell, so it avoids extensions provided+# by Bash, Ksh, etc; in particular arrays are avoided.+#+# The "traditional" practice of packing multiple parameters into a+# space-separated string is a well documented source of bugs and security+# problems, so this is (mostly) avoided, by progressively accumulating+# options in "$@", and eventually passing that to Java.+#+# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,+# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;+# see the in-line comments for details.+#+# There are tweaks for specific operating systems such as AIX, CygWin,+# Darwin, MinGW, and NonStop.+#+# (3) This script is generated from the Groovy template+# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt+# within the Gradle project.+#+# You can find Gradle at https://github.com/gradle/gradle/.+#+##############################################################################++# Attempt to set APP_HOME++# Resolve links: $0 may be a link+app_path=$0++# Need this for daisy-chained symlinks.+while+ APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path+ [ -h "$app_path" ]+do+ ls=$( ls -ld "$app_path" )+ link=${ls#*' -> '}+ case $link in #(+ /*) app_path=$link ;; #(+ *) app_path=$APP_HOME$link ;;+ esac+done++# This is normally unused+# shellcheck disable=SC2034+APP_BASE_NAME=${0##*/}+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)+APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit++# Use the maximum available, or set MAX_FD != -1 to use that value.+MAX_FD=maximum++warn () {+ echo "$*"+} >&2++die () {+ echo+ echo "$*"+ echo+ exit 1+} >&2++# OS specific support (must be 'true' or 'false').+cygwin=false+msys=false+darwin=false+nonstop=false+case "$( uname )" in #(+ CYGWIN* ) cygwin=true ;; #(+ Darwin* ) darwin=true ;; #(+ MSYS* | MINGW* ) msys=true ;; #(+ NONSTOP* ) nonstop=true ;;+esac++CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar+++# Determine the Java command to use to start the JVM.+if [ -n "$JAVA_HOME" ] ; then+ if [ -x "$JAVA_HOME/jre/sh/java" ] ; then+ # IBM's JDK on AIX uses strange locations for the executables+ JAVACMD=$JAVA_HOME/jre/sh/java+ else+ JAVACMD=$JAVA_HOME/bin/java+ fi+ if [ ! -x "$JAVACMD" ] ; then+ die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+else+ JAVACMD=java+ if ! command -v java >/dev/null 2>&1+ then+ die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.++Please set the JAVA_HOME variable in your environment to match the+location of your Java installation."+ fi+fi++# Increase the maximum file descriptors if we can.+if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then+ case $MAX_FD in #(+ max*)+ # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ MAX_FD=$( ulimit -H -n ) ||+ warn "Could not query maximum file descriptor limit"+ esac+ case $MAX_FD in #(+ '' | soft) :;; #(+ *)+ # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.+ # shellcheck disable=SC2039,SC3045+ ulimit -n "$MAX_FD" ||+ warn "Could not set maximum file descriptor limit to $MAX_FD"+ esac+fi++# Collect all arguments for the java command, stacking in reverse order:+# * args from the command line+# * the main class name+# * -classpath+# * -D...appname settings+# * --module-path (only if needed)+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.++# For Cygwin or MSYS, switch paths to Windows format before running java+if "$cygwin" || "$msys" ; then+ APP_HOME=$( cygpath --path --mixed "$APP_HOME" )+ CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )++ JAVACMD=$( cygpath --unix "$JAVACMD" )++ # Now convert the arguments - kludge to limit ourselves to /bin/sh+ for arg do+ if+ case $arg in #(+ -*) false ;; # don't mess with options #(+ /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath+ [ -e "$t" ] ;; #(+ *) false ;;+ esac+ then+ arg=$( cygpath --path --ignore --mixed "$arg" )+ fi+ # Roll the args list around exactly as many times as the number of+ # args, so each arg winds up back in the position where it started, but+ # possibly modified.+ #+ # NB: a `for` loop captures its iteration list before it begins, so+ # changing the positional parameters here affects neither the number of+ # iterations, nor the values presented in `arg`.+ shift # remove old arg+ set -- "$@" "$arg" # push replacement arg+ done+fi+++# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.+DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"'++# Collect all arguments for the java command:+# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,+# and any embedded shellness will be escaped.+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be+# treated as '${Hostname}' itself on the command line.++set -- \+ "-Dorg.gradle.appname=$APP_BASE_NAME" \+ -classpath "$CLASSPATH" \+ org.gradle.wrapper.GradleWrapperMain \+ "$@"++# Stop when "xargs" is not available.+if ! command -v xargs >/dev/null 2>&1+then+ die "xargs is not available"+fi++# Use "xargs" to parse quoted args.+#+# With -n1 it outputs one arg per line, with the quotes and backslashes removed.+#+# In Bash we could simply go:+#+# readarray ARGS < <( xargs -n1 <<<"$var" ) &&+# set -- "${ARGS[@]}" "$@"+#+# but POSIX shell has neither arrays nor command substitution, so instead we+# post-process each arg (as a line of input to sed) to backslash-escape any+# character that might be a shell metacharacter, then use eval to reverse+# that process (while maintaining the separation between arguments), and wrap+# the whole thing up as a single "set" statement.+#+# This will of course break if any of these variables contains a newline or+# an unmatched quote.+#++eval "set -- $(+ printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |+ xargs -n1 |+ sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |+ tr '\n' ' '+ )" '"$@"'++exec "$JAVACMD" "$@"diff --git a/native/android/keystore.properties.example b/native/android/keystore.properties.examplenew file mode 100644index 00000000..54f1b513--- /dev/null+++ b/native/android/keystore.properties.example@@ -0,0 +1,8 @@+# 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.shnew file mode 100755index 00000000..3a599a79--- /dev/null+++ b/native/android/run.sh@@ -0,0 +1,35 @@+#!/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/android/settings.gradle.kts b/native/android/settings.gradle.ktsnew file mode 100644index 00000000..ec06ebff--- /dev/null+++ b/native/android/settings.gradle.kts@@ -0,0 +1,17 @@+pluginManagement {+ repositories {+ google()+ mavenCentral()+ gradlePluginPortal()+ }+}++dependencyResolutionManagement {+ repositories {+ google()+ mavenCentral()+ }+}++rootProject.name = "bento"+include(":app")diff --git a/native/ios/Bento.xcodeproj/project.pbxproj b/native/ios/Bento.xcodeproj/project.pbxprojnew file mode 100644index 00000000..1e3cb4ed--- /dev/null+++ b/native/ios/Bento.xcodeproj/project.pbxproj@@ -0,0 +1,243 @@+// !$*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.xcschemenew file mode 100644index 00000000..33ec0bd3--- /dev/null+++ b/native/ios/Bento.xcodeproj/xcshareddata/xcschemes/Bento.xcscheme@@ -0,0 +1,50 @@+<?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.swiftnew file mode 100644index 00000000..d7bdb6be--- /dev/null+++ b/native/ios/Bento/AppDelegate.swift@@ -0,0 +1,24 @@+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.jsonnew file mode 100644index 00000000..a690abe7--- /dev/null+++ b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,38 @@+{+ "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.pngnew file mode 100644index 00000000..441d8182Binary files /dev/null and b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-dark.png differdiff --git a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-tinted.png b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-tinted.pngnew file mode 100644index 00000000..ba0bfc2bBinary files /dev/null and b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon-tinted.png differdiff --git a/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon.png b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon.pngnew file mode 100644index 00000000..441d8182Binary files /dev/null and b/native/ios/Bento/Assets.xcassets/AppIcon.appiconset/icon.png differdiff --git a/native/ios/Bento/Assets.xcassets/Contents.json b/native/ios/Bento/Assets.xcassets/Contents.jsonnew file mode 100644index 00000000..73c00596--- /dev/null+++ b/native/ios/Bento/Assets.xcassets/Contents.json@@ -0,0 +1,6 @@+{+ "info" : {+ "author" : "xcode",+ "version" : 1+ }+}diff --git a/native/ios/Bento/Info.plist b/native/ios/Bento/Info.plistnew file mode 100644index 00000000..d58c6e74--- /dev/null+++ b/native/ios/Bento/Info.plist@@ -0,0 +1,56 @@+<?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.swiftnew file mode 100644index 00000000..9d82dac2--- /dev/null+++ b/native/ios/Bento/ViewController.swift@@ -0,0 +1,581 @@+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.plistnew file mode 100644index 00000000..652f67b3--- /dev/null+++ b/native/ios/ExportOptions.plist@@ -0,0 +1,10 @@+<?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/Makefilenew file mode 100644index 00000000..4185dff6--- /dev/null+++ b/native/ios/Makefile@@ -0,0 +1,35 @@+.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.shnew file mode 100755index 00000000..d055ca7c--- /dev/null+++ b/native/ios/run.sh@@ -0,0 +1,83 @@+#!/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.jsonnew file mode 100644index 00000000..8d5bd555--- /dev/null+++ b/native/package.json@@ -0,0 +1,14 @@+{+ "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.shnew file mode 100755index 00000000..5a327406--- /dev/null+++ b/native/scripts/fetch-deck.sh@@ -0,0 +1,34 @@+#!/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.pynew file mode 100644index 00000000..95e88b4d--- /dev/null+++ b/native/scripts/gen_icons.py@@ -0,0 +1,85 @@+#!/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))