// 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) import CottonKit import PhotosUI import SwiftUI /// What a row of pictures is of: a character or a place, on a story day or not. struct InkPictureOwner: Equatable { var character: String? = nil var place: String? = nil var day: Int? = nil } /// Pictures to choose from: the photo library, or the camera. enum InkPictureSource { case library, camera } /// What Pictures says, from the `story` line set; pure, so a test reads it. enum InkPictureWords { /// "Picture 2 of 5"; the face (the first of a person or a place, not of a day) also says whose face it is. static func 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 } return InkWords.line("ink.face_label", ["name": name]) + ", " + picture } /// Where a picture goes to move it earlier or later: after which picture, or `start`. static func after(moving at: Int, by: Int, in ids: [String]) -> String? { let to = at + by guard by != 0, ids.indices.contains(at), ids.indices.contains(to) else { return nil } if by < 0 { return to == 0 ? "start" : ids[to - 1] } return ids[to] } } /// A pressed picture, with the row it stands in. struct InkHeldPicture { let picture: StoryPicture let owner: InkPictureOwner let ids: [String] let name: String var 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 @Observable final class InkPictureDesk { var asking: InkPictureOwner? var held: InkHeldPicture? var library = false var camera = false var 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 }] if Camera.isAvailable { acts.append(InkAct(words: InkWords.line("ink.picture_camera")) { [self] in asking = nil target = owner Task { if let refusal = await Camera.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.at let id = held.picture.id var acts: [InkAct] = [] if at > 0, held.owner.day == nil { acts.append(InkAct(words: InkWords.line("ink.picture_face")) { [self] in move(id, after: "start") }) } if let 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) }) } if let 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] in self.held = nil Task { await story.attempt { try await story.shelf.removePicture(id) } await after() } }) return acts } private func move(_ id: String, after: String) { held = nil Task { await story.attempt { try await story.shelf.movePicture(id, after: after) } await self.after() } } private func after() async { await changed() await story.reloadHome() } func pickedFromLibrary(_ chosen: PhotosPickerItem) async { guard let staged = await MediaStaging.stage(chosen) else { story.notice = DockModel.pictureRefused return } 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 = target await story.attempt { let kept = try await CoreMediaCapture(core: story.core).capture(file: url, mime: mime, kind: .photo, filename: url.lastPathComponent) try await story.shelf.addPicture(kept.key, character: owner.character, place: owner.place, day: owner.day) } await after() } } extension View { /// The pictures' panels, the library and the camera, over the whole page. func inkPictures(_ desk: InkPictureDesk) -> some View { modifier(InkPicturePanels(desk: desk)) } } private struct InkPicturePanels: ViewModifier { @Bindable var desk: InkPictureDesk @Environment(\.cottonCapabilities) private var capabilities func body(content: Content) -> some View { content .lookPanel(item: $desk.asking, style: Ink.panel) { owner in InkActsSheet(title: InkWords.line("ink.picture_add"), acts: desk.sources(owner, capabilities: capabilities)) } .lookPanel(item: $desk.held, style: Ink.panel) { held in InkActsSheet(title: held.label, acts: desk.acts(held)) } .photosPicker(isPresented: $desk.library, selection: $desk.item, matching: .images) .onChange(of: desk.item) { _, chosen in guard let chosen else { return } desk.item = nil Task { await desk.pickedFromLibrary(chosen) } } .fullScreenCover(isPresented: $desk.camera) { CameraPicker(onTaken: { url in desk.camera = false Task { await desk.keep(url, mime: "image/jpeg") } }, onCancelled: { desk.camera = false }) } } } /// A row of pictures sideways, then "+". struct InkPictureRow: View { let desk: InkPictureDesk let owner: InkPictureOwner let pictures: [StoryPicture] /// Whose pictures these are, for the face's label. let name: String static let edge: CGFloat = 92 var body: some View { ScrollView(.horizontal) { HStack(spacing: 12) { ForEach(pictures) { picture in let 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 in Button(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. struct InkPictureThumb: View { let key: String var edge: CGFloat = 92 @State private var slot = MediaImageSlot() @Environment(\.cottonCore) private var core @Environment(\.displayScale) private var scale var body: some View { ZStack { Ink.ground if let 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() } } private func load() async { let number = slot.begin(key) guard !key.isEmpty, let core else { slot.finish(.absent, for: key, ask: number) return } slot.finish(await MediaImages.load(from: core, key: key, edge: edge * scale), for: key, ask: number) } } #endif