Cotton code
406 lines · 17.2 KB · SwiftRaw
// A picture in the viewer: pinch and double-tap zoom, a pan while magnified,// and — on a note's picture — a long press that leaves a pin.//// The largest copy on this phone draws at once (it was decoded before the// swipe reached it, `ViewerPreparer`); the page the person is on then asks for// the original, because opening it is the tap that may fetch.import CottonKitimport SwiftUI#if canImport(UIKit)import UIKit#endifstruct ViewerPhotoPage: View {    let item: ViewerItem    let current: Bool    let pins: ViewerPins?    let words: ViewerWords?    @Binding var zoomed: Bool    let onTap: () -> Void    let onFile: (URL) -> Void    @Environment(\.cottonCore) private var core    @Environment(\.theme) private var theme    @Environment(\.tableDefinitions) private var definitions    @State private var image: UIImage?    @State private var refusal: String?    @State private var fetching = false    @State private var threads: [JSONValue] = []    @State private var pending: PinAnchor?    var body: some View {        GeometryReader { geometry in            ZStack {                if let image {                    zoom(image)                    if pins != nil, !zoomed { markers(in: geometry.size, image: image) }                } else if let refusal {                    // Not here, and the fetch did not bring it: the slip over                    // the dimmed preview, with Fetch.                    AbsentOverPoster(slip: AbsentSlip(                        kind: .photo, name: item.title, words: words,                        fetching: fetching, onFetch: { Task { await showOriginal() } })                    ) { blur }                } else {                    blur                }                if let pending, let pins {                    ViewerPinComposer(anchor: pending, pins: pins, words: words) { filed in                        self.pending = nil                        if filed { Task { await readThreads() } }                    }                    .frame(maxHeight: .infinity, alignment: .bottom)                }            }            .frame(width: geometry.size.width, height: geometry.size.height)        }        .task(id: item.key) { await showLargestHere() }        .task(id: current) { if current { await showOriginal() } }        .task(id: pins?.recordId) { await readThreads() }    }    @ViewBuilder private var blur: some View {        if let blur = PhotosBlur.image(base64: item.preview) {            Image(uiImage: blur).resizable().scaledToFit().blur(radius: ViewerKnobs.blurRadius)        }    }    @ViewBuilder private func zoom(_ image: UIImage) -> some View {        #if canImport(UIKit)        ViewerZoomView(            image: image, zoomed: $zoomed, onTap: onTap,            onPress: pins == nil ? nil : { x, y in                pending = PinAnchor(kind: item.record?.table ?? "photo", id: item.record?.id ?? item.id, x: x, y: y)            })            .accessibilityLabel(item.title ?? "")            .accessibilityHint(pins == nil ? "" : (words?.pinPress ?? ""))            .accessibilityIdentifier("viewer-photo")        #else        Image(nsImage: image).resizable().scaledToFit()            .onTapGesture(perform: onTap)            .accessibilityIdentifier("viewer-photo")        #endif    }    /// The pins already on this picture, numbered in comment order.    @ViewBuilder private func markers(in page: CGSize, image: UIImage) -> some View {        let fitted = ViewerGeometry.fit(image.size, in: page)        let attachment = RecordAttachment(kind: item.record?.table ?? "photo", id: item.record?.id ?? item.id, position: 0)        ZStack(alignment: .topLeading) {            ForEach(Array(RecordPins.markers(threads, on: attachment).enumerated()), id: \.offset) { _, marker in                PinMarker(pin: marker, width: fitted.width, height: fitted.height, onTap: nil)            }            if let pending {                Circle()                    .fill(theme.colors.accent.color)                    .frame(width: ViewerKnobs.pinMark, height: ViewerKnobs.pinMark)                    .position(x: CGFloat(pending.x) * fitted.width, y: CGFloat(pending.y) * fitted.height)                    .allowsHitTesting(false)            }        }        .frame(width: fitted.width, height: fitted.height)        .allowsHitTesting(false)    }    // MARK: - The bytes    private var pixels: Int { ViewerGeometry.screenPixels }    /// The largest copy on this phone, never a fetch: what a swipe lands on.    private func showLargestHere() async {        guard let key = item.key, let core else { return }        if let kept = MediaImageCache.shared.picture(key: key, maxPixel: pixels) {            image = kept.image            return        }        let media = PhotosMediaSource(core: core)        guard let answer = await media.answer(for: key, tier: .largest) else { return }        let pixels = pixels        let made = await Task.detached(priority: .userInitiated) {            PhotosImageFile.image(key: key, rung: answer.rung, atPath: answer.path, maxPixel: pixels)        }.value        if image == nil, let made { image = made }        if answer.rung == .original { onFile(URL(fileURLWithPath: answer.path)) }    }    /// The original, fetched if it is not here: the person is looking at it.    private func showOriginal() async {        guard let key = item.key, let core, !fetching else { return }        let media = PhotosMediaSource(core: core)        fetching = true        defer { fetching = false }        do {            let path = try await media.ensure(key)            await media.viewed(key)            onFile(URL(fileURLWithPath: path))            let pixels = pixels            let made = await Task.detached(priority: .userInitiated) {                PhotosImageFile.image(key: key, rung: .original, atPath: path, maxPixel: pixels)            }.value            if let made { image = made; refusal = nil } else if image == nil { refusal = words?.absent }        } catch {            // The crate's own sentence, said as it came, when nothing of the            // picture is here to draw.            if image == nil { refusal = (error as? CottonCallError)?.message ?? words?.absent }        }    }    private func readThreads() async {        guard let pins, let core else { return }        guard let answer = try? await core.callJSON(            CottonMethod.readRecord, RecordReadRequest(kind: pins.recordKind, id: pins.recordId))        else { return }        threads = answer.list("threads")    }}/// Decodes the pictures either side of the one on screen at screen size, so/// a swipe lands on a picture already drawn. Never fetches: a neighbour is not/// something the person asked for yet.@MainActorenum ViewerPreparer {    private static var running: Task<Void, Never>?    static func neighbours(of index: Int, in count: Int) -> [Int] {        [index + 1, index - 1].filter { $0 >= 0 && $0 < count }    }    static func prepare(around index: Int, in items: [ViewerItem], core: (any CottonCalling)?) {        guard let core else { return }        running?.cancel()        let keys = neighbours(of: index, in: items.count).compactMap { items[$0].kind == .photo ? items[$0].key : items[$0].poster }        let pixels = ViewerGeometry.screenPixels        running = Task.detached(priority: .utility) {            let media = PhotosMediaSource(core: core)            for key in keys {                if Task.isCancelled { return }                if MediaImageCache.shared.picture(key: key, maxPixel: pixels) != nil { continue }                guard let answer = await media.answer(for: key, tier: .largest) else { continue }                _ = PhotosImageFile.image(key: key, rung: answer.rung, atPath: answer.path, maxPixel: pixels)            }        }    }}enum ViewerGeometry {    /// The screen's longest side in pixels: what a picture is decoded to.    @MainActor static var screenPixels: Int {        #if canImport(UIKit)        let bounds = UIScreen.main.bounds        return Int(max(bounds.width, bounds.height) * UIScreen.main.scale)        #else        return 2560        #endif    }    /// `size` fitted inside `page`, its own shape kept.    static func fit(_ size: CGSize, in page: CGSize) -> CGSize {        guard size.width > 0, size.height > 0, page.width > 0, page.height > 0 else { return page }        let scale = min(page.width / size.width, page.height / size.height)        return CGSize(width: size.width * scale, height: size.height * scale)    }}#if canImport(UIKit)/// The scroll view that says when its own size changes: SwiftUI hands it a/// size only after `makeUIView`, so the picture is fitted then, and again on/// a rotation — never from the zero size it is born with.final class ViewerZoomScroll: UIScrollView {    var resized: ((UIScrollView) -> Void)?    private var fittedTo: CGSize = .zero    override func layoutSubviews() {        super.layoutSubviews()        guard bounds.size != fittedTo, bounds.width > 0, bounds.height > 0 else { return }        fittedTo = bounds.size        resized?(self)    }}/// The zoom: UIKit's scroll view, which is the pinch, the pan and the/// bounce people know from every photo viewer on the phone.struct ViewerZoomView: UIViewRepresentable {    let image: UIImage    @Binding var zoomed: Bool    let onTap: () -> Void    /// A long press at a point, in fractions of the picture; nil offers none.    let onPress: ((Double, Double) -> Void)?    func makeCoordinator() -> Coordinator { Coordinator(self) }    func makeUIView(context: Context) -> UIScrollView {        let scroll = ViewerZoomScroll()        scroll.resized = { [weak coordinator = context.coordinator] scroll in coordinator?.layout(scroll) }        scroll.delegate = context.coordinator        scroll.minimumZoomScale = 1        scroll.maximumZoomScale = ViewerKnobs.maxZoom        scroll.showsVerticalScrollIndicator = false        scroll.showsHorizontalScrollIndicator = false        scroll.contentInsetAdjustmentBehavior = .never        scroll.backgroundColor = .clear        scroll.decelerationRate = .fast        let view = UIImageView(image: image)        view.contentMode = .scaleAspectFit        view.isUserInteractionEnabled = true        scroll.addSubview(view)        context.coordinator.imageView = view        let double = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.doubleTapped(_:)))        double.numberOfTapsRequired = 2        scroll.addGestureRecognizer(double)        let single = UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.tapped))        single.require(toFail: double)        scroll.addGestureRecognizer(single)        let press = UILongPressGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.pressed(_:)))        scroll.addGestureRecognizer(press)        return scroll    }    func updateUIView(_ scroll: UIScrollView, context: Context) {        context.coordinator.parent = self        if context.coordinator.imageView?.image !== image {            context.coordinator.imageView?.image = image            context.coordinator.layout(scroll)        }        if !zoomed, scroll.zoomScale > 1 { scroll.setZoomScale(1, animated: true) }    }    func sizeThatFits(_ proposal: ProposedViewSize, uiView: UIScrollView, context: Context) -> CGSize? {        nil    }    final class Coordinator: NSObject, UIScrollViewDelegate {        var parent: ViewerZoomView        weak var imageView: UIImageView?        init(_ parent: ViewerZoomView) { self.parent = parent }        func viewForZooming(in scrollView: UIScrollView) -> UIView? { imageView }        /// The picture fitted to the page and centred, at zoom 1.        func layout(_ scroll: UIScrollView) {            guard let view = imageView, let image = view.image else { return }            let fitted = ViewerGeometry.fit(image.size, in: scroll.bounds.size)            scroll.zoomScale = 1            view.frame = CGRect(origin: .zero, size: fitted)            scroll.contentSize = fitted            centre(scroll)        }        func centre(_ scroll: UIScrollView) {            guard let view = imageView else { return }            let x = max(0, (scroll.bounds.width - view.frame.width) / 2)            let y = max(0, (scroll.bounds.height - view.frame.height) / 2)            scroll.contentInset = UIEdgeInsets(top: y, left: x, bottom: y, right: x)        }        func scrollViewDidZoom(_ scroll: UIScrollView) {            centre(scroll)            let now = scroll.zoomScale > 1.01            if parent.zoomed != now { parent.zoomed = now }        }        @objc func tapped() { parent.onTap() }        @objc func doubleTapped(_ recogniser: UITapGestureRecognizer) {            guard let scroll = recogniser.view as? UIScrollView, let view = imageView else { return }            if scroll.zoomScale > 1 {                scroll.setZoomScale(1, animated: true)            } else {                let point = recogniser.location(in: view)                let scale = ViewerKnobs.doubleTapZoom                let size = CGSize(width: scroll.bounds.width / scale, height: scroll.bounds.height / scale)                scroll.zoom(to: CGRect(x: point.x - size.width / 2, y: point.y - size.height / 2, width: size.width, height: size.height), animated: true)            }        }        @objc func pressed(_ recogniser: UILongPressGestureRecognizer) {            guard recogniser.state == .began, let onPress = parent.onPress, let view = imageView else { return }            let point = recogniser.location(in: view)            let bounds = view.bounds            guard bounds.contains(point), bounds.width > 0, bounds.height > 0 else { return }            UIImpactFeedbackGenerator(style: .medium).impactOccurred()            onPress(Double(point.x / bounds.width), Double(point.y / bounds.height))        }    }}#endif/// Leaving a pin: a comment filed on the note with the point it was pressed/// at — the ordinary `create_comment` on the ordinary write rail.struct ViewerPinComposer: View {    let anchor: PinAnchor    let pins: ViewerPins    let words: ViewerWords?    let done: (Bool) -> Void    @Environment(\.cottonCore) private var core    @Environment(\.theme) private var theme    @State private var text = ""    @State private var saving = false    @State private var refusal: String?    @FocusState private var focused: Bool    var body: some View {        VStack(alignment: .trailing, spacing: ViewerKnobs.chromeGap) {            Text(words?.pinHint ?? "")                .font(theme.type.interface(ViewerKnobs.positionSize))                .foregroundStyle(theme.colors.ink.opacity(ViewerKnobs.quiet))                .frame(maxWidth: .infinity, alignment: .leading)            TextField(words?.pinPlaceholder ?? "", text: $text, axis: .vertical)                .font(theme.type.interface(ViewerKnobs.captionSize))                .foregroundStyle(theme.colors.ink.color)                .focused($focused)                .lineLimit(2...6)                .accessibilityIdentifier("note-pin-input")            if let refusal {                Text(refusal)                    .font(theme.type.interface(ViewerKnobs.positionSize))                    .foregroundStyle(theme.colors.accent.color)                    .frame(maxWidth: .infinity, alignment: .leading)                    .accessibilityIdentifier("note-pin-refusal")            }            HStack(spacing: ViewerKnobs.chromeInset) {                Button(words?.cancel ?? "") { done(false) }                    .foregroundStyle(theme.colors.ink.color)                Button(saving ? (words?.saving ?? "") : (words?.save ?? "")) { Task { await save() } }                    .foregroundStyle(theme.colors.accent.color)                    // A pin with nothing written on it is a dot the next                    // reader cannot answer.                    .disabled(saving || text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)                    .accessibilityIdentifier("note-pin-save")            }            .font(theme.type.interface(ViewerKnobs.captionSize, weight: .semibold))        }        .padding(ViewerKnobs.chromeInset)        .background(theme.colors.groundElevated.color.ignoresSafeArea(edges: .bottom))        .onAppear { focused = true }    }    private func save() async {        guard let core, !saving else { return }        let body = text.trimmingCharacters(in: .whitespacesAndNewlines)        guard !body.isEmpty else { return }        saving = true        defer { saving = false }        do {            _ = try await core.call(                CottonMethod.write,                WriteRequest(                    tool: RecordExtrasTool.createComment,                    args: .object([                        "recordKind": .string(pins.recordKind),                        "recordId": .string(pins.recordId),                        "body": .string(body),                        "anchor": anchor.json,                    ])),                as: WriteAnswer.self)            done(true)        } catch {            // The words stay in the field: a refused save that emptied it            // would take the sentence away with the attempt.            refusal = (error as? CottonCallError)?.message ?? CottonStrings.somethingWentWrong        }    }}