// Home's fan's page pictures, as bytes and drawing (lane fan, stage 2;// architect's ruling 2–3, 14 Oct 2026). The bookkeeping — what is kept, what// is stale, what is decoded, what is drawn next — is `PagePictureLedger`.//// A picture is the first screen of a tile's page:// - drawn OFF SCREEN by `PagePainter` while the window is still — after// `StillWindow.quiet` with no touch (`TouchWatch`), the fan at// rest — one tile at a time, nearest the settled tile first; the page is// mounted in a host beside the window's right edge, given the time a first// read takes, drawn, and let go;// - taken from the LIVE page itself once it has stood still on screen// (`capture`), in the same still window, so what the turning fan shows is// what was just on screen.// Every picture keeps its alpha in PNG; an opaque image can use JPEG.// The settled tile's neighbours// within `fan_picture_reach` are kept decoded, ready to show. Pictures are// drawn in the standard range, a byte a channel: the default format on a// wide-colour screen is extended range, eight bytes a pixel, and its JPEG// resamples every pixel through half floats (fanperf, try4).//// A finger landing on the fan costs nothing: the live page is not drawn// again but snapshotted by the render server (`snapshot`), and that view is// shown in its place until the fan leaves the tile — one at a time, never// kept as a picture (fan3 part 0: a 3× image drawn and JPEG'd on every// touch-down held 14.7 MB a turn)./// When the live page's touch-down snapshot (`PagePictures.grab`) goes.enumFanSnapshotRule {/// Whether the snapshot of tile `grabbed` still stands: while the fan/// moves, or until its tile's live page is drawn again. A touch that ends/// with no turn — a tap on the settled tile — leaves the fan at rest on/// its drawn live page, and the snapshot goes (zoomframe 15 Oct: a tap on/// the settled tile left the record before it drawn over the page).staticfunc holds(grabbed: String?, moving: Bool, live: Bool, drawn: String?) -> Bool {guardlet grabbed else { returnfalse }return moving || !live || drawn != grabbed }}#if os(iOS)importCottonKitimportImageIOimport OSLogimportSwiftUIimport UIKit@MainActor@ObservablefinalclassPagePictures { @ObservationIgnored private(set) var ledger = PagePictureLedger()/// The pictures kept decoded, by tile.private(set) var decoded: [String: UIImage] = [:]/// The live page as a finger landed on the fan: shown in its place until/// the fan leaves its tile or the live page is back.private(set) var grabbed: Grabbed?structGrabbed {let key: Stringlet view: UIView } @ObservationIgnored privatevar data: [String: Data] = [:]/// The tiles whose picture was drawn with their page below its top. @ObservationIgnored privatevar scrolled: Set<String> = [] @ObservationIgnored privatevar window: Set<String> = []/// The one decoding under way (`refocus`). @ObservationIgnored privatevar focusing: Task<Void, Never>? @ObservationIgnored var quality: Double @ObservationIgnored var reach: Int/// Pixels a point every picture is drawn at; a decoded picture takes it/// back, so a picture's size is in the page's points. @ObservationIgnored var scale: Double/// The table definitions read now (`TableDefinitions.stamp`): a picture/// drawn under others is kept stale. @ObservationIgnored privatevar definitions: Int?init(quality: Double, reach: Int, scale: Double) {self.quality = qualityself.reach = reachself.scale = scale }/// Bytes kept compressed, and decoded (four bytes a pixel).var keptBytes: Int { ledger.bytes }var decodedBytes: Int { decoded.values.reduce(0) { $0 + Int($1.size.width * $1.scale * $1.size.height * $1.scale) * 4 } }/// One log line (subsystem `com.cottondb.fan`, category `pictures`) once/// every tile has its picture: the memory the pictures hold.func report(tiles: Int) {let line = "pictures: \(tiles) tiles, \(ledger.entries.count) kept, \(keptBytes / 1024) KB compressed, " + "\(decoded.count) decoded, \(decodedBytes / 1024) KB decoded"Self.log.notice("\(line, privacy: .public)") }privatestaticlet log = Logger(subsystem: "com.cottondb.fan", category: "pictures")func needsDrawing(_ key: String) -> Bool { ledger.needsDrawing(key) }/// The next page to paint: within `PagePictures.paintReach` of the/// settled tile, nearest first. Only the pages a turn reaches next are/// mounted off screen — each mount reads its list, and painting every tile/// at launch held the shared read pool 3–6 s a list on the owner's copy/// (import, devices, everything, bin; architect 16 Oct 2026/// 22:52 IST: launch reads only what the shown page needs; readpool).func next(of keys: [String], settled: Int, skipping: Set<String>) -> String? { ledger.next(of: keys, settled: settled, skipping: skipping, reach: Self.paintReach) }/// How far either side of the settled tile pages are painted ahead.staticlet paintReach = 2/// Keeps `image` as tile `key`'s picture, replacing the one before only/// now that it is drawn. The JPEG is made off the main thread./// `scrolled`: the page stood below its top when it was drawn;/// `definitions`, the table definitions it was drawn under.func keep(_ image: UIImage, for key: String, families: Set<ScreenFamily>?, scrolled: Bool = false, definitions: Int? = nil) async {let quality = qualityguardlet bytes = awaitTask.detached(priority: .utility, operation: {// A page is bare on the window's ground. JPEG would flatten its// clear pixels; only an image with no alpha can use JPEG.switch image.cgImage?.alphaInfo {case .some(.none), .some(.noneSkipFirst), .some(.noneSkipLast): return image.jpegData(compressionQuality: quality)default: return image.pngData() } }).value else { return } data[key] = bytesif scrolled { self.scrolled.insert(key) } else { self.scrolled.remove(key) } ledger.kept(key, bytes: bytes.count, families: families, size: image.size, definitions: definitions, current: self.definitions)if window.contains(key) { decoded[key] = image } }/// The live page snapshotted at the instant a finger lands: shown at/// once in its place, so the swap is the page itself, pixel for pixel./// The one before goes.func grab(_ view: UIView, for key: String) { grabbed = Grabbed(key: key, view: view) }/// The snapshot is no longer shown: the fan left its tile, or the live/// page is back.func letGo() { if grabbed != nil { grabbed = nil } }/// The pictures of pages drawn below their top go, and are drawn again:/// a switch forgets where the database's pages were left, so each draws/// at rest and a scrolled picture is of no page it will show (292, walker291:/// Me's page stood ~70 pt down, its head under the island, in the first/// frame after a switch to Tinmen).func dropScrolled() {for key in scrolled { data[key] = nil decoded[key] = nil ledger.invalidate(key: key) } scrolled = [] }func invalidate(_ moved: [ScreenFamily]) { ledger.invalidate(moved) }func invalidate(key: String) { ledger.invalidate(key: key) }/// The table definitions read now: every picture drawn under others is stale.func invalidate(definitions stamp: Int) { definitions = stamp ledger.invalidate(definitions: stamp) }func resized(to size: CGSize) { ledger.resized(to: size) }/// The tiles on Home now: the others' pictures go.func keepOnly(_ keys: [String]) {let keep = Set(keys) ledger.keepOnly(keep) data = data.filter { keep.contains($0.key) } decoded = decoded.filter { keep.contains($0.key) }iflet grabbed, !keep.contains(grabbed.key) { letGo() } }/// The fan is heading for, or rests on, `settled`: every decoded picture/// outside its reach goes at once, then the one decoding before is/// stopped and its own and its neighbours' are decoded. One decoding at a/// time: a fling changes its heading a dozen times, and each decoding/// left running held a picture of its own (fan3 leak, 15 Oct).func refocus(keys: [String], settled: Int) { evict(keys: keys, settled: settled) focusing?.cancel() focusing = Task { await focus(keys: keys, settled: settled) } }/// The decoding under way has finished (or was stopped).func decodingDone() async { await focusing?.value }/// Another database is shown: every decoded picture goes, its bytes kept.func letDecodedGo() { focusing?.cancel() letGo() window = []if !decoded.isEmpty { decoded = [:] } }/// The decoded pictures outside `settled` ± reach go: only their/// compressed bytes are kept (fan brief; fanperf2 15 Oct: 139 decoded/// pictures kept alive over 100 turns on iOS 26.5, 467 MB).func evict(keys: [String], settled: Int) {let order = PagePictureLedger.decodeOrder(around: settled, count: keys.count, reach: reach) window = Set(order.map { keys[$0] })if decoded.keys.contains(where: { !window.contains($0) }) { decoded = decoded.filter { window.contains($0.key) } } }/// Decodes the settled tile's picture first, then its neighbours'.func focus(keys: [String], settled: Int) async { evict(keys: keys, settled: settled)let order = PagePictureLedger.decodeOrder(around: settled, count: keys.count, reach: reach)let scale = scalefor key in order.map({ keys[$0] }) where decoded[key] == nil {guard !Task.isCancelled else { return }guardlet bytes = data[key],let image = awaitTask.detached(priority: .userInitiated, operation: { Self.decode(bytes, scale: scale) }).valueelse { continue }if !Task.isCancelled, window.contains(key), data[key] == bytes { decoded[key] = image } } }/// A compressed picture decoded into the app's own bitmap, nothing/// cached beside it: its pixels live exactly as long as the image. Not/// `UIImage(data:)` with `byPreparingForDisplay()`: the system kept a/// decoded copy past the image on iOS 26.5 (fanperf2, 15 Oct: CG image/// regions 39 → 178 over 100 turns while the fan held 8). nonisolated staticfunc decode(_ bytes: Data, scale: Double) -> UIImage? {let options = [kCGImageSourceShouldCache: false] as CFDictionaryguardlet source = CGImageSourceCreateWithData(bytes as CFData, options),let compressed = CGImageSourceCreateImageAtIndex(source, 0, options),let space = CGColorSpace(name: CGColorSpace.sRGB),let context = CGContext( data: nil, width: compressed.width, height: compressed.height, bitsPerComponent: 8, bytesPerRow: 0, space: space, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)else { returnnil } context.draw(compressed, in: CGRect(x: 0, y: 0, width: compressed.width, height: compressed.height))return context.makeImage().map { UIImage(cgImage: $0, scale: scale, orientation: .up) } }/// The live page's own drawing of `rect` (in window points), before a/// finger turns the fan away. Nil names the window for diagnostic checks.staticfunc capture(_ rect: CGRect, scale: Double, page: String? = nil) -> UIImage? {guardlet source = source(page: page), rect.width > 0, rect.height > 0else { returnnil }let local = source.view.convert(rect, from: source.window)return UIGraphicsImageRenderer(bounds: local, format: format(scale: scale)).image { _ in source.view.drawHierarchy(in: source.view.bounds, afterScreenUpdates: false) } }/// Hosted pages are captured from their own transparent stack, never/// from the window behind them. An unhosted shell and diagnostic window/// captures explicitly pass nil. A missing requested page has no picture.privatestaticfunc source(page: String?) -> (view: UIView, window: UIWindow)? {guardlet window = keyWindow else { returnnil }guardlet page else { return (window, window) }func find(_ controller: UIViewController) -> UIView? {iflet stack = controller as? TileStack, stack.key == page { return stack.view }for child in controller.children {iflet view = find(child) { return view } }returnnil }guardlet view = window.rootViewController.flatMap(find), view.window === window else { returnnil }return (view, window) }/// The render server's own copy of `rect` (in window points) as it is on/// screen: no drawing on the main thread and no pixels in the app.staticfunc snapshot(_ rect: CGRect, page: String? = nil) -> UIView? {guardlet source = source(page: page), rect.width > 0, rect.height > 0else { returnnil }return source.view.resizableSnapshotView(from: source.view.convert(rect, from: source.window), afterScreenUpdates: false, withCapInsets: .zero) }/// Every page picture keeps alpha, a byte a channel, at `scale`.staticfunc format(scale: Double) -> UIGraphicsImageRendererFormat {let format = UIGraphicsImageRendererFormat() format.scale = scale format.opaque = false format.preferredRange = .standardreturn format }/// `image` in an area of `size`, one pixel a point, as the page area/// draws it: at its own size, from the top leading corner.staticfunc redraw(_ image: UIImage, size: CGSize) -> UIImage { UIGraphicsImageRenderer(size: size, format: format(scale: 1)).image { _ in image.draw(in: CGRect(origin: .zero, size: image.size)) } }/// A picture's pixels, RGBA a byte a channel, at one pixel a point.staticfunc pixels(_ image: UIImage) -> [UInt8] {guardlet cg = image.cgImage else { return [] }let width = cg.width, height = cg.heightvar bytes = [UInt8](repeating: 0, count: width * height * 4)let drawn = bytes.withUnsafeMutableBytes { buffer -> Boolinguardlet context = CGContext( data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)else { returnfalse } context.draw(cg, in: CGRect(x: 0, y: 0, width: width, height: height))returntrue }return drawn ? bytes : [] }staticvar keyWindow: UIWindow? { UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } .flatMap(\.windows).first(where: \.isKeyWindow) }}/// The picture check (`scripts/home-preview/check-pictures.sh`): launched/// with `-fan-picture-check`, the fan compares three tiles' live pages with/// their pictures and logs how far apart they are (category `check`).enumFanPictureCheck {staticvar asked: Bool { ProcessInfo.processInfo.arguments.contains("-fan-picture-check") }/// A channel within this of the other picture's is the same: the/// difference text antialiasing makes between two draws.staticlet tolerance = 24/// One frame at 120 Hz: how often the check looks.staticlet frame = Duration.milliseconds(8)/// The tile whose live page last appeared, set only while checking. @MainActor staticvar appeared: String?privatestaticlet logger = Logger(subsystem: "com.cottondb.fan", category: "check")staticfunc log(_ line: String) { logger.notice("picture check: \(line, privacy: .public)") }/// The compared pictures, as PNGs in the app's temporary directory, for/// a person to look at when the check fails.staticfunc keep(_ pictures: [(String, UIImage)], key: String) {let folder = FileManager.default.temporaryDirectory.appendingPathComponent("fan-picture-check")try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)for (name, picture) in pictures {try? picture.pngData()?.write(to: folder.appendingPathComponent("\(key)-\(name).png")) } log("\(key) pictures in \(folder.path)") }}/// Draws one tile's page off screen: mounted in a host beside the window's/// right edge, with the window's environment, into the live page area's/// region (`PageRegion.painted`: all the live page draws, the area's insets/// as its safe area) — a host outside the window's bounds gets none of the/// window's, and the page laid itself out differently from the live one/// (architect, 14 Oct 2026: the title sat ~35 pt low) — given `settle` for/// its first read, then drawn; unless a finger came down meanwhile, when/// nothing is drawn and the page is let go at once — the caller cancels the/// drawing as the finger lands, so the page never stands mounted under a/// turning fan.////// The host stands at the height the live page draws from (`origin`), not at/// the window's top: a tile's page is a UIKit stack (`TileStack`) whose/// safe area UIKit reads from where it stands in the window, whatever the/// SwiftUI host says. Mounted at the top, under the status bar, the stack/// took the status bar as its own inset while the live page area below it/// has none, and every picture shown in a turn stood one status bar (62 pt)/// below the live page, which jumped up as the turn settled (291 row B).@MainActorenumPagePainter {/// Where the host stands in the window: beside its right edge, at the/// top of what the live page draws.staticfunc origin(of region: PageRegion, in window: CGRect) -> CGPoint { CGPoint(x: window.maxX + 1, y: region.drawn.minY) }/// The environment a page is painted in: the fan's own, carrying the/// table definitions its picture is kept under and the tools the fan/// holds now. The fan's `@Environment(\.self)` is not refreshed when only/// keys it never reads change, so it can still hold the definitions of/// its first frame — none — while the fan's own `\.tableDefinitions`/// holds the database's: the Tools deck was painted "Nothing here" under/// no definitions and kept as the picture of the ones read since, and/// every turn to Tools showed it (build 330).staticfunc environment( _ fan: EnvironmentValues, definitions: TableDefinitions, tools: ToolDefinitions ) -> EnvironmentValues {var environment = fan environment.tableDefinitions = definitions environment.toolDefinitions = toolsreturn environment }staticfunc draw( _ page: someView, environment: EnvironmentValues, region: PageRegion, keeping kept: CGSize, scale: Double, settle: Duration, touched: () -> Bool ) async -> (image: UIImage, scrolled: Bool)? {let size = region.drawn.sizeguardlet window = PagePictures.keyWindow, size.width > 0, size.height > 0, kept.width > 0, kept.height > 0else { returnnil }// In picture mode inside the window's environment: it draws, and does nothing else.let host = UIHostingController(rootView: region.painted(page.modifier(PictureMode()).environment(\.self, environment))) host.view.backgroundColor = .clear host.view.isOpaque = false host.safeAreaRegions = [] host.view.frame = CGRect(origin: origin(of: region, in: window.bounds), size: size) host.view.isUserInteractionEnabled = false host.view.accessibilityElementsHidden = true window.addSubview(host.view)defer { host.view.removeFromSuperview() }do { tryawaitTask.sleep(for: settle) } catch { returnnil }guard !touched(), !Task.isCancelled else { returnnil }// Laid out at the page's whole size, kept from its top down to the// picture region's foot, the standing fan's top.let bounds = CGRect(origin: .zero, size: kept)let image = UIGraphicsImageRenderer(bounds: bounds, format: PagePictures.format(scale: scale)).image { _ in host.view.drawHierarchy(in: host.view.bounds, afterScreenUpdates: true) }return (image, !FanScrollWatch.atTop(FanScrollWatch.scrollView(within: host.view))) }}#endif