// The three sources an editor offers a picture or a file from — the camera, // the photo library, the files — presented once, so the photo and file // column's editor and a long text's attach offer the same three the same way // (`PictureSources.swift` holds the camera and the staging they share). // // Whatever is picked arrives as an `AttachmentSource`: a file staged in the // temporary folder, which the receiver deletes once it is kept. Nothing here // keeps or writes anything — the editor hands the source on. import CottonKit import PhotosUI import SwiftUI import UniformTypeIdentifiers /// Which of the sources is open, one at a time. struct AttachmentSourceState: Equatable { var library = false var files = false var camera = false var isOpen: Bool { library || files || camera } /// The most the library hands over at once where it takes several. static let mostAtOnce = 20 } /// The words each source is offered with. enum AttachmentSourceWords { static let camera = "Camera" static let library = "Library" static let files = "Files" static var unreadablePhoto: String { ShellLines.line("editing", "attachment.unreadable_photo") } static var unreadableFile: String { ShellLines.line("editing", "attachment.unreadable_file") } } extension View { /// Presents the sources `state` opens. `photosOnly` keeps the library to /// pictures and the files to images (a photo column); otherwise the /// library offers films too and the files anything. /// `several` lets the library hand over more than one at a time (the /// box's "Choose photos"), each arriving as its own source. func attachmentSources( _ state: Binding, photosOnly: Bool, several: Bool = false, onPicked: @escaping (AttachmentSource) -> Void, onRefused: @escaping (String) -> Void, onCancelled: @escaping () -> Void = {} ) -> some View { modifier( AttachmentSourcesModifier( state: state, photosOnly: photosOnly, several: several, onPicked: onPicked, onRefused: onRefused, onCancelled: onCancelled)) } } private struct AttachmentSourcesModifier: ViewModifier { @Binding var state: AttachmentSourceState let photosOnly: Bool let several: Bool let onPicked: (AttachmentSource) -> Void let onRefused: (String) -> Void let onCancelled: () -> Void @State private var libraryItems: [PhotosPickerItem] = [] /// Something was picked since the sources last opened. @State private var picked = false func body(content: Content) -> some View { content .photosPicker( isPresented: $state.library, selection: $libraryItems, maxSelectionCount: several ? AttachmentSourceState.mostAtOnce : 1, matching: photosOnly ? .images : .any(of: [.images, .videos])) .onChange(of: libraryItems) { _, items in guard !items.isEmpty else { return } picked = true libraryItems = [] // In the order they were picked, one after another. Task { for item in items { await stage(item) } } } .onChange(of: state.isOpen) { _, open in // Closed with nothing picked. The pick's own change lands in // the same update when there was one, so a yield lets it. guard !open else { picked = false return } Task { await Task.yield() if !picked { onCancelled() } } } .fileImporter( isPresented: $state.files, allowedContentTypes: photosOnly ? [.image] : [.item], allowsMultipleSelection: false ) { result in guard case .success(let urls) = result, let url = urls.first else { return } picked = true imported(url) } .fullScreenCover(isPresented: $state.camera) { CameraPicker( onTaken: { url in picked = true state.camera = false onPicked( AttachmentSource( url: url, mime: "image/jpeg", kind: .photo, filename: url.lastPathComponent, origin: .camera)) }, onCancelled: { state.camera = false } ) } } private func stage(_ item: PhotosPickerItem) async { guard let staged = await MediaStaging.stage(item) else { onRefused(AttachmentSourceWords.unreadablePhoto) return } onPicked( AttachmentSource( url: staged.url, mime: staged.mime, kind: RecordAttachments.captureKind(UTType(mimeType: staged.mime)), filename: staged.url.lastPathComponent, origin: .library)) } /// A file from the files app is only readable inside its security scope, /// so it is copied out before anything reads it. private func imported(_ url: URL) { let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } let copy = FileManager.default.temporaryDirectory .appendingPathComponent("imported-\(UUID().uuidString)-\(url.lastPathComponent)") do { try FileManager.default.copyItem(at: url, to: copy) } catch { onRefused(AttachmentSourceWords.unreadableFile) return } let type = UTType(filenameExtension: url.pathExtension) onPicked( AttachmentSource( url: copy, mime: type?.preferredMIMEType ?? "application/octet-stream", kind: RecordAttachments.captureKind(type), filename: url.lastPathComponent, origin: .files)) } }