Cotton code
311 lines · 15.5 KB · SwiftRaw
// The share extension.//// There was no Cotton-authored one to port: a plugin generated the whole target// at build time, and what Cotton owned was the four activation rules (now// `project.yml:340-344`, verbatim) and the drain.// So this file is written to the rules rather than moved from anywhere, and// `ShareIntake` in `CottonKit` is the spec it has to satisfy; what the two// processes share is `CottonMailbox`, which carries no core.//// The class NAME is wire protocol — `project.yml` names it as the extension's// principal class and the iOS project spec test asserts it —// so a rename that misses one of the two is Cotton absent from the share sheet.//// ── What it does, and the three things it must not ───────────────────────────//// It reads the `NSExtensionItem`s, COPIES any file into the app group, appends// ONE mailbox entry, opens Cotton for whatever arrived, and closes. That is all of it.////   • **No FFI and no database.** The extension is a second process, and two//     writers on one SQLite WAL file is the race the whole store is built to//     avoid (design P9). It writes a `UserDefaults` entry the app drains.//   • **The sheet closes SILENTLY, and it opens Cotton on the way out.** There is still no view, no confirmation and no preview.//     What changed (2026-09-15) is the last step: the plugin's redirect out to//     the app was dropped with the previous runtime and the owner asked for it//     back — "it automatically should open the app and process it there and//     take me into the chat". The extension cannot import anything (it has no//     core and no database, design P9), so it stages, writes the entry and//     KNOCKS; the app drains, imports and lands in the chat. Since 23 Oct//     2026 every kind knocks, a picture and a link included (the owner: the//     app opens for every shared item the way it does for a chat export) —//     `ShareKnock` in `CottonMailbox/ShareKnock.swift` is that rule.//   • **The bytes are COPIED, before anything else.** That is the plugin's own//     rule and the reason it worked at all: the URL a provider hands over is//     valid for the length of one callback and is not readable from the app's//     process afterwards. The copy is `FileManager.copyItem` and never a read//     into memory — a shared video is a body with no ceiling, and a whole-body//     read is the jetsam kill with no exception that build 106 already paid for.//// The plugin's own channel does not come across: one overwritten slot cleared// when the app backgrounds, and a `<scheme>://dataUrl=<key>?nonce=<uuid>`// redirect that a native-intent hook rewrote back to `/`. Both retired with the// previous runtime; `ShareMailbox.swift` says why the append-only list replaces// the slot. **The redirect came back in a different shape**: the URL carries no// data at all now — `tinmen-cotton:///messages/import?share=<entry id>` — and// the bytes and the entry are already written before it is opened, so a knock// nobody answers costs nothing but a foreground.//// This target is an app EXTENSION and not a SwiftPM module, so there is no// `.module` bundle and no string catalogue — which costs nothing here, because// it draws no text.import CottonMailboximport CottonValuesimport ObjectiveCimport UIKitimport UniformTypeIdentifiersfinal class ShareViewController: UIViewController {    /// One file, copied, named and typed.    override func viewDidLoad() {        super.viewDidLoad()        // Nothing is drawn. The sheet is the system's and this is the whole of        // the app's contribution to it.        view.backgroundColor = .clear        let items = (extensionContext?.inputItems as? [NSExtensionItem]) ?? []        // `Task` inside a `@MainActor` method stays on the main actor, so the        // `NSExtensionItem`s never cross an isolation boundary; only Sendable        // values come back out of the providers' callbacks.        Task { [weak self] in            let written = await ShareItems.accept(items, stamp: CottonDate.format(Date()))            // THE KNOCK, and it is BEFORE `completeRequest`: the sheet's own            // context is what opens the URL, and a completed request has torn            // it down.            await self?.knock(written)            // ALWAYS, on every path. An extension that does not complete its            // request leaves the sheet on screen with nothing happening.            self?.extensionContext?.completeRequest(returningItems: nil)        }    }    /// Open Cotton for the first of these shares that has to be answered.    ///    /// The DECISION is `ShareOpener`'s and the two seams it needs are this    /// class's: the responder chain, and a read off the copy just staged. At    /// most one knock — two windows opening at once would be a second one    /// landing on the first, and one drain takes every entry anyway.    @MainActor    private func knock(_ written: [ShareEntry]) async {        let opener = ShareOpener(            open: { [weak self] url in await self?.openCotton(url) ?? false },            head: { path in DiskShareInboxFiles().head(path) },            shelf: ShareShelf.ofThisApp()        )        for entry in written {            if case .opened = await opener.arrived(entry) { break }        }    }    // MARK: - Opening Cotton    /// Ask the system to open Cotton, and say whether anything took the URL.    ///    /// **An app extension cannot say `UIApplication.shared`** — the symbol is    /// marked unavailable for extension targets, so this does not compile — and    /// there is no supported replacement that is one call. Two mechanisms are    /// tried, in this order, and the ORDER is the rule:    ///    ///   1. **`NSExtensionContext.open`**, which is the API an app extension is    ///      actually given. It answers `false` on the hosts that do not offer    ///      it rather than raising.    ///   2. **The responder chain**, walking `next` and collecting everything    ///      that answers `openURL:options:completionHandler:` — the    ///      NON-deprecated opener — then calling the one    ///      ``shareOpenerChoice(_:)`` picks, in the shape its CLASS takes.    ///    /// **Why the second one changed (the walk of 15 Sep 2026).** It used to    /// send the one-argument `openURL:` and return `true` without looking,    /// because a three-argument selector cannot go through `perform(_:with:)`.    /// On iOS 26 that call does nothing at all and says so in the extension's    /// system log — *"BUG IN CLIENT OF UIKIT: the caller of    /// UIApplication.openURL(_:) needs to migrate to the non-deprecated    /// UIApplication.open(_:options:completionHandler:). Force returning false    /// (NO)"* — so every share reported itself opened and nothing came    /// forward. Reaching the real opener means the `IMP` cast below; it is    /// guarded by `responds(to:)` and the signature is UIKit's published one,    /// and the alternative (fetching `UIApplication.shared` by `valueForKey:`)    /// is private-API use that fails review.    ///    /// **The completion is WAITED for, with a deadline.** The answer is the    /// whole point — a `false` means "did not open", and `completeRequest`    /// tears the context down, so answering before the block runs would be the    /// same lie in a new place. The deadline exists because a host that never    /// calls back would otherwise leave the share sheet on screen for ever.    ///    /// **One selector, TWO argument shapes — and that was the crash of 15 Sep    /// 2026.** The walk sent every answering responder `UIApplication`'s shape    /// (`NSDictionary` options). The first responder that answers on this host    /// is a `UIScene`, whose method takes a `UISceneOpenExternalURLOptions`    /// object, so UIKit sent `universalLinksOnly` to an empty dictionary and    /// the extension died: `NSInvalidArgumentException` —    /// *`-[__NSDictionary0 universalLinksOnly]: unrecognized selector`*. Every    /// share aborted and the sheet hung until it was tapped away. The chain is    /// now dispatched by the responder's CLASS (``ShareOpenerKind``), each call    /// is typed for the object it reaches, and a responder that is neither an    /// application nor a scene is skipped rather than guessed at.    ///    /// **A `false` from both is not an error.** The bytes are copied and the    /// mailbox entry is written, so the share lands on the next foreground —    /// exactly the behaviour this whole seam replaced, kept as the floor under    /// it rather than a share dropped because a host would not open a URL.    @MainActor    private func openCotton(_ url: URL) async -> Bool {        if let context = extensionContext {            let opened = await withCheckedContinuation {                (continuation: CheckedContinuation<Bool, Never>) in                context.open(url) { continuation.resume(returning: $0) }            }            if opened {                Log.write("share: opened by NSExtensionContext")                return true            }            Log.write("share: NSExtensionContext would not open — trying the responder chain")        }        let opened = await openThroughResponders(url)        Log.write("share: the responder chain answered \(opened)")        return opened    }    /// `openURL:options:completionHandler:` — the ObjC selector behind Swift's    /// `UIApplication.open(_:options:completionHandler:)`. Spelled out because    /// the Swift name and the selector differ, and sending the Swift-shaped    /// name would find nothing on the chain and read as "no host will open it".    private static let openSelector = NSSelectorFromString("openURL:options:completionHandler:")    /// How long a host is given to answer. Generous — the point is a ceiling,    /// not a stopwatch — and the floor under it is the mailbox.    private static let openDeadline = Duration.seconds(3)    @MainActor    private func openThroughResponders(_ url: URL) async -> Bool {        // The WHOLE chain first, then one choice — an application is preferred        // wherever it sits, so the walk cannot stop at the first answer.        var chain: [(responder: UIResponder, candidate: ShareOpenerCandidate)] = []        var responder: UIResponder? = self        while let current = responder {            let opensURLs = current.responds(to: ShareViewController.openSelector)            let kind =                opensURLs                ? shareOpenerKind(classAncestry: ShareViewController.classAncestry(of: current))                : nil            if opensURLs && kind == nil {                // It answers the selector and its third argument is unknown.                // An untyped call here is the crash this dispatch replaced.                Log.warn("share: \(type(of: current)) opens URLs in an unknown shape — skipped")            }            chain.append((current, ShareOpenerCandidate(opensURLs: opensURLs, kind: kind)))            responder = current.next        }        guard let index = shareOpenerChoice(chain.map(\.candidate)),            let kind = chain[index].candidate.kind        else {            Log.warn(                "share: nothing on the responder chain opens a URL — the chain was "                    + chain.map { String(describing: type(of: $0.responder)) }.joined(                        separator: ", "))            return false        }        let chosen = chain[index].responder        Log.write("share: opening through \(type(of: chosen)) as \(kind.optionsClassName)")        return await ShareViewController.send(url, to: chosen, as: kind)    }    /// The responder's class and every class above it, most specific first.    ///    /// The ancestry rather than `isKind(of:)` so the DECISION can live in    /// `CottonMailbox` with a test around it — this target is in no test bundle.    /// A runtime subclass still reads correctly: `NSKVONotifying_UIApplication`    /// has `UIApplication` above it.    private static func classAncestry(of responder: UIResponder) -> [String] {        var names: [String] = []        var current: AnyClass? = object_getClass(responder)        while let cls = current {            names.append(NSStringFromClass(cls))            current = class_getSuperclass(cls)        }        return names    }    /// The signature of `-[UIApplication openURL:options:completionHandler:]`,    /// as C sees it. `responds(to:)` has already said this object has that    /// selector; what this declares is what its bytes mean.    private typealias OpenURLApplicationIMP = @convention(c) (        AnyObject, Selector, NSURL, NSDictionary, @convention(block) (Bool) -> Void    ) -> Void    /// The signature of `-[UIScene openURL:options:completionHandler:]`. The    /// SAME selector and a different third argument — which is why the class    /// decides the call and not the selector.    private typealias OpenURLSceneIMP = @convention(c) (        AnyObject, Selector, NSURL, UIScene.OpenExternalURLOptions,        @convention(block) (Bool) -> Void    ) -> Void    @MainActor    private static func send(        _ url: URL, to responder: UIResponder, as kind: ShareOpenerKind    ) async -> Bool {        guard let method = responder.method(for: openSelector) else {            Log.warn("share: the responder answers the selector but has no method for it")            return false        }        let answer = OpenAnswer()        return await withCheckedContinuation { (continuation: CheckedContinuation<Bool, Never>) in            answer.hold(continuation)            // UIKit calls this block on the main queue.            let settle: @convention(block) (Bool) -> Void = { opened in answer.settle(opened) }            switch kind {            case .application:                let open = unsafeBitCast(method, to: OpenURLApplicationIMP.self)                open(responder, openSelector, url as NSURL, NSDictionary(), settle)            case .scene:                let open = unsafeBitCast(method, to: OpenURLSceneIMP.self)                open(                    responder, openSelector, url as NSURL,                    UIScene.OpenExternalURLOptions(), settle)            }            Task {                try? await Task.sleep(for: ShareViewController.openDeadline)                if answer.settle(false) {                    Log.warn("share: the opener never answered — the mailbox has it")                }            }        }    }    // MARK: - Reading one provider}/// A continuation two callers may reach — the completion block and the deadline/// — resumed exactly once.////// A lock rather than actor isolation: the block is UIKit's and carries no/// isolation of its own, and resuming a `CheckedContinuation` twice is a crash/// rather than a wrong answer.private final class OpenAnswer: @unchecked Sendable {    private let lock = NSLock()    private var continuation: CheckedContinuation<Bool, Never>?    private var settled = false    func hold(_ continuation: CheckedContinuation<Bool, Never>) {        lock.lock()        defer { lock.unlock() }        self.continuation = continuation    }    /// Answer, if nobody has. `true` when THIS call was the one that answered.    @discardableResult    func settle(_ opened: Bool) -> Bool {        lock.lock()        guard !settled, let continuation else {            lock.unlock()            return false        }        settled = true        self.continuation = nil        lock.unlock()        continuation.resume(returning: opened)        return true    }}