Cotton code
166 lines · 6.5 KB · SwiftRaw
// Where a picture or a file comes from: the camera, the photo library, the// files. One way to pick one in the whole app — the attachment editor, the// capture composer, a note and a thought all open these same three.//// A machine with no camera surface gets `CapabilityRefusal`'s own sentence,// the same answer a phone whose camera was denied gets; nothing here branches// on the platform by name.import CottonKitimport PhotosUIimport SwiftUIimport UniformTypeIdentifiers#if canImport(UIKit)import UIKit#endif/// Whether this machine can put a camera on screen at all.////// A capability, and the refusal is `CapabilityRefusal`'s own sentence — never/// a platform branch, and never a control that does nothing when tapped.enum Camera {    static var isAvailable: Bool {        #if canImport(UIKit)        return UIImagePickerController.isSourceTypeAvailable(.camera)        #else        return false        #endif    }    /// Whether the camera may open now — `nil` when it may, else the sentence    /// saying why not.    ///    /// **Two refusals, and both are capability answers rather than a platform    /// branch**: a machine with no camera surface at all, and a phone whose    /// camera this app was refused. Said ONCE here because two surfaces open    /// the camera — a note's sheet and the capture composer's fan — and two    /// copies of a refusal are two sentences that drift.    @MainActor    static func refusal(_ capabilities: any CapabilityAuthority) async -> String? {        guard isAvailable else {            return CapabilityRefusal.sentence(.camera, .unavailable)                ?? CottonStrings.somethingWentWrong        }        let answer = await capabilities.gate([.camera])        guard answer.isReady else {            return CapabilityRefusal.sentence(for: answer) ?? CottonStrings.somethingWentWrong        }        return nil    }}/// The camera, as a screen.////// `UIImagePickerController` is the one surface that takes a photograph and/// hands back a file without this app building an `AVCaptureSession` itself —/// which `DeviceCapability`'s own header says is the arrangement that used to/// crash. A machine without it never reaches this view: `Camera.isAvailable`/// is false and the verb refuses first.struct CameraPicker: View {    /// Whether the camera also films: Photos' Take a photo takes a photo or a    /// clip (`pick.kinds`); every other camera here takes a photograph.    var films = false    let onTaken: (URL) -> Void    let onCancelled: () -> Void    var body: some View {        #if canImport(UIKit)        CameraSurface(films: films, onTaken: onTaken, onCancelled: onCancelled)            .ignoresSafeArea()        #else        Color.clear.onAppear { onCancelled() }        #endif    }}#if canImport(UIKit)/// The controller, wrapped — and the picked image written to a FILE, because/// `capture.media` takes a path and refuses bytes by name.private struct CameraSurface: UIViewControllerRepresentable {    let films: Bool    let onTaken: (URL) -> Void    let onCancelled: () -> Void    func makeCoordinator() -> Coordinator {        Coordinator(onTaken: onTaken, onCancelled: onCancelled)    }    func makeUIViewController(context: Context) -> UIImagePickerController {        let controller = UIImagePickerController()        controller.sourceType = .camera        if films { controller.mediaTypes = [UTType.image.identifier, UTType.movie.identifier] }        controller.delegate = context.coordinator        return controller    }    func updateUIViewController(_ controller: UIImagePickerController, context: Context) {}    final class Coordinator: NSObject, UIImagePickerControllerDelegate,        UINavigationControllerDelegate    {        private let onTaken: (URL) -> Void        private let onCancelled: () -> Void        init(onTaken: @escaping (URL) -> Void, onCancelled: @escaping () -> Void) {            self.onTaken = onTaken            self.onCancelled = onCancelled        }        func imagePickerController(            _ picker: UIImagePickerController,            didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]        ) {            // A clip comes as a file the picker owns until this returns: moved            // out first, so it outlives the controller.            if let clip = info[.mediaURL] as? URL {                let suffix = clip.pathExtension.isEmpty ? "mov" : clip.pathExtension                let file = FileManager.default.temporaryDirectory                    .appendingPathComponent("camera-clip-\(UUID().uuidString).\(suffix)")                guard (try? FileManager.default.moveItem(at: clip, to: file)) != nil else {                    onCancelled()                    return                }                onTaken(file)                return            }            guard let image = info[.originalImage] as? UIImage,                let data = image.jpegData(compressionQuality: 0.9)            else {                onCancelled()                return            }            let file = FileManager.default.temporaryDirectory                .appendingPathComponent("camera-photo-\(UUID().uuidString).jpg")            guard (try? data.write(to: file, options: .atomic)) != nil else {                onCancelled()                return            }            onTaken(file)        }        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {            onCancelled()        }    }}#endif/// The file picked out of the photo library, staged as a file on disk.////// `PhotosPicker` runs out of process and hands back bytes, so they are written/// somewhere before the boundary is called: `capture.media` takes a PATH and/// refuses a `bytes` argument by name. The caller deletes the staged copy once/// the crate has copied it into the store.enum MediaStaging {    static func stage(_ item: PhotosPickerItem) async -> (url: URL, mime: String)? {        guard let bytes = try? await item.loadTransferable(type: Data.self) else { return nil }        let type = item.supportedContentTypes.first { $0.conforms(to: .image) }            ?? item.supportedContentTypes.first        let ext = type?.preferredFilenameExtension ?? "jpg"        let mime = type?.preferredMIMEType ?? "image/jpeg"        let file = FileManager.default.temporaryDirectory            .appendingPathComponent("picked-\(UUID().uuidString).\(ext)")        guard (try? bytes.write(to: file, options: .atomic)) != nil else { return nil }        return (file, mime)    }}