// 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.importCottonKitimportPhotosUIimportSwiftUI#if canImport(UIKit)import UIKitimport os#endif@MainActor @ObservablefinalclassCameraModel {privatelet 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.privatelet 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 }funcopen(_ capabilities: any CapabilityAuthority) async {iflet sentence = awaitCamera.refusal(capabilities) { refusal = sentencereturn } #if canImport(UIKit)let session = CameraCaptures.make { [weakself] file inTask { @MainActor inawaitself?.take(file) } }guardlet session, session.configure() else { refusal = CapabilityRefusal.sentence(.camera, .unavailable) ?? CottonStrings.somethingWentWrongreturn }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.privatevar 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)guardlet data = try? await item.loadTransferable(type: Data.self),let jpeg = UIImage(data: data)?.jpegData(compressionQuality: 0.9)else { rollTrouble = CottonStrings.somethingWentWrongreturn }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 }privatefunc 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 = tryawait pipeline.take(file: file, kind: .photo, saveToRoll: toRoll ?? saveToRoll) saved += 1switch taken.roll {case .refused: rollTrouble = CapabilityRefusal.sentence(.photoLibraryAdd, .denied)case .failed: rollTrouble = CottonStrings.somethingWentWrongcase .saved, .off, .unreachable:break }await onShot?(taken, moment) } catch { refusal = error.localizedDescription } }}structCameraScreen: View {let model: CameraModellet onClose: () -> Void @Environment(\.cottonCapabilities) privatevar capabilities/// Painted for the fan's picture: the face alone, no session, no ask. @Environment(\.paintsPicture) privatevar paintsPicture/// Drawn as a fan card's own page: there is nothing to close back to. @Environment(\.cottonAtColumnRoot) privatevar atRoot @State privatevar picked: PhotosPickerItem? @Environment(\.theme) privatevar themestaticvar 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).privatevar viewing: Bool { #if canImport(UIKit)return model.session != nil #elsereturnfalse #endif }/// The words on the page: white over the camera's picture, ink on paper.privatevar ink: Color { viewing ? .white : theme.colors.ink.color }var body: someView { ZStack {if viewing { Color.black.ignoresSafeArea() } else { PageGroundFill().ignoresSafeArea() } #if canImport(UIKit)iflet session = model.session {CameraPreview(capture: session).ignoresSafeArea() } #endififlet 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()iflet 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 inguardlet item else { return } picked = nilTask { await model.takePicked(item) } } .onDisappear { model.close() } }privatefunc 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.publicprotocolCameraCapture: 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.publicenumCameraCaptures {publictypealiasMake = @Sendable (_ onShot: @escaping @Sendable (URL) -> Void) -> any CameraCaptureprivatestaticlet held = OSAllocatedUnfairLock<Make?>(initialState: nil)publicstaticfunc install(_ make: @escaping Make) { held.withLock { $0 = make } }staticfunc 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.publictypealiasMakeReader = @MainActor (_ read: @escaping (String) -> Void, _ refused: @escaping () -> Void) -> UIViewController @MainActor privatestaticvar reader: MakeReader? @MainActor publicstaticfunc install(qrReader: @escaping MakeReader) { reader = qrReader } @MainActor staticfunc qrReader(read: @escaping (String) -> Void, refused: @escaping () -> Void) -> UIViewController? { reader?(read, refused) }}privatestructCameraPreview: UIViewRepresentable {let capture: any CameraCapturefunc makeUIView(context: Context) -> UIView { capture.preview() }func updateUIView(_ view: UIView, context: Context) {}}#endif