Cotton code
408 lines · 20.5 KB · SwiftRaw
// 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.enum FanSnapshotRule {    /// 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).    static func holds(grabbed: String?, moving: Bool, live: Bool, drawn: String?) -> Bool {        guard let grabbed else { return false }        return moving || !live || drawn != grabbed    }}#if os(iOS)import CottonKitimport ImageIOimport OSLogimport SwiftUIimport UIKit@MainActor@Observablefinal class PagePictures {    @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?    struct Grabbed {        let key: String        let view: UIView    }    @ObservationIgnored private var data: [String: Data] = [:]    /// The tiles whose picture was drawn with their page below its top.    @ObservationIgnored private var scrolled: Set<String> = []    @ObservationIgnored private var window: Set<String> = []    /// The one decoding under way (`refocus`).    @ObservationIgnored private var 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 private var definitions: Int?    init(quality: Double, reach: Int, scale: Double) {        self.quality = quality        self.reach = reach        self.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)")    }    private static let 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.    static let 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 = quality        guard let bytes = await Task.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] = bytes        if 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) }        if let 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 = scale        for key in order.map({ keys[$0] }) where decoded[key] == nil {            guard !Task.isCancelled else { return }            guard let bytes = data[key],                  let image = await Task.detached(priority: .userInitiated, operation: { Self.decode(bytes, scale: scale) }).value            else { 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 static func decode(_ bytes: Data, scale: Double) -> UIImage? {        let options = [kCGImageSourceShouldCache: false] as CFDictionary        guard let 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 { return nil }        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.    static func capture(_ rect: CGRect, scale: Double, page: String? = nil) -> UIImage? {        guard let source = source(page: page), rect.width > 0, rect.height > 0 else { return nil }        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.    private static func source(page: String?) -> (view: UIView, window: UIWindow)? {        guard let window = keyWindow else { return nil }        guard let page else { return (window, window) }        func find(_ controller: UIViewController) -> UIView? {            if let stack = controller as? TileStack, stack.key == page { return stack.view }            for child in controller.children {                if let view = find(child) { return view }            }            return nil        }        guard let view = window.rootViewController.flatMap(find), view.window === window else { return nil }        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.    static func snapshot(_ rect: CGRect, page: String? = nil) -> UIView? {        guard let source = source(page: page), rect.width > 0, rect.height > 0 else { return nil }        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`.    static func format(scale: Double) -> UIGraphicsImageRendererFormat {        let format = UIGraphicsImageRendererFormat()        format.scale = scale        format.opaque = false        format.preferredRange = .standard        return 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.    static func 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.    static func pixels(_ image: UIImage) -> [UInt8] {        guard let cg = image.cgImage else { return [] }        let width = cg.width, height = cg.height        var bytes = [UInt8](repeating: 0, count: width * height * 4)        let drawn = bytes.withUnsafeMutableBytes { buffer -> Bool in            guard let context = CGContext(                data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,                space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)            else { return false }            context.draw(cg, in: CGRect(x: 0, y: 0, width: width, height: height))            return true        }        return drawn ? bytes : []    }    static var 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`).enum FanPictureCheck {    static var 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.    static let tolerance = 24    /// One frame at 120 Hz: how often the check looks.    static let frame = Duration.milliseconds(8)    /// The tile whose live page last appeared, set only while checking.    @MainActor static var appeared: String?    private static let logger = Logger(subsystem: "com.cottondb.fan", category: "check")    static func 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.    static func 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).@MainActorenum PagePainter {    /// Where the host stands in the window: beside its right edge, at the    /// top of what the live page draws.    static func 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).    static func environment(        _ fan: EnvironmentValues, definitions: TableDefinitions, tools: ToolDefinitions    ) -> EnvironmentValues {        var environment = fan        environment.tableDefinitions = definitions        environment.toolDefinitions = tools        return environment    }    static func draw(        _ page: some View, environment: EnvironmentValues, region: PageRegion, keeping kept: CGSize,        scale: Double, settle: Duration, touched: () -> Bool    ) async -> (image: UIImage, scrolled: Bool)? {        let size = region.drawn.size        guard let window = PagePictures.keyWindow, size.width > 0, size.height > 0, kept.width > 0, kept.height > 0        else { return nil }        // 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 { try await Task.sleep(for: settle) } catch { return nil }        guard !touched(), !Task.isCancelled else { return nil }        // 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