Cotton code
419 lines · 19.0 KB · SwiftRaw
// The app.//// `WindowGroup` and nothing else: no provider tower. The previous app's root// layout was eleven nested providers (palette, safe area, gesture handler, bottom// sheets, keyboard, query client, state store, analytics, feedback, share// intent, error boundary) and design P20 drops every library behind them. What// survives// arrives as SwiftUI environment or as `@Observable` state a screen owns — which// here is exactly two objects, both created once and handed down.//// The core is opened ONCE, off the main thread (it is an actor), over the app// group's container. Everything after that is a method name inside `cotton_call`.import CottonKitimport CottonUIimport Security#if COTTON_CALLING    import CottonCalls#endif#if COTTON_CHAT    import CottonCalls    import CottonChat#endif#if COTTON_HEALTH    import CottonHealthKit#endif#if COTTON_MEETINGS    import CottonMeetingsLive#endifimport SwiftUIimport UIKit@mainstruct CottonApp: App {    /// The ONE thing SwiftUI cannot do for itself.    ///    /// `didRegisterForRemoteNotificationsWithDeviceToken` has no SwiftUI    /// equivalent, and `UNUserNotificationCenter`'s delegate has to be set on a    /// live object before any notification can be delivered — including the one    /// whose tap launched the app. So there is an adaptor, it holds no state    /// and reaches no core, and everything it learns it leaves on    /// `NotificationBridge` for `NotificationsModel` to take.    @UIApplicationDelegateAdaptor(CottonAppDelegate.self) private var delegate    @State private var opened: OpenState = .opening    init() {        // Before anything else: a report made during the open has a sink to        // go to, and the first line of the ring says whether this build sends.        LaunchMarks.mark("app-init")        let plan = BugsinkReporting.start()        Log.write("reporting: \(plan.reason)")        // The person's own stores open in the app and nowhere else (`LiveStores`).        #if !COTTON_NO_CONTACTS        LiveStores.install(addressBook: SystemAddressBook())        #endif        #if !COTTON_NO_PHOTOS        LiveStores.install(access: SystemPhotoAccess(add: false), for: .photoLibrary)        #if !COTTON_NO_PHOTO_WRITES        LiveStores.install(cameraRoll: SystemCameraRoll())        LiveStores.install(access: SystemPhotoAccess(add: true), for: .photoLibraryAdd)        #endif        #endif        // Cotton Albums' photo library, compiled into Albums alone (COTTON_ALBUMS): no other app references PhotoKit's        // library through it (ITMS-90683). Its writers, never in a look-only build.        #if COTTON_ALBUMS        AlbumsPhotosInstall.install(SystemAlbumsPhotos())        #if !COTTON_NO_PHOTO_WRITES        AlbumsWritesInstall.install(SystemAlbumsWrites())        #endif        #endif        #if !COTTON_NO_CAMERA        LiveStores.install(access: SystemCameraAccess(), for: .camera)        CameraCaptures.install { SystemCameraCapture(onShot: $0) }        CameraCaptures.install(qrReader: { read, refused in            let controller = ChatQRReaderController()            controller.read = read            controller.refused = refused            return controller        })        #endif        // Each list's last drawn rows outlive the process (`ListSeeds`).        ListSeeds.installInAppGroup()        // A LAUNCH IN THE BACKGROUND MOUNTS NO VIEW, so nothing below would        // ever open the core for it. The catch-up tasks ask through here and        // are handed the one core this process has — the window's, when the        // window got there first.        LaunchMarks.mark("app-stores")        BackgroundCatchUp.shared.attach {            if case .ready(let core) = await CottonApp.open() { return core }            return nil        }        // Post's round of This phone fetches runs in the same background wake (mail CONTRACT row 12).        #if os(iOS)        PostBackground.attach()        #endif        #if COTTON_CALLING            // COTTON CALLING listens for VoIP pushes from launch, before any            // view: a push that woke the app in the background must find its            // handler, and reports its call to CallKit before anything opens.            CallingEngine.shared.attach {                if case .ready(let core) = await CottonApp.open() { return core }                return nil            }        #endif        #if COTTON_CHAT            // Cotton chat's engine asks for the core when it first needs it:            // the socket and the outbox wait for the app to come forward.            ChatEngine.shared.attach {                if case .ready(let core) = await CottonApp.open() { return core }                return nil            }            // Calls inside Cotton Chat: Calling's engine listens for VoIP            // pushes from launch too, its token filed under Chat's bundle id.            CallingEngine.shared.attach {                if case .ready(let core) = await CottonApp.open() { return core }                return nil            }        #endif        #if COTTON_HEALTH            // Cotton Health attaches its Read Apple Health door and, only            // where the person already answered it, the observers HealthKit            // wakes the app through: before the first frame, asking nothing.            HealthEngine.shared.attach {                if case .ready(let core) = await CottonApp.open() { return core }                return nil            }        #endif        #if COTTON_MEETINGS            // Cotton Meetings' recorder belongs to the app, not a screen: the            // Action Button, the lock screen's control and the Live Activity            // reach it with no view mounted (`MeetingsGlue`).            MeetingsGlue.attach {                if case .ready(let core) = await CottonApp.open() { return core }                return nil            }        #endif    }    var body: some Scene {        WindowGroup {            root            // A link handed to Sites (Comms' and Post's Open in Sites) is held from the first moment: on a cold            // launch only the splash stands while the core opens, and Sites' own screens are not up to take it            // (`SitesLinkInbox`). Any other link goes on to RootView's handler as before.            .onOpenURL { SitesLinkInbox.shared.hold($0) }            // THE app's one measurement of the top safe-area inset, taken at            // the window because the window is the only place nothing has            // ignored it yet: every `ScreenBar` screen's scroller ignores the            // top edge on purpose, and a `GeometryReader` under that reports            // zeroes. `ScreenBarClearance` and the bar's wash read it back as            // `\.cottonTopInset`. Here rather than in `RootView` because a            // SECOND reader further down would publish over this answer.            // `CottonUI/Chrome/ScreenFrame.swift` states the rule.            .measuresTopInset()        }    }    @ViewBuilder private var root: some View {        Group {            switch opened {            case .opening:                // Nothing: the splash is up, and the open is one `cotton_open`                // over a path this process already knows.                SplashOverlay()                    .task { opened = await CottonApp.open() }            case .ready(let core):                RootView(core: core, reopen: {                    // "Re-key this device": the new key is in the Keychain,                    // so the core is closed and opened again on it.                    await CottonApp.closeForReopen()                    opened = .opening                })                #if COTTON_CALLING                    .callingShell()                #endif                #if COTTON_CHAT                    .chatShell()                    .chatCallsShell()                #endif                .sendShell(core: core)            case .refused(let refusal):                // The core would not open at all. Its message is a sentence                // meant to be shown as written, and it paints outside any route                // — there is no route yet.                ErrorFallback(message: refusal.message)            case .keyUnreadable(let refusal):                // The Keychain holds something in this phone's slot and will                // not give it back. The core is NOT opened: opening without a                // `deviceSecret` mints a second identity, and a phone with two                // is a phone whose server sees a stranger. So the one screen                // that offers "start over" paints here, outside any route,                // over no core at all.                ServerRefusalScreen(                    refusal: refusal,                    onRetry: { Task { opened = await CottonApp.open() } },                    onSignOut: {},                    onResetKey: {                        DeviceKey.forget(store: KeychainDeviceKeyStore())                        // Both halves of the vault key too: a phone starting                        // over is a NEW device, and a published public key                        // against an identity nobody approves is a row no                        // server will ever wrap for.                        VaultKeyring().forget()                        Task { opened = await CottonApp.open() }                    }                )                // A locked phone's key comes back the moment the phone is                // unlocked: the system says so, and the open runs again without                // waiting for a tap. Only for that refusal — every other one is                // a state an unlock does not change.                .task(id: refusal.code) {                    guard refusal.code == "keychain_locked" else { return }                    let unlocked = NotificationCenter.default.notifications(                        named: UIApplication.protectedDataDidBecomeAvailableNotification                    )                    for await _ in unlocked {                        opened = await CottonApp.open()                        return                    }                }            }        }    }    /// The Keychain, except in a DEBUG build launched with    /// `-CottonKeychainRehearsal locked` (or `unavailable`), which answers the    /// way a phone opened before its first unlock (or an unsigned build) does —    /// the only way to look at those two screens on a simulator, where the    /// Keychain is always open. A Release build has no such argument.    nonisolated private static func keyStore() -> any DeviceKeyStore {        #if DEBUG            switch UserDefaults.standard.string(forKey: "CottonKeychainRehearsal") {            case "locked": return RefusingKeyStore(status: errSecInteractionNotAllowed)            case "unavailable": return RefusingKeyStore(status: errSecMissingEntitlement)            default: break            }        #endif        return KeychainDeviceKeyStore()    }    private enum OpenState {        case opening        case ready(any CottonCalling)        case refused(CottonRefusal)        /// The one failure that must never be repaired by minting a second        /// identity — so it is a state of its own rather than an open with a        /// nil secret.        case keyUnreadable(ServerRefusal)    }    /// The core this process opened, once it has: there is ONE, whoever    /// asked first — the window or a background task.    private static var readyCore: (any CottonCalling)?    /// The open in flight, so that a window appearing while a background task    /// is opening the core waits for THAT open and not for a second one over    /// the same files.    private static var opening: Task<Void, Never>?    private static var lastOpen: OpenState = .opening    /// Close the open core so the next `open()` reads the Keychain again —    /// the one way a running phone takes a new device key.    @MainActor    private static func closeForReopen() async {        Log.write("core: closing for a reopen")        let core = readyCore        readyCore = nil        lastOpen = .opening        await core?.close()    }    /// The core, opened once per process.    ///    /// A refusal is NOT kept: "try again" and "start over" open afresh, and    /// so does a background task on a phone that has been unlocked since the    /// last one found its key unreadable.    private static func open() async -> OpenState {        if let readyCore { return .ready(readyCore) }        if let opening {            await opening.value            return lastOpen        }        let task = Task { @MainActor in            Log.write("core: opening")            lastOpen = await openNow()            if case .ready(let core) = lastOpen { readyCore = core }        }        opening = task        await task.value        opening = nil        return lastOpen    }    /// Open the core over the app group's container.    ///    /// `nonisolated`: `CottonApp` is an `App`, so its members run on the main    /// actor unless said otherwise, and this one used to — the Keychain read,    /// the folder adoption and `cotton_open` all held the main thread before    /// the first frame (pagespeed, 15 Oct 2026).    ///    /// The Keychain read happens HERE, off the main thread, and the seed goes    /// down as `OpenConfig.deviceSecret` — Swift owns the Keychain and Rust owns    /// everything the key is FOR (design P15). `SecItemCopyMatching` blocks on a    /// SecurityAgent prompt whenever the binary's signature has changed since    /// the item was written, and on the main thread that is an app with nothing    /// drawn and no way to say what it is waiting for.    nonisolated private static func openNow() async -> OpenState {        LaunchMarks.mark("open-asked")        let store = keyStore()        let seed: String        do {            seed = try DeviceKey.seed(store: store)        } catch {            // NEVER `try?`. A slot that is present and unreadable is a state            // with a screen and a way out ("start over on this phone", which            // deliberately mints a new key); swallowing it and opening with            // `deviceSecret: nil` would let the core mint one SILENTLY, and            // the person's server would then be facing a device it has never            // approved with no sentence anywhere saying why.            //            // WHICH refusal is the error's to decide: a build the Keychain            // turns away outright (an unsigned simulator build) is not a slot            // "Start over" can clear, and offering that button there was a            // button that did nothing (`ServerRefusal.forKeyRead`).            Log.write("device key: \(error)")            return .keyUnreadable(ServerRefusal.forKeyRead(error))        }        LaunchMarks.mark("keychain-read")        // **THE DATA FOLDER IS THE APP'S OWN, NOT THE APP GROUP'S.** iOS        // kills a suspended app holding a lock on a file in a shared container        // (0xDEAD10CC), and the core keeps the replica open; a phone that ran        // an earlier build has its data moved across here, entry by entry        // (`PhoneDataDirectory`).        let group = FileManager.default.containerURL(            forSecurityApplicationGroupIdentifier: CottonDefaults.appGroup(                bundleIdentifier: Bundle.main.bundleIdentifier            )        )        let container: URL        do {            container = try PhoneDataDirectory.own()        } catch {            Log.write("data folder: \(error)")            return .refused(                CottonRefusal(                    code: "no_container",                    title: CottonStrings.errorFallbackTitle,                    message: CottonStrings.errorFallbackBody                )            )        }        if let group { PhoneDataDirectory.adopt(from: group, into: container) }        // **THE STORE ROOT IS EXCLUDED FROM iCLOUD BACKUP, HERE, ON EVERY        // OPEN.** `OpenMode::Phone` takes `container_path` as the data dir        // verbatim (`crates/cotton-ffi/src/handle.rs`) and everything the core        // writes is under it: the replica, the media, the exports. Backing that        // up would put a person's whole archive, a COPY of a file that lives on        // their Mac, into an iCloud quota it cannot fit. Before the open, so a        // folder created moments ago is flagged before the first byte lands in        // it; a failure says so in the log rather than being swallowed        // (`StoreBackup.exclude`).        StoreBackup.exclude(container)        let config = CottonConfig(            containerPath: container.path,            previousContainerPath: group?.path,            // "1.0.0 (248)": the build rides the label onto the device row.            appVersion: CottonConfig.bundleVersionLabel,            // Read HERE, before anything pins this process to anything, so the            // recurrence rules below the boundary stay pure.            timeZone: TimeZone.current.identifier,            // Always a real seed by here: the unreadable case returned above,            // because opening without one is how a phone gets a second            // identity.            deviceSecret: seed        )        // `CottonRuntime` is the one door, and it answers whether or not the        // XCFramework is present — the app target does not link it directly, so        // a conditional written here would be asking about a module this target        // cannot see.        do {            let core = try CottonRuntime.open(config)            LaunchMarks.mark("core-opened")            // The boards and themes this build draws before any database            // answers, as its core decoded them: a shape or a board this app            // cannot draw is said here, on the open screen, and never reaches            // a screen that would trap on it.            do {                try await DefinitionCatalogue.receiveLastResort(from: core)            } catch {                await core.close()                return .refused(CottonRefusal(code: "definitions", title: CottonStrings.errorFallbackTitle, message: "\(error)"))            }            LaunchMarks.mark("catalogue-taken")            return .ready(core)        } catch let refusal as CottonRefusal {            return .refused(refusal)        } catch {            return .refused(                CottonRefusal(                    code: "unreadable",                    title: CottonStrings.errorFallbackTitle,                    message: String(describing: error)                )            )        }    }}#if DEBUG    /// A Keychain that answers every call with one status — see    /// `CottonApp.keyStore()`.    private struct RefusingKeyStore: DeviceKeyStore {        let status: OSStatus        func read() throws -> String? { throw DeviceKeyError.storeUnreadable(status) }        func writeIfAbsent(_ seed: String) throws -> String { throw DeviceKeyError.notWritten(status) }        func forget() {}        func replace(_ seed: String) throws { throw DeviceKeyError.notWritten(status) }    }#endif