import AppKit import Darwin import Foundation private struct FixtureError: Error, CustomStringConvertible { let description: String } private struct Dimensions: Codable { let width: Double let height: Double var size: NSSize { NSSize(width: width, height: height) } init(_ text: String, option: String) throws { let parts = text.split(separator: "x", omittingEmptySubsequences: false) guard parts.count == 2, let width = Double(parts[0]), let height = Double(parts[1]), width.isFinite, height.isFinite, width > 0, height > 0 else { throw FixtureError(description: "\(option) must be WIDTHxHEIGHT with positive finite dimensions") } self.width = width self.height = height } } private struct Options: Encodable { var windowCount = 1 var title = "Fixture" var titles: [String]? var minimumSize: Dimensions? var clampSize: Dimensions? var slowResizeMilliseconds = 0 var dialog = false var floatingPanel = false var fixedSize = false var validate = false var unreadableMenu = false init(arguments: [String]) throws { var index = 0 while index < arguments.count { let argument = arguments[index] index += 1 switch argument { case "--dialog": dialog = true continue case "--floating-panel": floatingPanel = true continue case "--fixed-size": fixedSize = true continue case "--validate": validate = true continue case "--unreadable-menu": unreadableMenu = true continue default: break } guard ["--windows", "--title", "--titles", "--min-size", "--clamp-size", "--slow-resize", "--slow"] .contains(argument), index < arguments.count else { throw FixtureError(description: "Unknown option or missing value: \(argument)") } let value = arguments[index] index += 1 switch argument { case "--windows": guard let count = Int(value), (1...100).contains(count) else { throw FixtureError(description: "--windows must be an integer between 1 and 100") } windowCount = count case "--title": guard !value.isEmpty else { throw FixtureError(description: "--title must not be empty") } title = value case "--titles": let titles = try JSONDecoder().decode([String].self, from: Data(value.utf8)) guard !titles.isEmpty, titles.allSatisfy({ !$0.isEmpty }), Set(titles).count == titles.count else { throw FixtureError(description: "--titles must be a JSON array of unique, nonempty titles") } self.titles = titles case "--min-size": minimumSize = try Dimensions(value, option: argument) case "--clamp-size": clampSize = try Dimensions(value, option: argument) case "--slow-resize", "--slow": guard let milliseconds = Int(value), (1...5_000).contains(milliseconds) else { throw FixtureError(description: "\(argument) must be milliseconds between 1 and 5000") } slowResizeMilliseconds = milliseconds default: preconditionFailure("Option validation and parsing disagree") } } if let titles, titles.count != windowCount { throw FixtureError(description: "--titles must contain exactly --windows titles") } } func title(for index: Int) -> String { if let titles, index <= titles.count { return titles[index - 1] } return "\(title) \(index)" } } private struct Control: Decodable { let id: String let action: String var window: Int? var title: String? var x: Double? var y: Double? var width: Double? var height: Double? var slowResizeMilliseconds: Int? var clampWidth: Double? var clampHeight: Double? var adjustNextFrame: Bool? var label: String? } private struct ResizeInterval: Encodable { let start: Double let end: Double } private struct WindowState: Encodable { let index: Int let number: Int let title: String let x: Double let y: Double let width: Double let height: Double let frameWrites: Int let resizeWrites: Int let slowResizeWrites: Int let clampedWrites: Int let adjustedWrites: Int let slowResizeIntervals: [ResizeInterval] let fullscreen: Bool let fullscreenTransition: Bool let edgeControlClicks: Int let edgeControl: ControlFrame? } private struct ControlFrame: Encodable { let x: Double let y: Double let width: Double let height: Double } private struct Reply: Encodable { let id: String let pid: Int32 let windows: [WindowState] let focusedWindow: Int? let keyWindowNumber: Int? let menuOpen: Bool let error: String? var recordings: [FrameRecording]? var markNanoseconds: UInt64? var overflow = false var inputEvents: [FixtureInputEvent] = [] var menuReadRequests = 0 var auxiliaryWindows: [AuxiliaryWindowState] = [] private enum CodingKeys: String, CodingKey { case id, pid, windows, focusedWindow, keyWindowNumber, menuOpen, error, recordings, overflow, inputEvents, menuReadRequests case markNanoseconds = "mark_ns" case auxiliaryWindows } } private struct AuxiliaryWindowState: Encodable { let kind: String let number: Int let parentNumber: Int? let frameWrites: Int let resizeWrites: Int } @MainActor private final class FixtureOpenPanel: NSOpenPanel { var recordsWrites = false private(set) var frameWrites = 0 private(set) var resizeWrites = 0 override func setFrame(_ frameRect: NSRect, display flag: Bool) { if recordsWrites { frameWrites += 1 if frameRect.size != frame.size { resizeWrites += 1 } } super.setFrame(frameRect, display: flag) } } @MainActor private final class FixturePanel: NSPanel { var recordsWrites = false private(set) var frameWrites = 0 private(set) var resizeWrites = 0 override func setFrame(_ frameRect: NSRect, display flag: Bool) { if recordsWrites { frameWrites += 1 if frameRect.size != frame.size { resizeWrites += 1 } } super.setFrame(frameRect, display: flag) } } @MainActor private final class FixtureWindow: NSWindow { var clampSize: NSSize? var slowResizeMilliseconds = 0 var adjustNextFrame = false private(set) var frameWrites = 0 private(set) var resizeWrites = 0 private(set) var slowResizeWrites = 0 private(set) var clampedWrites = 0 private(set) var adjustedWrites = 0 private(set) var slowResizeIntervals: [ResizeInterval] = [] var recordsWrites = false let frameRecorder = FrameRecorder() var fullscreenTransition = false private(set) var edgeControlClicks = 0 private(set) var edgeControl: NSButton? override func isAccessibilityEdited() -> Bool { isDocumentEdited } func installEdgeControl() throws { guard edgeControl == nil, let contentView, contentView.bounds.width >= 40, contentView.bounds.height >= 30 else { throw FixtureError(description: "Edge control needs an unconfigured content view") } let button = NSButton( frame: NSRect(x: contentView.bounds.maxX - 40, y: contentView.bounds.midY - 15, width: 40, height: 30)) button.autoresizingMask = [.minXMargin, .minYMargin, .maxYMargin] button.title = "Edge" button.isBordered = false button.setAccessibilityLabel("Fixture edge control") button.target = self button.action = #selector(edgeClicked) contentView.addSubview(button) edgeControl = button } @objc private func edgeClicked() { edgeControlClicks += 1 } override func setFrame(_ frameRect: NSRect, display flag: Bool) { var requested = frameRect if let clampSize { requested.size.width = max(requested.width, clampSize.width) requested.size.height = max(requested.height, clampSize.height) } let resizing = requested.size != frame.size if recordsWrites { frameWrites += 1 if resizing { resizeWrites += 1 } if requested.size != frameRect.size { clampedWrites += 1 } if resizing, slowResizeMilliseconds > 0 { slowResizeWrites += 1 // Deliberately stall only real resize writes, not discovery or the control channel. let start = ProcessInfo.processInfo.systemUptime Thread.sleep(forTimeInterval: Double(slowResizeMilliseconds) / 1_000) slowResizeIntervals.append(ResizeInterval(start: start, end: ProcessInfo.processInfo.systemUptime)) if slowResizeIntervals.count > 32 { slowResizeIntervals.removeFirst() } } } super.setFrame(requested, display: flag) if recordsWrites, adjustNextFrame { adjustNextFrame = false adjustedWrites += 1 var adjusted = frame adjusted.origin.y += 12 super.setFrame(adjusted, display: flag) } frameRecorder.write(frame: frame) } } @MainActor private final class FixtureDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDelegate { private let options: Options let inputRecorder = FixtureInputRecorder() private var windows: [Int: FixtureWindow] = [:] private var auxiliaryWindows: [NSWindow] = [] private var nextIndex = 1 private var inputSource: (any DispatchSourceRead)? private var input = Data() private var fixtureMenu: NSMenu? private var menuOpen = false private var recordingAllWindows = false private var completedRecordings: [FrameRecording] = [] private var replyRecordings: [FrameRecording]? private var replyMark: UInt64? func menuWillOpen(_ menu: NSMenu) { menuOpen = true } func menuDidClose(_ menu: NSMenu) { menuOpen = false } init(options: Options) { self.options = options } func applicationDidFinishLaunching(_ notification: Notification) { do { for _ in 0.. Bool { false } private func openDialogs() throws { guard auxiliaryWindows.isEmpty, let parent = windows[1] else { throw FixtureError(description: "Dialogs need the first fixture window and no existing auxiliaries") } let sheet = FixtureWindow( contentRect: NSRect(x: 0, y: 0, width: 300, height: 180), styleMask: [.titled, .closable], backing: .buffered, defer: false) sheet.title = "\(options.title) Sheet" sheet.isReleasedWhenClosed = false parent.beginSheet(sheet) sheet.recordsWrites = true let panel = FixturePanel( contentRect: NSRect(x: 250, y: 250, width: 300, height: 200), styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false) panel.title = "\(options.title) Panel" panel.isReleasedWhenClosed = false panel.isFloatingPanel = true panel.level = .floating panel.hidesOnDeactivate = false panel.orderFront(nil) panel.recordsWrites = true auxiliaryWindows = [sheet, panel] } private func openFilePicker() throws { guard auxiliaryWindows.isEmpty, let parent = windows[1] else { throw FixtureError(description: "File picker needs the first fixture window and no existing auxiliaries") } let picker = FixtureOpenPanel() // Deliberately share the document title: classification must use native semantics. picker.title = parent.title picker.canChooseFiles = true picker.canChooseDirectories = false picker.allowsMultipleSelection = false picker.directoryURL = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true) picker.isReleasedWhenClosed = false auxiliaryWindows = [picker] picker.beginSheetModal(for: parent) { _ in } picker.recordsWrites = true } func windowWillClose(_ notification: Notification) { guard let window = notification.object as? NSWindow else { fail("Window close notification needs a window") } if let index = windows.first(where: { $0.value === window })?.key, let fixture = windows[index] { if fixture.frameRecorder.isRecording { completedRecordings.append(fixture.frameRecorder.stop(index: index)) } windows[index] = nil } } func windowWillEnterFullScreen(_ notification: Notification) { setFullscreenTransition(notification, active: true) } func windowDidEnterFullScreen(_ notification: Notification) { setFullscreenTransition(notification, active: false) } func windowWillExitFullScreen(_ notification: Notification) { setFullscreenTransition(notification, active: true) } func windowDidExitFullScreen(_ notification: Notification) { setFullscreenTransition(notification, active: false) } func windowDidFailToEnterFullScreen(_ window: NSWindow) { fullscreenWindow(window).fullscreenTransition = false } func windowDidFailToExitFullScreen(_ window: NSWindow) { fullscreenWindow(window).fullscreenTransition = false } private func setFullscreenTransition(_ notification: Notification, active: Bool) { guard let window = notification.object as? NSWindow else { fail("Fullscreen notification needs a window") } fullscreenWindow(window).fullscreenTransition = active } private func fullscreenWindow(_ window: NSWindow) -> FixtureWindow { guard let fixture = windows.values.first(where: { $0 === window }) else { fail("Fullscreen transition needs a managed fixture window") } return fixture } private func createWindow(title: String? = nil, asTabOf parent: FixtureWindow? = nil) throws { let index = nextIndex nextIndex += 1 let window = FixtureWindow( contentRect: NSRect( x: 100 + 30 * ((index - 1) % 10), y: 100 + 30 * ((index - 1) % 10), width: 480, height: 320), styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) if options.fixedSize { window.styleMask.remove(.resizable) } window.title = title ?? options.title(for: index) if options.floatingPanel { window.setAccessibilitySubrole(.floatingWindow) window.level = .floating } window.delegate = self window.collectionBehavior.insert(.fullScreenPrimary) window.isReleasedWhenClosed = false window.tabbingMode = parent == nil ? .disallowed : .preferred window.minSize = options.minimumSize?.size ?? NSSize(width: 80, height: 80) window.clampSize = options.clampSize?.size let minimum = options.minimumSize?.size ?? .zero let clamp = options.clampSize?.size ?? .zero window.setFrame( NSRect( origin: window.frame.origin, size: NSSize( width: max(window.frame.width, minimum.width, clamp.width), height: max(window.frame.height, minimum.height, clamp.height))), display: false) window.slowResizeMilliseconds = options.slowResizeMilliseconds windows[index] = window if recordingAllWindows { try window.frameRecorder.start(window: window) } if let parent { parent.tabbingMode = .preferred parent.addTabbedWindow(window, ordered: .above) parent.tabGroup?.selectedWindow = window } window.makeKeyAndOrderFront(nil) window.recordsWrites = true } private func readControls() { var bytes = [UInt8](repeating: 0, count: 4_096) let count = Darwin.read(STDIN_FILENO, &bytes, bytes.count) if count == 0 { inputSource?.cancel() return } if count < 0 { if errno == EINTR { return } fail("Unable to read fixture controls: \(errno)") } input.append(contentsOf: bytes.prefix(count)) guard input.count <= 65_536 else { fail("Fixture control line exceeds 65536 bytes") } while let newline = input.firstIndex(of: 10) { let line = Data(input[.. 1 else { throw FixtureError(description: "Select tab needs a native tab group") } group.selectedWindow = window window.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) case "detach-tab": guard let group = window.tabGroup, group.windows.count > 1 else { throw FixtureError(description: "Detach tab needs a native tab group") } group.removeWindow(window) window.tabbingMode = .disallowed window.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) case "close": window.close() windows[index] = nil case "focus": window.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) case "enter-fullscreen", "exit-fullscreen": guard !window.fullscreenTransition else { throw FixtureError(description: "Fullscreen transition is active") } if window.styleMask.contains(.fullScreen) != (control.action == "enter-fullscreen") { window.toggleFullScreen(nil) } case "title": guard let title = control.title, !title.isEmpty else { throw FixtureError(description: "Title must not be empty") } window.title = title case "frame": guard let x = control.x, let y = control.y, let width = control.width, let height = control.height, [x, y, width, height].allSatisfy(\.isFinite), width > 0, height > 0, let primary = NSScreen.screens.first else { throw FixtureError(description: "Frame needs finite x/y and positive width/height on a display") } window.setFrame( NSRect(x: x, y: primary.frame.maxY - y - height, width: width, height: height), display: true) case "configure": guard control.slowResizeMilliseconds != nil || control.clampHeight != nil || control.adjustNextFrame != nil, control.slowResizeMilliseconds.map({ (0...5_000).contains($0) }) != false, (control.clampWidth == nil) == (control.clampHeight == nil), [control.clampWidth, control.clampHeight].compactMap({ $0 }).allSatisfy({ $0.isFinite && $0 > 0 }) else { throw FixtureError( description: "Configure needs a valid delay, positive clamp dimensions, or frame adjustment") } if let milliseconds = control.slowResizeMilliseconds { window.slowResizeMilliseconds = milliseconds } if let width = control.clampWidth, let height = control.clampHeight { window.clampSize = NSSize(width: width, height: height) } if let adjust = control.adjustNextFrame { window.adjustNextFrame = adjust } case "edge-control": try window.installEdgeControl() case "open-menu": guard fixtureMenu == nil, let view = window.contentView else { throw FixtureError(description: "A fixture menu is already scheduled or has no content view") } let menu = NSMenu(title: "Fixture Menu") menu.delegate = self menu.addItem(withTitle: "Fixture menu item", action: nil, keyEquivalent: "") fixtureMenu = menu RunLoop.main.perform(inModes: [.default]) { [weak self, weak window] in MainActor.assumeIsolated { guard let self else { return } guard let window, window.isVisible, let menu = self.fixtureMenu else { self.fixtureMenu = nil return } menu.popUp(positioning: nil, at: NSPoint(x: 40, y: view.bounds.maxY - 40), in: view) self.fixtureMenu = nil } } case "reset-metrics": throw FixtureError(description: "Write counters are monotonic; take a baseline snapshot instead") default: throw FixtureError(description: "Unknown control action: \(control.action)") } } private func sendReply(id: String, error: String? = nil) { guard let primary = NSScreen.screens.first else { fail("FixtureApp needs a display") } let states = windows.keys.sorted().compactMap { index -> WindowState? in guard let window = windows[index] else { return nil } let frame = window.frame let edgeControl = window.edgeControl.map { button -> ControlFrame in let rect = window.convertToScreen(button.convert(button.bounds, to: nil)) return ControlFrame( x: rect.minX, y: primary.frame.maxY - rect.maxY, width: rect.width, height: rect.height) } return WindowState( index: index, number: window.windowNumber, title: window.title, x: frame.minX, y: primary.frame.maxY - frame.maxY, width: frame.width, height: frame.height, frameWrites: window.frameWrites, resizeWrites: window.resizeWrites, slowResizeWrites: window.slowResizeWrites, clampedWrites: window.clampedWrites, adjustedWrites: window.adjustedWrites, slowResizeIntervals: window.slowResizeIntervals, fullscreen: window.styleMask.contains(.fullScreen), fullscreenTransition: window.fullscreenTransition, edgeControlClicks: window.edgeControlClicks, edgeControl: edgeControl) } let reply = Reply( id: id, pid: getpid(), windows: states, focusedWindow: windows.first { $0.value === NSApp.keyWindow }?.key, keyWindowNumber: NSApp.keyWindow?.windowNumber, menuOpen: menuOpen, error: error, recordings: replyRecordings, markNanoseconds: replyMark, overflow: windows.values.contains { $0.frameRecorder.overflow } || completedRecordings.contains { $0.overflow } || (replyRecordings?.contains { $0.overflow } ?? false) || inputRecorder.overflow, inputEvents: inputRecorder.events, menuReadRequests: (NSApp.mainMenu as? UnreadableMenu)?.readRequests ?? 0, auxiliaryWindows: auxiliaryWindows.map { window in AuxiliaryWindowState( kind: window is NSOpenPanel ? "open-panel" : (window.sheetParent == nil ? "panel" : "sheet"), number: window.windowNumber, parentNumber: window.sheetParent?.windowNumber, frameWrites: (window as? FixtureWindow)?.frameWrites ?? (window as? FixturePanel)?.frameWrites ?? (window as? FixtureOpenPanel)?.frameWrites ?? 0, resizeWrites: (window as? FixtureWindow)?.resizeWrites ?? (window as? FixturePanel)?.resizeWrites ?? (window as? FixtureOpenPanel)?.resizeWrites ?? 0) }) do { var data = try JSONEncoder().encode(reply) data.append(10) try FileHandle.standardOutput.write(contentsOf: data) } catch { fail("Unable to write fixture reply: \(error)") } } } private func fail(_ message: String) -> Never { FileHandle.standardError.write(Data("FixtureApp: \(message)\n".utf8)) exit(EXIT_FAILURE) } do { let options = try Options(arguments: Array(CommandLine.arguments.dropFirst())) if options.validate { var data = try JSONEncoder().encode(options) data.append(10) try FileHandle.standardOutput.write(contentsOf: data) } else { let application = NSApplication.shared if application.activationPolicy() != .regular { application.setActivationPolicy(.regular) } guard application.activationPolicy() == .regular else { throw FixtureError(description: "Unable to set application activation policy") } let menu = options.unreadableMenu ? UnreadableMenu(title: "Fixture") : NSMenu(title: "Fixture") let applicationItem = NSMenuItem(title: "Fixture", action: nil, keyEquivalent: "") let applicationMenu = NSMenu(title: "Fixture") applicationMenu.addItem(withTitle: "Open", action: nil, keyEquivalent: "o") applicationItem.submenu = applicationMenu menu.addItem(applicationItem) application.mainMenu = menu let delegate = FixtureDelegate(options: options) application.delegate = delegate guard let monitor = NSEvent.addLocalMonitorForEvents( matching: [.keyDown, .keyUp], handler: { event in MainActor.assumeIsolated { delegate.inputRecorder.record(event) } return event }) else { throw FixtureError(description: "Unable to install fixture keyboard recorder") } defer { NSEvent.removeMonitor(monitor) } withExtendedLifetime(delegate) { application.run() } } } catch { fail(String(describing: error)) }