// 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.importCottonKitimportPhotosUIimportSwiftUIimportUniformTypeIdentifiers#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.enumCamera {staticvar isAvailable: Bool { #if canImport(UIKit)return UIImagePickerController.isSourceTypeAvailable(.camera) #elsereturnfalse #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. @MainActorstaticfunc refusal(_ capabilities: any CapabilityAuthority) async -> String? {guard isAvailable else {returnCapabilityRefusal.sentence(.camera, .unavailable) ?? CottonStrings.somethingWentWrong }let answer = await capabilities.gate([.camera])guard answer.isReady else {returnCapabilityRefusal.sentence(for: answer) ?? CottonStrings.somethingWentWrong }returnnil }}/// 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.structCameraPicker: 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 = falselet onTaken: (URL) -> Voidlet onCancelled: () -> Voidvar body: someView { #if canImport(UIKit)CameraSurface(films: films, onTaken: onTaken, onCancelled: onCancelled) .ignoresSafeArea() #elseColor.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.privatestructCameraSurface: UIViewControllerRepresentable {let films: Boollet onTaken: (URL) -> Voidlet onCancelled: () -> Voidfunc makeCoordinator() -> Coordinator {Coordinator(onTaken: onTaken, onCancelled: onCancelled) }func makeUIViewController(context: Context) -> UIImagePickerController {let controller = UIImagePickerController() controller.sourceType = .cameraif films { controller.mediaTypes = [UTType.image.identifier, UTType.movie.identifier] } controller.delegate = context.coordinatorreturn controller }func updateUIViewController(_ controller: UIImagePickerController, context: Context) {}finalclassCoordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {privatelet onTaken: (URL) -> Voidprivatelet onCancelled: () -> Voidinit(onTaken: @escaping (URL) -> Void, onCancelled: @escaping () -> Void) {self.onTaken = onTakenself.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.iflet clip = info[.mediaURL] as? URL {let suffix = clip.pathExtension.isEmpty ? "mov" : clip.pathExtensionlet file = FileManager.default.temporaryDirectory .appendingPathComponent("camera-clip-\(UUID().uuidString).\(suffix)")guard (try? FileManager.default.moveItem(at: clip, to: file)) != nilelse { onCancelled()return } onTaken(file)return }guardlet 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)) != nilelse { 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.enumMediaStaging {staticfunc stage(_ item: PhotosPickerItem) async -> (url: URL, mime: String)? {guardlet bytes = try? await item.loadTransferable(type: Data.self) else { returnnil }let type = item.supportedContentTypes.first { $0.conforms(to: .image) } ?? item.supportedContentTypes.firstlet 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)) != nilelse { returnnil }return (file, mime) }}