// Pictures (CONTRACT.md 5; ink.html's faces): a row of a character's, a// place's or a story day's pictures, square and ruled thin in ink, each laid// on the sheet by multiply so it reads as ink on paper, then "+" to add one// from the photo library or the camera. A picture is kept in the store the// way every picture on this phone is (`capture.media`), then added to what// it is of (`story.picture.add`). The first picture of a character or a// place (not of a day) is its face; the core keeps the face in step after// every add, move and remove. Press and hold a picture: make it the face,// move it earlier or later, or remove it.#if os(iOS)importCottonKitimportPhotosUIimportSwiftUI/// What a row of pictures is of: a character or a place, on a story day or not.structInkPictureOwner: Equatable {var character: String? = nilvar place: String? = nilvar day: Int? = nil}/// Pictures to choose from: the photo library, or the camera.enumInkPictureSource { case library, camera }/// What Pictures says, from the `story` line set; pure, so a test reads it.enumInkPictureWords {/// "Picture 2 of 5"; the face (the first of a person or a place, not of a day) also says whose face it is.staticfunc label(at: Int, of count: Int, name: String, day: Bool) -> String {let picture = InkWords.line("ink.picture_label", ["n": String(at + 1), "of": String(count)])guard at == 0, !day, !name.isEmpty else { return picture }returnInkWords.line("ink.face_label", ["name": name]) + ", " + picture }/// Where a picture goes to move it earlier or later: after which picture, or `start`.staticfunc after(moving at: Int, by: Int, in ids: [String]) -> String? {let to = at + byguard by != 0, ids.indices.contains(at), ids.indices.contains(to) else { returnnil }if by < 0 { return to == 0 ? "start" : ids[to - 1] }return ids[to] }}/// A pressed picture, with the row it stands in.structInkHeldPicture {let picture: StoryPicturelet owner: InkPictureOwnerlet ids: [String]let name: Stringvar at: Int { ids.firstIndex(of: picture.id) ?? 0 }var label: String { InkPictureWords.label(at: at, of: ids.count, name: name, day: owner.day != nil) }}/// The pictures of one page: which row's "+" was tapped, which picture is/// held, the library and the camera. The page raises its panels over the/// whole screen (`inkPictures`), so a row only draws.@MainActor @ObservablefinalclassInkPictureDesk {var asking: InkPictureOwner?var held: InkHeldPicture?var library = falsevar camera = falsevar item: PhotosPickerItem?/// What the library's or the camera's picture is added to. @ObservationIgnored var target = InkPictureOwner() @ObservationIgnored let story: InkStory/// Read the page again after a change; the page sets it once it stands. @ObservationIgnored var changed: () async -> Void = {}init(story: InkStory) {self.story = story }/// The photo library, and the camera where this phone has one.func sources(_ owner: InkPictureOwner, capabilities: any CapabilityAuthority) -> [InkAct] {var acts = [InkAct(words: InkWords.line("ink.picture_library")) { [self] in asking = nil target = owner library = true }]ifCamera.isAvailable { acts.append(InkAct(words: InkWords.line("ink.picture_camera")) { [self] in asking = nil target = ownerTask {iflet refusal = awaitCamera.refusal(capabilities) { story.notice = refusal } else { camera = true } } }) }return acts }/// A picture's acts, in order: make it the face, move earlier, move later, remove.func acts(_ held: InkHeldPicture) -> [InkAct] {let at = held.atlet id = held.picture.idvar acts: [InkAct] = []if at > 0, held.owner.day == nil { acts.append(InkAct(words: InkWords.line("ink.picture_face")) { [self] in move(id, after: "start") }) }iflet after = InkPictureWords.after(moving: at, by: -1, in: held.ids) { acts.append(InkAct(words: InkWords.line("ink.picture_earlier")) { [self] in move(id, after: after) }) }iflet after = InkPictureWords.after(moving: at, by: 1, in: held.ids) { acts.append(InkAct(words: InkWords.line("ink.picture_later")) { [self] in move(id, after: after) }) } acts.append(InkAct(words: InkWords.line("ink.picture_remove"), quiet: true) { [self] inself.held = nilTask {await story.attempt { tryawait story.shelf.removePicture(id) }await after() } })return acts }privatefunc move(_ id: String, after: String) { held = nilTask {await story.attempt { tryawait story.shelf.movePicture(id, after: after) }awaitself.after() } }privatefunc after() async {await changed()await story.reloadHome() }func pickedFromLibrary(_ chosen: PhotosPickerItem) async {guardlet staged = awaitMediaStaging.stage(chosen) else { story.notice = DockModel.pictureRefusedreturn }await keep(staged.url, mime: staged.mime) }/// The staged file into the store, then onto what it is of; the staged copy goes after.func keep(_ url: URL, mime: String) async {defer { try? FileManager.default.removeItem(at: url) }let owner = targetawait story.attempt {let kept = tryawaitCoreMediaCapture(core: story.core).capture(file: url, mime: mime, kind: .photo, filename: url.lastPathComponent)tryawait story.shelf.addPicture(kept.key, character: owner.character, place: owner.place, day: owner.day) }await after() }}extensionView {/// The pictures' panels, the library and the camera, over the whole page.func inkPictures(_ desk: InkPictureDesk) -> someView { modifier(InkPicturePanels(desk: desk)) }}privatestructInkPicturePanels: ViewModifier { @Bindable var desk: InkPictureDesk @Environment(\.cottonCapabilities) privatevar capabilitiesfunc body(content: Content) -> someView { content .lookPanel(item: $desk.asking, style: Ink.panel) { owner inInkActsSheet(title: InkWords.line("ink.picture_add"), acts: desk.sources(owner, capabilities: capabilities)) } .lookPanel(item: $desk.held, style: Ink.panel) { held inInkActsSheet(title: held.label, acts: desk.acts(held)) } .photosPicker(isPresented: $desk.library, selection: $desk.item, matching: .images) .onChange(of: desk.item) { _, chosen inguardlet chosen else { return } desk.item = nilTask { await desk.pickedFromLibrary(chosen) } } .fullScreenCover(isPresented: $desk.camera) {CameraPicker(onTaken: { url in desk.camera = falseTask { await desk.keep(url, mime: "image/jpeg") } }, onCancelled: { desk.camera = false }) } }}/// A row of pictures sideways, then "+".structInkPictureRow: View {let desk: InkPictureDesklet owner: InkPictureOwnerlet pictures: [StoryPicture]/// Whose pictures these are, for the face's label.let name: Stringstaticlet edge: CGFloat = 92var body: someView {ScrollView(.horizontal) { HStack(spacing: 12) {ForEach(pictures) { picture inlet held = InkHeldPicture(picture: picture, owner: owner, ids: pictures.map(\.id), name: name)InkPictureThumb(key: picture.picture, edge: Self.edge) .contentShape(Rectangle()) .onLongPressGesture(minimumDuration: 0.45) { desk.held = held } .accessibilityElement(children: .ignore) .accessibilityLabel(held.label) .accessibilityAddTraits(.isImage) .accessibilityActions {ForEach(desk.acts(held)) { act inButton(act.words, action: act.run) } } }Button { desk.asking = owner } label: {Image(systemName: "plus") .font(.system(size: 22, weight: .regular)) .foregroundStyle(Ink.ink) .frame(width: Self.edge, height: Self.edge) .overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(Ink.rule, lineWidth: 1)) .contentShape(Rectangle()) } .buttonStyle(InkPress()) .accessibilityLabel(InkWords.line("ink.picture_add")) } .padding(.horizontal, Ink.gutter) .padding(.vertical, 2) } .scrollIndicators(.hidden) .padding(.horizontal, -Ink.gutter) }}/// One picture: a square ruled thin in ink, the picture laid in by multiply.structInkPictureThumb: View {let key: Stringvar edge: CGFloat = 92 @State privatevar slot = MediaImageSlot() @Environment(\.cottonCore) privatevar core @Environment(\.displayScale) privatevar scalevar body: someView { ZStack {Ink.groundiflet image = slot.image {Image(uiImage: image) .resizable() .scaledToFill() .blendMode(.multiply) } } .frame(width: edge, height: edge) .clipShape(RoundedRectangle(cornerRadius: 4)) .overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(Ink.ink, lineWidth: Ink.stroke)) .task(id: key) { await load() } .onMediaArrival {guard !slot.isReady else { return }await load() } }privatefunc load() async {let number = slot.begin(key)guard !key.isEmpty, let core else { slot.finish(.absent, for: key, ask: number)return } slot.finish(awaitMediaImages.load(from: core, key: key, edge: edge * scale), for: key, ask: number) }}#endif