Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home/ios: "Save a copy…" reports what the picker actually did (#600)
nyblnetaa3cd1b20440
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.mdindex f8868c76..ac91a880 100644--- a/docs/DECISIONS.md+++ b/docs/DECISIONS.md@@ -14,6 +14,29 @@ Decision. Why. Pointers.---+## 2026-10-04 — iOS: "Save a copy…" reports what the picker actually did++**Decision.** iOS follows the same rules as Android's 2026-10-04 entry on+saving from a read-only document (#595), so the two hosts give the same answer+to a page. A copy is remembered for the session by the name its handle was vended+under. Writes that arrive while its picker is open join that picker, and the+newest bytes win. A different name while a picker is open is refused out loud. A+cancel fails every write waiting on it. The rules live in Foundation-only+`home/ios/ExportSessions.swift`; `EditorViewController` presents the picker and+does the writing.++**Why.** `exportCopy` reported success the moment the picker *appeared*, and+set no delegate. So a cancelled "Save a copy…" told the page the copy was+saved. Nothing remembered where a copy went, either, so every later write to+that handle opened another picker — or, if one was already up, UIKit declined the+second presentation and never called back, and the page's save waited forever.+iOS never wrote a 0-byte file as Android did: it writes the temp copy before+asking.++**One iOS-specific detail.** The picker copies the temp file as it stood when+the picker opened. So when a write joins afterwards, the newer bytes are written+over the placed copy once the user has chosen, before any waiting write is+answered.## 2026-10-04 — A link that leaves a document opens outside it, on every host**Decision.** In a native host, a document never navigates away from itself.diff --git a/home/ios/EditorViewController.swift b/home/ios/EditorViewController.swiftindex 86507319..4551b1c0 100644--- a/home/ios/EditorViewController.swift+++ b/home/ios/EditorViewController.swift@@ -47,6 +47,13 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR/// fail: Bento derives it from the deck TITLE, so it rarely matches, and/// every save would wrongly prompt.private var openDocumentVended = false+ /// Where copies the page saved went, and the picker currently asking — see+ /// ExportSessions for the rules. Touched on the main thread only.+ private var exports = ExportSessions()+ /// Writes to a copy run here, one at a time and in order. A later save can+ /// address the copy before an earlier one has finished; two writes racing on+ /// one file is how a document gets interleaved.+ private let exportWrites = DispatchQueue(label: "page.bento.home.export-writes")private var isPresentingFullscreen = falseprivate var fullscreenObs: NSKeyValueObservation?@@ -494,6 +501,12 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKURlet want = (m["name"] as? String) ?? ""if targetsOpenDocument(want) {reply(id, ok: true, value: String(data: document.html, encoding: .utf8) ?? "")+ } else if let dest = exports.destination(for: want) {+ // A copy the user already placed is that handle's file now.+ exportWrites.async { [weak self] in+ let text = Self.readScoped(dest)+ DispatchQueue.main.async { self?.reply(id, ok: text != nil, value: text ?? "could not read the copy") }+ }} else {reply(id, ok: true, value: nil)}@@ -511,8 +524,21 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKURself?.reply(id, ok: ok, value: ok ? nil : "write failed")}} else {- exportCopy(named: name, text: text) { [weak self] ok, err in- self?.reply(id, ok: ok, value: err)+ switch exports.write(name: name, text: text, id: id) {+ case .present:+ // `done` only ever reports a failure to ASK — an unsafe name,+ // or no way to show the picker. Whether the copy was saved is+ // the picker delegate's to say, below.+ exportCopy(named: name, text: text) { [weak self] ok, err in+ guard let self, !ok else { return }+ for waiting in self.exports.cancelled() { self.reply(waiting, ok: false, value: err) }+ }+ case .joined:+ break // answered with the picker's result+ case .writeTo(let dest):+ writeCopy(text, to: dest) { [weak self] err in self?.reply(id, ok: err == nil, value: err) }+ case .refuse(let why):+ reply(id, ok: false, value: why)}}@@ -626,8 +652,36 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKURdone(false, "unsafe name"); return}do { try Data(text.utf8).write(to: tmp) } catch { done(false, "\(error)"); return }+ // UIKit refuses to present over something already presented, and then+ // never calls back — the page's save would wait forever. Say so instead.+ guard presentedViewController == nil else { done(false, "another dialog is open"); return }let picker = UIDocumentPickerViewController(forExporting: [tmp], asCopy: true)- present(picker, animated: true) { done(true, nil) }+ picker.delegate = self+ // Presenting the picker is not the save. It used to report success+ // here, so a cancelled "Save a copy…" told the page the copy was saved.+ present(picker, animated: true)+ }++ /// Write `text` over a copy the user placed earlier. Off the main thread,+ /// serialised, coordinated, and inside the security scope the picker gave.+ private func writeCopy(_ text: String, to dest: URL, then: @escaping (String?) -> Void) {+ exportWrites.async {+ let scoped = dest.startAccessingSecurityScopedResource()+ defer { if scoped { dest.stopAccessingSecurityScopedResource() } }+ var coordination: NSError?+ var failure: String?+ NSFileCoordinator().coordinate(writingItemAt: dest, options: .forReplacing, error: &coordination) { url in+ do { try Data(text.utf8).write(to: url, options: .atomic) } catch { failure = "\(error)" }+ }+ if let coordination { failure = failure ?? "\(coordination)" }+ DispatchQueue.main.async { then(failure) }+ }+ }++ private static func readScoped(_ url: URL) -> String? {+ let scoped = url.startAccessingSecurityScopedResource()+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }+ return (try? Data(contentsOf: url)).flatMap { String(data: $0, encoding: .utf8) }}}@@ -638,6 +692,27 @@ final class EditorViewController: UIViewController, WKScriptMessageHandler, WKUR/// only on a discrete tap, so a presenter swiping through a deck would never/// wake the exit control — the gesture that most needs to keep it alive is the/// one a tap recognizer cannot see. Observing touchesBegan catches every kind.+/// The answer to "Save a copy…": where the user put it, or that they didn't.+extension EditorViewController: UIDocumentPickerDelegate {+ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {+ guard let dest = urls.first else { documentPickerWasCancelled(controller); return }+ let (waiting, owed) = exports.picked(dest)+ guard let owed else {+ for id in waiting { reply(id, ok: true, value: nil) }+ return+ }+ // A write joined after the picker opened, so the copy it made is+ // already stale. Bring it up to the newest bytes before answering.+ writeCopy(owed, to: dest) { [weak self] err in+ for id in waiting { self?.reply(id, ok: err == nil, value: err) }+ }+ }++ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {+ for id in exports.cancelled() { reply(id, ok: false, value: "cancelled") }+ }+}+final class TouchWatcher: UIGestureRecognizer {private let onTouch: () -> Voiddiff --git a/home/ios/ExportSessions.swift b/home/ios/ExportSessions.swiftnew file mode 100644index 00000000..ea147174--- /dev/null+++ b/home/ios/ExportSessions.swift@@ -0,0 +1,78 @@+// SPDX-License-Identifier: MIT+// Copyright (c) 2026 The Bento authors++import Foundation++/// Where each write a page sends to an EXPORT handle goes — "Save a copy…",+/// a template, a read-only copy. The open document's own writes never come+/// through here; they go to the UIDocument in place.+///+/// The rules are home/android's (#595), so the two hosts answer the same way:+///+/// - **A copy is remembered for the session, by the name its handle was vended+/// under.** Once the user has chosen where it goes, later writes and reads on+/// that name go straight there. That is what the handle means on a desktop+/// browser: after Save-As, the copy is the document being edited. It is+/// recorded the moment the picker returns, so an autosave arriving in between+/// goes to the copy rather than to a second picker.+/// - **One picker per name.** Writes that arrive while it is open join it; the+/// newest bytes win, and every write gets the one result. A *different* name+/// while a picker is open is refused out loud, not queued behind a dialog that+/// is visibly for another file.+/// - **A cancel is a cancel.** Every write waiting on the picker is told it+/// failed. The copy is not remembered, so the next write asks again.+///+/// Foundation-only, so the whole state machine can be checked standalone with+/// `swiftc`. EditorViewController presents the picker and does the writing; it+/// decides none of this itself.+struct ExportSessions {+ enum Step: Equatable {+ /// No picker yet and nowhere remembered: write the temp copy and ask.+ case present(name: String)+ /// A picker for this very name is open; this write rides on it.+ case joined+ /// The user already chose where this copy goes; write it there.+ case writeTo(URL)+ /// Say no, with this reason.+ case refuse(String)+ }++ private(set) var remembered: [String: URL] = [:]+ private var pending: (name: String, ids: [Int], text: String, presented: String)?++ var isAsking: Bool { pending != nil }++ mutating func write(name: String, text: String, id: Int) -> Step {+ if let dest = remembered[name] { return .writeTo(dest) }+ if var p = pending {+ guard p.name == name else { return .refuse("another save is waiting for a location") }+ p.ids.append(id)+ p.text = text // newest bytes win+ pending = p+ return .joined+ }+ pending = (name, [id], text, text)+ return .present(name: name)+ }++ /// The user chose `dest`. Returns every write waiting on the picker, and the+ /// bytes still owed to `dest` if a later write replaced what the picker+ /// copied. The picker copies the temp file as it was when it opened, so a+ /// write that joined afterwards has to be written over the copy.+ mutating func picked(_ dest: URL) -> (ids: [Int], owed: String?) {+ guard let p = pending else { return ([], nil) }+ pending = nil+ remembered[p.name] = dest+ return (p.ids, p.text == p.presented ? nil : p.text)+ }++ /// The user cancelled, or the picker never appeared. Returns every write+ /// waiting on it, all of which failed.+ mutating func cancelled() -> [Int] {+ guard let p = pending else { return [] }+ pending = nil+ return p.ids+ }++ func destination(for name: String) -> URL? { remembered[name] }+}