#if COTTON_DEV && os(iOS)// DevFrames.swift — DEVELOPER TOOL, compiled into Cotton Dev only.//// How smoothly the screen is drawn, as numbers: one line a second saying how// many frames were drawn, how many were late and how long the worst one took,// beside the route on screen. A frame is late when the main// thread was busy past its turn, which is what a finger feels as a list that// drags — so a change said to make scrolling smoother is measured, before and// after, by scrolling the same list and reading these lines.//// OFF unless asked for: launch with `-dev.frames.on YES` (or set that default)// and read `tmp/dev-frames.log` in the app's container. Nothing is drawn.importFoundationimportQuartzCore@MainActorpublicfinalclassDevFrames: NSObject {publicstaticlet shared = DevFrames()staticlet onKey = "dev.frames.on"/// A frame is late past one and a half of its turn.staticlet lateFactor = 1.5/// The route on screen (`RootView` says it), written on every line.publicvar place = "/"privatevar link: CADisplayLink?privatevar last: CFTimeInterval?privatevar windowStart: CFTimeInterval = 0privatevar window = Window()privatevar log: FileHandle?structWindow {var frames = 0var late = 0var lateMillis = 0.0var worstMillis = 0.0 }/// Starts the meter when this launch asked for it. Safe to call again.publicfunc startIfAsked() {guard link == nil, UserDefaults.standard.bool(forKey: Self.onKey) else { return }let url = FileManager.default.temporaryDirectory.appendingPathComponent("dev-frames.log")FileManager.default.createFile(atPath: url.path, contents: nil) log = try? FileHandle(forWritingTo: url)let link = CADisplayLink(target: self, selector: #selector(tick(_:)))// `.common`, so a scroll's own run-loop mode does not stop the count. link.add(to: .main, forMode: .common)self.link = link } @objc privatefunc tick(_ link: CADisplayLink) {let now = link.timestampdefer { last = now }guardlet last else { windowStart = nowreturn }let turn = link.targetTimestamp - link.timestamplet took = now - last window.frames += 1 window.worstMillis = max(window.worstMillis, took * 1000)if turn > 0, took > turn * Self.lateFactor { window.late += 1 window.lateMillis += (took - turn) * 1000 }guard now - windowStart >= 1else { return } write(seconds: now - windowStart, turn: turn) windowStart = now window = Window() }/// One second as a line of the frames log, which only a developer reads:/// when, where, frames drawn, late frames, the time lost to them and the/// worst frame, each in milliseconds.privatefunc write(seconds: Double, turn: Double) {try? log?.write(contentsOf: Data((String( format: "%.3f place=%@ seconds=%.3f turn_ms=%.2f frames=%d late=%d late_ms=%.1f worst_ms=%.1f",Date().timeIntervalSince1970, place, seconds, turn * 1000, window.frames, window.late, window.lateMillis, window.worstMillis) + "\n").utf8)) }}#endif