Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home/android: a read-only document's Save-As no longer writes a zero-byte copy (#595)
nyblnet32b5a9557fec
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex 56ec0fa2..c0062774 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -7501,6 +7501,62 @@ rigs treat a drawn arrow as a deliberate difference: named in`test-maths-lite.ts`, counted with the identical ones in the coverage floor.Cost: +966 B of shell.+## 2026-10-04 — Android: a save from a read-only document remembers where it went, and one picker answers every write++The `ACTION_VIEW` route (a document handed over by Files, Drive or Gmail) was+written in #363 and first exercised on a device here. A writable grant — the+system Files app gives one — works end to end: open, edit, save in place, kill,+reopen. A **read-only** grant, the usual case from mail and most senders, lost+data, and in a way that looks like success.++**What was measured** (emulator, Android 16, a 1.2 MB slides deck). After an+edit, Bento's ⌘S and its autosave write-back (2.5s debounce) send two `write`s+for the same handle before the export picker returns. The host kept ONE pending+export: the second write overwrote it and launched a second picker on top of the+first. The first result to come back consumed the bytes; the second found nothing+pending and returned silently, leaving the file the picker had just created at+**0 bytes** — and the first write's promise was never answered. Separately,+nothing remembered where a copy had gone, so every later autosave to that handle+went back to a picker: one per edit.++**Decided:**++- **Exports are remembered for the session, by the name the handle was vended+ under.** A later write or read on that name goes straight to the copy. That is+ what the handle means on desktop: Save-As, then the copy is the document you+ are editing. The grant from `ACTION_CREATE_DOCUMENT` lasts as long as the+ activity, which is as long as the page's handle does. Recorded the moment the+ picker returns, not when the first write lands, so an autosave in between goes+ to the copy rather than to a new picker.+- **One picker per name.** Writes that arrive while it is open join it — newest+ bytes win, every id gets the one result. A *different* name while a picker is+ open is refused out loud ("another save is waiting for a location") rather than+ queued behind a dialog that is visibly for another file. A cancelled picker+ rejects every joined write.+- **All writes run on one thread, in order.** The copy can be addressed before+ its first write finishes; two threads truncating one file is how a document+ gets interleaved.+- **A null output stream is a failure.** The code read+ `openOutputStream(…)?.use { … } ?: "no output stream"` then `null`, which built+ the error and discarded it — a provider returning no stream was reported to the+ page as a save.++**Not changed, deliberately:** the intent filter stays `text/html`. Mail and+cloud senders often label attachments `application/octet-stream`, which would+keep bento/home out of the chooser; but content URIs have opaque paths, so+`pathPattern` cannot narrow by `.html`, and a bare octet-stream filter would+offer the app for every binary file — a store-review problem. How often real+senders do this is a hardware question, not one to guess at here.++**For the iOS host** (`exportCopy`): it could not write a 0-byte file — it+writes a temp copy first — but it reported success when the picker was+*presented*, so a cancelled export read as saved, and it had no export memory+either. Fixed in #600 under the same rules, so both hosts answer a page the same+way; verified there by reading and a standalone state-machine check, not yet on+a device. One iOS-specific difference is recorded in #600's entry: its picker+copies the temp file as it stood when the picker opened, so bytes from a write+that joined later must be written over the placed copy before anyone is+answered.## 2026-10-04 — PowerPoint import lives in convert/, beside the apps, and builds only on a verified, current shell**Where it lives.** The pptx importer moved from `kernel/src/convert/` to adiff --git a/home/android/app/src/main/java/page/bento/home/EditorActivity.kt b/home/android/app/src/main/java/page/bento/home/EditorActivity.ktindex 85d3fc02..4a5ba128 100644--- a/home/android/app/src/main/java/page/bento/home/EditorActivity.kt+++ b/home/android/app/src/main/java/page/bento/home/EditorActivity.kt@@ -34,6 +34,7 @@ import androidx.webkit.WebViewFeatureimport org.json.JSONObjectimport java.io.ByteArrayInputStreamimport java.security.MessageDigest+import java.util.concurrent.Executors/*** Hosts one open document in a WebView and bridges saving to the Storage Access@@ -123,10 +124,42 @@ class EditorActivity : Activity() {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)+ /**+ * An export whose bytes are held while the user chooses where it goes.+ *+ * ONE picker per name, however many writes arrive while it is open. Bento+ * autosaves 2.5s after an edit, so a ⌘S and an autosave routinely land+ * together; each used to launch its own picker and overwrite this slot, and+ * the second picker to return found nothing pending and left the file it had+ * just created at ZERO BYTES — while the first write's promise was never+ * answered. Now later writes join the open request: the newest bytes win,+ * and every id is answered with the one result. [name] is null for a+ * download, which nothing is waiting on.+ */+ private class PendingExport(val name: String?, var text: String, val ids: MutableList<Int>)private var pendingExport: PendingExport? = null+ /**+ * Where each exported copy went, by the name its handle was vended under.+ *+ * A save from a read-only document ends at a picker, and Bento then HOLDS a+ * handle to that copy — ⌘S and autosave write-back reuse it, exactly as they+ * would on desktop. Without this map every one of those writes asked for a+ * location again, so the user got a fresh picker after every edit. The grant+ * from ACTION_CREATE_DOCUMENT lasts as long as this activity, which is as+ * long as the page's handle does.+ */+ private val exportTargets = HashMap<String, Uri>()++ /**+ * Every write goes through this one thread, in arrival order. A copy is+ * recorded in [exportTargets] the moment its picker returns, so the next+ * autosave can be addressed to it before the first write has finished; two+ * threads both truncating and writing one file is how a document ends up+ * interleaved.+ */+ private val io = Executors.newSingleThreadExecutor()+/** 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 {@@ -490,27 +523,51 @@ class EditorActivity : Activity() {// 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)+ val name = m.optString("name")+ val copy = exportTargets[name]+ when {+ targetsOpenDocument(name) -> reply(id, true, bytes.toString(Charsets.UTF_8))+ // A copy saved earlier this session: what is on disk now.+ // Queued behind any write still in flight, so a read never+ // sees a half-written file.+ copy != null -> io.execute {+ val text = try {+ contentResolver.openInputStream(copy)?.use { it.readBytes() }+ ?.toString(Charsets.UTF_8)+ } catch (e: Exception) {+ Log.w(TAG, "copy read failed", e); null+ }+ runOnUiThread { reply(id, true, text) }+ }+ else -> reply(id, true, null)}}"write" -> {+ val name = m.optString("name")val text = m.optString("text")- if (targetsOpenDocument(m.optString("name"))) {- writeInPlace(id, text)- } else {- beginExport(id, m.optString("name"), text)+ val copy = exportTargets[name]+ when {+ targetsOpenDocument(name) -> writeInPlace(id, text)+ copy != null -> io.execute {+ val err = writeBytes(copy, text.toByteArray())+ runOnUiThread { reply(id, err == null, err) }+ }+ else -> beginExport(id, 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")+ if (pendingExport != null) {+ // A picker is already open. Saying so beats dropping the+ // bytes, or swapping them for the save the picker was for.+ notify(getString(R.string.err_download))+ } else {+ pendingExport = PendingExport(null, m.optString("text"), mutableListOf())+ launchCreateDocument(safeFileName(m.optString("name")) ?: "download.html")+ }}else -> reply(id, false, "unknown op")@@ -551,29 +608,52 @@ class EditorActivity : Activity() {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"- }+ io.execute {+ val err = writeBytes(uri, data)runOnUiThread {if (err == null) bytes = datareply(id, err == null, err)}- }.start()+ }}- private fun beginExport(id: Int, name: String?, text: String) {+ /**+ * Write a whole document to [uri]; null on success, else what went wrong.+ * Call on [io] only.+ *+ * "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.+ *+ * A null stream is a FAILURE. This used to read+ * `openOutputStream(…)?.use { … } ?: "no output stream"` followed by `null`,+ * which computed the error and then threw it away: a provider that handed+ * back no stream was reported to the page as a successful save.+ */+ private fun writeBytes(uri: Uri, data: ByteArray): String? = try {+ val out = contentResolver.openOutputStream(uri, "wt")+ if (out == null) "no output stream" else { out.use { it.write(data) }; null }+ } catch (e: Exception) {+ Log.w(TAG, "write failed", e); e.message ?: "write failed"+ }++ private fun beginExport(id: Int, name: String, text: String) {val safe = safeFileName(name) ?: return reply(id, false, "unsafe name")- pendingExport = PendingExport(id, text)+ val open = pendingExport+ if (open != null) {+ if (open.name == name) {+ open.text = text+ open.ids += id+ } else {+ // A different save while a picker is open. Refused out loud+ // rather than queued behind a dialog the user cannot see is for+ // a second file.+ reply(id, false, "another save is waiting for a location")+ }+ return+ }+ pendingExport = PendingExport(name, text, mutableListOf(id))launchCreateDocument(safe)}@@ -587,7 +667,7 @@ class EditorActivity : Activity() {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")+ p?.ids?.forEach { reply(it, false, "no picker available") }}}@@ -613,24 +693,24 @@ class EditorActivity : Activity() {// so. Reporting success would leave Bento believing a copy exists.if (p == null) returnif (resultCode != RESULT_OK || target == null) {- if (p.id >= 0) reply(p.id, false, "cancelled")+ p.ids.forEach { reply(it, false, "cancelled") }return}+ // Recorded NOW, not when the write lands: an autosave that arrives in+ // between must go to this copy, not open another picker. [io] keeps the+ // two writes in order.+ if (p.name != null) exportTargets[p.name] = target+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"- }+ io.execute {+ val err = writeBytes(target, payload)runOnUiThread {- if (p.id >= 0) reply(p.id, err == null, err)+ if (err != null && p.name != null) exportTargets.remove(p.name)+ p.ids.forEach { reply(it, err == null, err) }if (err != null) notify(getString(R.string.err_export))}- }.start()+ }}/**@@ -740,6 +820,9 @@ class EditorActivity : Activity() {// symptom.pendingFileChooser?.onReceiveValue(null)pendingFileChooser = null+ // Queued writes still run to completion; nothing new is accepted. A save+ // the user pressed just before leaving is a save that happens.+ io.shutdown()// A WebView outlives its activity if anything still references it, and// it holds the whole document. Detach and destroy explicitly.if (this::web.isInitialized) {