Cotton code
385 lines · 18.5 KB · SwiftRaw
// The share EXTENSION's own rules, written where a test can reach them.//// `App/ShareExtension/ShareViewController.swift` is an app-extension target: it// is not a SwiftPM module, it is in no test bundle, and nothing executable can// hold a rule that lives inside it. So the decisions it makes that are rules// rather than plumbing live here, in the module it already links:////   1. **how a provider's FILE is loaded, and under which type identifier**//      (``shareFileSource(registered:suggestedName:)``),//   2. **whether staging that file should OPEN Cotton**, and at what URL//      (``ShareOpener``), and//   3. **which responder on the chain is asked to open it, and with which of//      the two argument shapes that one selector has**//      (``shareOpenerKind(classAncestry:)``, ``shareOpenerChoice(_:)``).//// What stays in the extension is the part only a `UIViewController` can do:// walking `UIResponder.next` and making the typed call the rule chose.//// ── Why the extension opens the app at all ───────────────────────────────────//// It did not, and the comment at the head of `ShareViewController` recorded// that as dropped with the previous runtime. The owner's ruling (15 Sep 2026)// is that a chat export shared out of WhatsApp must land IN the chat: "it// automatically should open the app and process it there and take me into the// chat". An extension cannot import a chat — it has no core and no database// (design P9) — so what it can do is stage the bytes, write the mailbox entry// and knock on the app's door. The app drains, imports and lands.//// **Which kinds knock is declared once, in `ShareKnock.swift`** — every kind// the drain files, since the owner's ruling of 23 Oct 2026. The reasoning is// there, beside the list.import Foundationimport UniformTypeIdentifiers// MARK: - How a provider's file is loaded/// Where a provider's FILE comes from, and under which registered identifier.////// **The two cases load by DIFFERENT calls, and that is the whole point of the/// type.** `loadFileRepresentation` answers a real file for a concrete type and/// a PROPERTY LIST holding a `file://` string for `public.file-url` — 261 bytes/// with no extension, which the drain then rejected as "no extension" while the/// real export sat in the sharing app's container untouched (the walk of 15 Sep/// 2026, and the reason this type exists). A URL type is asked for its URL and/// the file it points at is copied; nothing else is ever written into the/// inbox.public enum ShareFileSource: Equatable, Sendable {    /// The provider registered a URL type: ask it for the `NSURL` and copy the    /// file that URL names, extension and all.    case url(identifier: String)    /// A concrete type: `loadFileRepresentation` hands over a real file.    case representation(identifier: String)    /// The identifier to load under — the one the provider REGISTERED, never a    /// `UTType` round-tripped back to a string, which is not guaranteed to be    /// the same one.    public var identifier: String {        switch self {        case .url(let identifier), .representation(let identifier): return identifier        }    }}/// How to stage this provider's FILE, or `nil` when it is not carrying one.////// Three passes, in this order, and the order is the rule://////   1. **a concrete data type that is neither text nor a URL.** A share that///      says `audio/mp4` knows more about its own bytes than a file extension///      does, and `ShareIntake`'s classification believes a declared type — so///      the concrete one is preferred over `public.file-url`, which says///      nothing and would leave an audio-only mp4 in the picture grid.///   2. **a file URL.** The copy then keeps the real extension, which is what///      the four classification rules read when a share declares no type. This///      pass answers ``ShareFileSource/url(identifier:)``, because a file URL///      has to be READ AS A URL: see the type's own note.///   3. **a text type, but only for a FILE.** Every text type conforms to///      `public.data`, so pass 1 excludes them to keep a selected paragraph out///      of the file branch — and a `.txt` FILE that registered nothing else///      fell through to `nil` and was staged as a text share. A selection and a///      file are told apart by the one thing that differs: a provider made from///      a file carries a `suggestedName` with an extension on it, and a///      highlighted paragraph carries none.public func shareFileSource(registered: [String], suggestedName: String?) -> ShareFileSource? {    let declared: [(identifier: String, type: UTType)] = registered.compactMap { identifier in        guard let type = UTType(identifier) else { return nil }        return (identifier, type)    }    if let match = declared.first(where: {        $0.type.conforms(to: .data) && !$0.type.conforms(to: .text)            && !$0.type.conforms(to: .url)    }) {        return .representation(identifier: match.identifier)    }    if let match = declared.first(where: { $0.type.conforms(to: .fileURL) }) {        return .url(identifier: match.identifier)    }    guard let suggestedName, !shareFileExtension(suggestedName).isEmpty else { return nil }    return declared.first(where: { $0.type.conforms(to: .text) && $0.type.conforms(to: .data) })        .map { .representation(identifier: $0.identifier) }}/// What to call a shared file's type on the wire, given the UTI it was loaded/// under — the share extension's rule and Settings › Bring in's, said once.////// The preferred MIME type of that type, when it has one. When it has none the/// answer is one of three ABSTRACT UTIs or nothing at all — and the "nothing at/// all" is the load-bearing half: `public.file-url` and `public.data` say less/// than the copied file's own extension does, and declaring one of them would/// make the drain read a picture as a paper (`shareFileKind` believes a/// declared type over an extension, and neither of those two is on its/// undeclared list). The three that ARE worth declaring are exactly the three/// the drain's UTI sets name.public func shareDeclaredType(forType identifier: String) -> String? {    guard let type = UTType(identifier) else { return nil }    if let mime = type.preferredMIMEType { return mime }    if type.conforms(to: .movie) { return UTType.movie.identifier }    if type.conforms(to: .audio) { return UTType.audio.identifier }    if type.conforms(to: .image) { return UTType.image.identifier }    return nil}/// The name to record on a mailbox entry for a file that arrived under `name`.////// **The name is a HINT the import needs and a stranger's text at the same/// time.** `import.whatsappExport` reads the chat's title out of it (`WhatsApp/// Chat - <name>.zip` names the other party, so the owner is the sender who is/// NOT in it), and the screen shows it while the export is read — so dropping/// it costs a question the person should never have been asked. But it is/// written by whatever app did the sharing, so what is kept is the LAST path/// segment with no separators and no control characters, and never a path.////// `nil` when nothing usable is left, which is what an unnamed share is.public func shareSanitisedFileName(_ name: String?) -> String? {    guard let name else { return nil }    // `omittingEmptySubsequences: false`, so a name ENDING in a separator    // answers nothing rather than the directory above it — the same reading    // `whatsapp_import.rs::sanitise_file_name` makes of the value it receives,    // and two spellings of "the leaf" is how one of them drifts.    let leaf = name        .split(maxSplits: Int.max, omittingEmptySubsequences: false, whereSeparator: {            $0 == "/" || $0 == "\\"        })        .last        .map(String.init) ?? ""    let cleaned = leaf.unicodeScalars        .filter { !CharacterSet.controlCharacters.contains($0) }        .reduce(into: "") { $0.unicodeScalars.append($1) }        .trimmingCharacters(in: .whitespacesAndNewlines)    // `.` and `..` are path, not a name.    if cleaned.isEmpty || cleaned == "." || cleaned == ".." { return nil }    return cleaned}// MARK: - The copy/// Copy a shared file into the inbox, under a name nothing can collide with/// and **with the source's own extension kept**.////// Written here rather than inside the extension for the reason the whole file/// exists: the extension target is in no test bundle, and the extension is what/// the drain's four classification rules read when a share declares no type. A/// copy that lost it is a `.txt` the drain calls "no extension" and discards.////// A `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 build 106 already paid for./// It THROWS rather than answering `nil`, because the caller has exactly one/// honest thing to do with a failed copy and a silence would hide which half/// failed.public func stageSharedFile(    from source: URL,    into directory: URL,    id: String = UUID().uuidString) throws -> String {    let ext = source.pathExtension    let target = directory.appendingPathComponent(id + (ext.isEmpty ? "" : "." + ext))    try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)    try FileManager.default.copyItem(at: source, to: target)    return target.path}/// Files this app was handed — chosen in Settings › Bring in, or opened in it/// (a `.cottonpkg` AirDropped or tapped in Files) — staged into the app/// group's share inbox exactly as the share extension stages a share, one/// mailbox-shaped entry per file that could be copied. A file from Files is/// readable only inside its security scope, so each copy is made inside it.public func stageForIntake(    _ urls: [URL],    at stamp: String,    into inbox: URL? = ShareChannel.inboxDirectory()) -> [ShareEntry] {    guard let inbox else { return [] }    return urls.compactMap { url in        let scoped = url.startAccessingSecurityScopedResource()        defer { if scoped { url.stopAccessingSecurityScopedResource() } }        guard let path = try? stageSharedFile(from: url, into: inbox) else { return nil }        let type = UTType(filenameExtension: url.pathExtension)        return ShareEntry(            at: stamp,            kind: ShareKind.file.rawValue,            path: path,            fileName: shareSanitisedFileName(url.lastPathComponent),            mimeType: type.flatMap { shareDeclaredType(forType: $0.identifier) }        )    }}/// A file the system opened this app WITH — a `.cottonpkg` AirDropped to the/// phone or tapped in Files (Rigby declares the type, `project.yml`). Not a/// route and not the share extension's knock: a package to import.public enum PackageOpen {    /// Whether this opened URL is a Cotton package.    public static func isPackage(_ url: URL) -> Bool {        url.isFileURL && isPackageShare(SharedFile(path: url.path))    }}// MARK: - The knock/// The URL the extension opens Cotton at, and how the app recognises it.public enum ShareOpen {    /// The query item that says "this URL is the share extension's own knock".    ///    /// It carries the mailbox entry's id, which is a fact worth having in the    /// log — but the app never looks the entry up by it: **the MAILBOX is the    /// truth and the URL is only the knock.** Draining is what decides where    /// the app goes, so an id the drain has already taken is not an error.    public static let marker = "share"    /// Whether this URL is the share extension's knock rather than an ordinary    /// deep link into one of the screens a knock lands on (a notification's,    /// one typed by hand). Only a knock triggers a drain.    ///    /// `ShareKnock` owns it, because the set of routes a knock may carry is the    /// set of kinds that knock, and that list is declared once.    public static func isShareArrival(_ url: URL) -> Bool {        ShareKnock.isArrival(url)    }}/// What came of a staged share.public enum ShareOpenOutcome: Equatable, Sendable {    /// Cotton was asked to open at this URL.    case opened(URL)    /// Nothing to open: the drain takes this share on the next foreground, as    /// it always did.    case nothingToOpen    /// Nobody on the responder chain would open it. **The share is not lost** —    /// the mailbox entry stands and the next foreground drains it, which is    /// exactly the behaviour this whole seam replaced. Some hosts do not offer    /// an opener, and a share that quietly waits is better than one that is    /// dropped because the knock went unanswered.    case couldNotOpen(URL)}/// The extension's decision about a share it has just written down.////// Both seams are INJECTED and neither has a default: `open` is a responder/// chain only a `UIViewController` has, and `head` is a read off the app group/// only a staged file has. A test hands in two closures and drives the whole/// rule with no share sheet, no container and no simulator.////// `@MainActor` because the opener it is handed is one: opening a URL from an/// extension walks `UIResponder.next`, which is main-actor state.@MainActorpublic struct ShareOpener {    private let open: (URL) async -> Bool    private let head: (String) -> String?    private let shelf: ShareShelf    public init(        open: @escaping (URL) async -> Bool,        head: @escaping (String) -> String?,        shelf: ShareShelf    ) {        self.open = open        self.head = head        self.shelf = shelf    }    /// One entry has been appended to the mailbox. Open Cotton at the screen    /// its kind lands on, and say what happened.    ///    /// **Which kinds, and where, is `ShareKnock`'s** — one declaration, so    /// adding a kind is an entry in a list rather than an edit in here.    public func arrived(_ entry: ShareEntry) async -> ShareOpenOutcome {        guard let kind = ShareKnock.kind(entry, shelf: shelf, head: head) else { return .nothingToOpen }        guard let url = ShareKnock.url(kind, shareId: entry.id) else { return .nothingToOpen }        return await open(url) ? .opened(url) : .couldNotOpen(url)    }}// MARK: - Which responder opens the URL, and how/// The two objects that answer `openURL:options:completionHandler:`, and they/// do **not** take the same arguments.////// This is root cause of the crash of 15 Sep 2026. The extension walked the/// responder chain for anything that answered the selector and sent every one/// of them `UIApplication`'s shape — an `NSDictionary` of options. On this/// host the first answering responder is a **`UIScene`**, whose method takes a/// `UISceneOpenExternalURLOptions` object, so UIKit sent `universalLinksOnly`/// to an empty dictionary and the extension died with/// `NSInvalidArgumentException: -[__NSDictionary0 universalLinksOnly]:/// unrecognized selector`. Every share aborted; the sheet hung until it was/// tapped away.////// One selector, two argument shapes — so the responder's CLASS decides the/// call, and a responder that is neither is not called at all.public enum ShareOpenerKind: Equatable, Sendable {    /// `-[UIApplication openURL:options:completionHandler:]` — an    /// `NSDictionary` of `UIApplication.OpenExternalURLOptionsKey`.    case application    /// `-[UIScene openURL:options:completionHandler:]` — a    /// `UISceneOpenExternalURLOptions` object (`UIScene.OpenExternalURLOptions`    /// in Swift).    case scene    /// The ObjC class name of the options argument this method takes.    ///    /// Declared here rather than only in the extension's two `typealias`es so    /// the rule and the call can be held to each other: the extension switches    /// on this enum, and this says what each case's third argument IS.    public var optionsClassName: String {        switch self {        case .application: return "NSDictionary"        case .scene: return "UISceneOpenExternalURLOptions"        }    }}/// Which opener this responder offers, read off its class ANCESTRY —/// most-specific first, as `object_getClass` then `class_getSuperclass` walks/// it (`["UIWindowScene", "UIScene", "UIResponder", "NSObject"]`).////// **The ancestry and not `isKind(of:)`** for the reason this whole file/// exists: the extension target is in no test bundle, and a rule expressed as/// a UIKit call can only be exercised on a running share sheet. A list of/// names is the same decision with a test around it — and it still reads a/// runtime subclass correctly, because `NSKVONotifying_UIApplication` has/// `UIApplication` above it.////// `nil` for anything else: a `UIView`, a `UIViewController`, some host's own/// responder. Those are SKIPPED rather than guessed at — a wrongly typed call/// is the crash, and the mailbox is the floor under a share nobody opens.public func shareOpenerKind(classAncestry: [String]) -> ShareOpenerKind? {    if classAncestry.contains("UIApplication") { return .application }    if classAncestry.contains("UIScene") { return .scene }    return nil}/// One responder on the chain, reduced to what the choice depends on.public struct ShareOpenerCandidate: Equatable, Sendable {    /// Whether it answers `openURL:options:completionHandler:` at all.    public let opensURLs: Bool    /// Which shape its method takes, when it is one of the two that can be    /// called safely.    public let kind: ShareOpenerKind?    public init(opensURLs: Bool, kind: ShareOpenerKind?) {        self.opensURLs = opensURLs        self.kind = kind    }}/// Which responder on the chain gets the URL — an index into `chain`, in the/// order the walk visits it (`self`, then `next`, then `next`…).////// **A `UIApplication` is preferred wherever it sits on the chain**, because/// it is the opener the platform documents for a URL leaving the process and/// the one whose `false` means "nothing will take this". A `UIScene` is the/// fallback and is called with its OWN options type. Anything else that/// answers the selector is skipped: its third argument is unknown, and the/// only honest thing to do with an unknown argument is not to send it.////// `nil` when nobody on the chain can be called safely — which is/// ``ShareOpenOutcome/couldNotOpen(_:)``, not an error: the bytes are staged/// and the mailbox entry is written, so the next foreground drains it.public func shareOpenerChoice(_ chain: [ShareOpenerCandidate]) -> Int? {    if let index = chain.firstIndex(where: { $0.opensURLs && $0.kind == .application }) {        return index    }    return chain.firstIndex(where: { $0.opensURLs && $0.kind == .scene })}