#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. import Foundation import QuartzCore @MainActor public final class DevFrames: NSObject { public static let shared = DevFrames() static let onKey = "dev.frames.on" /// A frame is late past one and a half of its turn. static let lateFactor = 1.5 /// The route on screen (`RootView` says it), written on every line. public var place = "/" private var link: CADisplayLink? private var last: CFTimeInterval? private var windowStart: CFTimeInterval = 0 private var window = Window() private var log: FileHandle? struct Window { var frames = 0 var late = 0 var lateMillis = 0.0 var worstMillis = 0.0 } /// Starts the meter when this launch asked for it. Safe to call again. public func 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 private func tick(_ link: CADisplayLink) { let now = link.timestamp defer { last = now } guard let last else { windowStart = now return } let turn = link.targetTimestamp - link.timestamp let 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 >= 1 else { 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. private func 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