Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Diagnostics: page frame rate, display refresh rates, Stage Manager (#80) (#101)

Victor Kildahl9434cc05709b
diff --git a/Packages/CraCore/Sources/CraCore/DisplayDiagnostics.swift b/Packages/CraCore/Sources/CraCore/DisplayDiagnostics.swift
new file mode 100644
index 0000000..ee7b0b6
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/DisplayDiagnostics.swift
@@ -0,0 +1,53 @@
+import Foundation
+
+/// A display as Help ▸ Export Diagnostics lists it. Pages that never paint on macOS 27 (#80)
+/// match a Chromium report tied to displays running at different refresh rates, so each
+/// display gives its rate and the list says when they differ. No display names: a Sidecar or
+/// AirPlay display is named after the user's device.
+public struct DisplayDiagnostics: Equatable, Sendable {
+ public var width: Int
+ public var height: Int
+ public var scale: Int
+ /// The fastest rate, and the slowest a variable-rate (ProMotion) display drops to; the
+ /// same on a fixed-rate display.
+ public var maximumHz: Int
+ public var minimumHz: Int
+ public var builtIn: Bool
+ /// The one with the menu bar.
+ public var main: Bool
+
+ public init(width: Int, height: Int, scale: Int, maximumHz: Int, minimumHz: Int, builtIn: Bool, main: Bool) {
+ self.width = width
+ self.height = height
+ self.scale = scale
+ self.maximumHz = maximumHz
+ self.minimumHz = minimumHz
+ self.builtIn = builtIn
+ self.main = main
+ }
+
+ /// From NSScreen's refresh intervals (seconds per frame); 0 means unknown.
+ public static func hz(interval: Double) -> Int {
+ interval > 0 ? Int((1 / interval).rounded()) : 0
+ }
+
+ /// "built-in 1800x1169@2x, 120 Hz (variable from 24), main"
+ public var line: String {
+ var s = "\(builtIn ? "built-in" : "external") \(width)x\(height)@\(scale)x, \(maximumHz) Hz"
+ if minimumHz > 0, minimumHz < maximumHz { s += " (variable from \(minimumHz))" }
+ if main { s += ", main" }
+ return s
+ }
+
+ /// Displays that each run at their own top rate.
+ public static func mixedRates(_ displays: [DisplayDiagnostics]) -> Bool {
+ Set(displays.map(\.maximumHz).filter { $0 > 0 }).count > 1
+ }
+
+ /// The summary's "Displays:" block, one display a line.
+ public static func summary(_ displays: [DisplayDiagnostics]) -> String {
+ guard !displays.isEmpty else { return "Displays: none" }
+ let head = "Displays: \(displays.count)\(mixedRates(displays) ? ", mixed refresh rates" : "")"
+ return ([head] + displays.map { " " + $0.line }).joined(separator: "\n")
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/DisplayDiagnosticsTests.swift b/Packages/CraCore/Tests/CraCoreTests/DisplayDiagnosticsTests.swift
new file mode 100644
index 0000000..932290e
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/DisplayDiagnosticsTests.swift
@@ -0,0 +1,40 @@
+import CraCore
+import Testing
+
+/// Help ▸ Export Diagnostics: the displays and their refresh rates (#80).
+struct DisplayDiagnosticsTests {
+ let laptop = DisplayDiagnostics(width: 1800, height: 1169, scale: 2, maximumHz: 120, minimumHz: 24, builtIn: true, main: true)
+ let monitor = DisplayDiagnostics(width: 3440, height: 1440, scale: 1, maximumHz: 200, minimumHz: 200, builtIn: false, main: false)
+
+ @Test func variableRateDisplayShowsItsRange() {
+ #expect(laptop.line == "built-in 1800x1169@2x, 120 Hz (variable from 24), main")
+ }
+
+ @Test func fixedRateDisplayShowsOneRate() {
+ #expect(monitor.line == "external 3440x1440@1x, 200 Hz")
+ }
+
+ @Test(arguments: [(1.0 / 120, 120), (1.0 / 59.94, 60), (0, 0), (-1, 0)])
+ func intervalsBecomeWholeHertz(interval: Double, hz: Int) {
+ #expect(DisplayDiagnostics.hz(interval: interval) == hz)
+ }
+
+ @Test func differentTopRatesAreMixed() {
+ #expect(DisplayDiagnostics.mixedRates([laptop, monitor]))
+ #expect(DisplayDiagnostics.summary([laptop, monitor]) == """
+ Displays: 2, mixed refresh rates
+ built-in 1800x1169@2x, 120 Hz (variable from 24), main
+ external 3440x1440@1x, 200 Hz
+ """)
+ }
+
+ @Test func sameTopRateOrUnknownIsNotMixed() {
+ var other = monitor
+ other.maximumHz = 120
+ #expect(!DisplayDiagnostics.mixedRates([laptop, other]))
+ other.maximumHz = 0
+ #expect(!DisplayDiagnostics.mixedRates([laptop, other]))
+ #expect(DisplayDiagnostics.summary([laptop]) == "Displays: 1\n built-in 1800x1169@2x, 120 Hz (variable from 24), main")
+ #expect(DisplayDiagnostics.summary([]) == "Displays: none")
+ }
+}
diff --git a/Sources/Cra/Services/Diagnostics.swift b/Sources/Cra/Services/Diagnostics.swift
index 9f8fa38..98bc373 100644
--- a/Sources/Cra/Services/Diagnostics.swift
+++ b/Sources/Cra/Services/Diagnostics.swift
@@ -25,7 +25,7 @@ enum Diagnostics {
var pending: [(String, CraBrowser)] = []
for (n, w) in windows.enumerated() {
let m = w.browsers!
- var s = "Window \(n + 1)\(w.window?.isKeyWindow == true ? " (key)" : ""): \(m.runtimes.count) live pages, frame \(w.window.map { NSStringFromRect($0.frame) } ?? "-")\n"
+ var s = "Window \(n + 1)\(w.window?.isKeyWindow == true ? " (key)" : ""): \(m.runtimes.count) live pages, frame \(w.window.map { NSStringFromRect($0.frame) } ?? "-"), display \(PageProbe.refreshRate(w.window?.screen))\n"
for id in m.visibleTabIDs {
let item = store.item(id)
let incognito = store.isIncognito(item: id)
@@ -127,12 +127,21 @@ enum Diagnostics {
sysctlbyname("hw.model", nil, &size, nil, 0)
var model = [CChar](repeating: 0, count: max(size, 1))
sysctlbyname("hw.model", &model, &size, nil, 0)
- let screens = NSScreen.screens.map { "\(Int($0.frame.width))x\(Int($0.frame.height))@\(Int($0.backingScaleFactor))x" }
+ let displays = NSScreen.screens.map { screen in
+ let id = (screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.uint32Value ?? 0
+ return DisplayDiagnostics(width: Int(screen.frame.width), height: Int(screen.frame.height), scale: Int(screen.backingScaleFactor),
+ maximumHz: screen.maximumFramesPerSecond,
+ minimumHz: DisplayDiagnostics.hz(interval: screen.maximumRefreshInterval),
+ builtIn: CGDisplayIsBuiltin(id) != 0, main: screen == NSScreen.screens.first)
+ }
+ // Chromium switches part of its window tracking off under Stage Manager (crbug 448103577).
+ let stageManager = UserDefaults.standard.persistentDomain(forName: "com.apple.WindowManager")?["GloballyEnabled"] as? Bool ?? false
var lines = [
"Cra \(info?["CFBundleShortVersionString"] as? String ?? "?") (\(info?["CFBundleVersion"] as? String ?? "?"))",
"Chromium \(CraCEFRuntime.chromiumVersion()), CEF \(CraCEFRuntime.cefVersion())",
"macOS \(os.majorVersion).\(os.minorVersion).\(os.patchVersion), \(String(cString: model)), \(ProcessInfo.processInfo.physicalMemory >> 30) GB, \(ProcessInfo.processInfo.activeProcessorCount) cores",
- "Displays: \(screens.joined(separator: ", "))",
+ DisplayDiagnostics.summary(displays),
+ "Stage Manager: \(stageManager ? "on" : "off")",
"Running from: \(Bundle.main.bundlePath)",
"Up for: \(Int(ProcessInfo.processInfo.systemUptime / 60)) min (Mac), \(Int(-(NSRunningApplication.current.launchDate ?? Date()).timeIntervalSinceNow / 60)) min (Cra)",
"Embedded pages: \(EmbeddedPages.isEnabled), Chrome-style hosting: \(CraCEFRuntime.chromeHosting())",
diff --git a/Sources/Cra/Services/PageProbe.swift b/Sources/Cra/Services/PageProbe.swift
index f1915e3..43493ac 100644
--- a/Sources/Cra/Services/PageProbe.swift
+++ b/Sources/Cra/Services/PageProbe.swift
@@ -4,21 +4,32 @@ import CraCEF
/// What a page holds, asked from the page itself: a blank tab tells apart a navigation that
/// never committed (about:blank), a page Chromium thinks is hidden, one that has content but
/// never painted it, and one that is simply empty.
+///
+/// `frameRate` counts animation frames for half a second. A visible page gets one per display
+/// refresh; 0 means Chromium's compositor never asked it to draw. Frames without `painted`
+/// mean they were drawn but never reached the screen (#80).
@MainActor
enum PageProbe {
private static let script = """
- JSON.stringify({blank: location.href === 'about:blank', ready: document.readyState, visibility: document.visibilityState,
- viewport: innerWidth + 'x' + innerHeight + '@' + devicePixelRatio,
- scrollHeight: document.documentElement ? document.documentElement.scrollHeight : 0,
- elements: document.getElementsByTagName('*').length,
- text: document.body ? document.body.textContent.length : -1,
- painted: performance.getEntriesByName('first-contentful-paint').length > 0})
+ new Promise(done => {
+ let frames = 0, counting = true;
+ const tick = () => { if (counting) { frames++; requestAnimationFrame(tick); } };
+ requestAnimationFrame(tick);
+ setTimeout(() => { counting = false;
+ done(JSON.stringify({blank: location.href === 'about:blank', ready: document.readyState, visibility: document.visibilityState,
+ viewport: innerWidth + 'x' + innerHeight + '@' + devicePixelRatio,
+ scrollHeight: document.documentElement ? document.documentElement.scrollHeight : 0,
+ elements: document.getElementsByTagName('*').length,
+ text: document.body ? document.body.textContent.length : -1,
+ painted: performance.getEntriesByName('first-contentful-paint').length > 0,
+ frameRate: frames * 2})); }, 500);
+ })
"""
/// One line ("ready=complete visibility=visible …"), or why there is none.
static func run(_ browser: CraBrowser, completion: @escaping (String) -> Void) {
guard browser.isCreated, !browser.isClosed else { completion("no browser yet"); return }
- let body = try? JSONSerialization.data(withJSONObject: ["expression": script, "returnByValue": true])
+ let body = try? JSONSerialization.data(withJSONObject: ["expression": script, "returnByValue": true, "awaitPromise": true])
var answered = false
let finish: (String) -> Void = { line in
guard !answered else { return }
@@ -36,7 +47,7 @@ enum PageProbe {
finish("probe failed: \(error ?? "no result")")
return
}
- finish(["blank", "ready", "visibility", "viewport", "scrollHeight", "elements", "text", "painted"]
+ finish(["blank", "ready", "visibility", "viewport", "scrollHeight", "elements", "text", "painted", "frameRate"]
.map { "\($0)=\(fields[$0].map { "\($0)" } ?? "?")" }.joined(separator: " "))
}
}
@@ -60,7 +71,14 @@ enum PageProbe {
// fine; hidden in a window on screen is not.
if let w = views.first?.window {
s += " window=\(w.occlusionState.contains(.visible) ? "on screen" : "covered")\(NSApp.isActive ? "" : " app=inactive")"
+ // Chromium times the page's frames to the display its own window is on.
+ s += " display=\(refreshRate(w.screen))"
+ if let host = rt.hostWindow, host.screen != w.screen { s += " pageDisplay=\(refreshRate(host.screen))" }
}
return s
}
+
+ static func refreshRate(_ screen: NSScreen?) -> String {
+ screen.map { "\($0.maximumFramesPerSecond)Hz" } ?? "none"
+ }
}
diff --git a/Tests/BrowserManagerLifecycleTests.swift b/Tests/BrowserManagerLifecycleTests.swift
index b9fd70a..124c73f 100644
--- a/Tests/BrowserManagerLifecycleTests.swift
+++ b/Tests/BrowserManagerLifecycleTests.swift
@@ -87,9 +87,40 @@ enum BrowserManagerLifecycleTests {
await nowPlayingPictureInPictureCase()
pageColoursCase()
await sleepCase("malformed or missing replies cannot authorize sleeping", reply: nil) { _, _ in }
+ await pageProbeCase()
print("Browser manager lifecycle: \(checks) checks passed")
}
+ /// The line cra.log gets about a page on screen (#80): how many frames the page was asked
+ /// for, and which display's refresh rate its window follows.
+ @MainActor
+ private static func pageProbeCase() async {
+ _ = NSApplication.shared
+ NSApp.setActivationPolicy(.prohibited)
+ let store = SidebarStore()
+ let manager = BrowserManager(store: store, favicons: FaviconCache(), container: NSView())
+ let runtime = manager.ensureRuntime(for: store.createTab(url: "https://example.test/probe").id)!
+ var line: String?
+ PageProbe.run(runtime.browser) { line = $0 }
+ expect(runtime.browser.lastParams.contains(#""awaitPromise":true"#) && runtime.browser.lastParams.contains("frameRate"),
+ "the probe waits for the page to count its frames")
+ let page = #"{"blank":false,"ready":"complete","visibility":"visible","painted":false,"frameRate":0}"#
+ let reply = try! JSONSerialization.data(withJSONObject: ["result": ["type": "string", "value": page]])
+ runtime.browser.reply(to: "Runtime.evaluate", with: String(decoding: reply, as: UTF8.self))
+ await drainMainQueue()
+ expect(line?.hasSuffix("visibility=visible viewport=? scrollHeight=? elements=? text=? painted=0 frameRate=0") == true,
+ "a visible page that was never asked to draw reads frameRate=0")
+
+ // Off every screen, as in a headless run: the window follows no display.
+ let window = NSWindow(contentRect: NSRect(x: -10000, y: -10000, width: 20, height: 20),
+ styleMask: .borderless, backing: .buffered, defer: true)
+ window.isReleasedWhenClosed = false
+ defer { window.close() }
+ window.contentView!.addSubview(runtime.browser.containerView)
+ expect(PageProbe.viewState(runtime).hasSuffix(" display=none"), "the view state names the display the page's window is on")
+ manager.closeAll()
+ }
+
@MainActor
private static func embeddedPageHandoffCase() {
_ = NSApplication.shared
diff --git a/docs/development.md b/docs/development.md
index 58269f8..0310a45 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -44,11 +44,13 @@ start over.
`cra.log` is Cra's own log: each tab's page opening, showing, loading and closing, and three
seconds after a tab comes on screen, what its page holds (`blank`, `visibility`, element and
-text counts, `painted` for a first contentful paint) and where Cra put it (view size,
-`window=covered` when another window hides it). `chromium.log` holds Chromium's warnings,
+text counts, `painted` for a first contentful paint, `frameRate` for the animation frames
+it got in half a second) and where Cra put it (view size, `window=covered` when another
+window hides it, `display=` the refresh rate of the display it is on). A visible page with
+`frameRate=0` was never asked to draw; frames without `painted` never reached the screen. `chromium.log` holds Chromium's warnings,
failed page loads and crashed renderers. Each launch keeps the last one's as `*.previous.log`.
Logs name sites by host only. Help ▸ Export Diagnostics… zips both with the GPU report,
-the on-screen pages' state, settings, extensions and the last week's crash reports, with
+the displays and their refresh rates, whether Stage Manager is on, the on-screen pages' state, settings, extensions and the last week's crash reports, with
addresses cut to their host; `cra://debug?exportDiagnostics=<path>` does the same without
the save panel.