Cotton code
314 lines · 13.8 KB · SwiftRaw
// A place's map picture: what a slip's `trailing_picture` and a postcard// cover draw for a latitude and its longitude. Copied from the Locations// postcard (`PostcardMap`, `PaperMapFragment`, `PostcardPin`), which went with// the Locations screens; drawn here once for any table whose definition names// a coordinate as its picture.//// A SNAPSHOT, printed onto the paper: MapKit's muted style with every point of// interest left out, drained of half its colour and multiplied onto the// paper, so the streets read as ink on the card. The pin is the one colour,// drawn as a `Shape` in the red ink. Never a live map on a list: thirty live// maps in a scroll view is thirty render loops for a picture nobody pans.//// KEPT, so it draws offline: every snapshot taken is written to this phone's// caches beside the place it shows, and a fragment of any size draws the kept// picture of its place when MapKit cannot be reached. With none kept, the// fragment says so in the media definition's words ("Map not fetched yet")// with the pin on the paper — never a ruled grid that reads as a map// (walker 604bcce6, offline pass).//// Live tiles are for a SHIPPED build alone (`MapPicture.source`): every other// build is screenshotted over invented data, and MapKit prints a real// district under an invented address. Those builds take no snapshot and draw// what an offline phone with none kept draws.import CottonKitimport ImageIOimport MapKitimport SwiftUI#if canImport(UIKit)import UIKit#endif/// A latitude and a longitude drawn as a map fragment with the red pin at its/// centre, at whatever size it is given.public struct MapPicture: View {    private let lat: Double    private let lng: Double    @Environment(\.theme) private var theme    @Environment(\.displayScale) private var displayScale    public init(lat: Double, lng: Double) {        self.lat = lat        self.lng = lng    }    public var body: some View {        GeometryReader { geo in            MapTiles(                request: Self.request(lat: lat, lng: lng, size: geo.size, scale: displayScale, span: Double(MapPictureKnobs.faceMapSpan),                    minimumSide: MapPictureKnobs.faceMapMinimumSide),                takes: Self.source == .tiles)        }        .accessibilityHidden(true)    }    /// Whether this build may take a snapshot.    enum Source: Sendable { case tiles, paper }    /// Tiles only in a packaged Release build; a test host and a preview are    /// paper too.    static func source(variant: String, packaged: Bool) -> Source {        packaged && variant.lowercased() == "release" ? .tiles : .paper    }    /// The running build's answer, asked once.    static let source: Source = {        let facts = BuildFacts.fromBundle()        return source(variant: facts.variant, packaged: facts.packaged)    }()    /// The snapshot a fragment at `size` points asks for, or nil when the size    /// is not a size or the place is off the globe. `span` is the degrees    /// either way the fragment shows (the theme's `face_map_span`): a few    /// streets, so a fragment the size of half a postcard shows a    /// neighbourhood as texture. `minimumSide` is the smallest fragment worth    /// asking for (`face_map_minimum_side`); a layout pass that proposes zero    /// must not start a request.    static func request(lat: Double, lng: Double, size: CGSize, scale: CGFloat, span: Double, minimumSide: CGFloat) -> MapPictureRequest? {        guard size.width.isFinite, size.height.isFinite,            size.width >= minimumSide, size.height >= minimumSide,            (-90...90).contains(lat), (-180...180).contains(lng)        else { return nil }        return MapPictureRequest(            latitude: lat, longitude: lng, span: span,            width: Int(size.width.rounded(.up)), height: Int(size.height.rounded(.up)),            scale: Int(min(3, max(1, scale.rounded(.up)))))    }}/// What a fragment asks MapKit to draw; every field is the cache key, so two/// requests that would draw different pictures never share one.struct MapPictureRequest: Hashable, Sendable {    let latitude: Double    let longitude: Double    let span: Double    let width: Int    let height: Int    let scale: Int    var key: String { place + String(format: "_%dx%d", width, height) }    /// The place at its zoom, whatever the size: what a kept snapshot of    /// another size can stand in for.    var place: String {        String(format: "%.6f,%.6f,%.5f@%d", latitude, longitude, span, scale)    }}/// A map pin: a round head over a point, with the paper showing through a/// hole in the head. The point is the bottom centre of its rect.struct MapPinMark: Shape {    /// Where the head's arc starts and ends, in degrees.    let arcStart: CGFloat    let arcEnd: CGFloat    /// The hole: its offset from the head's centre and its width, as    /// fractions of the head's radius.    let holeOffset: CGFloat    let holeDiameter: CGFloat    /// The pin the theme draws.    init(_ scale: ThemeScale) {        arcStart = MapPictureKnobs.faceMapPinArcStartDegrees        arcEnd = MapPictureKnobs.faceMapPinArcEndDegrees        holeOffset = MapPictureKnobs.faceMapPinHoleOffsetFraction        holeDiameter = MapPictureKnobs.faceMapPinHoleDiameterFraction    }    func path(in rect: CGRect) -> Path {        let radius = rect.width * 0.5        let centre = CGPoint(x: rect.midX, y: rect.minY + radius)        var path = Path()        path.move(to: CGPoint(x: rect.midX, y: rect.maxY))        path.addArc(center: centre, radius: radius, startAngle: .degrees(Double(arcStart)), endAngle: .degrees(Double(arcEnd)), clockwise: false)        path.closeSubpath()        path.addEllipse(in: CGRect(            x: centre.x - radius * holeOffset, y: centre.y - radius * holeOffset,            width: radius * holeDiameter, height: radius * holeDiameter))        return path    }}/// The pin in red ink, its point on the place.struct MapPin: View {    @Environment(\.theme) private var theme    /// The pin's height; nil is the theme's (`face_map_pin_height`).    var height: CGFloat? = nil    var body: some View {        let height = self.height ?? MapPictureKnobs.faceMapPinHeight        MapPinMark(theme.scale)            .fill(theme.print(.red), style: FillStyle(eoFill: true))            .frame(width: height * MapPictureKnobs.faceMapPinWidthFraction, height: height)            .offset(y: -height * 0.5)            .shadow(                color: theme.colors.shadow.color.opacity(MapPictureKnobs.faceMapShadowOpacity), radius: MapPictureKnobs.faceMapShadowRadius,                x: MapPictureKnobs.faceMapShadowOffsetX, y: MapPictureKnobs.faceMapShadowOffsetY)    }}/// The snapshot: the one in memory, else the one kept on this phone, else/// taken (a shipped build, online) and kept. None at all: the words on the/// paper with the pin.private struct MapTiles: View {    @Environment(\.theme) private var theme    @Environment(\.tableDefinitions) private var definitions    let request: MapPictureRequest?    let takes: Bool    @State private var image: UIImage?    @State private var looked = false    var body: some View {        ZStack {            if let image {                Image(uiImage: image)                    .resizable()                    .interpolation(.high)                    .scaledToFill()                    .saturation(0.5)                    .opacity(MapPictureKnobs.faceMapContentOpacity)                    .blendMode(.multiply)            } else if looked, request != nil {                Text(ViewerWords.reading(definitions)?.mapAbsent ?? "")                    .paperMeta(theme.scale.metaSize)                    .multilineTextAlignment(.center)                    .padding(MapPictureKnobs.faceMapAbsentInset)                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottom)                    .accessibilityIdentifier("map-not-fetched")            }            if request != nil { MapPin() }        }        .clipped()        .task(id: request) {            guard let request else { return }            image = MapSnapshots.shared.image(for: request)            if image == nil { image = await MapSnapshots.shared.kept(request) }            if image == nil, takes { image = await MapSnapshots.shared.snapshot(request) }            looked = true        }    }}/// The snapshots taken: in memory for this process, and kept on disk under/// the caches, so scrolling back draws what it drew and an offline phone/// draws what it once saw.@MainActorfinal class MapSnapshots {    static let shared = MapSnapshots()    private let cache = NSCache<NSString, UIImage>()    private static let folder: URL? = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first?        .appendingPathComponent("map-snapshots", isDirectory: true)    func image(for request: MapPictureRequest) -> UIImage? {        cache.object(forKey: request.key as NSString)    }    /// The kept picture of this request's size, else the largest kept of its    /// place — read off the main thread.    func kept(_ request: MapPictureRequest) async -> UIImage? {        guard let folder = Self.folder else { return nil }        let found = await Task.detached(priority: .userInitiated) { () -> UIImage? in            let exact = folder.appendingPathComponent(Self.fileName(request.key))            if let image = Self.decoded(exact, for: request) { return image }            let prefix = Self.fileName(request.place).replacingOccurrences(of: ".png", with: "_")            let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []            let same = names.filter { $0.hasPrefix(prefix) }            let largest = same.max { Self.area($0) < Self.area($1) }            return largest.flatMap { Self.decoded(folder.appendingPathComponent($0), for: request) }        }.value        if let found { cache.setObject(found, forKey: request.key as NSString) }        return found    }    func snapshot(_ request: MapPictureRequest) async -> UIImage? {        let options = MKMapSnapshotter.Options()        options.region = MKCoordinateRegion(            center: CLLocationCoordinate2D(latitude: request.latitude, longitude: request.longitude),            span: MKCoordinateSpan(latitudeDelta: request.span, longitudeDelta: request.span))        options.size = CGSize(width: request.width, height: request.height)        options.preferredConfiguration = MKStandardMapConfiguration(elevationStyle: .flat, emphasisStyle: .muted)        options.pointOfInterestFilter = .excludingAll        options.showsBuildings = false        #if canImport(UIKit)        options.traitCollection = UITraitCollection { traits in            traits.displayScale = CGFloat(request.scale)            traits.userInterfaceStyle = .light        }        #else        options.appearance = NSAppearance(named: .aqua)        #endif        guard let taken = try? await MKMapSnapshotter(options: options).start() else { return nil }        cache.setObject(taken.image, forKey: request.key as NSString)        if let folder = Self.folder {            let image = taken.image            Task.detached(priority: .utility) {                try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)                #if canImport(UIKit)                let data = image.pngData()                #else                let data = image.tiffRepresentation                #endif                try? data?.write(to: folder.appendingPathComponent(Self.fileName(request.key)), options: .atomic)            }        }        return taken.image    }    nonisolated private static func fileName(_ key: String) -> String {        key.replacingOccurrences(of: ",", with: "_").replacingOccurrences(of: "@", with: "s") + ".png"    }    /// A kept file's pixel area, read from its name's `_<w>x<h>`.    /// A kept snapshot decoded at the size it is drawn, never its file read    /// whole (`WholeBodySweepTests`): the largest kept of a place may be far    /// bigger than the slip that draws it.    nonisolated private static func decoded(_ file: URL, for request: MapPictureRequest) -> UIImage? {        guard let source = CGImageSourceCreateWithURL(file as CFURL, nil) else { return nil }        let scale = max(request.scale, 1)        let options: [CFString: Any] = [            kCGImageSourceCreateThumbnailFromImageAlways: true,            kCGImageSourceThumbnailMaxPixelSize: max(request.width, request.height, 1) * scale,        ]        guard let made = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }        return UIImage(cgImage: made, scale: CGFloat(scale), orientation: .up)    }    nonisolated private static func area(_ name: String) -> Int {        guard let size = name.split(separator: "_").last?.split(separator: ".").first else { return 0 }        let sides = size.split(separator: "x").compactMap { Int($0) }        return sides.count == 2 ? sides[0] * sides[1] : 0    }}/// The sizes, counts and timings MapPicture draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum MapPictureKnobs {    static let faceMapAbsentInset: CGFloat = 8    static let faceMapContentOpacity: CGFloat = 0.9    static let faceMapMinimumSide: CGFloat = 24    static let faceMapPinArcEndDegrees: CGFloat = 30    static let faceMapPinArcStartDegrees: CGFloat = 150    static let faceMapPinHeight: CGFloat = 20    static let faceMapPinHoleDiameterFraction: CGFloat = 0.76    static let faceMapPinHoleOffsetFraction: CGFloat = 0.38    static let faceMapPinWidthFraction: CGFloat = 0.7    static let faceMapShadowOffsetX: CGFloat = 0.4    static let faceMapShadowOffsetY: CGFloat = 0.8    static let faceMapShadowOpacity: CGFloat = 0.18    static let faceMapShadowRadius: CGFloat = 0.8    static let faceMapSpan: CGFloat = 0.008}