Cotton code
290 lines · 11.2 KB · SwiftRaw
// The Camera tool's capture surface — `/camera`, opened by the tool's tile.//// **A hand-built screen, and its reason is the camera itself.** A live// preview and a shutter that takes shot after shot without a review step are// not something a definition can describe; everything else about the tool —// its tile, its picture, its name — is data. Each shot is saved into Cotton// the moment it is taken (`ShotPipeline` → `camera.shot`: the photo row),// then to the camera roll while that is on for this device.//// **The one order** (`DeviceCapability`'s header): ask → configure the session// → construct the inputs → start. The session is built in `open()` after the// gate said yes, configured inside one begin/commit window, and started off// the main actor only after the commit.import CottonKitimport PhotosUIimport SwiftUI#if canImport(UIKit)import UIKitimport os#endif@MainActor @Observablefinal class CameraModel {    private let pipeline: ShotPipeline    /// Shots saved into Cotton since the screen opened.    private(set) var saved = 0    /// Why the camera cannot open, when it cannot.    private(set) var refusal: String?    /// Why the last shot did not reach the camera roll, said once.    private(set) var rollTrouble: String?    #if canImport(UIKit)    private(set) var session: (any CameraCapture)?    #endif    /// What a shot is for once it is in Cotton: nothing more for the    /// Camera tool; a one-photo form keeps its row with it and closes.    private let onShot: (@MainActor (ShotTaken, Date) async -> Void)?    /// The Camera tool: every shot a photo row (`camera.shot`).    convenience init(core: any CottonCalling, capabilities: any CapabilityAuthority) {        self.init(shooter: CoreMediaCapture(core: core), capabilities: capabilities)    }    init(        shooter: any CameraShooting,        capabilities: any CapabilityAuthority,        onShot: (@MainActor (ShotTaken, Date) async -> Void)? = nil    ) {        pipeline = ShotPipeline(            shooter: shooter,            mayAddToRoll: { await capabilities.gate([.photoLibraryAdd]).isReady }        )        self.onShot = onShot    }    func open(_ capabilities: any CapabilityAuthority) async {        if let sentence = await Camera.refusal(capabilities) {            refusal = sentence            return        }        #if canImport(UIKit)        let session = CameraCaptures.make { [weak self] file in            Task { @MainActor in await self?.take(file) }        }        guard let session, session.configure() else {            refusal = CapabilityRefusal.sentence(.camera, .unavailable) ?? CottonStrings.somethingWentWrong            return        }        self.session = session        session.start()        #endif    }    func close() {        #if canImport(UIKit)        session?.stop()        #endif    }    func shutter() {        #if canImport(UIKit)        session?.shoot()        #endif    }    /// The camera roll follows the device row's `camera_roll` once the rise    /// that adds it lands; until then it is the column's default, on.    private var saveToRoll: Bool { true }    /// A picture picked from the library where there is no camera: saved    /// into Cotton as a shot is, never added to the roll it came from.    func takePicked(_ item: PhotosPickerItem) async {        #if canImport(UIKit)        guard let data = try? await item.loadTransferable(type: Data.self),            let jpeg = UIImage(data: data)?.jpegData(compressionQuality: 0.9)        else {            rollTrouble = CottonStrings.somethingWentWrong            return        }        let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".jpg")        do {            try jpeg.write(to: file)            await take(file, toRoll: false)        } catch {            rollTrouble = CottonStrings.somethingWentWrong        }        #endif    }    private func take(_ file: URL, toRoll: Bool? = nil) async {        // The shot's moment: the file lands the instant the shutter fires.        let moment = Date()        do {            let taken = try await pipeline.take(file: file, kind: .photo, saveToRoll: toRoll ?? saveToRoll)            saved += 1            switch taken.roll {            case .refused:                rollTrouble = CapabilityRefusal.sentence(.photoLibraryAdd, .denied)            case .failed:                rollTrouble = CottonStrings.somethingWentWrong            case .saved, .off, .unreachable:                break            }            await onShot?(taken, moment)        } catch {            refusal = error.localizedDescription        }    }}struct CameraScreen: View {    let model: CameraModel    let onClose: () -> Void    @Environment(\.cottonCapabilities) private var capabilities    /// Painted for the fan's picture: the face alone, no session, no ask.    @Environment(\.paintsPicture) private var paintsPicture    /// Drawn as a fan card's own page: there is nothing to close back to.    @Environment(\.cottonAtColumnRoot) private var atRoot    @State private var picked: PhotosPickerItem?    @Environment(\.theme) private var theme    static var pickFromLibrary: String { ShellLines.line("editing", "camera.pick_from_the_library") }    /// The camera's picture fills the page: until it does — opening, refused,    /// painted for the fan — the page is paper, as every page is (walker292:    /// a black page under the island with no camera to show).    private var viewing: Bool {        #if canImport(UIKit)        return model.session != nil        #else        return false        #endif    }    /// The words on the page: white over the camera's picture, ink on paper.    private var ink: Color { viewing ? .white : theme.colors.ink.color }    var body: some View {        ZStack {            if viewing { Color.black.ignoresSafeArea() } else { PageGroundFill().ignoresSafeArea() }            #if canImport(UIKit)            if let session = model.session {                CameraPreview(capture: session).ignoresSafeArea()            }            #endif            if let refusal = model.refusal {                // No camera to reach: say so, and offer the library instead                // (walker, 16 Oct 2026: the shutter stood live and did nothing).                VStack(spacing: 20) {                    Text(refusal)                        .foregroundStyle(ink)                        .multilineTextAlignment(.center)                    PhotosPicker(selection: $picked, matching: .images) {                        Text(Self.pickFromLibrary)                            .font(.callout.weight(.semibold))                            .foregroundStyle(viewing ? .black : theme.colors.ground.color)                            .padding(.horizontal, 20)                            .padding(.vertical, 12)                            .background(Capsule().fill(ink))                    }                    .accessibilityIdentifier("camera-pick-library")                }                .padding(24)            }            VStack {                HStack {                    if !atRoot {                        Button(action: close) {                            Image(systemName: "xmark")                                .font(.title2.weight(.semibold))                                .foregroundStyle(ink)                                .padding(16)                        }                        .accessibilityLabel(Text(ShellLines.line("editing", "camera.close")))                    }                    Spacer()                    if model.saved > 0 {                        Text(ShellLines.line("editing", "camera.saved", ["saved": "\(model.saved)"]))                            .font(.callout.weight(.medium))                            .foregroundStyle(ink)                            .padding(.horizontal, 16)                    }                }                Spacer()                if let trouble = model.rollTrouble {                    Text(trouble)                        .font(.footnote)                        .foregroundStyle(ink.opacity(0.85))                        .padding(.horizontal, 24)                }                Button(action: model.shutter) {                    Circle()                        .strokeBorder(ink, lineWidth: 4)                        .background(Circle().fill(ink.opacity(0.9)).padding(8))                        .frame(width: 78, height: 78)                }                .accessibilityLabel(Text(ShellLines.line("editing", "camera.take_photo")))                .disabled(model.refusal != nil)                .opacity(model.refusal != nil ? 0.3 : 1)                .padding(.bottom, 32)            }        }        .task {            guard !paintsPicture else { return }            await model.open(capabilities)        }        .onChange(of: picked) { _, item in            guard let item else { return }            picked = nil            Task { await model.takePicked(item) }        }        .onDisappear { model.close() }    }    private func close() {        model.close()        onClose()    }}#if canImport(UIKit)/// The camera's capture, as the app builds it: the one `AVCaptureSession`, its photo output and its preview, in/// `App/Cotton/Camera+AVFoundation.swift` and nowhere in the package. An app whose plist does not say why it would use/// the camera is built without it (`COTTON_NO_CAMERA`), so App Store processing finds no capture API to ask a purpose/// string for (ITMS-90683, 22 Nov 2026); the Camera tool there says the camera cannot open.public protocol CameraCapture: AnyObject, Sendable {    /// Inputs and output inside one configuration window; false when this device has no back camera to use.    func configure() -> Bool    /// Started after the commit, off the main actor.    func start()    func stop()    func shoot()    /// The live preview, filling its frame.    @MainActor func preview() -> UIView}/// The capture the app installed at launch, built per screen; none in an app built without a camera.public enum CameraCaptures {    public typealias Make = @Sendable (_ onShot: @escaping @Sendable (URL) -> Void) -> any CameraCapture    private static let held = OSAllocatedUnfairLock<Make?>(initialState: nil)    public static func install(_ make: @escaping Make) {        held.withLock { $0 = make }    }    static func make(onShot: @escaping @Sendable (URL) -> Void) -> (any CameraCapture)? {        held.withLock { $0 }?(onShot)    }    /// Comms' safety-number scan: a controller over the back camera that hands on the first QR code read.    public typealias MakeReader = @MainActor (_ read: @escaping (String) -> Void, _ refused: @escaping () -> Void) -> UIViewController    @MainActor private static var reader: MakeReader?    @MainActor public static func install(qrReader: @escaping MakeReader) {        reader = qrReader    }    @MainActor static func qrReader(read: @escaping (String) -> Void, refused: @escaping () -> Void) -> UIViewController? {        reader?(read, refused)    }}private struct CameraPreview: UIViewRepresentable {    let capture: any CameraCapture    func makeUIView(context: Context) -> UIView { capture.preview() }    func updateUIView(_ view: UIView, context: Context) {}}#endif