// 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.importCottonKitimportImageIOimportMapKitimportSwiftUI#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.publicstructMapPicture: View {privatelet lat: Doubleprivatelet lng: Double @Environment(\.theme) privatevar theme @Environment(\.displayScale) privatevar displayScalepublicinit(lat: Double, lng: Double) {self.lat = latself.lng = lng }publicvar body: someView {GeometryReader { geo inMapTiles( 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.enumSource: Sendable { case tiles, paper }/// Tiles only in a packaged Release build; a test host and a preview are/// paper too.staticfunc source(variant: String, packaged: Bool) -> Source { packaged && variant.lowercased() == "release" ? .tiles : .paper }/// The running build's answer, asked once.staticlet 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.staticfunc 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 { returnnil }returnMapPictureRequest( 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.structMapPictureRequest: Hashable, Sendable {let latitude: Doublelet longitude: Doublelet span: Doublelet width: Intlet height: Intlet scale: Intvar 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.structMapPinMark: Shape {/// Where the head's arc starts and ends, in degrees.let arcStart: CGFloatlet arcEnd: CGFloat/// The hole: its offset from the head's centre and its width, as/// fractions of the head's radius.let holeOffset: CGFloatlet 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.5let 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.structMapPin: View { @Environment(\.theme) privatevar theme/// The pin's height; nil is the theme's (`face_map_pin_height`).var height: CGFloat? = nilvar body: someView {let height = self.height ?? MapPictureKnobs.faceMapPinHeightMapPinMark(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.privatestructMapTiles: View { @Environment(\.theme) privatevar theme @Environment(\.tableDefinitions) privatevar definitionslet request: MapPictureRequest?let takes: Bool @State privatevar image: UIImage? @State privatevar looked = falsevar body: someView { ZStack {iflet image {Image(uiImage: image) .resizable() .interpolation(.high) .scaledToFill() .saturation(0.5) .opacity(MapPictureKnobs.faceMapContentOpacity) .blendMode(.multiply) } elseif 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) {guardlet request else { return } image = MapSnapshots.shared.image(for: request)if image == nil { image = awaitMapSnapshots.shared.kept(request) }if image == nil, takes { image = awaitMapSnapshots.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.@MainActorfinalclassMapSnapshots {staticlet shared = MapSnapshots()privatelet cache = NSCache<NSString, UIImage>()privatestaticlet 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? {guardlet folder = Self.folder else { returnnil }let found = awaitTask.detached(priority: .userInitiated) { () -> UIImage? inlet exact = folder.appendingPathComponent(Self.fileName(request.key))iflet 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) } }.valueiflet 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) #endifguardlet taken = try? await MKMapSnapshotter(options: options).start() else { returnnil } cache.setObject(taken.image, forKey: request.key as NSString)iflet folder = Self.folder {let image = taken.imageTask.detached(priority: .utility) {try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) #if canImport(UIKit)let data = image.pngData() #elselet data = image.tiffRepresentation #endiftry? data?.write(to: folder.appendingPathComponent(Self.fileName(request.key)), options: .atomic) } }return taken.image } nonisolated privatestaticfunc 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 privatestaticfunc decoded(_ file: URL, for request: MapPictureRequest) -> UIImage? {guardlet source = CGImageSourceCreateWithURL(file as CFURL, nil) else { returnnil }let scale = max(request.scale, 1)let options: [CFString: Any] = [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: max(request.width, request.height, 1) * scale, ]guardlet made = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { returnnil }return UIImage(cgImage: made, scale: CGFloat(scale), orientation: .up) } nonisolated privatestaticfunc area(_ name: String) -> Int {guardlet size = name.split(separator: "_").last?.split(separator: ".").first else { return0 }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`).enumMapPictureKnobs {staticlet faceMapAbsentInset: CGFloat = 8staticlet faceMapContentOpacity: CGFloat = 0.9staticlet faceMapMinimumSide: CGFloat = 24staticlet faceMapPinArcEndDegrees: CGFloat = 30staticlet faceMapPinArcStartDegrees: CGFloat = 150staticlet faceMapPinHeight: CGFloat = 20staticlet faceMapPinHoleDiameterFraction: CGFloat = 0.76staticlet faceMapPinHoleOffsetFraction: CGFloat = 0.38staticlet faceMapPinWidthFraction: CGFloat = 0.7staticlet faceMapShadowOffsetX: CGFloat = 0.4staticlet faceMapShadowOffsetY: CGFloat = 0.8staticlet faceMapShadowOpacity: CGFloat = 0.18staticlet faceMapShadowRadius: CGFloat = 0.8staticlet faceMapSpan: CGFloat = 0.008}