Cotton code
77 lines · 2.8 KB · SwiftRaw
#if COTTON_DEV// DevTimings.swift — DEVELOPER TOOL, compiled into Cotton Dev only.//// Which surface is on screen, how long it took to its first rows, and the// core reads it made on the way (`CottonKit/Developer/DevReads.swift`). The// timings overlay draws it (`DevCorner.swift`) and a report names the surface// (`Feedback/ShakeReport.swift`). Surfaces say `begin` when they appear and// `rowsShown` once rows are drawn; nothing else writes here.import CottonKitimport Foundationimport Observationimport os@MainActor@Observablepublic final class DevTimings {    public static let shared = DevTimings()    /// The table definition on screen, by id.    public private(set) var surface: String?    /// From `begin` to the first rows; nil until they are drawn.    public private(set) var firstRowMillis: Double?    private var opened: ContinuousClock.Instant?    /// The overlay is drawn. A habit of this device, kept across launches.    public var showing: Bool {        didSet { UserDefaults.standard.set(showing, forKey: Self.showingKey) }    }    static let showingKey = "dev.timings.showing"    init() {        showing = UserDefaults.standard.bool(forKey: Self.showingKey)    }    public func begin(_ surface: String) {        self.surface = surface        opened = .now        firstRowMillis = nil    }    public func rowsShown(_ surface: String) {        guard surface == self.surface, firstRowMillis == nil, let opened else { return }        let elapsed = ContinuousClock.now - opened        let millis = Double(elapsed.components.seconds) * 1000            + Double(elapsed.components.attoseconds) / 1e15        firstRowMillis = millis        // Read off the device log by a walk that measures a list, so the        // number is taken without querying the screen (an accessibility        // query is itself main-thread work on every SwiftUI update).        Self.log.notice("first rows \(surface, privacy: .public) \(Int(millis.rounded())) ms")    }    private static let log = Logger(subsystem: "com.cottondb.dev", category: "timings")    /// The reads made since the surface appeared, oldest first.    public func reads() -> [DevReads.Call] {        guard let opened else { return [] }        return DevReads.since(opened)    }}/// Which synthetic household a reseed founds — `small` (about 2 000 rows) or/// `large` (about 100 000), the generator's own names (ws-m5b-dev2).public enum DevHouseholdSize: String, CaseIterable, Sendable {    case small, large    static let key = "dev.household.size"    public static var chosen: DevHouseholdSize {        get { UserDefaults.standard.string(forKey: key).flatMap(DevHouseholdSize.init) ?? .small }        set { UserDefaults.standard.set(newValue.rawValue, forKey: key) }    }    public var other: DevHouseholdSize { self == .small ? .large : .small }}#endif