diff --git a/Sources/CPrivateAPI/include/CPrivateAPI.h b/Sources/CPrivateAPI/include/CPrivateAPI.h index 3039cd82..6ff8b014 100644 --- a/Sources/CPrivateAPI/include/CPrivateAPI.h +++ b/Sources/CPrivateAPI/include/CPrivateAPI.h @@ -1,4 +1,4 @@ #pragma once #include -AXError _AXUIElementGetWindow(AXUIElementRef element, CGWindowID *outWindow); +typedef AXError (*TesseraAXGetWindowFunction)(AXUIElementRef element, CGWindowID *outWindow); diff --git a/Sources/TesseraPlatform/AXElement.swift b/Sources/TesseraPlatform/AXElement.swift new file mode 100644 index 00000000..ff693824 --- /dev/null +++ b/Sources/TesseraPlatform/AXElement.swift @@ -0,0 +1,184 @@ +public import ApplicationServices +public import CoreGraphics +import Darwin +import Foundation + +public enum AXPlatformError: Error, Equatable, Sendable { + case notPermitted + case timedOut + case messagingFailure + case attributeUnsupported + case elementInvalid + case noValue + case unexpectedValue(String) + case unavailable(String) + case other(Int32) + + public init(_ error: AXError) { + switch error { + case .apiDisabled: self = .notPermitted + case .cannotComplete: self = .messagingFailure + case .attributeUnsupported: self = .attributeUnsupported + case .invalidUIElement: self = .elementInvalid + case .noValue: self = .noValue + default: self = .other(error.rawValue) + } + } +} + +func checkAX(_ error: AXError) throws { + guard error == .success else { throw AXPlatformError(error) } +} + +public struct AXElement { + let raw: AXUIElement + let timeout: Float + + init(applicationPID: pid_t, timeout: Float = 0.35) throws { + try self.init(raw: AXUIElementCreateApplication(applicationPID), timeout: timeout) + } + + init(raw: AXUIElement, timeout: Float = 0.35) throws { + guard timeout.isFinite, timeout > 0 else { throw AXPlatformError.other(AXError.illegalArgument.rawValue) } + try checkAX(AXUIElementSetMessagingTimeout(raw, timeout)) + self.raw = raw + self.timeout = timeout + } + + static func checkCall(_ error: AXError, elapsed: Double, timeout: Float) throws { + if error == .cannotComplete && elapsed >= Double(timeout) * 0.9 { + throw AXPlatformError.timedOut + } + try checkAX(error) + } + + private func callAX(_ operation: () -> AXError) throws { + let start = DispatchTime.now().uptimeNanoseconds + let error = operation() + let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000 + try Self.checkCall(error, elapsed: elapsed, timeout: timeout) + } + + private func value(_ name: String) throws -> CFTypeRef { + var result: CFTypeRef? + try callAX { AXUIElementCopyAttributeValue(raw, name as CFString, &result) } + guard let result else { throw AXPlatformError.noValue } + return result + } + + private func checkedCF(_ result: CFTypeRef, type: CFTypeID, name: String) throws -> T { + guard CFGetTypeID(result) == type else { throw AXPlatformError.unexpectedValue(name) } + return Unmanaged.fromOpaque(Unmanaged.passUnretained(result).toOpaque()).takeUnretainedValue() + } + + private func string(_ name: String) throws -> String { + let result: CFString = try checkedCF(value(name), type: CFStringGetTypeID(), name: name) + return result as String + } + + private func boolean(_ name: String) throws -> Bool { + let result: CFBoolean = try checkedCF(value(name), type: CFBooleanGetTypeID(), name: name) + return CFBooleanGetValue(result) + } + + private func point(_ name: String) throws -> CGPoint { + let axValue: AXValue = try checkedCF(value(name), type: AXValueGetTypeID(), name: name) + var point = CGPoint.zero + guard AXValueGetType(axValue) == .cgPoint, AXValueGetValue(axValue, .cgPoint, &point) else { + throw AXPlatformError.unexpectedValue(name) + } + return point + } + + private func sizeValue(_ name: String) throws -> CGSize { + let axValue: AXValue = try checkedCF(value(name), type: AXValueGetTypeID(), name: name) + var size = CGSize.zero + guard AXValueGetType(axValue) == .cgSize, AXValueGetValue(axValue, .cgSize, &size) else { + throw AXPlatformError.unexpectedValue(name) + } + return size + } + + private func element(_ name: String) throws -> AXElement { + let result: AXUIElement = try checkedCF(value(name), type: AXUIElementGetTypeID(), name: name) + return try AXElement(raw: result, timeout: timeout) + } + + private func set(_ name: String, value: CFTypeRef) throws { + try callAX { AXUIElementSetAttributeValue(raw, name as CFString, value) } + } + + public var position: CGPoint { get throws { try point(kAXPositionAttribute) } } + public var size: CGSize { get throws { try sizeValue(kAXSizeAttribute) } } + public var frame: CGRect { get throws { try CGRect(origin: position, size: size) } } + public var title: String { get throws { try string(kAXTitleAttribute) } } + public var role: String { get throws { try string(kAXRoleAttribute) } } + public var subrole: String { get throws { try string(kAXSubroleAttribute) } } + public var minimized: Bool { get throws { try boolean(kAXMinimizedAttribute) } } + public var fullscreen: Bool { get throws { try boolean("AXFullScreen") } } + public var main: Bool { get throws { try boolean(kAXMainAttribute) } } + public var focused: Bool { get throws { try boolean(kAXFocusedAttribute) } } + public var enhancedUI: Bool { get throws { try boolean("AXEnhancedUserInterface") } } + public var focusedWindow: AXElement { get throws { try element(kAXFocusedWindowAttribute) } } + + public var windows: [AXElement] { + get throws { + let name = kAXWindowsAttribute + let array: CFArray = try checkedCF(value(name), type: CFArrayGetTypeID(), name: name) + return try (0...fromOpaque(pointer).takeUnretainedValue() + let element: AXUIElement = try checkedCF(object, type: AXUIElementGetTypeID(), name: name) + return try AXElement(raw: element, timeout: timeout) + } + } + } + + public func setPosition(_ point: CGPoint) throws { + var point = point + guard let result = AXValueCreate(.cgPoint, &point) else { + throw AXPlatformError.unexpectedValue(kAXPositionAttribute) + } + try set(kAXPositionAttribute, value: result) + } + + public func setSize(_ size: CGSize) throws { + var size = size + guard let result = AXValueCreate(.cgSize, &size) else { + throw AXPlatformError.unexpectedValue(kAXSizeAttribute) + } + try set(kAXSizeAttribute, value: result) + } + + public func setMinimized(_ value: Bool) throws { + try set(kAXMinimizedAttribute, value: value ? kCFBooleanTrue : kCFBooleanFalse) + } + public func setFullscreen(_ value: Bool) throws { + try set("AXFullScreen", value: value ? kCFBooleanTrue : kCFBooleanFalse) + } + public func setMain(_ value: Bool) throws { + try set(kAXMainAttribute, value: value ? kCFBooleanTrue : kCFBooleanFalse) + } + public func setFocused(_ value: Bool) throws { + try set(kAXFocusedAttribute, value: value ? kCFBooleanTrue : kCFBooleanFalse) + } + public func setEnhancedUI(_ value: Bool) throws { + try set("AXEnhancedUserInterface", value: value ? kCFBooleanTrue : kCFBooleanFalse) + } + public func setTitle(_ value: String) throws { try set(kAXTitleAttribute, value: value as CFString) } + public func setFocusedWindow(_ window: AXElement) throws { try set(kAXFocusedWindowAttribute, value: window.raw) } + + public func windowID() throws -> CGWindowID { + typealias GetWindow = @convention(c) (AXUIElement, UnsafeMutablePointer) -> AXError + guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "_AXUIElementGetWindow") else { + throw AXPlatformError.unavailable("_AXUIElementGetWindow") + } + let getWindow = unsafeBitCast(symbol, to: GetWindow.self) + var window: CGWindowID = 0 + try callAX { getWindow(raw, &window) } + guard window != 0 else { throw AXPlatformError.noValue } + return window + } +} diff --git a/Sources/TesseraPlatform/FrameWrites.swift b/Sources/TesseraPlatform/FrameWrites.swift new file mode 100644 index 00000000..16835b35 --- /dev/null +++ b/Sources/TesseraPlatform/FrameWrites.swift @@ -0,0 +1,78 @@ +public import AppKit +import CoreGraphics + +public struct AssistiveTechnology: Sendable, Equatable { + public let voiceOver: Bool + public let switchControl: Bool + + public init(voiceOver: Bool, switchControl: Bool) { + self.voiceOver = voiceOver + self.switchControl = switchControl + } + + @MainActor public static var current: Self { + Self(voiceOver: NSWorkspace.shared.isVoiceOverEnabled, switchControl: NSWorkspace.shared.isSwitchControlEnabled) + } +} + +public enum FrameWriteStep: Sendable, Equatable { + case size(CGSize) + case position(CGPoint) +} + +public struct FrameWritePlan: Sendable, Equatable { + public let steps: [FrameWriteStep] + + public init(current: CGRect, target: CGRect) { + var steps: [FrameWriteStep] = [] + if current.size != target.size { steps.append(.size(target.size)) } + if current.origin != target.origin { steps.append(.position(target.origin)) } + if current != target { steps.append(.size(target.size)) } + self.steps = steps + } +} + +public struct FrameWriteFailure: Error, Sendable { + public let writeError: any Error + public let restoreError: any Error +} + +extension AXElement { + func writeFrame(_ target: CGRect, application: AXElement, assistiveTechnology: AssistiveTechnology) throws -> CGRect + { + let plan = FrameWritePlan(current: try frame, target: target) + guard !plan.steps.isEmpty else { return target } + + var restoreEnhancedUI = false + if !assistiveTechnology.voiceOver && !assistiveTechnology.switchControl { + do { + if try application.enhancedUI { + try application.setEnhancedUI(false) + restoreEnhancedUI = true + } + } catch AXPlatformError.attributeUnsupported { + // An absent attribute cannot cause enhanced UI animation. + } + } + + do { + for step in plan.steps { + switch step { + case .size(let desired): + if try size != desired { try setSize(desired) } + case .position(let desired): + if try position != desired { try setPosition(desired) } + } + } + } catch { + if restoreEnhancedUI { + do { try application.setEnhancedUI(true) } catch let restoreError { + throw FrameWriteFailure(writeError: error, restoreError: restoreError) + } + } + throw error + } + if restoreEnhancedUI { try application.setEnhancedUI(true) } + return try frame + } +} diff --git a/Tests/TesseraPlatformTests/AXElementTests.swift b/Tests/TesseraPlatformTests/AXElementTests.swift new file mode 100644 index 00000000..0864c2b6 --- /dev/null +++ b/Tests/TesseraPlatformTests/AXElementTests.swift @@ -0,0 +1,54 @@ +import ApplicationServices +import Testing + +@testable import TesseraPlatform + +@Test(arguments: [ + (AXError.apiDisabled, AXPlatformError.notPermitted), + (.cannotComplete, .messagingFailure), + (.attributeUnsupported, .attributeUnsupported), + (.invalidUIElement, .elementInvalid), + (.noValue, .noValue), + (.failure, .other(AXError.failure.rawValue)), +]) +func mapsAccessibilityErrors(error: AXError, expected: AXPlatformError) { + #expect(AXPlatformError(error) == expected) +} + +@Test func distinguishesSlowCallsFromOtherMessagingFailures() { + #expect(throws: AXPlatformError.timedOut) { + try AXElement.checkCall(.cannotComplete, elapsed: 0.35, timeout: 0.35) + } + #expect(throws: AXPlatformError.messagingFailure) { + try AXElement.checkCall(.cannotComplete, elapsed: 0.01, timeout: 0.35) + } + #expect(throws: Never.self) { + try AXElement.checkCall(.success, elapsed: 1, timeout: 0.35) + } +} + +@Test func unchangedFrameHasNoWrites() { + let frame = CGRect(x: 10, y: 20, width: 300, height: 200) + #expect(FrameWritePlan(current: frame, target: frame).steps.isEmpty) +} + +@Test func changedFramePlansSizePositionSize() { + let old = CGRect(x: 10, y: 20, width: 300, height: 200) + let new = CGRect(x: 30, y: 40, width: 500, height: 400) + #expect( + FrameWritePlan(current: old, target: new).steps == [ + .size(new.size), .position(new.origin), .size(new.size), + ]) +} + +@Test func movedFrameStillChecksSizeAfterPosition() { + let old = CGRect(x: 10, y: 20, width: 300, height: 200) + let new = CGRect(x: 30, y: 40, width: 300, height: 200) + #expect(FrameWritePlan(current: old, target: new).steps == [.position(new.origin), .size(new.size)]) +} + +@Test func resizedFrameChecksSizeTwice() { + let old = CGRect(x: 10, y: 20, width: 300, height: 200) + let new = CGRect(x: 10, y: 20, width: 400, height: 400) + #expect(FrameWritePlan(current: old, target: new).steps == [.size(new.size), .size(new.size)]) +} -- knotmirror 0.0.1 From 1d8344976d6e79ba55cd3c27b85dbc555e17a3b6 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:36:11 -0400 Subject: [PATCH 02/44] Add window test fixture --- Sources/FixtureApp/main.swift | 162 +++++++++++++++- Tests/TesseraE2ETests/FixtureAppTests.swift | 198 ++++++++++++++++++++ 2 files changed, 359 insertions(+), 1 deletion(-) create mode 100644 Tests/TesseraE2ETests/FixtureAppTests.swift diff --git a/Sources/FixtureApp/main.swift b/Sources/FixtureApp/main.swift index 43dfdcef..16f32062 100644 --- a/Sources/FixtureApp/main.swift +++ b/Sources/FixtureApp/main.swift @@ -1 +1,161 @@ -print("FixtureApp") +import AppKit +import Darwin +import Foundation + +private struct Options { + var windowCount = 1 + var title = "Fixture" + var minimumSize: NSSize? + var slowMilliseconds: Int? + var dialog = false + + init(arguments: [String]) throws { + var index = 0 + while index < arguments.count { + let argument = arguments[index] + index += 1 + if argument == "--dialog" { + dialog = true + continue + } + guard ["--windows", "--title", "--min-size", "--slow"].contains(argument), + index < arguments.count + else { + throw ArgumentError(message: "Unknown option or missing value: \(argument)") + } + let value = arguments[index] + index += 1 + switch argument { + case "--windows": + guard let count = Int(value), count > 0 else { + throw ArgumentError(message: "--windows must be a positive integer") + } + windowCount = count + case "--title": + guard !value.isEmpty else { + throw ArgumentError(message: "--title must not be empty") + } + title = value + case "--min-size": + let dimensions = value.split(separator: "x", omittingEmptySubsequences: false) + guard dimensions.count == 2, + let width = Double(dimensions[0]), let height = Double(dimensions[1]), + width.isFinite, height.isFinite, width > 0, height > 0 + else { + throw ArgumentError(message: "--min-size must be WIDTHxHEIGHT with positive dimensions") + } + minimumSize = NSSize(width: width, height: height) + case "--slow": + guard let milliseconds = Int(value), milliseconds > 0 else { + throw ArgumentError(message: "--slow must be a positive number of milliseconds") + } + slowMilliseconds = milliseconds + default: + throw ArgumentError(message: "Unknown option: \(argument)") + } + } + } +} + +private struct ArgumentError: Error, CustomStringConvertible { + let message: String + var description: String { message } +} + +@MainActor +private final class FixtureDelegate: NSObject, NSApplicationDelegate { + private let options: Options + private var windows: [NSWindow] = [] + private var timer: Timer? + + init(options: Options) { + self.options = options + } + + func applicationDidFinishLaunching(_ notification: Notification) { + for index in 1...options.windowCount { + let window = NSWindow( + 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 + ) + window.title = "\(options.title) \(index)" + window.isReleasedWhenClosed = false + if let minimumSize = options.minimumSize { + window.minSize = minimumSize + let size = window.frame.size + window.setFrame( + NSRect( + origin: window.frame.origin, + size: NSSize( + width: max(size.width, minimumSize.width), + height: max(size.height, minimumSize.height) + ) + ), + display: false + ) + } + windows.append(window) + window.makeKeyAndOrderFront(nil) + } + + if options.dialog, let parent = windows.first { + let sheet = NSWindow( + 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 + windows.append(sheet) + parent.beginSheet(sheet) + + let panel = NSPanel( + 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 + windows.append(panel) + panel.orderFront(nil) + } + + if let milliseconds = options.slowMilliseconds { + let timer = Timer(timeInterval: 1, repeats: true) { _ in + Thread.sleep(forTimeInterval: TimeInterval(milliseconds) / 1_000) + } + RunLoop.main.add(timer, forMode: .common) + self.timer = timer + } + + NSApp.activate(ignoringOtherApps: true) + do { + try FileHandle.standardOutput.write(contentsOf: Data("ready \(getpid())\n".utf8)) + } catch { + FileHandle.standardError.write(Data("Unable to write ready line: \(error)\n".utf8)) + exit(EXIT_FAILURE) + } + } +} + +do { + let options = try Options(arguments: Array(CommandLine.arguments.dropFirst())) + let application = NSApplication.shared + guard application.setActivationPolicy(.regular) else { + throw ArgumentError(message: "Unable to set application activation policy") + } + let delegate = FixtureDelegate(options: options) + application.delegate = delegate + application.run() + withExtendedLifetime(delegate) {} +} catch { + FileHandle.standardError.write(Data("FixtureApp: \(error)\n".utf8)) + exit(EXIT_FAILURE) +} diff --git a/Tests/TesseraE2ETests/FixtureAppTests.swift b/Tests/TesseraE2ETests/FixtureAppTests.swift new file mode 100644 index 00000000..bcfd9a84 --- /dev/null +++ b/Tests/TesseraE2ETests/FixtureAppTests.swift @@ -0,0 +1,198 @@ +import ApplicationServices +import Darwin +import Foundation +import Testing + +private struct FixtureTestError: Error, CustomStringConvertible { + let description: String +} + +private func fixtureExecutable() throws -> URL { + var directory = Bundle.main.bundleURL + while directory.path != "/" { + let candidate = directory.appendingPathComponent("FixtureApp") + if FileManager.default.isExecutableFile(atPath: candidate.path) { + return candidate + } + directory.deleteLastPathComponent() + } + directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + while directory.path != "/" { + for path in ["FixtureApp", ".build/debug/FixtureApp"] { + let candidate = directory.appendingPathComponent(path) + if FileManager.default.isExecutableFile(atPath: candidate.path) { + return candidate + } + } + directory.deleteLastPathComponent() + } + throw FixtureTestError(description: "FixtureApp executable not found; build the FixtureApp product first") +} + +private func readyLine(from handle: FileHandle) throws -> String { + var bytes: [UInt8] = [] + let deadline = Date().addingTimeInterval(10) + while Date() < deadline { + var descriptor = pollfd(fd: handle.fileDescriptor, events: Int16(POLLIN), revents: 0) + let result = poll(&descriptor, 1, 100) + if result < 0 { + if errno == EINTR { continue } + throw FixtureTestError(description: "Polling fixture output failed: \(errno)") + } + if result == 0 { continue } + var byte: UInt8 = 0 + let count = Darwin.read(handle.fileDescriptor, &byte, 1) + guard count == 1 else { + throw FixtureTestError(description: "Fixture exited before its ready line") + } + if byte == 10 { return String(decoding: bytes, as: UTF8.self) } + bytes.append(byte) + guard bytes.count < 1_024 else { + throw FixtureTestError(description: "Fixture ready line is too long") + } + } + throw FixtureTestError(description: "Timed out waiting for fixture ready line") +} + +private func withFixture(arguments: [String], body: (Process) throws -> Void) throws { + let process = Process() + let output = Pipe() + process.executableURL = try fixtureExecutable() + process.arguments = arguments + process.standardOutput = output + try process.run() + defer { + if process.isRunning { process.terminate() } + process.waitUntilExit() + } + #expect(try readyLine(from: output.fileHandleForReading) == "ready \(process.processIdentifier)") + #expect(process.isRunning) + try body(process) +} + +private func axValue(_ element: AXUIElement, _ attribute: String) throws -> CFTypeRef? { + var value: CFTypeRef? + let result = AXUIElementCopyAttributeValue(element, attribute as CFString, &value) + if result == .noValue || result == .attributeUnsupported { return nil } + guard result == .success else { + throw FixtureTestError(description: "AX read \(attribute) failed: \(result.rawValue)") + } + return value +} + +private func axElements(_ element: AXUIElement, _ attribute: String) throws -> [AXUIElement] { + guard let value = try axValue(element, attribute) else { return [] } + guard let elements = value as? [AXUIElement] else { + throw FixtureTestError(description: "AX \(attribute) was not an element array") + } + return elements +} + +private func descendants(of element: AXUIElement, depth: Int = 0) throws -> [AXUIElement] { + guard depth < 10 else { return [] } + let children = try axElements(element, kAXChildrenAttribute) + return try [element] + children.flatMap { try descendants(of: $0, depth: depth + 1) } +} + +@Suite(.serialized) +struct FixtureAppTests { + @Test func rejectsInvalidArguments() throws { + let cases = [ + ["--windows", "0"], ["--windows"], ["--title", ""], + ["--min-size", "0x40"], ["--min-size", "10xnan"], + ["--slow", "-1"], ["--unknown"], + ] + for arguments in cases { + let process = Process() + let errors = Pipe() + process.executableURL = try fixtureExecutable() + process.arguments = arguments + process.standardError = errors + try process.run() + process.waitUntilExit() + let message = String(decoding: errors.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self) + #expect(process.terminationStatus != 0) + #expect(message.hasPrefix("FixtureApp:")) + } + } + + @Test func announcesReadinessAndStaysAlive() throws { + try withFixture(arguments: []) { process in + Thread.sleep(forTimeInterval: 0.2) + #expect(process.isRunning) + } + } + + @Test( + .enabled( + if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", + "Accessibility permission is required for fixture window tests" + )) + func createsWindowsSheetAndPanel() throws { + try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") + try withFixture(arguments: ["--windows", "2", "--title", "E2E Fixture", "--min-size", "720x540", "--dialog"]) { + process in + let app = AXUIElementCreateApplication(process.processIdentifier) + let deadline = Date().addingTimeInterval(5) + var windows: [AXUIElement] = [] + var titles: [String] = [] + var roles: [String] = [] + repeat { + windows = try axElements(app, kAXWindowsAttribute) + let all = try windows.flatMap { try descendants(of: $0) } + titles = try all.compactMap { try axValue($0, kAXTitleAttribute) as? String } + roles = try all.compactMap { try axValue($0, kAXRoleAttribute) as? String } + if titles.contains("E2E Fixture 1"), titles.contains("E2E Fixture 2"), + titles.contains("E2E Fixture Panel"), roles.contains(kAXSheetRole) + { + break + } + Thread.sleep(forTimeInterval: 0.1) + } while Date() < deadline + #expect(titles.contains("E2E Fixture 1")) + #expect(titles.contains("E2E Fixture 2")) + #expect(titles.contains("E2E Fixture Panel")) + #expect(roles.contains(kAXSheetRole)) + + let window = try #require( + windows.first { try axValue($0, kAXTitleAttribute) as? String == "E2E Fixture 2" }) + var requested = CGSize(width: 100, height: 100) + let size = try #require(AXValueCreate(.cgSize, &requested)) + try #require(AXUIElementSetAttributeValue(window, kAXSizeAttribute as CFString, size) == .success) + let actualValue = try #require(try axValue(window, kAXSizeAttribute)) + var minimum = CGSize(width: 720, height: 540) + let minimumValue = try #require(AXValueCreate(.cgSize, &minimum)) + #expect(CFEqual(actualValue, minimumValue)) + } + } + + @Test( + .enabled( + if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", + "Accessibility permission is required for fixture responsiveness tests" + )) + func slowOptionBlocksAccessibilityRepeatedly() throws { + try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") + try withFixture(arguments: ["--slow", "1200"]) { process in + let app = AXUIElementCreateApplication(process.processIdentifier) + #expect(AXUIElementSetMessagingTimeout(app, 0.6) == .success) + let deadline = Date().addingTimeInterval(8) + var slowCalls = 0 + while Date() < deadline && slowCalls < 2 { + let start = Date() + var value: CFTypeRef? + let result = AXUIElementCopyAttributeValue(app, kAXWindowsAttribute as CFString, &value) + guard result == .success || result == .cannotComplete else { + throw FixtureTestError(description: "AX read failed: \(result.rawValue)") + } + if Date().timeIntervalSince(start) >= 0.25 { + slowCalls += 1 + Thread.sleep(forTimeInterval: 1.3) + } else { + Thread.sleep(forTimeInterval: 0.1) + } + } + #expect(slowCalls == 2) + } + } +} -- knotmirror 0.0.1 From a0b2978dcbec3451a0e6ed463514b84d008752af Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:36:24 -0400 Subject: [PATCH 03/44] Add permission checks --- Sources/TesseraPlatform/Permissions.swift | 95 ++++++++++++++++ .../PermissionsTests.swift | 107 ++++++++++++++++++ 2 files changed, 202 insertions(+) create mode 100644 Sources/TesseraPlatform/Permissions.swift create mode 100644 Tests/TesseraPlatformTests/PermissionsTests.swift diff --git a/Sources/TesseraPlatform/Permissions.swift b/Sources/TesseraPlatform/Permissions.swift new file mode 100644 index 00000000..bddde09a --- /dev/null +++ b/Sources/TesseraPlatform/Permissions.swift @@ -0,0 +1,95 @@ +import AppKit +@preconcurrency import ApplicationServices +import CoreGraphics + +public enum AccessibilityStatus: Equatable, Sendable { + case granted + case notGranted + /// A previous grant was reported, but the process is not currently trusted. + /// This is not proof of a stale system entry; access may also have been revoked. + case possiblyStale + + public static func evaluate(isTrusted: Bool, wasPreviouslyGranted: Bool) -> Self { + if isTrusted { + return .granted + } + return wasPreviouslyGranted ? .possiblyStale : .notGranted + } +} + +public enum Permissions { + public enum SettingsPane: Sendable { + case accessibility + case inputMonitoring + + var url: URL? { + switch self { + case .accessibility: + URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") + case .inputMonitoring: + URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent") + } + } + } + + public enum PollingError: Error, Equatable, Sendable { + case invalidInterval + } + + /// The caller supplies evidence of a previous grant; this does not inspect System Settings. + public static func accessibilityStatus(wasPreviouslyGranted: Bool = false) -> AccessibilityStatus { + AccessibilityStatus.evaluate( + isTrusted: AXIsProcessTrusted(), + wasPreviouslyGranted: wasPreviouslyGranted + ) + } + + /// Requests the system prompt if needed. The result is the current trust state, not the prompt's outcome. + @discardableResult + public static func requestAccessibility() -> Bool { + let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary + return AXIsProcessTrustedWithOptions(options) + } + + /// Waits without prompting until Accessibility is granted or the task is cancelled. + public static func waitForAccessibility(pollInterval: Duration = .seconds(1)) async throws { + try await waitForAccessibility( + pollInterval: pollInterval, + isTrusted: { AXIsProcessTrusted() }, + sleep: { try await Task.sleep(for: $0) } + ) + } + + static func waitForAccessibility( + pollInterval: Duration, + isTrusted: @Sendable () async -> Bool, + sleep: @Sendable (Duration) async throws -> Void + ) async throws { + guard pollInterval > .zero else { throw PollingError.invalidInterval } + while true { + try Task.checkCancellation() + let trusted = await isTrusted() + try Task.checkCancellation() + if trusted { return } + try await sleep(pollInterval) + } + } + + public static func inputMonitoringIsGranted() -> Bool { + CGPreflightListenEventAccess() + } + + /// Requests Input Monitoring access and returns the system's current result. + @discardableResult + public static func requestInputMonitoring() -> Bool { + CGRequestListenEventAccess() + } + + /// Returns whether System Settings accepted the request to open the pane. + @MainActor + @discardableResult + public static func openSettings(_ pane: SettingsPane) -> Bool { + guard let url = pane.url else { return false } + return NSWorkspace.shared.open(url) + } +} diff --git a/Tests/TesseraPlatformTests/PermissionsTests.swift b/Tests/TesseraPlatformTests/PermissionsTests.swift new file mode 100644 index 00000000..4f793965 --- /dev/null +++ b/Tests/TesseraPlatformTests/PermissionsTests.swift @@ -0,0 +1,107 @@ +import Testing + +@testable import TesseraPlatform + +@Test(arguments: [ + (true, true, AccessibilityStatus.granted), + (true, false, AccessibilityStatus.granted), + (false, true, AccessibilityStatus.possiblyStale), + (false, false, AccessibilityStatus.notGranted), +]) +func accessibilityStatusUsesCurrentTrustAndPreviousEvidence( + isTrusted: Bool, + wasPreviouslyGranted: Bool, + expected: AccessibilityStatus +) { + #expect( + AccessibilityStatus.evaluate(isTrusted: isTrusted, wasPreviouslyGranted: wasPreviouslyGranted) == expected + ) +} + +private actor PollProbe { + var checks = 0 + var sleeps = 0 + + func trustAfterTwoChecks() -> Bool { + checks += 1 + return checks >= 3 + } + + func recordSleep() { + sleeps += 1 + } +} + +@Test func pollingChecksImmediatelyAndStopsAfterGrant() async throws { + let probe = PollProbe() + try await Permissions.waitForAccessibility( + pollInterval: .seconds(2), + isTrusted: { await probe.trustAfterTwoChecks() }, + sleep: { interval in + #expect(interval == .seconds(2)) + await probe.recordSleep() + } + ) + #expect(await probe.checks == 3) + #expect(await probe.sleeps == 2) +} + +@Test(arguments: [Duration.zero, .seconds(-1)]) +func pollingRejectsInvalidIntervals(interval: Duration) async { + let probe = PollProbe() + await #expect(throws: Permissions.PollingError.invalidInterval) { + try await Permissions.waitForAccessibility( + pollInterval: interval, + isTrusted: { await probe.trustAfterTwoChecks() }, + sleep: { _ in await probe.recordSleep() } + ) + } + #expect(await probe.checks == 0) + #expect(await probe.sleeps == 0) +} + +@Test func cancellationInterruptsPollingSleep() async { + let (enteredSleep, continuation) = AsyncStream.makeStream() + let task = Task { + try await Permissions.waitForAccessibility( + pollInterval: .seconds(3600), + isTrusted: { false }, + sleep: { interval in + continuation.yield(()) + try await Task.sleep(for: interval) + } + ) + } + var iterator = enteredSleep.makeAsyncIterator() + _ = await iterator.next() + task.cancel() + await #expect(throws: CancellationError.self) { + try await task.value + } + continuation.finish() +} + +@Test func pollingChecksCancellationBeforeAcceptingTrust() async { + let task = Task { + withUnsafeCurrentTask { $0?.cancel() } + try await Permissions.waitForAccessibility( + pollInterval: .seconds(1), + isTrusted: { true }, + sleep: { _ in } + ) + } + await #expect(throws: CancellationError.self) { + try await task.value + } +} + +@Test func settingsPanesUseCorrectPrivacyAnchors() { + #expect( + Permissions.SettingsPane.accessibility.url?.absoluteString + == "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" + ) + #expect( + Permissions.SettingsPane.inputMonitoring.url?.absoluteString + == "x-apple.systempreferences:com.apple.preference.security?Privacy_ListenEvent" + ) +} -- knotmirror 0.0.1 From 1560b853ffec37f6609ebc63508ebcfc818fef53 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:37:05 -0400 Subject: [PATCH 04/44] Add source-aware TOML parsing and lossless edits --- Package.swift | 5 +- Sources/TesseraConfig/ConfigText.swift | 7 + .../TesseraConfig/Resources/Parser.xcstrings | 36 ++ Sources/TesseraConfig/TOMLDocument.swift | 150 ++++++ Sources/TesseraConfig/TOMLModel.swift | 78 +++ Sources/TesseraConfig/TOMLParser.swift | 477 ++++++++++++++++++ Sources/TesseraConfig/TesseraConfig.swift | 1 - .../TOMLDocumentTests.swift | 178 +++++++ .../TesseraConfigTests/TOMLParserTests.swift | 222 ++++++++ .../TesseraConfigTests.swift | 4 - 10 files changed, 1152 insertions(+), 6 deletions(-) create mode 100644 Sources/TesseraConfig/ConfigText.swift create mode 100644 Sources/TesseraConfig/Resources/Parser.xcstrings create mode 100644 Sources/TesseraConfig/TOMLDocument.swift create mode 100644 Sources/TesseraConfig/TOMLModel.swift create mode 100644 Sources/TesseraConfig/TOMLParser.swift delete mode 100644 Sources/TesseraConfig/TesseraConfig.swift create mode 100644 Tests/TesseraConfigTests/TOMLDocumentTests.swift create mode 100644 Tests/TesseraConfigTests/TOMLParserTests.swift delete mode 100644 Tests/TesseraConfigTests/TesseraConfigTests.swift diff --git a/Package.swift b/Package.swift index 61373897..67a5fdc5 100644 --- a/Package.swift +++ b/Package.swift @@ -19,7 +19,10 @@ let package = Package( ], targets: [ .target(name: "TesseraCore", swiftSettings: strict), - .target(name: "TesseraConfig", dependencies: ["TesseraCore"], swiftSettings: strict), + .target( + name: "TesseraConfig", dependencies: ["TesseraCore"], + resources: [.process("Resources")], swiftSettings: strict + ), .target(name: "CPrivateAPI", linkerSettings: [.linkedFramework("ApplicationServices")]), .target(name: "TesseraPlatform", dependencies: ["TesseraCore", "CPrivateAPI"], swiftSettings: strict), .target(name: "TesseraAnimation", dependencies: ["TesseraCore"], swiftSettings: strict), diff --git a/Sources/TesseraConfig/ConfigText.swift b/Sources/TesseraConfig/ConfigText.swift new file mode 100644 index 00000000..6d1b2d0e --- /dev/null +++ b/Sources/TesseraConfig/ConfigText.swift @@ -0,0 +1,7 @@ +import Foundation + +enum ConfigText { + static func position(line: Int, column: Int, message: String) -> String { + String(localized: "line \(line), column \(column): \(message)", table: "Parser", bundle: .module) + } +} diff --git a/Sources/TesseraConfig/Resources/Parser.xcstrings b/Sources/TesseraConfig/Resources/Parser.xcstrings new file mode 100644 index 00000000..85619cee --- /dev/null +++ b/Sources/TesseraConfig/Resources/Parser.xcstrings @@ -0,0 +1,36 @@ +{ + "sourceLanguage": "en", + "strings": { + "line %lld, column %lld: %@": {}, + "Expected `%@` here.": {}, + "Use a newline or a CRLF pair, not a bare carriage return.": {}, + "Comments cannot contain control characters.": {}, + "Put each assignment or table header on its own line.": {}, + "Expected a key, like `gap` or `\"display name\"`.": {}, + "This value is nested too deeply; use fewer than 128 levels.": {}, + "Inline tables cannot end with a trailing comma.": {}, + "Dates and times are not supported in Tessera config; quote this value to use it as text.": {}, + "This integer is outside the signed 64-bit range.": {}, + "This floating-point number is too large; use `inf` only when infinity is intended.": {}, + "Expected a string, number, boolean, array, or inline table; text needs quotes.": {}, + "Expected a quoted string.": {}, + "Keys must use single-line strings.": {}, + "Too many closing quotes; escape quotes inside the string.": {}, + "A line continuation needs a newline after the backslash.": {}, + "Single-line strings cannot contain a newline.": {}, + "Strings cannot contain unescaped control characters.": {}, + "This string is missing its closing quote.": {}, + "This escape sequence is incomplete.": {}, + "A Unicode escape needs four or eight hexadecimal digits.": {}, + "This Unicode escape is not a valid Unicode scalar.": {}, + "Unknown escape sequence; use `\\\\` for a literal backslash.": {}, + "`%@` was already defined at line %lld, column %lld.": {}, + "A dotted key cannot extend a value or an inline table.": {}, + "A dotted key cannot redefine a table declared by a header.": {}, + "A table header cannot extend a value or an inline table.": {}, + "This array of tables has no current table.": {}, + "Choose a value or a new table key, not a table header or an array index.": {}, + "Add a value inside an existing table before editing this path.": {} + }, + "version": "1.0" +} diff --git a/Sources/TesseraConfig/TOMLDocument.swift b/Sources/TesseraConfig/TOMLDocument.swift new file mode 100644 index 00000000..22132677 --- /dev/null +++ b/Sources/TesseraConfig/TOMLDocument.swift @@ -0,0 +1,150 @@ +import Foundation + +public struct TOMLDocument: Sendable { + public private(set) var source: String + public private(set) var root: TOMLNode + private var sections: [TOMLSection] + private var editableRanges: [[TOMLPathComponent]: SourceRange] + + public init(parsing source: String) throws { + var reader = TOMLReader(source) + self.root = try reader.parse() + self.source = source + self.sections = reader.sections + self.editableRanges = reader.editableRanges + } + + public func render() -> String { source } + + public func node(at path: [TOMLPathComponent]) -> TOMLNode? { + var node = root + for component in path { + switch (component, node.value) { + case (.key(let key), .table(let entries)): + guard let child = entries[key] else { return nil } + node = child + case (.index(let index), .array(let entries)): + guard entries.indices.contains(index) else { return nil } + node = entries[index] + default: return nil + } + } + return node + } + + public func node(forKey path: [String]) -> TOMLNode? { + node(at: path.map { .key($0) }) + } + + public mutating func setValue(_ value: TOMLValue, forKey path: [String]) throws { + try setValue(value, at: path.map { .key($0) }) + } + + /// Reparse before committing an edit so a failed change never damages the document. + public mutating func setValue(_ value: TOMLValue, at path: [TOMLPathComponent]) throws { + let replacement = try TOMLWriter.encode(value) + if let range = editableRanges[path] { + try replace(range.start.offset.. String? in + guard case .key(let key) = component else { return nil } + return TOMLWriter.quote(key) + } + let newline = source.contains("\r\n") ? "\r\n" : "\n" + let offset = section.insertionOffset + let needsNewline = offset > 0 && Array(source.unicodeScalars)[offset - 1] != "\n" + let assignment = (needsNewline ? newline : "") + keys.joined(separator: ".") + " = " + replacement + newline + try replace(offset.., with replacement: String) throws { + var scalars = Array(source.unicodeScalars) + scalars.replaceSubrange(offsets, with: replacement.unicodeScalars) + self = try TOMLDocument(parsing: String(String.UnicodeScalarView(scalars))) + } + + private func editingError(_ message: String.LocalizationValue) -> ConfigDiagnostic { + ConfigDiagnostic(message: String(localized: message, table: "Parser", bundle: .module)) + } +} + +public enum TOMLWriter { + public static func write(_ document: TOMLDocument) -> String { document.source } + + public static func encode(_ value: TOMLValue) throws -> String { + try encode(value, depth: 0) + } + + private static func encode(_ value: TOMLValue, depth: Int) throws -> String { + guard depth < 128 else { + throw ConfigDiagnostic( + message: String( + localized: "This value is nested too deeply; use fewer than 128 levels.", table: "Parser", + bundle: .module) + ) + } + switch value { + case .string(let string): return quote(string) + case .integer(let integer): return String(integer) + case .float(let number): + if number.isNaN { return "nan" } + if number == .infinity { return "inf" } + if number == -.infinity { return "-inf" } + return String(number) + case .bool(let bool): return bool ? "true" : "false" + case .array(let values): + return "[" + (try values.map { try encode($0.value, depth: depth + 1) }).joined(separator: ", ") + "]" + case .table(let values): + let pairs = try values.sorted { $0.key < $1.key }.map { key, node in + quote(key) + " = " + (try encode(node.value, depth: depth + 1)) + } + return "{" + pairs.joined(separator: ", ") + "}" + } + } + + static func quote(_ string: String) -> String { + var result = "\"" + for scalar in string.unicodeScalars { + switch scalar { + case "\"": result += "\\\"" + case "\\": result += "\\\\" + case "\n": result += "\\n" + case "\r": result += "\\r" + case "\t": result += "\\t" + case "\u{08}": result += "\\b" + case "\u{0C}": result += "\\f" + default: + if scalar.value < 0x20 || scalar.value == 0x7F { + let hex = String(scalar.value, radix: 16, uppercase: true) + result += "\\u" + String(repeating: "0", count: 4 - hex.count) + hex + } else { + result.unicodeScalars.append(scalar) + } + } + } + return result + "\"" + } +} diff --git a/Sources/TesseraConfig/TOMLModel.swift b/Sources/TesseraConfig/TOMLModel.swift new file mode 100644 index 00000000..c405a874 --- /dev/null +++ b/Sources/TesseraConfig/TOMLModel.swift @@ -0,0 +1,78 @@ +public struct SourceLocation: Sendable, Equatable, Hashable { + public let line: Int + public let column: Int + /// Offset in Unicode scalars, not UTF-8 bytes or grapheme clusters. + public let offset: Int + + public init(line: Int = 1, column: Int = 1, offset: Int = 0) { + self.line = line + self.column = column + self.offset = offset + } +} + +public struct SourceRange: Sendable, Equatable { + public let start: SourceLocation + public let end: SourceLocation + + public init(start: SourceLocation, end: SourceLocation) { + self.start = start + self.end = end + } +} + +public struct ConfigDiagnostic: Error, Sendable, Equatable, CustomStringConvertible { + public enum Severity: String, Sendable { + case warning, error + } + + public let severity: Severity + public let location: SourceLocation + public let message: String + public let relatedLocation: SourceLocation? + + public init( + severity: Severity = .error, location: SourceLocation = SourceLocation(), + message: String, relatedLocation: SourceLocation? = nil + ) { + self.severity = severity + self.location = location + self.message = message + self.relatedLocation = relatedLocation + } + + public var description: String { + ConfigText.position(line: location.line, column: location.column, message: message) + } +} + +public indirect enum TOMLValue: Sendable, Equatable { + case string(String) + case integer(Int64) + case float(Double) + case bool(Bool) + case array([TOMLNode]) + case table([String: TOMLNode]) +} + +public struct TOMLNode: Sendable, Equatable { + public let value: TOMLValue + public let range: SourceRange + public let keyRange: SourceRange? + + public init(value: TOMLValue, range: SourceRange, keyRange: SourceRange? = nil) { + self.value = value + self.range = range + self.keyRange = keyRange + } + + public subscript(key: String) -> TOMLNode? { + guard case .table(let entries) = value else { return nil } + return entries[key] + } +} + +public enum TOMLPathComponent: Sendable, Equatable, Hashable { + case key(String) + case index(Int) +} diff --git a/Sources/TesseraConfig/TOMLParser.swift b/Sources/TesseraConfig/TOMLParser.swift new file mode 100644 index 00000000..cdf3f17a --- /dev/null +++ b/Sources/TesseraConfig/TOMLParser.swift @@ -0,0 +1,477 @@ +import Foundation + +public enum TOMLParser { + public static func parse(_ source: String) throws -> TOMLDocument { + try TOMLDocument(parsing: source) + } +} + +struct TOMLSection: Sendable { + let path: [TOMLPathComponent] + let insertionOffset: Int +} + +private final class ParsedNode { + enum Content { + case value(TOMLValue) + case table([String: ParsedNode]) + case array([ParsedNode]) + } + + var content: Content + var range: SourceRange + var keyRange: SourceRange? + var declared = false + var dotted = false + var sealed = false + var arrayOfTables = false + + init(_ content: Content, range: SourceRange) { + self.content = content + self.range = range + } + + func freeze() -> TOMLNode { + let value: TOMLValue + switch content { + case .value(let scalar): value = scalar + case .table(let entries): value = .table(entries.mapValues { $0.freeze() }) + case .array(let entries): value = .array(entries.map { $0.freeze() }) + } + return TOMLNode(value: value, range: range, keyRange: keyRange) + } +} + +struct TOMLReader { + private let scalars: [Unicode.Scalar] + private var index = 0 + private var lineStarts = [0] + private var depth = 0 + private(set) var sections = [TOMLSection(path: [], insertionOffset: 0)] + private(set) var editableRanges: [[TOMLPathComponent]: SourceRange] = [:] + + init(_ source: String) { + scalars = Array(source.unicodeScalars) + for (offset, scalar) in scalars.enumerated() where scalar == "\n" { + lineStarts.append(offset + 1) + } + } + + mutating func parse() throws -> TOMLNode { + let root = ParsedNode(.table([:]), range: range(0, scalars.count)) + var current = root + var currentPath: [TOMLPathComponent] = [] + while !atEnd { + skipSpaces() + if peek() == "#" { try skipComment() } + if try consumeNewline() { continue } + if atEnd { break } + if peek() == "[" { + let start = index + index += 1 + let isArray = consume("[") + let keys = try parseKeys() + try expect("]") + if isArray { try expect("]") } + (current, currentPath) = try openTable(root, keys: keys, isArray: isArray, start: start) + try finishLine() + sections.append(TOMLSection(path: currentPath, insertionOffset: index)) + } else { + let keys = try parseKeys() + try expect("=") + skipSpaces() + let value = try parseValue() + try insert(value, keys: keys, into: current) + recordEditable(value, path: currentPath + keys.map { .key($0.0) }) + try finishLine() + } + } + return root.freeze() + } + + private var atEnd: Bool { index >= scalars.count } + + private func peek(_ ahead: Int = 0) -> Unicode.Scalar? { + let position = index + ahead + return position < scalars.count ? scalars[position] : nil + } + + private func location(_ offset: Int) -> SourceLocation { + var low = 0 + var high = lineStarts.count + while low + 1 < high { + let middle = (low + high) / 2 + if lineStarts[middle] <= offset { low = middle } else { high = middle } + } + return SourceLocation(line: low + 1, column: offset - lineStarts[low] + 1, offset: offset) + } + + private func range(_ start: Int, _ end: Int) -> SourceRange { + SourceRange(start: location(start), end: location(end)) + } + + private func error(_ message: String.LocalizationValue, at offset: Int? = nil) -> ConfigDiagnostic { + ConfigDiagnostic( + location: location(offset ?? index), + message: String(localized: message, table: "Parser", bundle: .module) + ) + } + + private mutating func consume(_ scalar: Unicode.Scalar) -> Bool { + guard peek() == scalar else { return false } + index += 1 + return true + } + + private mutating func expect(_ scalar: Unicode.Scalar) throws { + guard consume(scalar) else { throw error("Expected `\(String(scalar))` here.") } + } + + private mutating func skipSpaces() { + while peek() == " " || peek() == "\t" { index += 1 } + } + + private mutating func consumeNewline() throws -> Bool { + if consume("\n") { return true } + if peek() == "\r" { + guard peek(1) == "\n" else { throw error("Use a newline or a CRLF pair, not a bare carriage return.") } + index += 2 + return true + } + return false + } + + private mutating func skipComment() throws { + while let scalar = peek(), scalar != "\n", scalar != "\r" { + guard !isForbiddenControl(scalar) else { throw error("Comments cannot contain control characters.") } + index += 1 + } + } + + private mutating func finishLine() throws { + skipSpaces() + if peek() == "#" { try skipComment() } + if atEnd { return } + guard try consumeNewline() else { throw error("Put each assignment or table header on its own line.") } + } + + private mutating func skipArrayWhitespace() throws { + while true { + skipSpaces() + if peek() == "#" { try skipComment() } + if try !consumeNewline() { break } + } + } + + private func isForbiddenControl(_ scalar: Unicode.Scalar) -> Bool { + scalar.value < 0x20 && scalar != "\t" || scalar.value == 0x7F + } + + private func isBareKey(_ scalar: Unicode.Scalar) -> Bool { + switch scalar.value { + case 48...57, 65...90, 97...122, 45, 95: true + default: false + } + } + + private mutating func parseKeys() throws -> [(String, SourceRange)] { + var keys: [(String, SourceRange)] = [] + repeat { + skipSpaces() + let start = index + let key: String + if peek() == "\"" || peek() == "'" { + key = try parseString(allowMultiline: false) + } else { + while let scalar = peek(), isBareKey(scalar) { index += 1 } + guard index > start else { throw error("Expected a key, like `gap` or `\"display name\"`.") } + key = text(start, index) + } + keys.append((key, range(start, index))) + skipSpaces() + } while consume(".") + return keys + } + + private func text(_ start: Int, _ end: Int) -> String { + String(String.UnicodeScalarView(scalars[start.. ParsedNode { + guard depth < 128 else { throw error("This value is nested too deeply; use fewer than 128 levels.") } + depth += 1 + defer { depth -= 1 } + let start = index + let content: ParsedNode.Content + switch peek() { + case "\"", "'": content = .value(.string(try parseString(allowMultiline: true))) + case "[": + index += 1 + var values: [ParsedNode] = [] + try skipArrayWhitespace() + if !consume("]") { + while true { + values.append(try parseValue()) + try skipArrayWhitespace() + if consume("]") { break } + try expect(",") + try skipArrayWhitespace() + if consume("]") { break } + } + } + content = .array(values) + case "{": + index += 1 + let table = ParsedNode(.table([:]), range: range(start, index)) + skipSpaces() + if !consume("}") { + while true { + let keys = try parseKeys() + try expect("=") + skipSpaces() + try insert(try parseValue(), keys: keys, into: table) + skipSpaces() + if consume("}") { break } + try expect(",") + skipSpaces() + if peek() == "}" { throw error("Inline tables cannot end with a trailing comma.") } + } + } + table.range = range(start, index) + table.sealed = true + return table + default: content = .value(try parseScalar()) + } + return ParsedNode(content, range: range(start, index)) + } + + private mutating func parseScalar() throws -> TOMLValue { + let start = index + while let scalar = peek(), ![" ", "\t", "\r", "\n", "#", ",", "]", "}"].contains(scalar) { + index += 1 + } + let token = text(start, index) + if token == "true" { return .bool(true) } + if token == "false" { return .bool(false) } + if token.range(of: #"^\d{4}-\d{2}-\d{2}|^\d{2}:\d{2}:\d{2}"#, options: .regularExpression) != nil { + throw error( + "Dates and times are not supported in Tessera config; quote this value to use it as text.", at: start) + } + if ["inf", "+inf", "-inf", "nan", "+nan", "-nan"].contains(token) { + return .float(token.hasSuffix("nan") ? .nan : (token == "-inf" ? -.infinity : .infinity)) + } + let patterns: [(String, Int)] = [ + (#"^0x[0-9a-fA-F](?:_?[0-9a-fA-F])*$"#, 16), + (#"^0o[0-7](?:_?[0-7])*$"#, 8), + (#"^0b[01](?:_?[01])*$"#, 2), + (#"^[+-]?(?:0|[1-9](?:_?[0-9])*)$"#, 10), + ] + for (pattern, radix) in patterns where token.range(of: pattern, options: .regularExpression) != nil { + let digits = radix == 10 ? token : String(token.dropFirst(2)) + guard let integer = Int64(digits.replacingOccurrences(of: "_", with: ""), radix: radix) else { + throw error("This integer is outside the signed 64-bit range.", at: start) + } + return .integer(integer) + } + let floatPattern = + #"^[+-]?(?:0|[1-9](?:_?[0-9])*)(?:(?:\.[0-9](?:_?[0-9])*)(?:[eE][+-]?[0-9](?:_?[0-9])*)?|[eE][+-]?[0-9](?:_?[0-9])*)$"# + if token.range(of: floatPattern, options: .regularExpression) != nil { + guard let number = Double(token.replacingOccurrences(of: "_", with: "")), number.isFinite else { + throw error( + "This floating-point number is too large; use `inf` only when infinity is intended.", at: start) + } + return .float(number) + } + throw error("Expected a string, number, boolean, array, or inline table; text needs quotes.", at: start) + } + + private mutating func parseString(allowMultiline: Bool) throws -> String { + let start = index + guard let quote = peek() else { throw error("Expected a quoted string.") } + index += 1 + let multiline = peek() == quote && peek(1) == quote + if multiline { + guard allowMultiline else { throw error("Keys must use single-line strings.", at: start) } + index += 2 + _ = try consumeNewline() + } + var result = String.UnicodeScalarView() + while let scalar = peek() { + if scalar == quote { + if !multiline { + index += 1 + return String(result) + } + var count = 0 + while peek(count) == quote { count += 1 } + if count >= 3 { + guard count <= 5 else { throw error("Too many closing quotes; escape quotes inside the string.") } + for _ in 3.. Unicode.Scalar { + let start = index - 1 + guard let scalar = peek() else { throw error("This escape sequence is incomplete.", at: start) } + index += 1 + switch scalar { + case "b": return "\u{08}" + case "t": return "\t" + case "n": return "\n" + case "f": return "\u{0C}" + case "r": return "\r" + case "\"": return "\"" + case "\\": return "\\" + case "u", "U": + let length = scalar == "u" ? 4 : 8 + let digitsStart = index + for _ in 0.. ConfigDiagnostic { + let first = previous.keyRange?.start ?? previous.range.start + return ConfigDiagnostic( + location: range.start, + message: String( + localized: "`\(key)` was already defined at line \(first.line), column \(first.column).", + table: "Parser", bundle: .module + ), relatedLocation: first + ) + } + + private func insert(_ value: ParsedNode, keys: [(String, SourceRange)], into table: ParsedNode) throws { + var current = table + for (position, pair) in keys.enumerated() { + let (key, keyRange) = pair + guard case .table(var entries) = current.content, !current.sealed else { + throw error("A dotted key cannot extend a value or an inline table.", at: keyRange.start.offset) + } + if position == keys.count - 1 { + if let previous = entries[key] { throw duplicate(key, range: keyRange, previous: previous) } + value.keyRange = keyRange + entries[key] = value + current.content = .table(entries) + } else if let next = entries[key] { + guard !next.declared else { + throw error("A dotted key cannot redefine a table declared by a header.", at: keyRange.start.offset) + } + current = next + } else { + let next = ParsedNode(.table([:]), range: keyRange) + next.keyRange = keyRange + next.dotted = true + entries[key] = next + current.content = .table(entries) + current = next + } + } + } + + private func openTable( + _ root: ParsedNode, keys: [(String, SourceRange)], isArray: Bool, start: Int + ) throws -> (ParsedNode, [TOMLPathComponent]) { + var current = root + var path: [TOMLPathComponent] = [] + for (position, pair) in keys.enumerated() { + let (key, keyRange) = pair + let last = position == keys.count - 1 + guard case .table(var entries) = current.content, !current.sealed else { + throw error("A table header cannot extend a value or an inline table.", at: keyRange.start.offset) + } + path.append(.key(key)) + let next: ParsedNode + if let existing = entries[key] { + next = existing + } else { + next = ParsedNode(isArray && last ? .array([]) : .table([:]), range: keyRange) + next.keyRange = keyRange + next.arrayOfTables = isArray && last + entries[key] = next + current.content = .table(entries) + } + if next.arrayOfTables, case .array(var elements) = next.content { + if last && isArray { + let element = ParsedNode(.table([:]), range: range(start, index)) + element.declared = true + element.keyRange = keyRange + elements.append(element) + next.content = .array(elements) + } else if last { + throw duplicate(key, range: keyRange, previous: next) + } + guard let element = elements.last else { + throw error("This array of tables has no current table.", at: keyRange.start.offset) + } + path.append(.index(elements.count - 1)) + current = element + } else { + guard case .table = next.content, !next.sealed else { + throw duplicate(key, range: keyRange, previous: next) + } + if last { + guard !isArray, !next.declared, !next.dotted else { + throw duplicate(key, range: keyRange, previous: next) + } + next.declared = true + next.range = range(start, index) + next.keyRange = keyRange + } + current = next + } + } + return (current, path) + } + + private mutating func recordEditable(_ node: ParsedNode, path: [TOMLPathComponent]) { + if !node.dotted { editableRanges[path] = node.range } + switch node.content { + case .table(let entries): + for (key, child) in entries { recordEditable(child, path: path + [.key(key)]) } + case .array(let entries): + for (index, child) in entries.enumerated() { recordEditable(child, path: path + [.index(index)]) } + case .value: break + } + } +} diff --git a/Sources/TesseraConfig/TesseraConfig.swift b/Sources/TesseraConfig/TesseraConfig.swift deleted file mode 100644 index 8b137891..00000000 --- a/Sources/TesseraConfig/TesseraConfig.swift +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Tests/TesseraConfigTests/TOMLDocumentTests.swift b/Tests/TesseraConfigTests/TOMLDocumentTests.swift new file mode 100644 index 00000000..ad81efa1 --- /dev/null +++ b/Tests/TesseraConfigTests/TOMLDocumentTests.swift @@ -0,0 +1,178 @@ +import Testing + +@testable import TesseraConfig + +@Suite struct TOMLDocumentTests { + private let sample = """ + # My desk, my rules. + version = 1 + + [general] # Start here. + prefix = 'ctrl-alt' + launch-at-login = false + + [layout] + default = "grid" + ratio = 0.5 # Give both sides room. + gaps = { inner = 8, outer = 12 } + + [[float-rules]] + bundle-id = 'org.example.notes' + title-regex = '^Quick .*$' + + [[float-rules]] + role = 'AXDialog' + """ + + @Test(arguments: [ + "", "# Only a comment", "\n\n", "x = [1,\n # note\n 2,]\n", "'odd key'\t=\t'''raw text''' # keep", + ]) + func unchangedSourceIsByteExact(source: String) throws { + let document = try TOMLDocument(parsing: source) + #expect(document.render() == source) + #expect(TOMLWriter.write(document) == source) + } + + @Test func realisticFileRoundTrips() throws { + #expect(try TOMLDocument(parsing: sample).render() == sample) + } + + @Test func updatesOnlyValueRange() throws { + var document = try TOMLDocument(parsing: sample) + try document.setValue(.float(0.6), forKey: ["layout", "ratio"]) + #expect(document.source == sample.replacingOccurrences(of: "ratio = 0.5", with: "ratio = 0.6")) + } + + @Test func editsInlineTableLeafWithoutReformatting() throws { + var document = try TOMLDocument(parsing: sample) + try document.setValue(.integer(10), forKey: ["layout", "gaps", "inner"]) + #expect(document.source == sample.replacingOccurrences(of: "inner = 8", with: "inner = 10")) + } + + @Test func editsArrayOfTablesByIndex() throws { + var document = try TOMLDocument(parsing: sample) + try document.setValue(.string("AXSheet"), at: [.key("float-rules"), .index(1), .key("role")]) + #expect(document.source == sample.replacingOccurrences(of: "'AXDialog'", with: "\"AXSheet\"")) + #expect( + document.node(at: [.key("float-rules"), .index(0), .key("bundle-id")])?.value + == .string("org.example.notes")) + } + + @Test func repeatedEditsRebaseRanges() throws { + var document = try TOMLDocument(parsing: "first='x'\nsecond=1 # keep") + try document.setValue(.string("a much longer value 🪟"), forKey: ["first"]) + try document.setValue(.integer(999), forKey: ["second"]) + #expect(document.source == "first=\"a much longer value 🪟\"\nsecond=999 # keep") + } + + @Test func editsArrayElement() throws { + var document = try TOMLDocument(parsing: "a = [1, # first\n 2, 3]") + try document.setValue(.integer(8), at: [.key("a"), .index(1)]) + #expect(document.source == "a = [1, # first\n 8, 3]") + } + + @Test func editsNestedInlineTableInArray() throws { + var document = try TOMLDocument(parsing: "a = [{ x = 1, y=2 }, {x=3}]") + try document.setValue(.integer(8), at: [.key("a"), .index(0), .key("x")]) + #expect(document.source == "a = [{ x = 8, y=2 }, {x=3}]") + } + + @Test func crlfRemainsIntact() throws { + let source = "# 🪟\r\n[a]\r\nx = 1\r\ny = 2\r\n" + var document = try TOMLDocument(parsing: source) + try document.setValue(.integer(42), forKey: ["a", "y"]) + #expect(document.source == source.replacingOccurrences(of: "y = 2", with: "y = 42")) + } + + @Test func insertsNewRootKeyBeforeTables() throws { + var document = try TOMLDocument(parsing: "# keep\n[a]\nx=1") + try document.setValue(.integer(1), forKey: ["version"]) + #expect(document.source == "\"version\" = 1\n# keep\n[a]\nx=1") + #expect(document.root["version"]?.value == .integer(1)) + } + + @Test func insertsInsideCorrectTable() throws { + var document = try TOMLDocument(parsing: "[a]\nx=1\n[b]\ny=2") + try document.setValue(.integer(3), forKey: ["a", "z"]) + #expect(document.source == "[a]\n\"z\" = 3\nx=1\n[b]\ny=2") + #expect(document.node(forKey: ["a", "z"])?.value == .integer(3)) + #expect(document.node(forKey: ["b", "z"]) == nil) + } + + @Test func insertsUnderHeaderWithoutFinalNewline() throws { + var document = try TOMLDocument(parsing: "[a]") + try document.setValue(.bool(true), forKey: ["a", "enabled"]) + #expect(document.source == "[a]\n\"enabled\" = true\n") + } + + @Test func insertsNewNestedTableUsingDottedKey() throws { + var document = try TOMLDocument(parsing: "[layout]\nratio=0.5") + try document.setValue(.integer(8), forKey: ["layout", "gaps", "inner"]) + #expect(document.node(forKey: ["layout", "gaps", "inner"])?.value == .integer(8)) + } + + @Test func insertsIntoInlineTable() throws { + var document = try TOMLDocument(parsing: "gaps = {inner=8} # keep") + try document.setValue(.integer(12), forKey: ["gaps", "outer"]) + #expect(document.source == "gaps = {inner=8, \"outer\" = 12} # keep") + } + + @Test func insertsIntoEmptyInlineTable() throws { + var document = try TOMLDocument(parsing: "gaps = {}") + try document.setValue(.integer(8), forKey: ["gaps", "inner"]) + #expect(document.source == "gaps = {\"inner\" = 8}") + } + + @Test func insertsInsideArrayOfTables() throws { + var document = try TOMLDocument(parsing: "[[rules]]\nx=1\n[[rules]]\nx=2") + try document.setValue(.bool(true), at: [.key("rules"), .index(0), .key("enabled")]) + #expect(document.node(at: [.key("rules"), .index(0), .key("enabled")])?.value == .bool(true)) + #expect(document.node(at: [.key("rules"), .index(1), .key("enabled")]) == nil) + } + + @Test func deepestTableWinsEvenIfParentDeclaredLater() throws { + var document = try TOMLDocument(parsing: "[a.b]\nx=1\n[a]\ny=2") + try document.setValue(.integer(3), forKey: ["a", "b", "z"]) + #expect(document.node(forKey: ["a", "b", "z"])?.value == .integer(3)) + } + + @Test func invalidEditLeavesOriginalUntouched() throws { + var document = try TOMLDocument(parsing: "x=1 # keep") + #expect(throws: ConfigDiagnostic.self) { try document.setValue(.integer(2), forKey: ["x", "y"]) } + #expect(document.source == "x=1 # keep") + #expect(throws: ConfigDiagnostic.self) { try document.setValue(.integer(2), at: [.key("x"), .index(0)]) } + #expect(document.source == "x=1 # keep") + } + + @Test func tableHeaderCannotBeReplacedAsAValue() throws { + var document = try TOMLDocument(parsing: "[x]\ny=1") + #expect(throws: ConfigDiagnostic.self) { try document.setValue(.integer(2), forKey: ["x"]) } + #expect(document.source == "[x]\ny=1") + } + + @Test func nodeLookupRejectsWrongKindsAndBounds() throws { + let document = try TOMLDocument(parsing: "a=[1]") + #expect(document.node(at: [.key("a"), .index(-1)]) == nil) + #expect(document.node(at: [.key("a"), .index(1)]) == nil) + #expect(document.node(at: [.key("a"), .key("missing")]) == nil) + #expect(document.node(at: [.key("missing")]) == nil) + #expect(document.node(at: []) == document.root) + } + + @Test(arguments: ["", "café 🪟", "'\"\\", "one\ntwo\r\t", "\u{00}\u{08}\u{0C}\u{1F}\u{7F}"]) + func writerEscapesStrings(input: String) throws { + let encoded = try TOMLWriter.encode(.string(input)) + #expect(try TOMLDocument(parsing: "v=" + encoded).root["v"]?.value == .string(input)) + } + + @Test func writerEncodesCollectionsAndScalars() throws { + let document = try TOMLDocument(parsing: "v = { a = [1, 1.5, true, 'hi'], z = {} }") + let value = try #require(document.root["v"]?.value) + let encoded = try TOMLWriter.encode(value) + #expect(encoded == "{\"a\" = [1, 1.5, true, \"hi\"], \"z\" = {}}") + #expect(try TOMLWriter.encode(.float(.infinity)) == "inf") + #expect(try TOMLWriter.encode(.float(-.infinity)) == "-inf") + #expect(try TOMLWriter.encode(.float(.nan)) == "nan") + #expect(try TOMLWriter.encode(.bool(false)) == "false") + } +} diff --git a/Tests/TesseraConfigTests/TOMLParserTests.swift b/Tests/TesseraConfigTests/TOMLParserTests.swift new file mode 100644 index 00000000..0d2fe1d5 --- /dev/null +++ b/Tests/TesseraConfigTests/TOMLParserTests.swift @@ -0,0 +1,222 @@ +import Foundation +import Testing + +@testable import TesseraConfig + +@Suite struct TOMLParserTests { + @Test(arguments: [ + ("0", Int64(0)), ("+0", 0), ("-0", 0), ("42", 42), ("+42", 42), ("-17", -17), + ("1_000_000", 1_000_000), ("0xDEAD_BEEF", 3_735_928_559), ("0o755", 493), + ("0b1101_0010", 210), ("0x0", 0), ("0o0", 0), ("0b0", 0), + ("9223372036854775807", Int64.max), ("-9223372036854775808", Int64.min), + ("0x7fffffffffffffff", Int64.max), + ]) + func integers(input: String, expected: Int64) throws { + #expect(try scalar(input) == .integer(expected)) + } + + @Test(arguments: [ + ("0.0", 0.0), ("+1.0", 1.0), ("-0.5", -0.5), ("1e3", 1000), ("1E+3", 1000), + ("1e-3", 0.001), ("3.14_15", 3.1415), ("1_000.5_0e+0_2", 100050), ("-2E2", -200), + ]) + func floats(input: String, expected: Double) throws { + #expect(try scalar(input) == .float(expected)) + } + + @Test(arguments: ["inf", "+inf", "-inf", "nan", "+nan", "-nan"]) + func specialFloats(input: String) throws { + guard case .float(let value) = try scalar(input) else { + Issue.record("Expected a float") + return + } + if input.hasSuffix("nan") { + #expect(value.isNaN) + } else { + #expect(value.isInfinite) + #expect(value.sign == (input.hasPrefix("-") ? .minus : .plus)) + } + } + + @Test(arguments: [ + (#""hello""#, "hello"), (#"'hello'"#, "hello"), (#""""#, ""), ("''", ""), + (#""\b\t\n\f\r\"\\""#, "\u{08}\t\n\u{0C}\r\"\\"), + (#""\u0041\U0001F600""#, "A😀"), (#"'C:\Users\test'"#, "C:\\Users\\test"), + (#""café 🪟""#, "café 🪟"), (#""""hello""""#, "hello"), + ("'''\nhello\nworld'''", "hello\nworld"), ("\"\"\"\nhello\nworld\"\"\"", "hello\nworld"), + ("\"\"\"\r\nhello\r\nworld\"\"\"", "hello\nworld"), + ("'''\r\nhello\r\nworld'''", "hello\nworld"), + ("\"\"\"one\\\n two\"\"\"", "onetwo"), + ("\"\"\"one\\ \t\n \n\t two\"\"\"", "onetwo"), + (#""""a"b""c""""#, "a\"b\"\"c"), (#""""a"""""#, "a\""), + (#""""a""""""#, "a\"\""), ("'''a''''", "a'"), ("'''a'''''", "a''"), + ("\"tab\tcharacter\"", "tab\tcharacter"), ("'tab\tcharacter'", "tab\tcharacter"), + ]) + func strings(input: String, expected: String) throws { + #expect(try scalar(input) == .string(expected)) + } + + @Test(arguments: ["true", "false"]) + func booleans(input: String) throws { + #expect(try scalar(input) == .bool(input == "true")) + } + + @Test(arguments: [ + "", " \t", "# hello", "# hello\r\n", "\n\n", "\t # comment\n", + ]) + func emptyDocuments(source: String) throws { + #expect(try TOMLParser.parse(source).root.value == .table([:])) + } + + @Test(arguments: ["[1, 2, 3]", "[1,2,3,]", "[\n1, # one\n2,\n3,\n]"]) + func arrays(input: String) throws { + guard case .array(let entries) = try scalar(input) else { + Issue.record("Expected an array") + return + } + #expect(entries.map(\.value) == [.integer(1), .integer(2), .integer(3)]) + } + + @Test func mixedArrays() throws { + guard case .array(let entries) = try scalar("[1, 'two', true, [], {}]") else { + Issue.record("Expected an array") + return + } + #expect(entries.map(\.value) == [.integer(1), .string("two"), .bool(true), .array([]), .table([:])]) + } + + @Test func inlineTablesAndDottedKeys() throws { + let document = try TOMLDocument(parsing: "point = { x = 1, details.name = 'desk', y = 2 }") + #expect(document.node(forKey: ["point", "x"])?.value == .integer(1)) + #expect(document.node(forKey: ["point", "details", "name"])?.value == .string("desk")) + } + + @Test func inlineTablesCanContainMultilineValues() throws { + let document = try TOMLDocument(parsing: "v = { a = [\n1,\n2], b = '''\nthree\nfour''' }") + #expect(document.node(forKey: ["v", "b"])?.value == .string("three\nfour")) + } + + @Test func quotedAndBareKeys() throws { + let source = "\"\" = 1\n'hello.world' = 2\n\"🪟\" . 'inner gap' = 3\n123 = 4\nfoo-bar_baz = 5" + let document = try TOMLDocument(parsing: source) + #expect(document.root[""]?.value == .integer(1)) + #expect(document.root["hello.world"]?.value == .integer(2)) + #expect(document.node(forKey: ["🪟", "inner gap"])?.value == .integer(3)) + #expect(document.root["123"]?.value == .integer(4)) + #expect(document.root["foo-bar_baz"]?.value == .integer(5)) + } + + @Test func parentTablesMayFollowChildren() throws { + let document = try TOMLDocument(parsing: "[a.b.c]\nx=1\n[a]\ny=2\n[a.b]\nz=3") + #expect(document.node(forKey: ["a", "b", "c", "x"])?.value == .integer(1)) + #expect(document.node(forKey: ["a", "y"])?.value == .integer(2)) + #expect(document.node(forKey: ["a", "b", "z"])?.value == .integer(3)) + } + + @Test func dottedTablesCanHaveNewSubtables() throws { + let document = try TOMLDocument(parsing: "a.b.c = 1\na.b.d = 2\n[a.b.extra]\ne = 3") + #expect(document.node(forKey: ["a", "b", "extra", "e"])?.value == .integer(3)) + } + + @Test func arraysOfTablesAttachToLatestElement() throws { + let document = try TOMLDocument( + parsing: """ + [[displays]] + name = 'first' + [displays.gaps] + inner = 8 + [[displays.rules]] + role = 'one' + [[displays.rules]] + role = 'two' + [[displays]] + name = 'second' + [displays.gaps] + inner = 12 + """) + #expect(document.node(at: [.key("displays"), .index(0), .key("gaps"), .key("inner")])?.value == .integer(8)) + #expect(document.node(at: [.key("displays"), .index(1), .key("gaps"), .key("inner")])?.value == .integer(12)) + #expect( + document.node(at: [.key("displays"), .index(0), .key("rules"), .index(1), .key("role")])?.value + == .string("two")) + } + + @Test func unicodeScalarLocations() throws { + let document = try TOMLDocument(parsing: "# 🪟\r\n\"é\" = 'café' # note") + let node = try #require(document.root["é"]) + #expect(node.range.start == SourceLocation(line: 2, column: 8, offset: 12)) + #expect(node.keyRange?.start == SourceLocation(line: 2, column: 1, offset: 5)) + #expect(node.range.end.column == 14) + } + + @Test func duplicateIncludesBothPositions() throws { + do { + _ = try TOMLParser.parse("[layout]\ngap = 8\ngap = 12") + Issue.record("Expected a duplicate error") + } catch let diagnostic as ConfigDiagnostic { + #expect(diagnostic.location.line == 3) + #expect(diagnostic.location.column == 1) + #expect(diagnostic.relatedLocation?.line == 2) + #expect(diagnostic.description.contains("line 3, column 1")) + #expect(diagnostic.message.contains("line 2, column 1")) + } + } + + @Test(arguments: [ + "a = 01", "a = -01", "a = +01", "a = 1_", "a = _1", "a = 1__2", "a = 0x_1", + "a = 0b2", "a = 0o8", "a = 0XFF", "a = +0x1", "a = -0x1", "a = 0x", + "a = .5", "a = 1.", "a = 1.e2", "a = 01.2", "a = 1e", "a = 1e_2", "a = 1_e2", + "a = 1e+", "a = 1e9999", "a = 9223372036854775808", "a = -9223372036854775809", + "a = 0xffffffffffffffff", "a = True", "a = FALSE", "a = text", "a = null", "a =", + "a = 1 b = 2", "a = 1\rb = 2", "a = [1 2]", "a = [1,,2]", "a = [,]", "a = [1", + "a = {x=1,}", "a = {x=1\ny=2}", "a = {\nx=1}", "a = {x=1 # nope\n}", + "a = 'unfinished", "a = \"unfinished", "a = 'one\ntwo'", "a = \"one\ntwo\"", + #"a = "\x00""#, #"a = "\uD800""#, #"a = "\U00110000""#, #"a = "\u123""#, + #"a = "\q""#, "a = '\u{00}'", "a = '\u{7F}'", "# bad\u{01}", + "a = \"\"\"x\\ y\"\"\"", "a = \"\"\"x\"\"\"\"\"\"", + "=1", "a..b=1", "a.=1", "a b=1", "🪟=1", "\"\"\"a\"\"\"=1", + "[a", "[]", "[[a]", "[a] a=1", "a=1\na=2", "a.b=1\na=2", "a=1\na.b=2", + "a={b=1}\na.c=2", "a={b=1}\n[a.c]", "a.b=1\n[a]", "[a]\n[a]", + "a=[]\n[[a]]", "a=[{}]\n[[a]]", "[[a]]\n[a]", "[a]\n[[a]]", + "[[a]]\nx=1\nx=2", "a={x=1,x=2}", "a={x={y=1},x.z=2}", + "[a.b]\nx=1\n[a]\nb.y=2", + ]) + func invalidDocuments(source: String) { + #expect(throws: ConfigDiagnostic.self) { try TOMLDocument(parsing: source) } + } + + @Test(arguments: ["1979-05-27", "1979-05-27T07:32:00Z", "07:32:00", "1979-05-27 07:32:00"]) + func datesHaveClearErrors(input: String) throws { + do { + _ = try scalar(input) + Issue.record("Expected an unsupported date error") + } catch let diagnostic as ConfigDiagnostic { + #expect(diagnostic.message.contains("Dates and times")) + #expect(diagnostic.location.column == 5) + } + } + + @Test(arguments: [ + ("a = [1,\n nope]", 2, 3), ("a = \"bad\\q\"", 1, 9), ("# comment\n=1", 2, 1), + ("a=1\r", 1, 4), ("a = 'x\ny'", 1, 7), ("a = {x=1,}", 1, 10), + ("[a]\nx = 1\nx = 2", 3, 1), + ]) + func errorPositions(source: String, line: Int, column: Int) throws { + do { + _ = try TOMLDocument(parsing: source) + Issue.record("Expected an error") + } catch let diagnostic as ConfigDiagnostic { + #expect(diagnostic.location.line == line) + #expect(diagnostic.location.column == column) + } + } + + @Test func excessiveNestingIsDiagnosed() { + let source = "value = " + String(repeating: "[", count: 129) + "1" + String(repeating: "]", count: 129) + #expect(throws: ConfigDiagnostic.self) { try TOMLDocument(parsing: source) } + } + + private func scalar(_ source: String) throws -> TOMLValue { + let document = try TOMLDocument(parsing: "v = " + source) + return try #require(document.root["v"]?.value) + } +} diff --git a/Tests/TesseraConfigTests/TesseraConfigTests.swift b/Tests/TesseraConfigTests/TesseraConfigTests.swift deleted file mode 100644 index 29e47642..00000000 --- a/Tests/TesseraConfigTests/TesseraConfigTests.swift +++ /dev/null @@ -1,4 +0,0 @@ -import Testing -@testable import TesseraConfig - -@Test func builds() {} -- knotmirror 0.0.1 From 443c27211c6e3534eee6055d4fed0b4eacc7d845 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:38:23 -0400 Subject: [PATCH 05/44] Monitor display changes --- Sources/TesseraPlatform/Displays.swift | 195 ++++++++++++++++++ .../TesseraPlatformTests/DisplaysTests.swift | 140 +++++++++++++ 2 files changed, 335 insertions(+) create mode 100644 Sources/TesseraPlatform/Displays.swift create mode 100644 Tests/TesseraPlatformTests/DisplaysTests.swift diff --git a/Sources/TesseraPlatform/Displays.swift b/Sources/TesseraPlatform/Displays.swift new file mode 100644 index 00000000..68830712 --- /dev/null +++ b/Sources/TesseraPlatform/Displays.swift @@ -0,0 +1,195 @@ +internal import AppKit +internal import ColorSync +public import CoreGraphics +public import Foundation + +public struct Display: Equatable, Sendable { + public let id: UUID + public let frame: CGRect + public let visibleFrame: CGRect + public let scale: CGFloat + public let isBuiltIn: Bool + + public init(id: UUID, frame: CGRect, visibleFrame: CGRect, scale: CGFloat, isBuiltIn: Bool) { + self.id = id + self.frame = frame + self.visibleFrame = visibleFrame + self.scale = scale + self.isBuiltIn = isBuiltIn + } +} + +public enum DisplayEnumerationError: Error, Equatable, Sendable { + case missingDisplayID + case missingDisplayUUID(UInt32) +} + +struct DisplayChangeDebouncer { + static let interval: Duration = .milliseconds(300) + private(set) var deadline: ContinuousClock.Instant? + + mutating func record(at instant: ContinuousClock.Instant) -> ContinuousClock.Instant { + let next = instant.advanced(by: Self.interval) + deadline = next + return next + } + + mutating func consumeIfDue(at instant: ContinuousClock.Instant) -> Bool { + guard let deadline, instant >= deadline else { return false } + self.deadline = nil + return true + } +} + +// Only the main actor installs tokens; deinit removes them after the last owner is gone. +private final class DisplayObservers: @unchecked Sendable { + private var entries: [(NotificationCenter, any NSObjectProtocol)] = [] + + @MainActor func append(center: NotificationCenter, token: any NSObjectProtocol) { + entries.append((center, token)) + } + + deinit { + for (center, token) in entries { + center.removeObserver(token) + } + } +} + +@MainActor +public final class Displays { + private let observers = DisplayObservers() + private let snapshot: @MainActor () throws -> [Display] + private let clock = ContinuousClock() + private var debouncer = DisplayChangeDebouncer() + private var timer: Task? + private var subscribers: [UUID: AsyncThrowingStream<[Display], any Error>.Continuation] = [:] + + public convenience init() { + self.init( + snapshot: Self.enumerate, + screenCenter: .default, + workspaceCenter: NSWorkspace.shared.notificationCenter + ) + } + + init( + snapshot: @escaping @MainActor () throws -> [Display], + screenCenter: NotificationCenter, + workspaceCenter: NotificationCenter + ) { + self.snapshot = snapshot + observe(NSApplication.didChangeScreenParametersNotification, in: screenCenter) + observe(NSWorkspace.willSleepNotification, in: workspaceCenter) + observe(NSWorkspace.didWakeNotification, in: workspaceCenter) + observe(NSWorkspace.screensDidSleepNotification, in: workspaceCenter) + observe(NSWorkspace.screensDidWakeNotification, in: workspaceCenter) + } + + deinit { + timer?.cancel() + for continuation in subscribers.values { + continuation.finish() + } + } + + /// Frames use AppKit's screen coordinate space, in points. + public func current() throws -> [Display] { + try snapshot() + } + + private static func enumerate() throws -> [Display] { + try NSScreen.screens.map { screen in + guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber else { + throw DisplayEnumerationError.missingDisplayID + } + let displayID = number.uint32Value + guard let reference = CGDisplayCreateUUIDFromDisplayID(displayID)?.takeRetainedValue() else { + throw DisplayEnumerationError.missingDisplayUUID(displayID) + } + let bytes = CFUUIDGetUUIDBytes(reference) + let id = UUID( + uuid: ( + bytes.byte0, bytes.byte1, bytes.byte2, bytes.byte3, + bytes.byte4, bytes.byte5, bytes.byte6, bytes.byte7, + bytes.byte8, bytes.byte9, bytes.byte10, bytes.byte11, + bytes.byte12, bytes.byte13, bytes.byte14, bytes.byte15 + )) + return Display( + id: id, + frame: screen.frame, + visibleFrame: screen.visibleFrame, + scale: screen.backingScaleFactor, + isBuiltIn: CGDisplayIsBuiltin(displayID) != 0 + ) + } + } + + /// Emits the current snapshot immediately, then the latest snapshot after each quiet period. + /// Keep this instance alive while consuming the stream. Enumeration errors terminate it. + public func changes() -> AsyncThrowingStream<[Display], any Error> { + let id = UUID() + let (stream, continuation) = AsyncThrowingStream<[Display], any Error>.makeStream( + bufferingPolicy: .bufferingNewest(1)) + continuation.onTermination = { [weak self] _ in + Task { @MainActor [weak self] in + self?.subscribers.removeValue(forKey: id) + } + } + do { + let snapshot = try current() + subscribers[id] = continuation + continuation.yield(snapshot) + } catch { + continuation.finish(throwing: error) + } + return stream + } + + private func observe(_ name: Notification.Name, in center: NotificationCenter) { + let token = center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor [weak self] in + self?.scheduleChange() + } + } + observers.append(center: center, token: token) + } + + private func scheduleChange() { + let deadline = debouncer.record(at: clock.now) + timer?.cancel() + let clock = clock + timer = Task { @MainActor [weak self] in + do { + try await clock.sleep(until: deadline) + guard let self, self.debouncer.consumeIfDue(at: clock.now) else { return } + self.timer = nil + self.publishChange() + } catch is CancellationError { + // Rescheduling or releasing the owner cancels the timer. + } catch { + self?.finishSubscribers(throwing: error) + } + } + } + + private func publishChange() { + guard !subscribers.isEmpty else { return } + do { + let snapshot = try current() + for continuation in subscribers.values { + continuation.yield(snapshot) + } + } catch { + finishSubscribers(throwing: error) + } + } + + private func finishSubscribers(throwing error: any Error) { + let active = subscribers.values + subscribers.removeAll() + for continuation in active { + continuation.finish(throwing: error) + } + } +} diff --git a/Tests/TesseraPlatformTests/DisplaysTests.swift b/Tests/TesseraPlatformTests/DisplaysTests.swift new file mode 100644 index 00000000..6c7ca471 --- /dev/null +++ b/Tests/TesseraPlatformTests/DisplaysTests.swift @@ -0,0 +1,140 @@ +import AppKit +import CoreGraphics +import Foundation +import Testing + +@testable import TesseraPlatform + +@Test func displayChangeWaitsForTheQuietPeriod() { + var debouncer = DisplayChangeDebouncer() + let start = ContinuousClock().now + + #expect(debouncer.consumeIfDue(at: start) == false) + #expect(debouncer.record(at: start) == start.advanced(by: .milliseconds(300))) + #expect(debouncer.consumeIfDue(at: start.advanced(by: .milliseconds(299))) == false) + #expect(debouncer.consumeIfDue(at: start.advanced(by: .milliseconds(300))) == true) + #expect(debouncer.consumeIfDue(at: start.advanced(by: .seconds(1))) == false) +} + +@Test func displayChangeBurstExtendsDeadline() { + var debouncer = DisplayChangeDebouncer() + let start = ContinuousClock().now + let originalDeadline = debouncer.record(at: start) + let latestDeadline = debouncer.record(at: start.advanced(by: .milliseconds(250))) + + #expect(latestDeadline == start.advanced(by: .milliseconds(550))) + #expect(debouncer.consumeIfDue(at: originalDeadline) == false) + #expect(debouncer.consumeIfDue(at: start.advanced(by: .milliseconds(549))) == false) + #expect(debouncer.consumeIfDue(at: latestDeadline) == true) + #expect(debouncer.deadline == nil) +} + +@Test func displayChangeCanStartANewBurstAfterDelivery() { + var debouncer = DisplayChangeDebouncer() + let start = ContinuousClock().now + _ = debouncer.record(at: start) + #expect(debouncer.consumeIfDue(at: start.advanced(by: .milliseconds(500))) == true) + + let secondStart = start.advanced(by: .seconds(1)) + _ = debouncer.record(at: secondStart) + #expect(debouncer.consumeIfDue(at: secondStart.advanced(by: .milliseconds(299))) == false) + #expect(debouncer.consumeIfDue(at: secondStart.advanced(by: .milliseconds(301))) == true) + #expect(debouncer.consumeIfDue(at: secondStart.advanced(by: .seconds(1))) == false) +} + +private enum SnapshotError: Error, Equatable { + case unavailable + case timedOut +} + +@Test @MainActor func displayStreamEmitsInitialSnapshotAndFinishesWithOwner() async throws { + let display = Display( + id: UUID(), frame: CGRect(x: 0, y: 0, width: 100, height: 80), + visibleFrame: CGRect(x: 0, y: 10, width: 100, height: 70), scale: 2, isBuiltIn: true + ) + let stream: AsyncThrowingStream<[Display], any Error> + do { + let displays = Displays( + snapshot: { [display] }, screenCenter: NotificationCenter(), workspaceCenter: NotificationCenter()) + #expect(try displays.current() == [display]) + stream = displays.changes() + } + var iterator = stream.makeAsyncIterator() + #expect(try await iterator.next() == [display]) + #expect(try await iterator.next() == nil) +} + +@Test @MainActor func displayStreamSurfacesEnumerationFailure() async { + let displays = Displays( + snapshot: { throw SnapshotError.unavailable }, + screenCenter: NotificationCenter(), workspaceCenter: NotificationCenter()) + var iterator = displays.changes().makeAsyncIterator() + do { + _ = try await iterator.next() + Issue.record("Expected an enumeration error") + } catch { + #expect(error as? SnapshotError == .unavailable) + } +} + +@MainActor private final class SnapshotFixture { + let id = UUID() + var count = 0 + var shouldFail = false + + func read() throws -> [Display] { + if shouldFail { throw SnapshotError.unavailable } + count += 1 + return [Display(id: id, frame: .zero, visibleFrame: .zero, scale: CGFloat(count), isBuiltIn: false)] + } +} + +@MainActor private func exerciseDisplayNotifications() async throws { + let screenCenter = NotificationCenter() + let workspaceCenter = NotificationCenter() + let fixture = SnapshotFixture() + let displays = Displays( + snapshot: { try fixture.read() }, screenCenter: screenCenter, workspaceCenter: workspaceCenter) + var iterator = displays.changes().makeAsyncIterator() + #expect(try await iterator.next()?.first?.scale == 1) + var secondIterator = displays.changes().makeAsyncIterator() + #expect(try await secondIterator.next()?.first?.scale == 2) + for (index, event) in [ + (screenCenter, NSApplication.didChangeScreenParametersNotification), + (workspaceCenter, NSWorkspace.willSleepNotification), + (workspaceCenter, NSWorkspace.didWakeNotification), + (workspaceCenter, NSWorkspace.screensDidSleepNotification), + (workspaceCenter, NSWorkspace.screensDidWakeNotification), + ].enumerated() { + event.0.post(name: event.1, object: nil) + #expect(try await iterator.next()?.first?.scale == CGFloat(index + 3)) + #expect(try await secondIterator.next()?.first?.scale == CGFloat(index + 3)) + } + fixture.shouldFail = true + screenCenter.post(name: NSApplication.didChangeScreenParametersNotification, object: nil) + do { + _ = try await iterator.next() + Issue.record("Expected an enumeration error") + } catch { + #expect(error as? SnapshotError == .unavailable) + } + do { + _ = try await secondIterator.next() + Issue.record("Expected an enumeration error") + } catch { + #expect(error as? SnapshotError == .unavailable) + } + withExtendedLifetime(displays) {} +} + +@Test func screenSleepAndWakeNotificationsPublishSnapshots() async throws { + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { try await exerciseDisplayNotifications() } + group.addTask { + try await Task.sleep(for: .seconds(10)) + throw SnapshotError.timedOut + } + try await group.next() + group.cancelAll() + } +} -- knotmirror 0.0.1 From 45955619f6614bc7c7530634854177ca498a3db4 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:39:12 -0400 Subject: [PATCH 06/44] Test platform window operations --- .../PlatformIntegrationTests.swift | 310 ++++++++++++++++++ 1 file changed, 310 insertions(+) create mode 100644 Tests/TesseraE2ETests/PlatformIntegrationTests.swift diff --git a/Tests/TesseraE2ETests/PlatformIntegrationTests.swift b/Tests/TesseraE2ETests/PlatformIntegrationTests.swift new file mode 100644 index 00000000..2df7d819 --- /dev/null +++ b/Tests/TesseraE2ETests/PlatformIntegrationTests.swift @@ -0,0 +1,310 @@ +import ApplicationServices +import Darwin +import Foundation +import TesseraPlatform +import Testing + +private struct PlatformTestError: Error, CustomStringConvertible { + let description: String +} + +private func platformFixtureExecutable() throws -> URL { + var directory = Bundle.main.bundleURL + while directory.path != "/" { + let candidate = directory.appendingPathComponent("FixtureApp") + if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate } + directory.deleteLastPathComponent() + } + directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + while directory.path != "/" { + for path in ["FixtureApp", ".build/debug/FixtureApp"] { + let candidate = directory.appendingPathComponent(path) + if FileManager.default.isExecutableFile(atPath: candidate.path) { return candidate } + } + directory.deleteLastPathComponent() + } + throw PlatformTestError(description: "FixtureApp executable not found; build the FixtureApp product first") +} + +private func platformReadyLine(_ handle: FileHandle) throws -> String { + let deadline = Date().addingTimeInterval(10) + var bytes: [UInt8] = [] + while Date() < deadline { + var descriptor = pollfd(fd: handle.fileDescriptor, events: Int16(POLLIN), revents: 0) + let result = poll(&descriptor, 1, 100) + if result < 0 { + if errno == EINTR { continue } + throw PlatformTestError(description: "Polling fixture output failed: \(errno)") + } + if result == 0 { continue } + var byte: UInt8 = 0 + guard Darwin.read(handle.fileDescriptor, &byte, 1) == 1 else { + throw PlatformTestError(description: "Fixture exited before its ready line") + } + if byte == 10 { return String(decoding: bytes, as: UTF8.self) } + bytes.append(byte) + guard bytes.count < 1_024 else { + throw PlatformTestError(description: "Fixture ready line is too long") + } + } + throw PlatformTestError(description: "Timed out waiting for fixture ready line") +} + +private final class PlatformFixture { + let process = Process() + private let output = Pipe() + + init(arguments: [String]) throws { + process.executableURL = try platformFixtureExecutable() + process.arguments = arguments + process.standardOutput = output + try process.run() + do { + let line = try platformReadyLine(output.fileHandleForReading) + guard line == "ready \(process.processIdentifier)", process.isRunning else { + throw PlatformTestError(description: "Unexpected fixture readiness: \(line)") + } + } catch { + stop() + throw error + } + } + + func stop() { + guard process.isRunning else { return } + let result = Darwin.kill(process.processIdentifier, SIGKILL) + #expect(result == 0 || errno == ESRCH, "Failed to terminate fixture: \(errno)") + let deadline = Date().addingTimeInterval(2) + while process.isRunning && Date() < deadline { usleep(10_000) } + #expect(!process.isRunning, "Fixture did not exit after SIGKILL") + } +} + +// A task group would wait for a stuck AX operation even after the deadline wins. +private final class DeadlineRace: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + + init(_ continuation: CheckedContinuation) { + self.continuation = continuation + } + + func finish(_ result: Result) { + lock.lock() + let continuation = self.continuation + self.continuation = nil + lock.unlock() + continuation?.resume(with: result) + } +} + +private func within( + _ seconds: Int, _ label: String, operation: @escaping @Sendable () async throws -> Value +) async throws -> Value { + try await withCheckedThrowingContinuation { continuation in + let race = DeadlineRace(continuation) + Task.detached { + do { race.finish(.success(try await operation())) } catch { race.finish(.failure(error)) } + } + Task.detached { + do { try await Task.sleep(for: .seconds(seconds)) } catch { return } + race.finish(.failure(PlatformTestError(description: "Timed out waiting for \(label)"))) + } + } +} + +private final class OperationEnd: @unchecked Sendable { + private let lock = NSLock() + private var value: UInt64? + + func record() { + lock.lock() + value = DispatchTime.now().uptimeNanoseconds + lock.unlock() + } + + func read() -> UInt64? { + lock.lock() + defer { lock.unlock() } + return value + } +} + +private struct PlatformWindow: Sendable { + let id: CGWindowID + let title: String + let frame: CGRect +} + +private func platformWindows(_ thread: AppThread) async throws -> [PlatformWindow] { + try await within(8, "window enumeration") { + try await thread.perform { application in + try application.windows.map { window in + try PlatformWindow(id: window.windowID(), title: window.title, frame: window.frame) + } + } + } +} + +private func platformWindow(_ thread: AppThread, title: String) async throws -> PlatformWindow { + let deadline = Date().addingTimeInterval(5) + repeat { + if let window = try await platformWindows(thread).first(where: { $0.title == title }) { return window } + try await Task.sleep(for: .milliseconds(100)) + } while Date() < deadline + throw PlatformTestError(description: "Fixture window not found: \(title)") +} + +private func close(_ left: CGRect, _ right: CGRect, tolerance: CGFloat = 1) -> Bool { + abs(left.minX - right.minX) <= tolerance && abs(left.minY - right.minY) <= tolerance + && abs(left.width - right.width) <= tolerance && abs(left.height - right.height) <= tolerance +} + +@Suite(.serialized) +struct PlatformIntegrationTests { + @Test( + .enabled( + if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", + "Accessibility permission is required for platform integration tests" + )) + func listsWindowsAndWritesFramesWithMinimumSize() async throws { + try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") + let fixture = try PlatformFixture( + arguments: ["--windows", "2", "--title", "Platform Frames", "--min-size", "720x540"]) + defer { fixture.stop() } + let thread = AppThread(pid: fixture.process.processIdentifier) + defer { thread.shutdown() } + + let first = try await platformWindow(thread, title: "Platform Frames 1") + let second = try await platformWindow(thread, title: "Platform Frames 2") + #expect(first.id != second.id) + let all = try await platformWindows(thread) + #expect(all.contains { $0.id == first.id && $0.title == first.title }) + #expect(all.contains { $0.id == second.id && $0.title == second.title }) + + let target = CGRect( + x: first.frame.minX + 30, y: first.frame.minY + 25, + width: first.frame.width + 60, height: first.frame.height + 40, + ) + let written = try await within(8, "frame write") { + try await thread.writeFrame(windowID: first.id, target: target) + } + let readBack = try await platformWindow(thread, title: first.title) + #expect(close(written, target), "Frame write did not reach the requested geometry") + #expect(close(readBack.frame, written), "AX frame readback did not match the write result") + + let undersized = CGRect(origin: second.frame.origin, size: CGSize(width: 100, height: 100)) + let clamped = try await within(8, "minimum-size frame write") { + try await thread.writeFrame(windowID: second.id, target: undersized) + } + let clampedReadBack = try await platformWindow(thread, title: second.title) + #expect(abs(clamped.width - 720) <= 1 && abs(clamped.height - 540) <= 1) + #expect(close(clampedReadBack.frame, clamped), "Clamped frame did not match AX readback") + } + + @Test( + .enabled( + if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", + "Accessibility permission is required for platform responsiveness tests" + )) + func slowApplicationDoesNotBlockHealthyApplication() async throws { + try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") + let healthyFixture = try PlatformFixture(arguments: ["--title", "Platform Healthy"]) + defer { healthyFixture.stop() } + let slowFixture = try PlatformFixture(arguments: ["--title", "Platform Slow", "--slow", "1200"]) + defer { slowFixture.stop() } + let healthy = AppThread(pid: healthyFixture.process.processIdentifier) + let slow = AppThread(pid: slowFixture.process.processIdentifier, timeout: 0.35) + defer { + healthy.shutdown() + slow.shutdown() + } + let healthyWindow = try await platformWindow(healthy, title: "Platform Healthy 1") + + var observedOverlap = false + let deadline = Date().addingTimeInterval(10) + while Date() < deadline && !observedOverlap { + let (started, signal) = AsyncStream.makeStream() + let operationEnd = OperationEnd() + let slowCall = Task { () throws -> (Bool, UInt64) in + defer { signal.finish() } + let timedOut: Bool + do { + _ = try await slow.perform { application in + defer { operationEnd.record() } + signal.yield(DispatchTime.now().uptimeNanoseconds) + return try application.windows.count + } + timedOut = false + } catch AXPlatformError.timedOut { + timedOut = true + } + guard let end = operationEnd.read() else { + throw PlatformTestError(description: "Slow operation ended without a timestamp") + } + return (timedOut, end) + } + defer { signal.finish() } + let slowStart = try await within(8, "slow operation to start") { + var iterator = started.makeAsyncIterator() + guard let instant = await iterator.next() else { + _ = try await slowCall.value + throw PlatformTestError(description: "Slow operation did not start") + } + return instant + } + let healthyStart = DispatchTime.now().uptimeNanoseconds + let healthyWindows = try await platformWindows(healthy) + let healthyEnd = DispatchTime.now().uptimeNanoseconds + let (timedOut, slowEnd) = try await within(8, "slow operation to finish") { + try await slowCall.value + } + #expect(healthyWindows.contains { $0.id == healthyWindow.id && $0.title == healthyWindow.title }) + observedOverlap = timedOut && slowStart < healthyStart && healthyEnd < slowEnd + if !observedOverlap { try await Task.sleep(for: .milliseconds(100)) } + } + #expect(observedOverlap, "Expected a slow AX timeout while the healthy application remained responsive") + } + + @Test( + .enabled( + if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", + "Accessibility permission is required for platform event tests" + )) + func deliversWindowMinimizedEvent() async throws { + try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") + let fixture = try PlatformFixture(arguments: ["--title", "Platform Events"]) + defer { fixture.stop() } + let thread = AppThread(pid: fixture.process.processIdentifier) + defer { thread.shutdown() } + let window = try await platformWindow(thread, title: "Platform Events 1") + let wasMinimized = try await within(8, "initial minimized state") { + try await thread.perform { application in + for candidate in try application.windows where try candidate.windowID() == window.id { + return try candidate.minimized + } + throw PlatformTestError(description: "Event window disappeared") + } + } + try #require(!wasMinimized, "Fixture window was already minimized") + let event = Task { + try await within(8, "matching window event") { + for await event in thread.events { + if case .windowMinimized(let id) = event, id == window.id { return event } + } + throw PlatformTestError(description: "Event stream ended before the matching window event") + } + } + let isMinimized = try await within(8, "minimize window") { + try await thread.perform { application in + for candidate in try application.windows where try candidate.windowID() == window.id { + try candidate.setMinimized(true) + return try candidate.minimized + } + throw PlatformTestError(description: "Event window disappeared") + } + } + #expect(isMinimized) + _ = try await event.value + } +} -- knotmirror 0.0.1 From dabdc1c4ab64e64c61a78123469731b2c005dc7d Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:39:29 -0400 Subject: [PATCH 07/44] Build geometry and tile layouts --- Sources/TesseraCore/Geometry.swift | 136 ++++++++++ Sources/TesseraCore/LayoutEngine.swift | 106 ++++++++ Sources/TesseraCore/Model.swift | 170 ++++++++++++ Sources/TesseraCore/TesseraCore.swift | 1 - Sources/TesseraCore/TileTree.swift | 184 +++++++++++++ .../GeometryLayoutTests.swift | 252 ++++++++++++++++++ Tests/TesseraCoreTests/TesseraCoreTests.swift | 4 - 7 files changed, 848 insertions(+), 5 deletions(-) create mode 100644 Sources/TesseraCore/Geometry.swift create mode 100644 Sources/TesseraCore/LayoutEngine.swift create mode 100644 Sources/TesseraCore/Model.swift delete mode 100644 Sources/TesseraCore/TesseraCore.swift create mode 100644 Sources/TesseraCore/TileTree.swift create mode 100644 Tests/TesseraCoreTests/GeometryLayoutTests.swift delete mode 100644 Tests/TesseraCoreTests/TesseraCoreTests.swift diff --git a/Sources/TesseraCore/Geometry.swift b/Sources/TesseraCore/Geometry.swift new file mode 100644 index 00000000..8b327082 --- /dev/null +++ b/Sources/TesseraCore/Geometry.swift @@ -0,0 +1,136 @@ +public struct Point: Sendable, Equatable, Hashable, Codable { + public var xCoordinate: Double + public var yCoordinate: Double + + public init(x xCoordinate: Double = 0, y yCoordinate: Double = 0) { + self.xCoordinate = xCoordinate + self.yCoordinate = yCoordinate + } +} + +public struct Size: Sendable, Equatable, Codable { + public var width: Double + public var height: Double + + public init(width: Double = 0, height: Double = 0) { + self.width = width + self.height = height + } +} + +public struct Insets: Sendable, Equatable, Codable { + public var top: Double + public var left: Double + public var bottom: Double + public var right: Double + + public init(top: Double = 0, left: Double = 0, bottom: Double = 0, right: Double = 0) { + self.top = top + self.left = left + self.bottom = bottom + self.right = right + } + + public init(_ all: Double) { + self.init(top: all, left: all, bottom: all, right: all) + } +} + +public struct Rect: Sendable, Equatable, Codable { + public var origin: Point + public var size: Size + + public init(x xCoordinate: Double = 0, y yCoordinate: Double = 0, width: Double = 0, height: Double = 0) { + origin = Point(x: xCoordinate, y: yCoordinate) + size = Size(width: width, height: height) + } + + public init(origin: Point, size: Size) { + self.origin = origin + self.size = size + } + + public var minX: Double { origin.xCoordinate } + public var minY: Double { origin.yCoordinate } + public var maxX: Double { origin.xCoordinate + max(0, size.width) } + public var maxY: Double { origin.yCoordinate + max(0, size.height) } + public var center: Point { Point(x: (minX + maxX) / 2, y: (minY + maxY) / 2) } + + public func inset(by insets: Insets) -> Rect { + let left = min(max(0, insets.left), max(0, size.width)) + let top = min(max(0, insets.top), max(0, size.height)) + return Rect( + x: minX + left, y: minY + top, + width: max(0, size.width - left - max(0, insets.right)), + height: max(0, size.height - top - max(0, insets.bottom)) + ) + } + + // Round shared edges, not sizes, so neighbouring tiles stay joined. + public func roundedToWholePoints() -> Rect { + let horizontal = minX.rounded() + let vertical = minY.rounded() + return Rect(x: horizontal, y: vertical, width: maxX.rounded() - horizontal, height: maxY.rounded() - vertical) + } + + public func contains(_ point: Point) -> Bool { + point.xCoordinate >= minX && point.xCoordinate <= maxX + && point.yCoordinate >= minY && point.yCoordinate <= maxY + } +} + +public enum Axis: String, Sendable, Equatable, Codable { + case horizontal, vertical +} + +public enum Direction: String, Sendable, Equatable, Codable, CaseIterable { + case left, right, up, down + + public var axis: Axis { + self == .left || self == .right ? .horizontal : .vertical + } + + public var isBefore: Bool { self == .left || self == .up } + + public func distance(from source: Rect, to candidate: Rect) -> DirectionalDistance? { + let sourceCenter = source.center + let candidateCenter = candidate.center + let forward: Double + let perpendicular: Double + let overlap: Double + switch self { + case .left, .right: + forward = + self == .left + ? sourceCenter.xCoordinate - candidateCenter.xCoordinate + : candidateCenter.xCoordinate - sourceCenter.xCoordinate + perpendicular = abs(sourceCenter.yCoordinate - candidateCenter.yCoordinate) + overlap = min(source.maxY, candidate.maxY) - max(source.minY, candidate.minY) + case .up, .down: + forward = + self == .up + ? sourceCenter.yCoordinate - candidateCenter.yCoordinate + : candidateCenter.yCoordinate - sourceCenter.yCoordinate + perpendicular = abs(sourceCenter.xCoordinate - candidateCenter.xCoordinate) + overlap = min(source.maxX, candidate.maxX) - max(source.minX, candidate.minX) + } + guard forward > 0 else { return nil } + return DirectionalDistance( + isAligned: overlap > 0, forward: forward, perpendicular: perpendicular + ) + } +} + +public struct DirectionalDistance: Sendable, Equatable, Codable, Comparable { + public let isAligned: Bool + public let forward: Double + public let perpendicular: Double + + public static func < (lhs: Self, rhs: Self) -> Bool { + if lhs.isAligned != rhs.isAligned { return lhs.isAligned } + let leftSquared = lhs.forward * lhs.forward + lhs.perpendicular * lhs.perpendicular + let rightSquared = rhs.forward * rhs.forward + rhs.perpendicular * rhs.perpendicular + if leftSquared != rightSquared { return leftSquared < rightSquared } + return lhs.perpendicular < rhs.perpendicular + } +} diff --git a/Sources/TesseraCore/LayoutEngine.swift b/Sources/TesseraCore/LayoutEngine.swift new file mode 100644 index 00000000..e87df25e --- /dev/null +++ b/Sources/TesseraCore/LayoutEngine.swift @@ -0,0 +1,106 @@ +public struct LayoutResult: Sendable, Equatable, Codable { + public var frames: [WindowID: Rect] + public var visibleWindows: [WindowID] + public var cannotFit: [WindowID] + + public init(frames: [WindowID: Rect] = [:], visibleWindows: [WindowID] = [], cannotFit: [WindowID] = []) { + self.frames = frames + self.visibleWindows = visibleWindows + self.cannotFit = cannotFit + } +} + +public enum LayoutEngine { + public static func arrange( + _ workspace: Workspace, in screen: Rect, windows: [WindowID: ManagedWindow] = [:] + ) -> LayoutResult { + guard let tree = workspace.tree else { return LayoutResult() } + let area = screen.inset(by: workspace.reservedEdges).inset(by: workspace.gaps.outer) + let horizontalDividers = dividers(tree, axis: .horizontal) + let verticalDividers = dividers(tree, axis: .vertical) + var gap = max(0, workspace.gaps.inner) + if horizontalDividers > 0 { gap = min(gap, area.size.width / Double(horizontalDividers)) } + if verticalDividers > 0 { gap = min(gap, area.size.height / Double(verticalDividers)) } + var result = LayoutResult(visibleWindows: tree.visibleWindows) + place(tree, in: area, gap: gap, windows: windows, result: &result) + result.cannotFit.sort() + return result + } + + private static func dividers(_ tree: TileTree, axis: Axis) -> Int { + switch tree { + case .tile: return 0 + case .split(let splitAxis, _, let first, let second): + let left = dividers(first, axis: axis) + let right = dividers(second, axis: axis) + return splitAxis == axis ? left + right + 1 : max(left, right) + } + } + + private static func minimum(_ tree: TileTree, gap: Double, windows: [WindowID: ManagedWindow]) -> Size { + switch tree { + case .tile(let stack): + return stack.windows.reduce(Size()) { size, window in + let learned = windows[window]?.minimumSize ?? Size() + return Size(width: max(size.width, learned.width), height: max(size.height, learned.height)) + } + case .split(let axis, _, let first, let second): + let left = minimum(first, gap: gap, windows: windows) + let right = minimum(second, gap: gap, windows: windows) + return axis == .horizontal + ? Size(width: left.width + gap + right.width, height: max(left.height, right.height)) + : Size(width: max(left.width, right.width), height: left.height + gap + right.height) + } + } + + private static func place( + _ tree: TileTree, in area: Rect, gap: Double, windows: [WindowID: ManagedWindow], result: inout LayoutResult + ) { + switch tree { + case .tile(let stack): + let frame = area.roundedToWholePoints() + for window in stack.windows { + result.frames[window] = frame + if let size = windows[window]?.minimumSize, + frame.size.width < size.width || frame.size.height < size.height + { + result.cannotFit.append(window) + } + } + case .split(let axis, let fraction, let first, let second): + let extent = axis == .horizontal ? area.size.width : area.size.height + let available = max(0, extent - gap) + let firstMinimum = minimum(first, gap: gap, windows: windows) + let secondMinimum = minimum(second, gap: gap, windows: windows) + let lower = axis == .horizontal ? firstMinimum.width : firstMinimum.height + let upper = axis == .horizontal ? secondMinimum.width : secondMinimum.height + let firstGaps = Double(dividers(first, axis: axis)) * gap + let secondGaps = Double(dividers(second, axis: axis)) * gap + let desired = max(0, available - firstGaps - secondGaps) * min(1, max(0, fraction)) + firstGaps + let length: Double + if lower + upper <= available { + length = min(available - upper, max(lower, desired)) + } else { + // Keep every tile on-screen when constraints conflict; report the shortfall below. + length = lower + upper > 0 ? available * lower / (lower + upper) : desired + } + let left: Rect + let right: Rect + if axis == .horizontal { + left = Rect(x: area.minX, y: area.minY, width: length, height: area.size.height) + right = Rect( + x: area.minX + length + gap, y: area.minY, + width: max(0, available - length), height: area.size.height + ) + } else { + left = Rect(x: area.minX, y: area.minY, width: area.size.width, height: length) + right = Rect( + x: area.minX, y: area.minY + length + gap, + width: area.size.width, height: max(0, available - length) + ) + } + place(first, in: left, gap: gap, windows: windows, result: &result) + place(second, in: right, gap: gap, windows: windows, result: &result) + } + } +} diff --git a/Sources/TesseraCore/Model.swift b/Sources/TesseraCore/Model.swift new file mode 100644 index 00000000..818baae0 --- /dev/null +++ b/Sources/TesseraCore/Model.swift @@ -0,0 +1,170 @@ +public struct WindowID: RawRepresentable, Sendable, Equatable, Hashable, Codable, Comparable { + public let rawValue: UInt32 + public init(rawValue: UInt32) { self.rawValue = rawValue } + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } +} + +public struct AppID: Sendable, Equatable, Hashable, Codable { + public let pid: Int32 + public let bundleID: String + public init(pid: Int32, bundleID: String) { + self.pid = pid + self.bundleID = bundleID + } +} + +public struct DisplayID: RawRepresentable, Sendable, Equatable, Hashable, Codable, Comparable { + public let rawValue: String + public init(rawValue: String) { self.rawValue = rawValue } + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } +} + +public struct SpaceID: RawRepresentable, Sendable, Equatable, Hashable, Codable, Comparable { + public let rawValue: UInt64 + public init(rawValue: UInt64) { self.rawValue = rawValue } + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } +} + +public struct WorkspaceKey: Sendable, Equatable, Hashable, Codable, Comparable { + public let display: DisplayID + public let space: SpaceID + public init(display: DisplayID, space: SpaceID) { + self.display = display + self.space = space + } + public static func < (lhs: Self, rhs: Self) -> Bool { + lhs.display == rhs.display ? lhs.space < rhs.space : lhs.display < rhs.display + } +} + +public struct LearnedMinimumSize: Sendable, Equatable, Codable { + public let schemaVersion: Int + public let size: Size + public init(size: Size, schemaVersion: Int = 1) { + self.size = size + self.schemaVersion = schemaVersion + } +} + +public struct ManagedWindow: Sendable, Equatable, Codable { + public let id: WindowID + public var app: AppID + public var title: String + public var role: String + public var subrole: String? + public var minimum: LearnedMinimumSize? + public var isFloating: Bool + + public var minimumSize: Size? { minimum?.size } + + public init( + id: WindowID, app: AppID, title: String = "", role: String = "AXWindow", subrole: String? = nil, + minimumSize: Size? = nil, isFloating: Bool = false + ) { + self.id = id + self.app = app + self.title = title + self.role = role + self.subrole = subrole + minimum = minimumSize.map { LearnedMinimumSize(size: $0) } + self.isFloating = isFloating + } +} + +public struct Display: Sendable, Equatable, Codable { + public let id: DisplayID + public var frame: Rect + public init(id: DisplayID, frame: Rect) { + self.id = id + self.frame = frame + } +} + +public enum Layout: String, Sendable, Equatable, Codable, CaseIterable { + case grid, columns, rows, side + + public var next: Layout { + switch self { + case .grid: .columns + case .columns: .rows + case .rows: .side + case .side: .grid + } + } +} + +public struct MainRatio: Sendable, Equatable, Codable { + public let value: Double + public static let half = MainRatio(1.0 / 2) + public static let threeFifths = MainRatio(3.0 / 5) + public static let twoThirds = MainRatio(2.0 / 3) + public static let bounds = 0.2...0.8 + + public init(_ value: Double) { + precondition(value.isFinite, "A ratio must be finite") + self.value = min(Self.bounds.upperBound, max(Self.bounds.lowerBound, value)) + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + let value = try container.decode(Double.self) + guard value.isFinite else { + throw DecodingError.dataCorruptedError(in: container, debugDescription: "A ratio must be finite") + } + self.init(value) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(value) + } +} + +public struct Gaps: Sendable, Equatable, Codable { + public var inner: Double + public var outer: Insets + public init(inner: Double = 0, outer: Insets = Insets()) { + self.inner = inner + self.outer = outer + } +} + +public struct WindowStack: Sendable, Equatable, Codable { + public private(set) var windows: [WindowID] + public private(set) var visible: WindowID + + public init(_ first: WindowID, others: [WindowID] = []) { + windows = [first] + others.filter { $0 != first } + visible = first + } + + mutating func append(_ window: WindowID) { + guard !windows.contains(window) else { return } + windows.append(window) + visible = window + } + + mutating func select(_ window: WindowID) { + if windows.contains(window) { visible = window } + } + + mutating func cycle(forward: Bool) { + guard let index = windows.firstIndex(of: visible) else { return } + visible = windows[(index + (forward ? 1 : windows.count - 1)) % windows.count] + } + + func removing(_ window: WindowID) -> WindowStack? { + let remaining = windows.filter { $0 != window } + guard let first = remaining.first else { return nil } + var result = WindowStack(first, others: Array(remaining.dropFirst())) + result.visible = remaining.contains(visible) ? visible : remaining[remaining.count - 1] + return result + } + + func replacing(_ old: WindowID, with new: WindowID) -> WindowStack { + var result = self + result.windows = windows.map { $0 == old ? new : $0 } + if visible == old { result.visible = new } + return result + } +} diff --git a/Sources/TesseraCore/TesseraCore.swift b/Sources/TesseraCore/TesseraCore.swift deleted file mode 100644 index 8b137891..00000000 --- a/Sources/TesseraCore/TesseraCore.swift +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Sources/TesseraCore/TileTree.swift b/Sources/TesseraCore/TileTree.swift new file mode 100644 index 00000000..6920c292 --- /dev/null +++ b/Sources/TesseraCore/TileTree.swift @@ -0,0 +1,184 @@ +public indirect enum TileTree: Sendable, Equatable, Codable { + case tile(WindowStack) + case split(axis: Axis, fraction: Double, first: TileTree, second: TileTree) + + public var stacks: [WindowStack] { + switch self { + case .tile(let stack): [stack] + case .split(_, _, let first, let second): first.stacks + second.stacks + } + } + + public var windows: [WindowID] { stacks.flatMap(\.windows) } + public var tileCount: Int { stacks.count } + public var visibleWindows: [WindowID] { stacks.map(\.visible) } + + public static func balanced(_ stacks: [WindowStack], layout: Layout, ratio: MainRatio = .half) -> TileTree? { + guard let first = stacks.first else { return nil } + guard stacks.count > 1 else { return .tile(first) } + switch layout { + case .columns: return line(stacks, axis: .horizontal) + case .rows: return line(stacks, axis: .vertical) + case .side: + return .split( + axis: .horizontal, fraction: ratio.value, first: .tile(first), + second: line(Array(stacks.dropFirst()), axis: .vertical) + ) + case .grid: + let columns = Int(Double(stacks.count).squareRoot().rounded(.up)) + let rows = stride(from: 0, to: stacks.count, by: columns).map { start in + line(Array(stacks[start.. TileTree { + lineTrees(stacks.map { .tile($0) }, axis: axis) + } + + private static func lineTrees(_ trees: [TileTree], axis: Axis) -> TileTree { + precondition(!trees.isEmpty) + if trees.count == 1 { return trees[0] } + return .split( + axis: axis, fraction: 1 / Double(trees.count), first: trees[0], + second: lineTrees(Array(trees.dropFirst()), axis: axis) + ) + } + + func mappingStacks(_ transform: (WindowStack) -> WindowStack) -> TileTree { + switch self { + case .tile(let stack): .tile(transform(stack)) + case .split(let axis, let fraction, let first, let second): + .split( + axis: axis, fraction: fraction, + first: first.mappingStacks(transform), second: second.mappingStacks(transform) + ) + } + } + + func removing(_ window: WindowID) -> TileTree? { + switch self { + case .tile(let stack): return stack.removing(window).map { .tile($0) } + case .split(let axis, let fraction, let first, let second): + let left = first.removing(window) + let right = second.removing(window) + if let left, let right { return .split(axis: axis, fraction: fraction, first: left, second: right) } + return left ?? right + } + } + + func inserting(_ window: WindowID, beside target: WindowID, axis: Axis, before: Bool) -> TileTree { + switch self { + case .tile(let stack): + guard stack.windows.contains(target) else { return self } + let new = TileTree.tile(WindowStack(window)) + return .split(axis: axis, fraction: 0.5, first: before ? new : self, second: before ? self : new) + case .split(let splitAxis, let fraction, let first, let second): + return .split( + axis: splitAxis, fraction: fraction, + first: first.inserting(window, beside: target, axis: axis, before: before), + second: second.inserting(window, beside: target, axis: axis, before: before) + ) + } + } + + func settingMainRatio(_ ratio: MainRatio) -> TileTree { + guard case .split(.horizontal, _, let first, let second) = self else { return self } + return .split(axis: .horizontal, fraction: ratio.value, first: first, second: second) + } +} + +public struct Workspace: Sendable, Equatable, Codable { + public let key: WorkspaceKey + public var layout: Layout + public var ratio: MainRatio + public var gaps: Gaps + public var reservedEdges: Insets + public private(set) var windowCap: Int + public internal(set) var order: [WindowID] + public internal(set) var focus: WindowID? + public internal(set) var tree: TileTree? + + public init( + key: WorkspaceKey, layout: Layout = .grid, ratio: MainRatio = .half, + gaps: Gaps = Gaps(), reservedEdges: Insets = Insets(), windowCap: Int = 8, + order: [WindowID] = [], focus: WindowID? = nil + ) { + self.key = key + self.layout = layout + self.ratio = ratio + self.gaps = gaps + self.reservedEdges = reservedEdges + self.windowCap = max(1, windowCap) + var seen: Set = [] + self.order = order.filter { seen.insert($0).inserted } + self.focus = focus.flatMap { self.order.contains($0) ? $0 : nil } + tree = nil + rebuild(stacks: self.order.map { WindowStack($0) }) + } + + public var visibleWindows: [WindowID] { tree?.visibleWindows ?? [] } + + public mutating func setWindowCap(_ cap: Int) { + windowCap = max(1, cap) + rebuild(stacks: tree?.stacks ?? []) + } + + mutating func rebuild(stacks: [WindowStack]) { + var capped = Array(stacks.prefix(windowCap)) + if !capped.isEmpty { + for overflow in stacks.dropFirst(windowCap) { + for window in overflow.windows { capped[capped.count - 1].append(window) } + } + } + tree = TileTree.balanced(capped, layout: layout, ratio: ratio) + if let focus { select(focus) } + } + + mutating func select(_ window: WindowID) { + guard order.contains(window) else { return } + focus = window + tree = tree?.mappingStacks { stack in + var selected = stack + selected.select(window) + return selected + } + } + + mutating func remove(_ window: WindowID) { + order.removeAll { $0 == window } + tree = tree?.removing(window) + if focus == window { focus = tree?.visibleWindows.last ?? order.last } + } + + mutating func insert(_ window: WindowID, floating: Bool, in frame: Rect, windows: [WindowID: ManagedWindow]) { + guard !order.contains(window) else { return } + order.append(window) + focus = window + guard !floating else { return } + guard let current = tree, let newest = current.stacks.last else { + tree = .tile(WindowStack(window)) + return + } + if current.tileCount >= windowCap { + tree = current.mappingStacks { stack in + var updated = stack + if stack.windows == newest.windows { updated.append(window) } + return updated + } + return + } + let axis: Axis + switch layout { + case .columns: axis = .horizontal + case .rows: axis = .vertical + case .side: axis = current.tileCount == 1 ? .horizontal : .vertical + case .grid: + let area = LayoutEngine.arrange(self, in: frame, windows: windows).frames[newest.visible] ?? frame + axis = area.size.width >= area.size.height ? .horizontal : .vertical + } + tree = current.inserting(window, beside: newest.visible, axis: axis, before: false) + if layout == .side && current.tileCount == 1 { tree = tree?.settingMainRatio(ratio) } + } +} diff --git a/Tests/TesseraCoreTests/GeometryLayoutTests.swift b/Tests/TesseraCoreTests/GeometryLayoutTests.swift new file mode 100644 index 00000000..ea94b48d --- /dev/null +++ b/Tests/TesseraCoreTests/GeometryLayoutTests.swift @@ -0,0 +1,252 @@ +import Foundation +import Testing + +@testable import TesseraCore + +func windowID(_ number: Int) -> WindowID { WindowID(rawValue: UInt32(number)) } +let primaryDisplay = DisplayID(rawValue: "00000000-0000-0000-0000-000000000001") +let primarySpace = SpaceID(rawValue: 1) +let primaryKey = WorkspaceKey(display: primaryDisplay, space: primarySpace) +let testScreen = Rect(x: 0, y: 0, width: 1200, height: 800) + +func managed(_ number: Int, minimum: Size? = nil, floating: Bool = false) -> ManagedWindow { + ManagedWindow( + id: windowID(number), app: AppID(pid: Int32(number), bundleID: "test.fixture"), + title: "Window \(number)", minimumSize: minimum, isFloating: floating + ) +} + +func workspace(_ count: Int, layout: Layout = .grid, gaps: Gaps = Gaps(), cap: Int = 8) -> Workspace { + Workspace( + key: primaryKey, layout: layout, gaps: gaps, windowCap: cap, + order: (1...max(1, count)).prefix(count).map(windowID)) +} + +func roundTrip(_ value: Value) throws { + #expect(try JSONDecoder().decode(Value.self, from: JSONEncoder().encode(value)) == value) +} + +@Test func geometryValues() throws { + let point = Point(x: -50, y: 70) + let size = Size(width: 400, height: 300) + let rect = Rect(origin: point, size: size) + #expect(rect.minX == -50) + #expect(rect.maxX == 350) + #expect(rect.minY == 70) + #expect(rect.maxY == 370) + #expect(rect.center == Point(x: 150, y: 220)) + #expect(rect.contains(Point(x: 350, y: 370))) + #expect(!rect.contains(Point(x: 351, y: 370))) + try roundTrip(point) + try roundTrip(size) + try roundTrip(rect) + try roundTrip(Insets(3)) +} + +@Test func insetClampsExcessAndNegativeValues() { + #expect( + testScreen.inset(by: Insets(top: 20, left: 30, bottom: 40, right: 50)) + == Rect(x: 30, y: 20, width: 1120, height: 740)) + #expect(testScreen.inset(by: Insets(2000)) == Rect(x: 1200, y: 800, width: 0, height: 0)) + #expect(testScreen.inset(by: Insets(-10)) == testScreen) + #expect(Rect(width: -2, height: -3).inset(by: Insets()) == Rect()) +} + +@Test func roundingUsesEdgesInGlobalCoordinates() { + #expect( + Rect(x: -0.6, y: 0.6, width: 10.2, height: 10.2).roundedToWholePoints() + == Rect(x: -1, y: 1, width: 11, height: 10)) +} + +@Test func identifiersAndWindowMetadata() throws { + try roundTrip(windowID(3)) + try roundTrip(primaryDisplay) + try roundTrip(primarySpace) + try roundTrip(primaryKey) + var window = managed(1, minimum: Size(width: 300, height: 200), floating: true) + window.subrole = "AXStandardWindow" + #expect(window.minimum?.schemaVersion == 1) + #expect(window.minimumSize == Size(width: 300, height: 200)) + try roundTrip(window) + window.minimum = nil + #expect(window.minimumSize == nil) + #expect(windowID(1) < windowID(2)) + #expect(primarySpace < SpaceID(rawValue: 2)) +} + +@Test(arguments: [-10.0, 0.2, 0.5, 0.6, 2.0 / 3, 0.8, 10.0]) +func ratiosClampAndEncode(value: Double) throws { + let ratio = MainRatio(value) + #expect(ratio.value == min(0.8, max(0.2, value))) + try roundTrip(ratio) + #expect(try JSONDecoder().decode(MainRatio.self, from: Data("10".utf8)) == MainRatio(0.8)) + #expect(MainRatio.half.value == 0.5) + #expect(MainRatio.threeFifths.value == 0.6) + #expect(MainRatio.twoThirds.value == 2.0 / 3) +} + +@Test(arguments: Layout.allCases, 1...8) +func canonicalLayoutPixels(layout: Layout, count: Int) { + let frames = LayoutEngine.arrange(workspace(count, layout: layout), in: testScreen).frames + #expect(frames.count == count) + for index in 0..= area.minX && frame.maxX <= area.maxX) + #expect(frame.minY >= area.minY && frame.maxY <= area.maxY) + #expect(frame.minX == frame.minX.rounded()) + #expect(frame.size.width >= 0 && frame.size.height >= 0) + } + if count == 1 { #expect(frames[windowID(1)] == area) } + if layout == .columns && count > 1 { + for number in 1..= 0 && frame.size.height >= 0) + #expect(frame.minX >= 2 && frame.maxX <= 28) + #expect(frame.minY >= 2 && frame.maxY <= 18) + } +} + +@Test(arguments: [MainRatio.half, .threeFifths, .twoThirds], 2...8) +func sideRatioPixels(ratio: MainRatio, count: Int) { + var space = workspace(count, layout: .side) + space.ratio = ratio + space.rebuild(stacks: space.tree?.stacks ?? []) + let result = LayoutEngine.arrange(space, in: testScreen) + #expect(result.frames[windowID(1)] == Rect(width: (1200 * ratio.value).rounded(), height: 800)) + #expect(result.cannotFit.isEmpty) +} + +@Test func minimumSizesShiftDividerWithoutLeavingScreen() { + let space = workspace(2, layout: .columns) + let windows = [windowID(1): managed(1, minimum: Size(width: 900, height: 400)), windowID(2): managed(2)] + let result = LayoutEngine.arrange(space, in: testScreen, windows: windows) + #expect(result.frames[windowID(1)] == Rect(width: 900, height: 800)) + #expect(result.frames[windowID(2)] == Rect(x: 900, width: 300, height: 800)) + #expect(result.cannotFit.isEmpty) +} + +@Test(arguments: Layout.allCases) +func impossibleMinimumSizesAreReported(layout: Layout) { + let space = workspace(3, layout: layout) + let windows = Dictionary( + uniqueKeysWithValues: (1...3).map { (windowID($0), managed($0, minimum: Size(width: 1500, height: 900))) }) + let result = LayoutEngine.arrange(space, in: testScreen, windows: windows) + #expect(result.cannotFit == (1...3).map(windowID)) + for frame in result.frames.values { + #expect(frame.minX >= 0 && frame.maxX <= 1200) + #expect(frame.minY >= 0 && frame.maxY <= 800) + } +} + +@Test(arguments: Layout.allCases, 1...4) +func capStacksOverflow(layout: Layout, cap: Int) throws { + let space = workspace(8, layout: layout, cap: cap) + #expect(space.tree?.tileCount == cap) + #expect(space.tree?.windows == (1...8).map(windowID)) + let result = LayoutEngine.arrange(space, in: testScreen) + for number in cap...8 { #expect(result.frames[windowID(number)] == result.frames[windowID(cap)]) } + #expect(result.visibleWindows.last == windowID(8)) + try roundTrip(space) +} + +@Test func stackMinimumIncludesHiddenMembers() { + let space = workspace(3, layout: .columns, cap: 2) + let windows = [windowID(2): managed(2, minimum: Size(width: 850, height: 10))] + let result = LayoutEngine.arrange(space, in: testScreen, windows: windows) + #expect(result.frames[windowID(2)]?.size.width == 850) + #expect(result.frames[windowID(3)] == result.frames[windowID(2)]) +} + +@Test func emptyWorkspaceAndClampedCap() { + #expect(LayoutEngine.arrange(workspace(0), in: testScreen) == LayoutResult()) + var space = workspace(3, cap: 0) + #expect(space.windowCap == 1) + space.setWindowCap(2) + #expect(space.tree?.tileCount == 1) + #expect(space.order == (1...3).map(windowID)) +} + +@Test(arguments: Layout.allCases) +func insertionSplitsOnlyNewestArea(layout: Layout) { + var space = workspace(0, layout: layout) + space.insert(windowID(1), floating: false, in: testScreen, windows: [:]) + #expect(LayoutEngine.arrange(space, in: testScreen).frames[windowID(1)] == testScreen) + space.insert(windowID(2), floating: false, in: testScreen, windows: [:]) + let before = LayoutEngine.arrange(space, in: testScreen).frames + space.insert(windowID(3), floating: false, in: testScreen, windows: [:]) + let after = LayoutEngine.arrange(space, in: testScreen).frames + #expect(after[windowID(1)] == before[windowID(1)]) + let expected: Rect + switch layout { + case .columns: expected = Rect(x: 900, width: 300, height: 800) + case .rows: expected = Rect(y: 600, width: 1200, height: 200) + case .grid, .side: expected = Rect(x: 600, y: 400, width: 600, height: 400) + } + #expect(after[windowID(3)] == expected) + #expect(space.order == (1...3).map(windowID)) +} + +@Test func removingLeafCollapsesItsSplit() { + var space = workspace(3, layout: .columns) + space.remove(windowID(2)) + #expect(space.tree?.tileCount == 2) + #expect(space.order == [windowID(1), windowID(3)]) + #expect(LayoutEngine.arrange(space, in: testScreen).frames[windowID(3)] == Rect(x: 400, width: 800, height: 800)) + space.remove(windowID(1)) + #expect(LayoutEngine.arrange(space, in: testScreen).frames[windowID(3)] == testScreen) +} diff --git a/Tests/TesseraCoreTests/TesseraCoreTests.swift b/Tests/TesseraCoreTests/TesseraCoreTests.swift deleted file mode 100644 index 13bcff47..00000000 --- a/Tests/TesseraCoreTests/TesseraCoreTests.swift +++ /dev/null @@ -1,4 +0,0 @@ -import Testing -@testable import TesseraCore - -@Test func builds() {} -- knotmirror 0.0.1 From 93d2fc6f92b410dd51d17e21a8f0d2ec1eb23a30 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:40:47 -0400 Subject: [PATCH 08/44] Read window server state --- Sources/TesseraPlatform/WindowServer.swift | 267 ++++++++++++++++++ .../WindowServerTests.swift | 182 ++++++++++++ 2 files changed, 449 insertions(+) create mode 100644 Sources/TesseraPlatform/WindowServer.swift create mode 100644 Tests/TesseraPlatformTests/WindowServerTests.swift diff --git a/Sources/TesseraPlatform/WindowServer.swift b/Sources/TesseraPlatform/WindowServer.swift new file mode 100644 index 00000000..f84dc1d0 --- /dev/null +++ b/Sources/TesseraPlatform/WindowServer.swift @@ -0,0 +1,267 @@ +import CoreFoundation +public import CoreGraphics +import Darwin +import Foundation + +public struct WindowServer: Sendable { + public struct Window: Equatable, Sendable { + public let number: CGWindowID + public let pid: pid_t + public let bounds: CGRect + public let layer: Int32 + public let isOnscreen: Bool + } + + public struct DisplaySpaces: Equatable, Sendable { + public let displayID: String + public let spaces: [UInt64] + } + + public struct Capabilities: Equatable, Sendable { + public let mainConnection: Bool + public let managedDisplaySpaces: Bool + public let currentSpace: Bool + public let windowListBrightness: Bool + + public var canReadDisplaySpaces: Bool { mainConnection && managedDisplaySpaces } + public var canReadCurrentSpace: Bool { mainConnection && currentSpace } + public var experimentalBrightness: Bool { mainConnection && windowListBrightness } + + init(probe: (String) -> Bool) { + mainConnection = probe("SLSMainConnectionID") + managedDisplaySpaces = probe("SLSCopyManagedDisplaySpaces") + currentSpace = probe("SLSManagedDisplayGetCurrentSpace") + windowListBrightness = probe("CGSSetWindowListBrightness") + } + } + + public enum DataProblem: Equatable, Sendable { + case missing + case malformed + } + + public enum ReadError: Error, Equatable, Sendable, CustomStringConvertible { + case windowListUnavailable + case malformedWindowList + case displaySpacesUnavailable + case malformedDisplaySpacesList + case symbolUnavailable(String) + case currentSpaceUnavailable(displayID: String) + case invalidWindow(index: Int, field: String, problem: DataProblem) + case invalidDisplaySpaces(index: Int, field: String, problem: DataProblem) + + public var description: String { + switch self { + case .windowListUnavailable: + return "The window server did not return a window list." + case .malformedWindowList: + return "The window server returned a malformed window list." + case .displaySpacesUnavailable: + return "The window server did not return display spaces." + case .malformedDisplaySpacesList: + return "The window server returned a malformed display spaces list." + case .symbolUnavailable(let symbol): + return "The window server symbol \(symbol) is unavailable." + case .currentSpaceUnavailable(let displayID): + return "The current space is unavailable for display \(displayID)." + case .invalidWindow(let index, let field, let problem): + return "Window \(index) has \(problem) data for \(field)." + case .invalidDisplaySpaces(let index, let field, let problem): + return "Display spaces entry \(index) has \(problem) data for \(field)." + } + } + } + + public init() {} + + public var capabilities: Capabilities { RuntimeSymbols.shared.capabilities } + + public func windows( + options: CGWindowListOption = .optionAll, + relativeTo: CGWindowID = kCGNullWindowID + ) throws -> [Window] { + guard let records = CGWindowListCopyWindowInfo(options, relativeTo) else { + throw ReadError.windowListUnavailable + } + guard CFGetTypeID(records) == CFArrayGetTypeID() else { throw ReadError.malformedWindowList } + return try Self.decodeWindows(records as NSArray) + } + + public func displaySpaces() throws -> [DisplaySpaces] { + let symbols = RuntimeSymbols.shared + guard let connectionPointer = symbols.mainConnection else { + throw ReadError.symbolUnavailable("SLSMainConnectionID") + } + guard let spacesPointer = symbols.managedDisplaySpaces else { + throw ReadError.symbolUnavailable("SLSCopyManagedDisplaySpaces") + } + let connection = unsafeBitCast(connectionPointer, to: MainConnection.self) + let copySpaces = unsafeBitCast(spacesPointer, to: CopyManagedDisplaySpaces.self) + guard let records = copySpaces(connection())?.takeRetainedValue() else { + throw ReadError.displaySpacesUnavailable + } + guard CFGetTypeID(records) == CFArrayGetTypeID() else { throw ReadError.malformedDisplaySpacesList } + return try Self.decodeDisplaySpaces(records as NSArray) + } + + public func currentSpace(displayID: String) throws -> UInt64 { + guard !displayID.isEmpty else { + throw ReadError.currentSpaceUnavailable(displayID: displayID) + } + let symbols = RuntimeSymbols.shared + guard let connectionPointer = symbols.mainConnection else { + throw ReadError.symbolUnavailable("SLSMainConnectionID") + } + guard let spacePointer = symbols.currentSpace else { + throw ReadError.symbolUnavailable("SLSManagedDisplayGetCurrentSpace") + } + let connection = unsafeBitCast(connectionPointer, to: MainConnection.self) + let getCurrentSpace = unsafeBitCast(spacePointer, to: GetCurrentSpace.self) + let space = getCurrentSpace(connection(), displayID as CFString) + guard space != 0 else { + throw ReadError.currentSpaceUnavailable(displayID: displayID) + } + return space + } + + static func decodeWindows(_ value: Any) throws -> [Window] { + guard let records = value as? [Any] else { throw ReadError.malformedWindowList } + return try records.enumerated().map { index, record in + func error(_ field: String, _ problem: DataProblem) -> ReadError { + .invalidWindow(index: index, field: field, problem: problem) + } + guard let fields = record as? [String: Any] else { + throw error("record", .malformed) + } + func required(_ key: String) throws -> Any { + guard let value = fields[key] else { throw error(key, .missing) } + return value + } + let numberKey = kCGWindowNumber as String + let pidKey = kCGWindowOwnerPID as String + let boundsKey = kCGWindowBounds as String + let layerKey = kCGWindowLayer as String + let onscreenKey = kCGWindowIsOnscreen as String + + guard let number = unsignedInteger(try required(numberKey), as: UInt32.self), number != 0 else { + throw error(numberKey, .malformed) + } + guard let pid = signedInteger(try required(pidKey), as: Int32.self), pid >= 0 else { + throw error(pidKey, .malformed) + } + guard let layer = signedInteger(try required(layerKey), as: Int32.self) else { + throw error(layerKey, .malformed) + } + guard let boundsFields = try required(boundsKey) as? [String: Any] else { + throw error(boundsKey, .malformed) + } + func coordinate(_ key: String) throws -> Double { + guard let value = boundsFields[key] else { throw error("\(boundsKey).\(key)", .missing) } + guard let number = numericValue(value), number.doubleValue.isFinite else { + throw error("\(boundsKey).\(key)", .malformed) + } + return number.doubleValue + } + let originX = try coordinate("X") + let originY = try coordinate("Y") + let width = try coordinate("Width") + let height = try coordinate("Height") + guard width >= 0, height >= 0 else { throw error(boundsKey, .malformed) } + let onscreen: Bool + if let value = fields[onscreenKey] { + guard let boolean = value as? NSNumber, CFGetTypeID(boolean) == CFBooleanGetTypeID() else { + throw error(onscreenKey, .malformed) + } + onscreen = boolean.boolValue + } else { + // Core Graphics omits this key for windows not ordered onscreen. + onscreen = false + } + return Window( + number: number, pid: pid, bounds: CGRect(x: originX, y: originY, width: width, height: height), + layer: layer, isOnscreen: onscreen + ) + } + } + + static func decodeDisplaySpaces(_ value: Any) throws -> [DisplaySpaces] { + guard let records = value as? [Any] else { throw ReadError.malformedDisplaySpacesList } + return try records.enumerated().map { index, record in + func error(_ field: String, _ problem: DataProblem) -> ReadError { + .invalidDisplaySpaces(index: index, field: field, problem: problem) + } + guard let fields = record as? [String: Any] else { throw error("record", .malformed) } + guard let rawDisplayID = fields["Display Identifier"] else { + throw error("Display Identifier", .missing) + } + guard let displayID = rawDisplayID as? String, !displayID.isEmpty else { + throw error("Display Identifier", .malformed) + } + guard let rawSpaces = fields["Spaces"] else { throw error("Spaces", .missing) } + guard let spaces = rawSpaces as? [Any] else { throw error("Spaces", .malformed) } + let identifiers: [UInt64] = try spaces.enumerated().map { spaceIndex, space in + let field = "Spaces[\(spaceIndex)].ManagedSpaceID" + guard let entry = space as? [String: Any] else { throw error("Spaces[\(spaceIndex)]", .malformed) } + guard let rawID = entry["ManagedSpaceID"] else { throw error(field, .missing) } + guard let identifier = unsignedInteger(rawID, as: UInt64.self), identifier != 0 else { + throw error(field, .malformed) + } + return identifier + } + return DisplaySpaces(displayID: displayID, spaces: identifiers) + } + } +} + +private func numericValue(_ value: Any) -> NSNumber? { + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() else { return nil } + return number +} + +private func signedInteger(_ value: Any, as: T.Type) -> T? { + guard let number = numericValue(value) else { return nil } + return T(number.stringValue) +} + +private func unsignedInteger(_ value: Any, as: T.Type) -> T? { + guard let number = numericValue(value) else { return nil } + return T(number.stringValue) +} + +private typealias MainConnection = @convention(c) () -> UInt32 +private typealias CopyManagedDisplaySpaces = @convention(c) (UInt32) -> Unmanaged? +private typealias GetCurrentSpace = @convention(c) (UInt32, CFString) -> UInt64 + +private final class RuntimeSymbols: @unchecked Sendable { + static let shared = RuntimeSymbols() + + let mainConnection: UnsafeMutableRawPointer? + let managedDisplaySpaces: UnsafeMutableRawPointer? + let currentSpace: UnsafeMutableRawPointer? + let capabilities: WindowServer.Capabilities + + private init() { + // Keep handles open for the lifetime of the function pointers. + let skyLight = dlopen("/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight", RTLD_LAZY | RTLD_LOCAL) + func lookup(_ handle: UnsafeMutableRawPointer?, _ name: String) -> UnsafeMutableRawPointer? { + guard let handle else { return nil } + return dlsym(handle, name) + } + let connection = lookup(skyLight, "SLSMainConnectionID") + let spaces = lookup(skyLight, "SLSCopyManagedDisplaySpaces") + let current = lookup(skyLight, "SLSManagedDisplayGetCurrentSpace") + let brightness = lookup(skyLight, "CGSSetWindowListBrightness") + mainConnection = connection + managedDisplaySpaces = spaces + currentSpace = current + capabilities = WindowServer.Capabilities { name in + switch name { + case "SLSMainConnectionID": connection != nil + case "SLSCopyManagedDisplaySpaces": spaces != nil + case "SLSManagedDisplayGetCurrentSpace": current != nil + case "CGSSetWindowListBrightness": brightness != nil + default: false + } + } + } +} diff --git a/Tests/TesseraPlatformTests/WindowServerTests.swift b/Tests/TesseraPlatformTests/WindowServerTests.swift new file mode 100644 index 00000000..24445c58 --- /dev/null +++ b/Tests/TesseraPlatformTests/WindowServerTests.swift @@ -0,0 +1,182 @@ +import CoreGraphics +import Foundation +import Testing + +@testable import TesseraPlatform + +private func windowFields() -> [String: Any] { + [ + kCGWindowNumber as String: 123, + kCGWindowOwnerPID as String: 456, + kCGWindowBounds as String: ["X": -20.5, "Y": 30.0, "Width": 800.0, "Height": 600.0], + kCGWindowLayer as String: -1, + kCGWindowIsOnscreen as String: true, + ] +} + +@Test func probesCapabilitiesIndependently() { + let available: Set = ["SLSMainConnectionID", "SLSCopyManagedDisplaySpaces", "CGSSetWindowListBrightness"] + var probed: [String] = [] + let capabilities = WindowServer.Capabilities { symbol in + probed.append(symbol) + return available.contains(symbol) + } + #expect( + probed == [ + "SLSMainConnectionID", "SLSCopyManagedDisplaySpaces", "SLSManagedDisplayGetCurrentSpace", + "CGSSetWindowListBrightness", + ]) + #expect(capabilities.mainConnection) + #expect(capabilities.managedDisplaySpaces) + #expect(!capabilities.currentSpace) + #expect(capabilities.experimentalBrightness) + #expect(capabilities.canReadDisplaySpaces) + #expect(!capabilities.canReadCurrentSpace) + + let missingConnection = WindowServer.Capabilities { $0 != "SLSMainConnectionID" } + #expect(!missingConnection.canReadDisplaySpaces) + #expect(!missingConnection.canReadCurrentSpace) + #expect(!missingConnection.experimentalBrightness) + let missingBrightness = WindowServer.Capabilities { $0 != "CGSSetWindowListBrightness" } + #expect(!missingBrightness.experimentalBrightness) + let noSymbols = WindowServer.Capabilities { _ in false } + #expect(!noSymbols.experimentalBrightness) + #expect(!noSymbols.canReadDisplaySpaces) + #expect(!noSymbols.canReadCurrentSpace) +} + +@Test func decodesWindowRecords() throws { + var offscreen = windowFields() + offscreen.removeValue(forKey: kCGWindowIsOnscreen as String) + let windows = try WindowServer.decodeWindows(([windowFields(), offscreen] as NSArray).map { $0 }) + #expect(windows.count == 2) + #expect(windows[0].number == 123) + #expect(windows[0].pid == 456) + #expect(windows[0].bounds == CGRect(x: -20.5, y: 30, width: 800, height: 600)) + #expect(windows[0].layer == -1) + #expect(windows[0].isOnscreen) + #expect(!windows[1].isOnscreen) + #expect(try WindowServer.decodeWindows([]).isEmpty) +} + +@Test func rejectsMissingAndMalformedWindowFields() { + let number = kCGWindowNumber as String + let pid = kCGWindowOwnerPID as String + let bounds = kCGWindowBounds as String + let layer = kCGWindowLayer as String + let onscreen = kCGWindowIsOnscreen as String + + #expect(throws: WindowServer.ReadError.invalidWindow(index: 0, field: "record", problem: .malformed)) { + try WindowServer.decodeWindows(["not a dictionary"]) + } + var fields = windowFields() + fields.removeValue(forKey: number) + #expect(throws: WindowServer.ReadError.invalidWindow(index: 0, field: number, problem: .missing)) { + try WindowServer.decodeWindows([fields]) + } + for invalid: Any in [true, -1, 0, 4.5, UInt64.max, "123"] { + fields = windowFields() + fields[number] = invalid + #expect(throws: WindowServer.ReadError.invalidWindow(index: 0, field: number, problem: .malformed)) { + try WindowServer.decodeWindows([fields]) + } + } + fields = windowFields() + fields[pid] = Int64(Int32.max) + 1 + #expect(throws: WindowServer.ReadError.invalidWindow(index: 0, field: pid, problem: .malformed)) { + try WindowServer.decodeWindows([fields]) + } + fields = windowFields() + fields[layer] = 0.5 + #expect(throws: WindowServer.ReadError.invalidWindow(index: 0, field: layer, problem: .malformed)) { + try WindowServer.decodeWindows([fields]) + } + fields = windowFields() + fields[onscreen] = 1 + #expect(throws: WindowServer.ReadError.invalidWindow(index: 0, field: onscreen, problem: .malformed)) { + try WindowServer.decodeWindows([fields]) + } + fields = windowFields() + fields[bounds] = ["X": 1, "Y": 2, "Width": 3] + #expect(throws: WindowServer.ReadError.invalidWindow(index: 0, field: "\(bounds).Height", problem: .missing)) { + try WindowServer.decodeWindows([fields]) + } + for invalid: Any in [Double.infinity, Double.nan, true, "2"] { + fields = windowFields() + fields[bounds] = ["X": invalid, "Y": 2, "Width": 3, "Height": 4] + #expect(throws: WindowServer.ReadError.invalidWindow(index: 0, field: "\(bounds).X", problem: .malformed)) { + try WindowServer.decodeWindows([fields]) + } + } + fields = windowFields() + fields[bounds] = ["X": 0, "Y": 0, "Width": -1, "Height": 2] + #expect(throws: WindowServer.ReadError.invalidWindow(index: 1, field: bounds, problem: .malformed)) { + try WindowServer.decodeWindows([windowFields(), fields]) + } +} + +@Test func decodesDisplaySpaces() throws { + let entries: [Any] = [ + ["Display Identifier": "display-a", "Spaces": [["ManagedSpaceID": 3], ["ManagedSpaceID": UInt64.max]]], + ["Display Identifier": "display-b", "Spaces": []], + ] + let result = try WindowServer.decodeDisplaySpaces((entries as NSArray).map { $0 }) + #expect(result.count == 2) + #expect(result[0].displayID == "display-a") + #expect(result[0].spaces == [3, UInt64.max]) + #expect(result[1].displayID == "display-b") + #expect(result[1].spaces.isEmpty) + #expect(try WindowServer.decodeDisplaySpaces([]).isEmpty) +} + +@Test func rejectsMalformedDisplaySpaces() { + #expect(throws: WindowServer.ReadError.invalidDisplaySpaces(index: 0, field: "record", problem: .malformed)) { + try WindowServer.decodeDisplaySpaces([false]) + } + #expect( + throws: WindowServer.ReadError.invalidDisplaySpaces(index: 0, field: "Display Identifier", problem: .missing) + ) { + try WindowServer.decodeDisplaySpaces([[:]]) + } + #expect( + throws: WindowServer.ReadError.invalidDisplaySpaces(index: 0, field: "Display Identifier", problem: .malformed) + ) { + try WindowServer.decodeDisplaySpaces([["Display Identifier": ""]]) + } + #expect(throws: WindowServer.ReadError.invalidDisplaySpaces(index: 0, field: "Spaces", problem: .missing)) { + try WindowServer.decodeDisplaySpaces([["Display Identifier": "display"]]) + } + #expect(throws: WindowServer.ReadError.invalidDisplaySpaces(index: 0, field: "Spaces", problem: .malformed)) { + try WindowServer.decodeDisplaySpaces([["Display Identifier": "display", "Spaces": "not an array"]]) + } + #expect(throws: WindowServer.ReadError.invalidDisplaySpaces(index: 0, field: "Spaces[0]", problem: .malformed)) { + try WindowServer.decodeDisplaySpaces([["Display Identifier": "display", "Spaces": [5]]]) + } + #expect( + throws: WindowServer.ReadError.invalidDisplaySpaces( + index: 0, field: "Spaces[0].ManagedSpaceID", problem: .missing) + ) { + try WindowServer.decodeDisplaySpaces([["Display Identifier": "display", "Spaces": [[:]]]]) + } + for invalid: Any in [true, -1, 0, 1.5, "3"] { + #expect( + throws: WindowServer.ReadError.invalidDisplaySpaces( + index: 0, field: "Spaces[0].ManagedSpaceID", problem: .malformed) + ) { + try WindowServer.decodeDisplaySpaces([ + ["Display Identifier": "display", "Spaces": [["ManagedSpaceID": invalid]]] + ]) + } + } +} + +@Test func readsCurrentWindowList() throws { + let windows = try WindowServer().windows() + #expect(windows.allSatisfy { $0.number != 0 && $0.bounds.width >= 0 && $0.bounds.height >= 0 }) +} + +@Test func rejectsEmptyDisplayID() { + #expect(throws: WindowServer.ReadError.currentSpaceUnavailable(displayID: "")) { + try WindowServer().currentSpace(displayID: "") + } +} -- knotmirror 0.0.1 From 143508423abb13fe8c4e1742ec23a386c74062b9 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:40:48 -0400 Subject: [PATCH 09/44] Observe apps on dedicated threads --- Sources/TesseraPlatform/AppThread.swift | 662 ++++++++++++++++++ .../TesseraPlatformTests/AppThreadTests.swift | 223 ++++++ 2 files changed, 885 insertions(+) create mode 100644 Sources/TesseraPlatform/AppThread.swift create mode 100644 Tests/TesseraPlatformTests/AppThreadTests.swift diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift new file mode 100644 index 00000000..8c234992 --- /dev/null +++ b/Sources/TesseraPlatform/AppThread.swift @@ -0,0 +1,662 @@ +import ApplicationServices +import CoreFoundation +public import CoreGraphics +import Darwin +public import Foundation + +/// Events contain window server IDs rather than AX objects, which stay on the app thread. +public enum AppThreadEvent: Sendable, Equatable { + case windowCreated(CGWindowID) + case windowDestroyed(CGWindowID) + case windowMoved(CGWindowID, origin: AppThreadEventOrigin) + case windowResized(CGWindowID, origin: AppThreadEventOrigin) + case windowTitleChanged(CGWindowID) + case windowMinimized(CGWindowID) + case windowDeminimized(CGWindowID) + case focusedWindowChanged + case applicationActivated + case applicationDeactivated + case windowList([CGWindowID]) + case reconciliation(AppThreadReconciliation) + case unresponsive + case responsive + case failure(AppThreadFailure) +} + +/// A snapshot, not a claim that every window server entry should have an AX counterpart. +public struct AppThreadReconciliation: Sendable, Equatable { + public let axWindowIDs: [CGWindowID] + public let serverWindows: [WindowServer.Window] + public let axOnly: [CGWindowID] + public let serverOnly: [CGWindowID] + + init(pid: pid_t, axWindowIDs: [CGWindowID], serverWindows: [WindowServer.Window]) { + let axIDs = Set(axWindowIDs) + let windows = serverWindows.filter { $0.pid == pid }.sorted { $0.number < $1.number } + let serverIDs = Set(windows.map(\.number)) + self.axWindowIDs = axIDs.sorted() + self.serverWindows = windows + self.axOnly = axIDs.subtracting(serverIDs).sorted() + self.serverOnly = serverIDs.subtracting(axIDs).sorted() + } +} + +/// A matching frame is evidence of a write, not proof: AX has no transaction IDs. +public enum AppThreadEventOrigin: Sendable, Equatable { + case unattributed + case possiblySelfGenerated(UUID) +} + +public enum AppThreadFailure: Error, Sendable, Equatable { + case stopped + case runLoopUnavailable + case initialization(String) + case observerCreation(Int32) + case observerRegistration(notification: String, windowID: CGWindowID?, code: Int32) + case observerRemoval(notification: String, windowID: CGWindowID, code: Int32) + case windowEnumeration(String) + case windowServer(String) + case windowIdentification(String) + case windowFrame(String) + case windowNotFound(CGWindowID) +} + +/// Owns one application's AX objects and observer on a dedicated run-loop thread. +public final class AppThread: Sendable { + public let events: AsyncStream + private let worker: AppThreadWorker + private let executor: AppThreadExecutor + + public init(pid: pid_t, timeout: Float = 0.35, timeoutThreshold: Int = 3) { + precondition(timeout > 0 && timeout.isFinite) + precondition(timeoutThreshold > 0) + let (events, continuation) = AsyncStream.makeStream() + self.events = events + let worker = AppThreadWorker( + pid: pid, timeout: timeout, timeoutThreshold: timeoutThreshold, events: continuation) + self.worker = worker + self.executor = AppThreadExecutor( + start: { worker.start() }, + stop: { worker.stop() }, + failure: { worker.executorFailed() } + ) + } + + /// The closure runs on the owning thread. Neither it nor its result may transfer AX objects. + /// A successful closure is treated as a responsive AX operation, even if it made no AX calls. + public func perform( + _ operation: @escaping @Sendable (AXElement) throws -> Value + ) async throws -> Value { + let worker = self.worker + return try await withCheckedThrowingContinuation { continuation in + executor.submit( + run: { worker.perform(operation, continuation: continuation) }, + cancel: { continuation.resume(throwing: AppThreadFailure.stopped) } + ) + } + } + + /// Tags matching move/resize notifications conservatively; callers must not treat a tag as proof. + /// Pass a write ID to correlate candidate notifications with this request. + public func writeFrame(windowID: CGWindowID, target: CGRect, writeID: UUID = UUID()) async throws -> CGRect { + let assistiveTechnology = await MainActor.run { AssistiveTechnology.current } + let worker = self.worker + return try await withCheckedThrowingContinuation { continuation in + executor.submit( + run: { + worker.writeFrame( + windowID: windowID, target: target, writeID: writeID, assistiveTechnology: assistiveTechnology, + continuation: continuation) + }, + cancel: { continuation.resume(throwing: AppThreadFailure.stopped) } + ) + } + } + + /// Requests shutdown without waiting for an in-flight AX call to return. + public func shutdown() { + executor.shutdown() + } + + deinit { + executor.shutdown() + } +} + +// This object is accessed only by its executor's thread, including observer callbacks. +private final class AppThreadWorker: @unchecked Sendable { + private let pid: pid_t + private let timeout: Float + private let events: AsyncStream.Continuation + private var timeouts: AppThreadTimeoutTracker + private var application: AXElement? + private var startupFailure: AppThreadFailure? + private var observer: AXObserver? + private var reconciliationTimer: CFRunLoopTimer? + private var windows: [(raw: AXUIElement, id: CGWindowID)] = [] + private var frameWrites = AppThreadFrameWriteTracker() + + init(pid: pid_t, timeout: Float, timeoutThreshold: Int, events: AsyncStream.Continuation) { + self.pid = pid + self.timeout = timeout + self.events = events + self.timeouts = AppThreadTimeoutTracker(threshold: timeoutThreshold) + } + + func start() { + do { + let application = try AXElement(applicationPID: pid, timeout: timeout) + self.application = application + var observer: AXObserver? + let result = AXObserverCreate( + pid, + { _, element, notification, context in + guard let context else { return } + let worker = Unmanaged.fromOpaque(context).takeUnretainedValue() + worker.receive(element: element, notification: notification as String) + }, &observer) + guard result == .success, let observer else { + let failure = AppThreadFailure.observerCreation(result.rawValue) + startupFailure = failure + events.yield(.failure(failure)) + return + } + self.observer = observer + CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer), .defaultMode) + for notification in Self.applicationNotifications { + register(notification, on: application.raw, windowID: nil) + } + do { + let initialWindows = try application.windows + recordSuccess() + for window in initialWindows { + observe(window) + } + } catch { + record(error) + events.yield(.failure(.windowEnumeration(String(describing: error)))) + } + guard + let timer = CFRunLoopTimerCreateWithHandler( + nil, CFAbsoluteTimeGetCurrent() + 10, 10, 0, 0, { [self] _ in reconcile() } + ) + else { + events.yield(.failure(.initialization("Unable to create reconciliation timer"))) + return + } + reconciliationTimer = timer + CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, .defaultMode) + } catch { + record(error) + let failure = AppThreadFailure.initialization(String(describing: error)) + startupFailure = failure + events.yield(.failure(failure)) + } + } + + func executorFailed() { + events.yield(.failure(.runLoopUnavailable)) + } + + func stop() { + if let reconciliationTimer { + CFRunLoopTimerInvalidate(reconciliationTimer) + } + reconciliationTimer = nil + if let observer { + CFRunLoopRemoveSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer), .defaultMode) + } + observer = nil + windows.removeAll() + application = nil + events.finish() + } + + private func reconcile() { + guard let application else { return } + do { + let current = try application.windows + recordSuccess() + var ids: [CGWindowID] = [] + for window in current { + ids.append(try window.windowID()) + recordSuccess() + observe(window) + } + let present = Set(ids) + let missing = windows.filter { !present.contains($0.id) } + windows.removeAll { !present.contains($0.id) } + for window in missing { + frameWrites.clear(windowID: window.id) + if let observer { + for notification in Self.windowNotifications { + let result = AXObserverRemoveNotification(observer, window.raw, notification as CFString) + if result != .success && result != .notificationNotRegistered { + events.yield( + .failure( + .observerRemoval( + notification: notification, windowID: window.id, code: result.rawValue))) + } + } + } + } + events.yield(.windowList(ids)) + events.yield( + AppThreadWindowReconciler.event(pid: pid, axWindowIDs: ids) { options in + try WindowServer().windows(options: options) + }) + } catch { + record(error) + events.yield(.failure(.windowEnumeration(String(describing: error)))) + } + } + + func perform( + _ operation: @Sendable (AXElement) throws -> Value, + continuation: CheckedContinuation + ) { + if let startupFailure { + continuation.resume(throwing: startupFailure) + return + } + guard let application else { + continuation.resume(throwing: AppThreadFailure.stopped) + return + } + do { + let result = try operation(application) + recordSuccess() + continuation.resume(returning: result) + } catch { + record(error) + continuation.resume(throwing: error) + } + } + + func writeFrame( + windowID: CGWindowID, target: CGRect, writeID: UUID, assistiveTechnology: AssistiveTechnology, + continuation: CheckedContinuation + ) { + frameWrites.clear(windowID: windowID) + if let startupFailure { + continuation.resume(throwing: startupFailure) + return + } + guard let application else { + continuation.resume(throwing: AppThreadFailure.stopped) + return + } + do { + var found: AXElement? + for window in try application.windows { + if try window.windowID() == windowID { + found = window + break + } + } + guard let window = found else { throw AppThreadFailure.windowNotFound(windowID) } + observe(window) + let before = try window.frame + let actual = try window.writeFrame( + target, application: application, assistiveTechnology: assistiveTechnology) + frameWrites.record(windowID: windowID, writeID: writeID, before: before, actual: actual) + recordSuccess() + continuation.resume(returning: actual) + } catch { + record(error) + continuation.resume(throwing: error) + } + } + + private static let applicationNotifications = [ + kAXWindowCreatedNotification, + kAXFocusedWindowChangedNotification, + kAXApplicationActivatedNotification, + kAXApplicationDeactivatedNotification, + ] + private static let windowNotifications = [ + kAXUIElementDestroyedNotification, + kAXWindowMovedNotification, + kAXWindowResizedNotification, + kAXTitleChangedNotification, + kAXWindowMiniaturizedNotification, + kAXWindowDeminiaturizedNotification, + ] + + private func register(_ notification: String, on element: AXUIElement, windowID: CGWindowID?) { + guard let observer else { return } + let start = DispatchTime.now().uptimeNanoseconds + let result = AXObserverAddNotification( + observer, element, notification as CFString, Unmanaged.passUnretained(self).toOpaque()) + let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000 + if result == .success { + recordSuccess() + } else { + if result == .cannotComplete && elapsed >= Double(timeout) * 0.9 { + if timeouts.timedOut() { events.yield(.unresponsive) } + } else { + timeouts.otherFailure() + } + events.yield( + .failure(.observerRegistration(notification: notification, windowID: windowID, code: result.rawValue))) + } + } + + private func observe(_ window: AXElement) { + guard !windows.contains(where: { CFEqual($0.raw, window.raw) }) else { return } + do { + let id = try window.windowID() + recordSuccess() + windows.append((window.raw, id)) + for notification in Self.windowNotifications { + register(notification, on: window.raw, windowID: id) + } + } catch { + record(error) + events.yield(.failure(.windowIdentification(String(describing: error)))) + } + } + + private func receive(element: AXUIElement, notification: String) { + switch notification { + case kAXWindowCreatedNotification: + do { + let window = try AXElement(raw: element, timeout: timeout) + observe(window) + if let id = windows.first(where: { CFEqual($0.raw, element) })?.id { + events.yield(.windowCreated(id)) + } + } catch { + record(error) + events.yield(.failure(.windowIdentification(String(describing: error)))) + } + case kAXFocusedWindowChangedNotification: + events.yield(.focusedWindowChanged) + case kAXApplicationActivatedNotification: + events.yield(.applicationActivated) + case kAXApplicationDeactivatedNotification: + events.yield(.applicationDeactivated) + default: + guard let index = windows.firstIndex(where: { CFEqual($0.raw, element) }) else { + events.yield(.failure(.windowIdentification("Notification for an unobserved window: \(notification)"))) + return + } + let id = windows[index].id + switch notification { + case kAXUIElementDestroyedNotification: + windows.remove(at: index) + frameWrites.clear(windowID: id) + events.yield(.windowDestroyed(id)) + case kAXWindowMovedNotification: + events.yield(.windowMoved(id, origin: frameOrigin(windowID: id, raw: element, axis: .position))) + case kAXWindowResizedNotification: + events.yield(.windowResized(id, origin: frameOrigin(windowID: id, raw: element, axis: .size))) + case kAXTitleChangedNotification: events.yield(.windowTitleChanged(id)) + case kAXWindowMiniaturizedNotification: events.yield(.windowMinimized(id)) + case kAXWindowDeminiaturizedNotification: events.yield(.windowDeminimized(id)) + default: break + } + } + } + + private func frameOrigin(windowID: CGWindowID, raw: AXUIElement, axis: AppThreadFrameWriteTracker.Axis) + -> AppThreadEventOrigin + { + guard frameWrites.hasCandidate(windowID: windowID, axis: axis) else { return .unattributed } + do { + let frame = try AXElement(raw: raw, timeout: timeout).frame + recordSuccess() + return frameWrites.match(windowID: windowID, axis: axis, frame: frame) + } catch { + frameWrites.clear(windowID: windowID) + record(error) + events.yield(.failure(.windowFrame(String(describing: error)))) + return .unattributed + } + } + + private func record(_ error: any Error) { + let timedOut: Bool + if let axError = error as? AXPlatformError, case .timedOut = axError { + timedOut = true + } else if let frameError = error as? FrameWriteFailure { + timedOut = Self.isTimeout(frameError.writeError) || Self.isTimeout(frameError.restoreError) + } else { + timedOut = false + } + if timedOut { + if timeouts.timedOut() { events.yield(.unresponsive) } + } else { + timeouts.otherFailure() + } + } + + private static func isTimeout(_ error: any Error) -> Bool { + guard let error = error as? AXPlatformError, case .timedOut = error else { return false } + return true + } + + private func recordSuccess() { + if timeouts.succeeded() { events.yield(.responsive) } + } +} + +enum AppThreadWindowReconciler { + static func event( + pid: pid_t, axWindowIDs: [CGWindowID], read: (CGWindowListOption) throws -> [WindowServer.Window] + ) -> AppThreadEvent { + do { + return .reconciliation( + AppThreadReconciliation(pid: pid, axWindowIDs: axWindowIDs, serverWindows: try read(.optionAll))) + } catch { + return .failure(.windowServer(String(describing: error))) + } + } +} + +struct AppThreadFrameWriteTracker { + enum Axis { case position, size } + static let maximumAgeNanoseconds: UInt64 = 500_000_000 + private struct Candidate { + let id: UUID + let frame: CGRect + let createdAt: UInt64 + var position: Bool + var size: Bool + } + private var candidates: [CGWindowID: Candidate] = [:] + + mutating func record( + windowID: CGWindowID, writeID: UUID, before: CGRect, actual: CGRect, + now: UInt64 = DispatchTime.now().uptimeNanoseconds + ) { + let position = before.origin != actual.origin + let size = before.size != actual.size + candidates[windowID] = + position || size + ? Candidate(id: writeID, frame: actual, createdAt: now, position: position, size: size) : nil + } + + mutating func clear(windowID: CGWindowID) { + candidates.removeValue(forKey: windowID) + } + + mutating func hasCandidate( + windowID: CGWindowID, axis: Axis, now: UInt64 = DispatchTime.now().uptimeNanoseconds + ) -> Bool { + guard let candidate = candidates[windowID] else { return false } + guard now >= candidate.createdAt && now - candidate.createdAt < Self.maximumAgeNanoseconds else { + clear(windowID: windowID) + return false + } + switch axis { + case .position: return candidate.position + case .size: return candidate.size + } + } + + mutating func match( + windowID: CGWindowID, axis: Axis, frame: CGRect, now: UInt64 = DispatchTime.now().uptimeNanoseconds + ) -> AppThreadEventOrigin { + guard hasCandidate(windowID: windowID, axis: axis, now: now), let candidateValue = candidates[windowID] else { + return .unattributed + } + var candidate = candidateValue + guard candidate.frame == frame else { + clear(windowID: windowID) + return .unattributed + } + switch axis { + case .position: candidate.position = false + case .size: candidate.size = false + } + candidates[windowID] = candidate.position || candidate.size ? candidate : nil + return .possiblySelfGenerated(candidate.id) + } +} + +struct AppThreadTimeoutTracker { + private let threshold: Int + private var count = 0 + private var wedged = false + + init(threshold: Int) { + precondition(threshold > 0) + self.threshold = threshold + } + + mutating func timedOut() -> Bool { + if count < threshold { count += 1 } + guard count == threshold && !wedged else { return false } + wedged = true + return true + } + + mutating func succeeded() -> Bool { + count = 0 + let wasWedged = wedged + wedged = false + return wasWedged + } + + mutating func otherFailure() { + count = 0 + } +} + +// The lock protects the queue and run-loop handles; jobs themselves only run on the owner thread. +final class AppThreadExecutor: @unchecked Sendable { + private struct Job: Sendable { + let run: @Sendable () -> Void + let cancel: @Sendable () -> Void + } + private let lock = NSLock() + private var jobs: [Job] = [] + private var stopping = false + private var runLoop: CFRunLoop? + private var source: CFRunLoopSource? + private let start: @Sendable () -> Void + private let stop: @Sendable () -> Void + private let failure: @Sendable () -> Void + + init( + start: @escaping @Sendable () -> Void, stop: @escaping @Sendable () -> Void, + failure: @escaping @Sendable () -> Void = {} + ) { + self.start = start + self.stop = stop + self.failure = failure + Thread { [self] in threadMain() }.start() + } + + func submit(run: @escaping @Sendable () -> Void, cancel: @escaping @Sendable () -> Void) { + lock.lock() + guard !stopping else { + lock.unlock() + cancel() + return + } + jobs.append(Job(run: run, cancel: cancel)) + signalLocked() + lock.unlock() + } + + func shutdown() { + lock.lock() + guard !stopping else { + lock.unlock() + return + } + stopping = true + let cancelled = jobs + jobs.removeAll() + signalLocked() + lock.unlock() + for job in cancelled { job.cancel() } + } + + private func signalLocked() { + if let source { CFRunLoopSourceSignal(source) } + if let runLoop { CFRunLoopWakeUp(runLoop) } + } + + private func threadMain() { + guard let runLoop = CFRunLoopGetCurrent() else { + failure() + shutdown() + stop() + return + } + var context = CFRunLoopSourceContext( + version: 0, info: Unmanaged.passUnretained(self).toOpaque(), + retain: nil, release: nil, copyDescription: nil, equal: nil, hash: nil, + schedule: nil, cancel: nil, + perform: { info in + guard let info else { return } + Unmanaged.fromOpaque(info).takeUnretainedValue().drain() + } + ) + guard let source = CFRunLoopSourceCreate(nil, 0, &context) else { + failure() + shutdown() + stop() + return + } + CFRunLoopAddSource(runLoop, source, .defaultMode) + lock.lock() + self.runLoop = runLoop + self.source = source + signalLocked() + lock.unlock() + start() + CFRunLoopRun() + lock.lock() + let unexpectedExit = !stopping + lock.unlock() + if unexpectedExit { failure() } + shutdown() + stop() + CFRunLoopRemoveSource(runLoop, source, .defaultMode) + lock.lock() + self.source = nil + self.runLoop = nil + lock.unlock() + } + + private func drain() { + lock.lock() + if stopping { + lock.unlock() + CFRunLoopStop(CFRunLoopGetCurrent()) + return + } + guard !jobs.isEmpty else { + lock.unlock() + return + } + let job = jobs.removeFirst() + if !jobs.isEmpty { signalLocked() } + lock.unlock() + job.run() + } +} diff --git a/Tests/TesseraPlatformTests/AppThreadTests.swift b/Tests/TesseraPlatformTests/AppThreadTests.swift new file mode 100644 index 00000000..a5a8676e --- /dev/null +++ b/Tests/TesseraPlatformTests/AppThreadTests.swift @@ -0,0 +1,223 @@ +import CoreFoundation +import CoreGraphics +import Darwin +import Foundation +import Testing + +@testable import TesseraPlatform + +@Test func reconciliationComparesAllWindowsForOnlyTheRequestedApplication() { + let bounds = CGRect(x: 20, y: 30, width: 400, height: 300) + let windows = [ + WindowServer.Window(number: 3, pid: 42, bounds: .zero, layer: 1, isOnscreen: false), + WindowServer.Window(number: 5, pid: 99, bounds: .zero, layer: 0, isOnscreen: true), + WindowServer.Window(number: 1, pid: 42, bounds: bounds, layer: 0, isOnscreen: true), + ] + var requestedOptions: CGWindowListOption? + let event = AppThreadWindowReconciler.event(pid: 42, axWindowIDs: [2, 1, 2]) { options in + requestedOptions = options + return windows + } + #expect(requestedOptions == .optionAll) + guard case .reconciliation(let summary) = event else { + Issue.record("Expected a reconciliation summary") + return + } + #expect(summary.axWindowIDs == [1, 2]) + #expect(summary.serverWindows.map(\.number) == [1, 3]) + #expect(summary.serverWindows[0].bounds == bounds) + #expect(summary.serverWindows[1].isOnscreen == false) + #expect(summary.axOnly == [2]) + #expect(summary.serverOnly == [3]) +} + +@Test func reconciliationSurfacesWindowServerFailures() { + let event = AppThreadWindowReconciler.event(pid: 42, axWindowIDs: [1]) { _ in + throw WindowServer.ReadError.windowListUnavailable + } + #expect(event == .failure(.windowServer(WindowServer.ReadError.windowListUnavailable.description))) +} + +@Test func timeoutTrackerSignalsTransitionsOnce() { + var tracker = AppThreadTimeoutTracker(threshold: 3) + #expect(tracker.timedOut() == false) + #expect(tracker.timedOut() == false) + #expect(tracker.timedOut() == true) + #expect(tracker.timedOut() == false) + #expect(tracker.succeeded() == true) + #expect(tracker.succeeded() == false) + #expect(tracker.timedOut() == false) + #expect(tracker.timedOut() == false) + #expect(tracker.timedOut() == true) +} + +@Test func unrelatedFailureBreaksTimeoutStreakButDoesNotClaimRecovery() { + var tracker = AppThreadTimeoutTracker(threshold: 2) + #expect(tracker.timedOut() == false) + tracker.otherFailure() + #expect(tracker.timedOut() == false) + #expect(tracker.timedOut() == true) + tracker.otherFailure() + #expect(tracker.timedOut() == false) + #expect(tracker.timedOut() == false) + #expect(tracker.succeeded() == true) +} + +@Test func frameWriteCandidatesAreWindowSpecificAndConsumedPerAxis() { + var tracker = AppThreadFrameWriteTracker() + let id = UUID() + let before = CGRect(x: 0, y: 0, width: 100, height: 100) + let actual = CGRect(x: 10, y: 20, width: 120, height: 130) + tracker.record(windowID: 1, writeID: id, before: before, actual: actual) + #expect(tracker.match(windowID: 2, axis: .position, frame: actual) == .unattributed) + #expect(tracker.match(windowID: 1, axis: .position, frame: actual) == .possiblySelfGenerated(id)) + #expect(tracker.match(windowID: 1, axis: .position, frame: actual) == .unattributed) + #expect(tracker.match(windowID: 1, axis: .size, frame: actual) == .possiblySelfGenerated(id)) + #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) +} + +@Test func mismatchedAndSupersededFrameCandidatesAreNotTagged() { + var tracker = AppThreadFrameWriteTracker() + let before = CGRect(x: 0, y: 0, width: 100, height: 100) + let actual = CGRect(x: 10, y: 20, width: 120, height: 130) + let other = CGRect(x: 15, y: 20, width: 120, height: 130) + let first = UUID() + let second = UUID() + tracker.record(windowID: 1, writeID: first, before: before, actual: actual) + #expect(tracker.match(windowID: 1, axis: .position, frame: other) == .unattributed) + #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) + tracker.record(windowID: 1, writeID: first, before: before, actual: actual) + tracker.record(windowID: 1, writeID: second, before: actual, actual: other) + #expect(tracker.match(windowID: 1, axis: .position, frame: other) == .possiblySelfGenerated(second)) + tracker.record(windowID: 1, writeID: first, before: actual, actual: actual) + #expect(tracker.hasCandidate(windowID: 1, axis: .position) == false) + tracker.record(windowID: 1, writeID: first, before: before, actual: actual) + tracker.clear(windowID: 1) + #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) +} + +@Test func frameWriteCandidatesExpireAtBoundedDeadline() { + var tracker = AppThreadFrameWriteTracker() + let before = CGRect(x: 0, y: 0, width: 100, height: 100) + let actual = CGRect(x: 10, y: 20, width: 120, height: 130) + let id = UUID() + let limit = AppThreadFrameWriteTracker.maximumAgeNanoseconds + tracker.record(windowID: 1, writeID: id, before: before, actual: actual, now: 100) + #expect( + tracker.match(windowID: 1, axis: .position, frame: actual, now: 100 + limit - 1) == .possiblySelfGenerated(id)) + #expect(tracker.match(windowID: 1, axis: .size, frame: actual, now: 100 + limit) == .unattributed) + #expect(tracker.hasCandidate(windowID: 1, axis: .size, now: 100 + limit) == false) +} + +private func execute( + _ executor: AppThreadExecutor, + _ operation: @escaping @Sendable () -> Value +) async throws -> Value { + try await withCheckedThrowingContinuation { continuation in + executor.submit( + run: { continuation.resume(returning: operation()) }, + cancel: { continuation.resume(throwing: AppThreadFailure.stopped) } + ) + } +} + +@Test func executorsHaveStableIndependentOwnerThreads() async throws { + let first = AppThreadExecutor(start: {}, stop: {}) + let second = AppThreadExecutor(start: {}, stop: {}) + defer { + first.shutdown() + second.shutdown() + } + let firstID = try await execute(first) { pthread_mach_thread_np(pthread_self()) } + let secondID = try await execute(second) { pthread_mach_thread_np(pthread_self()) } + let again = try await execute(first) { pthread_mach_thread_np(pthread_self()) } + #expect(firstID == again) + #expect(firstID != secondID) +} + +@Test func shutdownCancelsQueuedJobsAndFinishesAfterInFlightJob() async throws { + let (started, startedContinuation) = AsyncStream.makeStream() + let (stopped, stoppedContinuation) = AsyncStream.makeStream() + let gate = DispatchSemaphore(value: 0) + let executor = AppThreadExecutor(start: {}, stop: { stoppedContinuation.yield(()) }) + executor.submit( + run: { + startedContinuation.yield(()) + gate.wait() + }, + cancel: { startedContinuation.finish() } + ) + var starts = started.makeAsyncIterator() + #expect(await starts.next() != nil) + let (cancelled, cancelledContinuation) = AsyncStream.makeStream() + executor.submit( + run: { cancelledContinuation.yield(false) }, + cancel: { cancelledContinuation.yield(true) } + ) + executor.shutdown() + executor.shutdown() + var cancellations = cancelled.makeAsyncIterator() + #expect(await cancellations.next() == true) + gate.signal() + var stops = stopped.makeAsyncIterator() + #expect(await stops.next() != nil) + await #expect(throws: AppThreadFailure.stopped) { + try await execute(executor) { 1 } + } +} + +@Test func unexpectedRunLoopExitCancelsPendingWork() async { + let (started, startedContinuation) = AsyncStream.makeStream() + let (stopped, stoppedContinuation) = AsyncStream.makeStream() + let (failed, failedContinuation) = AsyncStream.makeStream() + let gate = DispatchSemaphore(value: 0) + let executor = AppThreadExecutor( + start: { + startedContinuation.yield(()) + gate.wait() + }, + stop: { stoppedContinuation.yield(()) }, + failure: { failedContinuation.yield(()) } + ) + var starts = started.makeAsyncIterator() + #expect(await starts.next() != nil) + executor.submit(run: { CFRunLoopStop(CFRunLoopGetCurrent()) }, cancel: {}) + let (cancelled, cancelledContinuation) = AsyncStream.makeStream() + executor.submit( + run: { cancelledContinuation.yield(false) }, + cancel: { cancelledContinuation.yield(true) } + ) + gate.signal() + var cancellations = cancelled.makeAsyncIterator() + #expect(await cancellations.next() == true) + var failures = failed.makeAsyncIterator() + #expect(await failures.next() != nil) + var stops = stopped.makeAsyncIterator() + #expect(await stops.next() != nil) +} + +@Test func shutdownBeforeStartupCompletesCancelsPendingWork() async { + let (started, startedContinuation) = AsyncStream.makeStream() + let (stopped, stoppedContinuation) = AsyncStream.makeStream() + let gate = DispatchSemaphore(value: 0) + let executor = AppThreadExecutor( + start: { + startedContinuation.yield(()) + gate.wait() + }, + stop: { stoppedContinuation.yield(()) } + ) + var starts = started.makeAsyncIterator() + #expect(await starts.next() != nil) + let (cancelled, cancelledContinuation) = AsyncStream.makeStream() + executor.submit( + run: { cancelledContinuation.yield(false) }, + cancel: { cancelledContinuation.yield(true) } + ) + executor.shutdown() + var cancellations = cancelled.makeAsyncIterator() + #expect(await cancellations.next() == true) + gate.signal() + var stops = stopped.makeAsyncIterator() + #expect(await stops.next() != nil) +} -- knotmirror 0.0.1 From 6bef09f54d345130434e2daffea38a2e94079e77 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:40:57 -0400 Subject: [PATCH 10/44] Test frame write safeguards --- Sources/TesseraPlatform/FrameWrites.swift | 83 +++++++++++------- .../TesseraPlatformTests/AXElementTests.swift | 87 +++++++++++++++++++ 2 files changed, 139 insertions(+), 31 deletions(-) diff --git a/Sources/TesseraPlatform/FrameWrites.swift b/Sources/TesseraPlatform/FrameWrites.swift index 16835b35..b387b835 100644 --- a/Sources/TesseraPlatform/FrameWrites.swift +++ b/Sources/TesseraPlatform/FrameWrites.swift @@ -37,42 +37,63 @@ public struct FrameWriteFailure: Error, Sendable { public let restoreError: any Error } -extension AXElement { - func writeFrame(_ target: CGRect, application: AXElement, assistiveTechnology: AssistiveTechnology) throws -> CGRect - { - let plan = FrameWritePlan(current: try frame, target: target) - guard !plan.steps.isEmpty else { return target } +protocol FrameWriteAccess { + var frame: CGRect { get throws } + var size: CGSize { get throws } + var position: CGPoint { get throws } + var enhancedUI: Bool { get throws } + func setSize(_ value: CGSize) throws + func setPosition(_ value: CGPoint) throws + func setEnhancedUI(_ value: Bool) throws +} - var restoreEnhancedUI = false - if !assistiveTechnology.voiceOver && !assistiveTechnology.switchControl { - do { - if try application.enhancedUI { - try application.setEnhancedUI(false) - restoreEnhancedUI = true - } - } catch AXPlatformError.attributeUnsupported { - // An absent attribute cannot cause enhanced UI animation. - } - } +extension AXElement: FrameWriteAccess {} + +func executeFrameWrite( + _ target: CGRect, window: Window, application: Application, assistiveTechnology: AssistiveTechnology +) throws -> CGRect { + let plan = FrameWritePlan(current: try window.frame, target: target) + guard !plan.steps.isEmpty else { return target } + var restoreEnhancedUI = false + if !assistiveTechnology.voiceOver && !assistiveTechnology.switchControl { + let enhancedUI: Bool do { - for step in plan.steps { - switch step { - case .size(let desired): - if try size != desired { try setSize(desired) } - case .position(let desired): - if try position != desired { try setPosition(desired) } - } + enhancedUI = try application.enhancedUI + } catch AXPlatformError.attributeUnsupported { + // An absent attribute cannot cause enhanced UI animation. + enhancedUI = false + } + if enhancedUI { + try application.setEnhancedUI(false) + restoreEnhancedUI = true + } + } + + do { + for step in plan.steps { + switch step { + case .size(let desired): + if try window.size != desired { try window.setSize(desired) } + case .position(let desired): + if try window.position != desired { try window.setPosition(desired) } } - } catch { - if restoreEnhancedUI { - do { try application.setEnhancedUI(true) } catch let restoreError { - throw FrameWriteFailure(writeError: error, restoreError: restoreError) - } + } + } catch { + if restoreEnhancedUI { + do { try application.setEnhancedUI(true) } catch let restoreError { + throw FrameWriteFailure(writeError: error, restoreError: restoreError) } - throw error } - if restoreEnhancedUI { try application.setEnhancedUI(true) } - return try frame + throw error + } + if restoreEnhancedUI { try application.setEnhancedUI(true) } + return try window.frame +} + +extension AXElement { + func writeFrame(_ target: CGRect, application: AXElement, assistiveTechnology: AssistiveTechnology) throws -> CGRect + { + try executeFrameWrite(target, window: self, application: application, assistiveTechnology: assistiveTechnology) } } diff --git a/Tests/TesseraPlatformTests/AXElementTests.swift b/Tests/TesseraPlatformTests/AXElementTests.swift index 0864c2b6..db7b0433 100644 --- a/Tests/TesseraPlatformTests/AXElementTests.swift +++ b/Tests/TesseraPlatformTests/AXElementTests.swift @@ -52,3 +52,90 @@ func mapsAccessibilityErrors(error: AXError, expected: AXPlatformError) { let new = CGRect(x: 10, y: 20, width: 400, height: 400) #expect(FrameWritePlan(current: old, target: new).steps == [.size(new.size), .size(new.size)]) } + +private final class FrameWriteProbe: FrameWriteAccess { + var rectangle = CGRect(x: 10, y: 20, width: 300, height: 200) + var enabled = true + var actions: [String] = [] + var failDisable = false + var failPosition = false + var failRestore = false + var positionResetsSize = false + + var frame: CGRect { get throws { rectangle } } + var size: CGSize { get throws { rectangle.size } } + var position: CGPoint { get throws { rectangle.origin } } + var enhancedUI: Bool { get throws { enabled } } + + func setSize(_ value: CGSize) throws { + actions.append("size") + rectangle.size = value + } + func setPosition(_ value: CGPoint) throws { + actions.append("position") + if failPosition { throw AXPlatformError.notPermitted } + rectangle.origin = value + if positionResetsSize { rectangle.size = CGSize(width: 300, height: 200) } + } + func setEnhancedUI(_ value: Bool) throws { + actions.append(value ? "enable" : "disable") + if !value && failDisable { throw AXPlatformError.attributeUnsupported } + if value && failRestore { throw AXPlatformError.elementInvalid } + enabled = value + } +} + +@Test func frameWriteRestoresEnhancedUIAndRechecksSize() throws { + let probe = FrameWriteProbe() + probe.positionResetsSize = true + let target = CGRect(x: 30, y: 40, width: 500, height: 400) + let actual = try executeFrameWrite( + target, window: probe, application: probe, + assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false) + ) + #expect(actual == target) + #expect(probe.actions == ["disable", "size", "position", "size", "enable"]) +} + +@Test(arguments: [ + AssistiveTechnology(voiceOver: true, switchControl: false), + AssistiveTechnology(voiceOver: false, switchControl: true), +]) +func frameWriteKeepsEnhancedUIForAssistiveTechnology(assistive: AssistiveTechnology) throws { + let probe = FrameWriteProbe() + let target = CGRect(x: 30, y: 20, width: 300, height: 200) + _ = try executeFrameWrite(target, window: probe, application: probe, assistiveTechnology: assistive) + #expect(probe.actions == ["position"]) + #expect(probe.enabled) +} + +@Test func frameWriteDoesNotHideFailureToDisableEnhancedUI() { + let probe = FrameWriteProbe() + probe.failDisable = true + #expect(throws: AXPlatformError.attributeUnsupported) { + try executeFrameWrite( + CGRect(x: 30, y: 20, width: 300, height: 200), window: probe, application: probe, + assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false) + ) + } + #expect(probe.actions == ["disable"]) +} + +@Test func frameWriteReportsBothWriteAndRestoreFailures() { + let probe = FrameWriteProbe() + probe.failPosition = true + probe.failRestore = true + do { + _ = try executeFrameWrite( + CGRect(x: 30, y: 20, width: 300, height: 200), window: probe, application: probe, + assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false) + ) + Issue.record("Expected frame write failure") + } catch let failure as FrameWriteFailure { + #expect(failure.writeError as? AXPlatformError == .notPermitted) + #expect(failure.restoreError as? AXPlatformError == .elementInvalid) + } catch { + Issue.record("Unexpected failure: \(error)") + } + #expect(probe.actions == ["disable", "position", "enable"]) +} -- knotmirror 0.0.1 From 5e58a7ce57d2b8fce6b3a73acbf1123c563e3fbb Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:42:35 -0400 Subject: [PATCH 11/44] Clarify AX timeout detection --- Sources/TesseraPlatform/AXElement.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Sources/TesseraPlatform/AXElement.swift b/Sources/TesseraPlatform/AXElement.swift index ff693824..d7fae7e1 100644 --- a/Sources/TesseraPlatform/AXElement.swift +++ b/Sources/TesseraPlatform/AXElement.swift @@ -46,6 +46,7 @@ public struct AXElement { } static func checkCall(_ error: AXError, elapsed: Double, timeout: Float) throws { + // AX uses the same error for timeouts and immediate messaging failures. if error == .cannotComplete && elapsed >= Double(timeout) * 0.9 { throw AXPlatformError.timedOut } -- knotmirror 0.0.1 From a21f376e2194446a6ce80522062ceef09eb83055 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:43:08 -0400 Subject: [PATCH 12/44] Format platform test --- Tests/TesseraPlatformTests/TesseraPlatformTests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Tests/TesseraPlatformTests/TesseraPlatformTests.swift b/Tests/TesseraPlatformTests/TesseraPlatformTests.swift index 0075eed6..d20b35de 100644 --- a/Tests/TesseraPlatformTests/TesseraPlatformTests.swift +++ b/Tests/TesseraPlatformTests/TesseraPlatformTests.swift @@ -1,4 +1,5 @@ import Testing + @testable import TesseraPlatform @Test func builds() {} -- knotmirror 0.0.1 From c975edfc37eeab32cd656a40e61c7b4bc6673137 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:43:27 -0400 Subject: [PATCH 13/44] Add validated config defaults and hot reload --- Sources/TesseraConfig/ConfigCommand.swift | 68 ++ Sources/TesseraConfig/ConfigFileWatcher.swift | 88 ++ Sources/TesseraConfig/ConfigJSONSchema.swift | 194 +++++ Sources/TesseraConfig/ConfigStore.swift | 254 ++++++ Sources/TesseraConfig/ConfigValidator.swift | 520 +++++++++++ Sources/TesseraConfig/Configuration.swift | 160 ++++ Sources/TesseraConfig/KeyChord.swift | 337 ++++++++ .../Resources/Keybindings.xcstrings | 83 ++ .../TesseraConfig/Resources/Parser.xcstrings | 360 +++++++- .../TesseraConfig/Resources/Schema.xcstrings | 98 +++ .../TesseraConfig/Resources/Store.xcstrings | 116 +++ .../Resources/en.lproj/Keybindings.strings | 20 + .../Resources/en.lproj/Parser.strings | 66 ++ .../Resources/en.lproj/Schema.strings | 62 ++ .../Resources/en.lproj/Store.strings | 26 + Sources/TesseraConfig/TOMLDocument.swift | 19 +- Sources/TesseraConfig/TOMLParser.swift | 7 + .../TesseraConfig.docc/TesseraConfig.md | 77 ++ .../ConfigResourceTests.swift | 41 + .../TesseraConfigTests/ConfigStoreTests.swift | 544 ++++++++++++ .../ConfigValidationTests.swift | 813 ++++++++++++++++++ Tests/TesseraConfigTests/KeyChordTests.swift | 275 ++++++ .../TOMLDocumentTests.swift | 7 + .../TesseraConfigTests/TOMLParserTests.swift | 33 + 24 files changed, 4232 insertions(+), 36 deletions(-) create mode 100644 Sources/TesseraConfig/ConfigCommand.swift create mode 100644 Sources/TesseraConfig/ConfigFileWatcher.swift create mode 100644 Sources/TesseraConfig/ConfigJSONSchema.swift create mode 100644 Sources/TesseraConfig/ConfigStore.swift create mode 100644 Sources/TesseraConfig/ConfigValidator.swift create mode 100644 Sources/TesseraConfig/Configuration.swift create mode 100644 Sources/TesseraConfig/KeyChord.swift create mode 100644 Sources/TesseraConfig/Resources/Keybindings.xcstrings create mode 100644 Sources/TesseraConfig/Resources/Schema.xcstrings create mode 100644 Sources/TesseraConfig/Resources/Store.xcstrings create mode 100644 Sources/TesseraConfig/Resources/en.lproj/Keybindings.strings create mode 100644 Sources/TesseraConfig/Resources/en.lproj/Parser.strings create mode 100644 Sources/TesseraConfig/Resources/en.lproj/Schema.strings create mode 100644 Sources/TesseraConfig/Resources/en.lproj/Store.strings create mode 100644 Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md create mode 100644 Tests/TesseraConfigTests/ConfigResourceTests.swift create mode 100644 Tests/TesseraConfigTests/ConfigStoreTests.swift create mode 100644 Tests/TesseraConfigTests/ConfigValidationTests.swift create mode 100644 Tests/TesseraConfigTests/KeyChordTests.swift diff --git a/Sources/TesseraConfig/ConfigCommand.swift b/Sources/TesseraConfig/ConfigCommand.swift new file mode 100644 index 00000000..1a9b73f1 --- /dev/null +++ b/Sources/TesseraConfig/ConfigCommand.swift @@ -0,0 +1,68 @@ +public enum ConfigCommand: String, CaseIterable, Sendable { + case focusLeft = "focus-left" + case focusRight = "focus-right" + case focusUp = "focus-up" + case focusDown = "focus-down" + case swapLeft = "swap-left" + case swapRight = "swap-right" + case swapUp = "swap-up" + case swapDown = "swap-down" + case moveLeft = "move-left" + case moveRight = "move-right" + case moveUp = "move-up" + case moveDown = "move-down" + case layoutGrid = "layout-grid" + case layoutColumns = "layout-columns" + case layoutRows = "layout-rows" + case layoutSide = "layout-side" + case ratioIncrease = "ratio-increase" + case ratioDecrease = "ratio-decrease" + case floatToggle = "float-toggle" + case retile + case stack + case stackNext = "stack-next" + case stackPrevious = "stack-previous" + case displayMoveLeft = "display-move-left" + case displayMoveRight = "display-move-right" + case displayMoveUp = "display-move-up" + case displayMoveDown = "display-move-down" + case openSettings = "open-settings" +} + +public enum DefaultKeybindings { + public static func bindings(prefix: KeyModifiers = [.ctrl, .alt]) -> [ConfigCommand: KeyChord] { + defaults.mapValues { KeyChord(modifiers: prefix.union($0.modifiers), key: $0.key) } + } + + // Distinct physical keys prevent collisions even when the prefix already includes every modifier. + private static let defaults: [ConfigCommand: KeyChord] = [ + .focusLeft: KeyChord(key: .left), + .focusRight: KeyChord(key: .right), + .focusUp: KeyChord(key: .up), + .focusDown: KeyChord(key: .down), + .swapLeft: KeyChord(modifiers: .shift, key: .h), + .swapRight: KeyChord(modifiers: .shift, key: .l), + .swapUp: KeyChord(modifiers: .shift, key: .k), + .swapDown: KeyChord(modifiers: .shift, key: .j), + .moveLeft: KeyChord(modifiers: .shift, key: .a), + .moveRight: KeyChord(modifiers: .shift, key: .d), + .moveUp: KeyChord(modifiers: .shift, key: .w), + .moveDown: KeyChord(modifiers: .shift, key: .s), + .layoutGrid: KeyChord(key: .g), + .layoutColumns: KeyChord(key: .c), + .layoutRows: KeyChord(key: .r), + .layoutSide: KeyChord(key: .e), + .ratioIncrease: KeyChord(key: .equal), + .ratioDecrease: KeyChord(key: .minus), + .floatToggle: KeyChord(key: .f), + .retile: KeyChord(key: .return), + .stack: KeyChord(key: .space), + .stackNext: KeyChord(key: .rightBracket), + .stackPrevious: KeyChord(key: .leftBracket), + .displayMoveLeft: KeyChord(modifiers: .cmd, key: .f1), + .displayMoveRight: KeyChord(modifiers: .cmd, key: .f2), + .displayMoveUp: KeyChord(modifiers: .cmd, key: .f3), + .displayMoveDown: KeyChord(modifiers: .cmd, key: .f4), + .openSettings: KeyChord(key: .comma), + ] +} diff --git a/Sources/TesseraConfig/ConfigFileWatcher.swift b/Sources/TesseraConfig/ConfigFileWatcher.swift new file mode 100644 index 00000000..79e21b9a --- /dev/null +++ b/Sources/TesseraConfig/ConfigFileWatcher.swift @@ -0,0 +1,88 @@ +import Foundation + +struct ConfigFileWatcher: Sendable { + private let task: Task + + init( + pollInterval: Duration, + sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, + poll: @escaping @Sendable () async -> Bool, + failed: @escaping @Sendable (ConfigDiagnostic) async -> Void + ) { + task = Task.detached(priority: .utility) { + while !Task.isCancelled { + guard await poll() else { return } + do { + try await sleep(pollInterval) + } catch is CancellationError { + return + } catch { + await failed( + ConfigDiagnostic( + message: String( + localized: "Configuration watching stopped unexpectedly: \(error.localizedDescription)", + table: "Store", bundle: .module + ) + ) + ) + return + } + } + } + } + + func cancel() { + task.cancel() + } + + func waitUntilFinished() async { + await task.value + } +} + +enum ConfigFileContents: Sendable, Equatable { + case bytes(Data) + case missing + case failure(ConfigDiagnostic) + + static func read(from url: URL) -> ConfigFileContents { + guard url.isFileURL else { + return .failure( + ConfigDiagnostic( + message: String( + localized: "The configuration URL must point to a local file: \(url.absoluteString)", + table: "Store", bundle: .module + ) + ) + ) + } + do { + var resolvedURL = url.resolvingSymlinksInPath() + resolvedURL.removeAllCachedResourceValues() + let values = try resolvedURL.resourceValues(forKeys: [.isRegularFileKey]) + guard values.isRegularFile == true else { + return .failure( + ConfigDiagnostic( + message: String( + localized: "The configuration path is not a regular file: \(url.path)", + table: "Store", bundle: .module + ) + ) + ) + } + return .bytes(try Data(contentsOf: url)) + } catch let error as CocoaError where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile { + return .missing + } catch { + return .failure( + ConfigDiagnostic( + message: String( + localized: + "Could not read the configuration file at \(url.path): \(error.localizedDescription)", + table: "Store", bundle: .module + ) + ) + ) + } + } +} diff --git a/Sources/TesseraConfig/ConfigJSONSchema.swift b/Sources/TesseraConfig/ConfigJSONSchema.swift new file mode 100644 index 00000000..bebeae0b --- /dev/null +++ b/Sources/TesseraConfig/ConfigJSONSchema.swift @@ -0,0 +1,194 @@ +import Foundation + +public enum ConfigJSONSchema { + public static let string: String = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + do { + return String(decoding: try encoder.encode(schema), as: UTF8.self) + } catch { + preconditionFailure( + String( + localized: "The configuration schema could not be encoded: \(String(describing: error)).", + table: "Schema", bundle: .module + ) + ) + } + }() + + private static var schema: SchemaValue { + let defaults = TesseraConfiguration.defaults + let bindings = DefaultKeybindings.bindings() + var keybindings: [String: SchemaValue] = [:] + for command in ConfigCommand.allCases { + var property: [String: SchemaValue] = [ + "oneOf": .array([ + .object([ + "type": .string("string"), "minLength": .integer(1), "format": .string("tessera-key-chord"), + ]), + .object(["const": .bool(false)]), + ]) + ] + if let chord = bindings[command] { property["default"] = .string(chord.description) } + keybindings[command.rawValue] = .object(property) + } + var layout = layoutProperties(defaults.layout.global, includeDefaults: true) + layout["displays"] = .object([ + "type": .string("object"), + "default": .object([:]), + "propertyNames": .object([ + "pattern": .string("^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$") + ]), + "additionalProperties": object(layoutProperties(defaults.layout.global, includeDefaults: false)), + "description": .string( + "UUID-keyed display tables inherit every omitted layout value from the global layout."), + ]) + var ruleProperties: [String: SchemaValue] = [:] + for key in ["bundle-id", "title-regex", "role"] { + var property: [String: SchemaValue] = [ + "type": .string("string"), "minLength": .integer(1), "pattern": .string("\\S"), + ] + if key == "title-regex" { property["format"] = .string("tessera-title-regex") } + ruleProperties[key] = .object(property) + } + let floatRule = object( + ruleProperties, + extra: [ + "anyOf": .array( + ["bundle-id", "title-regex", "role"].map { key in + .object(["required": .array([.string(key)])]) + }) + ] + ) + return object( + [ + "version": .object([ + "type": .string("integer"), "const": .integer(1), "default": .integer(defaults.version), + ]), + "general": object([ + "prefix": .object([ + "type": .string("string"), "format": .string("tessera-modifiers"), + "default": .string(defaults.general.prefix.description), + "description": .string( + "Modifiers used only to generate inherited shortcuts; explicit shortcuts are absolute."), + ]), + "launch-at-login": boolean(defaults.general.launchAtLogin), + ]), + "layout": object(layout), + "motion": object([ + "enabled": boolean(defaults.motion.enabled), + "speed": number(ConfigLimits.speed, defaultValue: defaults.motion.speed), + "whimsy": choice( + ConfigWhimsy.allCases.map(\.rawValue), defaultValue: defaults.motion.whimsy.rawValue), + ]), + "keybindings": object( + keybindings, + extra: [ + "description": .string( + "Shortcuts inherit generated defaults. Set any command to false to remove it."), + "default": .object( + Dictionary( + uniqueKeysWithValues: bindings.map { ($0.key.rawValue, .string($0.value.description)) }) + ), + ] + ), + "float-rules": .object(["type": .string("array"), "items": floatRule, "default": .array([])]), + "accessibility": object([ + "announce-layout-changes": boolean(defaults.accessibility.announceLayoutChanges) + ]), + ], + extra: [ + "$schema": .string("https://json-schema.org/draft/2020-12/schema"), + "title": .string("Tessera configuration, version 1"), + "$comment": .string( + "This schema describes parsed TOML. Unknown settings are accepted with warnings by ConfigValidator. " + + "ConfigValidator also checks the tessera-modifiers and tessera-key-chord formats, " + + "ICU expressions in tessera-title-regex, case-insensitive duplicate display UUIDs, " + + "and duplicate resolved shortcuts, including inherited defaults. " + + "Display overrides have no fixed defaults: omitted fields inherit the global layout." + ), + ] + ) + } + + private static func layoutProperties(_ values: LayoutValues, includeDefaults: Bool) -> [String: SchemaValue] { + var reserved: [String: SchemaValue] = [:] + for (key, value) in [ + ("top", values.reserved.top), ("right", values.reserved.right), ("bottom", values.reserved.bottom), + ("left", values.reserved.left), + ] { + reserved[key] = number(ConfigLimits.reserved, defaultValue: includeDefaults ? value : nil) + } + return [ + "default": choice( + ConfigLayout.allCases.map(\.rawValue), + defaultValue: includeDefaults ? values.defaultLayout.rawValue : nil), + "ratio": number(ConfigLimits.ratio, defaultValue: includeDefaults ? values.ratio : nil), + "gaps": object([ + "inner": number(ConfigLimits.gap, defaultValue: includeDefaults ? values.gaps.inner : nil), + "outer": number(ConfigLimits.gap, defaultValue: includeDefaults ? values.gaps.outer : nil), + ]), + "reserved": object(reserved), + "window-cap": integer( + ConfigLimits.windowCap, defaultValue: includeDefaults ? values.windowCap : nil, + description: "Maximum tiled windows; 0 means unlimited." + ), + ] + } + + private static func object(_ properties: [String: SchemaValue], extra: [String: SchemaValue] = [:]) -> SchemaValue { + .object( + extra.merging([ + "type": .string("object"), "properties": .object(properties), "additionalProperties": .bool(true), + ]) { _, structural in structural } + ) + } + + private static func boolean(_ defaultValue: Bool) -> SchemaValue { + .object(["type": .string("boolean"), "default": .bool(defaultValue)]) + } + + private static func choice(_ values: [String], defaultValue: String?) -> SchemaValue { + var result: [String: SchemaValue] = ["type": .string("string"), "enum": .array(values.map(SchemaValue.string))] + if let defaultValue { result["default"] = .string(defaultValue) } + return .object(result) + } + + private static func number(_ range: ClosedRange, defaultValue: Double?) -> SchemaValue { + var result: [String: SchemaValue] = [ + "type": .string("number"), "minimum": .number(range.lowerBound), "maximum": .number(range.upperBound), + ] + if let defaultValue { result["default"] = .number(defaultValue) } + return .object(result) + } + + private static func integer(_ range: ClosedRange, defaultValue: Int?, description: String) -> SchemaValue { + var result: [String: SchemaValue] = [ + "type": .string("integer"), "minimum": .integer(range.lowerBound), "maximum": .integer(range.upperBound), + "description": .string(description), + ] + if let defaultValue { result["default"] = .integer(defaultValue) } + return .object(result) + } +} + +private indirect enum SchemaValue: Encodable { + case object([String: SchemaValue]) + case array([SchemaValue]) + case string(String) + case number(Double) + case integer(Int) + case bool(Bool) + + func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .object(let value): try container.encode(value) + case .array(let value): try container.encode(value) + case .string(let value): try container.encode(value) + case .number(let value): try container.encode(value) + case .integer(let value): try container.encode(value) + case .bool(let value): try container.encode(value) + } + } +} diff --git a/Sources/TesseraConfig/ConfigStore.swift b/Sources/TesseraConfig/ConfigStore.swift new file mode 100644 index 00000000..1c1b2d1b --- /dev/null +++ b/Sources/TesseraConfig/ConfigStore.swift @@ -0,0 +1,254 @@ +public import Foundation + +public enum ConfigSource: Equatable, Sendable { + case defaults + case file(URL) + case sourceText +} + +public enum ConfigLoadState: Equatable, Sendable { + case notLoaded + case loaded + case missingFileUsingDefaults + case rejected +} + +public struct ConfigSnapshot: Sendable { + public let activeConfiguration: TesseraConfiguration + public let lastGoodDocument: TOMLDocument? + public let activeSource: ConfigSource + public let attemptedSource: ConfigSource? + public let loadState: ConfigLoadState + public let diagnostics: [ConfigDiagnostic] +} + +public actor ConfigStore { + public static var defaultFileURL: URL { + FileManager.default.homeDirectoryForCurrentUser + .appendingPathComponent(".config/tessera/tessera.toml", isDirectory: false) + } + + public nonisolated let fileURL: URL + public private(set) var snapshot = ConfigSnapshot( + activeConfiguration: .defaults, lastGoodDocument: nil, activeSource: .defaults, + attemptedSource: nil, loadState: .notLoaded, diagnostics: [] + ) + public var isWatching: Bool { watcher != nil } + + private var watcher: ConfigFileWatcher? + private var watchID: UUID? + private var previousContents: ConfigFileContents? + private var subscribers: [UUID: AsyncStream.Continuation] = [:] + + public init(fileURL: URL = ConfigStore.defaultFileURL) { + self.fileURL = fileURL + } + + deinit { + watcher?.cancel() + for subscriber in subscribers.values { + subscriber.finish() + } + } + + /// Includes the current snapshot. Slow consumers receive the newest state, not an unbounded history. + public func updates() -> AsyncStream { + let id = UUID() + let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + continuation.onTermination = { [weak self] _ in + Task { await self?.removeSubscriber(id) } + } + subscribers[id] = continuation + continuation.yield(snapshot) + return stream + } + + @discardableResult + public func reload() -> ConfigSnapshot { + let contents = ConfigFileContents.read(from: fileURL) + previousContents = contents + apply(contents) + return snapshot + } + + /// A running watcher resumes loading its file on the next poll. + @discardableResult + public func load(source: String) -> ConfigSnapshot { + previousContents = nil + apply(source: source, from: .sourceText) + return snapshot + } + + /// Polls bytes rather than inode metadata to follow atomic saves, recreation, and same-size writes. + /// The default interval is 250 ms, plus read/validation and scheduling time; intermediate writes may coalesce. + public func startWatching(pollInterval: Duration = .milliseconds(250)) throws { + guard pollInterval > .zero else { + throw ConfigDiagnostic( + message: String( + localized: "The configuration polling interval must be greater than zero.", + table: "Store", bundle: .module + ) + ) + } + guard watcher == nil else { return } + let id = UUID() + watchID = id + previousContents = nil + watcher = ConfigFileWatcher( + pollInterval: pollInterval, + poll: { [weak self] in + await self?.poll(watchID: id) ?? false + }, + failed: { [weak self] diagnostic in + await self?.watchFailed(diagnostic, watchID: id) + } + ) + } + + /// Waits for the canceled watcher to finish; it cannot publish after this call returns. + public func stopWatching() async { + watchID = nil + let previous = watcher + watcher = nil + previous?.cancel() + await previous?.waitUntilFinished() + } + + private func poll(watchID id: UUID) -> Bool { + guard watchID == id, !Task.isCancelled else { return false } + let contents = ConfigFileContents.read(from: fileURL) + guard !Task.isCancelled else { return false } + if contents != previousContents { + previousContents = contents + apply(contents) + } + return true + } + + private func watchFailed(_ diagnostic: ConfigDiagnostic, watchID id: UUID) { + guard watchID == id else { return } + watcher = nil + watchID = nil + reject([diagnostic], from: .file(fileURL)) + } + + private func apply(_ contents: ConfigFileContents) { + let source = ConfigSource.file(fileURL) + switch contents { + case .bytes(let bytes): + guard let text = String(data: bytes, encoding: .utf8) else { + reject( + [ + ConfigDiagnostic( + message: String( + localized: + "The configuration file at \(fileURL.path) is not valid UTF-8. Save it as UTF-8 and try again.", + table: "Store", bundle: .module + ) + ) + ], from: source + ) + return + } + apply(source: text, from: source) + case .missing: + if snapshot.activeSource == .defaults { + publish( + ConfigSnapshot( + activeConfiguration: snapshot.activeConfiguration, lastGoodDocument: snapshot.lastGoodDocument, + activeSource: snapshot.activeSource, attemptedSource: source, + loadState: .missingFileUsingDefaults, + diagnostics: [ + ConfigDiagnostic( + severity: .warning, + message: String( + localized: + "No configuration file exists at \(fileURL.path). Using built-in defaults until a valid file is available.", + table: "Store", bundle: .module + ) + ) + ] + ) + ) + } else { + reject( + [ + ConfigDiagnostic( + message: String( + localized: + "The configuration file at \(fileURL.path) is missing. Keeping the last good configuration.", + table: "Store", bundle: .module + ) + ) + ], from: source + ) + } + case .failure(let diagnostic): + reject([diagnostic], from: source) + } + } + + private func apply(source: String, from origin: ConfigSource) { + do { + let document = try TOMLDocument(parsing: source) + let result = ConfigValidator.validate(document) + guard let configuration = result.configuration, + !result.diagnostics.contains(where: { $0.severity == .error }) + else { + var diagnostics = result.diagnostics + if !diagnostics.contains(where: { $0.severity == .error }) { + diagnostics.append( + ConfigDiagnostic( + message: String( + localized: "Configuration validation did not produce a usable configuration.", + table: "Store", bundle: .module + ) + ) + ) + } + reject(diagnostics, from: origin) + return + } + publish( + ConfigSnapshot( + activeConfiguration: configuration, lastGoodDocument: document, activeSource: origin, + attemptedSource: origin, loadState: .loaded, diagnostics: result.diagnostics + ) + ) + } catch let diagnostic as ConfigDiagnostic { + reject([diagnostic], from: origin) + } catch { + reject( + [ + ConfigDiagnostic( + message: String( + localized: "Could not parse the configuration: \(error.localizedDescription)", + table: "Store", bundle: .module + ) + ) + ], from: origin + ) + } + } + + private func reject(_ diagnostics: [ConfigDiagnostic], from source: ConfigSource) { + publish( + ConfigSnapshot( + activeConfiguration: snapshot.activeConfiguration, lastGoodDocument: snapshot.lastGoodDocument, + activeSource: snapshot.activeSource, attemptedSource: source, + loadState: .rejected, diagnostics: diagnostics + ) + ) + } + + private func publish(_ value: ConfigSnapshot) { + snapshot = value + for subscriber in subscribers.values { + subscriber.yield(value) + } + } + + private func removeSubscriber(_ id: UUID) { + subscribers.removeValue(forKey: id) + } +} diff --git a/Sources/TesseraConfig/ConfigValidator.swift b/Sources/TesseraConfig/ConfigValidator.swift new file mode 100644 index 00000000..bbd95fea --- /dev/null +++ b/Sources/TesseraConfig/ConfigValidator.swift @@ -0,0 +1,520 @@ +import Foundation + +public enum ConfigValidator { + public static func validate(_ document: TOMLDocument) -> ConfigValidationResult { + var validation = Validation(document: document) + return validation.run() + } +} + +private struct Validation { + let document: TOMLDocument + var diagnostics: [ConfigDiagnostic] = [] + + mutating func run() -> ConfigValidationResult { + let root = table(document.root, path: "configuration", example: "version = 1") + unknownKeys( + root, + allowed: ["version", "general", "layout", "motion", "keybindings", "float-rules", "accessibility"] + ) + var configuration = TesseraConfiguration.defaults + configuration.version = integer(root["version"], path: "version", fallback: 1, bounds: 1...1) + configuration.general = general(root["general"]) + configuration.layout = layout(root["layout"]) + configuration.motion = motion(root["motion"]) + configuration.accessibility = accessibility(root["accessibility"]) + configuration.floatRules = floatRules(root["float-rules"]) + configuration.keybindings = keybindings( + root["keybindings"], prefix: configuration.general.prefix, + prefixLocation: root["general"]?["prefix"]?.range.start ?? document.root.range.start + ) + diagnostics.sort { + if $0.location.offset != $1.location.offset { + return $0.location.offset < $1.location.offset + } + return $0.message < $1.message + } + return ConfigValidationResult( + configuration: diagnostics.contains { $0.severity == .error } ? nil : configuration, + diagnostics: diagnostics + ) + } + + mutating func general(_ node: TOMLNode?) -> GeneralConfiguration { + var result = GeneralConfiguration() + guard let node else { return result } + let values = table(node, path: "general", example: "[general]\nlaunch-at-login = false") + unknownKeys(values, allowed: ["prefix", "launch-at-login"], path: "general") + result.launchAtLogin = boolean( + values["launch-at-login"], path: "general.launch-at-login", fallback: result.launchAtLogin + ) + if let prefix = string(values["prefix"], path: "general.prefix", example: "prefix = \"ctrl-alt\"") { + do { + result.prefix = try KeyModifiers(parsing: prefix) + } catch { + if let node = values["prefix"] { + failure( + node, + String( + localized: + "Invalid general.prefix: \(String(describing: error)). For example: prefix = \"ctrl-alt\".", + table: "Schema", bundle: .module + ) + ) + } + } + } + return result + } + + mutating func layout(_ node: TOMLNode?) -> LayoutConfiguration { + guard let node else { return LayoutConfiguration() } + let values = table(node, path: "layout", example: "[layout]\ndefault = \"grid\"") + let global = layoutValues(values, path: "layout", inherited: LayoutValues(), allowsDisplays: true) + var displays: [UUID: LayoutValues] = [:] + if let displayNode = values["displays"] { + let example = "[layout.displays.\"00000000-0000-0000-0000-000000000001\"]\ndefault = \"columns\"" + let entries = table(displayNode, path: "layout.displays", example: example) + var locations: [UUID: SourceLocation] = [:] + for key in entries.keys.sorted() { + guard let entry = entries[key] else { continue } + guard key.count == 36, let id = UUID(uuidString: key) else { + failure( + entry, + String( + localized: "Display key “\(key)” must be a UUID. For example:\n\(example)", + table: "Schema", bundle: .module + ) + ) + continue + } + if let previous = locations[id] { + failure( + entry, + String( + localized: + "Display UUID “\(key)” is configured twice with different letter casing. Keep one table, for example:\n\(example)", + table: "Schema", bundle: .module + ), + relatedLocation: previous + ) + continue + } + locations[id] = entry.range.start + let path = "layout.displays.\"\(key)\"" + let overrides = table(entry, path: path, example: example) + displays[id] = layoutValues(overrides, path: path, inherited: global) + } + } + return LayoutConfiguration(global: global, displays: displays) + } + + mutating func layoutValues( + _ values: [String: TOMLNode], path: String, inherited: LayoutValues, allowsDisplays: Bool = false + ) -> LayoutValues { + var allowed = ["default", "ratio", "gaps", "reserved", "window-cap"] + if allowsDisplays { allowed.append("displays") } + unknownKeys(values, allowed: allowed, path: path) + var result = inherited + result.defaultLayout = choice(values["default"], path: "\(path).default", fallback: result.defaultLayout) + result.ratio = number( + values["ratio"], path: "\(path).ratio", fallback: result.ratio, bounds: ConfigLimits.ratio) + result.windowCap = integer( + values["window-cap"], path: "\(path).window-cap", fallback: result.windowCap, bounds: ConfigLimits.windowCap + ) + if let node = values["gaps"] { + let gaps = table(node, path: "\(path).gaps", example: "[\(path).gaps]\ninner = 8") + unknownKeys(gaps, allowed: ["inner", "outer"], path: "\(path).gaps") + result.gaps.inner = number( + gaps["inner"], path: "\(path).gaps.inner", fallback: result.gaps.inner, bounds: ConfigLimits.gap + ) + result.gaps.outer = number( + gaps["outer"], path: "\(path).gaps.outer", fallback: result.gaps.outer, bounds: ConfigLimits.gap + ) + } + if let node = values["reserved"] { + let reserved = table(node, path: "\(path).reserved", example: "[\(path).reserved]\ntop = 0") + unknownKeys(reserved, allowed: ["top", "right", "bottom", "left"], path: "\(path).reserved") + result.reserved.top = number( + reserved["top"], path: "\(path).reserved.top", fallback: result.reserved.top, + bounds: ConfigLimits.reserved + ) + result.reserved.right = number( + reserved["right"], path: "\(path).reserved.right", fallback: result.reserved.right, + bounds: ConfigLimits.reserved + ) + result.reserved.bottom = number( + reserved["bottom"], path: "\(path).reserved.bottom", fallback: result.reserved.bottom, + bounds: ConfigLimits.reserved + ) + result.reserved.left = number( + reserved["left"], path: "\(path).reserved.left", fallback: result.reserved.left, + bounds: ConfigLimits.reserved + ) + } + return result + } + + mutating func motion(_ node: TOMLNode?) -> MotionConfiguration { + var result = MotionConfiguration() + guard let node else { return result } + let values = table(node, path: "motion", example: "[motion]\nenabled = true") + unknownKeys(values, allowed: ["enabled", "speed", "whimsy"], path: "motion") + result.enabled = boolean(values["enabled"], path: "motion.enabled", fallback: result.enabled) + result.speed = number(values["speed"], path: "motion.speed", fallback: result.speed, bounds: ConfigLimits.speed) + result.whimsy = choice(values["whimsy"], path: "motion.whimsy", fallback: result.whimsy) + return result + } + + mutating func accessibility(_ node: TOMLNode?) -> AccessibilityConfiguration { + var result = AccessibilityConfiguration() + guard let node else { return result } + let values = table(node, path: "accessibility", example: "[accessibility]\nannounce-layout-changes = false") + unknownKeys(values, allowed: ["announce-layout-changes"], path: "accessibility") + result.announceLayoutChanges = boolean( + values["announce-layout-changes"], path: "accessibility.announce-layout-changes", + fallback: result.announceLayoutChanges + ) + return result + } + + mutating func floatRules(_ node: TOMLNode?) -> [FloatRule] { + guard let node else { return [] } + let example = "[[float-rules]]\nbundle-id = \"com.example.app\"" + guard case .array(let entries) = node.value else { + failure( + node, + String( + localized: "float-rules must be an array of tables. For example:\n\(example)", + table: "Schema", bundle: .module + ) + ) + return [] + } + var result: [FloatRule] = [] + for (index, entry) in entries.enumerated() { + let path = "float-rules[\(index)]" + let values = table(entry, path: path, example: example) + unknownKeys(values, allowed: ["bundle-id", "title-regex", "role"], path: path) + if !["bundle-id", "title-regex", "role"].contains(where: { values[$0] != nil }) { + failure( + entry, + String( + localized: + "“\(path)” needs at least one matcher: bundle-id, title-regex, or role. For example:\n\(example)", + table: "Schema", bundle: .module + ) + ) + } + let bundleID = matcher( + values["bundle-id"], path: "\(path).bundle-id", example: "bundle-id = \"com.example.app\"") + let titleRegex = matcher( + values["title-regex"], path: "\(path).title-regex", example: "title-regex = \"^Preferences$\"") + let role = matcher(values["role"], path: "\(path).role", example: "role = \"AXDialog\"") + if let titleRegex, let regexNode = values["title-regex"] { + do { + _ = try NSRegularExpression(pattern: titleRegex) + } catch { + failure( + regexNode, + String( + localized: + "“\(path).title-regex” is not a valid regular expression. For example: title-regex = \"^Preferences$\".", + table: "Schema", bundle: .module + ) + ) + } + } + result.append(FloatRule(bundleID: bundleID, titleRegex: titleRegex, role: role)) + } + return result + } + + mutating func matcher(_ node: TOMLNode?, path: String, example: String) -> String? { + guard let value = string(node, path: path, example: example), let node else { return nil } + guard !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + failure( + node, + String( + localized: "“\(path)” cannot be empty. For example: \(example).", + table: "Schema", bundle: .module + ) + ) + return nil + } + return value + } + + mutating func keybindings( + _ node: TOMLNode?, prefix: KeyModifiers, prefixLocation: SourceLocation + ) -> [ConfigCommand: KeyChord] { + var result = DefaultKeybindings.bindings(prefix: prefix) + var explicitLocations: [ConfigCommand: SourceLocation] = [:] + if let node { + let examples = DefaultKeybindings.bindings() + let example = + ConfigCommand.allCases.first.flatMap { command in + examples[command].map { "\(command.rawValue) = \"\($0.description)\"" } + } ?? "[keybindings]" + let values = table(node, path: "keybindings", example: "[keybindings]\n\(example)") + unknownKeys(values, allowed: ConfigCommand.allCases.map(\.rawValue), path: "keybindings") + for command in ConfigCommand.allCases { + guard let entry = values[command.rawValue] else { continue } + if case .bool(false) = entry.value { + result.removeValue(forKey: command) + continue + } + let assignment = + examples[command].map { "\(command.rawValue) = \"\($0.description)\"" } + ?? "\(command.rawValue) = false" + guard case .string(let text) = entry.value else { + failure( + entry, + String( + localized: + "“keybindings.\(command.rawValue)” needs a shortcut string or false to disable it. For example: \(assignment).", + table: "Schema", bundle: .module + ) + ) + continue + } + do { + result[command] = try KeyChord(parsing: text) + explicitLocations[command] = entry.range.start + } catch { + failure( + entry, + String( + localized: + "Invalid shortcut for “\(command.rawValue)”: \(String(describing: error)). For example: \(assignment).", + table: "Schema", bundle: .module + ) + ) + } + } + } + duplicateChords(result, explicitLocations: explicitLocations, prefixLocation: prefixLocation) + return result + } + + mutating func duplicateChords( + _ bindings: [ConfigCommand: KeyChord], explicitLocations: [ConfigCommand: SourceLocation], + prefixLocation: SourceLocation + ) { + var seen: [KeyChord: ConfigCommand] = [:] + let commands = bindings.keys.sorted { + let lhs = explicitLocations[$0]?.offset ?? -1 + let rhs = explicitLocations[$1]?.offset ?? -1 + return lhs == rhs ? $0.rawValue < $1.rawValue : lhs < rhs + } + for command in commands { + guard let chord = bindings[command] else { continue } + guard let previous = seen[chord] else { + seen[chord] = command + continue + } + let location = explicitLocations[command] ?? prefixLocation + let related = explicitLocations[previous] ?? prefixLocation + let message: String + if explicitLocations[previous] == nil, explicitLocations[command] == nil { + message = String( + localized: + "Inherited defaults “\(previous.rawValue)” and “\(command.rawValue)” both resolve to \(chord.description) with this prefix. Change general.prefix or disable one with \(command.rawValue) = false.", + table: "Schema", bundle: .module + ) + } else if explicitLocations[previous] == nil { + message = String( + localized: + "“\(command.rawValue)” uses \(chord.description), which conflicts with the inherited default for “\(previous.rawValue)”. Override that default or disable it with \(previous.rawValue) = false.", + table: "Schema", bundle: .module + ) + } else { + message = String( + localized: + "“\(command.rawValue)” and “\(previous.rawValue)” both use \(chord.description); the earlier binding is at line \(related.line), column \(related.column). Assign different shortcuts, or disable one with \(command.rawValue) = false.", + table: "Schema", bundle: .module + ) + } + diagnostics.append( + ConfigDiagnostic(severity: .error, location: location, message: message, relatedLocation: related) + ) + } + } + + mutating func table(_ node: TOMLNode, path: String, example: String) -> [String: TOMLNode] { + guard case .table(let entries) = node.value else { + failure( + node, + String( + localized: "Expected a table for “\(path)”. For example:\n\(example)", + table: "Schema", bundle: .module + ) + ) + return [:] + } + return entries + } + + mutating func boolean(_ node: TOMLNode?, path: String, fallback: Bool) -> Bool { + guard let node else { return fallback } + guard case .bool(let value) = node.value else { + let example = "\(path) = \(fallback)" + failure( + node, + String( + localized: "Expected true or false for “\(path)”. For example: \(example).", + table: "Schema", bundle: .module + ) + ) + return fallback + } + return value + } + + mutating func string(_ node: TOMLNode?, path: String, example: String) -> String? { + guard let node else { return nil } + guard case .string(let value) = node.value else { + failure( + node, + String( + localized: "Expected a quoted string for “\(path)”. For example: \(example).", + table: "Schema", bundle: .module + ) + ) + return nil + } + return value + } + + mutating func integer(_ node: TOMLNode?, path: String, fallback: Int, bounds: ClosedRange) -> Int { + guard let node else { return fallback } + let example = "\(path) = \(fallback)" + guard case .integer(let value) = node.value else { + failure( + node, + String( + localized: "Expected a whole number for “\(path)”. For example: \(example).", + table: "Schema", bundle: .module + ) + ) + return fallback + } + guard let converted = Int(exactly: value), bounds.contains(converted) else { + failure( + node, + String( + localized: + "“\(path)” must be a whole number between \(bounds.lowerBound) and \(bounds.upperBound). For example: \(example).", + table: "Schema", bundle: .module + ) + ) + return fallback + } + return converted + } + + mutating func number(_ node: TOMLNode?, path: String, fallback: Double, bounds: ClosedRange) -> Double { + guard let node else { return fallback } + let example = "\(path) = \(fallback)" + let value: Double + switch node.value { + case .float(let number): value = number + case .integer(let number): value = Double(number) + default: + failure( + node, + String( + localized: "Expected a number for “\(path)”. For example: \(example).", + table: "Schema", bundle: .module + ) + ) + return fallback + } + guard value.isFinite, bounds.contains(value) else { + let lower = String(bounds.lowerBound) + let upper = String(bounds.upperBound) + failure( + node, + String( + localized: + "“\(path)” must be a finite number between \(lower) and \(upper). For example: \(example).", + table: "Schema", bundle: .module + ) + ) + return fallback + } + return value + } + + mutating func choice( + _ node: TOMLNode?, path: String, fallback: Choice + ) -> Choice where Choice.RawValue == String { + let example = "\(path) = \"\(fallback.rawValue)\"" + guard let text = string(node, path: path, example: example), let node else { return fallback } + guard let value = Choice(rawValue: text) else { + let options = Choice.allCases.map { "\"\($0.rawValue)\"" }.joined(separator: ", ") + failure( + node, + String( + localized: "“\(path)” must be one of \(options). For example: \(example).", + table: "Schema", bundle: .module + ) + ) + return fallback + } + return value + } + + mutating func unknownKeys(_ values: [String: TOMLNode], allowed: [String], path: String = "") { + for key in values.keys.sorted() where !allowed.contains(key) { + guard let node = values[key] else { continue } + let qualified = path.isEmpty ? key : "\(path).\(key)" + let closest = allowed.sorted { + let lhs = Self.editDistance(key, $0) + let rhs = Self.editDistance(key, $1) + return lhs == rhs ? $0 < $1 : lhs < rhs + }.first + let message: String + if let closest, Self.editDistance(key, closest) <= (key.count < 3 ? 1 : 2) { + let suggestion = path.isEmpty ? closest : "\(path).\(closest)" + message = String( + localized: "Unknown key “\(qualified)”. Did you mean “\(suggestion)”?", + table: "Schema", bundle: .module + ) + } else { + message = String( + localized: "Unknown key “\(qualified)”; this setting is ignored.", + table: "Schema", bundle: .module + ) + } + diagnostics.append( + ConfigDiagnostic( + severity: .warning, location: node.keyRange?.start ?? node.range.start, message: message) + ) + } + } + + mutating func failure(_ node: TOMLNode, _ message: String, relatedLocation: SourceLocation? = nil) { + diagnostics.append( + ConfigDiagnostic( + severity: .error, location: node.range.start, message: message, relatedLocation: relatedLocation) + ) + } + + static func editDistance(_ lhs: String, _ rhs: String) -> Int { + let right = Array(rhs) + var previous = Array(0...right.count) + for (leftIndex, character) in lhs.enumerated() { + var row = [leftIndex + 1] + for (rightIndex, other) in right.enumerated() { + row.append( + min( + row[rightIndex] + 1, previous[rightIndex + 1] + 1, + previous[rightIndex] + (character == other ? 0 : 1)) + ) + } + previous = row + } + return previous[right.count] + } +} diff --git a/Sources/TesseraConfig/Configuration.swift b/Sources/TesseraConfig/Configuration.swift new file mode 100644 index 00000000..20e503b7 --- /dev/null +++ b/Sources/TesseraConfig/Configuration.swift @@ -0,0 +1,160 @@ +public import Foundation + +public struct TesseraConfiguration: Equatable, Sendable { + public var version: Int + public var general: GeneralConfiguration + public var layout: LayoutConfiguration + public var motion: MotionConfiguration + public var keybindings: [ConfigCommand: KeyChord] + public var floatRules: [FloatRule] + public var accessibility: AccessibilityConfiguration + + public static let defaults = TesseraConfiguration() + + public init( + version: Int = 1, + general: GeneralConfiguration = GeneralConfiguration(), + layout: LayoutConfiguration = LayoutConfiguration(), + motion: MotionConfiguration = MotionConfiguration(), + keybindings: [ConfigCommand: KeyChord]? = nil, + floatRules: [FloatRule] = [], + accessibility: AccessibilityConfiguration = AccessibilityConfiguration() + ) { + self.version = version + self.general = general + self.layout = layout + self.motion = motion + self.keybindings = keybindings ?? DefaultKeybindings.bindings(prefix: general.prefix) + self.floatRules = floatRules + self.accessibility = accessibility + } +} + +public struct GeneralConfiguration: Equatable, Sendable { + public var prefix: KeyModifiers + public var launchAtLogin: Bool + + public init(prefix: KeyModifiers = [.ctrl, .alt], launchAtLogin: Bool = false) { + self.prefix = prefix + self.launchAtLogin = launchAtLogin + } +} + +public enum ConfigLayout: String, CaseIterable, Sendable { + case grid, columns, rows, side +} + +public struct LayoutConfiguration: Equatable, Sendable { + public var global: LayoutValues + public var displays: [UUID: LayoutValues] + + public init(global: LayoutValues = LayoutValues(), displays: [UUID: LayoutValues] = [:]) { + self.global = global + self.displays = displays + } + + public func values(for displayID: UUID) -> LayoutValues { + displays[displayID] ?? global + } +} + +public struct LayoutValues: Equatable, Sendable { + public var defaultLayout: ConfigLayout + public var ratio: Double + public var gaps: LayoutGaps + public var reserved: ReservedEdges + /// Zero means no window limit. + public var windowCap: Int + + public init( + defaultLayout: ConfigLayout = .grid, + ratio: Double = 0.5, + gaps: LayoutGaps = LayoutGaps(), + reserved: ReservedEdges = ReservedEdges(), + windowCap: Int = 0 + ) { + self.defaultLayout = defaultLayout + self.ratio = ratio + self.gaps = gaps + self.reserved = reserved + self.windowCap = windowCap + } +} + +public struct LayoutGaps: Equatable, Sendable { + public var inner: Double + public var outer: Double + + public init(inner: Double = 8, outer: Double = 8) { + self.inner = inner + self.outer = outer + } +} + +public struct ReservedEdges: Equatable, Sendable { + public var top: Double + public var right: Double + public var bottom: Double + public var left: Double + + public init(top: Double = 0, right: Double = 0, bottom: Double = 0, left: Double = 0) { + self.top = top + self.right = right + self.bottom = bottom + self.left = left + } +} + +public enum ConfigWhimsy: String, CaseIterable, Sendable { + case calm, playful, extra +} + +public struct MotionConfiguration: Equatable, Sendable { + public var enabled: Bool + public var speed: Double + public var whimsy: ConfigWhimsy + + public init(enabled: Bool = true, speed: Double = 1, whimsy: ConfigWhimsy = .playful) { + self.enabled = enabled + self.speed = speed + self.whimsy = whimsy + } +} + +public struct FloatRule: Equatable, Sendable { + public var bundleID: String? + public var titleRegex: String? + public var role: String? + + public init(bundleID: String? = nil, titleRegex: String? = nil, role: String? = nil) { + self.bundleID = bundleID + self.titleRegex = titleRegex + self.role = role + } +} + +public struct AccessibilityConfiguration: Equatable, Sendable { + public var announceLayoutChanges: Bool + + public init(announceLayoutChanges: Bool = false) { + self.announceLayoutChanges = announceLayoutChanges + } +} + +public struct ConfigValidationResult: Equatable, Sendable { + public let configuration: TesseraConfiguration? + public let diagnostics: [ConfigDiagnostic] + + public init(configuration: TesseraConfiguration?, diagnostics: [ConfigDiagnostic]) { + self.configuration = configuration + self.diagnostics = diagnostics + } +} + +enum ConfigLimits { + static let ratio = 0.1...0.9 + static let gap = 0.0...256.0 + static let reserved = 0.0...4096.0 + static let windowCap = 0...100 + static let speed = 0.1...4.0 +} diff --git a/Sources/TesseraConfig/KeyChord.swift b/Sources/TesseraConfig/KeyChord.swift new file mode 100644 index 00000000..c1d37470 --- /dev/null +++ b/Sources/TesseraConfig/KeyChord.swift @@ -0,0 +1,337 @@ +public import Foundation + +public struct KeyModifiers: OptionSet, Sendable, Hashable, CustomStringConvertible { + public let rawValue: UInt8 + + public init(rawValue: UInt8) { + precondition( + rawValue & 0b1110_0000 == 0, + String( + localized: "Key modifiers must use only the five supported bits.", table: "Keybindings", bundle: .module + ) + ) + self.rawValue = rawValue + } + + public static let ctrl = KeyModifiers(rawValue: 1 << 0) + public static let alt = KeyModifiers(rawValue: 1 << 1) + public static let cmd = KeyModifiers(rawValue: 1 << 2) + public static let shift = KeyModifiers(rawValue: 1 << 3) + public static let fn = KeyModifiers(rawValue: 1 << 4) + public static let hyper: KeyModifiers = [.ctrl, .alt, .cmd, .shift] + + public init(parsing text: String) throws(KeyChordParseError) { + let text = KeyChordSyntax.normalize(text) + if text.isEmpty { + self = [] + return + } + self = try Self.parse(KeyChordSyntax.components(text)) + } + + public var description: String { + let names: [(Self, String)] = [(.ctrl, "ctrl"), (.alt, "alt"), (.cmd, "cmd"), (.shift, "shift"), (.fn, "fn")] + return names.filter { contains($0.0) }.map(\.1).joined(separator: "-") + } + + fileprivate static func named(_ name: String) -> Self? { + switch name { + case "ctrl", "control": .ctrl + case "alt", "opt", "option": .alt + case "cmd", "command": .cmd + case "shift": .shift + case "fn": .fn + case "hyper": .hyper + default: nil + } + } + + fileprivate static func parse(_ components: [String]) throws(KeyChordParseError) -> Self { + var modifiers: Self = [] + for component in components { + guard !component.isEmpty else { throw .emptyComponent } + guard let modifier = named(component) else { throw .unknownModifier(component) } + guard modifiers.intersection(modifier).isEmpty else { throw .duplicateModifier(component) } + modifiers.formUnion(modifier) + } + return modifiers + } +} + +/// Physical ANSI positions; letters do not depend on the active keyboard layout. +public enum ANSIKey: String, CaseIterable, Sendable, CustomStringConvertible { + case a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z + case zero = "0" + case one = "1" + case two = "2" + case three = "3" + case four = "4" + case five = "5" + case six = "6" + case seven = "7" + case eight = "8" + case nine = "9" + case minus + case equal = "=" + case leftBracket = "[" + case rightBracket = "]" + case backslash = "\\" + case semicolon = ";" + case quote = "'" + case comma = "," + case period = "." + case slash = "/" + case grave = "`" + case `return`, space, tab, escape, delete + case forwardDelete = "forwarddelete" + case capsLock = "capslock" + case home, end, help + case pageUp = "pageup" + case pageDown = "pagedown" + case left, right, up, down + case f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20 + case keypad0, keypad1, keypad2, keypad3, keypad4, keypad5, keypad6, keypad7, keypad8, keypad9 + case keypadDecimal = "keypaddecimal" + case keypadMultiply = "keypadmultiply" + case keypadPlus = "keypadplus" + case keypadClear = "keypadclear" + case keypadDivide = "keypaddivide" + case keypadEnter = "keypadenter" + case keypadMinus = "keypadminus" + case keypadEqual = "keypadequal" + + public var description: String { rawValue } + + public var keyCode: UInt16 { + switch self { + case .a: 0 + case .s: 1 + case .d: 2 + case .f: 3 + case .h: 4 + case .g: 5 + case .z: 6 + case .x: 7 + case .c: 8 + case .v: 9 + case .b: 11 + case .q: 12 + case .w: 13 + case .e: 14 + case .r: 15 + case .y: 16 + case .t: 17 + case .one: 18 + case .two: 19 + case .three: 20 + case .four: 21 + case .six: 22 + case .five: 23 + case .equal: 24 + case .nine: 25 + case .seven: 26 + case .minus: 27 + case .eight: 28 + case .zero: 29 + case .rightBracket: 30 + case .o: 31 + case .u: 32 + case .leftBracket: 33 + case .i: 34 + case .p: 35 + case .return: 36 + case .l: 37 + case .j: 38 + case .quote: 39 + case .k: 40 + case .semicolon: 41 + case .backslash: 42 + case .comma: 43 + case .slash: 44 + case .n: 45 + case .m: 46 + case .period: 47 + case .tab: 48 + case .space: 49 + case .grave: 50 + case .delete: 51 + case .escape: 53 + case .capsLock: 57 + case .f17: 64 + case .keypadDecimal: 65 + case .keypadMultiply: 67 + case .keypadPlus: 69 + case .keypadClear: 71 + case .keypadDivide: 75 + case .keypadEnter: 76 + case .keypadMinus: 78 + case .f18: 79 + case .f19: 80 + case .keypadEqual: 81 + case .keypad0: 82 + case .keypad1: 83 + case .keypad2: 84 + case .keypad3: 85 + case .keypad4: 86 + case .keypad5: 87 + case .keypad6: 88 + case .keypad7: 89 + case .f20: 90 + case .keypad8: 91 + case .keypad9: 92 + case .f5: 96 + case .f6: 97 + case .f7: 98 + case .f3: 99 + case .f8: 100 + case .f9: 101 + case .f11: 103 + case .f13: 105 + case .f16: 106 + case .f14: 107 + case .f10: 109 + case .f12: 111 + case .f15: 113 + case .help: 114 + case .home: 115 + case .pageUp: 116 + case .forwardDelete: 117 + case .f4: 118 + case .end: 119 + case .f2: 120 + case .pageDown: 121 + case .f1: 122 + case .left: 123 + case .right: 124 + case .down: 125 + case .up: 126 + } + } + + fileprivate static func parse(_ token: String) throws(KeyChordParseError) -> (Self, KeyModifiers) { + if let key = Self(rawValue: token) { return (key, []) } + switch token { + case "-", "hyphen": return (.minus, []) + case "equal", "equals": return (.equal, []) + case "leftbracket": return (.leftBracket, []) + case "rightbracket": return (.rightBracket, []) + case "backslash": return (.backslash, []) + case "semicolon": return (.semicolon, []) + case "quote", "apostrophe": return (.quote, []) + case "comma": return (.comma, []) + case "period", "dot": return (.period, []) + case "slash": return (.slash, []) + case "grave", "backtick": return (.grave, []) + case "enter": return (.return, []) + case "esc": return (.escape, []) + case "backspace": return (.delete, []) + case "!": return (.one, .shift) + case "@": return (.two, .shift) + case "#": return (.three, .shift) + case "$": return (.four, .shift) + case "%": return (.five, .shift) + case "^": return (.six, .shift) + case "&": return (.seven, .shift) + case "*": return (.eight, .shift) + case "(": return (.nine, .shift) + case ")": return (.zero, .shift) + case "_": return (.minus, .shift) + case "+": return (.equal, .shift) + case "{": return (.leftBracket, .shift) + case "}": return (.rightBracket, .shift) + case "|": return (.backslash, .shift) + case ":": return (.semicolon, .shift) + case "\"": return (.quote, .shift) + case "<": return (.comma, .shift) + case ">": return (.period, .shift) + case "?": return (.slash, .shift) + case "~": return (.grave, .shift) + default: throw .unknownKey(token) + } + } +} + +public struct KeyChord: Sendable, Hashable, CustomStringConvertible { + public let modifiers: KeyModifiers + public let key: ANSIKey + + public init(modifiers: KeyModifiers = [], key: ANSIKey) { + self.modifiers = modifiers + self.key = key + } + + public init(parsing text: String) throws(KeyChordParseError) { + let text = KeyChordSyntax.normalize(text) + guard !text.isEmpty else { throw .emptyChord } + var components = KeyChordSyntax.components(text) + // A doubled separator spells a literal minus; printing uses its unambiguous name. + if text == "-" { + components = ["minus"] + } else if components.count >= 3 && components.suffix(2).allSatisfy(\.isEmpty) { + components.removeLast(2) + components.append("minus") + } + guard let keyToken = components.popLast(), !keyToken.isEmpty else { throw .missingKey } + let modifiers = try KeyModifiers.parse(components) + guard KeyModifiers.named(keyToken) == nil else { throw .missingKey } + let (key, impliedModifiers) = try ANSIKey.parse(keyToken) + self.init(modifiers: modifiers.union(impliedModifiers), key: key) + } + + public var keyCode: UInt16 { key.keyCode } + + public var description: String { + modifiers.isEmpty ? key.description : "\(modifiers)-\(key)" + } +} + +public enum KeyChordParseError: Error, LocalizedError, Sendable, Equatable, CustomStringConvertible { + case emptyChord + case emptyComponent + case missingKey + case unknownModifier(String) + case duplicateModifier(String) + case unknownKey(String) + + public var errorDescription: String? { description } + + public var description: String { + switch self { + case .emptyChord: + String(localized: "A key chord cannot be empty.", table: "Keybindings", bundle: .module) + case .emptyComponent: + String(localized: "A key chord contains an empty modifier.", table: "Keybindings", bundle: .module) + case .missingKey: + String(localized: "A key chord needs a key after its modifiers.", table: "Keybindings", bundle: .module) + case .unknownModifier(let token): + String( + localized: "Unknown modifier ‘\(token)’. Use ctrl, alt (or opt), cmd, shift, fn, or hyper.", + table: "Keybindings", bundle: .module + ) + case .duplicateModifier(let token): + String( + localized: "Modifier ‘\(token)’ repeats a modifier already present.", + table: "Keybindings", bundle: .module + ) + case .unknownKey(let token): + String( + localized: "Unknown ANSI key ‘\(token)’. Use a letter, digit, punctuation, named key, or f1–f20.", + table: "Keybindings", bundle: .module + ) + } + } +} + +private enum KeyChordSyntax { + static func normalize(_ text: String) -> String { + let bytes = text.trimmingCharacters(in: .whitespacesAndNewlines).utf8.map { byte in + (65...90).contains(byte) ? byte + 32 : byte + } + return String(decoding: bytes, as: UTF8.self) + } + + static func components(_ text: String) -> [String] { + text.split(separator: "-", omittingEmptySubsequences: false) + .map { $0.trimmingCharacters(in: .whitespacesAndNewlines) } + } +} diff --git a/Sources/TesseraConfig/Resources/Keybindings.xcstrings b/Sources/TesseraConfig/Resources/Keybindings.xcstrings new file mode 100644 index 00000000..777491b7 --- /dev/null +++ b/Sources/TesseraConfig/Resources/Keybindings.xcstrings @@ -0,0 +1,83 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "A key chord cannot be empty." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "A key chord cannot be empty." + } + } + } + }, + "A key chord contains an empty modifier." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "A key chord contains an empty modifier." + } + } + } + }, + "A key chord needs a key after its modifiers." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "A key chord needs a key after its modifiers." + } + } + } + }, + "Key modifiers must use only the five supported bits." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Key modifiers must use only the five supported bits." + } + } + } + }, + "Modifier ‘%@’ repeats a modifier already present." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Modifier ‘%@’ repeats a modifier already present." + } + } + } + }, + "Unknown ANSI key ‘%@’. Use a letter, digit, punctuation, named key, or f1–f20." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Unknown ANSI key ‘%@’. Use a letter, digit, punctuation, named key, or f1–f20." + } + } + } + }, + "Unknown modifier ‘%@’. Use ctrl, alt (or opt), cmd, shift, fn, or hyper." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Unknown modifier ‘%@’. Use ctrl, alt (or opt), cmd, shift, fn, or hyper." + } + } + } + } + }, + "version" : "1.0" +} diff --git a/Sources/TesseraConfig/Resources/Parser.xcstrings b/Sources/TesseraConfig/Resources/Parser.xcstrings index 85619cee..c3330485 100644 --- a/Sources/TesseraConfig/Resources/Parser.xcstrings +++ b/Sources/TesseraConfig/Resources/Parser.xcstrings @@ -1,36 +1,336 @@ { "sourceLanguage": "en", "strings": { - "line %lld, column %lld: %@": {}, - "Expected `%@` here.": {}, - "Use a newline or a CRLF pair, not a bare carriage return.": {}, - "Comments cannot contain control characters.": {}, - "Put each assignment or table header on its own line.": {}, - "Expected a key, like `gap` or `\"display name\"`.": {}, - "This value is nested too deeply; use fewer than 128 levels.": {}, - "Inline tables cannot end with a trailing comma.": {}, - "Dates and times are not supported in Tessera config; quote this value to use it as text.": {}, - "This integer is outside the signed 64-bit range.": {}, - "This floating-point number is too large; use `inf` only when infinity is intended.": {}, - "Expected a string, number, boolean, array, or inline table; text needs quotes.": {}, - "Expected a quoted string.": {}, - "Keys must use single-line strings.": {}, - "Too many closing quotes; escape quotes inside the string.": {}, - "A line continuation needs a newline after the backslash.": {}, - "Single-line strings cannot contain a newline.": {}, - "Strings cannot contain unescaped control characters.": {}, - "This string is missing its closing quote.": {}, - "This escape sequence is incomplete.": {}, - "A Unicode escape needs four or eight hexadecimal digits.": {}, - "This Unicode escape is not a valid Unicode scalar.": {}, - "Unknown escape sequence; use `\\\\` for a literal backslash.": {}, - "`%@` was already defined at line %lld, column %lld.": {}, - "A dotted key cannot extend a value or an inline table.": {}, - "A dotted key cannot redefine a table declared by a header.": {}, - "A table header cannot extend a value or an inline table.": {}, - "This array of tables has no current table.": {}, - "Choose a value or a new table key, not a table header or an array index.": {}, - "Add a value inside an existing table before editing this path.": {} + "line %lld, column %lld: %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "line %lld, column %lld: %@" + } + } + } + }, + "Expected `%@` here.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Expected `%@` here." + } + } + } + }, + "Use a newline or a CRLF pair, not a bare carriage return.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Use a newline or a CRLF pair, not a bare carriage return." + } + } + } + }, + "Comments cannot contain control characters.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Comments cannot contain control characters." + } + } + } + }, + "Put each assignment or table header on its own line.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Put each assignment or table header on its own line." + } + } + } + }, + "Expected a key, like `gap` or `\"display name\"`.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Expected a key, like `gap` or `\"display name\"`." + } + } + } + }, + "This value is nested too deeply; use fewer than 128 levels.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This value is nested too deeply; use fewer than 128 levels." + } + } + } + }, + "Inline tables cannot end with a trailing comma.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Inline tables cannot end with a trailing comma." + } + } + } + }, + "Dates and times are not supported in Tessera config; quote this value to use it as text.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Dates and times are not supported in Tessera config; quote this value to use it as text." + } + } + } + }, + "This integer is outside the signed 64-bit range.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This integer is outside the signed 64-bit range." + } + } + } + }, + "This floating-point number is too large; use `inf` only when infinity is intended.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This floating-point number is too large; use `inf` only when infinity is intended." + } + } + } + }, + "Expected a string, number, boolean, array, or inline table; text needs quotes.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Expected a string, number, boolean, array, or inline table; text needs quotes." + } + } + } + }, + "Expected a quoted string.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Expected a quoted string." + } + } + } + }, + "Keys must use single-line strings.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Keys must use single-line strings." + } + } + } + }, + "Too many closing quotes; escape quotes inside the string.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Too many closing quotes; escape quotes inside the string." + } + } + } + }, + "A line continuation needs a newline after the backslash.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A line continuation needs a newline after the backslash." + } + } + } + }, + "Single-line strings cannot contain a newline.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Single-line strings cannot contain a newline." + } + } + } + }, + "Strings cannot contain unescaped control characters.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Strings cannot contain unescaped control characters." + } + } + } + }, + "This string is missing its closing quote.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This string is missing its closing quote." + } + } + } + }, + "This escape sequence is incomplete.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This escape sequence is incomplete." + } + } + } + }, + "A Unicode escape needs four or eight hexadecimal digits.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A Unicode escape needs four or eight hexadecimal digits." + } + } + } + }, + "This Unicode escape is not a valid Unicode scalar.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This Unicode escape is not a valid Unicode scalar." + } + } + } + }, + "Unknown escape sequence; use `\\\\` for a literal backslash.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Unknown escape sequence; use `\\\\` for a literal backslash." + } + } + } + }, + "`%@` was already defined at line %lld, column %lld.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "`%@` was already defined at line %lld, column %lld." + } + } + } + }, + "A dotted key cannot extend a value or an inline table.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A dotted key cannot extend a value or an inline table." + } + } + } + }, + "A dotted key cannot redefine a table declared by a header.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A dotted key cannot redefine a table declared by a header." + } + } + } + }, + "A table header cannot extend a value or an inline table.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A table header cannot extend a value or an inline table." + } + } + } + }, + "This array of tables has no current table.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This array of tables has no current table." + } + } + } + }, + "Choose a value or a new table key, not a table header or an array index.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose a value or a new table key, not a table header or an array index." + } + } + } + }, + "Add a value inside an existing table before editing this path.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Add a value inside an existing table before editing this path." + } + } + } + } }, "version": "1.0" } diff --git a/Sources/TesseraConfig/Resources/Schema.xcstrings b/Sources/TesseraConfig/Resources/Schema.xcstrings new file mode 100644 index 00000000..87354d7f --- /dev/null +++ b/Sources/TesseraConfig/Resources/Schema.xcstrings @@ -0,0 +1,98 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "Invalid general.prefix: %@. For example: prefix = \"ctrl-alt\"." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Invalid general.prefix: %@. For example: prefix = \"ctrl-alt\"." } } } + }, + "Display key “%@” must be a UUID. For example:\n%@" : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Display key “%@” must be a UUID. For example:\n%@" } } } + }, + "Display UUID “%@” is configured twice with different letter casing. Keep one table, for example:\n%@" : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Display UUID “%@” is configured twice with different letter casing. Keep one table, for example:\n%@" } } } + }, + "float-rules must be an array of tables. For example:\n%@" : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "float-rules must be an array of tables. For example:\n%@" } } } + }, + "“%@” needs at least one matcher: bundle-id, title-regex, or role. For example:\n%@" : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” needs at least one matcher: bundle-id, title-regex, or role. For example:\n%@" } } } + }, + "“%@.title-regex” is not a valid regular expression. For example: title-regex = \"^Preferences$\"." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@.title-regex” is not a valid regular expression. For example: title-regex = \"^Preferences$\"." } } } + }, + "“%@” cannot be empty. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” cannot be empty. For example: %@." } } } + }, + "“keybindings.%@” needs a shortcut string or false to disable it. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“keybindings.%@” needs a shortcut string or false to disable it. For example: %@." } } } + }, + "Invalid shortcut for “%@”: %@. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Invalid shortcut for “%@”: %@. For example: %@." } } } + }, + "Inherited defaults “%@” and “%@” both resolve to %@ with this prefix. Change general.prefix or disable one with %@ = false." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Inherited defaults “%@” and “%@” both resolve to %@ with this prefix. Change general.prefix or disable one with %@ = false." } } } + }, + "“%@” uses %@, which conflicts with the inherited default for “%@”. Override that default or disable it with %@ = false." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” uses %@, which conflicts with the inherited default for “%@”. Override that default or disable it with %@ = false." } } } + }, + "“%@” and “%@” both use %@; the earlier binding is at line %lld, column %lld. Assign different shortcuts, or disable one with %@ = false." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” and “%@” both use %@; the earlier binding is at line %lld, column %lld. Assign different shortcuts, or disable one with %@ = false." } } } + }, + "Expected a table for “%@”. For example:\n%@" : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Expected a table for “%@”. For example:\n%@" } } } + }, + "Expected true or false for “%@”. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Expected true or false for “%@”. For example: %@." } } } + }, + "Expected a quoted string for “%@”. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Expected a quoted string for “%@”. For example: %@." } } } + }, + "Expected a whole number for “%@”. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Expected a whole number for “%@”. For example: %@." } } } + }, + "“%@” must be a whole number between %lld and %lld. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” must be a whole number between %lld and %lld. For example: %@." } } } + }, + "Expected a number for “%@”. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Expected a number for “%@”. For example: %@." } } } + }, + "“%@” must be a finite number between %@ and %@. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” must be a finite number between %@ and %@. For example: %@." } } } + }, + "“%@” must be one of %@. For example: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "“%@” must be one of %@. For example: %@." } } } + }, + "Unknown key “%@”. Did you mean “%@”?" : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Unknown key “%@”. Did you mean “%@”?" } } } + }, + "Unknown key “%@”; this setting is ignored." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Unknown key “%@”; this setting is ignored." } } } + }, + "The configuration schema could not be encoded: %@." : { + "extractionState" : "manual", + "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "The configuration schema could not be encoded: %@." } } } + } + }, + "version" : "1.0" +} diff --git a/Sources/TesseraConfig/Resources/Store.xcstrings b/Sources/TesseraConfig/Resources/Store.xcstrings new file mode 100644 index 00000000..2877b1dc --- /dev/null +++ b/Sources/TesseraConfig/Resources/Store.xcstrings @@ -0,0 +1,116 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "Configuration validation did not produce a usable configuration." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Configuration validation did not produce a usable configuration." + } + } + } + }, + "Configuration watching stopped unexpectedly: %@" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Configuration watching stopped unexpectedly: %@" + } + } + } + }, + "Could not parse the configuration: %@" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Could not parse the configuration: %@" + } + } + } + }, + "Could not read the configuration file at %@: %@" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Could not read the configuration file at %@: %@" + } + } + } + }, + "No configuration file exists at %@. Using built-in defaults until a valid file is available." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "No configuration file exists at %@. Using built-in defaults until a valid file is available." + } + } + } + }, + "The configuration file at %@ is missing. Keeping the last good configuration." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The configuration file at %@ is missing. Keeping the last good configuration." + } + } + } + }, + "The configuration file at %@ is not valid UTF-8. Save it as UTF-8 and try again." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The configuration file at %@ is not valid UTF-8. Save it as UTF-8 and try again." + } + } + } + }, + "The configuration path is not a regular file: %@" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The configuration path is not a regular file: %@" + } + } + } + }, + "The configuration polling interval must be greater than zero." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The configuration polling interval must be greater than zero." + } + } + } + }, + "The configuration URL must point to a local file: %@" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The configuration URL must point to a local file: %@" + } + } + } + } + }, + "version" : "1.0" +} diff --git a/Sources/TesseraConfig/Resources/en.lproj/Keybindings.strings b/Sources/TesseraConfig/Resources/en.lproj/Keybindings.strings new file mode 100644 index 00000000..179ca0a6 --- /dev/null +++ b/Sources/TesseraConfig/Resources/en.lproj/Keybindings.strings @@ -0,0 +1,20 @@ + + + + + A key chord cannot be empty. + A key chord cannot be empty. + A key chord contains an empty modifier. + A key chord contains an empty modifier. + A key chord needs a key after its modifiers. + A key chord needs a key after its modifiers. + Key modifiers must use only the five supported bits. + Key modifiers must use only the five supported bits. + Modifier ‘%@’ repeats a modifier already present. + Modifier ‘%@’ repeats a modifier already present. + Unknown ANSI key ‘%@’. Use a letter, digit, punctuation, named key, or f1–f20. + Unknown ANSI key ‘%@’. Use a letter, digit, punctuation, named key, or f1–f20. + Unknown modifier ‘%@’. Use ctrl, alt (or opt), cmd, shift, fn, or hyper. + Unknown modifier ‘%@’. Use ctrl, alt (or opt), cmd, shift, fn, or hyper. + + diff --git a/Sources/TesseraConfig/Resources/en.lproj/Parser.strings b/Sources/TesseraConfig/Resources/en.lproj/Parser.strings new file mode 100644 index 00000000..5d5978ae --- /dev/null +++ b/Sources/TesseraConfig/Resources/en.lproj/Parser.strings @@ -0,0 +1,66 @@ + + + + + A Unicode escape needs four or eight hexadecimal digits. + A Unicode escape needs four or eight hexadecimal digits. + A dotted key cannot extend a value or an inline table. + A dotted key cannot extend a value or an inline table. + A dotted key cannot redefine a table declared by a header. + A dotted key cannot redefine a table declared by a header. + A line continuation needs a newline after the backslash. + A line continuation needs a newline after the backslash. + A table header cannot extend a value or an inline table. + A table header cannot extend a value or an inline table. + Add a value inside an existing table before editing this path. + Add a value inside an existing table before editing this path. + Choose a value or a new table key, not a table header or an array index. + Choose a value or a new table key, not a table header or an array index. + Comments cannot contain control characters. + Comments cannot contain control characters. + Dates and times are not supported in Tessera config; quote this value to use it as text. + Dates and times are not supported in Tessera config; quote this value to use it as text. + Expected `%@` here. + Expected `%@` here. + Expected a key, like `gap` or `"display name"`. + Expected a key, like `gap` or `"display name"`. + Expected a quoted string. + Expected a quoted string. + Expected a string, number, boolean, array, or inline table; text needs quotes. + Expected a string, number, boolean, array, or inline table; text needs quotes. + Inline tables cannot end with a trailing comma. + Inline tables cannot end with a trailing comma. + Keys must use single-line strings. + Keys must use single-line strings. + Put each assignment or table header on its own line. + Put each assignment or table header on its own line. + Single-line strings cannot contain a newline. + Single-line strings cannot contain a newline. + Strings cannot contain unescaped control characters. + Strings cannot contain unescaped control characters. + This Unicode escape is not a valid Unicode scalar. + This Unicode escape is not a valid Unicode scalar. + This array of tables has no current table. + This array of tables has no current table. + This escape sequence is incomplete. + This escape sequence is incomplete. + This floating-point number is too large; use `inf` only when infinity is intended. + This floating-point number is too large; use `inf` only when infinity is intended. + This integer is outside the signed 64-bit range. + This integer is outside the signed 64-bit range. + This string is missing its closing quote. + This string is missing its closing quote. + This value is nested too deeply; use fewer than 128 levels. + This value is nested too deeply; use fewer than 128 levels. + Too many closing quotes; escape quotes inside the string. + Too many closing quotes; escape quotes inside the string. + Unknown escape sequence; use `\\` for a literal backslash. + Unknown escape sequence; use `\\` for a literal backslash. + Use a newline or a CRLF pair, not a bare carriage return. + Use a newline or a CRLF pair, not a bare carriage return. + `%@` was already defined at line %lld, column %lld. + `%@` was already defined at line %lld, column %lld. + line %lld, column %lld: %@ + line %lld, column %lld: %@ + + diff --git a/Sources/TesseraConfig/Resources/en.lproj/Schema.strings b/Sources/TesseraConfig/Resources/en.lproj/Schema.strings new file mode 100644 index 00000000..016a168c --- /dev/null +++ b/Sources/TesseraConfig/Resources/en.lproj/Schema.strings @@ -0,0 +1,62 @@ + + + + + Display UUID “%@” is configured twice with different letter casing. Keep one table, for example: +%@ + Display UUID “%@” is configured twice with different letter casing. Keep one table, for example: +%@ + Display key “%@” must be a UUID. For example: +%@ + Display key “%@” must be a UUID. For example: +%@ + Expected a number for “%@”. For example: %@. + Expected a number for “%@”. For example: %@. + Expected a quoted string for “%@”. For example: %@. + Expected a quoted string for “%@”. For example: %@. + Expected a table for “%@”. For example: +%@ + Expected a table for “%@”. For example: +%@ + Expected a whole number for “%@”. For example: %@. + Expected a whole number for “%@”. For example: %@. + Expected true or false for “%@”. For example: %@. + Expected true or false for “%@”. For example: %@. + Inherited defaults “%@” and “%@” both resolve to %@ with this prefix. Change general.prefix or disable one with %@ = false. + Inherited defaults “%@” and “%@” both resolve to %@ with this prefix. Change general.prefix or disable one with %@ = false. + Invalid general.prefix: %@. For example: prefix = "ctrl-alt". + Invalid general.prefix: %@. For example: prefix = "ctrl-alt". + Invalid shortcut for “%@”: %@. For example: %@. + Invalid shortcut for “%@”: %@. For example: %@. + The configuration schema could not be encoded: %@. + The configuration schema could not be encoded: %@. + Unknown key “%@”. Did you mean “%@”? + Unknown key “%@”. Did you mean “%@”? + Unknown key “%@”; this setting is ignored. + Unknown key “%@”; this setting is ignored. + float-rules must be an array of tables. For example: +%@ + float-rules must be an array of tables. For example: +%@ + “%@.title-regex” is not a valid regular expression. For example: title-regex = "^Preferences$". + “%@.title-regex” is not a valid regular expression. For example: title-regex = "^Preferences$". + “%@” and “%@” both use %@; the earlier binding is at line %lld, column %lld. Assign different shortcuts, or disable one with %@ = false. + “%@” and “%@” both use %@; the earlier binding is at line %lld, column %lld. Assign different shortcuts, or disable one with %@ = false. + “%@” cannot be empty. For example: %@. + “%@” cannot be empty. For example: %@. + “%@” must be a finite number between %@ and %@. For example: %@. + “%@” must be a finite number between %@ and %@. For example: %@. + “%@” must be a whole number between %lld and %lld. For example: %@. + “%@” must be a whole number between %lld and %lld. For example: %@. + “%@” must be one of %@. For example: %@. + “%@” must be one of %@. For example: %@. + “%@” needs at least one matcher: bundle-id, title-regex, or role. For example: +%@ + “%@” needs at least one matcher: bundle-id, title-regex, or role. For example: +%@ + “%@” uses %@, which conflicts with the inherited default for “%@”. Override that default or disable it with %@ = false. + “%@” uses %@, which conflicts with the inherited default for “%@”. Override that default or disable it with %@ = false. + “keybindings.%@” needs a shortcut string or false to disable it. For example: %@. + “keybindings.%@” needs a shortcut string or false to disable it. For example: %@. + + diff --git a/Sources/TesseraConfig/Resources/en.lproj/Store.strings b/Sources/TesseraConfig/Resources/en.lproj/Store.strings new file mode 100644 index 00000000..1b1d1a90 --- /dev/null +++ b/Sources/TesseraConfig/Resources/en.lproj/Store.strings @@ -0,0 +1,26 @@ + + + + + Configuration validation did not produce a usable configuration. + Configuration validation did not produce a usable configuration. + Configuration watching stopped unexpectedly: %@ + Configuration watching stopped unexpectedly: %@ + Could not parse the configuration: %@ + Could not parse the configuration: %@ + Could not read the configuration file at %@: %@ + Could not read the configuration file at %@: %@ + No configuration file exists at %@. Using built-in defaults until a valid file is available. + No configuration file exists at %@. Using built-in defaults until a valid file is available. + The configuration URL must point to a local file: %@ + The configuration URL must point to a local file: %@ + The configuration file at %@ is missing. Keeping the last good configuration. + The configuration file at %@ is missing. Keeping the last good configuration. + The configuration file at %@ is not valid UTF-8. Save it as UTF-8 and try again. + The configuration file at %@ is not valid UTF-8. Save it as UTF-8 and try again. + The configuration path is not a regular file: %@ + The configuration path is not a regular file: %@ + The configuration polling interval must be greater than zero. + The configuration polling interval must be greater than zero. + + diff --git a/Sources/TesseraConfig/TOMLDocument.swift b/Sources/TesseraConfig/TOMLDocument.swift index 22132677..b12bddb8 100644 --- a/Sources/TesseraConfig/TOMLDocument.swift +++ b/Sources/TesseraConfig/TOMLDocument.swift @@ -47,16 +47,23 @@ public struct TOMLDocument: Sendable { try replace(range.start.offset.. String? in + guard case .key(let key) = component else { return nil } + return TOMLWriter.quote(key) + } + guard keys.count == suffix.count else { break } let insertion = parentRange.end.offset - 1 let separator = entries.isEmpty ? "" : ", " - try replace(insertion.. 1) + } + + @Test func initiallyInvalidSchemaKeepsDefaultsAndValidatorDiagnostics() async throws { + let store = ConfigStore() + let source = "[motion]\nspeed = -1\n" + let expected = ConfigValidator.validate(try TOMLDocument(parsing: source)).diagnostics + let snapshot = await store.load(source: source) + #expect(snapshot.activeConfiguration == .defaults) + #expect(snapshot.activeSource == .defaults) + #expect(snapshot.lastGoodDocument == nil) + #expect(snapshot.loadState == .rejected) + #expect(snapshot.diagnostics == expected) + #expect(snapshot.diagnostics.first?.location.line == 2) + } + + @Test(arguments: ["[layout]\nratio =\n", "[layout]\nratio = 8\n"]) + func rejectedSourceKeepsTheLastGoodConfigurationAndDocument(invalid: String) async { + let store = ConfigStore() + let source = "# Original formatting\n[layout]\nratio=0.6\n" + let good = await store.load(source: source) + let rejected = await store.load(source: invalid) + #expect(rejected.activeConfiguration == good.activeConfiguration) + #expect(rejected.activeSource == good.activeSource) + #expect(rejected.lastGoodDocument?.render() == source) + #expect(rejected.loadState == .rejected) + #expect(rejected.diagnostics.contains { $0.severity == .error }) + } + + @Test func validConfigurationWithWarningsStillBecomesLastGood() async { + let store = ConfigStore() + let source = "unknown-setting = true\n[layout]\nratio = 0.6\n" + let snapshot = await store.load(source: source) + #expect(snapshot.loadState == .loaded) + #expect(snapshot.activeConfiguration.layout.global.ratio == 0.6) + #expect(snapshot.lastGoodDocument?.render() == source) + #expect(snapshot.diagnostics.count == 1) + #expect(snapshot.diagnostics.first?.severity == .warning) + } + + @Test func goodSourceRecoversAndClearsOldDiagnostics() async { + let store = ConfigStore() + await store.load(source: "[motion]\nspeed = -1\n") + let source = "[motion]\nenabled = false\n" + let recovered = await store.load(source: source) + #expect(recovered.loadState == .loaded) + #expect(!recovered.activeConfiguration.motion.enabled) + #expect(recovered.lastGoodDocument?.render() == source) + #expect(recovered.diagnostics.isEmpty) + } + + @Test func missingInitialFileReportsDefaultsWithoutCreatingAFile() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let store = ConfigStore(fileURL: fixture.fileURL) + let snapshot = await store.reload() + #expect(snapshot.loadState == .missingFileUsingDefaults) + #expect(snapshot.activeConfiguration == .defaults) + #expect(snapshot.activeSource == .defaults) + #expect(snapshot.attemptedSource == .file(fixture.fileURL)) + #expect(snapshot.lastGoodDocument == nil) + #expect(snapshot.diagnostics.first?.severity == .warning) + #expect(snapshot.diagnostics.first?.location == SourceLocation()) + #expect(!FileManager.default.fileExists(atPath: fixture.fileURL.path)) + } + + @Test func utf8FileLoadingReportsItsOrigin() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let source = "# 配置\n[layout]\nratio = 0.6\n" + try fixture.write(source) + let store = ConfigStore(fileURL: fixture.fileURL) + let snapshot = await store.reload() + #expect(snapshot.activeSource == .file(fixture.fileURL)) + #expect(snapshot.activeConfiguration.layout.global.ratio == 0.6) + #expect(snapshot.lastGoodDocument?.render() == source) + #expect(snapshot.diagnostics.isEmpty) + } + + @Test func initialInvalidFileReportsProblemsWithoutBecomingActive() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try fixture.write("[motion]\nspeed = -1\n") + let store = ConfigStore(fileURL: fixture.fileURL) + let snapshot = await store.reload() + #expect(snapshot.loadState == .rejected) + #expect(snapshot.activeConfiguration == .defaults) + #expect(snapshot.activeSource == .defaults) + #expect(snapshot.attemptedSource == .file(fixture.fileURL)) + #expect(snapshot.lastGoodDocument == nil) + #expect(snapshot.diagnostics.first?.location.line == 2) + } + + @Test func invalidUTF8IsRejectedWithoutLossyDecoding() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try fixture.write("[layout]\nratio = 0.6\n") + let store = ConfigStore(fileURL: fixture.fileURL) + let good = await store.reload() + try Data([0xFF, 0xFE, 0x61]).write(to: fixture.fileURL) + let bad = await store.reload() + #expect(bad.loadState == .rejected) + #expect(bad.activeConfiguration == good.activeConfiguration) + #expect(bad.lastGoodDocument?.source == good.lastGoodDocument?.source) + #expect(bad.activeSource == good.activeSource) + #expect(bad.diagnostics.first?.severity == .error) + #expect(bad.diagnostics.first?.location == SourceLocation()) + #expect(bad.diagnostics.first?.message.contains("UTF-8") == true) + } + + @Test func deletingAFileWhoseValuesEqualDefaultsStillPreservesItsDocument() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let source = "# Intentionally use the defaults.\n" + try fixture.write(source) + let store = ConfigStore(fileURL: fixture.fileURL) + await store.reload() + try FileManager.default.removeItem(at: fixture.fileURL) + let missing = await store.reload() + #expect(missing.activeConfiguration == .defaults) + #expect(missing.activeSource == .file(fixture.fileURL)) + #expect(missing.lastGoodDocument?.source == source) + #expect(missing.loadState == .rejected) + #expect(missing.diagnostics.first?.severity == .error) + } + + @Test func directoryReadFailureKeepsLastGoodAndIdentifiesTheAttemptedFile() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try FileManager.default.createDirectory(at: fixture.fileURL, withIntermediateDirectories: false) + let store = ConfigStore(fileURL: fixture.fileURL) + let good = await store.load(source: "[motion]\nenabled = false\n") + let failed = await store.reload() + #expect(failed.loadState == .rejected) + #expect(failed.activeConfiguration == good.activeConfiguration) + #expect(failed.lastGoodDocument?.source == good.lastGoodDocument?.source) + #expect(failed.activeSource == .sourceText) + #expect(failed.attemptedSource == .file(fixture.fileURL)) + #expect(failed.diagnostics.first?.severity == .error) + #expect(failed.diagnostics.first?.location == SourceLocation()) + } + + @Test func unreadableFileReportsAnIOErrorAndRecovers() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try fixture.write("[layout]\nratio = 0.6\n") + let store = ConfigStore(fileURL: fixture.fileURL) + let good = await store.reload() + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: fixture.fileURL.path) + let failed = await store.reload() + try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: fixture.fileURL.path) + #expect(failed.loadState == .rejected) + #expect(failed.activeConfiguration == good.activeConfiguration) + #expect(failed.lastGoodDocument?.source == good.lastGoodDocument?.source) + #expect(failed.diagnostics.first?.severity == .error) + let recovered = await store.reload() + #expect(recovered.loadState == .loaded) + #expect(recovered.diagnostics.isEmpty) + } + + @Test func nonFileURLsAreRejectedWithoutNetworkAccess() async throws { + let url = try #require(URL(string: "https://example.invalid/tessera.toml")) + let store = ConfigStore(fileURL: url) + let snapshot = await store.reload() + #expect(snapshot.loadState == .rejected) + #expect(snapshot.activeConfiguration == .defaults) + #expect(snapshot.diagnostics.first?.severity == .error) + } + + @Test func symbolicLinksLoadTheirTarget() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let target = fixture.directory.appendingPathComponent("target.toml") + let source = "[motion]\nenabled = false\n" + try Data(source.utf8).write(to: target) + try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) + let store = ConfigStore(fileURL: fixture.fileURL) + let snapshot = await store.reload() + #expect(snapshot.loadState == .loaded) + #expect(snapshot.activeSource == .file(fixture.fileURL)) + #expect(snapshot.lastGoodDocument?.source == source) + } + + @Test func watcherFollowsAtomicReplacement() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let original = "[layout]\nratio = 0.6\n" + let replacement = "[layout]\nratio = 0.7\n" + try fixture.write(original) + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } + let stream = await store.updates() + var iterator = stream.makeAsyncIterator() + #expect(await iterator.next()?.lastGoodDocument?.source == original) + try fixture.write(replacement, atomic: true) + let snapshot = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } + #expect(snapshot.activeConfiguration.layout.global.ratio == 0.7) + #expect(snapshot.loadState == .loaded) + #expect(await iterator.next()?.lastGoodDocument?.source == replacement) + } + } + + @Test func watcherDetectsSameSizeInPlaceWritesWithRestoredModificationTime() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let original = "[layout]\nratio = 0.6\n" + let replacement = "[layout]\nratio = 0.7\n" + #expect(original.utf8.count == replacement.utf8.count) + try fixture.write(original) + let values = try fixture.fileURL.resourceValues(forKeys: [.contentModificationDateKey]) + let modified = try #require(values.contentModificationDate) + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } + try fixture.writeInPlace(replacement) + try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: fixture.fileURL.path) + let snapshot = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } + #expect(snapshot.activeConfiguration.layout.global.ratio == 0.7) + } + } + + @Test func watcherRecoversFromBadSyntaxToGoodContent() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let original = "# Last good\n[layout]\nratio = 0.6\n" + try fixture.write(original) + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == original } + try fixture.write("[layout]\nratio =\n", atomic: true) + let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } + #expect(failed.lastGoodDocument?.source == original) + #expect(failed.activeConfiguration.layout.global.ratio == 0.6) + #expect(failed.diagnostics.first?.location.line == 2) + let replacement = "# Recovered\n[layout]\nratio = 0.8\n" + try fixture.write(replacement, atomic: true) + let recovered = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } + #expect(recovered.loadState == .loaded) + #expect(recovered.diagnostics.isEmpty) + } + } + + @Test func watcherFollowsDeletionAndRecreationOfTheParentDirectory() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let source = "[layout]\nratio = 0.6\n" + try fixture.write(source) + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + try FileManager.default.removeItem(at: fixture.directory) + let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } + #expect(missing.lastGoodDocument?.source == source) + #expect(missing.activeSource == .file(fixture.fileURL)) + #expect(missing.diagnostics.first?.severity == .error) + try FileManager.default.createDirectory(at: fixture.directory, withIntermediateDirectories: true) + try fixture.write(source) + let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded } + #expect(recreated.lastGoodDocument?.source == source) + #expect(recreated.diagnostics.isEmpty) + } + } + + @Test func watcherLoadsAFileCreatedAfterAnInitialMissingFile() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try await fixture.withWatchingStore { store in + let initial = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } + #expect(initial.activeSource == .defaults) + try fixture.write("[motion]\nenabled = false\n") + let loaded = try await waitForSnapshot(store) { $0.loadState == .loaded } + #expect(!loaded.activeConfiguration.motion.enabled) + #expect(loaded.diagnostics.isEmpty) + } + } + + @Test func watcherRecoversFromAFileReadFailure() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try FileManager.default.createDirectory(at: fixture.fileURL, withIntermediateDirectories: false) + try await fixture.withWatchingStore { store in + let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } + #expect(failed.activeSource == .defaults) + try FileManager.default.removeItem(at: fixture.fileURL) + try fixture.write("[layout]\nratio = 0.6\n") + let loaded = try await waitForSnapshot(store) { $0.loadState == .loaded } + #expect(loaded.activeConfiguration.layout.global.ratio == 0.6) + } + } + + @Test func stoppedWatcherCannotPublishAndCanRestart() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let original = "[layout]\nratio = 0.6\n" + let replacement = "[layout]\nratio = 0.7\n" + try fixture.write(original) + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + await store.stopWatching() + await store.stopWatching() + #expect(await !store.isWatching) + try fixture.write(replacement) + try await Task.sleep(for: .milliseconds(80)) + #expect(await store.snapshot.lastGoodDocument?.source == original) + try await store.startWatching(pollInterval: .milliseconds(15)) + try await store.startWatching(pollInterval: .milliseconds(15)) + let restarted = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } + #expect(restarted.diagnostics.isEmpty) + } + } + + @Test func cancellationInterruptsALongPollingSleep() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let store = ConfigStore(fileURL: fixture.fileURL) + try await store.startWatching(pollInterval: .seconds(60)) + _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } + let clock = ContinuousClock() + let start = clock.now + await store.stopWatching() + #expect(start.duration(to: clock.now) < .seconds(1)) + #expect(await !store.isWatching) + } + + @Test(arguments: [Duration.zero, .milliseconds(-1)]) + func nonpositivePollingIntervalsAreRejected(interval: Duration) async throws { + let store = ConfigStore() + do { + try await store.startWatching(pollInterval: interval) + Issue.record("An invalid polling interval was accepted.") + await store.stopWatching() + } catch let diagnostic as ConfigDiagnostic { + #expect(diagnostic.severity == .error) + } + #expect(await !store.isWatching) + } + + @Test func updatesIncludeCurrentStateAndRejectedLoads() async throws { + let store = ConfigStore() + let stream = await store.updates() + var iterator = stream.makeAsyncIterator() + #expect(await iterator.next()?.loadState == .notLoaded) + let source = "[layout]\nratio = 0.6\n" + await store.load(source: source) + #expect(await iterator.next()?.lastGoodDocument?.source == source) + await store.load(source: "[layout]\nratio =\n") + let rejected = try #require(await iterator.next()) + #expect(rejected.loadState == .rejected) + #expect(rejected.lastGoodDocument?.source == source) + #expect(!rejected.diagnostics.isEmpty) + } + + @Test func slowUpdateConsumersReceiveOnlyTheNewestSnapshot() async throws { + let store = ConfigStore() + let stream = await store.updates() + await store.load(source: "[layout]\nratio = 0.6\n") + await store.load(source: "[layout]\nratio = 0.7\n") + var iterator = stream.makeAsyncIterator() + let newest = try #require(await iterator.next()) + #expect(newest.activeConfiguration.layout.global.ratio == 0.7) + } + + @Test func cancelingOneUpdateConsumerDoesNotAffectOthers() async { + let store = ConfigStore() + let canceledStream = await store.updates() + let survivingStream = await store.updates() + let consumer = Task { + for await _ in canceledStream {} + } + consumer.cancel() + await consumer.value + await store.load(source: "[motion]\nenabled = false\n") + var iterator = survivingStream.makeAsyncIterator() + #expect(await iterator.next()?.activeConfiguration.motion.enabled == false) + } + + @Test func watcherDoesNotRetainTheStoreDuringSleep() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + var store: ConfigStore? = ConfigStore(fileURL: fixture.fileURL) + weak let weakStore = store + if let store { + try await store.startWatching(pollInterval: .seconds(60)) + _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } + } + store = nil + for _ in 0..<100 { + if weakStore == nil { break } + try await Task.sleep(for: .milliseconds(10)) + } + #expect(weakStore == nil) + } + + @Test func releasingStoreFinishesItsUpdateStreams() async throws { + var store: ConfigStore? = ConfigStore() + weak let weakStore = store + let stream = try #require(await store?.updates()) + var iterator = stream.makeAsyncIterator() + #expect(await iterator.next()?.loadState == .notLoaded) + store = nil + #expect(weakStore == nil) + #expect(await iterator.next() == nil) + } + + @Test func watcherSurfacesUnexpectedSleepFailure() async throws { + let failures = WatcherFailureRecorder() + let watcher = ConfigFileWatcher( + pollInterval: .seconds(1), sleep: { _ in throw StoreTestError.injected }, + poll: { true }, failed: { await failures.append($0) } + ) + await watcher.waitUntilFinished() + let diagnostics = await failures.diagnostics + #expect(diagnostics.count == 1) + #expect(diagnostics.first?.severity == .error) + #expect(diagnostics.first?.message.isEmpty == false) + } + + @Test func watcherCancellationIsNotReportedAsAFailure() async { + let failures = WatcherFailureRecorder() + let watcher = ConfigFileWatcher( + pollInterval: .seconds(1), sleep: { _ in throw CancellationError() }, + poll: { true }, failed: { await failures.append($0) } + ) + await watcher.waitUntilFinished() + #expect(await failures.diagnostics.isEmpty) + } +} + +private enum StoreTestError: Error { + case timedOut + case injected +} + +private actor WatcherFailureRecorder { + private(set) var diagnostics: [ConfigDiagnostic] = [] + + func append(_ diagnostic: ConfigDiagnostic) { + diagnostics.append(diagnostic) + } +} + +private struct TemporaryConfigFile: Sendable { + let directory: URL + var fileURL: URL { directory.appendingPathComponent("tessera.toml") } + + init() throws { + directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + + func write(_ text: String, atomic: Bool = false) throws { + try Data(text.utf8).write(to: fileURL, options: atomic ? .atomic : []) + } + + func writeInPlace(_ text: String) throws { + let handle = try FileHandle(forWritingTo: fileURL) + defer { + do { + try handle.close() + } catch { + Issue.record(error) + } + } + try handle.write(contentsOf: Data(text.utf8)) + try handle.truncate(atOffset: UInt64(text.utf8.count)) + } + + func withWatchingStore(_ body: @Sendable (ConfigStore) async throws -> Void) async throws { + let store = ConfigStore(fileURL: fileURL) + try await store.startWatching(pollInterval: .milliseconds(15)) + do { + try await body(store) + } catch { + await store.stopWatching() + throw error + } + await store.stopWatching() + } + + func remove() { + do { + try FileManager.default.removeItem(at: directory) + } catch { + Issue.record(error) + } + } +} + +private func waitForSnapshot( + _ store: ConfigStore, matching predicate: @Sendable (ConfigSnapshot) -> Bool +) async throws -> ConfigSnapshot { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: .seconds(3)) + repeat { + let snapshot = await store.snapshot + if predicate(snapshot) { return snapshot } + try await Task.sleep(for: .milliseconds(10)) + } while clock.now < deadline + throw StoreTestError.timedOut +} diff --git a/Tests/TesseraConfigTests/ConfigValidationTests.swift b/Tests/TesseraConfigTests/ConfigValidationTests.swift new file mode 100644 index 00000000..e4ff8e41 --- /dev/null +++ b/Tests/TesseraConfigTests/ConfigValidationTests.swift @@ -0,0 +1,813 @@ +import Foundation +import Testing + +@testable import TesseraConfig + +@Suite("Configuration validation") +struct ConfigValidationTests { + private let displayID = "A1B2C3D4-1234-5678-9ABC-0123456789AB" + + @Test func emptyDocumentUsesDefaults() throws { + let result = try validate("") + #expect(result.configuration == .defaults) + #expect(result.diagnostics.isEmpty) + } + + @Test func explicitVersionOneUsesDefaults() throws { + #expect(try configuration("version = 1") == .defaults) + } + + @Test func defaultPrefix() { + #expect(TesseraConfiguration.defaults.general.prefix == [.ctrl, .alt]) + } + + @Test func defaultLaunchAtLogin() { + #expect(!TesseraConfiguration.defaults.general.launchAtLogin) + } + + @Test func defaultLayout() { + let layout = TesseraConfiguration.defaults.layout.global + #expect(layout.defaultLayout == .grid) + #expect(layout.ratio == 0.5) + #expect(layout.windowCap == 0) + } + + @Test func defaultGaps() { + #expect(TesseraConfiguration.defaults.layout.global.gaps == LayoutGaps(inner: 8, outer: 8)) + } + + @Test func defaultReservedEdges() { + #expect( + TesseraConfiguration.defaults.layout.global.reserved == ReservedEdges(top: 0, right: 0, bottom: 0, left: 0)) + } + + @Test func defaultMotion() { + #expect(TesseraConfiguration.defaults.motion == MotionConfiguration(enabled: true, speed: 1, whimsy: .playful)) + } + + @Test func defaultAccessibility() { + #expect(!TesseraConfiguration.defaults.accessibility.announceLayoutChanges) + } + + @Test func defaultCollections() { + #expect(TesseraConfiguration.defaults.layout.displays.isEmpty) + #expect(TesseraConfiguration.defaults.floatRules.isEmpty) + } + + @Test func defaultsContainEveryCommand() { + let bindings = TesseraConfiguration.defaults.keybindings + #expect(bindings == DefaultKeybindings.bindings()) + #expect(Set(bindings.keys) == Set(ConfigCommand.allCases)) + } + + @Test func defaultsHaveNoDuplicateChords() { + let bindings = TesseraConfiguration.defaults.keybindings + #expect(Set(bindings.values).count == bindings.count) + } + + @Test func customInitializerGeneratesPrefixDefaults() { + let value = TesseraConfiguration(general: GeneralConfiguration(prefix: .fn)) + #expect(value.keybindings == DefaultKeybindings.bindings(prefix: .fn)) + } + + @Test func customInitializerCanRemoveEveryBinding() { + #expect(TesseraConfiguration(keybindings: [:]).keybindings.isEmpty) + } + + @Test(arguments: ["0", "2", "-1", "9223372036854775807", "1.0", "true", "\"1\"", "[]", "{}"]) + func invalidVersions(_ value: String) throws { + let result = try validate("version = \(value)") + #expect(result.configuration == nil) + let error = try #require(result.diagnostics.first) + #expect(error.severity == .error) + #expect(error.location.line == 1) + #expect(error.location.column == 11) + #expect(error.message.contains("version = 1")) + } + + @Test func launchAtLoginCanBeEnabled() throws { + #expect(try configuration("[general]\nlaunch-at-login = true").general.launchAtLogin) + } + + @Test func prefixReplacesOnlyGeneratedDefaults() throws { + let value = try configuration("[general]\nprefix = \"cmd-fn\"") + #expect(value.general.prefix == [.cmd, .fn]) + #expect(value.keybindings == DefaultKeybindings.bindings(prefix: [.cmd, .fn])) + } + + @Test func emptyPrefixIsSupported() throws { + let value = try configuration("[general]\nprefix = \"\"") + #expect(value.general.prefix.isEmpty) + #expect(value.keybindings == DefaultKeybindings.bindings(prefix: [])) + } + + @Test func hyperPrefixIsSupported() throws { + #expect(try configuration("[general]\nprefix = \"hyper\"").general.prefix == .hyper) + } + + @Test func prefixAliasesAreNormalized() throws { + #expect(try configuration("[general]\nprefix = \"CONTROL-OPTION\"").general.prefix == [.ctrl, .alt]) + } + + @Test(arguments: ["\"ctrl-mystery\"", "\"ctrl-ctrl\"", "\"ctrl-a\"", "42", "true"]) + func invalidPrefixes(_ value: String) throws { + let result = try validate("[general]\nprefix = \(value)") + #expect(result.configuration == nil) + #expect(result.diagnostics.contains { $0.message.contains("prefix = \"ctrl-alt\"") }) + } + + @Test func explicitShortcutIsAbsoluteAfterPrefixChange() throws { + let value = try configuration("[general]\nprefix = \"fn\"\n[keybindings]\nfocus-left = \"cmd-f20\"") + #expect(value.keybindings[.focusLeft] == (try KeyChord(parsing: "cmd-f20"))) + #expect(value.keybindings[.focusRight] == DefaultKeybindings.bindings(prefix: .fn)[.focusRight]) + } + + @Test(arguments: ConfigLayout.allCases) + func everyLayoutIsAccepted(_ layout: ConfigLayout) throws { + #expect(try configuration("[layout]\ndefault = \"\(layout.rawValue)\"").layout.global.defaultLayout == layout) + } + + @Test func unknownLayoutIsRejectedWithExample() throws { + let result = try validate("[layout]\ndefault = \"spiral\"") + #expect(result.configuration == nil) + #expect(result.diagnostics.first?.message.contains("\"grid\", \"columns\", \"rows\", \"side\"") == true) + } + + @Test func layoutNamesAreCaseSensitive() throws { + #expect(try validate("[layout]\ndefault = \"Grid\"").configuration == nil) + } + + @Test func ratioCanBeCustomized() throws { + #expect(try configuration("[layout]\nratio = 0.7").layout.global.ratio == 0.7) + } + + @Test func gapsCanBeFractional() throws { + let value = try configuration("[layout.gaps]\ninner = 2.5\nouter = 12") + #expect(value.layout.global.gaps == LayoutGaps(inner: 2.5, outer: 12)) + } + + @Test func reservedEdgesCanBeCustomized() throws { + let value = try configuration("[layout.reserved]\ntop = 1\nright = 2.5\nbottom = 3\nleft = 4.5") + #expect(value.layout.global.reserved == ReservedEdges(top: 1, right: 2.5, bottom: 3, left: 4.5)) + } + + @Test func windowCapCanBeCustomized() throws { + #expect(try configuration("[layout]\nwindow-cap = 12").layout.global.windowCap == 12) + } + + @Test func fractionalWindowCapIsRejected() throws { + #expect(try validate("[layout]\nwindow-cap = 12.5").configuration == nil) + } + + @Test(arguments: numericFields) + func numericBoundsAreInclusive(_ field: NumericField) throws { + #expect(try validate("\(field.path) = \(field.lower)").configuration != nil) + #expect(try validate("\(field.path) = \(field.upper)").configuration != nil) + } + + @Test(arguments: numericFields) + func numericOutOfRangeValuesAreRejected(_ field: NumericField) throws { + for value in [field.below, field.above] { + let result = try validate("\(field.path) = \(value)") + #expect(result.configuration == nil) + let error = try #require(result.diagnostics.first) + #expect(error.message.contains(field.path)) + #expect(error.message.contains("For example:")) + #expect(error.location.column == field.path.count + 4) + } + } + + @Test(arguments: numericFields) + func numericFieldsRejectStrings(_ field: NumericField) throws { + #expect(try validate("\(field.path) = \"2\"").configuration == nil) + } + + @Test(arguments: ["nan", "+nan", "-nan", "inf", "+inf", "-inf"]) + func nonFiniteNumbersAreRejected(_ number: String) throws { + let result = try validate("motion.speed = \(number)") + #expect(result.configuration == nil) + #expect(result.diagnostics.first?.message.contains("finite number") == true) + } + + @Test func omittedDisplayValuesInheritGlobalValues() throws { + let value = try configuration( + """ + [layout] + default = "side" + ratio = 0.65 + window-cap = 9 + [layout.gaps] + inner = 11 + outer = 13 + [layout.reserved] + top = 17 + [layout.displays."\(displayID)"] + """ + ) + let id = try #require(UUID(uuidString: displayID)) + #expect(value.layout.displays[id] == value.layout.global) + } + + @Test func displayOverrideDoesNotChangeGlobalValues() throws { + let value = try configuration( + "[layout.displays.\"\(displayID)\"]\nratio = 0.8\ndefault = \"rows\"\nwindow-cap = 2") + let id = try #require(UUID(uuidString: displayID)) + #expect(value.layout.displays[id]?.ratio == 0.8) + #expect(value.layout.displays[id]?.defaultLayout == .rows) + #expect(value.layout.displays[id]?.windowCap == 2) + #expect(value.layout.global == LayoutValues()) + } + + @Test func displayGapsInheritIndividually() throws { + let value = try configuration( + "[layout.gaps]\ninner = 12\nouter = 18\n[layout.displays.\"\(displayID)\".gaps]\ninner = 3") + let id = try #require(UUID(uuidString: displayID)) + #expect(value.layout.displays[id]?.gaps == LayoutGaps(inner: 3, outer: 18)) + } + + @Test func displayReservedEdgesInheritIndividually() throws { + let value = try configuration( + "[layout.reserved]\ntop = 10\nright = 20\nbottom = 30\nleft = 40\n[layout.displays.\"\(displayID)\".reserved]\nleft = 5" + ) + let id = try #require(UUID(uuidString: displayID)) + #expect(value.layout.displays[id]?.reserved == ReservedEdges(top: 10, right: 20, bottom: 30, left: 5)) + } + + @Test func unknownDisplayUsesGlobalValues() throws { + let value = try configuration("[layout]\nratio = 0.75") + let id = try #require(UUID(uuidString: displayID)) + #expect(value.layout.values(for: id) == value.layout.global) + } + + @Test func configuredDisplayUsesOverride() throws { + let value = try configuration("[layout.displays.\"\(displayID)\"]\nratio = 0.75") + let id = try #require(UUID(uuidString: displayID)) + #expect(value.layout.values(for: id).ratio == 0.75) + } + + @Test func lowercaseDisplayUUIDIsAccepted() throws { + let value = try configuration("[layout.displays.\"\(displayID.lowercased())\"]\nratio = 0.75") + #expect(value.layout.displays.count == 1) + } + + @Test func duplicateUUIDCasingIsRejected() throws { + let result = try validate("[layout.displays.\"\(displayID)\"]\n[layout.displays.\"\(displayID.lowercased())\"]") + #expect(result.configuration == nil) + #expect(result.diagnostics.contains { $0.message.contains("configured twice") && $0.relatedLocation != nil }) + } + + @Test(arguments: ["display-one", "123", "A1B2C3D4123456789ABC0123456789AB", "ZZZZZZZZ-1234-5678-9ABC-0123456789AB"]) + func malformedDisplayUUIDsAreRejected(_ id: String) throws { + let result = try validate("[layout.displays.\"\(id)\"]\nratio = 0.75") + #expect(result.configuration == nil) + #expect(result.diagnostics.first?.message.contains("UUID") == true) + } + + @Test func displayValueMustBeATable() throws { + #expect(try validate("layout.displays.\"\(displayID)\" = 3").configuration == nil) + } + + @Test func displayValuesUseSameLimits() throws { + #expect(try validate("[layout.displays.\"\(displayID)\"]\nratio = 0.99").configuration == nil) + } + + @Test func nestedDisplayOverridesAreUnknown() throws { + let result = try validate("[layout.displays.\"\(displayID)\".displays]") + #expect(result.configuration != nil) + #expect(result.diagnostics.first?.severity == .warning) + } + + @Test func motionCanBeDisabled() throws { + #expect(try configuration("[motion]\nenabled = false").motion.enabled == false) + } + + @Test func integerMotionSpeedIsAccepted() throws { + #expect(try configuration("[motion]\nspeed = 2").motion.speed == 2) + } + + @Test(arguments: ConfigWhimsy.allCases) + func everyWhimsyIsAccepted(_ whimsy: ConfigWhimsy) throws { + #expect(try configuration("[motion]\nwhimsy = \"\(whimsy.rawValue)\"").motion.whimsy == whimsy) + } + + @Test func unknownWhimsyIsRejected() throws { + #expect(try validate("[motion]\nwhimsy = \"maximum\"").configuration == nil) + } + + @Test func announcementCanBeEnabled() throws { + #expect( + try configuration("[accessibility]\nannounce-layout-changes = true").accessibility.announceLayoutChanges) + } + + @Test(arguments: ["general.launch-at-login", "motion.enabled", "accessibility.announce-layout-changes"]) + func booleansRejectStrings(_ path: String) throws { + #expect(try validate("\(path) = \"true\"").configuration == nil) + } + + @Test(arguments: [ + "general", "layout", "layout.gaps", "layout.reserved", "layout.displays", "motion", "keybindings", + "accessibility", + ]) + func sectionsMustBeTables(_ path: String) throws { + let result = try validate("\(path) = []") + #expect(result.configuration == nil) + #expect(result.diagnostics.contains { $0.message.contains("Expected a table") }) + } + + @Test func floatRuleCanMatchBundleID() throws { + #expect( + try configuration("[[float-rules]]\nbundle-id = \"com.example.app\"").floatRules == [ + FloatRule(bundleID: "com.example.app") + ]) + } + + @Test func floatRuleCanMatchTitleRegex() throws { + #expect( + try configuration("[[float-rules]]\ntitle-regex = \"^Preferences$\"").floatRules == [ + FloatRule(titleRegex: "^Preferences$") + ]) + } + + @Test func floatRuleCanMatchRole() throws { + #expect(try configuration("[[float-rules]]\nrole = \"AXDialog\"").floatRules == [FloatRule(role: "AXDialog")]) + } + + @Test func floatRuleCanCombineMatchers() throws { + let value = try configuration( + "[[float-rules]]\nbundle-id = \"com.example.app\"\ntitle-regex = \"Prefs.*\"\nrole = \"AXDialog\"") + #expect(value.floatRules == [FloatRule(bundleID: "com.example.app", titleRegex: "Prefs.*", role: "AXDialog")]) + } + + @Test func multipleFloatRulesPreserveOrder() throws { + let value = try configuration( + "[[float-rules]]\nrole = \"AXDialog\"\n[[float-rules]]\nbundle-id = \"com.example.app\"") + #expect(value.floatRules == [FloatRule(role: "AXDialog"), FloatRule(bundleID: "com.example.app")]) + } + + @Test func emptyFloatRulesArrayIsAccepted() throws { + #expect(try configuration("float-rules = []").floatRules.isEmpty) + } + + @Test func inlineFloatRuleTablesAreAccepted() throws { + #expect(try configuration("float-rules = [{ role = \"AXDialog\" }]").floatRules.count == 1) + } + + @Test func floatRulesMustBeAnArray() throws { + #expect(try validate("[float-rules]\nrole = \"AXDialog\"").configuration == nil) + } + + @Test func floatRuleElementsMustBeTables() throws { + #expect(try validate("float-rules = [1]").configuration == nil) + } + + @Test func floatRuleRequiresMatcher() throws { + let result = try validate("[[float-rules]]") + #expect(result.configuration == nil) + #expect(result.diagnostics.contains { $0.message.contains("at least one matcher") }) + } + + @Test func unknownMatcherDoesNotCountAsMatcher() throws { + let result = try validate("[[float-rules]]\nbundle = \"com.example.app\"") + #expect(result.configuration == nil) + #expect(result.diagnostics.contains { $0.severity == .warning }) + #expect(result.diagnostics.contains { $0.severity == .error }) + } + + @Test(arguments: ["bundle-id", "title-regex", "role"]) + func emptyMatchersAreRejected(_ key: String) throws { + #expect(try validate("[[float-rules]]\n\(key) = \"\"").configuration == nil) + #expect(try validate("[[float-rules]]\n\(key) = \" \"").configuration == nil) + } + + @Test(arguments: ["bundle-id", "title-regex", "role"]) + func matcherTypesAreChecked(_ key: String) throws { + #expect(try validate("[[float-rules]]\n\(key) = 12").configuration == nil) + } + + @Test func invalidRegexReportsValueLocation() throws { + let document = try TOMLDocument(parsing: "[[float-rules]]\ntitle-regex = \"[\"") + let result = ConfigValidator.validate(document) + #expect(result.configuration == nil) + let error = try #require(result.diagnostics.first) + #expect(error.message.contains("regular expression")) + #expect(error.location.line == 2) + #expect(error.location.column == 15) + } + + @Test func validRegexDoesNotTrimMeaningfulWhitespace() throws { + #expect(try configuration("[[float-rules]]\ntitle-regex = \" a \"").floatRules.first?.titleRegex == " a ") + } + + @Test func explicitBindingOverridesDefault() throws { + #expect( + try configuration("[keybindings]\nfocus-left = \"cmd-f20\"").keybindings[.focusLeft] + == (try KeyChord(parsing: "cmd-f20"))) + } + + @Test func falseRemovesBinding() throws { + let value = try configuration("[keybindings]\nfocus-left = false") + #expect(value.keybindings[.focusLeft] == nil) + #expect(value.keybindings.count == ConfigCommand.allCases.count - 1) + } + + @Test(arguments: ConfigCommand.allCases) + func everyCommandCanBeRemoved(_ command: ConfigCommand) throws { + #expect(try configuration("[keybindings]\n\(command.rawValue) = false").keybindings[command] == nil) + } + + @Test(arguments: ConfigCommand.allCases) + func everyCommandCanBeOverridden(_ command: ConfigCommand) throws { + #expect( + try configuration("[keybindings]\n\(command.rawValue) = \"cmd-f20\"").keybindings[command] + == (try KeyChord(parsing: "cmd-f20"))) + } + + @Test func allBindingsCanBeRemoved() throws { + let text = "[keybindings]\n" + ConfigCommand.allCases.map { "\($0.rawValue) = false" }.joined(separator: "\n") + #expect(try configuration(text).keybindings.isEmpty) + } + + @Test(arguments: ["true", "1", "[]", "{}", "\"\"", "\"cmd\"", "\"cmd-notakey\""]) + func invalidBindingValuesAreRejected(_ value: String) throws { + let result = try validate("[keybindings]\nfocus-left = \(value)") + #expect(result.configuration == nil) + #expect(result.diagnostics.contains { $0.message.contains("For example:") }) + } + + @Test func duplicateExplicitBindingsIncludeBothValueLocations() throws { + let document = try TOMLDocument(parsing: "[keybindings]\nfocus-left = \"cmd-f20\"\nfocus-right = \"cmd-f20\"") + let result = ConfigValidator.validate(document) + #expect(result.configuration == nil) + let error = try #require(result.diagnostics.first) + #expect(error.location == document.root["keybindings"]?["focus-right"]?.range.start) + #expect(error.relatedLocation == document.root["keybindings"]?["focus-left"]?.range.start) + #expect(error.message.contains("focus-left")) + #expect(error.message.contains("focus-right")) + #expect(error.message.contains("= false")) + #expect(error.description.contains("line 3, column 15")) + #expect(error.description.contains("line 2, column 14")) + } + + @Test func aliasesResolveBeforeDuplicateCheck() throws { + let result = try validate("[keybindings]\nfocus-left = \"CTRL-OPT-ESC\"\nfocus-right = \"alt-ctrl-escape\"") + #expect(result.configuration == nil) + #expect(result.diagnostics.count == 1) + #expect(result.diagnostics.first?.relatedLocation != nil) + } + + @Test func shiftedPunctuationResolvesBeforeDuplicateCheck() throws { + let result = try validate("[keybindings]\nfocus-left = \"cmd-!\"\nfocus-right = \"cmd-shift-1\"") + #expect(result.configuration == nil) + #expect(result.diagnostics.count == 1) + } + + @Test func inheritedDefaultConflictIsExplicitlyIdentified() throws { + let chord = try #require(DefaultKeybindings.bindings()[.focusRight]) + let document = try TOMLDocument(parsing: "[keybindings]\nfocus-left = \"\(chord.description)\"") + let result = ConfigValidator.validate(document) + #expect(result.configuration == nil) + let error = try #require(result.diagnostics.first) + #expect(error.message.contains("inherited default")) + #expect(error.message.contains("focus-right")) + #expect(error.location == document.root["keybindings"]?["focus-left"]?.range.start) + #expect(error.relatedLocation == document.root.range.start) + } + + @Test func inheritedConflictPointsToChangedPrefix() throws { + let chord = try #require(DefaultKeybindings.bindings(prefix: .fn)[.focusRight]) + let document = try TOMLDocument( + parsing: "[general]\nprefix = \"fn\"\n[keybindings]\nfocus-left = \"\(chord.description)\"") + let result = ConfigValidator.validate(document) + let error = try #require(result.diagnostics.first) + #expect(error.relatedLocation == document.root["general"]?["prefix"]?.range.start) + #expect(error.message.contains("inherited default")) + } + + @Test func disablingInheritedBindingResolvesConflict() throws { + let chord = try #require(DefaultKeybindings.bindings()[.focusRight]) + #expect( + try validate("[keybindings]\nfocus-left = \"\(chord.description)\"\nfocus-right = false").configuration + != nil) + } + + @Test func overridingInheritedBindingResolvesConflict() throws { + let chord = try #require(DefaultKeybindings.bindings()[.focusRight]) + #expect( + try validate("[keybindings]\nfocus-left = \"\(chord.description)\"\nfocus-right = \"cmd-f20\"") + .configuration != nil) + } + + @Test func threeDuplicateBindingsReportEachAdditionalBinding() throws { + let result = try validate( + "[keybindings]\nfocus-left = \"cmd-f20\"\nfocus-right = \"cmd-f20\"\nfocus-up = \"cmd-f20\"") + #expect(result.diagnostics.count == 2) + #expect(result.diagnostics.allSatisfy { $0.relatedLocation?.line == 2 }) + } + + @Test func unknownRootKeyWarnsWithoutRejecting() throws { + let result = try validate("future-feature = true") + #expect(result.configuration == .defaults) + #expect(result.diagnostics.first?.severity == .warning) + } + + @Test func unknownKeyUsesKeyRange() throws { + let document = try TOMLDocument(parsing: "[general]\n launch_at_login = true") + let result = ConfigValidator.validate(document) + #expect(result.configuration != nil) + let warning = try #require(result.diagnostics.first) + #expect(warning.location == document.root["general"]?["launch_at_login"]?.keyRange?.start) + #expect(warning.location.column == 3) + } + + @Test func nearbyUnknownKeyGetsSuggestion() throws { + let result = try validate("[general]\nlaunch-at-logn = true") + #expect(result.diagnostics.first?.message.contains("general.launch-at-login") == true) + #expect(result.diagnostics.first?.message.contains("Did you mean") == true) + } + + @Test func underscoreSpellingGetsKebabCaseSuggestion() throws { + let result = try validate("[layout]\nwindow_cap = 2") + #expect(result.configuration?.layout.global.windowCap == 0) + #expect(result.diagnostics.first?.message.contains("layout.window-cap") == true) + } + + @Test func transposedLettersGetSuggestion() throws { + let result = try validate("[layuot]") + #expect(result.diagnostics.first?.message.contains("Did you mean “layout”") == true) + } + + @Test func distantUnknownKeyDoesNotGetUnhelpfulSuggestion() throws { + let result = try validate("something-entirely-different = true") + #expect(result.diagnostics.first?.message.contains("Did you mean") == false) + } + + @Test func unknownCommandGetsSuggestion() throws { + let result = try validate("[keybindings]\nfocsu-left = false") + #expect(result.configuration != nil) + #expect(result.diagnostics.first?.message.contains("keybindings.focus-left") == true) + } + + @Test(arguments: [ + "layout.gaps.iner", "layout.reserved.tpo", "motion.speeed", "accessibility.announce-layout-change", + ]) + func nestedUnknownKeysWarn(_ path: String) throws { + let result = try validate("\(path) = 1") + #expect(result.configuration != nil) + #expect(result.diagnostics.first?.severity == .warning) + #expect(result.diagnostics.first?.message.contains("Did you mean") == true) + } + + @Test func knownWrongTypeUsesValueRange() throws { + let document = try TOMLDocument(parsing: "[motion]\n speed = \"fast\"") + let result = ConfigValidator.validate(document) + #expect(result.diagnostics.first?.location == document.root["motion"]?["speed"]?.range.start) + #expect(result.diagnostics.first?.location.column == 11) + } + + @Test func multipleErrorsAreCollectedAndSorted() throws { + let result = try validate("version = 2\n[layout]\nratio = 4\n[motion]\nenabled = \"yes\"") + #expect(result.configuration == nil) + #expect(result.diagnostics.count == 3) + #expect(result.diagnostics.map(\.location.line) == [1, 3, 5]) + } + + @Test func warningsDoNotHideErrors() throws { + let result = try validate("mystery = true\nversion = 2") + #expect(result.configuration == nil) + #expect(result.diagnostics.map(\.severity) == [.warning, .error]) + } + + @Test func validationIsDeterministic() throws { + let document = try TOMLDocument(parsing: "[layout]\nz = true\nx = 4\nratio = 7") + #expect(ConfigValidator.validate(document) == ConfigValidator.validate(document)) + } + + private func validate(_ source: String) throws -> ConfigValidationResult { + ConfigValidator.validate(try TOMLDocument(parsing: source)) + } + + private func configuration(_ source: String) throws -> TesseraConfiguration { + let result = try validate(source) + #expect(result.diagnostics.isEmpty) + return try #require(result.configuration) + } + + struct NumericField: Sendable { + let path: String + let lower: String + let upper: String + let below: String + let above: String + } + + static let numericFields: [NumericField] = [ + NumericField(path: "layout.ratio", lower: "0.1", upper: "0.9", below: "0.099", above: "0.901"), + NumericField(path: "layout.gaps.inner", lower: "0", upper: "256", below: "-0.1", above: "256.1"), + NumericField(path: "layout.gaps.outer", lower: "0", upper: "256", below: "-0.1", above: "256.1"), + NumericField(path: "layout.reserved.top", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), + NumericField(path: "layout.reserved.right", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), + NumericField(path: "layout.reserved.bottom", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), + NumericField(path: "layout.reserved.left", lower: "0", upper: "4096", below: "-0.1", above: "4096.1"), + NumericField(path: "layout.window-cap", lower: "0", upper: "100", below: "-1", above: "101"), + NumericField(path: "motion.speed", lower: "0.1", upper: "4", below: "0.099", above: "4.001"), + ] +} + +@Suite("Configuration JSON Schema") +struct ConfigJSONSchemaTests { + @Test func schemaIsDraft202012() throws { + #expect(try schema()["$schema"] == .string("https://json-schema.org/draft/2020-12/schema")) + } + + @Test func schemaDescribesRootTable() throws { + #expect(try schema()["type"] == .string("object")) + } + + @Test func schemaOnlyExposesKebabCaseRootKeys() throws { + let properties = try #require(schema()["properties"]?.object) + #expect( + Set(properties.keys) == [ + "version", "general", "layout", "motion", "keybindings", "float-rules", "accessibility", + ]) + } + + @Test func schemaVersionIsOptionalButConstrainedToOne() throws { + let root = try schema() + #expect(root["required"] == nil) + #expect(root["properties"]?["version"]?["const"] == .number(1)) + #expect(root["properties"]?["version"]?["default"] == .number(1)) + } + + @Test func schemaAllowsUnknownKeysForValidatorWarnings() throws { + #expect(try schema()["additionalProperties"] == .bool(true)) + #expect(try schema()["properties"]?["general"]?["additionalProperties"] == .bool(true)) + } + + @Test func schemaGeneralDefaultsMatchModel() throws { + let general = try schema()["properties"]?["general"]?["properties"] + #expect(general?["prefix"]?["default"] == .string(TesseraConfiguration.defaults.general.prefix.description)) + #expect(general?["launch-at-login"]?["default"] == .bool(false)) + } + + @Test func schemaLayoutEnumMatchesModel() throws { + let layout = try schema()["properties"]?["layout"]?["properties"]?["default"] + #expect(layout?["enum"] == .array(ConfigLayout.allCases.map { .string($0.rawValue) })) + #expect(layout?["default"] == .string(TesseraConfiguration.defaults.layout.global.defaultLayout.rawValue)) + } + + @Test func schemaWhimsyEnumMatchesModel() throws { + let whimsy = try schema()["properties"]?["motion"]?["properties"]?["whimsy"] + #expect(whimsy?["enum"] == .array(ConfigWhimsy.allCases.map { .string($0.rawValue) })) + #expect(whimsy?["default"] == .string(TesseraConfiguration.defaults.motion.whimsy.rawValue)) + } + + @Test(arguments: ConfigValidationTests.numericFields) + func schemaBoundsMatchValidation(_ field: ConfigValidationTests.NumericField) throws { + var node: TestJSON? = try schema() + for key in field.path.split(separator: ".") { + node = node?["properties"]?[String(key)] + } + #expect(node?["minimum"] == Double(field.lower).map(TestJSON.number)) + #expect(node?["maximum"] == Double(field.upper).map(TestJSON.number)) + #expect(node?["default"] != nil) + } + + @Test func schemaWindowCapIsInteger() throws { + #expect(try schema()["properties"]?["layout"]?["properties"]?["window-cap"]?["type"] == .string("integer")) + } + + @Test func schemaDisplayKeysAreUUIDs() throws { + let displays = try schema()["properties"]?["layout"]?["properties"]?["displays"] + let pattern = try #require(displays?["propertyNames"]?["pattern"]?.string) + let regex = try NSRegularExpression(pattern: pattern) + let id = "A1B2C3D4-1234-5678-9ABC-0123456789AB" + #expect(regex.firstMatch(in: id, range: NSRange(id.startIndex..., in: id)) != nil) + #expect(regex.firstMatch(in: "invalid", range: NSRange(location: 0, length: 7)) == nil) + } + + @Test func schemaDisplayOverridesDoNotShadowInheritedDefaults() throws { + let override = try schema()["properties"]?["layout"]?["properties"]?["displays"]?["additionalProperties"]?[ + "properties"] + #expect(override?["ratio"]?["default"] == nil) + #expect(override?["gaps"]?["properties"]?["inner"]?["default"] == nil) + #expect(override?["reserved"]?["properties"]?["top"]?["default"] == nil) + #expect(override?["window-cap"]?["default"] == nil) + #expect(override?["displays"] == nil) + } + + @Test func schemaDisplayBoundsMatchGlobalBounds() throws { + let global = try schema()["properties"]?["layout"]?["properties"] + let override = global?["displays"]?["additionalProperties"]?["properties"] + #expect(override?["ratio"]?["minimum"] == global?["ratio"]?["minimum"]) + #expect(override?["ratio"]?["maximum"] == global?["ratio"]?["maximum"]) + } + + @Test func schemaHasEveryCommand() throws { + let bindings = try #require(schema()["properties"]?["keybindings"]?["properties"]?.object) + #expect(Set(bindings.keys) == Set(ConfigCommand.allCases.map(\.rawValue))) + } + + @Test(arguments: ConfigCommand.allCases) + func schemaBindingDefaultsComeFromDefaultTable(_ command: ConfigCommand) throws { + let binding = try schema()["properties"]?["keybindings"]?["properties"]?[command.rawValue] + let chord = try #require(DefaultKeybindings.bindings()[command]) + #expect(binding?["default"] == .string(chord.description)) + let variants = try #require(binding?["oneOf"]?.array) + #expect(variants.contains { $0["const"] == .bool(false) }) + #expect(variants.contains { $0["type"] == .string("string") && $0["format"] == .string("tessera-key-chord") }) + } + + @Test func schemaFloatRuleRequiresOneMatcher() throws { + let rule = try schema()["properties"]?["float-rules"]?["items"] + #expect( + rule?["anyOf"] + == .array(["bundle-id", "title-regex", "role"].map { .object(["required": .array([.string($0)])]) })) + } + + @Test func schemaFloatMatchersMustBeNonblankStrings() throws { + let properties = try schema()["properties"]?["float-rules"]?["items"]?["properties"] + for key in ["bundle-id", "title-regex", "role"] { + #expect(properties?[key]?["type"] == .string("string")) + #expect(properties?[key]?["minLength"] == .number(1)) + #expect(properties?[key]?["pattern"] == .string("\\S")) + } + } + + @Test func schemaDocumentsNativeValidation() throws { + let root = try schema() + #expect(root["$comment"]?.string?.contains("duplicate resolved shortcuts") == true) + #expect( + root["properties"]?["float-rules"]?["items"]?["properties"]?["title-regex"]?["format"] + == .string("tessera-title-regex")) + #expect(root["properties"]?["general"]?["properties"]?["prefix"]?["format"] == .string("tessera-modifiers")) + } + + @Test func schemaAccessibilityDefaultMatchesModel() throws { + #expect( + try schema()["properties"]?["accessibility"]?["properties"]?["announce-layout-changes"]?["default"] + == .bool(false)) + } + + @Test func schemaExportIsStable() { + #expect(ConfigJSONSchema.string == ConfigJSONSchema.string) + #expect(ConfigJSONSchema.string.hasPrefix("{")) + } + + private func schema() throws -> TestJSON { + try JSONDecoder().decode(TestJSON.self, from: Data(ConfigJSONSchema.string.utf8)) + } +} + +private indirect enum TestJSON: Decodable, Equatable { + case object([String: TestJSON]) + case array([TestJSON]) + case string(String) + case number(Double) + case bool(Bool) + case null + + init(from decoder: any Decoder) throws { + let value = try decoder.singleValueContainer() + if value.decodeNil() { + self = .null + return + } + do { + self = .object(try value.decode([String: TestJSON].self)) + return + } catch DecodingError.typeMismatch {} + do { + self = .array(try value.decode([TestJSON].self)) + return + } catch DecodingError.typeMismatch {} + do { + self = .string(try value.decode(String.self)) + return + } catch DecodingError.typeMismatch {} + do { + self = .bool(try value.decode(Bool.self)) + return + } catch DecodingError.typeMismatch {} + self = .number(try value.decode(Double.self)) + } + + subscript(key: String) -> TestJSON? { + guard case .object(let values) = self else { return nil } + return values[key] + } + + var object: [String: TestJSON]? { + guard case .object(let values) = self else { return nil } + return values + } + + var array: [TestJSON]? { + guard case .array(let values) = self else { return nil } + return values + } + + var string: String? { + guard case .string(let value) = self else { return nil } + return value + } +} diff --git a/Tests/TesseraConfigTests/KeyChordTests.swift b/Tests/TesseraConfigTests/KeyChordTests.swift new file mode 100644 index 00000000..3202f655 --- /dev/null +++ b/Tests/TesseraConfigTests/KeyChordTests.swift @@ -0,0 +1,275 @@ +import Foundation +import TesseraConfig +import Testing + +struct KeyChordTests { + @Test(arguments: KeyChordSamples.physicalKeys) + func physicalKeyCodes(_ sample: KeyCodeSample) throws { + let chord = try KeyChord(parsing: sample.key.rawValue) + #expect(chord.key == sample.key) + #expect(chord.modifiers.isEmpty) + #expect(chord.keyCode == sample.code) + #expect(sample.key.keyCode == sample.code) + #expect(chord.description == sample.key.rawValue) + + let modified = try KeyChord(parsing: "CTRL-OPT-CMD-SHIFT-FN-\(sample.key.rawValue)") + #expect(modified.key == sample.key) + #expect(modified.keyCode == sample.code) + #expect(modified.modifiers == [.hyper, .fn]) + } + + @Test func physicalKeyFixturesAreExhaustiveAndDistinct() { + #expect(Set(KeyChordSamples.physicalKeys.map(\.key)) == Set(ANSIKey.allCases)) + #expect(KeyChordSamples.physicalKeys.count == ANSIKey.allCases.count) + #expect(Set(ANSIKey.allCases.map(\.keyCode)).count == ANSIKey.allCases.count) + } + + @Test(arguments: KeyChordSamples.normalizations) + func normalizesAliasesAndOrder(_ input: String, _ canonical: String) throws { + let parsed = try KeyChord(parsing: input) + #expect(parsed.description == canonical) + #expect(try KeyChord(parsing: canonical) == parsed) + } + + @Test(arguments: KeyChordSamples.shiftedPunctuation) + func shiftedPunctuationUsesPhysicalKey(_ symbol: String, _ key: ANSIKey) throws { + #expect(try KeyChord(parsing: symbol) == KeyChord(modifiers: .shift, key: key)) + #expect(try KeyChord(parsing: "ctrl-\(symbol)") == KeyChord(modifiers: [.ctrl, .shift], key: key)) + #expect(try KeyChord(parsing: "ctrl-shift-\(symbol)") == KeyChord(modifiers: [.ctrl, .shift], key: key)) + } + + @Test(arguments: KeyChordSamples.prefixes) + func parsesModifierOnlyPrefixes(_ input: String, _ expected: KeyModifiers, _ canonical: String) throws { + let modifiers = try KeyModifiers(parsing: input) + #expect(modifiers == expected) + #expect(modifiers.description == canonical) + #expect(try KeyModifiers(parsing: modifiers.description) == expected) + } + + @Test(arguments: KeyChordSamples.invalidChords) + func reportsTypedChordErrors(_ input: String, _ expected: KeyChordParseError) { + #expect(throws: expected) { try KeyChord(parsing: input) } + } + + @Test(arguments: KeyChordSamples.invalidPrefixes) + func reportsTypedPrefixErrors(_ input: String, _ expected: KeyChordParseError) { + #expect(throws: expected) { try KeyModifiers(parsing: input) } + } + + @Test func hyperIsItsExpandedModifierSet() throws { + let hyper = try KeyChord(parsing: "hyper-a") + let expanded = try KeyChord(parsing: "shift-cmd-alt-ctrl-a") + #expect(hyper == expanded) + #expect(Set([hyper, expanded]).count == 1) + #expect(hyper.modifiers == [.ctrl, .alt, .cmd, .shift]) + #expect(hyper.modifiers.rawValue == 15) + #expect(!hyper.modifiers.contains(.fn)) + #expect(hyper.description == "ctrl-alt-cmd-shift-a") + #expect(try KeyChord(parsing: "fn-hyper-a").modifiers == [.hyper, .fn]) + } + + @Test func equalityIncludesPhysicalKeyAndAllModifiers() throws { + let plain = try KeyChord(parsing: "a") + let shifted = try KeyChord(parsing: "shift-a") + let otherKey = try KeyChord(parsing: "s") + let function = try KeyChord(parsing: "fn-a") + #expect(Set([plain, shifted, otherKey, function]).count == 4) + #expect(try KeyChord(parsing: "A") == plain) + #expect(try KeyChord(parsing: "opt-A") == KeyChord(parsing: "alt-a")) + #expect(try KeyChord(parsing: "+") == KeyChord(parsing: "shift-=")) + #expect(try KeyChord(parsing: "enter") != KeyChord(parsing: "keypadenter")) + #expect(try KeyChord(parsing: "1") != KeyChord(parsing: "keypad1")) + } + + @Test(arguments: UInt8(0)..<32) + func allPhysicalKeysAndModifierSetsRoundTrip(_ rawValue: UInt8) throws { + let modifiers = KeyModifiers(rawValue: rawValue) + #expect(try KeyModifiers(parsing: modifiers.description) == modifiers) + for key in ANSIKey.allCases { + let chord = KeyChord(modifiers: modifiers, key: key) + #expect(try KeyChord(parsing: chord.description) == chord) + } + } + + @Test(arguments: KeyChordSamples.errorMessages) + func errorsProvideLocalizedUsefulMessages(_ error: KeyChordParseError, _ expected: String) { + #expect(error.description == expected) + #expect(error.errorDescription == expected) + #expect(error.localizedDescription == expected) + } +} + +struct DefaultKeybindingsTests { + @Test(arguments: UInt8(0)..<32) + func everyPrefixIsExhaustiveAndCollisionFree(_ rawValue: UInt8) throws { + let prefix = KeyModifiers(rawValue: rawValue) + let bindings = DefaultKeybindings.bindings(prefix: prefix) + let withoutPrefix = DefaultKeybindings.bindings(prefix: []) + #expect(Set(bindings.keys) == Set(ConfigCommand.allCases)) + #expect(Set(bindings.values).count == bindings.count) + #expect(Set(bindings.values.map(\.keyCode)).count == bindings.count) + for command in ConfigCommand.allCases { + let chord = try #require(bindings[command]) + let base = try #require(withoutPrefix[command]) + #expect(chord.modifiers == base.modifiers.union(prefix)) + #expect(chord.key == base.key) + #expect(try KeyChord(parsing: chord.description) == chord) + } + } + + @Test(arguments: KeyChordSamples.defaults) + func stableDefaultShortcuts(_ command: ConfigCommand, _ expected: String) throws { + #expect(DefaultKeybindings.bindings()[command] == (try KeyChord(parsing: expected))) + } + + @Test func defaultPrefixAndFixtureCoverage() { + #expect(DefaultKeybindings.bindings() == DefaultKeybindings.bindings(prefix: [.ctrl, .alt])) + #expect(Set(KeyChordSamples.defaults.map(\.0)) == Set(ConfigCommand.allCases)) + } + + @Test(arguments: KeyChordSamples.commands) + func commandRawValues(_ command: ConfigCommand, _ expected: String) { + #expect(command.rawValue == expected) + #expect(ConfigCommand(rawValue: expected) == command) + } + + @Test func commandFixturesAreExhaustive() { + #expect(Set(KeyChordSamples.commands.map(\.0)) == Set(ConfigCommand.allCases)) + #expect(KeyChordSamples.commands.count == ConfigCommand.allCases.count) + #expect(ConfigCommand(rawValue: "focusLeft") == nil) + #expect(ConfigCommand(rawValue: "focus-diagonal") == nil) + } +} + +struct KeyCodeSample: Sendable { + let key: ANSIKey + let code: UInt16 + + init(_ key: ANSIKey, _ code: UInt16) { + self.key = key + self.code = code + } +} + +private enum KeyChordSamples { + static let physicalKeys: [KeyCodeSample] = [ + .init(.a, 0), .init(.s, 1), .init(.d, 2), .init(.f, 3), .init(.h, 4), .init(.g, 5), + .init(.z, 6), .init(.x, 7), .init(.c, 8), .init(.v, 9), .init(.b, 11), + .init(.q, 12), .init(.w, 13), .init(.e, 14), .init(.r, 15), .init(.y, 16), .init(.t, 17), + .init(.one, 18), .init(.two, 19), .init(.three, 20), .init(.four, 21), .init(.six, 22), .init(.five, 23), + .init(.equal, 24), .init(.nine, 25), .init(.seven, 26), .init(.minus, 27), .init(.eight, 28), .init(.zero, 29), + .init(.rightBracket, 30), .init(.o, 31), .init(.u, 32), .init(.leftBracket, 33), .init(.i, 34), .init(.p, 35), + .init(.return, 36), .init(.l, 37), .init(.j, 38), .init(.quote, 39), .init(.k, 40), .init(.semicolon, 41), + .init(.backslash, 42), .init(.comma, 43), .init(.slash, 44), .init(.n, 45), .init(.m, 46), .init(.period, 47), + .init(.tab, 48), .init(.space, 49), .init(.grave, 50), .init(.delete, 51), .init(.escape, 53), + .init(.capsLock, 57), .init(.f17, 64), .init(.keypadDecimal, 65), .init(.keypadMultiply, 67), + .init(.keypadPlus, 69), .init(.keypadClear, 71), .init(.keypadDivide, 75), .init(.keypadEnter, 76), + .init(.keypadMinus, 78), .init(.f18, 79), .init(.f19, 80), .init(.keypadEqual, 81), + .init(.keypad0, 82), .init(.keypad1, 83), .init(.keypad2, 84), .init(.keypad3, 85), .init(.keypad4, 86), + .init(.keypad5, 87), .init(.keypad6, 88), .init(.keypad7, 89), .init(.f20, 90), + .init(.keypad8, 91), .init(.keypad9, 92), .init(.f5, 96), .init(.f6, 97), .init(.f7, 98), + .init(.f3, 99), .init(.f8, 100), .init(.f9, 101), .init(.f11, 103), .init(.f13, 105), .init(.f16, 106), + .init(.f14, 107), .init(.f10, 109), .init(.f12, 111), .init(.f15, 113), .init(.help, 114), + .init(.home, 115), .init(.pageUp, 116), .init(.forwardDelete, 117), .init(.f4, 118), .init(.end, 119), + .init(.f2, 120), .init(.pageDown, 121), .init(.f1, 122), + .init(.left, 123), .init(.right, 124), .init(.down, 125), .init(.up, 126), + ] + + static let normalizations: [(String, String)] = [ + ("shift-CMD-Opt-CTRL-A", "ctrl-alt-cmd-shift-a"), + (" \tFn - COMMAND - OPTION - CONTROL - Shift - F20\n", "ctrl-alt-cmd-shift-fn-f20"), + ("hyper-left", "ctrl-alt-cmd-shift-left"), ("FN-hyper-RIGHT", "ctrl-alt-cmd-shift-fn-right"), + ("ctrl--", "ctrl-minus"), ("ctrl-alt--", "ctrl-alt-minus"), ("-", "minus"), + ("ctrl - -", "ctrl-minus"), ("hyphen", "minus"), ("ctrl-minus", "ctrl-minus"), + ("equal", "="), ("equals", "="), ("leftbracket", "["), ("rightbracket", "]"), + ("backslash", "\\"), ("semicolon", ";"), ("quote", "'"), ("apostrophe", "'"), + ("comma", ","), ("period", "."), ("dot", "."), ("slash", "/"), + ("grave", "`"), ("backtick", "`"), ("enter", "return"), ("ESC", "escape"), + ("backspace", "delete"), ("ALT-PAGEUP", "alt-pageup"), ("Cmd-KEYPADENTER", "cmd-keypadenter"), + ("ctrl-+", "ctrl-shift-="), ("hyper-_", "ctrl-alt-cmd-shift-minus"), + ("A", "a"), ("ctrl-;", "ctrl-;"), ("cmd-'", "cmd-'"), ("opt-\\", "alt-\\"), + ] + + static let shiftedPunctuation: [(String, ANSIKey)] = [ + ("!", .one), ("@", .two), ("#", .three), ("$", .four), ("%", .five), + ("^", .six), ("&", .seven), ("*", .eight), ("(", .nine), (")", .zero), + ("_", .minus), ("+", .equal), ("{", .leftBracket), ("}", .rightBracket), + ("|", .backslash), (":", .semicolon), ("\"", .quote), ("<", .comma), (">", .period), + ("?", .slash), ("~", .grave), + ] + + static let prefixes: [(String, KeyModifiers, String)] = [ + ("", [], ""), (" \t\n", [], ""), + ("ctrl", .ctrl, "ctrl"), ("CONTROL", .ctrl, "ctrl"), + ("alt", .alt, "alt"), ("opt", .alt, "alt"), ("OPTION", .alt, "alt"), + ("cmd", .cmd, "cmd"), ("command", .cmd, "cmd"), + ("shift", .shift, "shift"), ("fn", .fn, "fn"), + ("hyper", .hyper, "ctrl-alt-cmd-shift"), ("shift-alt-cmd-ctrl", .hyper, "ctrl-alt-cmd-shift"), + ("FN-HYPER", [.hyper, .fn], "ctrl-alt-cmd-shift-fn"), + (" opt - ctrl ", [.ctrl, .alt], "ctrl-alt"), ("cmd-fn", [.cmd, .fn], "cmd-fn"), + ] + + static let invalidChords: [(String, KeyChordParseError)] = [ + ("", .emptyChord), (" \t\n", .emptyChord), + ("ctrl", .missingKey), ("hyper", .missingKey), ("ctrl-alt", .missingKey), + ("ctrl-", .missingKey), ("ctrl- ", .missingKey), + ("-a", .emptyComponent), ("--", .emptyComponent), ("ctrl--a", .emptyComponent), + ("ctrl---", .emptyComponent), ("ctrl- -a", .emptyComponent), + ("ctrl-ctrl-a", .duplicateModifier("ctrl")), ("alt-opt-a", .duplicateModifier("opt")), + ("hyper-shift-a", .duplicateModifier("shift")), ("ctrl-hyper-a", .duplicateModifier("hyper")), + ("fn-fn-a", .duplicateModifier("fn")), ("super-a", .unknownModifier("super")), + ("ctrl-left-a", .unknownModifier("left")), ("ctrl-a-b", .unknownModifier("a")), + ("ctrl-f0", .unknownKey("f0")), ("ctrl-f21", .unknownKey("f21")), ("ctrl-f01", .unknownKey("f01")), + ("ctrl-nope", .unknownKey("nope")), ("ctrl-ä", .unknownKey("ä")), + ("ctrl-K", .unknownKey("K")), ("ctrl-ø", .unknownKey("ø")), + ("ctrl-a b", .unknownKey("a b")), ("ctrl+alt+a", .unknownKey("ctrl+alt+a")), + ] + + static let invalidPrefixes: [(String, KeyChordParseError)] = [ + ("ctrl-", .emptyComponent), ("-", .emptyComponent), ("-ctrl", .emptyComponent), + ("ctrl--alt", .emptyComponent), ("ctrl-a", .unknownModifier("a")), + ("super", .unknownModifier("super")), ("return", .unknownModifier("return")), + ("alt-opt", .duplicateModifier("opt")), ("hyper-cmd", .duplicateModifier("cmd")), + ("shift-hyper", .duplicateModifier("hyper")), ("fn-fn", .duplicateModifier("fn")), + ] + + static let errorMessages: [(KeyChordParseError, String)] = [ + (.emptyChord, "A key chord cannot be empty."), + (.emptyComponent, "A key chord contains an empty modifier."), + (.missingKey, "A key chord needs a key after its modifiers."), + (.unknownModifier("super"), "Unknown modifier ‘super’. Use ctrl, alt (or opt), cmd, shift, fn, or hyper."), + (.duplicateModifier("alt"), "Modifier ‘alt’ repeats a modifier already present."), + (.unknownKey("f21"), "Unknown ANSI key ‘f21’. Use a letter, digit, punctuation, named key, or f1–f20."), + ] + + static let defaults: [(ConfigCommand, String)] = [ + (.focusLeft, "ctrl-alt-left"), (.focusRight, "ctrl-alt-right"), + (.focusUp, "ctrl-alt-up"), (.focusDown, "ctrl-alt-down"), + (.swapLeft, "ctrl-alt-shift-h"), (.swapRight, "ctrl-alt-shift-l"), + (.swapUp, "ctrl-alt-shift-k"), (.swapDown, "ctrl-alt-shift-j"), + (.moveLeft, "ctrl-alt-shift-a"), (.moveRight, "ctrl-alt-shift-d"), + (.moveUp, "ctrl-alt-shift-w"), (.moveDown, "ctrl-alt-shift-s"), + (.layoutGrid, "ctrl-alt-g"), (.layoutColumns, "ctrl-alt-c"), + (.layoutRows, "ctrl-alt-r"), (.layoutSide, "ctrl-alt-e"), + (.ratioIncrease, "ctrl-alt-="), (.ratioDecrease, "ctrl-alt-minus"), + (.floatToggle, "ctrl-alt-f"), (.retile, "ctrl-alt-return"), (.stack, "ctrl-alt-space"), + (.stackNext, "ctrl-alt-]"), (.stackPrevious, "ctrl-alt-["), + (.displayMoveLeft, "ctrl-alt-cmd-f1"), (.displayMoveRight, "ctrl-alt-cmd-f2"), + (.displayMoveUp, "ctrl-alt-cmd-f3"), (.displayMoveDown, "ctrl-alt-cmd-f4"), + (.openSettings, "ctrl-alt-,"), + ] + + static let commands: [(ConfigCommand, String)] = [ + (.focusLeft, "focus-left"), (.focusRight, "focus-right"), (.focusUp, "focus-up"), (.focusDown, "focus-down"), + (.swapLeft, "swap-left"), (.swapRight, "swap-right"), (.swapUp, "swap-up"), (.swapDown, "swap-down"), + (.moveLeft, "move-left"), (.moveRight, "move-right"), (.moveUp, "move-up"), (.moveDown, "move-down"), + (.layoutGrid, "layout-grid"), (.layoutColumns, "layout-columns"), + (.layoutRows, "layout-rows"), (.layoutSide, "layout-side"), + (.ratioIncrease, "ratio-increase"), (.ratioDecrease, "ratio-decrease"), + (.floatToggle, "float-toggle"), (.retile, "retile"), (.stack, "stack"), + (.stackNext, "stack-next"), (.stackPrevious, "stack-previous"), + (.displayMoveLeft, "display-move-left"), (.displayMoveRight, "display-move-right"), + (.displayMoveUp, "display-move-up"), (.displayMoveDown, "display-move-down"), + (.openSettings, "open-settings"), + ] +} diff --git a/Tests/TesseraConfigTests/TOMLDocumentTests.swift b/Tests/TesseraConfigTests/TOMLDocumentTests.swift index ad81efa1..a5c8965d 100644 --- a/Tests/TesseraConfigTests/TOMLDocumentTests.swift +++ b/Tests/TesseraConfigTests/TOMLDocumentTests.swift @@ -117,6 +117,13 @@ import Testing #expect(document.source == "gaps = {inner=8, \"outer\" = 12} # keep") } + @Test func insertsNestedKeysInsideInlineTables() throws { + var document = try TOMLDocument(parsing: "layout = {ratio=0.5} # keep") + try document.setValue(.integer(12), forKey: ["layout", "gaps", "inner"]) + #expect(document.source == "layout = {ratio=0.5, \"gaps\".\"inner\" = 12} # keep") + #expect(document.node(forKey: ["layout", "gaps", "inner"])?.value == .integer(12)) + } + @Test func insertsIntoEmptyInlineTable() throws { var document = try TOMLDocument(parsing: "gaps = {}") try document.setValue(.integer(8), forKey: ["gaps", "inner"]) diff --git a/Tests/TesseraConfigTests/TOMLParserTests.swift b/Tests/TesseraConfigTests/TOMLParserTests.swift index 0d2fe1d5..e500ba1d 100644 --- a/Tests/TesseraConfigTests/TOMLParserTests.swift +++ b/Tests/TesseraConfigTests/TOMLParserTests.swift @@ -215,6 +215,39 @@ import Testing #expect(throws: ConfigDiagnostic.self) { try TOMLDocument(parsing: source) } } + @Test(arguments: [ + "[a.b.c]\nx=1\n[a]\nb.d=2", + "[a.b.c]\nx=1\n[a]\nb.d=2\n[a.b.e]\nz=3", + "a.b.c=1\n[a.b.d]\nx=2", + "[[a.b]]\nx=1\n[a]\ny=2", + "[[a]]\nx=1\n[[a.b]]\ny=2\n[[a]]\nx=2\n[[a.b]]\ny=3", + ]) + func implicitTableExtensions(source: String) throws { + _ = try TOMLDocument(parsing: source) + } + + @Test(arguments: [ + "[a.b.c]\nx=1\n[a]\nb.d=2\n[a.b]\nz=3", + "[[a]]\n[a.b]\nx=1\n[a.b]\ny=2", + "[[a]]\nb.c=1\n[a.b]\ny=2", + "[a.b.c]\nx=1\n[a]\nb.d.e=2\n[a.b.d]\ny=3", + ]) + func dottedUseDeclaresImplicitTables(source: String) { + #expect(throws: ConfigDiagnostic.self) { try TOMLDocument(parsing: source) } + } + + @Test func excessiveDottedNestingIsDiagnosed() { + let key = Array(repeating: "a", count: 129).joined(separator: ".") + #expect(throws: ConfigDiagnostic.self) { try TOMLDocument(parsing: key + "=1") } + #expect(throws: ConfigDiagnostic.self) { try TOMLDocument(parsing: "[" + key + "]") } + } + + @Test func inlineDottedNestingSharesDepthBudget() { + let prefix = Array(repeating: "a", count: 64).joined(separator: ".") + let source = "v={" + prefix + "={" + prefix + "={x=1}}}" + #expect(throws: ConfigDiagnostic.self) { try TOMLDocument(parsing: source) } + } + private func scalar(_ source: String) throws -> TOMLValue { let document = try TOMLDocument(parsing: "v = " + source) return try #require(document.root["v"]?.value) -- knotmirror 0.0.1 From a03e45c70950b0e3c36dce8c1f4a451b9bed3aab Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:48:12 -0400 Subject: [PATCH 14/44] Add the socket protocol and CLI --- NOTICE | 6 + Package.swift | 7 +- Sources/TesseraIPC/IPCClient.swift | 143 +++++ Sources/TesseraIPC/IPCServer.swift | 385 +++++++++++++ .../Resources/Localizable.xcstrings | 237 ++++++++ .../Resources/en.lproj/Localizable.strings | 48 ++ Sources/TesseraIPC/Socket.swift | 278 ++++++++++ .../TesseraIPC/TesseraIPC.docc/TesseraIPC.md | 55 ++ Sources/TesseraIPC/TesseraIPC.swift | 203 +++++++ Sources/tessera/CLIOutput.swift | 211 ++++++++ .../tessera/Resources/Localizable.xcstrings | 60 +++ .../Resources/en.lproj/Localizable.strings | 114 ++++ Sources/tessera/TesseraCLI.swift | 340 ++++++++++++ Sources/tessera/main.swift | 1 - Tests/TesseraIPCTests/CLITests.swift | 459 ++++++++++++++++ Tests/TesseraIPCTests/ClientTests.swift | 204 +++++++ Tests/TesseraIPCTests/SocketTests.swift | 507 ++++++++++++++++++ Tests/TesseraIPCTests/TesseraIPCTests.swift | 129 ++++- 18 files changed, 3382 insertions(+), 5 deletions(-) create mode 100644 Sources/TesseraIPC/IPCClient.swift create mode 100644 Sources/TesseraIPC/IPCServer.swift create mode 100644 Sources/TesseraIPC/Resources/Localizable.xcstrings create mode 100644 Sources/TesseraIPC/Resources/en.lproj/Localizable.strings create mode 100644 Sources/TesseraIPC/Socket.swift create mode 100644 Sources/TesseraIPC/TesseraIPC.docc/TesseraIPC.md create mode 100644 Sources/tessera/CLIOutput.swift create mode 100644 Sources/tessera/Resources/Localizable.xcstrings create mode 100644 Sources/tessera/Resources/en.lproj/Localizable.strings create mode 100644 Sources/tessera/TesseraCLI.swift delete mode 100644 Sources/tessera/main.swift create mode 100644 Tests/TesseraIPCTests/CLITests.swift create mode 100644 Tests/TesseraIPCTests/ClientTests.swift create mode 100644 Tests/TesseraIPCTests/SocketTests.swift diff --git a/NOTICE b/NOTICE index 102a81b3..b1749165 100644 --- a/NOTICE +++ b/NOTICE @@ -2,3 +2,9 @@ Tessera Copyright 2026 Vincent Taverna Licensed under the Apache License, Version 2.0. + +Swift Argument Parser +Copyright 2019–2026 Apple Inc. and the Swift project authors. +Licensed under Apache 2.0 with Runtime Library Exception. +https://github.com/apple/swift-argument-parser +Used by the tessera command-line interface; no source copied into this repo. diff --git a/Package.swift b/Package.swift index 61373897..a46194ff 100644 --- a/Package.swift +++ b/Package.swift @@ -11,7 +11,7 @@ let package = Package( defaultLocalization: "en", platforms: [.macOS(.v15)], products: [ - .executable(name: "Tessera", targets: ["TesseraApp"]), + .executable(name: "TesseraApp", targets: ["TesseraApp"]), .executable(name: "tessera", targets: ["tessera"]), ], dependencies: [ @@ -24,12 +24,13 @@ let package = Package( .target(name: "TesseraPlatform", dependencies: ["TesseraCore", "CPrivateAPI"], swiftSettings: strict), .target(name: "TesseraAnimation", dependencies: ["TesseraCore"], swiftSettings: strict), .target(name: "TesseraEngine", dependencies: ["TesseraCore", "TesseraConfig", "TesseraPlatform", "TesseraAnimation"], swiftSettings: strict), - .target(name: "TesseraIPC", dependencies: ["TesseraCore"], swiftSettings: strict), + .target(name: "TesseraIPC", dependencies: ["TesseraCore"], resources: [.process("Resources")], swiftSettings: strict), .target(name: "TesseraUI", dependencies: ["TesseraCore", "TesseraConfig", "TesseraEngine", "TesseraAnimation"], swiftSettings: strict), .executableTarget(name: "TesseraApp", dependencies: ["TesseraUI", "TesseraEngine", "TesseraIPC"], swiftSettings: strict), .executableTarget( name: "tessera", dependencies: ["TesseraIPC", .product(name: "ArgumentParser", package: "swift-argument-parser")], + resources: [.process("Resources")], swiftSettings: strict ), .executableTarget(name: "FixtureApp", swiftSettings: strict), @@ -39,7 +40,7 @@ let package = Package( .testTarget(name: "TesseraPlatformTests", dependencies: ["TesseraPlatform"]), .testTarget(name: "TesseraEngineTests", dependencies: ["TesseraEngine"]), .testTarget(name: "TesseraAnimationTests", dependencies: ["TesseraAnimation"]), - .testTarget(name: "TesseraIPCTests", dependencies: ["TesseraIPC"]), + .testTarget(name: "TesseraIPCTests", dependencies: ["TesseraIPC", "tessera"]), .testTarget(name: "TesseraE2ETests", dependencies: ["TesseraPlatform", "TesseraCore"]), ], swiftLanguageModes: [.v6] diff --git a/Sources/TesseraIPC/IPCClient.swift b/Sources/TesseraIPC/IPCClient.swift new file mode 100644 index 00000000..46340275 --- /dev/null +++ b/Sources/TesseraIPC/IPCClient.swift @@ -0,0 +1,143 @@ +import Foundation + +public struct IPCSubscription: Sendable { + public let events: AsyncThrowingStream + private let channel: SocketChannel + private let task: Task + + init(events: AsyncThrowingStream, channel: SocketChannel, task: Task) { + self.events = events + self.channel = channel + self.task = task + } + + public func cancel() async { + task.cancel() + await channel.close() + await task.value + } +} + +public actor IPCClient { + public let socketPath: String + private var channels: [UUID: SocketChannel] = [:] + + public init(socketPath: String? = nil) throws { + self.socketPath = try socketPath ?? IPCSocketPath.resolve() + _ = try SocketAddress(self.socketPath) + } + + public func request(_ request: IPCRequest) async throws -> IPCResponse { + guard request.command != "subscribe" else { + throw IPCTransportError.protocolViolation( + String(localized: "Use subscribe(topics:) to receive events.", bundle: .module)) + } + let (id, channel) = try openChannel() + do { + try await channel.connect(path: socketPath) + try await channel.write(IPCCodec.encode(request)) + guard let line = try await channel.readLine() else { throw IPCTransportError.closed } + let response = try IPCCodec.decode(IPCResponse.self, from: line) + try validate(response, id: request.id) + await channel.close() + channels.removeValue(forKey: id) + return response + } catch { + await channel.close() + channels.removeValue(forKey: id) + throw error + } + } + + public func subscribe(topics: [IPCTopic] = []) async throws -> IPCSubscription { + let request = IPCRequest(command: "subscribe", args: topics.map(\.rawValue)) + let (id, channel) = try openChannel() + do { + try await channel.connect(path: socketPath) + try await channel.write(IPCCodec.encode(request)) + guard let line = try await channel.readLine() else { throw IPCTransportError.closed } + let response = try IPCCodec.decode(IPCResponse.self, from: line) + try validate(response, id: request.id) + if let error = response.error { throw error } + let (events, continuation) = AsyncThrowingStream.makeStream( + bufferingPolicy: .bufferingOldest(128)) + let task = Task { [weak self] in + do { + while let line = try await channel.readLine() { + let message = try IPCCodec.decode(JSONValue.self, from: line) + if case .object(let fields) = message, fields["ok"] != nil { + let response = try IPCCodec.decode(IPCResponse.self, from: line) + try Self.validateResponse(response, id: request.id) + if let error = response.error { throw error } + throw IPCTransportError.protocolViolation( + String(localized: "Expected an event, not another response.", bundle: .module)) + } + let event = try IPCCodec.decode(IPCEvent.self, from: line) + guard event.v == IPCProtocol.version else { + throw IPCTransportError.protocolViolation( + String(localized: "Unsupported event version: \(event.v)", bundle: .module)) + } + switch continuation.yield(event) { + case .enqueued: break + case .dropped: + throw IPCError( + code: "slow_subscriber", + message: String( + localized: "The event consumer fell behind. Reconnect and query the current state.", + bundle: .module)) + case .terminated: + await channel.close() + await self?.removeChannel(id) + return + @unknown default: preconditionFailure("Unknown stream yield result") + } + } + continuation.finish() + } catch { + if Task.isCancelled { continuation.finish() } else { continuation.finish(throwing: error) } + } + await channel.close() + await self?.removeChannel(id) + } + continuation.onTermination = { _ in + task.cancel() + Task { await channel.close() } + } + return IPCSubscription(events: events, channel: channel, task: task) + } catch { + await channel.close() + channels.removeValue(forKey: id) + throw error + } + } + + public func close() async { + let channels = Array(channels.values) + self.channels.removeAll() + for channel in channels { await channel.close() } + } + + private func openChannel() throws -> (UUID, SocketChannel) { + let id = UUID() + let channel = SocketChannel(descriptor: try makeSocket()) + channels[id] = channel + return (id, channel) + } + + private func removeChannel(_ id: UUID) { channels.removeValue(forKey: id) } + + private func validate(_ response: IPCResponse, id: IPCRequestID) throws { + try Self.validateResponse(response, id: id) + } + + private static func validateResponse(_ response: IPCResponse, id: IPCRequestID) throws { + guard response.v == IPCProtocol.version else { + throw IPCTransportError.protocolViolation( + String(localized: "Unsupported response version: \(response.v)", bundle: .module)) + } + guard response.id == id else { + throw IPCTransportError.protocolViolation( + String(localized: "The response ID does not match the request.", bundle: .module)) + } + } +} diff --git a/Sources/TesseraIPC/IPCServer.swift b/Sources/TesseraIPC/IPCServer.swift new file mode 100644 index 00000000..26dcde0a --- /dev/null +++ b/Sources/TesseraIPC/IPCServer.swift @@ -0,0 +1,385 @@ +import Darwin +import Dispatch +import Foundation +import OSLog + +public actor IPCServer { + public let socketPath: String + public var clientCount: Int { clients.count } + public var subscriberCount: Int { subscribers.count } + + private let handler: any IPCHandler + private let serverVersion: String + private let onError: @Sendable (any Error) -> Void + private var listener: Int32? + private var lock: Int32? + private var socketIdentity: SocketIdentity? + private var source: (any DispatchSourceRead)? + private var generation = UUID() + private var stopping = false + private var clients: [UUID: Client] = [:] + private var subscribers: [UUID: Subscriber] = [:] + + public init( + handler: any IPCHandler, + socketPath: String? = nil, + serverVersion: String = "0.1.0", + onError: (@Sendable (any Error) -> Void)? = nil + ) throws { + self.handler = handler + self.socketPath = try socketPath ?? IPCSocketPath.resolve() + _ = try SocketAddress(self.socketPath) + self.serverVersion = serverVersion + self.onError = + onError ?? { error in + Logger(subsystem: "com.tessera.ipc", category: "server").error( + "\(error.localizedDescription, privacy: .public)") + } + } + + deinit { + source?.cancel() + if let listener { Darwin.close(listener) } + if let socketIdentity { socketIdentity.removeIfOwned(path: socketPath) } + if let lock { Darwin.close(lock) } + } + + public func start() throws { + guard listener == nil, !stopping else { throw IPCTransportError.alreadyRunning(socketPath) } + let lock = try acquireLock() + var descriptor: Int32? + var boundIdentity: SocketIdentity? + do { + try removeStaleSocket() + let fd = try makeSocket() + descriptor = fd + var address = try SocketAddress(socketPath) + guard address.withPointer({ Darwin.bind(fd, $0, $1) }) == 0 else { + throw IPCTransportError.system(operation: "bind", code: errno) + } + boundIdentity = try SocketIdentity.read(path: socketPath) + guard chmod(socketPath, S_IRUSR | S_IWUSR) == 0 else { + throw IPCTransportError.system(operation: "chmod", code: errno) + } + guard Darwin.listen(fd, 128) == 0 else { throw IPCTransportError.system(operation: "listen", code: errno) } + listener = fd + self.lock = lock + socketIdentity = boundIdentity + generation = UUID() + let generation = generation + let source = DispatchSource.makeReadSource(fileDescriptor: fd, queue: .global()) + self.source = source + source.setEventHandler { @Sendable [weak self] in + Task { [weak self] in await self?.acceptClients(generation: generation) } + } + source.resume() + } catch { + if let descriptor { Darwin.close(descriptor) } + boundIdentity?.removeIfOwned(path: socketPath) + Darwin.close(lock) + throw error + } + } + + public func stop() async throws { + guard !stopping else { throw IPCTransportError.operationInProgress } + stopping = true + defer { stopping = false } + generation = UUID() + source?.cancel() + source = nil + if let listener { Darwin.close(listener) } + listener = nil + let clients = Array(clients.values) + self.clients.removeAll() + for subscriber in subscribers.values { subscriber.continuation.finish() } + subscribers.removeAll() + for client in clients { + client.task.cancel() + await client.channel.close() + } + for client in clients { await client.task.value } + var cleanupError: (any Error)? + do { try socketIdentity?.remove(path: socketPath) } catch { cleanupError = error } + socketIdentity = nil + if let lock { Darwin.close(lock) } + lock = nil + if let cleanupError { throw cleanupError } + } + + public func publish(_ event: IPCEvent) throws { + guard event.v == IPCProtocol.version else { throw unsupportedVersion(event.v) } + _ = try IPCCodec.encode(event) + var finished: [UUID] = [] + for (id, subscriber) in subscribers where subscriber.topics.contains(event.topic) { + switch subscriber.continuation.yield(event) { + case .enqueued: break + case .dropped: + subscriber.continuation.finish( + throwing: IPCError( + code: "slow_subscriber", + message: String( + localized: "The event consumer fell behind. Reconnect and query the current state.", + bundle: .module) + )) + finished.append(id) + case .terminated: finished.append(id) + @unknown default: + preconditionFailure("Unknown stream yield result") + } + } + for id in finished { subscribers.removeValue(forKey: id) } + } + + private func acquireLock() throws -> Int32 { + let path = socketPath + ".lock" + let fd = Darwin.open(path, O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK, S_IRUSR | S_IWUSR) + guard fd >= 0 else { throw IPCTransportError.system(operation: "open lock", code: errno) } + do { + var info = stat() + guard fstat(fd, &info) == 0 else { throw IPCTransportError.system(operation: "fstat lock", code: errno) } + guard info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFREG, info.st_nlink == 1 else { + throw IPCTransportError.unsafeExistingPath(path) + } + guard flock(fd, LOCK_EX | LOCK_NB) == 0 else { + if errno == EWOULDBLOCK { throw IPCTransportError.alreadyRunning(socketPath) } + throw IPCTransportError.system(operation: "flock", code: errno) + } + guard fchmod(fd, S_IRUSR | S_IWUSR) == 0 else { + throw IPCTransportError.system(operation: "chmod lock", code: errno) + } + return fd + } catch { + Darwin.close(fd) + throw error + } + } + + private func removeStaleSocket() throws { + guard let identity = try SocketIdentity.read(path: socketPath) else { return } + let probe = try makeSocket() + defer { Darwin.close(probe) } + var address = try SocketAddress(socketPath) + let result = address.withPointer { Darwin.connect(probe, $0, $1) } + if result == 0 || errno == EINPROGRESS || errno == EAGAIN { + throw IPCTransportError.alreadyRunning(socketPath) + } + guard errno == ECONNREFUSED || errno == ENOENT else { + throw IPCTransportError.system(operation: "probe", code: errno) + } + try identity.remove(path: socketPath) + } + + private func acceptClients(generation: UUID) async { + guard self.generation == generation, let listener else { return } + while self.generation == generation { + let fd = Darwin.accept(listener, nil, nil) + if fd < 0 { + if errno == EINTR { continue } + if errno != EAGAIN && errno != EWOULDBLOCK { + onError(IPCTransportError.system(operation: "accept", code: errno)) + } + return + } + do { + try configureSocket(fd) + var uid: uid_t = 0 + var gid: gid_t = 0 + guard getpeereid(fd, &uid, &gid) == 0 else { + throw IPCTransportError.system(operation: "getpeereid", code: errno) + } + guard uid == getuid() else { throw IPCTransportError.unsafeExistingPath(socketPath) } + let id = UUID() + let channel = SocketChannel(descriptor: fd) + let task = Task { await serve(id: id, channel: channel) } + clients[id] = Client(channel: channel, task: task) + } catch { + Darwin.close(fd) + onError(error) + } + } + } + + private func serve(id: UUID, channel: SocketChannel) async { + do { + while let line = try await channel.readLine() { + let request: IPCRequest + do { + request = try IPCCodec.decode(IPCRequest.self, from: line) + } catch { + let envelope: RequestEnvelope? + do { envelope = try JSONDecoder().decode(RequestEnvelope.self, from: line) } catch { + envelope = nil + } + let failure: IPCError + if let version = envelope?.v, version != IPCProtocol.version { + failure = unsupportedVersion(version) + } else { + failure = IPCError( + code: "invalid_request", + message: String( + localized: "Expected a JSON request with v, id, command, and string args.", + bundle: .module) + ) + } + let response = IPCResponse(id: envelope?.id, error: failure) + try await channel.write(IPCCodec.encode(response)) + continue + } + guard request.v == IPCProtocol.version else { + try await channel.write( + IPCCodec.encode(IPCResponse(id: request.id, error: unsupportedVersion(request.v)))) + continue + } + if request.command == "subscribe" { + do { try await stream(request: request, id: id, channel: channel) } catch let error as IPCError { + try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, error: error))) + } + break + } + let response: IPCResponse + do { response = IPCResponse(id: request.id, result: try await execute(request)) } catch { + response = IPCResponse(id: request.id, error: handlerError(error)) + } + try await channel.write(IPCCodec.encode(response)) + } + } catch { + if !Task.isCancelled { onError(error) } + } + subscribers.removeValue(forKey: id)?.continuation.finish() + clients.removeValue(forKey: id) + await channel.close() + } + + private func execute(_ request: IPCRequest) async throws -> JSONValue { + switch request.command { + case "ping": + try requireNoArguments(request) + return .string("pong") + case "version": + try requireNoArguments(request) + return .object(["protocol": .integer(Int64(IPCProtocol.version)), "version": .string(serverVersion)]) + case "query": + guard request.args.count == 1, let argument = request.args.first, let query = IPCQuery(rawValue: argument) + else { + throw invalidArguments() + } + return try await handler.query(query) + case "run": + guard let command = request.args.first, !command.isEmpty else { throw invalidArguments() } + return try await handler.run(command: command, args: Array(request.args.dropFirst())) + case "reload-config": + try requireNoArguments(request) + return try await handler.reloadConfig() + default: + throw IPCError( + code: "unknown_command", + message: String(localized: "Unknown IPC command: \(request.command)", bundle: .module)) + } + } + + private func stream(request: IPCRequest, id: UUID, channel: SocketChannel) async throws { + var topics = Set() + for argument in request.args { + guard let topic = IPCTopic(rawValue: argument) else { throw invalidArguments() } + topics.insert(topic) + } + if topics.isEmpty { topics = Set(IPCTopic.allCases) } + let (events, continuation) = AsyncThrowingStream.makeStream( + bufferingPolicy: .bufferingOldest(128)) + subscribers[id] = Subscriber(topics: topics, continuation: continuation) + defer { subscribers.removeValue(forKey: id)?.continuation.finish() } + try await channel.write( + IPCCodec.encode( + IPCResponse( + id: request.id, + result: .object(["topics": .array(topics.map(\.rawValue).sorted().map(JSONValue.string))]) + ))) + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + while (try await channel.readLine()) != nil { + throw IPCError( + code: "subscription_only", + message: String(localized: "A subscribed connection only receives events.", bundle: .module)) + } + } + group.addTask { + do { + for try await event in events { try await channel.write(IPCCodec.encode(event)) } + } catch let error as IPCError { + try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, error: error))) + } + } + defer { group.cancelAll() } + _ = try await group.next() + } + } + + private func requireNoArguments(_ request: IPCRequest) throws { + guard request.args.isEmpty else { throw invalidArguments() } + } + + private func invalidArguments() -> IPCError { + IPCError( + code: "invalid_arguments", + message: String(localized: "The command arguments are missing or invalid.", bundle: .module)) + } + + private func unsupportedVersion(_ version: Int) -> IPCError { + IPCError( + code: "unsupported_version", + message: String( + localized: "Unsupported protocol version \(version). This server supports v=1.", bundle: .module)) + } + + private func handlerError(_ error: any Error) -> IPCError { + if let error = error as? IPCError { return error } + return IPCError(code: "handler_error", message: error.localizedDescription) + } + + private struct Client { + let channel: SocketChannel + let task: Task + } + + private struct Subscriber { + let topics: Set + let continuation: AsyncThrowingStream.Continuation + } + + private struct RequestEnvelope: Decodable { + let v: Int? + let id: IPCRequestID? + } +} + +private struct SocketIdentity { + let device: dev_t + let inode: ino_t + + static func read(path: String) throws -> Self? { + var info = stat() + guard lstat(path, &info) == 0 else { + if errno == ENOENT { return nil } + throw IPCTransportError.system(operation: "lstat", code: errno) + } + guard info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFSOCK else { + throw IPCTransportError.unsafeExistingPath(path) + } + return Self(device: info.st_dev, inode: info.st_ino) + } + + func remove(path: String) throws { + guard let current = try Self.read(path: path), current.device == device, current.inode == inode else { return } + guard unlink(path) == 0 || errno == ENOENT else { + throw IPCTransportError.system(operation: "unlink", code: errno) + } + } + + func removeIfOwned(path: String) { + do { try remove(path: path) } catch { + Logger(subsystem: "com.tessera.ipc", category: "cleanup").error( + "\(error.localizedDescription, privacy: .public)") + } + } +} diff --git a/Sources/TesseraIPC/Resources/Localizable.xcstrings b/Sources/TesseraIPC/Resources/Localizable.xcstrings new file mode 100644 index 00000000..215138fb --- /dev/null +++ b/Sources/TesseraIPC/Resources/Localizable.xcstrings @@ -0,0 +1,237 @@ +{ + "sourceLanguage": "en", + "strings": { + "The socket path is empty, relative, or too long: %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The socket path is empty, relative, or too long: %@" + } + } + } + }, + "Socket operation %@ failed (%d): %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Socket operation %@ failed (%d): %@" + } + } + } + }, + "Another Tessera server already owns %@.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Another Tessera server already owns %@." + } + } + } + }, + "Refusing to replace a file, link, or socket owned by another user at %@.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Refusing to replace a file, link, or socket owned by another user at %@." + } + } + } + }, + "Tessera isn't running. Open the Tessera app and try again. Socket: %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tessera isn't running. Open the Tessera app and try again. Socket: %@" + } + } + } + }, + "The Tessera connection closed.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The Tessera connection closed." + } + } + } + }, + "The connection ended before a complete JSON message arrived.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The connection ended before a complete JSON message arrived." + } + } + } + }, + "The JSON message exceeds the 1 MiB limit.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The JSON message exceeds the 1 MiB limit." + } + } + } + }, + "Another operation is already using this connection.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Another operation is already using this connection." + } + } + } + }, + "Invalid Tessera response: %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Invalid Tessera response: %@" + } + } + } + }, + "The event consumer fell behind. Reconnect and query the current state.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The event consumer fell behind. Reconnect and query the current state." + } + } + } + }, + "Expected a JSON request with v, id, command, and string args.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Expected a JSON request with v, id, command, and string args." + } + } + } + }, + "Unknown IPC command: %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Unknown IPC command: %@" + } + } + } + }, + "A subscribed connection only receives events.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A subscribed connection only receives events." + } + } + } + }, + "The command arguments are missing or invalid.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The command arguments are missing or invalid." + } + } + } + }, + "Unsupported protocol version %lld. This server supports v=1.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Unsupported protocol version %lld. This server supports v=1." + } + } + } + }, + "Use subscribe(topics:) to receive events.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Use subscribe(topics:) to receive events." + } + } + } + }, + "Expected an event, not another response.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Expected an event, not another response." + } + } + } + }, + "Unsupported event version: %lld": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Unsupported event version: %lld" + } + } + } + }, + "Unsupported response version: %lld": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Unsupported response version: %lld" + } + } + } + }, + "The response ID does not match the request.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The response ID does not match the request." + } + } + } + } + }, + "version": "1.0" +} diff --git a/Sources/TesseraIPC/Resources/en.lproj/Localizable.strings b/Sources/TesseraIPC/Resources/en.lproj/Localizable.strings new file mode 100644 index 00000000..f029cace --- /dev/null +++ b/Sources/TesseraIPC/Resources/en.lproj/Localizable.strings @@ -0,0 +1,48 @@ + + + + + A subscribed connection only receives events. + A subscribed connection only receives events. + Another Tessera server already owns %@. + Another Tessera server already owns %@. + Another operation is already using this connection. + Another operation is already using this connection. + Expected a JSON request with v, id, command, and string args. + Expected a JSON request with v, id, command, and string args. + Expected an event, not another response. + Expected an event, not another response. + Invalid Tessera response: %@ + Invalid Tessera response: %@ + Refusing to replace a file, link, or socket owned by another user at %@. + Refusing to replace a file, link, or socket owned by another user at %@. + Socket operation %@ failed (%d): %@ + Socket operation %@ failed (%d): %@ + Tessera isn't running. Open the Tessera app and try again. Socket: %@ + Tessera isn't running. Open the Tessera app and try again. Socket: %@ + The JSON message exceeds the 1 MiB limit. + The JSON message exceeds the 1 MiB limit. + The Tessera connection closed. + The Tessera connection closed. + The command arguments are missing or invalid. + The command arguments are missing or invalid. + The connection ended before a complete JSON message arrived. + The connection ended before a complete JSON message arrived. + The event consumer fell behind. Reconnect and query the current state. + The event consumer fell behind. Reconnect and query the current state. + The response ID does not match the request. + The response ID does not match the request. + The socket path is empty, relative, or too long: %@ + The socket path is empty, relative, or too long: %@ + Unknown IPC command: %@ + Unknown IPC command: %@ + Unsupported event version: %lld + Unsupported event version: %lld + Unsupported protocol version %lld. This server supports v=1. + Unsupported protocol version %lld. This server supports v=1. + Unsupported response version: %lld + Unsupported response version: %lld + Use subscribe(topics:) to receive events. + Use subscribe(topics:) to receive events. + + diff --git a/Sources/TesseraIPC/Socket.swift b/Sources/TesseraIPC/Socket.swift new file mode 100644 index 00000000..3b4f2c25 --- /dev/null +++ b/Sources/TesseraIPC/Socket.swift @@ -0,0 +1,278 @@ +public import Darwin +import Dispatch +public import Foundation + +public enum IPCTransportError: Error, Sendable, Equatable, LocalizedError { + case invalidPath(String) + case system(operation: String, code: Int32) + case alreadyRunning(String) + case unsafeExistingPath(String) + case notRunning(String) + case closed + case truncatedMessage + case messageTooLarge + case operationInProgress + case protocolViolation(String) + + public var errorDescription: String? { + switch self { + case .invalidPath(let path): + String(localized: "The socket path is empty, relative, or too long: \(path)", bundle: .module) + case .system(let operation, let code): + String( + localized: "Socket operation \(operation) failed (\(code)): \(String(cString: strerror(code)))", + bundle: .module) + case .alreadyRunning(let path): + String(localized: "Another Tessera server already owns \(path).", bundle: .module) + case .unsafeExistingPath(let path): + String( + localized: "Refusing to replace a file, link, or socket owned by another user at \(path).", + bundle: .module) + case .notRunning(let path): + String( + localized: "Tessera isn't running. Open the Tessera app and try again. Socket: \(path)", bundle: .module + ) + case .closed: + String(localized: "The Tessera connection closed.", bundle: .module) + case .truncatedMessage: + String(localized: "The connection ended before a complete JSON message arrived.", bundle: .module) + case .messageTooLarge: + String(localized: "The JSON message exceeds the 1 MiB limit.", bundle: .module) + case .operationInProgress: + String(localized: "Another operation is already using this connection.", bundle: .module) + case .protocolViolation(let detail): + String(localized: "Invalid Tessera response: \(detail)", bundle: .module) + } + } +} + +public enum IPCSocketPath { + public static func resolve( + environment: [String: String] = ProcessInfo.processInfo.environment, + uid: UInt32 = getuid(), + temporaryDirectory: String = NSTemporaryDirectory() + ) throws -> String { + let path: String + if let override = environment["TESSERA_SOCKET"] { + path = override + } else { + let directory = environment["TMPDIR"] ?? temporaryDirectory + path = (directory as NSString).appendingPathComponent("tessera-\(uid).sock") + } + _ = try SocketAddress(path) + return path + } +} + +struct SocketAddress { + var value: sockaddr_un + let length: socklen_t + + init(_ path: String) throws { + var address = sockaddr_un() + let bytes = Array(path.utf8) + guard path.hasPrefix("/"), !bytes.contains(0), bytes.count < MemoryLayout.size(ofValue: address.sun_path) else { + throw IPCTransportError.invalidPath(path) + } + address.sun_family = sa_family_t(AF_UNIX) + length = socklen_t(MemoryLayout.size) + address.sun_len = UInt8(length) + withUnsafeMutableBytes(of: &address.sun_path) { destination in + destination.copyBytes(from: bytes) + } + value = address + } + + mutating func withPointer(_ body: (UnsafePointer, socklen_t) throws -> Result) rethrows -> Result + { + try withUnsafePointer(to: &value) { pointer in + try pointer.withMemoryRebound(to: sockaddr.self, capacity: 1) { try body($0, length) } + } + } +} + +func makeSocket() throws -> Int32 { + let fd = Darwin.socket(AF_UNIX, SOCK_STREAM, 0) + guard fd >= 0 else { throw IPCTransportError.system(operation: "socket", code: errno) } + do { + try configureSocket(fd) + return fd + } catch { + Darwin.close(fd) + throw error + } +} + +func configureSocket(_ fd: Int32) throws { + guard fcntl(fd, F_SETFL, O_NONBLOCK) == 0, fcntl(fd, F_SETFD, FD_CLOEXEC) == 0 else { + throw IPCTransportError.system(operation: "fcntl", code: errno) + } + var enabled: Int32 = 1 + guard setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &enabled, socklen_t(MemoryLayout.size)) == 0 else { + throw IPCTransportError.system(operation: "setsockopt", code: errno) + } +} + +actor SocketChannel { + private var descriptor: Int32? + private var buffer = Data() + private var reading = false + private var writing = false + private var readSource: (any DispatchSourceRead)? + private var writeSource: (any DispatchSourceWrite)? + private var readWaiter: CheckedContinuation? + private var writeWaiter: CheckedContinuation? + private var readToken: UUID? + private var writeToken: UUID? + + init(descriptor: Int32) { self.descriptor = descriptor } + + deinit { + readSource?.cancel() + writeSource?.cancel() + if let descriptor { Darwin.close(descriptor) } + } + + func connect(path: String) async throws { + guard let descriptor else { throw IPCTransportError.closed } + var address = try SocketAddress(path) + let result = address.withPointer { Darwin.connect(descriptor, $0, $1) } + if result == 0 { return } + let code = errno + if code == ENOENT || code == ECONNREFUSED { throw IPCTransportError.notRunning(path) } + guard code == EINPROGRESS || code == EAGAIN else { + throw IPCTransportError.system(operation: "connect", code: code) + } + try await wait(read: false) + guard let descriptor = self.descriptor else { throw IPCTransportError.closed } + var socketError: Int32 = 0 + var length = socklen_t(MemoryLayout.size) + guard getsockopt(descriptor, SOL_SOCKET, SO_ERROR, &socketError, &length) == 0 else { + throw IPCTransportError.system(operation: "getsockopt", code: errno) + } + if socketError == ENOENT || socketError == ECONNREFUSED { throw IPCTransportError.notRunning(path) } + guard socketError == 0 else { throw IPCTransportError.system(operation: "connect", code: socketError) } + } + + func readLine() async throws -> Data? { + guard !reading else { throw IPCTransportError.operationInProgress } + reading = true + defer { reading = false } + while true { + try Task.checkCancellation() + if let newline = buffer.firstIndex(of: 0x0A) { + let count = buffer.distance(from: buffer.startIndex, to: newline) + guard count <= IPCProtocol.maximumMessageBytes else { throw IPCTransportError.messageTooLarge } + let line = Data(buffer[.. 0 { + buffer.append(contentsOf: bytes.prefix(count)) + } else if count == 0 { + guard buffer.isEmpty else { throw IPCTransportError.truncatedMessage } + return nil + } else if errno == EINTR { + continue + } else if errno == EAGAIN || errno == EWOULDBLOCK { + try await wait(read: true) + } else { + throw IPCTransportError.system(operation: "recv", code: errno) + } + } + } + + func write(_ data: Data) async throws { + guard !writing else { throw IPCTransportError.operationInProgress } + writing = true + defer { writing = false } + var offset = 0 + while offset < data.count { + try Task.checkCancellation() + guard let descriptor else { throw IPCTransportError.closed } + let count = data.withUnsafeBytes { bytes in + guard let base = bytes.baseAddress else { return 0 } + return Darwin.send(descriptor, base.advanced(by: offset), data.count - offset, 0) + } + if count > 0 { + offset += count + } else if count < 0 && errno == EINTR { + continue + } else if count < 0 && (errno == EAGAIN || errno == EWOULDBLOCK) { + try await wait(read: false) + } else { + throw IPCTransportError.system(operation: "send", code: count == 0 ? EPIPE : errno) + } + } + } + + func close() { + readSource?.cancel() + writeSource?.cancel() + readSource = nil + writeSource = nil + if let descriptor { + Darwin.shutdown(descriptor, SHUT_RDWR) + Darwin.close(descriptor) + self.descriptor = nil + } + readWaiter?.resume(throwing: IPCTransportError.closed) + writeWaiter?.resume(throwing: IPCTransportError.closed) + readWaiter = nil + writeWaiter = nil + } + + private func wait(read: Bool) async throws { + try await withTaskCancellationHandler { + try Task.checkCancellation() + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + guard let descriptor else { + continuation.resume(throwing: IPCTransportError.closed) + return + } + let token = UUID() + if read { + let source = DispatchSource.makeReadSource(fileDescriptor: descriptor, queue: .global()) + readWaiter = continuation + readSource = source + readToken = token + source.setEventHandler { @Sendable in Task { await self.ready(read: true, token: token) } } + source.resume() + } else { + let source = DispatchSource.makeWriteSource(fileDescriptor: descriptor, queue: .global()) + writeWaiter = continuation + writeSource = source + writeToken = token + source.setEventHandler { @Sendable in Task { await self.ready(read: false, token: token) } } + source.resume() + } + } + } onCancel: { + Task { await self.close() } + } + } + + private func ready(read: Bool, token: UUID) { + if read { + guard readToken == token else { return } + readToken = nil + readSource?.cancel() + readSource = nil + let waiter = readWaiter + readWaiter = nil + waiter?.resume() + } else { + guard writeToken == token else { return } + writeToken = nil + writeSource?.cancel() + writeSource = nil + let waiter = writeWaiter + writeWaiter = nil + waiter?.resume() + } + } +} diff --git a/Sources/TesseraIPC/TesseraIPC.docc/TesseraIPC.md b/Sources/TesseraIPC/TesseraIPC.docc/TesseraIPC.md new file mode 100644 index 00000000..4d432bb7 --- /dev/null +++ b/Sources/TesseraIPC/TesseraIPC.docc/TesseraIPC.md @@ -0,0 +1,55 @@ +# TesseraIPC + +Tessera's local, versioned socket API. No window model types cross this boundary. + +## Connect + +The path is `$TMPDIR/tessera-$UID.sock`. `TESSERA_SOCKET` overrides it; the app and CLI must use the same override. Paths must be absolute and fit the Unix socket's 103-byte path limit. + +`IPCServer(handler:socketPath:serverVersion:onError:)` takes a `Sendable` handler with three async methods: + +- `query(_:)` for windows, workspaces, displays, and config. +- `run(command:args:)` for engine commands, without IPC-specific validation. +- `reloadConfig()` for an explicit config reload. + +Each returns `JSONValue`. Throw `IPCError(code:message:)` for a stable error code; other errors become `handler_error` with their localized description. The app chooses the snapshot fields. `serverVersion` should come from the app's build metadata. + +Call `start()` once and `stop()` during shutdown. Call `publish(_:)` when an engine event reaches the app. A main-actor handler can conform directly with async methods; the socket never blocks on the engine. + +The socket and its companion `.lock` file have mode `0600`. Startup refuses a live socket, removes only stale sockets owned by this user, and never follows a symlink. The empty lock file remains after shutdown so racing starts always lock the same inode. Runtime failures go to `onError`, or unified logging by default. + +## Wire format + +Every message is UTF-8 JSON followed by a newline. Requests and responses are limited to 1 MiB before the newline. IDs are strings or signed 64-bit integers. + +```json +{"v":1,"id":1,"command":"query","args":["windows"]} +{"v":1,"id":1,"ok":true,"result":[]} +{"v":1,"id":2,"ok":false,"error":{"code":"unknown_command","message":"Unknown IPC command: example"}} +``` + +A malformed request gets `invalid_request`, with a null ID if its envelope cannot be read. Unsupported versions get `unsupported_version`; the response itself always uses v=1. + +Commands are `query`, `run`, `subscribe`, `ping`, `version`, and `reload-config`. `run` takes the engine command as its first argument. Ping returns `"pong"`. Version returns `{"protocol":1,"version":"…"}`. + +## Events and cancellation + +Subscribe takes any of `focus`, `layout`, `workspace`, and `window`. No topics means all topics. The first response acknowledges the topics; only events follow on that connection: + +```json +{"v":1,"id":3,"command":"subscribe","args":["focus","layout"]} +{"v":1,"id":3,"ok":true,"result":{"topics":["focus","layout"]}} +{"v":1,"topic":"focus","data":{"window":42}} +``` + +`IPCClient.request(_:)` uses a fresh connection per request, so concurrent calls are safe. It returns both successful and failed responses; transport failures throw. `subscribe(topics:)` returns `IPCSubscription`, whose `events` stream throws for protocol or server errors. Call `cancel()` when leaving a subscription, or `IPCClient.close()` to close all of that client's connections. Canceling an event-reading task also disconnects. + +Queues hold at most 128 events. A slow subscriber receives `slow_subscriber` and must reconnect and query current state; events are never silently dropped. A subscription has no replay or sequence cursor. + +## Localized strings + +The String Catalog is the source of truth. SwiftPM copies catalogs rather than compiling them, so keep its compiled strings beside it: + +```sh +xcrun xcstringstool compile Sources/TesseraIPC/Resources/Localizable.xcstrings --output-directory Sources/TesseraIPC/Resources +``` diff --git a/Sources/TesseraIPC/TesseraIPC.swift b/Sources/TesseraIPC/TesseraIPC.swift index 8b137891..2a0cefd7 100644 --- a/Sources/TesseraIPC/TesseraIPC.swift +++ b/Sources/TesseraIPC/TesseraIPC.swift @@ -1 +1,204 @@ +public import Foundation +public enum IPCProtocol { + public static let version = 1 + public static let maximumMessageBytes = 1_048_576 +} + +public enum JSONValue: Sendable, Equatable, Codable { + case null + case bool(Bool) + case integer(Int64) + case number(Double) + case string(String) + case array([JSONValue]) + case object([String: JSONValue]) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + if container.decodeNil() { + self = .null + } else { + do { self = .bool(try container.decode(Bool.self)) } catch DecodingError.typeMismatch { + self = try Self.decodeRemaining(container) + } + } + } + + private static func decodeRemaining(_ container: any SingleValueDecodingContainer) throws -> Self { + do { + let number = try container.decode(Double.self) + if number.rounded() == number, number >= Double(Int64.min), number <= Double(Int64.max) { + do { return .integer(try container.decode(Int64.self)) } catch DecodingError.dataCorrupted { + return .number(number) + } + } + return .number(number) + } catch DecodingError.typeMismatch {} + do { return .string(try container.decode(String.self)) } catch DecodingError.typeMismatch {} + do { return .array(try container.decode([JSONValue].self)) } catch DecodingError.typeMismatch {} + return .object(try container.decode([String: JSONValue].self)) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .null: try container.encodeNil() + case .bool(let value): try container.encode(value) + case .integer(let value): try container.encode(value) + case .number(let value): try container.encode(value) + case .string(let value): try container.encode(value) + case .array(let value): try container.encode(value) + case .object(let value): try container.encode(value) + } + } +} + +public enum IPCRequestID: Sendable, Equatable, Hashable, Codable { + case string(String) + case integer(Int64) + + public init(from decoder: any Decoder) throws { + let container = try decoder.singleValueContainer() + do { self = .string(try container.decode(String.self)) } catch DecodingError.typeMismatch { + self = .integer(try container.decode(Int64.self)) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .string(let value): try container.encode(value) + case .integer(let value): try container.encode(value) + } + } +} + +public struct IPCRequest: Sendable, Equatable, Codable { + public var v: Int + public var id: IPCRequestID + public var command: String + public var args: [String] + + public init( + id: IPCRequestID = .string(UUID().uuidString), command: String, args: [String] = [], + v: Int = IPCProtocol.version + ) { + self.v = v + self.id = id + self.command = command + self.args = args + } +} + +public struct IPCError: Error, Sendable, Equatable, Codable, LocalizedError { + public var code: String + public var message: String + + public init(code: String, message: String) { + self.code = code + self.message = message + } + + public var errorDescription: String? { message } +} + +public struct IPCResponse: Sendable, Equatable, Codable { + public let v: Int + public let id: IPCRequestID? + public let ok: Bool + public let result: JSONValue? + public let error: IPCError? + + public init(id: IPCRequestID?, result: JSONValue, v: Int = IPCProtocol.version) { + self.v = v + self.id = id + self.ok = true + self.result = result + self.error = nil + } + + public init(id: IPCRequestID?, error: IPCError, v: Int = IPCProtocol.version) { + self.v = v + self.id = id + self.ok = false + self.result = nil + self.error = error + } + + private enum CodingKeys: String, CodingKey { case v, id, ok, result, error } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + v = try container.decode(Int.self, forKey: .v) + id = try container.decodeIfPresent(IPCRequestID.self, forKey: .id) + ok = try container.decode(Bool.self, forKey: .ok) + if ok { + guard container.contains(.result), !container.contains(.error) else { + throw DecodingError.dataCorruptedError( + forKey: .result, in: container, + debugDescription: "A successful response must contain only a result.") + } + result = try container.decode(JSONValue.self, forKey: .result) + error = nil + } else { + guard !container.contains(.result) else { + throw DecodingError.dataCorruptedError( + forKey: .error, in: container, debugDescription: "A failed response must contain only an error.") + } + result = nil + error = try container.decode(IPCError.self, forKey: .error) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(v, forKey: .v) + try container.encode(id, forKey: .id) + try container.encode(ok, forKey: .ok) + if ok { try container.encode(result, forKey: .result) } else { try container.encode(error, forKey: .error) } + } +} + +public enum IPCQuery: String, Sendable, Codable, CaseIterable { + case windows, workspaces, displays, config +} + +public enum IPCTopic: String, Sendable, Codable, CaseIterable { + case focus, layout, workspace, window +} + +public struct IPCEvent: Sendable, Equatable, Codable { + public var v: Int + public var topic: IPCTopic + public var data: JSONValue + + public init(topic: IPCTopic, data: JSONValue, v: Int = IPCProtocol.version) { + self.v = v + self.topic = topic + self.data = data + } +} + +public protocol IPCHandler: Sendable { + func query(_ query: IPCQuery) async throws -> JSONValue + func run(command: String, args: [String]) async throws -> JSONValue + func reloadConfig() async throws -> JSONValue +} + +public enum IPCCodec { + public static func encode(_ message: Message) throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + var data = try encoder.encode(message) + guard data.count <= IPCProtocol.maximumMessageBytes else { throw IPCTransportError.messageTooLarge } + data.append(0x0A) + return data + } + + public static func decode(_ type: Message.Type, from data: Data) throws -> Message { + let payload = data.last == 0x0A ? data.dropLast() : data[...] + guard payload.count <= IPCProtocol.maximumMessageBytes else { throw IPCTransportError.messageTooLarge } + return try JSONDecoder().decode(type, from: payload) + } +} diff --git a/Sources/tessera/CLIOutput.swift b/Sources/tessera/CLIOutput.swift new file mode 100644 index 00000000..bf701d4c --- /dev/null +++ b/Sources/tessera/CLIOutput.swift @@ -0,0 +1,211 @@ +import Foundation +import TesseraIPC + +struct CLIOutput { + static func write(_ text: String) throws { + try FileHandle.standardOutput.write(contentsOf: Data(text.utf8)) + } + + static func response(_ response: IPCResponse, query: IPCQuery? = nil, json: Bool = false) throws -> String { + guard response.ok else { + guard let error = response.error else { throw CLIOutputError.missingError } + throw CLIOutputError.rejected(code: error.code, message: error.message) + } + guard let result = response.result else { throw CLIOutputError.missingResult } + return try format(result, query: query, json: json) + } + + static func event(_ event: IPCEvent, json: Bool = false) throws -> String { + if json { return try jsonLine(event) } + return event.topic.rawValue + ": " + escapeCell(String(try jsonLine(event.data).dropLast())) + "\n" + } + + static func format(_ value: JSONValue, query: IPCQuery? = nil, json: Bool = false) throws -> String { + if json { return try jsonLine(value) } + + switch value { + case .array(let rows): + return try rowTable(rows, emptyMessage: emptyMessage(query)) + case .object(let fields): + if let query, fields.count == 1, let rows = fields[query.rawValue] { + return try format(rows, query: query) + } + guard !fields.isEmpty else { return emptyMessage(query) + "\n" } + let rows = try fields.sorted { $0.key < $1.key }.map { field in + [escapeCell(field.key), try cell(field.value)] + } + let keyHeading = + query == .config + ? String(localized: "Setting", bundle: .module) : String(localized: "Field", bundle: .module) + return table(headers: [keyHeading, String(localized: "Value", bundle: .module)], rows: rows) + case .null: + return String(localized: "Done.", bundle: .module) + "\n" + default: + return try cell(value) + "\n" + } + } + + static func jsonLine(_ value: Value) throws -> String { + guard let text = String(data: try IPCCodec.encode(value), encoding: .utf8) else { + throw CLIOutputError.invalidUTF8 + } + return text + } + + static func rowTable(_ values: [JSONValue], emptyMessage: String) throws -> String { + guard !values.isEmpty else { return emptyMessage + "\n" } + let objects = values.compactMap { value -> [String: JSONValue]? in + guard case .object(let fields) = value else { return nil } + return fields + } + if objects.isEmpty { + return table( + headers: [String(localized: "Value", bundle: .module)], + rows: try values.map { [try cell($0)] } + ) + } + guard objects.count == values.count else { throw CLIOutputError.inconsistentRows } + let columns = Set(objects.flatMap(\.keys)).sorted(by: columnOrder) + guard !columns.isEmpty else { + return table(headers: [String(localized: "Value", bundle: .module)], rows: objects.map { _ in ["{}"] }) + } + let rows = try objects.map { fields in + try columns.map { key in + if let value = fields[key] { return try cell(value) } + return String(localized: "—", bundle: .module) + } + } + return table(headers: columns.map(heading), rows: rows) + } + + static func table(headers: [String], rows: [[String]]) -> String { + precondition(!headers.isEmpty, "Tables need at least one column.") + precondition(rows.allSatisfy { $0.count == headers.count }, "Table rows must match the column count.") + let safeHeaders = headers.map(escapeCell) + let safeRows = rows.map { $0.map(escapeCell) } + let widths = safeRows.reduce(safeHeaders.map(terminalWidth)) { widths, row in + zip(widths, row).map { max($0.0, terminalWidth($0.1)) } + } + func line(_ row: [String]) -> String { + row.enumerated().map { index, cell in + if index == row.count - 1 { return cell } + return cell + String(repeating: " ", count: widths[index] - terminalWidth(cell)) + }.joined(separator: " ") + } + let separator = widths.map { String(repeating: "─", count: $0) }.joined(separator: " ") + return ([line(safeHeaders), separator] + safeRows.map(line)).joined(separator: "\n") + "\n" + } + + static func cell(_ value: JSONValue) throws -> String { + switch value { + case .null: return String(localized: "—", bundle: .module) + case .bool(let flag): + return flag ? String(localized: "Yes", bundle: .module) : String(localized: "No", bundle: .module) + case .string(let text): return escapeCell(text) + default: return escapeCell(String(try jsonLine(value).dropLast())) + } + } + + static func escapeCell(_ text: String) -> String { + text.unicodeScalars.map { scalar in + switch scalar { + case "\n": return "\\n" + case "\r": return "\\r" + case "\t": return "\\t" + default: + switch scalar.properties.generalCategory { + case .control, .lineSeparator, .paragraphSeparator: + return "\\u{" + String(scalar.value, radix: 16) + "}" + case .format where scalar.value != 0x200C && scalar.value != 0x200D: + return "\\u{" + String(scalar.value, radix: 16) + "}" + default: return String(scalar) + } + } + }.joined() + } + + // Grapheme counts alone misalign wide glyphs, combining marks, and joined emoji in terminal tables. + static func terminalWidth(_ text: String) -> Int { + text.reduce(0) { width, character in + let scalars = character.unicodeScalars + let emoji = + scalars.contains { $0.properties.isEmojiPresentation } + || (scalars.contains { $0.value == 0xFE0F } && scalars.contains { $0.properties.isEmoji }) + if emoji { return width + 2 } + let characterWidth = + scalars.map { scalar -> Int in + switch scalar.properties.generalCategory { + case .nonspacingMark, .enclosingMark, .format: return 0 + default: break + } + switch scalar.value { + case 0x1100...0x115F, 0x2329...0x232A, 0x2E80...0x303E, 0x3040...0xA4CF, + 0xAC00...0xD7A3, 0xF900...0xFAFF, 0xFE10...0xFE19, 0xFE30...0xFE6F, + 0xFF01...0xFF60, 0xFFE0...0xFFE6, 0x1B000...0x1B2FF, 0x1F200...0x1F251, + 0x20000...0x3FFFD: + return 2 + default: return 1 + } + }.max() ?? 0 + return width + characterWidth + } + } + + private static func columnOrder(_ lhs: String, _ rhs: String) -> Bool { + let preferred = ["id", "pid", "app", "title", "name", "workspace", "display", "layout", "focused"] + let left = preferred.firstIndex(of: lhs) ?? preferred.count + let right = preferred.firstIndex(of: rhs) ?? preferred.count + return left == right ? lhs < rhs : left < right + } + + private static func heading(_ key: String) -> String { + switch key { + case "id": return String(localized: "ID", bundle: .module) + case "pid": return String(localized: "PID", bundle: .module) + case "app": return String(localized: "Application", bundle: .module) + case "title": return String(localized: "Title", bundle: .module) + case "name": return String(localized: "Name", bundle: .module) + case "workspace": return String(localized: "Workspace", bundle: .module) + case "display": return String(localized: "Display", bundle: .module) + case "layout": return String(localized: "Layout", bundle: .module) + case "focused": return String(localized: "Focused", bundle: .module) + default: return escapeCell(key) + } + } + + private static func emptyMessage(_ query: IPCQuery?) -> String { + switch query { + case .windows: String(localized: "No windows.", bundle: .module) + case .workspaces: String(localized: "No workspaces.", bundle: .module) + case .displays: String(localized: "No displays.", bundle: .module) + case .config: String(localized: "No configuration values.", bundle: .module) + case nil: String(localized: "No results.", bundle: .module) + } + } +} + +enum CLIOutputError: LocalizedError { + case rejected(code: String, message: String) + case missingResult + case missingError + case inconsistentRows + case invalidUTF8 + + var errorDescription: String? { + switch self { + case .rejected(let code, let message): + String( + localized: + "Tessera rejected the command (\(CLIOutput.escapeCell(code))): \(CLIOutput.escapeCell(message))", + bundle: .module) + case .missingResult: + String(localized: "Tessera returned a response without a result.", bundle: .module) + case .missingError: + String(localized: "Tessera returned a failed response without an error.", bundle: .module) + case .inconsistentRows: + String(localized: "Tessera returned a table mixing records and other values.", bundle: .module) + case .invalidUTF8: + String(localized: "Tessera returned JSON that is not valid UTF-8.", bundle: .module) + } + } +} diff --git a/Sources/tessera/Resources/Localizable.xcstrings b/Sources/tessera/Resources/Localizable.xcstrings new file mode 100644 index 00000000..9dcff3e1 --- /dev/null +++ b/Sources/tessera/Resources/Localizable.xcstrings @@ -0,0 +1,60 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "Application" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Application" } } } }, + "Balance window sizes in the focused workspace." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Balance window sizes in the focused workspace." } } } }, + "Change the focused workspace's layout." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Change the focused workspace's layout." } } } }, + "Check whether Tessera is running." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Check whether Tessera is running." } } } }, + "Close the focused window." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Close the focused window." } } } }, + "Destination workspace name." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Destination workspace name." } } } }, + "Direction: left, right, up, down." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Direction: left, right, up, down." } } } }, + "Display" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Display" } } } }, + "Done." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Done." } } } }, + "Engine command followed by its arguments." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Engine command followed by its arguments." } } } }, + "Field" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Field" } } } }, + "Focus a neighboring window." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Focus a neighboring window." } } } }, + "Focus a workspace by name." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Focus a workspace by name." } } } }, + "Focused" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Focused" } } } }, + "Forward any engine command and its arguments." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Forward any engine command and its arguments." } } } }, + "ID" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "ID" } } } }, + "Inspect windows, workspaces, displays, or configuration." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Inspect windows, workspaces, displays, or configuration." } } } }, + "Layout" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Layout" } } } }, + "Layout name, such as side." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Layout name, such as side." } } } }, + "Move the focused window in a direction." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Move the focused window in a direction." } } } }, + "Name" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Name" } } } }, + "No" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "No" } } } }, + "No configuration values." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "No configuration values." } } } }, + "No displays." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "No displays." } } } }, + "No results." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "No results." } } } }, + "No windows." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "No windows." } } } }, + "No workspaces." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "No workspaces." } } } }, + "PID" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "PID" } } } }, + "Print the CLI version without connecting to Tessera." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Print the CLI version without connecting to Tessera." } } } }, + "Provide an engine command to run." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Provide an engine command to run." } } } }, + "Put --json before the engine command. Everything after the command is forwarded unchanged, including flags and --." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Put --json before the engine command. Everything after the command is forwarded unchanged, including flags and --." } } } }, + "Reload Tessera's configuration." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Reload Tessera's configuration." } } } }, + "Send the focused window to a workspace." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Send the focused window to a workspace." } } } }, + "Setting" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Setting" } } } }, + "Swap the focused window with a neighbor." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Swap the focused window with a neighbor." } } } }, + "Talk to Tessera from your terminal." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Talk to Tessera from your terminal." } } } }, + "Tessera rejected the command (%@): %@" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Tessera rejected the command (%@): %@" } } } }, + "Tessera returned a failed response without an error." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Tessera returned a failed response without an error." } } } }, + "Tessera returned a response without a result." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Tessera returned a response without a result." } } } }, + "Tessera returned a table mixing records and other values." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Tessera returned a table mixing records and other values." } } } }, + "Tessera returned JSON that is not valid UTF-8." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Tessera returned JSON that is not valid UTF-8." } } } }, + "The name must not be empty." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "The name must not be empty." } } } }, + "Title" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Title" } } } }, + "Toggle floating for the focused window." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Toggle floating for the focused window." } } } }, + "Toggle fullscreen for the focused window." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Toggle fullscreen for the focused window." } } } }, + "Topics: focus, layout, workspace, window. Omit to watch all topics." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Topics: focus, layout, workspace, window. Omit to watch all topics." } } } }, + "Value" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Value" } } } }, + "Watch Tessera events until interrupted." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Watch Tessera events until interrupted." } } } }, + "What to inspect: windows, workspaces, displays, config." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "What to inspect: windows, workspaces, displays, config." } } } }, + "Workspace" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Workspace" } } } }, + "Workspace name." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Workspace name." } } } }, + "Write compact JSON for scripts." : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Write compact JSON for scripts." } } } }, + "Yes" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Yes" } } } }, + "—" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "—" } } } } + }, + "version" : "1.0" +} diff --git a/Sources/tessera/Resources/en.lproj/Localizable.strings b/Sources/tessera/Resources/en.lproj/Localizable.strings new file mode 100644 index 00000000..88771b9f --- /dev/null +++ b/Sources/tessera/Resources/en.lproj/Localizable.strings @@ -0,0 +1,114 @@ + + + + + Application + Application + Balance window sizes in the focused workspace. + Balance window sizes in the focused workspace. + Change the focused workspace's layout. + Change the focused workspace's layout. + Check whether Tessera is running. + Check whether Tessera is running. + Close the focused window. + Close the focused window. + Destination workspace name. + Destination workspace name. + Direction: left, right, up, down. + Direction: left, right, up, down. + Display + Display + Done. + Done. + Engine command followed by its arguments. + Engine command followed by its arguments. + Field + Field + Focus a neighboring window. + Focus a neighboring window. + Focus a workspace by name. + Focus a workspace by name. + Focused + Focused + Forward any engine command and its arguments. + Forward any engine command and its arguments. + ID + ID + Inspect windows, workspaces, displays, or configuration. + Inspect windows, workspaces, displays, or configuration. + Layout + Layout + Layout name, such as side. + Layout name, such as side. + Move the focused window in a direction. + Move the focused window in a direction. + Name + Name + No + No + No configuration values. + No configuration values. + No displays. + No displays. + No results. + No results. + No windows. + No windows. + No workspaces. + No workspaces. + PID + PID + Print the CLI version without connecting to Tessera. + Print the CLI version without connecting to Tessera. + Provide an engine command to run. + Provide an engine command to run. + Put --json before the engine command. Everything after the command is forwarded unchanged, including flags and --. + Put --json before the engine command. Everything after the command is forwarded unchanged, including flags and --. + Reload Tessera's configuration. + Reload Tessera's configuration. + Send the focused window to a workspace. + Send the focused window to a workspace. + Setting + Setting + Swap the focused window with a neighbor. + Swap the focused window with a neighbor. + Talk to Tessera from your terminal. + Talk to Tessera from your terminal. + Tessera rejected the command (%@): %@ + Tessera rejected the command (%@): %@ + Tessera returned JSON that is not valid UTF-8. + Tessera returned JSON that is not valid UTF-8. + Tessera returned a failed response without an error. + Tessera returned a failed response without an error. + Tessera returned a response without a result. + Tessera returned a response without a result. + Tessera returned a table mixing records and other values. + Tessera returned a table mixing records and other values. + The name must not be empty. + The name must not be empty. + Title + Title + Toggle floating for the focused window. + Toggle floating for the focused window. + Toggle fullscreen for the focused window. + Toggle fullscreen for the focused window. + Topics: focus, layout, workspace, window. Omit to watch all topics. + Topics: focus, layout, workspace, window. Omit to watch all topics. + Value + Value + Watch Tessera events until interrupted. + Watch Tessera events until interrupted. + What to inspect: windows, workspaces, displays, config. + What to inspect: windows, workspaces, displays, config. + Workspace + Workspace + Workspace name. + Workspace name. + Write compact JSON for scripts. + Write compact JSON for scripts. + Yes + Yes + — + — + + diff --git a/Sources/tessera/TesseraCLI.swift b/Sources/tessera/TesseraCLI.swift new file mode 100644 index 00000000..03ee82a4 --- /dev/null +++ b/Sources/tessera/TesseraCLI.swift @@ -0,0 +1,340 @@ +import ArgumentParser +import Foundation +import TesseraIPC + +@main +struct TesseraCLI: AsyncParsableCommand { + static let version = "0.1.0" + static var resourceBundle: Bundle { .module } + + static let configuration = CommandConfiguration( + commandName: "tessera", + abstract: String(localized: "Talk to Tessera from your terminal.", bundle: .module), + version: version, + subcommands: [ + QueryCommand.self, DirectionCommand.self, + DirectionCommand.self, DirectionCommand.self, + NameCommand.self, NameCommand.self, + NameCommand.self, + SimpleCommand.self, SimpleCommand.self, + SimpleCommand.self, SimpleCommand.self, + SubscribeCommand.self, PingCommand.self, ReloadCommand.self, VersionCommand.self, + RunCommand.self, + ] + ) +} + +struct CLIOptions: ParsableArguments { + @Flag(help: ArgumentHelp(String(localized: "Write compact JSON for scripts.", bundle: .module))) + var json = false +} + +enum CLIInvocation: Sendable, Equatable { + case request(command: String, args: [String], query: IPCQuery?, json: Bool) + case subscribe(topics: [IPCTopic], json: Bool) + case version + + static func engine(_ command: String, args: [String], json: Bool) -> Self { + .request(command: "run", args: [command] + args, query: nil, json: json) + } + + var request: IPCRequest? { + guard case .request(let command, let args, _, _) = self else { return nil } + return IPCRequest(command: command, args: args) + } +} + +protocol CLICommand: AsyncParsableCommand { + var invocation: CLIInvocation { get throws } +} + +extension CLICommand { + mutating func run() async throws { + try await CLIRunner.execute(invocation) + } +} + +enum CLIParsing { + static func parse(_ arguments: [String]) throws -> CLIInvocation { + let parsed = try TesseraCLI.parseAsRoot(arguments) + guard let command = parsed as? any CLICommand else { + throw CleanExit.helpRequest() + } + return try command.invocation + } + + static func requireName(_ name: String) throws { + guard !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + throw ValidationError(String(localized: "The name must not be empty.", bundle: .module)) + } + } +} + +struct QueryArgument: ExpressibleByArgument, Sendable { + let value: IPCQuery + + init?(argument: String) { + guard let value = IPCQuery(rawValue: argument) else { return nil } + self.value = value + } + + static var allValueStrings: [String] { IPCQuery.allCases.map(\.rawValue) } +} + +struct TopicArgument: ExpressibleByArgument, Sendable { + let value: IPCTopic + + init?(argument: String) { + guard let value = IPCTopic(rawValue: argument) else { return nil } + self.value = value + } + + static var allValueStrings: [String] { IPCTopic.allCases.map(\.rawValue) } +} + +struct QueryCommand: CLICommand { + static let configuration = CommandConfiguration( + commandName: "query", + abstract: String(localized: "Inspect windows, workspaces, displays, or configuration.", bundle: .module) + ) + + @OptionGroup var output: CLIOptions + @Argument( + help: ArgumentHelp( + String(localized: "What to inspect: windows, workspaces, displays, config.", bundle: .module), + valueName: "resource" + )) + var resource: QueryArgument + + var invocation: CLIInvocation { + .request(command: "query", args: [resource.value.rawValue], query: resource.value, json: output.json) + } +} + +enum CLIDirection: String, ExpressibleByArgument, Sendable, CaseIterable { + case left, right, up, down +} + +protocol Shortcut: Sendable { + static var name: String { get } + static var abstract: String { get } +} + +protocol NamedShortcut: Shortcut { + static var argumentHelp: String { get } +} + +struct DirectionCommand: CLICommand { + static var configuration: CommandConfiguration { + CommandConfiguration(commandName: Action.name, abstract: Action.abstract) + } + + @OptionGroup var output: CLIOptions + @Argument(help: ArgumentHelp(String(localized: "Direction: left, right, up, down.", bundle: .module))) + var direction: CLIDirection + + var invocation: CLIInvocation { + .engine(Action.name, args: [direction.rawValue], json: output.json) + } +} + +struct NameCommand: CLICommand { + static var configuration: CommandConfiguration { + CommandConfiguration(commandName: Action.name, abstract: Action.abstract) + } + + @OptionGroup var output: CLIOptions + @Argument(help: ArgumentHelp(Action.argumentHelp)) var name: String + + mutating func validate() throws { try CLIParsing.requireName(name) } + + var invocation: CLIInvocation { .engine(Action.name, args: [name], json: output.json) } +} + +struct SimpleCommand: CLICommand { + static var configuration: CommandConfiguration { + CommandConfiguration(commandName: Action.name, abstract: Action.abstract) + } + + @OptionGroup var output: CLIOptions + + var invocation: CLIInvocation { .engine(Action.name, args: [], json: output.json) } +} + +enum FocusShortcut: Shortcut { + static let name = "focus" + static var abstract: String { String(localized: "Focus a neighboring window.", bundle: .module) } +} + +enum MoveShortcut: Shortcut { + static let name = "move" + static var abstract: String { String(localized: "Move the focused window in a direction.", bundle: .module) } +} + +enum SwapShortcut: Shortcut { + static let name = "swap" + static var abstract: String { String(localized: "Swap the focused window with a neighbor.", bundle: .module) } +} + +enum LayoutShortcut: NamedShortcut { + static let name = "layout" + static var abstract: String { String(localized: "Change the focused workspace's layout.", bundle: .module) } + static var argumentHelp: String { String(localized: "Layout name, such as side.", bundle: .module) } +} + +enum WorkspaceShortcut: NamedShortcut { + static let name = "workspace" + static var abstract: String { String(localized: "Focus a workspace by name.", bundle: .module) } + static var argumentHelp: String { String(localized: "Workspace name.", bundle: .module) } +} + +enum MoveToWorkspaceShortcut: NamedShortcut { + static let name = "move-to-workspace" + static var abstract: String { String(localized: "Send the focused window to a workspace.", bundle: .module) } + static var argumentHelp: String { String(localized: "Destination workspace name.", bundle: .module) } +} + +enum BalanceShortcut: Shortcut { + static let name = "balance" + static var abstract: String { String(localized: "Balance window sizes in the focused workspace.", bundle: .module) } +} + +enum CloseShortcut: Shortcut { + static let name = "close" + static var abstract: String { String(localized: "Close the focused window.", bundle: .module) } +} + +enum ToggleFloatingShortcut: Shortcut { + static let name = "toggle-floating" + static var abstract: String { String(localized: "Toggle floating for the focused window.", bundle: .module) } +} + +enum ToggleFullscreenShortcut: Shortcut { + static let name = "toggle-fullscreen" + static var abstract: String { String(localized: "Toggle fullscreen for the focused window.", bundle: .module) } +} + +struct SubscribeCommand: CLICommand { + static let configuration = CommandConfiguration( + commandName: "subscribe", + abstract: String(localized: "Watch Tessera events until interrupted.", bundle: .module) + ) + + @OptionGroup var output: CLIOptions + @Argument( + help: ArgumentHelp( + String(localized: "Topics: focus, layout, workspace, window. Omit to watch all topics.", bundle: .module), + valueName: "topic" + )) + var topics: [TopicArgument] = [] + + var invocation: CLIInvocation { .subscribe(topics: topics.map(\.value), json: output.json) } +} + +struct PingCommand: CLICommand { + static let configuration = CommandConfiguration( + commandName: "ping", + abstract: String(localized: "Check whether Tessera is running.", bundle: .module) + ) + + @OptionGroup var output: CLIOptions + + var invocation: CLIInvocation { .request(command: "ping", args: [], query: nil, json: output.json) } +} + +struct ReloadCommand: CLICommand { + static let configuration = CommandConfiguration( + commandName: "reload", + abstract: String(localized: "Reload Tessera's configuration.", bundle: .module) + ) + + @OptionGroup var output: CLIOptions + + var invocation: CLIInvocation { .request(command: "reload-config", args: [], query: nil, json: output.json) } +} + +struct VersionCommand: CLICommand { + static let configuration = CommandConfiguration( + commandName: "version", + abstract: String(localized: "Print the CLI version without connecting to Tessera.", bundle: .module) + ) + + var invocation: CLIInvocation { .version } +} + +struct RunCommand: CLICommand { + static let configuration = CommandConfiguration( + commandName: "run", + abstract: String(localized: "Forward any engine command and its arguments.", bundle: .module), + discussion: String( + localized: + "Put --json before the engine command. Everything after the command is forwarded unchanged, including flags and --.", + bundle: .module + ) + ) + + @OptionGroup var output: CLIOptions + @Argument( + parsing: .captureForPassthrough, + help: ArgumentHelp( + String(localized: "Engine command followed by its arguments.", bundle: .module), valueName: "command" + )) + var commandAndArguments: [String] + + mutating func validate() throws { + guard let command = commandAndArguments.first else { + throw ValidationError(String(localized: "Provide an engine command to run.", bundle: .module)) + } + if command == "--help" || command == "-h" { + throw CleanExit.helpRequest(self) + } + if command == "--version" { + throw CleanExit.message(TesseraCLI.version) + } + try CLIParsing.requireName(command) + } + + var invocation: CLIInvocation { + .request(command: "run", args: commandAndArguments, query: nil, json: output.json) + } +} + +struct CLIRunner { + static func execute( + _ invocation: CLIInvocation, + socketPath: String? = nil, + write: @Sendable (String) throws -> Void = CLIOutput.write + ) async throws { + if invocation == .version { + try write(TesseraCLI.version + "\n") + return + } + + let client = try IPCClient(socketPath: socketPath) + do { + switch invocation { + case .request(let command, let args, let query, let json): + let response = try await client.request(IPCRequest(command: command, args: args)) + try write(CLIOutput.response(response, query: query, json: json)) + case .subscribe(let topics, let json): + let subscription = try await client.subscribe(topics: topics) + do { + for try await event in subscription.events { + try Task.checkCancellation() + try write(CLIOutput.event(event, json: json)) + } + await subscription.cancel() + } catch { + await subscription.cancel() + throw error + } + case .version: + break + } + await client.close() + } catch { + await client.close() + throw error + } + } +} diff --git a/Sources/tessera/main.swift b/Sources/tessera/main.swift deleted file mode 100644 index 0dc82b3b..00000000 --- a/Sources/tessera/main.swift +++ /dev/null @@ -1 +0,0 @@ -print("tessera") diff --git a/Tests/TesseraIPCTests/CLITests.swift b/Tests/TesseraIPCTests/CLITests.swift new file mode 100644 index 00000000..164e708c --- /dev/null +++ b/Tests/TesseraIPCTests/CLITests.swift @@ -0,0 +1,459 @@ +import Foundation +import Synchronization +import TesseraIPC +import Testing + +@testable import tessera + +@Suite("CLI parsing") +struct CLIParsingTests { + @Test(arguments: IPCQuery.allCases, [false, true]) + func query(query: IPCQuery, json: Bool) throws { + let args = ["query", query.rawValue] + (json ? ["--json"] : []) + #expect( + try CLIParsing.parse(args) == .request(command: "query", args: [query.rawValue], query: query, json: json)) + } + + @Test(arguments: ["focus", "move", "swap"], CLIDirection.allCases) + func directionalShortcuts(command: String, direction: CLIDirection) throws { + let invocation = try CLIParsing.parse([command, direction.rawValue]) + #expect(invocation == .engine(command, args: [direction.rawValue], json: false)) + let request = try #require(invocation.request) + #expect(request.command == "run") + #expect(request.args == [command, direction.rawValue]) + #expect(request.v == IPCProtocol.version) + #expect( + try CLIParsing.parse([command, "--json", direction.rawValue]) + == .engine(command, args: [direction.rawValue], json: true)) + } + + @Test(arguments: ["layout", "workspace", "move-to-workspace"], ["side", "Design work", "東京"]) + func namedShortcuts(command: String, name: String) throws { + #expect(try CLIParsing.parse([command, name]) == .engine(command, args: [name], json: false)) + #expect(try CLIParsing.parse([command, name, "--json"]) == .engine(command, args: [name], json: true)) + } + + @Test(arguments: ["balance", "close", "toggle-floating", "toggle-fullscreen"], [false, true]) + func simpleShortcuts(command: String, json: Bool) throws { + #expect(try CLIParsing.parse([command] + (json ? ["--json"] : [])) == .engine(command, args: [], json: json)) + } + + @Test(arguments: [false, true]) + func transportCommands(json: Bool) throws { + let flags = json ? ["--json"] : [] + #expect(try CLIParsing.parse(["ping"] + flags) == .request(command: "ping", args: [], query: nil, json: json)) + #expect( + try CLIParsing.parse(["reload"] + flags) + == .request(command: "reload-config", args: [], query: nil, json: json)) + } + + @Test(arguments: IPCTopic.allCases, [false, true]) + func singleTopic(topic: IPCTopic, json: Bool) throws { + #expect( + try CLIParsing.parse(["subscribe", topic.rawValue] + (json ? ["--json"] : [])) + == .subscribe(topics: [topic], json: json)) + } + + @Test(arguments: [false, true]) + func subscriptionTopics(json: Bool) throws { + let flags = json ? ["--json"] : [] + #expect(try CLIParsing.parse(["subscribe"] + flags) == .subscribe(topics: [], json: json)) + #expect( + try CLIParsing.parse(["subscribe", "focus", "layout"] + flags) + == .subscribe(topics: [.focus, .layout], json: json)) + } + + @Test( + arguments: [ + ["future-command"], + ["resize", "width", "-10"], + ["future-command", "--unknown", "value"], + ["future-command", "--json", "--help", "--version"], + ["future-command", "--", "-a", "two words"], + ["focus", "not-a-shortcut-direction"], + ["query", "not-a-transport-query"], + ["future-command", "", "東京", "quote\"", "\\", "\n"], + ], [false, true]) + func unrestrictedRun(engineArguments: [String], json: Bool) throws { + let args = ["run"] + (json ? ["--json"] : []) + engineArguments + #expect(try CLIParsing.parse(args) == .request(command: "run", args: engineArguments, query: nil, json: json)) + } + + @Test(arguments: [ + ["unknown-command"], ["query"], ["query", "invalid"], ["query", "Windows"], + ["query", "windows", "extra"], ["query", "windows", "--unknown"], + ["focus"], ["focus", "diagonal"], ["focus", "left", "extra"], + ["move", "invalid"], ["swap", "invalid"], + ["layout"], ["layout", ""], ["layout", " \n\t"], ["layout", "side", "extra"], + ["workspace", ""], ["move-to-workspace", " "], + ["subscribe", "invalid"], ["subscribe", "focus", "invalid"], + ["subscribe", "--unknown"], ["ping", "extra"], ["reload", "extra"], + ["balance", "extra"], ["close", "--unknown"], ["run"], ["run", "--json"], ["run", ""], + ["version", "extra"], + ]) + func parsingErrors(arguments: [String]) { + do { + _ = try CLIParsing.parse(arguments) + Issue.record("Expected invalid arguments to fail: \(arguments)") + } catch { + #expect(TesseraCLI.exitCode(for: error).rawValue != 0) + #expect(!TesseraCLI.fullMessage(for: error).isEmpty) + } + } + + @Test func queryFlagBeforeResource() throws { + #expect( + try CLIParsing.parse(["query", "--json", "windows"]) + == .request(command: "query", args: ["windows"], query: .windows, json: true)) + } + + @Test func versionIsLocal() throws { + #expect(try CLIParsing.parse(["version"]) == .version) + #expect(CLIInvocation.version.request == nil) + } + + @Test(arguments: [ + ["--help"], ["--version"], ["query", "--help"], ["run", "--help"], ["run", "-h"], ["run", "--json", "--help"], + ["run", "--version"], ["run", "--json", "--version"], [], + ]) + func informationalExits(arguments: [String]) { + do { + _ = try CLIParsing.parse(arguments) + Issue.record("Expected an informational exit") + } catch { + #expect(TesseraCLI.exitCode(for: error).rawValue == 0) + #expect(!TesseraCLI.fullMessage(for: error).isEmpty) + } + } +} + +@Suite("CLI output") +struct CLIOutputTests { + @Test func windowsTable() throws { + let value: JSONValue = .array([ + .object(["id": .integer(1), "title": .string("Notes"), "focused": .bool(true)]), + .object(["id": .integer(42), "title": .string("Mail"), "focused": .bool(false)]), + ]) + #expect( + try CLIOutput.format(value, query: .windows) + == "ID Title Focused\n── ───── ───────\n1 Notes Yes\n42 Mail No\n") + } + + @Test func configurationTable() throws { + let value: JSONValue = .object(["zeta": .integer(2), "alpha": .bool(true)]) + #expect( + try CLIOutput.format(value, query: .config) == "Setting Value\n─────── ─────\nalpha Yes\nzeta 2\n") + } + + @Test func sparseRowsUseUnionOfColumns() throws { + let value: JSONValue = .array([.object(["id": .integer(1)]), .object(["title": .string("Notes")])]) + #expect(try CLIOutput.format(value, query: .windows) == "ID Title\n── ─────\n1 —\n— Notes\n") + } + + @Test func unknownColumnsAreStable() throws { + let value: JSONValue = .array([.object(["zeta": .integer(1), "alpha": .integer(2), "id": .integer(3)])]) + #expect(try CLIOutput.format(value) == "ID alpha zeta\n── ───── ────\n3 2 1\n") + } + + @Test( + arguments: [ + (IPCQuery.windows, "No windows.\n"), + (IPCQuery.workspaces, "No workspaces.\n"), + (IPCQuery.displays, "No displays.\n"), + (IPCQuery.config, "No configuration values.\n"), + ], [JSONValue.array([]), JSONValue.object([:])]) + func emptyQueryTable(expected: (IPCQuery, String), value: JSONValue) throws { + #expect(try CLIOutput.format(value, query: expected.0) == expected.1) + } + + @Test func emptyGenericTable() throws { + #expect(try CLIOutput.format(.array([])) == "No results.\n") + #expect(try CLIOutput.format(.object([:])) == "No results.\n") + #expect(try CLIOutput.format(.array([]), json: true) == "[]\n") + #expect(try CLIOutput.format(.object([:]), json: true) == "{}\n") + } + + @Test func emptyRecordsRemainVisible() throws { + #expect(try CLIOutput.format(.array([.object([:]), .object([:])])) == "Value\n─────\n{}\n{}\n") + } + + @Test func listValues() throws { + #expect( + try CLIOutput.format(.array([.string("Work"), .string("Home")]), query: .workspaces) + == "Value\n─────\nWork\nHome\n") + } + + @Test func mixedRecordsFailVisibly() { + #expect(throws: CLIOutputError.self) { + try CLIOutput.format(.array([.object(["id": .integer(1)]), .string("not a record")])) + } + } + + @Test func wrappedRows() throws { + let rows: JSONValue = .array([.object(["id": .integer(1)])]) + #expect( + try CLIOutput.format(.object(["windows": rows]), query: .windows) == CLIOutput.format(rows, query: .windows) + ) + let metadata: JSONValue = .object(["windows": rows, "total": .integer(1)]) + let text = try CLIOutput.format(metadata, query: .windows) + #expect(text.contains("total")) + #expect(text.contains("windows")) + #expect(text.contains("[{\"id\":1}]")) + } + + @Test func nestedConfigurationIsNotDropped() throws { + let value: JSONValue = .object(["layout": .object(["z": .integer(2), "a": .integer(1)])]) + #expect(try CLIOutput.format(value, query: .config).contains("{\"a\":1,\"z\":2}")) + } + + @Test(arguments: [ + (JSONValue.null, "Done.\n"), (.bool(true), "Yes\n"), (.bool(false), "No\n"), + (.integer(-42), "-42\n"), (.number(0.25), "0.25\n"), (.string("ready"), "ready\n"), + ]) + func friendlyScalars(expected: (JSONValue, String)) throws { + #expect(try CLIOutput.format(expected.0) == expected.1) + } + + @Test(arguments: [ + ("first\nsecond", "first\\nsecond"), ("a\rb", "a\\rb"), ("a\tb", "a\\tb"), + ("\u{1B}[31m", "\\u{1b}[31m"), ("a\u{0}b", "a\\u{0}b"), + ("a\u{2028}b", "a\\u{2028}b"), ("a\u{2029}b", "a\\u{2029}b"), + ("a\u{202E}b", "a\\u{202e}b"), ("東京", "東京"), + ("cafe\u{301}", "cafe\u{301}"), ("👩‍💻", "👩‍💻"), ("\"\\", "\"\\"), + ]) + func controlCharactersAndUnicode(expected: (String, String)) throws { + #expect(CLIOutput.escapeCell(expected.0) == expected.1) + #expect(try CLIOutput.format(.string(expected.0)) == expected.1 + "\n") + } + + @Test func tableEscapesHeadersAndCells() { + #expect(CLIOutput.table(headers: ["a\nb"], rows: [["\u{1B}[2J"]]) == "a\\nb\n─────────\n\\u{1b}[2J\n") + } + + @Test(arguments: [ + ("ASCII", 5), ("東京", 4), ("한글", 4), ("AB", 4), ("cafe\u{301}", 4), ("👩‍💻", 2), ("☀️", 2), ("é", 1), ("", 0), + ]) + func terminalColumnWidths(expected: (String, Int)) { + #expect(CLIOutput.terminalWidth(expected.0) == expected.1) + } + + @Test func wideGlyphsAlignInTables() { + #expect( + CLIOutput.table(headers: ["Name", "ID"], rows: [["東京", "1"], ["é", "2"]]) + == "Name ID\n──── ──\n東京 1\né 2\n") + } + + @Test func catalogMatchesCompiledEnglishStrings() throws { + let bundle = TesseraCLI.resourceBundle + let catalogURL = try #require(bundle.url(forResource: "Localizable", withExtension: "xcstrings")) + let stringsURL = try #require( + bundle.url(forResource: "Localizable", withExtension: "strings", subdirectory: nil, localization: "en")) + let catalog = try JSONDecoder().decode(CLIStringCatalog.self, from: Data(contentsOf: catalogURL)) + let compiled = try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: stringsURL)) + #expect(catalog.sourceLanguage == "en") + #expect(!catalog.strings.isEmpty) + var expected: [String: String] = [:] + for (key, entry) in catalog.strings { + expected[key] = try #require(entry.localizations["en"]?.stringUnit.value) + } + #expect(compiled == expected) + #expect(bundle.localizations.contains("en")) + } + + @Test func noTrailingTableWhitespace() { + let text = CLIOutput.table(headers: ["Key", "Value"], rows: [["a", "1"], ["long", "2"]]) + #expect(text.split(separator: "\n").allSatisfy { !$0.hasSuffix(" ") }) + #expect(text.hasSuffix("\n")) + #expect(!text.hasSuffix("\n\n")) + } + + @Test(arguments: [ + JSONValue.null, .bool(true), .bool(false), .integer(Int64.min), .integer(Int64.max), + .number(0.25), .string("quote\" slash\\ newline\n tab\t 東京"), + .array([.null, .bool(true), .integer(7)]), + .object(["z": .integer(2), "a": .object(["y": .bool(true), "b": .null])]), + ]) + func jsonRoundTrips(value: JSONValue) throws { + let text = try CLIOutput.format(value, json: true) + #expect(text.filter { $0 == "\n" }.count == 1) + #expect(text.hasSuffix("\n")) + #expect(try IPCCodec.decode(JSONValue.self, from: Data(text.utf8)) == value) + } + + @Test func jsonIsStableSortedAndCompact() throws { + let first: JSONValue = .object([ + "z": .array([.bool(true), .null]), "a": .string("quote \" slash \\ newline\n\t"), + "nested": .object(["z": .integer(2), "a": .integer(1)]), + ]) + let second: JSONValue = .object([ + "nested": .object(["a": .integer(1), "z": .integer(2)]), "a": .string("quote \" slash \\ newline\n\t"), + "z": .array([.bool(true), .null]), + ]) + let expected = #"{"a":"quote \" slash \\ newline\n\t","nested":{"a":1,"z":2},"z":[true,null]}"# + "\n" + #expect(try CLIOutput.format(first, json: true) == expected) + #expect(try CLIOutput.format(first, json: true) == CLIOutput.format(second, json: true)) + } + + @Test(arguments: [Double.infinity, -Double.infinity, Double.nan]) + func nonfiniteNumbersAreErrors(value: Double) { + #expect(throws: EncodingError.self) { try CLIOutput.format(.number(value), json: true) } + #expect(throws: EncodingError.self) { try CLIOutput.format(.number(value)) } + } + + @Test func jsonResponseContainsOnlyResult() throws { + let response = IPCResponse(id: .integer(7), result: .object(["ready": .bool(true)])) + #expect(try CLIOutput.response(response, json: true) == "{\"ready\":true}\n") + #expect(try CLIOutput.response(IPCResponse(id: .string("request"), result: .null), json: true) == "null\n") + } + + @Test(arguments: [false, true]) + func serverErrorsAreNonzeroAndReadable(json: Bool) { + let response = IPCResponse( + id: .integer(1), error: IPCError(code: "invalid_command", message: "Choose a direction.")) + do { + _ = try CLIOutput.response(response, json: json) + Issue.record("Expected a server error") + } catch { + #expect(TesseraCLI.exitCode(for: error).rawValue != 0) + #expect(TesseraCLI.fullMessage(for: error).contains("invalid_command")) + #expect(TesseraCLI.fullMessage(for: error).contains("Choose a direction.")) + } + } + + @Test func serverErrorEscapesTerminalControls() throws { + let error = CLIOutputError.rejected(code: "bad\ncode", message: "\u{1B}[2J") + #expect(error.errorDescription == "Tessera rejected the command (bad\\ncode): \\u{1b}[2J") + } + + @Test func friendlyEventsStayOnOneLine() throws { + let event = IPCEvent(topic: .focus, data: .string("line\nseparator\u{2028}\u{202E}")) + let text = try CLIOutput.event(event) + #expect(text.filter { $0 == "\n" }.count == 1) + #expect(!text.contains("\u{2028}")) + #expect(!text.contains("\u{202E}")) + } + + @Test(arguments: IPCTopic.allCases, [false, true]) + func events(topic: IPCTopic, json: Bool) throws { + let event = IPCEvent(topic: topic, data: .object(["id": .integer(7)])) + let text = try CLIOutput.event(event, json: json) + if json { + #expect(text == "{\"data\":{\"id\":7},\"topic\":\"\(topic.rawValue)\",\"v\":1}\n") + #expect(try IPCCodec.decode(IPCEvent.self, from: Data(text.utf8)) == event) + } else { + #expect(text == "\(topic.rawValue): {\"id\":7}\n") + } + } +} + +@Suite("CLI execution") +struct CLIExecutionTests { + @Test(arguments: [ + CLIInvocation.request(command: "ping", args: [], query: nil, json: false), + .subscribe(topics: [.focus], json: false), + ]) + func appNotRunning(invocation: CLIInvocation) async { + let path = "/tmp/tcli-missing-\(UUID().uuidString).sock" + do { + try await CLIRunner.execute(invocation, socketPath: path) { _ in + Issue.record("A failed request must not write to stdout") + } + Issue.record("Expected a missing app to fail") + } catch { + #expect(error as? IPCTransportError == .notRunning(path)) + #expect(TesseraCLI.exitCode(for: error).rawValue != 0) + #expect(TesseraCLI.fullMessage(for: error).contains("Tessera isn't running")) + #expect(TesseraCLI.fullMessage(for: error).contains("Open the Tessera app")) + } + } + + @Test func versionDoesNotConnect() async throws { + let capture = CLITextCapture() + try await CLIRunner.execute(.version, socketPath: "not-an-absolute-path", write: capture.write) + #expect(capture.text == TesseraCLI.version + "\n") + } + + @Test(arguments: [ + ["query", "windows", "--json"], ["focus", "left"], ["run", "--json", "future-command", "--flag", "two words"], + ["reload", "--json"], + ]) + func executesWireRequests(arguments: [String]) async throws { + let directory = URL(fileURLWithPath: "/tmp/tcli-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { + do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } + } + let path = directory.appendingPathComponent("s").path + let handler = CLIRecordingHandler() + let server = try IPCServer(handler: handler, socketPath: path) + try await server.start() + let capture = CLITextCapture() + do { + let invocation = try CLIParsing.parse(arguments) + try await CLIRunner.execute(invocation, socketPath: path, write: capture.write) + let request = try #require(invocation.request) + switch request.command { + case "query": + #expect(await handler.queries == [.windows]) + #expect(capture.text == "[{\"id\":1}]\n") + case "run": + #expect(await handler.commands == [request.args]) + #expect(capture.text == (arguments.contains("--json") ? "null\n" : "Done.\n")) + case "reload-config": + #expect(await handler.reloadCount == 1) + #expect(capture.text == "{\"reloaded\":true}\n") + default: + Issue.record("Unexpected test request") + } + } catch { + try await server.stop() + throw error + } + try await server.stop() + } +} + +private struct CLIStringCatalog: Decodable { + let sourceLanguage: String + let strings: [String: Entry] + + struct Entry: Decodable { + let localizations: [String: Localization] + } + + struct Localization: Decodable { + let stringUnit: StringUnit + } + + struct StringUnit: Decodable { + let value: String + } +} + +private final class CLITextCapture: Sendable { + private let storage = Mutex("") + + func write(_ text: String) { storage.withLock { $0 += text } } + var text: String { storage.withLock { $0 } } +} + +private actor CLIRecordingHandler: IPCHandler { + var queries: [IPCQuery] = [] + var commands: [[String]] = [] + var reloadCount = 0 + + func query(_ query: IPCQuery) async throws -> JSONValue { + queries.append(query) + return .array([.object(["id": .integer(1)])]) + } + + func run(command: String, args: [String]) async throws -> JSONValue { + commands.append([command] + args) + return .null + } + + func reloadConfig() async throws -> JSONValue { + reloadCount += 1 + return .object(["reloaded": .bool(true)]) + } +} diff --git a/Tests/TesseraIPCTests/ClientTests.swift b/Tests/TesseraIPCTests/ClientTests.swift new file mode 100644 index 00000000..721fd969 --- /dev/null +++ b/Tests/TesseraIPCTests/ClientTests.swift @@ -0,0 +1,204 @@ +import Darwin +import Foundation +import Testing + +@testable import TesseraIPC + +private func withRawServer( + reply: @escaping @Sendable (IPCRequest, SocketChannel) async throws -> Void, + clientAction: @escaping @Sendable (IPCClient) async throws -> Void +) async throws { + let fixture = try SocketFixture() + defer { fixture.remove() } + let listener = try makeSocket() + defer { Darwin.close(listener) } + var address = try SocketAddress(fixture.path) + guard address.withPointer({ Darwin.bind(listener, $0, $1) }) == 0, Darwin.listen(listener, 1) == 0 else { + throw IPCTransportError.system(operation: "bind test listener", code: errno) + } + let client = try IPCClient(socketPath: fixture.path) + try await withThrowingTaskGroup(of: Void.self) { group in + group.addTask { + var descriptor: Int32 = -1 + while descriptor < 0 { + descriptor = Darwin.accept(listener, nil, nil) + if descriptor < 0 { + guard errno == EAGAIN || errno == EWOULDBLOCK else { + throw IPCTransportError.system(operation: "accept test client", code: errno) + } + try await Task.sleep(for: .milliseconds(2)) + } + } + try configureSocket(descriptor) + let channel = SocketChannel(descriptor: descriptor) + do { + let line = try #require(await channel.readLine()) + let request = try IPCCodec.decode(IPCRequest.self, from: line) + try await reply(request, channel) + await channel.close() + } catch { + await channel.close() + throw error + } + } + group.addTask { try await clientAction(client) } + defer { group.cancelAll() } + try await group.waitForAll() + } + await client.close() +} + +@Suite("Client validation", .timeLimit(.minutes(1))) +struct ClientTests { + @Test(arguments: [0, 2, 99]) + func responseVersion(_ version: Int) async throws { + try await withRawServer { request, channel in + try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, result: .null, v: version))) + } clientAction: { client in + _ = await #expect(throws: IPCTransportError.self) { try await client.request(IPCRequest(command: "ping")) } + } + } + + @Test func mismatchedID() async throws { + try await withRawServer { _, channel in + try await channel.write(IPCCodec.encode(IPCResponse(id: .string("wrong"), result: .null))) + } clientAction: { client in + _ = await #expect(throws: IPCTransportError.self) { try await client.request(IPCRequest(command: "ping")) } + } + } + + @Test func malformedResponse() async throws { + try await withRawServer { _, channel in + try await channel.write(Data("{\"v\":1,\"ok\":true}\n".utf8)) + } clientAction: { client in + _ = await #expect(throws: DecodingError.self) { try await client.request(IPCRequest(command: "ping")) } + } + } + + @Test func noResponse() async throws { + try await withRawServer { _, _ in + } clientAction: { client in + _ = await #expect(throws: IPCTransportError.closed) { + try await client.request(IPCRequest(command: "ping")) + } + } + } + + @Test func subscriptionHandshakeError() async throws { + let expected = IPCError(code: "unavailable", message: "Try again later.") + try await withRawServer { request, channel in + try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, error: expected))) + } clientAction: { client in + _ = await #expect(throws: expected) { try await client.subscribe() } + } + } + + @Test func subscriptionVersion() async throws { + try await withRawServer { request, channel in + try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, result: .null, v: 2))) + } clientAction: { client in + _ = await #expect(throws: IPCTransportError.self) { try await client.subscribe() } + } + } + + @Test(arguments: [0, 2, 99]) + func eventVersion(_ version: Int) async throws { + try await withRawServer { request, channel in + try await channel.write( + IPCCodec.encode(IPCResponse(id: request.id, result: .object(["topics": .array([])])))) + try await channel.write(IPCCodec.encode(IPCEvent(topic: .focus, data: .null, v: version))) + } clientAction: { client in + let subscription = try await client.subscribe() + _ = await #expect(throws: IPCTransportError.self) { + try await deadline { + var iterator = subscription.events.makeAsyncIterator() + return try await iterator.next() + } + } + await subscription.cancel() + } + } + + @Test func streamErrorResponse() async throws { + let expected = IPCError(code: "slow_subscriber", message: "Reconnect.") + try await withRawServer { request, channel in + try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, result: .null))) + try await channel.write(IPCCodec.encode(IPCResponse(id: request.id, error: expected))) + } clientAction: { client in + let subscription = try await client.subscribe() + _ = await #expect(throws: expected) { + try await deadline { + var iterator = subscription.events.makeAsyncIterator() + return try await iterator.next() + } + } + await subscription.cancel() + } + } + + @Test func extraResponseIsNotAnEvent() async throws { + try await withRawServer { request, channel in + let response = IPCResponse(id: request.id, result: .null) + try await channel.write(IPCCodec.encode(response)) + try await channel.write(IPCCodec.encode(response)) + } clientAction: { client in + let subscription = try await client.subscribe() + _ = await #expect(throws: IPCTransportError.self) { + try await deadline { + var iterator = subscription.events.makeAsyncIterator() + return try await iterator.next() + } + } + await subscription.cancel() + } + } + + @Test func slowSubscriberGetsAnError() async throws { + try await withServer { server, client, _, _ in + let subscription = try await client.subscribe() + for number in 0..<512 { try await server.publish(IPCEvent(topic: .focus, data: .integer(Int64(number)))) } + _ = await #expect(throws: IPCError.self) { + try await deadline { + for try await _ in subscription.events {} + } + } + await subscription.cancel() + } + } + + @Test func clientCanBeReusedAfterClose() async throws { + try await withServer { _, client, _, _ in + await client.close() + let response = try await client.request(IPCRequest(command: "ping")) + #expect(response.ok) + } + } +} + +@Suite("Catalog resources") +struct IPCResourceTests { + @Test func compiledStringsMatchCatalog() throws { + let catalogURL = try #require(Bundle.module.url(forResource: "Localizable", withExtension: "xcstrings")) + let catalog = try JSONDecoder().decode(Catalog.self, from: Data(contentsOf: catalogURL)) + let stringsURL = try #require( + Bundle.module.url(forResource: "Localizable", withExtension: "strings", subdirectory: "en.lproj")) + let strings = try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: stringsURL)) + #expect(strings.count == catalog.strings.count) + for (key, entry) in catalog.strings { + #expect(strings[key] == entry.localizations["en"]?.stringUnit.value) + } + } + + private struct Catalog: Decodable { + let strings: [String: Entry] + struct Entry: Decodable { + let localizations: [String: Localization] + } + struct Localization: Decodable { + let stringUnit: Unit + } + struct Unit: Decodable { + let value: String + } + } +} diff --git a/Tests/TesseraIPCTests/SocketTests.swift b/Tests/TesseraIPCTests/SocketTests.swift new file mode 100644 index 00000000..87e56a26 --- /dev/null +++ b/Tests/TesseraIPCTests/SocketTests.swift @@ -0,0 +1,507 @@ +import Darwin +import Foundation +import Testing + +@testable import TesseraIPC + +actor FakeHandler: IPCHandler { + struct Invocation: Equatable, Sendable { + let command: String + let args: [String] + } + + var invocations: [Invocation] = [] + var reloads = 0 + + func query(_ query: IPCQuery) async throws -> JSONValue { + .object(["query": .string(query.rawValue), "items": .array([])]) + } + + func run(command: String, args: [String]) async throws -> JSONValue { + invocations.append(Invocation(command: command, args: args)) + if command == "fail" { throw IPCError(code: "engine_failure", message: "The window is gone.") } + if command == "other-error" { throw FakeError() } + if command == "wait" { try await Task.sleep(for: .seconds(30)) } + return .object(["command": .string(command), "args": .array(args.map(JSONValue.string))]) + } + + func reloadConfig() async throws -> JSONValue { + reloads += 1 + return .bool(true) + } + + struct FakeError: Error, LocalizedError { + var errorDescription: String? { "A visible handler failure." } + } +} + +struct SocketFixture { + let directory: URL + var path: String { directory.appendingPathComponent("ipc.sock").path } + + init() throws { + directory = URL(fileURLWithPath: "/tmp/tessera-ipc-" + UUID().uuidString.prefix(8)) + try FileManager.default.createDirectory( + at: directory, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) + } + + func remove() { + do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } + } +} + +func withServer( + _ body: (IPCServer, IPCClient, FakeHandler, String) async throws -> Void +) async throws { + let fixture = try SocketFixture() + defer { fixture.remove() } + let handler = FakeHandler() + let server = try IPCServer(handler: handler, socketPath: fixture.path) + let client = try IPCClient(socketPath: fixture.path) + try await server.start() + do { + try await body(server, client, handler, fixture.path) + await client.close() + try await server.stop() + } catch { + await client.close() + do { try await server.stop() } catch { Issue.record(error) } + throw error + } +} + +func eventually(_ condition: @escaping @Sendable () async -> Bool) async throws { + let clock = ContinuousClock() + let deadline = clock.now.advanced(by: .seconds(3)) + while !(await condition()) { + guard clock.now < deadline else { throw Timeout() } + try await Task.sleep(for: .milliseconds(2)) + } +} + +struct Timeout: Error {} + +func deadline(_ operation: @escaping @Sendable () async throws -> Value) async throws -> Value { + try await withThrowingTaskGroup(of: Value.self) { group in + group.addTask { try await operation() } + group.addTask { + try await Task.sleep(for: .seconds(3)) + throw Timeout() + } + defer { group.cancelAll() } + return try #require(await group.next()) + } +} + +@Suite("Live IPC", .timeLimit(.minutes(1))) +struct ServerTests { + @Test func ping() async throws { + try await withServer { _, client, _, _ in + let request = IPCRequest(id: .integer(42), command: "ping") + let response = try await client.request(request) + #expect(response == IPCResponse(id: request.id, result: .string("pong"))) + } + } + + @Test func version() async throws { + try await withServer { _, client, _, _ in + let response = try await client.request(IPCRequest(command: "version")) + #expect(response.result == .object(["protocol": .integer(1), "version": .string("0.1.0")])) + } + } + + @Test(arguments: IPCQuery.allCases) + func query(_ query: IPCQuery) async throws { + try await withServer { _, client, _, _ in + let response = try await client.request(IPCRequest(command: "query", args: [query.rawValue])) + #expect(response.result == .object(["query": .string(query.rawValue), "items": .array([])])) + } + } + + @Test func runPreservesArguments() async throws { + try await withServer { _, client, handler, _ in + let args = ["left", "two words", "--future-option", "☀️"] + let response = try await client.request(IPCRequest(command: "run", args: ["future-command"] + args)) + #expect(response.ok) + #expect(await handler.invocations == [.init(command: "future-command", args: args)]) + } + } + + @Test func reloadConfig() async throws { + try await withServer { _, client, handler, _ in + let response = try await client.request(IPCRequest(command: "reload-config")) + #expect(response.result == .bool(true)) + #expect(await handler.reloads == 1) + } + } + + @Test(arguments: [0, 2, 99, -1]) + func unknownVersions(_ version: Int) async throws { + try await withServer { _, client, handler, _ in + let response = try await client.request(IPCRequest(command: "run", args: ["focus", "left"], v: version)) + #expect(response.error?.code == "unsupported_version") + #expect(response.error?.message.contains("v=1") == true) + #expect(await handler.invocations.isEmpty) + } + } + + @Test(arguments: [ + IPCRequest(command: "query"), IPCRequest(command: "query", args: ["unknown"]), + IPCRequest(command: "query", args: ["windows", "extra"]), IPCRequest(command: "run"), + IPCRequest(command: "run", args: [""]), IPCRequest(command: "ping", args: ["extra"]), + IPCRequest(command: "version", args: ["extra"]), IPCRequest(command: "reload-config", args: ["extra"]), + ]) + func invalidArguments(_ request: IPCRequest) async throws { + try await withServer { _, client, _, _ in + let response = try await client.request(request) + #expect(response.error?.code == "invalid_arguments") + } + } + + @Test func unknownCommand() async throws { + try await withServer { _, client, _, _ in + let response = try await client.request(IPCRequest(command: "not-a-command")) + #expect(response.error?.code == "unknown_command") + } + } + + @Test func typedHandlerError() async throws { + try await withServer { _, client, _, _ in + let response = try await client.request(IPCRequest(command: "run", args: ["fail"])) + #expect(response.error == IPCError(code: "engine_failure", message: "The window is gone.")) + } + } + + @Test func untypedHandlerError() async throws { + try await withServer { _, client, _, _ in + let response = try await client.request(IPCRequest(command: "run", args: ["other-error"])) + #expect(response.error == IPCError(code: "handler_error", message: "A visible handler failure.")) + } + } + + @Test func concurrentClients() async throws { + try await withServer { _, _, handler, path in + try await withThrowingTaskGroup(of: IPCResponse.self) { group in + for number in 0..<32 { + group.addTask { + let client = try IPCClient(socketPath: path) + return try await client.request( + IPCRequest(id: .integer(Int64(number)), command: "run", args: ["focus", "left"])) + } + } + var ids = Set() + for try await response in group { + #expect(response.ok) + ids.insert(try #require(response.id)) + } + #expect(ids.count == 32) + } + #expect(await handler.invocations.count == 32) + } + } + + @Test func concurrentRequestsOnOneClient() async throws { + try await withServer { _, client, _, _ in + try await withThrowingTaskGroup(of: IPCResponse.self) { group in + for number in 0..<16 { + group.addTask { try await client.request(IPCRequest(id: .integer(Int64(number)), command: "ping")) } + } + var count = 0 + for try await response in group { + #expect(response.result == .string("pong")) + count += 1 + } + #expect(count == 16) + } + } + } + + @Test func subscribeAndDisconnect() async throws { + try await withServer { server, client, _, _ in + let subscription = try await client.subscribe(topics: [.focus, .layout]) + #expect(await server.subscriberCount == 1) + let expected = [ + IPCEvent(topic: .focus, data: .integer(42)), IPCEvent(topic: .layout, data: .string("side")), + ] + try await server.publish(IPCEvent(topic: .window, data: .null)) + for event in expected { try await server.publish(event) } + let received = try await deadline { + var iterator = subscription.events.makeAsyncIterator() + return [try #require(await iterator.next()), try #require(await iterator.next())] + } + #expect(received == expected) + await subscription.cancel() + try await eventually { + let subscribers = await server.subscriberCount + let clients = await server.clientCount + return subscribers == 0 && clients == 0 + } + } + } + + @Test func defaultTopicsAndDuplicateTopics() async throws { + try await withServer { server, client, _, _ in + let all = try await client.subscribe() + let duplicate = try await client.subscribe(topics: [.window, .window]) + let event = IPCEvent(topic: .window, data: .string("created")) + try await server.publish(event) + let received = try await deadline { + var first = all.events.makeAsyncIterator() + var second = duplicate.events.makeAsyncIterator() + return [try #require(await first.next()), try #require(await second.next())] + } + #expect(received == [event, event]) + await all.cancel() + await duplicate.cancel() + } + } + + @Test func serverStopEndsSubscriptions() async throws { + try await withServer { server, client, _, _ in + let subscription = try await client.subscribe() + try await server.stop() + let next = try await deadline { + var iterator = subscription.events.makeAsyncIterator() + return try await iterator.next() + } + #expect(next == nil) + await subscription.cancel() + } + } + + @Test func clientCloseDisconnectsSubscription() async throws { + try await withServer { server, client, _, _ in + let subscription = try await client.subscribe() + await client.close() + try await eventually { await server.subscriberCount == 0 } + await subscription.cancel() + } + } + + @Test func canceledIteratorDisconnects() async throws { + try await withServer { server, client, _, _ in + let subscription = try await client.subscribe() + let reader = Task { for try await _ in subscription.events {} } + reader.cancel() + _ = await reader.result + try await eventually { await server.subscriberCount == 0 } + await subscription.cancel() + } + } + + @Test func invalidPublishVersion() async throws { + try await withServer { server, _, _, _ in + await #expect(throws: IPCError.self) { + try await server.publish(IPCEvent(topic: .focus, data: .null, v: 2)) + } + } + } + + @Test func requestCannotSubscribe() async throws { + let client = try IPCClient(socketPath: "/tmp/nonexistent-tessera-test.sock") + await #expect(throws: IPCTransportError.self) { try await client.request(IPCRequest(command: "subscribe")) } + } + + @Test func notRunningIsFriendly() async throws { + let fixture = try SocketFixture() + defer { fixture.remove() } + let client = try IPCClient(socketPath: fixture.path) + await #expect(throws: IPCTransportError.notRunning(fixture.path)) { + try await client.request(IPCRequest(command: "ping")) + } + } + + @Test func permissionsAndShutdownCleanup() async throws { + try await withServer { server, _, _, path in + let attributes = try FileManager.default.attributesOfItem(atPath: path) + #expect(attributes[.posixPermissions] as? Int == 0o600) + let lockAttributes = try FileManager.default.attributesOfItem(atPath: path + ".lock") + #expect(lockAttributes[.posixPermissions] as? Int == 0o600) + try await server.stop() + #expect(!FileManager.default.fileExists(atPath: path)) + } + } + + @Test func liveServerIsNotReplaced() async throws { + try await withServer { _, client, _, path in + let other = try IPCServer(handler: FakeHandler(), socketPath: path) + await #expect(throws: IPCTransportError.alreadyRunning(path)) { try await other.start() } + #expect(try await client.request(IPCRequest(command: "ping")).ok) + } + } + + @Test func duplicateStartFails() async throws { + try await withServer { server, _, _, path in + await #expect(throws: IPCTransportError.alreadyRunning(path)) { try await server.start() } + } + } + + @Test func stoppedServerCanRestart() async throws { + try await withServer { server, client, _, _ in + try await server.stop() + try await server.start() + #expect(try await client.request(IPCRequest(command: "ping")).ok) + } + } + + @Test func staleSocketIsRemoved() async throws { + let fixture = try SocketFixture() + defer { fixture.remove() } + let fd = try makeSocket() + var address = try SocketAddress(fixture.path) + #expect(address.withPointer { Darwin.bind(fd, $0, $1) } == 0) + Darwin.close(fd) + let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) + try await server.start() + let client = try IPCClient(socketPath: fixture.path) + #expect(try await client.request(IPCRequest(command: "ping")).ok) + try await server.stop() + } + + @Test func regularFileIsNotDeleted() async throws { + let fixture = try SocketFixture() + defer { fixture.remove() } + try Data("keep me".utf8).write(to: URL(fileURLWithPath: fixture.path)) + let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) + await #expect(throws: IPCTransportError.unsafeExistingPath(fixture.path)) { try await server.start() } + #expect(try String(contentsOfFile: fixture.path, encoding: .utf8) == "keep me") + } + + @Test func symlinkIsNotFollowed() async throws { + let fixture = try SocketFixture() + defer { fixture.remove() } + let target = fixture.directory.appendingPathComponent("keep.txt") + try Data("keep me".utf8).write(to: target) + try FileManager.default.createSymbolicLink(atPath: fixture.path, withDestinationPath: target.path) + let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) + await #expect(throws: IPCTransportError.unsafeExistingPath(fixture.path)) { try await server.start() } + #expect(try String(contentsOf: target, encoding: .utf8) == "keep me") + } + + @Test func lockSymlinkIsNotFollowed() async throws { + let fixture = try SocketFixture() + defer { fixture.remove() } + let target = fixture.directory.appendingPathComponent("keep.txt") + try Data("keep me".utf8).write(to: target) + try FileManager.default.createSymbolicLink(atPath: fixture.path + ".lock", withDestinationPath: target.path) + let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) + await #expect(throws: IPCTransportError.self) { try await server.start() } + #expect(try String(contentsOf: target, encoding: .utf8) == "keep me") + } + + @Test func liveSocketWithoutLockIsDetected() async throws { + let fixture = try SocketFixture() + defer { fixture.remove() } + let fd = try makeSocket() + defer { Darwin.close(fd) } + var address = try SocketAddress(fixture.path) + #expect(address.withPointer { Darwin.bind(fd, $0, $1) } == 0) + #expect(Darwin.listen(fd, 4) == 0) + let server = try IPCServer(handler: FakeHandler(), socketPath: fixture.path) + await #expect(throws: IPCTransportError.alreadyRunning(fixture.path)) { try await server.start() } + #expect(FileManager.default.fileExists(atPath: fixture.path)) + } + + @Test func shutdownDoesNotDeleteReplacementSocket() async throws { + try await withServer { server, _, _, path in + #expect(unlink(path) == 0) + let fd = try makeSocket() + defer { Darwin.close(fd) } + var address = try SocketAddress(path) + #expect(address.withPointer { Darwin.bind(fd, $0, $1) } == 0) + try await server.stop() + #expect(FileManager.default.fileExists(atPath: path)) + } + } + + @Test func requestCancellationDoesNotStopServer() async throws { + try await withServer { _, client, handler, _ in + let request = Task { try await client.request(IPCRequest(command: "run", args: ["wait"])) } + try await eventually { await handler.invocations.count == 1 } + request.cancel() + _ = await request.result + #expect(try await client.request(IPCRequest(command: "ping")).ok) + } + } +} + +@Suite("NDJSON framing", .timeLimit(.minutes(1))) +struct FramingTests { + @Test func partialAndMultipleMessages() async throws { + try await withServer { _, _, _, path in + let channel = SocketChannel(descriptor: try makeSocket()) + try await channel.connect(path: path) + let first = try IPCCodec.encode(IPCRequest(id: .integer(1), command: "ping")) + try await channel.write(Data(first.prefix(5))) + var remaining = Data(first.dropFirst(5)) + remaining.append(try IPCCodec.encode(IPCRequest(id: .integer(2), command: "ping"))) + try await channel.write(remaining) + let a = try #require(await channel.readLine()) + let b = try #require(await channel.readLine()) + #expect(try IPCCodec.decode(IPCResponse.self, from: a).id == .integer(1)) + #expect(try IPCCodec.decode(IPCResponse.self, from: b).id == .integer(2)) + await channel.close() + } + } + + @Test(arguments: [ + "not json", "{\"v\":1,\"id\":42,\"command\":\"ping\"}", "{\"v\":2,\"id\":42}", + "{\"id\":42,\"command\":\"ping\",\"args\":[]}", + ]) + func malformedRequestGetsResponse(_ json: String) async throws { + try await withServer { _, _, _, path in + let channel = SocketChannel(descriptor: try makeSocket()) + try await channel.connect(path: path) + try await channel.write(Data((json + "\n").utf8)) + let line = try #require(await channel.readLine()) + let response = try IPCCodec.decode(IPCResponse.self, from: line) + #expect(!response.ok) + #expect(response.error?.code == (json.contains("\"v\":2") ? "unsupported_version" : "invalid_request")) + #expect(response.id == (json == "not json" ? nil : .integer(42))) + try await channel.write(IPCCodec.encode(IPCRequest(id: .integer(5), command: "ping"))) + let next = try #require(await channel.readLine()) + #expect(try IPCCodec.decode(IPCResponse.self, from: next).ok) + await channel.close() + } + } + + @Test func invalidSubscriptionTopic() async throws { + try await withServer { server, _, _, path in + let channel = SocketChannel(descriptor: try makeSocket()) + try await channel.connect(path: path) + try await channel.write(IPCCodec.encode(IPCRequest(command: "subscribe", args: ["unknown"]))) + let line = try #require(await channel.readLine()) + #expect(try IPCCodec.decode(IPCResponse.self, from: line).error?.code == "invalid_arguments") + #expect(await server.subscriberCount == 0) + await channel.close() + } + } + + @Test func oversizedFrameClosesConnection() async throws { + try await withServer { _, _, _, path in + let channel = SocketChannel(descriptor: try makeSocket()) + try await channel.connect(path: path) + do { + try await channel.write(Data(repeating: 32, count: IPCProtocol.maximumMessageBytes + 16_384)) + let next = try await deadline { try await channel.readLine() } + #expect(next == nil) + } catch let error as IPCTransportError { + if case .system = error {} else { Issue.record(error) } + } + await channel.close() + } + } + + @Test func truncatedFrameReportsError() async throws { + var pair: [Int32] = [0, 0] + #expect(socketpair(AF_UNIX, SOCK_STREAM, 0, &pair) == 0) + try configureSocket(pair[0]) + try configureSocket(pair[1]) + let channel = SocketChannel(descriptor: pair[0]) + let peer = SocketChannel(descriptor: pair[1]) + try await peer.write(Data("unfinished".utf8)) + await peer.close() + await #expect(throws: IPCTransportError.truncatedMessage) { try await channel.readLine() } + await channel.close() + } +} diff --git a/Tests/TesseraIPCTests/TesseraIPCTests.swift b/Tests/TesseraIPCTests/TesseraIPCTests.swift index a02f9934..c957867b 100644 --- a/Tests/TesseraIPCTests/TesseraIPCTests.swift +++ b/Tests/TesseraIPCTests/TesseraIPCTests.swift @@ -1,4 +1,131 @@ +import Foundation import Testing + @testable import TesseraIPC -@Test func builds() {} +@Suite("JSON protocol") +struct ProtocolTests { + @Test(arguments: [ + JSONValue.null, .bool(true), .bool(false), .integer(.min), .integer(.max), .number(1.25), .string("café\n\"☀️"), + .array([.null, .integer(3)]), .object(["nested": .array([.bool(true)])]), + ]) + func jsonRoundTrip(_ value: JSONValue) throws { + #expect(try IPCCodec.decode(JSONValue.self, from: IPCCodec.encode(value)) == value) + } + + @Test(arguments: [IPCRequestID.string("request-☀️"), .integer(.min), .integer(.max)]) + func requestRoundTrip(_ id: IPCRequestID) throws { + let request = IPCRequest(id: id, command: "run", args: ["focus", "left", "two words"]) + #expect(try IPCCodec.decode(IPCRequest.self, from: IPCCodec.encode(request)) == request) + } + + @Test func defaultVersion() { #expect(IPCProtocol.version == 1) } + + @Test func defaultIDsAreUnique() { + #expect(IPCRequest(command: "ping").id != IPCRequest(command: "ping").id) + } + + @Test(arguments: [JSONValue.null, .string("pong"), .array([]), .object(["id": .integer(1)])]) + func successfulResponse(_ result: JSONValue) throws { + let response = IPCResponse(id: .integer(1), result: result) + #expect(try IPCCodec.decode(IPCResponse.self, from: IPCCodec.encode(response)) == response) + } + + @Test func errorResponse() throws { + let response = IPCResponse(id: nil, error: IPCError(code: "bad_command", message: "Try another command.")) + #expect(try IPCCodec.decode(IPCResponse.self, from: IPCCodec.encode(response)) == response) + #expect(response.error?.localizedDescription == "Try another command.") + } + + @Test(arguments: IPCTopic.allCases) + func eventRoundTrip(_ topic: IPCTopic) throws { + let event = IPCEvent(topic: topic, data: .object(["window": .integer(42)])) + #expect(try IPCCodec.decode(IPCEvent.self, from: IPCCodec.encode(event)) == event) + } + + @Test(arguments: [ + "{\"v\":1,\"id\":1,\"ok\":true}", + "{\"v\":1,\"id\":1,\"ok\":true,\"result\":null,\"error\":null}", + "{\"v\":1,\"id\":1,\"ok\":false}", + "{\"v\":1,\"id\":1,\"ok\":false,\"result\":null,\"error\":{\"code\":\"bad\",\"message\":\"bad\"}}", + "{\"v\":1,\"id\":1,\"ok\":false,\"error\":null}", + ]) + func invalidResponseShape(_ json: String) { + #expect(throws: (any Error).self) { try IPCCodec.decode(IPCResponse.self, from: Data(json.utf8)) } + } + + @Test(arguments: [ + "{}", "[]", "null", "{\"v\":1,\"id\":true,\"command\":\"ping\",\"args\":[]}", + "{\"v\":1,\"id\":1,\"command\":\"run\",\"args\":[42]}", + ]) + func invalidRequests(_ json: String) { + #expect(throws: (any Error).self) { try IPCCodec.decode(IPCRequest.self, from: Data(json.utf8)) } + } + + @Test func encoderProducesOneSortedLine() throws { + let data = try IPCCodec.encode(JSONValue.object(["z": .string("one\ntwo"), "a": .integer(2)])) + #expect(String(decoding: data, as: UTF8.self) == "{\"a\":2,\"z\":\"one\\ntwo\"}\n") + #expect(data.filter { $0 == 10 }.count == 1) + } + + @Test func oversizedEncodeFails() { + #expect(throws: IPCTransportError.messageTooLarge) { + try IPCCodec.encode(JSONValue.string(String(repeating: "x", count: IPCProtocol.maximumMessageBytes))) + } + } + + @Test func oversizedDecodeFails() { + #expect(throws: IPCTransportError.messageTooLarge) { + try IPCCodec.decode(JSONValue.self, from: Data(repeating: 32, count: IPCProtocol.maximumMessageBytes + 2)) + } + } + + @Test func nonFiniteNumberFails() { + #expect(throws: (any Error).self) { try IPCCodec.encode(JSONValue.number(.infinity)) } + } +} + +@Suite("Socket paths") +struct PathTests { + @Test func temporaryDirectoryAndUID() throws { + #expect( + try IPCSocketPath.resolve(environment: ["TMPDIR": "/tmp/private/"], uid: 501) + == "/tmp/private/tessera-501.sock") + } + + @Test func platformTemporaryDirectory() throws { + #expect( + try IPCSocketPath.resolve(environment: [:], uid: 42, temporaryDirectory: "/tmp") == "/tmp/tessera-42.sock") + } + + @Test func overrideWins() throws { + #expect( + try IPCSocketPath.resolve(environment: ["TESSERA_SOCKET": "/tmp/custom.sock", "TMPDIR": "invalid"], uid: 1) + == "/tmp/custom.sock") + } + + @Test(arguments: [ + "", "relative.sock", "/tmp/\u{0}bad", "/" + String(repeating: "x", count: 103), + "/" + String(repeating: "é", count: 52), + ]) + func invalidPaths(_ path: String) { + #expect(throws: IPCTransportError.invalidPath(path)) { + try IPCSocketPath.resolve(environment: ["TESSERA_SOCKET": path]) + } + #expect(throws: IPCTransportError.invalidPath(path)) { try IPCClient(socketPath: path) } + } + + @Test func longestPathFits() throws { + let path = "/" + String(repeating: "x", count: 102) + #expect(try IPCSocketPath.resolve(environment: ["TESSERA_SOCKET": path]) == path) + } + + @Test(arguments: [ + IPCTransportError.closed, .truncatedMessage, .messageTooLarge, .operationInProgress, + .notRunning("/tmp/test.sock"), .alreadyRunning("/tmp/test.sock"), .invalidPath(""), + .unsafeExistingPath("/tmp/test"), .system(operation: "connect", code: 2), .protocolViolation("wrong id"), + ]) + func transportErrorsHaveMessages(_ error: IPCTransportError) { + #expect(!error.localizedDescription.isEmpty) + } +} -- knotmirror 0.0.1 From 4367143839794e46ddd933d62990903cd6910775 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:48:26 -0400 Subject: [PATCH 15/44] Avoid executable name collision --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 61373897..5ff5675b 100644 --- a/Package.swift +++ b/Package.swift @@ -11,7 +11,7 @@ let package = Package( defaultLocalization: "en", platforms: [.macOS(.v15)], products: [ - .executable(name: "Tessera", targets: ["TesseraApp"]), + .executable(name: "TesseraApp", targets: ["TesseraApp"]), .executable(name: "tessera", targets: ["tessera"]), ], dependencies: [ -- knotmirror 0.0.1 From 4ef3ccb1385e7816d0728c12ce8fb70298c8253a Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:48:27 -0400 Subject: [PATCH 16/44] Add experimental brightness control --- Sources/TesseraPlatform/Brightness.swift | 114 ++++++++++++++++++ Sources/TesseraPlatform/WindowServer.swift | 6 +- .../BrightnessTests.swift | 107 ++++++++++++++++ .../WindowServerTests.swift | 7 +- 4 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 Sources/TesseraPlatform/Brightness.swift create mode 100644 Tests/TesseraPlatformTests/BrightnessTests.swift diff --git a/Sources/TesseraPlatform/Brightness.swift b/Sources/TesseraPlatform/Brightness.swift new file mode 100644 index 00000000..a3a6f071 --- /dev/null +++ b/Sources/TesseraPlatform/Brightness.swift @@ -0,0 +1,114 @@ +public import CoreGraphics +import Darwin + +/// Experimental compositor brightness offsets. A successful status does not verify the effect. +public struct Brightness { + public enum Result: Equatable, Sendable { + case unverified + case noWindows + } + + public enum Failure: Error, Equatable, Sendable { + case invalidOffset + case invalidWindowID(CGWindowID) + case tooManyWindows + case symbolUnavailable(String) + case connectionUnavailable + case invalidBuffer + case status(Int32) + } + + struct Dependencies { + let lookup: (String) -> UnsafeMutableRawPointer? + let connection: (UnsafeMutableRawPointer) -> Int32 + let set: + ( + UnsafeMutableRawPointer, Int32, UnsafeMutablePointer, UnsafeMutablePointer, Int32 + ) -> Int32 + } + + private let dependencies: Dependencies + + public init() { + let library = BrightnessLibrary() + dependencies = Dependencies( + lookup: { library.lookup($0) }, + connection: { pointer in + unsafeBitCast(pointer, to: BrightnessConnection.self)() + }, + set: { pointer, connection, windows, offsets, count in + unsafeBitCast(pointer, to: SetWindowBrightness.self)(connection, windows, offsets, count) + } + ) + } + + init(dependencies: Dependencies) { + self.dependencies = dependencies + } + + /// Accepts finite offsets from -1 to 1; zero requests normal brightness. + /// The allowed range is conservative because the private API is undocumented. + public func set(windowIDs: [CGWindowID], offset: Float) throws -> Result { + guard offset.isFinite, (-1...1).contains(offset) else { throw Failure.invalidOffset } + for id in windowIDs where id == kCGNullWindowID { + throw Failure.invalidWindowID(id) + } + guard let count = Int32(exactly: windowIDs.count) else { throw Failure.tooManyWindows } + guard count != 0 else { return .noWindows } + + guard let setter = dependencies.lookup("CGSSetWindowListBrightness") else { + throw Failure.symbolUnavailable("CGSSetWindowListBrightness") + } + guard + let connection = dependencies.lookup("SLSMainConnectionID") + ?? dependencies.lookup("CGSMainConnectionID") + else { + throw Failure.symbolUnavailable("SLSMainConnectionID or CGSMainConnectionID") + } + let connectionID = dependencies.connection(connection) + guard connectionID != 0 else { throw Failure.connectionUnavailable } + var windows = windowIDs.map(Int.init) + var offsets = [Float](repeating: offset, count: windows.count) + let status = try windows.withUnsafeMutableBufferPointer { windowBuffer in + try offsets.withUnsafeMutableBufferPointer { offsetBuffer in + guard let windowPointer = windowBuffer.baseAddress, let offsetPointer = offsetBuffer.baseAddress else { + throw Failure.invalidBuffer + } + return dependencies.set(setter, connectionID, windowPointer, offsetPointer, count) + } + } + guard status == 0 else { throw Failure.status(status) } + return .unverified + } + + /// Requests a reset for the supplied WindowServer window IDs, such as at launch. + public func resetAll(windowIDs: [CGWindowID]) throws -> Result { + try set(windowIDs: windowIDs, offset: 0) + } + + /// Enumerates all windows for a launch-time reset. The reset remains unverified. + public func resetAll(using windowServer: WindowServer = WindowServer()) throws -> Result { + try resetAll(windowIDs: windowServer.windows().map(\.number)) + } +} + +// The available external declaration uses C long window IDs and C float offsets. +// Private ABI and behavior may change between macOS releases. +private typealias BrightnessConnection = @convention(c) () -> Int32 +private typealias SetWindowBrightness = + @convention(c) ( + Int32, UnsafeMutablePointer, UnsafeMutablePointer, Int32 + ) -> Int32 + +private final class BrightnessLibrary { + private let handle = dlopen("/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight", RTLD_LAZY | RTLD_LOCAL) + + func lookup(_ name: String) -> UnsafeMutableRawPointer? { + guard let handle else { return nil } + return dlsym(handle, name) + } + + deinit { + if let handle { dlclose(handle) } + } +} diff --git a/Sources/TesseraPlatform/WindowServer.swift b/Sources/TesseraPlatform/WindowServer.swift index f84dc1d0..c3265633 100644 --- a/Sources/TesseraPlatform/WindowServer.swift +++ b/Sources/TesseraPlatform/WindowServer.swift @@ -22,13 +22,15 @@ public struct WindowServer: Sendable { public let managedDisplaySpaces: Bool public let currentSpace: Bool public let windowListBrightness: Bool + public let brightnessConnection: Bool public var canReadDisplaySpaces: Bool { mainConnection && managedDisplaySpaces } public var canReadCurrentSpace: Bool { mainConnection && currentSpace } - public var experimentalBrightness: Bool { mainConnection && windowListBrightness } + public var experimentalBrightness: Bool { brightnessConnection && windowListBrightness } init(probe: (String) -> Bool) { mainConnection = probe("SLSMainConnectionID") + brightnessConnection = mainConnection || probe("CGSMainConnectionID") managedDisplaySpaces = probe("SLSCopyManagedDisplaySpaces") currentSpace = probe("SLSManagedDisplayGetCurrentSpace") windowListBrightness = probe("CGSSetWindowListBrightness") @@ -248,6 +250,7 @@ private final class RuntimeSymbols: @unchecked Sendable { return dlsym(handle, name) } let connection = lookup(skyLight, "SLSMainConnectionID") + let brightnessConnection = lookup(skyLight, "CGSMainConnectionID") let spaces = lookup(skyLight, "SLSCopyManagedDisplaySpaces") let current = lookup(skyLight, "SLSManagedDisplayGetCurrentSpace") let brightness = lookup(skyLight, "CGSSetWindowListBrightness") @@ -257,6 +260,7 @@ private final class RuntimeSymbols: @unchecked Sendable { capabilities = WindowServer.Capabilities { name in switch name { case "SLSMainConnectionID": connection != nil + case "CGSMainConnectionID": brightnessConnection != nil case "SLSCopyManagedDisplaySpaces": spaces != nil case "SLSManagedDisplayGetCurrentSpace": current != nil case "CGSSetWindowListBrightness": brightness != nil diff --git a/Tests/TesseraPlatformTests/BrightnessTests.swift b/Tests/TesseraPlatformTests/BrightnessTests.swift new file mode 100644 index 00000000..4e79a5a7 --- /dev/null +++ b/Tests/TesseraPlatformTests/BrightnessTests.swift @@ -0,0 +1,107 @@ +import CoreGraphics +import Testing + +@testable import TesseraPlatform + +private final class BrightnessProbe { + var symbols: Set = ["CGSSetWindowListBrightness", "SLSMainConnectionID"] + var lookups: [String] = [] + var connection: Int32 = 42 + var status: Int32 = 0 + var calls: [(Int32, [Int], [Float])] = [] + private let pointer = UnsafeMutableRawPointer(bitPattern: 1)! + + func makeBrightness() -> Brightness { + Brightness( + dependencies: .init( + lookup: { name in + self.lookups.append(name) + return self.symbols.contains(name) ? self.pointer : nil + }, + connection: { _ in self.connection }, + set: { _, connection, windows, offsets, count in + let length = Int(count) + self.calls.append( + ( + connection, + Array(UnsafeBufferPointer(start: windows, count: length)), + Array(UnsafeBufferPointer(start: offsets, count: length)) + )) + return self.status + } + )) + } +} + +@Test func brightnessReportsUnverifiedWritesAndResets() throws { + let probe = BrightnessProbe() + let brightness = probe.makeBrightness() + #expect(try brightness.set(windowIDs: [123, 456], offset: -0.6) == .unverified) + #expect(probe.calls.count == 1) + #expect(probe.calls[0].0 == 42) + #expect(probe.calls[0].1 == [123, 456]) + #expect(probe.calls[0].2 == [-0.6, -0.6]) + #expect(try brightness.resetAll(windowIDs: [456]) == .unverified) + #expect(probe.calls[1].1 == [456]) + #expect(probe.calls[1].2 == [0]) +} + +@Test func brightnessResetEnumeratesWindows() throws { + let probe = BrightnessProbe() + let result = try probe.makeBrightness().resetAll() + switch result { + case .unverified: + #expect(probe.calls.count == 1) + #expect(!probe.calls[0].1.isEmpty) + #expect(probe.calls[0].2.allSatisfy { $0 == 0 }) + case .noWindows: + #expect(probe.calls.isEmpty) + } +} + +@Test func brightnessRejectsInvalidValuesWithoutCallingPrivateAPI() throws { + let probe = BrightnessProbe() + let brightness = probe.makeBrightness() + for offset: Float in [.nan, .infinity, -.infinity, -1.1, 1.1] { + #expect(throws: Brightness.Failure.invalidOffset) { + try brightness.set(windowIDs: [1], offset: offset) + } + } + #expect(throws: Brightness.Failure.invalidWindowID(0)) { + try brightness.set(windowIDs: [1, 0], offset: 0) + } + #expect(try brightness.set(windowIDs: [], offset: 0) == .noWindows) + #expect(probe.lookups.isEmpty) + #expect(probe.calls.isEmpty) +} + +@Test func brightnessReportsMissingSymbolsAndConnection() { + let probe = BrightnessProbe() + let brightness = probe.makeBrightness() + probe.symbols = [] + #expect(throws: Brightness.Failure.symbolUnavailable("CGSSetWindowListBrightness")) { + try brightness.set(windowIDs: [1], offset: 0) + } + probe.symbols = ["CGSSetWindowListBrightness"] + #expect(throws: Brightness.Failure.symbolUnavailable("SLSMainConnectionID or CGSMainConnectionID")) { + try brightness.set(windowIDs: [1], offset: 0) + } + probe.symbols.insert("SLSMainConnectionID") + probe.connection = 0 + #expect(throws: Brightness.Failure.connectionUnavailable) { + try brightness.set(windowIDs: [1], offset: 0) + } + #expect(probe.calls.isEmpty) +} + +@Test func brightnessFallbackAndFailureStatus() throws { + let probe = BrightnessProbe() + probe.symbols = ["CGSSetWindowListBrightness", "CGSMainConnectionID"] + let brightness = probe.makeBrightness() + #expect(try brightness.set(windowIDs: [42], offset: 1) == .unverified) + #expect(probe.lookups == ["CGSSetWindowListBrightness", "SLSMainConnectionID", "CGSMainConnectionID"]) + probe.status = 1000 + #expect(throws: Brightness.Failure.status(1000)) { + try brightness.set(windowIDs: [42], offset: -1) + } +} diff --git a/Tests/TesseraPlatformTests/WindowServerTests.swift b/Tests/TesseraPlatformTests/WindowServerTests.swift index 24445c58..514136b8 100644 --- a/Tests/TesseraPlatformTests/WindowServerTests.swift +++ b/Tests/TesseraPlatformTests/WindowServerTests.swift @@ -33,10 +33,15 @@ private func windowFields() -> [String: Any] { #expect(capabilities.canReadDisplaySpaces) #expect(!capabilities.canReadCurrentSpace) - let missingConnection = WindowServer.Capabilities { $0 != "SLSMainConnectionID" } + let missingConnection = WindowServer.Capabilities { $0 != "SLSMainConnectionID" && $0 != "CGSMainConnectionID" } #expect(!missingConnection.canReadDisplaySpaces) #expect(!missingConnection.canReadCurrentSpace) #expect(!missingConnection.experimentalBrightness) + let legacyBrightness = WindowServer.Capabilities { + ["CGSMainConnectionID", "CGSSetWindowListBrightness"].contains($0) + } + #expect(legacyBrightness.experimentalBrightness) + #expect(!legacyBrightness.canReadDisplaySpaces) let missingBrightness = WindowServer.Capabilities { $0 != "CGSSetWindowListBrightness" } #expect(!missingBrightness.experimentalBrightness) let noSymbols = WindowServer.Capabilities { _ in false } -- knotmirror 0.0.1 From ce93de2a0accd220fd799e839ee8d5168e82561b Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:52:23 -0400 Subject: [PATCH 17/44] Generate config localization tables --- Scripts/generate-config-strings.sh | 61 ++++ .../TesseraConfig/Resources/Store.xcstrings | 4 +- .../Resources/en.lproj/Store.strings | 4 +- .../TesseraConfig.docc/TesseraConfig.md | 9 +- .../ConfigResourceTests.swift | 306 +++++++++++++++++- 5 files changed, 362 insertions(+), 22 deletions(-) create mode 100755 Scripts/generate-config-strings.sh diff --git a/Scripts/generate-config-strings.sh b/Scripts/generate-config-strings.sh new file mode 100755 index 00000000..25a16f96 --- /dev/null +++ b/Scripts/generate-config-strings.sh @@ -0,0 +1,61 @@ +#!/bin/bash +set -euo pipefail +shopt -s nullglob + +root="$(cd "$(dirname "$0")/.." && pwd)" +check=false +if [[ "${1:-}" == --check ]]; then + check=true + shift +fi +if [[ $# -gt 1 || "${1:-}" == -* ]]; then + printf 'Usage: %s [--check] [resources-directory]\n' "$0" >&2 + exit 2 +fi +resources="$(cd "${1:-$root/Sources/TesseraConfig/Resources}" && pwd)" +catalogs=("$resources"/*.xcstrings) +if [[ ${#catalogs[@]} -eq 0 ]]; then + printf 'No String Catalogs found in %s\n' "$resources" >&2 + exit 1 +fi + +staging="$(mktemp -d "$root/.config-strings.XXXXXX")" +trap 'rm -rf -- "$staging"' EXIT +trap 'exit 1' HUP INT TERM + +# A failed catalog must not leave the checked-in tables partially regenerated. +for catalog in "${catalogs[@]}"; do + xcrun xcstringstool compile "$catalog" --output-directory "$staging" --serialization-format text +done + +status=0 +for generated in "$staging"/*.lproj/*.strings "$staging"/*.lproj/*.stringsdict; do + relative="${generated#"$staging"/}" + destination="$resources/$relative" + if "$check"; then + if ! cmp -s "$generated" "$destination"; then + printf 'Out-of-date generated resource: %s\n' "$destination" >&2 + status=1 + fi + else + mkdir -p "$(dirname "$destination")" + cp "$generated" "$destination" + fi +done + +for existing in "$resources"/*.lproj/*.strings "$resources"/*.lproj/*.stringsdict; do + relative="${existing#"$resources"/}" + if [[ ! -f "$staging/$relative" ]]; then + if "$check"; then + printf 'Unexpected generated resource: %s\n' "$existing" >&2 + status=1 + else + rm -- "$existing" + fi + fi +done + +if [[ $status -ne 0 ]]; then + printf 'Run Scripts/generate-config-strings.sh to regenerate catalog outputs.\n' >&2 +fi +exit "$status" diff --git a/Sources/TesseraConfig/Resources/Store.xcstrings b/Sources/TesseraConfig/Resources/Store.xcstrings index 2877b1dc..76081cb8 100644 --- a/Sources/TesseraConfig/Resources/Store.xcstrings +++ b/Sources/TesseraConfig/Resources/Store.xcstrings @@ -89,13 +89,13 @@ } } }, - "The configuration polling interval must be greater than zero." : { + "The configuration debounce interval must be greater than zero." : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", - "value" : "The configuration polling interval must be greater than zero." + "value" : "The configuration debounce interval must be greater than zero." } } } diff --git a/Sources/TesseraConfig/Resources/en.lproj/Store.strings b/Sources/TesseraConfig/Resources/en.lproj/Store.strings index 1b1d1a90..355be7d7 100644 --- a/Sources/TesseraConfig/Resources/en.lproj/Store.strings +++ b/Sources/TesseraConfig/Resources/en.lproj/Store.strings @@ -14,13 +14,13 @@ No configuration file exists at %@. Using built-in defaults until a valid file is available. The configuration URL must point to a local file: %@ The configuration URL must point to a local file: %@ + The configuration debounce interval must be greater than zero. + The configuration debounce interval must be greater than zero. The configuration file at %@ is missing. Keeping the last good configuration. The configuration file at %@ is missing. Keeping the last good configuration. The configuration file at %@ is not valid UTF-8. Save it as UTF-8 and try again. The configuration file at %@ is not valid UTF-8. Save it as UTF-8 and try again. The configuration path is not a regular file: %@ The configuration path is not a regular file: %@ - The configuration polling interval must be greater than zero. - The configuration polling interval must be greater than zero. diff --git a/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md b/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md index c899bf4b..70c16504 100644 --- a/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md +++ b/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md @@ -66,12 +66,11 @@ An invalid read reports diagnostics and leaves the active configuration and last ## Localized diagnostics -Edit the String Catalogs in `Sources/TesseraConfig/Resources`. SwiftPM copies catalogs without compiling them, so the English `.strings` outputs are checked in as well. Regenerate outputs when changing a catalog: +Edit only the String Catalogs in `Sources/TesseraConfig/Resources`. SwiftPM 6.2.4 copies catalogs without compiling them, so generated localization tables are checked in as well. Regenerate them with the selected developer toolchain: ```sh -for catalog in Sources/TesseraConfig/Resources/*.xcstrings; do - xcrun xcstringstool compile "$catalog" --output-directory Sources/TesseraConfig/Resources -done +Scripts/generate-config-strings.sh +Scripts/generate-config-strings.sh --check ``` -Resource tests check that the compiled English tables stay in sync with their catalogs. Add compiled outputs for new languages through the same command. +The script compiles every catalog and language, including plural variations, and removes obsolete `.strings` and `.stringsdict` outputs. `--check` reports missing, changed, or obsolete outputs without modifying them. Resource tests run this check and resolve every English entry through `Bundle.module` with an explicit missing-value sentinel, so returning a key cannot mask a missing table. diff --git a/Tests/TesseraConfigTests/ConfigResourceTests.swift b/Tests/TesseraConfigTests/ConfigResourceTests.swift index f32870f3..7fbb5fc8 100644 --- a/Tests/TesseraConfigTests/ConfigResourceTests.swift +++ b/Tests/TesseraConfigTests/ConfigResourceTests.swift @@ -4,18 +4,218 @@ import Testing @testable import TesseraConfig @Suite struct ConfigResourceTests { - @Test(arguments: ["Parser", "Keybindings", "Schema", "Store"]) + private static let tables = ["Parser", "Keybindings", "Schema", "Store"] + private static let repositoryURL = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + private static let resourcesURL = repositoryURL.appending(path: "Sources/TesseraConfig/Resources") + + @Test(arguments: tables) func compiledEnglishMatchesCatalog(table: String) throws { - let catalogURL = try #require(Bundle.module.url(forResource: table, withExtension: "xcstrings")) + let catalog = try catalog(table: table) + #expect(catalog.sourceLanguage == "en") let stringsURL = try #require( Bundle.module.url(forResource: table, withExtension: "strings", subdirectory: "en.lproj")) - let catalog = try JSONDecoder().decode(Catalog.self, from: Data(contentsOf: catalogURL)) - let compiled = try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: stringsURL)) - let expected = catalog.strings.mapValues { $0.localizations["en"]?.stringUnit.value } - #expect(compiled.count == expected.count) - for (key, value) in expected { - #expect(value != nil) - #expect(compiled[key] == value) + let expected = try catalog.strings.mapValues { try #require($0.localizations["en"]).stringUnit.value } + #expect(try strings(at: stringsURL) == expected) + } + + @Test(arguments: tables) + func moduleLookupResolvesEveryEnglishEntry(table: String) throws { + let catalog = try catalog(table: table) + let missing = "Missing localization: \(UUID().uuidString)" + #expect(!catalog.strings.isEmpty) + for (key, entry) in catalog.strings { + let expected = try #require(entry.localizations["en"]).stringUnit.value + let value = Bundle.module.localizedString(forKey: key, value: missing, table: table) + #expect(value != missing, "Missing entry in \(table): \(key)") + #expect(value == expected) + } + #expect(Bundle.module.localizedString(forKey: missing, value: missing, table: table) == missing) + } + + @Test func moduleLookupReportsMissingTable() { + let missing = "Missing localization: \(UUID().uuidString)" + let value = Bundle.module.localizedString( + forKey: "A key chord cannot be empty.", value: missing, table: missing) + #expect(value == missing) + } + + @Test func everySourceCatalogIsBundledAndTested() throws { + let sourceFiles = try FileManager.default.contentsOfDirectory( + at: Self.resourcesURL, includingPropertiesForKeys: nil) + let sourceTables = Set( + sourceFiles.filter { $0.pathExtension == "xcstrings" }.map { $0.deletingPathExtension().lastPathComponent }) + let bundleURL = try #require(Bundle.module.resourceURL) + let bundledFiles = try FileManager.default.contentsOfDirectory(at: bundleURL, includingPropertiesForKeys: nil) + let bundledTables = Set( + bundledFiles.filter { $0.pathExtension == "xcstrings" }.map { $0.deletingPathExtension().lastPathComponent } + ) + #expect(sourceTables == Set(Self.tables)) + #expect(bundledTables == sourceTables) + } + + @Test func checkedInOutputsAreUpToDate() throws { + let result = try runGenerator(arguments: ["--check"]) + #expect(result.status == 0, "\(result.output)") + } + + @Test func generatorPreservesEscapingAndLanguagesAndIsRepeatable() throws { + try withResources { resources in + let english = "“C:\\Notes” says \"Hello\", %@.\n\t%lld & more." + let french = "Été : %@, %lld éléments." + try writeCatalog(at: resources, table: "Example table", translations: ["en": english, "fr": french]) + try writeCatalog(at: resources, table: "Other", translations: ["en": "Another table"]) + let catalogData = try snapshot(resources) + let first = try runGenerator(resources: resources) + try #require(first.status == 0, "\(first.output)") + #expect( + try strings(at: resources.appending(path: "en.lproj/Example table.strings")) == ["notice.key": english]) + #expect( + try strings(at: resources.appending(path: "fr.lproj/Example table.strings")) == ["notice.key": french]) + #expect( + try strings(at: resources.appending(path: "en.lproj/Other.strings")) == ["notice.key": "Another table"]) + let generated = try snapshot(resources) + for (path, data) in catalogData { + #expect(generated[path] == data) + } + let second = try runGenerator(resources: resources) + #expect(second.status == 0, "\(second.output)") + #expect(try snapshot(resources) == generated) + let check = try runGenerator(arguments: ["--check"], resources: resources) + #expect(check.status == 0, "\(check.output)") + #expect(try snapshot(resources) == generated) + } + } + + @Test(arguments: ResourceChange.allCases) + func checkDetectsDriftWithoutWritingAndGenerationRepairsIt(change: ResourceChange) throws { + try withResources { resources in + try writeCatalog(at: resources) + let generated = try runGenerator(resources: resources) + try #require(generated.status == 0, "\(generated.output)") + let unrelated = resources.appending(path: "en.lproj/keep.txt") + try Data("Unrelated resource".utf8).write(to: unrelated) + let changedURL = resources.appending(path: change.path) + switch change { + case .missing: + try FileManager.default.removeItem(at: changedURL) + case .changed, .obsoleteTable, .obsoletePlural, .obsoleteLanguage: + try FileManager.default.createDirectory( + at: changedURL.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("Outdated output".utf8).write(to: changedURL) + } + let before = try snapshot(resources) + let check = try runGenerator(arguments: ["--check"], resources: resources) + #expect(check.status == 1) + #expect(check.output.contains(change.path)) + #expect(check.output.contains("generate-config-strings.sh")) + #expect(try snapshot(resources) == before) + let repaired = try runGenerator(resources: resources) + #expect(repaired.status == 0, "\(repaired.output)") + let recheck = try runGenerator(arguments: ["--check"], resources: resources) + #expect(recheck.status == 0, "\(recheck.output)") + #expect( + try strings(at: resources.appending(path: "en.lproj/Example.strings")) == [ + "notice.key": "A translated value" + ]) + #expect(try Data(contentsOf: unrelated) == Data("Unrelated resource".utf8)) + } + } + + @Test func generatorRemovesOutputsForDeletedCatalogsAndLanguages() throws { + try withResources { resources in + try writeCatalog(at: resources, translations: ["en": "English", "fr": "Français"]) + try writeCatalog(at: resources, table: "Deleted") + let initial = try runGenerator(resources: resources) + try #require(initial.status == 0, "\(initial.output)") + try writeCatalog(at: resources, translations: ["en": "Updated English"]) + try FileManager.default.removeItem(at: resources.appending(path: "Deleted.xcstrings")) + let check = try runGenerator(arguments: ["--check"], resources: resources) + #expect(check.status == 1) + #expect(check.output.contains("fr.lproj/Example.strings")) + #expect(check.output.contains("en.lproj/Deleted.strings")) + let result = try runGenerator(resources: resources) + #expect(result.status == 0, "\(result.output)") + #expect(!FileManager.default.fileExists(atPath: resources.appending(path: "fr.lproj/Example.strings").path)) + #expect(!FileManager.default.fileExists(atPath: resources.appending(path: "en.lproj/Deleted.strings").path)) + #expect( + try strings(at: resources.appending(path: "en.lproj/Example.strings")) == [ + "notice.key": "Updated English" + ]) + } + } + + @Test(arguments: [false, true]) + func malformedCatalogFailsBeforeChangingOutputs(check: Bool) throws { + try withResources { resources in + try writeCatalog(at: resources) + let initial = try runGenerator(resources: resources) + try #require(initial.status == 0, "\(initial.output)") + try writeCatalog(at: resources, translations: ["en": "Changed value"]) + try Data("{ invalid catalog".utf8).write(to: resources.appending(path: "ZBroken.xcstrings")) + let before = try snapshot(resources) + let result = try runGenerator(arguments: check ? ["--check"] : [], resources: resources) + #expect(result.status != 0) + #expect(!result.output.isEmpty) + #expect(try snapshot(resources) == before) + } + } + + @Test(arguments: [false, true]) + func noCatalogsIsAnErrorAndPreservesExistingOutputs(check: Bool) throws { + try withResources { resources in + let language = resources.appending(path: "en.lproj") + try FileManager.default.createDirectory(at: language, withIntermediateDirectories: true) + try Data("Existing output".utf8).write(to: language.appending(path: "Example.strings")) + let before = try snapshot(resources) + let result = try runGenerator(arguments: check ? ["--check"] : [], resources: resources) + #expect(result.status == 1) + #expect(result.output.contains("No String Catalogs found")) + #expect(try snapshot(resources) == before) + } + } + + @Test func unknownGeneratorOptionIsAnError() throws { + let result = try runGenerator(arguments: ["--unknown"]) + #expect(result.status == 2) + #expect(result.output.contains("Usage:")) + } + + @Test func generatorCompilesPluralVariations() throws { + try withResources { resources in + let source = #""" + { + "sourceLanguage": "en", + "version": "1.0", + "strings": { + "%lld files": { + "extractionState": "manual", + "localizations": { + "en": { + "variations": { + "plural": { + "one": {"stringUnit": {"state": "translated", "value": "%lld file"}}, + "other": {"stringUnit": {"state": "translated", "value": "%lld files"}} + } + } + } + } + } + } + } + """# + try Data(source.utf8).write(to: resources.appending(path: "Counts.xcstrings")) + let result = try runGenerator(resources: resources) + try #require(result.status == 0, "\(result.output)") + let pluralURL = resources.appending(path: "en.lproj/Counts.stringsdict") + #expect(try !Data(contentsOf: pluralURL).isEmpty) + let englishBundle = try #require(Bundle(url: resources.appending(path: "en.lproj"))) + let format = englishBundle.localizedString(forKey: "%lld files", value: "Missing plural", table: "Counts") + #expect(format != "Missing plural") + #expect(String.localizedStringWithFormat(format, Int64(1)) == "1 file") + #expect(String.localizedStringWithFormat(format, Int64(2)) == "2 files") + let check = try runGenerator(arguments: ["--check"], resources: resources) + #expect(check.status == 0, "\(check.output)") } } @@ -26,15 +226,95 @@ import Testing #expect(diagnostic.relatedLocation == nil) } - private struct Catalog: Decodable { + enum ResourceChange: CaseIterable { + case missing, changed, obsoleteTable, obsoletePlural, obsoleteLanguage + + var path: String { + switch self { + case .missing, .changed: "en.lproj/Example.strings" + case .obsoleteTable: "en.lproj/Removed.strings" + case .obsoletePlural: "en.lproj/Example.stringsdict" + case .obsoleteLanguage: "fr.lproj/Example.strings" + } + } + } + + private func catalog(table: String) throws -> Catalog { + let url = try #require(Bundle.module.url(forResource: table, withExtension: "xcstrings")) + return try JSONDecoder().decode(Catalog.self, from: Data(contentsOf: url)) + } + + private func strings(at url: URL) throws -> [String: String] { + try PropertyListDecoder().decode([String: String].self, from: Data(contentsOf: url)) + } + + private func writeCatalog( + at resources: URL, table: String = "Example", translations: [String: String] = ["en": "A translated value"] + ) throws { + let localizations = translations.mapValues { Catalog.Localization(stringUnit: Catalog.Unit(value: $0)) } + let catalog = Catalog(strings: ["notice.key": Catalog.Entry(localizations: localizations)]) + try JSONEncoder().encode(catalog).write(to: resources.appending(path: "\(table).xcstrings")) + } + + private func runGenerator(arguments: [String] = [], resources: URL? = nil) throws -> (status: Int32, output: String) + { + let process = Process() + process.executableURL = Self.repositoryURL.appending(path: "Scripts/generate-config-strings.sh") + process.currentDirectoryURL = Self.repositoryURL.appending(path: "Tests") + process.arguments = arguments + (resources.map { [$0.path] } ?? []) + let pipe = Pipe() + process.standardOutput = pipe + process.standardError = pipe + try process.run() + let data = try pipe.fileHandleForReading.readToEnd() ?? Data() + process.waitUntilExit() + #expect(process.terminationReason == .exit) + return (process.terminationStatus, try #require(String(data: data, encoding: .utf8))) + } + + private func withResources(_ body: (URL) throws -> Void) throws { + let resources = Self.repositoryURL.appending(path: ".build-catalog-check/Resource test \(UUID().uuidString)") + try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true) + defer { + do { + try FileManager.default.removeItem(at: resources) + } catch { + Issue.record(error) + } + } + try body(resources) + } + + private func snapshot(_ directory: URL) throws -> [String: Data] { + var files: [String: Data] = [:] + for url in try FileManager.default.contentsOfDirectory( + at: directory, includingPropertiesForKeys: [.isDirectoryKey]) + { + if try url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true { + for (path, data) in try snapshot(url) { + files["\(url.lastPathComponent)/\(path)"] = data + } + } else { + files[url.lastPathComponent] = try Data(contentsOf: url) + } + } + return files + } + + private struct Catalog: Codable { + var sourceLanguage = "en" let strings: [String: Entry] - struct Entry: Decodable { + var version = "1.0" + + struct Entry: Codable { + var extractionState = "manual" let localizations: [String: Localization] } - struct Localization: Decodable { + struct Localization: Codable { let stringUnit: Unit } - struct Unit: Decodable { + struct Unit: Codable { + var state = "translated" let value: String } } -- knotmirror 0.0.1 From 0203799e8f85a12c7ab741e293e501b642ed6cbd Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:53:07 -0400 Subject: [PATCH 18/44] Watch configuration changes without polling --- Sources/TesseraConfig/ConfigFileWatcher.swift | 233 ++++++++++++++-- Sources/TesseraConfig/ConfigStore.swift | 20 +- .../TesseraConfig.docc/TesseraConfig.md | 2 +- .../TesseraConfigTests/ConfigStoreTests.swift | 259 ++++++++++++++++-- 4 files changed, 460 insertions(+), 54 deletions(-) diff --git a/Sources/TesseraConfig/ConfigFileWatcher.swift b/Sources/TesseraConfig/ConfigFileWatcher.swift index 79e21b9a..ae4566c7 100644 --- a/Sources/TesseraConfig/ConfigFileWatcher.swift +++ b/Sources/TesseraConfig/ConfigFileWatcher.swift @@ -1,36 +1,71 @@ +import Darwin +import Dispatch import Foundation struct ConfigFileWatcher: Sendable { private let task: Task + private let events: AsyncStream.Continuation init( - pollInterval: Duration, + fileURL: URL, + debounceInterval: Duration, sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, - poll: @escaping @Sendable () async -> Bool, + changed: @escaping @Sendable () async -> Bool, failed: @escaping @Sendable (ConfigDiagnostic) async -> Void ) { + let (events, continuation) = AsyncStream.makeStream() + self.events = continuation task = Task.detached(priority: .utility) { - while !Task.isCancelled { - guard await poll() else { return } - do { - try await sleep(pollInterval) - } catch is CancellationError { - return - } catch { - await failed( - ConfigDiagnostic( - message: String( - localized: "Configuration watching stopped unexpectedly: \(error.localizedDescription)", - table: "Store", bundle: .module - ) - ) - ) - return + let queue = DispatchQueue(label: "TesseraConfig.file-watcher", qos: .utility) + var observations: [String: FileObservation] = [:] + var debounce: Task? + var generation: UUID? + defer { + debounce?.cancel() + for observation in observations.values { observation.source.cancel() } + continuation.finish() + } + do { + try Self.refresh(fileURL, observations: &observations, queue: queue, events: continuation) + guard !Task.isCancelled, await changed() else { return } + for await event in events { + guard !Task.isCancelled else { return } + switch event { + case .changed: + debounce?.cancel() + let id = UUID() + generation = id + debounce = Task { + do { + try await sleep(debounceInterval) + if !Task.isCancelled { continuation.yield(.reload(id)) } + } catch is CancellationError { + return + } catch { + continuation.yield(.failure(Self.diagnostic(error))) + } + } + case .reload(let id): + guard generation == id else { continue } + debounce = nil + generation = nil + try Self.refresh(fileURL, observations: &observations, queue: queue, events: continuation) + guard await changed() else { return } + case .failure(let diagnostic): + await failed(diagnostic) + return + } } + } catch { + if !Task.isCancelled { await failed(Self.diagnostic(error)) } } } } + func requestReload() { + events.yield(.changed) + } + func cancel() { task.cancel() } @@ -38,6 +73,157 @@ struct ConfigFileWatcher: Sendable { func waitUntilFinished() async { await task.value } + + private static func diagnostic(_ error: any Error) -> ConfigDiagnostic { + ConfigDiagnostic( + message: String( + localized: "Configuration watching stopped unexpectedly: \(error.localizedDescription)", + table: "Store", bundle: .module + ) + ) + } + + private static func refresh( + _ url: URL, observations: inout [String: FileObservation], queue: DispatchQueue, + events: AsyncStream.Continuation + ) throws { + guard url.isFileURL else { + throw ConfigDiagnostic( + message: String( + localized: "The configuration URL must point to a local file: \(url.absoluteString)", + table: "Store", bundle: .module + ) + ) + } + while !Task.isCancelled { + let paths = try watchPaths(for: url) + try observe(paths, observations: &observations, queue: queue, events: events) + // A save can replace the path between discovery and opening its descriptor. + let latest = try watchPaths(for: url) + guard latest == paths, try latest.allSatisfy({ try matches($0, observation: observations[$0]) }) else { + continue + } + for path in observations.keys where !latest.contains(path) { + observations.removeValue(forKey: path)?.source.cancel() + } + return + } + } + + private static func matches(_ path: String, observation: FileObservation?) throws -> Bool { + guard let observation else { return false } + var metadata = stat() + guard stat(path, &metadata) == 0 else { + let code = errno + guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: path) } + return false + } + return observation.device == metadata.st_dev && observation.inode == metadata.st_ino + } + + private static func observe( + _ paths: Set, observations: inout [String: FileObservation], queue: DispatchQueue, + events: AsyncStream.Continuation + ) throws { + for path in paths.sorted() { + var metadata = stat() + if stat(path, &metadata) != 0 { + let code = errno + guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: path) } + observations.removeValue(forKey: path)?.source.cancel() + continue + } + if let current = observations[path], current.device == metadata.st_dev, current.inode == metadata.st_ino { + continue + } + observations.removeValue(forKey: path)?.source.cancel() + let descriptor = open(path, O_EVTONLY | O_CLOEXEC) + guard descriptor >= 0 else { + let code = errno + guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: path) } + continue + } + var opened = stat() + guard fstat(descriptor, &opened) == 0 else { + let code = errno + close(descriptor) + throw fileError(code, path: path) + } + let source = DispatchSource.makeFileSystemObjectSource( + fileDescriptor: descriptor, + eventMask: [.write, .extend, .attrib, .link, .rename, .delete, .revoke], queue: queue + ) + source.setEventHandler { events.yield(.changed) } + source.setCancelHandler { close(descriptor) } + observations[path] = FileObservation(source: source, device: opened.st_dev, inode: opened.st_ino) + source.activate() + } + } + + private static func watchPaths(for url: URL) throws -> Set { + var paths: Set = [] + var current = URL(fileURLWithPath: "/", isDirectory: true) + var remaining = Array(url.pathComponents.dropFirst().reversed()) + var links = 0 + while let component = remaining.popLast() { + if component == "." { continue } + if component == ".." { + current.deleteLastPathComponent() + continue + } + let next = current.appendingPathComponent(component) + var metadata = stat() + if lstat(next.path, &metadata) != 0 { + let code = errno + guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: next.path) } + current = next + while let suffix = remaining.popLast() { current.appendPathComponent(suffix) } + break + } + if metadata.st_mode & S_IFMT == S_IFLNK { + links += 1 + guard links <= 40 else { throw fileError(ELOOP, path: next.path) } + paths.insert(current.path) + let destination = try FileManager.default.destinationOfSymbolicLink(atPath: next.path) + let components = NSString(string: destination).pathComponents + if destination.hasPrefix("/") { current = URL(fileURLWithPath: "/", isDirectory: true) } + remaining.append(contentsOf: components.filter { $0 != "/" }.reversed()) + } else { + current = next + } + } + paths.insert(current.path) + paths.insert(current.deletingLastPathComponent().path) + // Missing directories need their nearest surviving ancestor to announce recreation. + var existing: Set = [] + for path in paths { + var candidate = URL(fileURLWithPath: path) + var metadata = stat() + while stat(candidate.path, &metadata) != 0 { + let code = errno + guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: candidate.path) } + candidate.deleteLastPathComponent() + } + existing.insert(candidate.path) + } + return existing + } + + private static func fileError(_ code: Int32, path: String) -> NSError { + NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: [NSFilePathErrorKey: path]) + } +} + +private enum WatchEvent: Sendable { + case changed + case reload(UUID) + case failure(ConfigDiagnostic) +} + +private struct FileObservation { + let source: any DispatchSourceFileSystemObject + let device: dev_t + let inode: ino_t } enum ConfigFileContents: Sendable, Equatable { @@ -57,10 +243,13 @@ enum ConfigFileContents: Sendable, Equatable { ) } do { - var resolvedURL = url.resolvingSymlinksInPath() - resolvedURL.removeAllCachedResourceValues() - let values = try resolvedURL.resourceValues(forKeys: [.isRegularFileKey]) - guard values.isRegularFile == true else { + var metadata = stat() + guard stat(url.path, &metadata) == 0 else { + let code = errno + if code == ENOENT || code == ENOTDIR { return .missing } + throw NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: [NSFilePathErrorKey: url.path]) + } + guard metadata.st_mode & S_IFMT == S_IFREG else { return .failure( ConfigDiagnostic( message: String( diff --git a/Sources/TesseraConfig/ConfigStore.swift b/Sources/TesseraConfig/ConfigStore.swift index 1c1b2d1b..17c361a4 100644 --- a/Sources/TesseraConfig/ConfigStore.swift +++ b/Sources/TesseraConfig/ConfigStore.swift @@ -71,21 +71,21 @@ public actor ConfigStore { return snapshot } - /// A running watcher resumes loading its file on the next poll. + /// A running watcher resumes loading its file after the debounce interval. @discardableResult public func load(source: String) -> ConfigSnapshot { previousContents = nil apply(source: source, from: .sourceText) + watcher?.requestReload() return snapshot } - /// Polls bytes rather than inode metadata to follow atomic saves, recreation, and same-size writes. - /// The default interval is 250 ms, plus read/validation and scheduling time; intermediate writes may coalesce. - public func startWatching(pollInterval: Duration = .milliseconds(250)) throws { - guard pollInterval > .zero else { + /// Watches file-system events with a short debounce and no timers while idle. + public func startWatching(debounceInterval: Duration = .milliseconds(100)) throws { + guard debounceInterval > .zero else { throw ConfigDiagnostic( message: String( - localized: "The configuration polling interval must be greater than zero.", + localized: "The configuration debounce interval must be greater than zero.", table: "Store", bundle: .module ) ) @@ -95,9 +95,9 @@ public actor ConfigStore { watchID = id previousContents = nil watcher = ConfigFileWatcher( - pollInterval: pollInterval, - poll: { [weak self] in - await self?.poll(watchID: id) ?? false + fileURL: fileURL, debounceInterval: debounceInterval, + changed: { [weak self] in + await self?.fileChanged(watchID: id) ?? false }, failed: { [weak self] diagnostic in await self?.watchFailed(diagnostic, watchID: id) @@ -114,7 +114,7 @@ public actor ConfigStore { await previous?.waitUntilFinished() } - private func poll(watchID id: UUID) -> Bool { + private func fileChanged(watchID id: UUID) -> Bool { guard watchID == id, !Task.isCancelled else { return false } let contents = ConfigFileContents.read(from: fileURL) guard !Task.isCancelled else { return false } diff --git a/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md b/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md index 70c16504..4a833304 100644 --- a/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md +++ b/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md @@ -58,7 +58,7 @@ The parser supports TOML 1.0 tables, arrays of tables, dotted/quoted keys, all s ## Reload safely -`ConfigStore` is an actor. Subscribe to `updates()` for snapshots, call `reload()` for a single read, or `startWatching()` for hot reload. Stop watching when the owner no longer needs updates. The watcher compares file contents every 250 ms by default, rather than depending on modification times or file identities. This follows atomic saves, deletion/recreation, parent-directory replacement, and in-place writes. It performs file work away from the main actor. +`ConfigStore` is an actor. Subscribe to `updates()` for snapshots, call `reload()` for a single read, or `startWatching(debounceInterval:)` for hot reload. Stop watching when the owner no longer needs updates. File-system sources watch the file and its parent directory, with a 100 ms debounce and no timers while idle. Symlink targets and missing directories are followed too, including atomic saves, deletion/recreation, and in-place writes. File work stays off the main actor. `stopWatching()` waits until the watcher can no longer publish. An invalid read reports diagnostics and leaves the active configuration and last good document alone. A missing initial file is an explicit default-config state, not a parse failure. Unknown keys warn with nearby spelling suggestions; wrong types, bad ranges, unsupported versions, and duplicate effective bindings reject the file. Conflicts with defaults identify the inherited binding rather than inventing a source line. diff --git a/Tests/TesseraConfigTests/ConfigStoreTests.swift b/Tests/TesseraConfigTests/ConfigStoreTests.swift index 1fab0e6b..489df4b7 100644 --- a/Tests/TesseraConfigTests/ConfigStoreTests.swift +++ b/Tests/TesseraConfigTests/ConfigStoreTests.swift @@ -247,6 +247,112 @@ struct ConfigStoreTests { } } + @Test func watcherRearmsAfterRepeatedAtomicSaves() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try fixture.write("version = 1") + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + for index in 0..<3 { + let source = "# Save \(index)\nversion = 1" + try fixture.write(source, atomic: true) + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == source } + let edited = source + "\n# In place" + try fixture.writeInPlace(edited) + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } + } + } + } + + @Test func watcherFollowsFileDeletionAndRecreation() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let source = "[motion]\nenabled = false\n" + try fixture.write(source) + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + try FileManager.default.removeItem(at: fixture.fileURL) + let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } + #expect(missing.lastGoodDocument?.source == source) + try fixture.write(source) + let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded } + #expect(recreated.lastGoodDocument?.source == source) + #expect(recreated.diagnostics.isEmpty) + try fixture.writeInPlace("version = 1") + _ = try await waitForSnapshot(store) { $0.activeConfiguration.motion.enabled } + } + } + + @Test func watcherFollowsEditsThroughASymlinkAndTargetReplacement() async throws { + let fixture = try TemporaryConfigFile() + let target = try TemporaryConfigFile() + defer { + fixture.remove() + target.remove() + } + try target.write("version = 1") + try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target.fileURL) + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + let edited = "[motion]\nenabled = false\n" + try fixture.writeInPlace(edited) + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } + let replacement = "[layout]\nratio = 0.7\n" + try target.write(replacement, atomic: true) + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } + try target.writeInPlace(edited) + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == edited } + try FileManager.default.removeItem(at: target.fileURL) + _ = try await waitForSnapshot(store) { $0.loadState == .rejected } + try target.write(replacement) + let recreated = try await waitForSnapshot(store) { $0.loadState == .loaded } + #expect(recreated.lastGoodDocument?.source == replacement) + #expect(recreated.activeSource == .file(fixture.fileURL)) + } + } + + @Test func watcherFollowsRelativeDanglingSymlinkAndRetargeting() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let target = fixture.directory.appendingPathComponent("nested/target.toml") + try FileManager.default.createSymbolicLink( + atPath: fixture.fileURL.path, withDestinationPath: "nested/target.toml") + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("version = 1".utf8).write(to: target) + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + let other = fixture.directory.appendingPathComponent("other.toml") + let source = "[motion]\nenabled = false\n" + try Data(source.utf8).write(to: other) + try FileManager.default.removeItem(at: fixture.fileURL) + try FileManager.default.createSymbolicLink(atPath: fixture.fileURL.path, withDestinationPath: "other.toml") + _ = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == source } + try fixture.writeInPlace("version = 1") + _ = try await waitForSnapshot(store) { $0.activeConfiguration.motion.enabled } + } + } + + @Test func watcherLoadsAfterMissingAncestorDirectoriesAreCreated() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let file = fixture.directory.appendingPathComponent("one/two/tessera.toml") + let store = ConfigStore(fileURL: file) + try await store.startWatching() + do { + _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("version = 1".utf8).write(to: file) + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + } catch { + await store.stopWatching() + throw error + } + await store.stopWatching() + } + @Test func watcherDetectsSameSizeInPlaceWritesWithRestoredModificationTime() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } @@ -346,19 +452,21 @@ struct ConfigStoreTests { try fixture.write(replacement) try await Task.sleep(for: .milliseconds(80)) #expect(await store.snapshot.lastGoodDocument?.source == original) - try await store.startWatching(pollInterval: .milliseconds(15)) - try await store.startWatching(pollInterval: .milliseconds(15)) + try await store.startWatching(debounceInterval: .milliseconds(15)) + try await store.startWatching(debounceInterval: .milliseconds(15)) let restarted = try await waitForSnapshot(store) { $0.lastGoodDocument?.source == replacement } #expect(restarted.diagnostics.isEmpty) } } - @Test func cancellationInterruptsALongPollingSleep() async throws { + @Test func cancellationInterruptsAPendingDebounce() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } let store = ConfigStore(fileURL: fixture.fileURL) - try await store.startWatching(pollInterval: .seconds(60)) + try await store.startWatching(debounceInterval: .seconds(60)) _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } + try fixture.write("[motion]\nenabled = false\n") + try await Task.sleep(for: .milliseconds(50)) let clock = ContinuousClock() let start = clock.now await store.stopWatching() @@ -367,11 +475,11 @@ struct ConfigStoreTests { } @Test(arguments: [Duration.zero, .milliseconds(-1)]) - func nonpositivePollingIntervalsAreRejected(interval: Duration) async throws { + func nonpositiveDebounceIntervalsAreRejected(interval: Duration) async throws { let store = ConfigStore() do { - try await store.startWatching(pollInterval: interval) - Issue.record("An invalid polling interval was accepted.") + try await store.startWatching(debounceInterval: interval) + Issue.record("An invalid debounce interval was accepted.") await store.stopWatching() } catch let diagnostic as ConfigDiagnostic { #expect(diagnostic.severity == .error) @@ -418,13 +526,13 @@ struct ConfigStoreTests { #expect(await iterator.next()?.activeConfiguration.motion.enabled == false) } - @Test func watcherDoesNotRetainTheStoreDuringSleep() async throws { + @Test func idleWatcherDoesNotRetainTheStore() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } var store: ConfigStore? = ConfigStore(fileURL: fixture.fileURL) weak let weakStore = store if let store { - try await store.startWatching(pollInterval: .seconds(60)) + try await store.startWatching(debounceInterval: .seconds(60)) _ = try await waitForSnapshot(store) { $0.loadState == .missingFileUsingDefaults } } store = nil @@ -446,27 +554,116 @@ struct ConfigStoreTests { #expect(await iterator.next() == nil) } - @Test func watcherSurfacesUnexpectedSleepFailure() async throws { - let failures = WatcherFailureRecorder() + @Test func watcherSurfacesUnexpectedDebounceFailure() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let recorder = WatcherRecorder() let watcher = ConfigFileWatcher( - pollInterval: .seconds(1), sleep: { _ in throw StoreTestError.injected }, - poll: { true }, failed: { await failures.append($0) } + fileURL: fixture.fileURL, debounceInterval: .seconds(1), + sleep: { _ in throw StoreTestError.injected }, + changed: { await recorder.changed() }, failed: { await recorder.append($0) } ) + defer { watcher.cancel() } + try await recorder.waitForChanges(1) + try fixture.write("version = 1") await watcher.waitUntilFinished() - let diagnostics = await failures.diagnostics + let diagnostics = await recorder.diagnostics #expect(diagnostics.count == 1) #expect(diagnostics.first?.severity == .error) #expect(diagnostics.first?.message.isEmpty == false) } - @Test func watcherCancellationIsNotReportedAsAFailure() async { - let failures = WatcherFailureRecorder() + @Test func watcherHasNoIdleReadsOrSleepsAndCoalescesBurstWrites() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try fixture.write("version = 1") + let recorder = WatcherRecorder() let watcher = ConfigFileWatcher( - pollInterval: .seconds(1), sleep: { _ in throw CancellationError() }, - poll: { true }, failed: { await failures.append($0) } + fileURL: fixture.fileURL, debounceInterval: .milliseconds(100), + sleep: { try await recorder.sleep($0) }, + changed: { await recorder.changed() }, failed: { await recorder.append($0) } ) + defer { watcher.cancel() } + try await recorder.waitForChanges(1) + try await Task.sleep(for: .milliseconds(300)) + #expect(await recorder.changes == 1) + #expect(await recorder.sleeps == 0) + for index in 0..<3 { + try fixture.writeInPlace("# \(index)\nversion = 1") + try await Task.sleep(for: .milliseconds(20)) + } + try await recorder.waitForChanges(2) + try await Task.sleep(for: .milliseconds(300)) + #expect(await recorder.changes == 2) + let sleeps = await recorder.sleeps + #expect(sleeps > 0) + try await Task.sleep(for: .milliseconds(300)) + #expect(await recorder.sleeps == sleeps) + watcher.cancel() await watcher.waitUntilFinished() - #expect(await failures.diagnostics.isEmpty) + #expect(await recorder.diagnostics.isEmpty) + } + + @Test func watcherCancellationIsNotReportedAsAFailure() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let recorder = WatcherRecorder() + let watcher = ConfigFileWatcher( + fileURL: fixture.fileURL, debounceInterval: .seconds(60), + sleep: { try await recorder.sleep($0) }, + changed: { await recorder.changed() }, failed: { await recorder.append($0) } + ) + defer { watcher.cancel() } + try await recorder.waitForChanges(1) + try fixture.write("version = 1") + for _ in 0..<100 { + if await recorder.sleeps > 0 { break } + try await Task.sleep(for: .milliseconds(10)) + } + #expect(await recorder.sleeps > 0) + watcher.cancel() + await watcher.waitUntilFinished() + #expect(await recorder.changes == 1) + #expect(await recorder.diagnostics.isEmpty) + } + + @Test func watchedFileResumesAfterSourceTextLoading() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let original = "version = 1" + try fixture.write(original) + try await fixture.withWatchingStore { store in + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + let loaded = await store.load(source: "[motion]\nenabled = false\n") + #expect(loaded.activeSource == .sourceText) + let resumed = try await waitForSnapshot(store) { $0.activeSource == .file(fixture.fileURL) } + #expect(resumed.lastGoodDocument?.source == original) + } + } + + @Test func watcherReportsSetupFailureAndCanRestart() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: fixture.fileURL) + let store = ConfigStore(fileURL: fixture.fileURL) + try await store.startWatching() + let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } + #expect(!failed.diagnostics.isEmpty) + #expect(await !store.isWatching) + try FileManager.default.removeItem(at: fixture.fileURL) + try fixture.write("version = 1") + try await store.startWatching() + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + await store.stopWatching() + } + + @Test func watcherRejectsNonFileURLs() async throws { + let url = try #require(URL(string: "https://example.invalid/tessera.toml")) + let store = ConfigStore(fileURL: url) + try await store.startWatching() + let failed = try await waitForSnapshot(store) { $0.loadState == .rejected } + #expect(failed.activeConfiguration == .defaults) + #expect(await !store.isWatching) } } @@ -475,12 +672,32 @@ private enum StoreTestError: Error { case injected } -private actor WatcherFailureRecorder { +private actor WatcherRecorder { private(set) var diagnostics: [ConfigDiagnostic] = [] + private(set) var changes = 0 + private(set) var sleeps = 0 + + func changed() -> Bool { + changes += 1 + return true + } + + func sleep(_ duration: Duration) async throws { + sleeps += 1 + try await Task.sleep(for: duration) + } func append(_ diagnostic: ConfigDiagnostic) { diagnostics.append(diagnostic) } + + func waitForChanges(_ count: Int) async throws { + for _ in 0..<300 { + if changes >= count { return } + try await Task.sleep(for: .milliseconds(10)) + } + throw StoreTestError.timedOut + } } private struct TemporaryConfigFile: Sendable { @@ -511,7 +728,7 @@ private struct TemporaryConfigFile: Sendable { func withWatchingStore(_ body: @Sendable (ConfigStore) async throws -> Void) async throws { let store = ConfigStore(fileURL: fileURL) - try await store.startWatching(pollInterval: .milliseconds(15)) + try await store.startWatching(debounceInterval: .milliseconds(15)) do { try await body(store) } catch { -- knotmirror 0.0.1 From 70b293f1391a61def1f7fc4f1375b93c31ee32df Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 22:55:06 -0400 Subject: [PATCH 19/44] Align motion configuration with its defaults --- Sources/TesseraConfig/ConfigJSONSchema.swift | 11 +- Sources/TesseraConfig/ConfigValidator.swift | 11 +- Sources/TesseraConfig/Configuration.swift | 32 ++++- .../TesseraConfig.docc/TesseraConfig.md | 8 +- .../ConfigValidationTests.swift | 118 ++++++++++++++++-- 5 files changed, 160 insertions(+), 20 deletions(-) diff --git a/Sources/TesseraConfig/ConfigJSONSchema.swift b/Sources/TesseraConfig/ConfigJSONSchema.swift index bebeae0b..01840026 100644 --- a/Sources/TesseraConfig/ConfigJSONSchema.swift +++ b/Sources/TesseraConfig/ConfigJSONSchema.swift @@ -77,9 +77,16 @@ public enum ConfigJSONSchema { "layout": object(layout), "motion": object([ "enabled": boolean(defaults.motion.enabled), + "level": choice( + ConfigMotionLevel.allCases.map(\.rawValue), defaultValue: defaults.motion.level.rawValue), "speed": number(ConfigLimits.speed, defaultValue: defaults.motion.speed), - "whimsy": choice( - ConfigWhimsy.allCases.map(\.rawValue), defaultValue: defaults.motion.whimsy.rawValue), + "transitions": choice( + ConfigMotionTransition.allCases.map(\.rawValue), + defaultValue: defaults.motion.transitions.rawValue), + "focus_border": boolean(defaults.motion.focusBorder), + "sound": boolean(defaults.motion.sound), + "menu_bar_icon": choice( + ConfigMenuBarIcon.allCases.map(\.rawValue), defaultValue: defaults.motion.menuBarIcon.rawValue), ]), "keybindings": object( keybindings, diff --git a/Sources/TesseraConfig/ConfigValidator.swift b/Sources/TesseraConfig/ConfigValidator.swift index bbd95fea..a247c2d3 100644 --- a/Sources/TesseraConfig/ConfigValidator.swift +++ b/Sources/TesseraConfig/ConfigValidator.swift @@ -159,10 +159,17 @@ private struct Validation { var result = MotionConfiguration() guard let node else { return result } let values = table(node, path: "motion", example: "[motion]\nenabled = true") - unknownKeys(values, allowed: ["enabled", "speed", "whimsy"], path: "motion") + unknownKeys( + values, allowed: ["enabled", "level", "speed", "transitions", "focus_border", "sound", "menu_bar_icon"], + path: "motion" + ) result.enabled = boolean(values["enabled"], path: "motion.enabled", fallback: result.enabled) + result.level = choice(values["level"], path: "motion.level", fallback: result.level) result.speed = number(values["speed"], path: "motion.speed", fallback: result.speed, bounds: ConfigLimits.speed) - result.whimsy = choice(values["whimsy"], path: "motion.whimsy", fallback: result.whimsy) + result.transitions = choice(values["transitions"], path: "motion.transitions", fallback: result.transitions) + result.focusBorder = boolean(values["focus_border"], path: "motion.focus_border", fallback: result.focusBorder) + result.sound = boolean(values["sound"], path: "motion.sound", fallback: result.sound) + result.menuBarIcon = choice(values["menu_bar_icon"], path: "motion.menu_bar_icon", fallback: result.menuBarIcon) return result } diff --git a/Sources/TesseraConfig/Configuration.swift b/Sources/TesseraConfig/Configuration.swift index 20e503b7..f9740026 100644 --- a/Sources/TesseraConfig/Configuration.swift +++ b/Sources/TesseraConfig/Configuration.swift @@ -105,19 +105,43 @@ public struct ReservedEdges: Equatable, Sendable { } } -public enum ConfigWhimsy: String, CaseIterable, Sendable { +public enum ConfigMotionLevel: String, CaseIterable, Sendable { case calm, playful, extra } +public enum ConfigMotionTransition: String, CaseIterable, Sendable { + case glide, ghost, snap +} + +public enum ConfigMenuBarIcon: String, CaseIterable, Sendable { + case minimap, logo +} + public struct MotionConfiguration: Equatable, Sendable { public var enabled: Bool + public var level: ConfigMotionLevel public var speed: Double - public var whimsy: ConfigWhimsy + public var transitions: ConfigMotionTransition + public var focusBorder: Bool + public var sound: Bool + public var menuBarIcon: ConfigMenuBarIcon - public init(enabled: Bool = true, speed: Double = 1, whimsy: ConfigWhimsy = .playful) { + public init( + enabled: Bool = true, + level: ConfigMotionLevel = .playful, + speed: Double = 1, + transitions: ConfigMotionTransition = .glide, + focusBorder: Bool = true, + sound: Bool = false, + menuBarIcon: ConfigMenuBarIcon = .minimap + ) { self.enabled = enabled + self.level = level self.speed = speed - self.whimsy = whimsy + self.transitions = transitions + self.focusBorder = focusBorder + self.sound = sound + self.menuBarIcon = menuBarIcon } } diff --git a/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md b/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md index 4a833304..be43768e 100644 --- a/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md +++ b/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md @@ -24,8 +24,12 @@ gaps.outer = 12 [motion] enabled = true +level = "playful" speed = 1.0 -whimsy = "playful" +transitions = "glide" +focus_border = true +sound = false +menu_bar_icon = "minimap" [keybindings] focus-left = "hyper-h" @@ -41,6 +45,8 @@ announce-layout-changes = false Omitted fields use defaults. A display override inherits the global layout, including individual gap and reserved-edge values. Display keys are UUIDs, not names. Float-rule matchers are combined by the consuming engine; this module validates their values and title-regex syntax. +Motion levels are `calm`, `playful`, and `extra`; transitions are `glide`, `ghost`, and `snap`. Speed accepts finite values from 0.1 through 4. The menu bar icon is `minimap` or `logo`. These are preferences for the animation and UI modules: disabling motion must turn off every animation, including fades, and system Reduce Motion still overrides enabled motion. The motion keys use the spellings above; the old `whimsy` key now produces an unknown-key warning. + The prefix affects default bindings only. Explicit chords are absolute. `hyper` means Control, Option, Command, and Shift. Chords use physical ANSI keys, and print in `ctrl-alt-cmd-shift-fn` order; `opt` prints as `alt`, and the minus key prints as `minus`. All 28 commands have defaults. Inspect `DefaultKeybindings.bindings()` for the complete table. ## Read and edit diff --git a/Tests/TesseraConfigTests/ConfigValidationTests.swift b/Tests/TesseraConfigTests/ConfigValidationTests.swift index e4ff8e41..336e0a16 100644 --- a/Tests/TesseraConfigTests/ConfigValidationTests.swift +++ b/Tests/TesseraConfigTests/ConfigValidationTests.swift @@ -42,7 +42,11 @@ struct ConfigValidationTests { } @Test func defaultMotion() { - #expect(TesseraConfiguration.defaults.motion == MotionConfiguration(enabled: true, speed: 1, whimsy: .playful)) + #expect( + TesseraConfiguration.defaults.motion + == MotionConfiguration( + enabled: true, level: .playful, speed: 1, transitions: .glide, + focusBorder: true, sound: false, menuBarIcon: .minimap)) } @Test func defaultAccessibility() { @@ -285,13 +289,68 @@ struct ConfigValidationTests { #expect(try configuration("[motion]\nspeed = 2").motion.speed == 2) } - @Test(arguments: ConfigWhimsy.allCases) - func everyWhimsyIsAccepted(_ whimsy: ConfigWhimsy) throws { - #expect(try configuration("[motion]\nwhimsy = \"\(whimsy.rawValue)\"").motion.whimsy == whimsy) + @Test(arguments: ConfigMotionLevel.allCases) + func everyMotionLevelIsAccepted(_ level: ConfigMotionLevel) throws { + #expect(try configuration("[motion]\nlevel = \"\(level.rawValue)\"").motion.level == level) + } + + @Test(arguments: ConfigMotionTransition.allCases) + func everyMotionTransitionIsAccepted(_ transition: ConfigMotionTransition) throws { + #expect( + try configuration("[motion]\ntransitions = \"\(transition.rawValue)\"").motion.transitions == transition) + } + + @Test(arguments: ConfigMenuBarIcon.allCases) + func everyMenuBarIconIsAccepted(_ icon: ConfigMenuBarIcon) throws { + #expect(try configuration("[motion]\nmenu_bar_icon = \"\(icon.rawValue)\"").motion.menuBarIcon == icon) + } + + @Test( + arguments: ["level", "transitions", "menu_bar_icon"], ["\"maximum\"", "\"Playful\"", "false", "1", "[]", "{}"]) + func invalidMotionChoicesAreRejectedWithValueLocations(key: String, value: String) throws { + let document = try TOMLDocument(parsing: "[motion]\n\(key) = \(value)") + let result = ConfigValidator.validate(document) + #expect(result.configuration == nil) + let diagnostic = try #require(result.diagnostics.first) + #expect(diagnostic.severity == .error) + #expect(diagnostic.location == document.root["motion"]?[key]?.range.start) + #expect(diagnostic.message.contains("motion.\(key)")) + #expect(diagnostic.message.contains("For example:")) + } + + @Test func allMotionSettingsCanBeCustomizedIndependently() throws { + let motion = try configuration( + """ + [motion] + enabled = false + level = "extra" + speed = 1.5 + transitions = "ghost" + focus_border = false + sound = true + menu_bar_icon = "logo" + """ + ).motion + #expect( + motion + == MotionConfiguration( + enabled: false, level: .extra, speed: 1.5, transitions: .ghost, + focusBorder: false, sound: true, menuBarIcon: .logo)) } - @Test func unknownWhimsyIsRejected() throws { - #expect(try validate("[motion]\nwhimsy = \"maximum\"").configuration == nil) + @Test func omittedMotionSettingsUseDefaults() throws { + #expect(try configuration("[motion]").motion == MotionConfiguration()) + #expect(try configuration("[motion]\nsound = true").motion == MotionConfiguration(sound: true)) + #expect(try configuration("[motion]\nfocus_border = false").motion == MotionConfiguration(focusBorder: false)) + } + + @Test(arguments: ["whimsy", "focus-border", "menu-bar-icon"]) + func obsoleteMotionKeysWarnRatherThanChangeDefaults(key: String) throws { + let result = try validate("[motion]\n\(key) = \"extra\"") + #expect(result.configuration?.motion == MotionConfiguration()) + #expect(result.diagnostics.count == 1) + #expect(result.diagnostics.first?.severity == .warning) + #expect(result.diagnostics.first?.message.contains("motion.\(key)") == true) } @Test func announcementCanBeEnabled() throws { @@ -299,7 +358,10 @@ struct ConfigValidationTests { try configuration("[accessibility]\nannounce-layout-changes = true").accessibility.announceLayoutChanges) } - @Test(arguments: ["general.launch-at-login", "motion.enabled", "accessibility.announce-layout-changes"]) + @Test(arguments: [ + "general.launch-at-login", "motion.enabled", "motion.focus_border", "motion.sound", + "accessibility.announce-layout-changes", + ]) func booleansRejectStrings(_ path: String) throws { #expect(try validate("\(path) = \"true\"").configuration == nil) } @@ -655,10 +717,44 @@ struct ConfigJSONSchemaTests { #expect(layout?["default"] == .string(TesseraConfiguration.defaults.layout.global.defaultLayout.rawValue)) } - @Test func schemaWhimsyEnumMatchesModel() throws { - let whimsy = try schema()["properties"]?["motion"]?["properties"]?["whimsy"] - #expect(whimsy?["enum"] == .array(ConfigWhimsy.allCases.map { .string($0.rawValue) })) - #expect(whimsy?["default"] == .string(TesseraConfiguration.defaults.motion.whimsy.rawValue)) + @Test func schemaMotionKeysMatchThePublicConfiguration() throws { + let motion = try #require(schema()["properties"]?["motion"]?["properties"]?.object) + #expect( + Set(motion.keys) == ["enabled", "level", "speed", "transitions", "focus_border", "sound", "menu_bar_icon"]) + } + + @Test func schemaMotionLevelEnumMatchesModel() throws { + let level = try schema()["properties"]?["motion"]?["properties"]?["level"] + #expect(level?["type"] == .string("string")) + #expect(level?["enum"] == .array(ConfigMotionLevel.allCases.map { .string($0.rawValue) })) + #expect(level?["default"] == .string(TesseraConfiguration.defaults.motion.level.rawValue)) + } + + @Test func schemaMotionTransitionEnumMatchesModel() throws { + let transitions = try schema()["properties"]?["motion"]?["properties"]?["transitions"] + #expect(transitions?["type"] == .string("string")) + #expect(transitions?["enum"] == .array(ConfigMotionTransition.allCases.map { .string($0.rawValue) })) + #expect(transitions?["default"] == .string(TesseraConfiguration.defaults.motion.transitions.rawValue)) + } + + @Test func schemaMenuBarIconEnumMatchesModel() throws { + let icon = try schema()["properties"]?["motion"]?["properties"]?["menu_bar_icon"] + #expect(icon?["type"] == .string("string")) + #expect(icon?["enum"] == .array(ConfigMenuBarIcon.allCases.map { .string($0.rawValue) })) + #expect(icon?["default"] == .string(TesseraConfiguration.defaults.motion.menuBarIcon.rawValue)) + } + + @Test func schemaMotionBooleanAndSpeedDefaultsMatchModel() throws { + let motion = try schema()["properties"]?["motion"]?["properties"] + let defaults = TesseraConfiguration.defaults.motion + for (key, expected) in [ + ("enabled", defaults.enabled), ("focus_border", defaults.focusBorder), ("sound", defaults.sound), + ] { + #expect(motion?[key]?["type"] == .string("boolean")) + #expect(motion?[key]?["default"] == .bool(expected)) + } + #expect(motion?["speed"]?["type"] == .string("number")) + #expect(motion?["speed"]?["default"] == .number(defaults.speed)) } @Test(arguments: ConfigValidationTests.numericFields) -- knotmirror 0.0.1 From 56cc79fb727afc1d9a86dd78fc83ed3cc7ec3d9b Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:00:32 -0400 Subject: [PATCH 20/44] Keep watching across path replacement races --- Sources/TesseraConfig/ConfigFileWatcher.swift | 61 ++++++++-- .../TesseraConfig.docc/TesseraConfig.md | 2 +- .../TesseraConfigTests/ConfigStoreTests.swift | 114 ++++++++++++++++++ 3 files changed, 163 insertions(+), 14 deletions(-) diff --git a/Sources/TesseraConfig/ConfigFileWatcher.swift b/Sources/TesseraConfig/ConfigFileWatcher.swift index ae4566c7..15758525 100644 --- a/Sources/TesseraConfig/ConfigFileWatcher.swift +++ b/Sources/TesseraConfig/ConfigFileWatcher.swift @@ -100,10 +100,12 @@ struct ConfigFileWatcher: Sendable { try observe(paths, observations: &observations, queue: queue, events: events) // A save can replace the path between discovery and opening its descriptor. let latest = try watchPaths(for: url) - guard latest == paths, try latest.allSatisfy({ try matches($0, observation: observations[$0]) }) else { + guard latest == paths, + try latest.keys.allSatisfy({ try matches($0, observation: observations[$0]) }) + else { continue } - for path in observations.keys where !latest.contains(path) { + for path in observations.keys where latest[path] == nil { observations.removeValue(forKey: path)?.source.cancel() } return @@ -122,10 +124,11 @@ struct ConfigFileWatcher: Sendable { } private static func observe( - _ paths: Set, observations: inout [String: FileObservation], queue: DispatchQueue, + _ paths: [String: DispatchSource.FileSystemEvent], observations: inout [String: FileObservation], + queue: DispatchQueue, events: AsyncStream.Continuation ) throws { - for path in paths.sorted() { + for (path, mask) in paths.sorted(by: { $0.key < $1.key }) { var metadata = stat() if stat(path, &metadata) != 0 { let code = errno @@ -133,7 +136,9 @@ struct ConfigFileWatcher: Sendable { observations.removeValue(forKey: path)?.source.cancel() continue } - if let current = observations[path], current.device == metadata.st_dev, current.inode == metadata.st_ino { + if let current = observations[path], current.device == metadata.st_dev, current.inode == metadata.st_ino, + current.mask == mask + { continue } observations.removeValue(forKey: path)?.source.cancel() @@ -150,22 +155,26 @@ struct ConfigFileWatcher: Sendable { throw fileError(code, path: path) } let source = DispatchSource.makeFileSystemObjectSource( - fileDescriptor: descriptor, - eventMask: [.write, .extend, .attrib, .link, .rename, .delete, .revoke], queue: queue + fileDescriptor: descriptor, eventMask: mask, queue: queue ) source.setEventHandler { events.yield(.changed) } source.setCancelHandler { close(descriptor) } - observations[path] = FileObservation(source: source, device: opened.st_dev, inode: opened.st_ino) + observations[path] = FileObservation( + source: source, device: opened.st_dev, inode: opened.st_ino, mask: mask) source.activate() } } - private static func watchPaths(for url: URL) throws -> Set { + static func watchPaths( + for url: URL, + readLink: (String) throws -> String? = symlinkDestination + ) throws -> [String: DispatchSource.FileSystemEvent] { var paths: Set = [] var current = URL(fileURLWithPath: "/", isDirectory: true) var remaining = Array(url.pathComponents.dropFirst().reversed()) var links = 0 while let component = remaining.popLast() { + try Task.checkCancellation() if component == "." { continue } if component == ".." { current.deleteLastPathComponent() @@ -181,10 +190,13 @@ struct ConfigFileWatcher: Sendable { break } if metadata.st_mode & S_IFMT == S_IFLNK { + paths.insert(current.path) + guard let destination = try readLink(next.path) else { + remaining.append(component) + continue + } links += 1 guard links <= 40 else { throw fileError(ELOOP, path: next.path) } - paths.insert(current.path) - let destination = try FileManager.default.destinationOfSymbolicLink(atPath: next.path) let components = NSString(string: destination).pathComponents if destination.hasPrefix("/") { current = URL(fileURLWithPath: "/", isDirectory: true) } remaining.append(contentsOf: components.filter { $0 != "/" }.reversed()) @@ -195,7 +207,7 @@ struct ConfigFileWatcher: Sendable { paths.insert(current.path) paths.insert(current.deletingLastPathComponent().path) // Missing directories need their nearest surviving ancestor to announce recreation. - var existing: Set = [] + var existing: [String: DispatchSource.FileSystemEvent] = [:] for path in paths { var candidate = URL(fileURLWithPath: path) var metadata = stat() @@ -204,11 +216,33 @@ struct ConfigFileWatcher: Sendable { guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: candidate.path) } candidate.deleteLastPathComponent() } - existing.insert(candidate.path) + existing[candidate.path, default: []].formUnion([ + .write, .extend, .attrib, .link, .rename, .delete, .revoke, + ]) + // Ancestors report moves without waking us for unrelated descendant writes. + while candidate.path != "/" { + candidate.deleteLastPathComponent() + existing[candidate.path, default: []].formUnion([.rename, .delete, .revoke]) + } } return existing } + static func symlinkDestination(_ path: String) throws -> String? { + var buffer = [CChar](repeating: 0, count: Int(PATH_MAX) + 1) + let count = readlink(path, &buffer, buffer.count - 1) + guard count >= 0 else { + let code = errno + // The link may have disappeared or become a regular file since lstat. + if code == ENOENT || code == ENOTDIR || code == EINVAL { return nil } + throw fileError(code, path: path) + } + guard count < buffer.count - 1 else { throw fileError(ENAMETOOLONG, path: path) } + let bytes = buffer.prefix(count).map { UInt8(bitPattern: $0) } + guard let destination = String(validating: bytes, as: UTF8.self) else { throw fileError(EILSEQ, path: path) } + return destination + } + private static func fileError(_ code: Int32, path: String) -> NSError { NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: [NSFilePathErrorKey: path]) } @@ -224,6 +258,7 @@ private struct FileObservation { let source: any DispatchSourceFileSystemObject let device: dev_t let inode: ino_t + let mask: DispatchSource.FileSystemEvent } enum ConfigFileContents: Sendable, Equatable { diff --git a/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md b/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md index be43768e..6e2a69fc 100644 --- a/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md +++ b/Sources/TesseraConfig/TesseraConfig.docc/TesseraConfig.md @@ -64,7 +64,7 @@ The parser supports TOML 1.0 tables, arrays of tables, dotted/quoted keys, all s ## Reload safely -`ConfigStore` is an actor. Subscribe to `updates()` for snapshots, call `reload()` for a single read, or `startWatching(debounceInterval:)` for hot reload. Stop watching when the owner no longer needs updates. File-system sources watch the file and its parent directory, with a 100 ms debounce and no timers while idle. Symlink targets and missing directories are followed too, including atomic saves, deletion/recreation, and in-place writes. File work stays off the main actor. `stopWatching()` waits until the watcher can no longer publish. +`ConfigStore` is an actor. Subscribe to `updates()` for snapshots, call `reload()` for a single read, or `startWatching(debounceInterval:)` for hot reload. Stop watching when the owner no longer needs updates. File-system sources watch the file and its parent directory, with a 100 ms debounce and no timers while idle. Symlink targets and missing directories are followed too, including atomic saves, deletion/recreation, and in-place writes. Additional ancestor subscriptions listen only for rename, delete, or revoke events, not unrelated sibling writes. File work stays off the main actor. `stopWatching()` waits until the watcher can no longer publish. An invalid read reports diagnostics and leaves the active configuration and last good document alone. A missing initial file is an explicit default-config state, not a parse failure. Unknown keys warn with nearby spelling suggestions; wrong types, bad ranges, unsupported versions, and duplicate effective bindings reject the file. Conflicts with defaults identify the inherited binding rather than inventing a source line. diff --git a/Tests/TesseraConfigTests/ConfigStoreTests.swift b/Tests/TesseraConfigTests/ConfigStoreTests.swift index 489df4b7..01aaa8db 100644 --- a/Tests/TesseraConfigTests/ConfigStoreTests.swift +++ b/Tests/TesseraConfigTests/ConfigStoreTests.swift @@ -411,6 +411,120 @@ struct ConfigStoreTests { } } + @Test(arguments: [false, true]) + func watcherFollowsAncestorRenameAndRecreation(throughSymlink: Bool) async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let outer = fixture.directory.appendingPathComponent("outer") + let target = outer.appendingPathComponent("inner/tessera.toml") + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("[layout]\nratio = 0.6\n".utf8).write(to: target) + if throughSymlink { + try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) + } + let store = ConfigStore(fileURL: throughSymlink ? fixture.fileURL : target) + try await store.startWatching() + do { + _ = try await waitForSnapshot(store) { $0.loadState == .loaded } + try FileManager.default.moveItem(at: outer, to: fixture.directory.appendingPathComponent("moved")) + let missing = try await waitForSnapshot(store) { $0.loadState == .rejected } + #expect(missing.activeConfiguration.layout.global.ratio == 0.6) + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("[layout]\nratio = 0.7\n".utf8).write(to: target) + _ = try await waitForSnapshot(store) { $0.activeConfiguration.layout.global.ratio == 0.7 } + try Data("[layout]\nratio = 0.8\n".utf8).write(to: target, options: .atomic) + _ = try await waitForSnapshot(store) { $0.activeConfiguration.layout.global.ratio == 0.8 } + #expect(await store.isWatching) + } catch { + await store.stopWatching() + throw error + } + await store.stopWatching() + } + + @Test(arguments: ["deleted", "regular", "retargeted"]) + func symlinkDiscoveryRetriesWhenTheLinkChangesAfterInspection(replacement: String) throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let target = fixture.directory.appendingPathComponent("target.toml") + try Data("version = 1".utf8).write(to: target) + try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) + let suffix = "/\(fixture.directory.lastPathComponent)/tessera.toml" + var replaced = false + let paths = try ConfigFileWatcher.watchPaths(for: fixture.fileURL) { path in + if path.hasSuffix(suffix), !replaced { + replaced = true + try FileManager.default.removeItem(at: fixture.fileURL) + if replacement == "regular" { try fixture.write("version = 1") } + let destination = try ConfigFileWatcher.symlinkDestination(path) + #expect(destination == nil) + if replacement == "retargeted" { + try FileManager.default.createSymbolicLink(at: fixture.fileURL, withDestinationURL: target) + } + return destination + } + return try ConfigFileWatcher.symlinkDestination(path) + } + #expect(replaced) + let directory = try #require(paths.keys.first { $0.hasSuffix("/\(fixture.directory.lastPathComponent)") }) + #expect(paths[directory]?.contains(.write) == true) + if replacement == "regular" { #expect(paths["\(directory)/tessera.toml"]?.contains(.write) == true) } + if replacement == "retargeted" { #expect(paths["\(directory)/target.toml"]?.contains(.write) == true) } + } + + @Test func symlinkReadDistinguishesTransientChangesFromAccessFailures() throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.path) == nil) + try fixture.write("version = 1") + #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.path) == nil) + #expect(try ConfigFileWatcher.symlinkDestination(fixture.fileURL.appendingPathComponent("child").path) == nil) + let blocked = fixture.directory.appendingPathComponent("blocked") + try FileManager.default.createDirectory(at: blocked, withIntermediateDirectories: false) + try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: blocked.path) + defer { + do { + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: blocked.path) + } catch { + Issue.record(error) + } + } + #expect(throws: (any Error).self) { + try ConfigFileWatcher.symlinkDestination(blocked.appendingPathComponent("link").path) + } + } + + @Test func ancestorSiblingChangesDoNotScheduleReloads() async throws { + let fixture = try TemporaryConfigFile() + defer { fixture.remove() } + let target = fixture.directory.appendingPathComponent("inner/tessera.toml") + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("version = 1".utf8).write(to: target) + let paths = try ConfigFileWatcher.watchPaths(for: target) + let ancestor = try #require(paths.keys.first { $0.hasSuffix("/\(fixture.directory.lastPathComponent)") }) + #expect(paths[ancestor] == [.rename, .delete, .revoke]) + let recorder = WatcherRecorder() + let watcher = ConfigFileWatcher( + fileURL: target, debounceInterval: .milliseconds(100), sleep: { try await recorder.sleep($0) }, + changed: { await recorder.changed() }, failed: { await recorder.append($0) } + ) + defer { watcher.cancel() } + try await recorder.waitForChanges(1) + for _ in 0..<3 { + try fixture.write("# Unrelated sibling") + try FileManager.default.removeItem(at: fixture.fileURL) + } + try await Task.sleep(for: .milliseconds(300)) + watcher.cancel() + await watcher.waitUntilFinished() + #expect(await recorder.changes == 1) + #expect(await recorder.sleeps == 0) + #expect(await recorder.diagnostics.isEmpty) + } + @Test func watcherLoadsAFileCreatedAfterAnInitialMissingFile() async throws { let fixture = try TemporaryConfigFile() defer { fixture.remove() } -- knotmirror 0.0.1 From b403b5d1a8878a030bcdacbcf2181b54c6f25a58 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:01:35 -0400 Subject: [PATCH 21/44] Add workspace reducer and deterministic replay --- Package.swift | 2 +- Sources/TesseraCore/Commands.swift | 190 ++++++++++++ Sources/TesseraCore/Decoding.swift | 42 +++ Sources/TesseraCore/Events.swift | 135 ++++++++ Sources/TesseraCore/LayoutEngine.swift | 25 +- Sources/TesseraCore/Model.swift | 20 +- Sources/TesseraCore/Reducer.swift | 131 ++++++++ Sources/TesseraCore/Replay.swift | 70 +++++ Sources/TesseraCore/State.swift | 125 ++++++++ .../TesseraCore.docc/TesseraCore.md | 52 ++++ Tests/TesseraCoreTests/CommandTests.swift | 290 ++++++++++++++++++ .../TesseraCoreTests/DisplaySpaceTests.swift | 257 ++++++++++++++++ .../Fixtures/displays-frames.json | 5 + .../TesseraCoreTests/Fixtures/displays.jsonl | 10 + .../Fixtures/side-frames.json | 5 + Tests/TesseraCoreTests/Fixtures/side.jsonl | 8 + Tests/TesseraCoreTests/LayoutPixelTests.swift | 80 +++++ Tests/TesseraCoreTests/ReducerTests.swift | 284 +++++++++++++++++ Tests/TesseraCoreTests/RegressionTests.swift | 154 ++++++++++ Tests/TesseraCoreTests/ReplayTests.swift | 142 +++++++++ 20 files changed, 2015 insertions(+), 12 deletions(-) create mode 100644 Sources/TesseraCore/Commands.swift create mode 100644 Sources/TesseraCore/Decoding.swift create mode 100644 Sources/TesseraCore/Events.swift create mode 100644 Sources/TesseraCore/Reducer.swift create mode 100644 Sources/TesseraCore/Replay.swift create mode 100644 Sources/TesseraCore/State.swift create mode 100644 Sources/TesseraCore/TesseraCore.docc/TesseraCore.md create mode 100644 Tests/TesseraCoreTests/CommandTests.swift create mode 100644 Tests/TesseraCoreTests/DisplaySpaceTests.swift create mode 100644 Tests/TesseraCoreTests/Fixtures/displays-frames.json create mode 100644 Tests/TesseraCoreTests/Fixtures/displays.jsonl create mode 100644 Tests/TesseraCoreTests/Fixtures/side-frames.json create mode 100644 Tests/TesseraCoreTests/Fixtures/side.jsonl create mode 100644 Tests/TesseraCoreTests/LayoutPixelTests.swift create mode 100644 Tests/TesseraCoreTests/ReducerTests.swift create mode 100644 Tests/TesseraCoreTests/RegressionTests.swift create mode 100644 Tests/TesseraCoreTests/ReplayTests.swift diff --git a/Package.swift b/Package.swift index 61373897..f5f78d58 100644 --- a/Package.swift +++ b/Package.swift @@ -34,7 +34,7 @@ let package = Package( ), .executableTarget(name: "FixtureApp", swiftSettings: strict), - .testTarget(name: "TesseraCoreTests", dependencies: ["TesseraCore"]), + .testTarget(name: "TesseraCoreTests", dependencies: ["TesseraCore"], resources: [.copy("Fixtures")]), .testTarget(name: "TesseraConfigTests", dependencies: ["TesseraConfig"]), .testTarget(name: "TesseraPlatformTests", dependencies: ["TesseraPlatform"]), .testTarget(name: "TesseraEngineTests", dependencies: ["TesseraEngine"]), diff --git a/Sources/TesseraCore/Commands.swift b/Sources/TesseraCore/Commands.swift new file mode 100644 index 00000000..36f8a05f --- /dev/null +++ b/Sources/TesseraCore/Commands.swift @@ -0,0 +1,190 @@ +extension Command { + var affectsWorkspace: Bool { + switch self { + case .cycleLayout, .setLayout, .setRatio, .nudgeRatio, .retile, .setWindowCap: true + default: false + } + } +} + +extension State { + mutating func apply(_ command: Command, effects: inout [Effect]) { + if command.affectsWorkspace { + guard let key = activeWorkspace, isActive(key) else { + effects.append(.report(.noActiveWorkspace)) + return + } + applyWorkspace(command, key: key, effects: &effects) + } else { + guard let window = focusedWindow, let key = workspace(containing: window), isActive(key) else { + effects.append(.report(.noFocusedWindow)) + return + } + applyFocused(command, window: window, key: key, effects: &effects) + } + } + + private mutating func applyWorkspace(_ command: Command, key: WorkspaceKey, effects: inout [Effect]) { + guard var workspace = workspaces[key] else { return } + switch command { + case .cycleLayout: + workspace.layout = workspace.layout.next + workspace.rebuild(stacks: workspace.tree?.stacks ?? []) + effects.append(.announce(.layoutChanged(workspace.layout))) + case .setLayout(let layout): + workspace.layout = layout + workspace.rebuild(stacks: workspace.tree?.stacks ?? []) + effects.append(.announce(.layoutChanged(layout))) + case .setRatio(let ratio): + workspace.changeRatio(ratio, effects: &effects) + case .nudgeRatio(let delta): + guard delta.isFinite else { + effects.append(.report(.invalidRatio)) + return + } + workspace.changeRatio(MainRatio(workspace.ratio.value + min(1, max(-1, delta))), effects: &effects) + case .retile: + workspace.rebuild(stacks: workspace.tree?.stacks ?? []) + case .setWindowCap(let cap): + workspace.setWindowCap(cap) + default: break + } + workspaces[key] = workspace + } + + private mutating func applyFocused(_ command: Command, window: WindowID, key: WorkspaceKey, effects: inout [Effect]) + { + switch command { + case .focus(let direction): + guard let target = neighbor(of: window, direction: direction) else { + effects.append(.report(.noNeighbor(direction))) + return + } + focus(target, effects: &effects) + case .swap(let direction): + swap(window, direction: direction, effects: &effects) + case .move(let direction): + move(window, direction: direction, stacking: false, effects: &effects) + case .stack(let direction): + move(window, direction: direction, stacking: true, effects: &effects) + case .toggleFloat: + toggleFloat(window, key: key, effects: &effects) + case .moveToDisplay(let direction): + moveToDisplay(window, from: key, direction: direction, effects: &effects) + case .unstack: + unstack(window, key: key, effects: &effects) + case .focusNextInStack, .focusPreviousInStack: + cycleStack(window, key: key, forward: command == .focusNextInStack, effects: &effects) + default: break + } + } + + private mutating func swap(_ window: WindowID, direction: Direction, effects: inout [Effect]) { + guard let target = neighbor(of: window, direction: direction, tiledOnly: true), + windows[window]?.isFloating == false, + let source = workspace(containing: window), let destination = workspace(containing: target) + else { + effects.append(.report(.noNeighbor(direction))) + return + } + for key in Set([source, destination]).sorted() { + guard var workspace = workspaces[key] else { continue } + workspace.tree = workspace.tree?.mappingStacks { stack in + if stack.windows.contains(window) { return stack.replacing(window, with: target) } + if stack.windows.contains(target) { return stack.replacing(target, with: window) } + return stack + } + workspace.order = workspace.order.map { $0 == window ? target : ($0 == target ? window : $0) } + workspaces[key] = workspace + } + workspaces[source]?.focus = target + focus(window, effects: &effects) + } + + private mutating func move(_ window: WindowID, direction: Direction, stacking: Bool, effects: inout [Effect]) { + guard windows[window]?.isFloating == false, + let target = neighbor(of: window, direction: direction, tiledOnly: true), + let source = workspace(containing: window), let destination = workspace(containing: target), + var workspace = workspaces[destination] + else { + effects.append(.report(.noNeighbor(direction))) + return + } + workspaces[source]?.remove(window) + if source == destination, let updated = workspaces[source] { workspace = updated } + let index = workspace.order.firstIndex(of: target) ?? workspace.order.count + workspace.order.insert(window, at: min(workspace.order.count, index + (direction.isBefore ? 0 : 1))) + if stacking || (workspace.tree?.tileCount ?? 0) >= workspace.windowCap { + workspace.tree = workspace.tree?.mappingStacks { stack in + var updated = stack + if stack.windows.contains(target) { updated.append(window) } + return updated + } + } else { + workspace.tree = workspace.tree?.inserting( + window, beside: target, axis: direction.axis, before: direction.isBefore) + } + workspace.select(window) + workspaces[destination] = workspace + focus(window, effects: &effects) + if stacking { + let count = workspace.tree?.stacks.first { $0.windows.contains(window) }?.windows.count ?? 1 + effects.append(.announce(.stackChanged(window: window, count: count))) + } + } + + private mutating func toggleFloat(_ window: WindowID, key: WorkspaceKey, effects: inout [Effect]) { + guard let wasFloating = windows[window]?.isFloating else { return } + windows[window]?.isFloating = !wasFloating + if wasFloating { + workspaces[key]?.remove(window) + workspaces[key]?.insert( + window, floating: false, in: displays[key.display]?.frame ?? Rect(), windows: windows) + } else { + let remaining = workspaces[key]?.tree?.removing(window) + workspaces[key]?.tree = remaining + } + effects.append(.announce(.floatingChanged(window, isFloating: !wasFloating))) + } + + private mutating func moveToDisplay( + _ window: WindowID, from key: WorkspaceKey, direction: Direction, effects: inout [Effect] + ) { + guard let display = displayNeighbor(from: key.display, direction: direction), let space = activeSpaces[display] + else { + effects.append(.report(.noNeighbor(direction))) + return + } + transfer(window, to: WorkspaceKey(display: display, space: space)) + focus(window, effects: &effects) + effects.append(.announce(.movedToDisplay(window, display))) + } + + private mutating func unstack(_ window: WindowID, key: WorkspaceKey, effects: inout [Effect]) { + guard var workspace = workspaces[key], + let stack = workspace.tree?.stacks.first(where: { $0.windows.contains(window) }), stack.windows.count > 1 + else { return } + guard (workspace.tree?.tileCount ?? 0) < workspace.windowCap else { + effects.append(.report(.atWindowCap(workspace.windowCap))) + return + } + workspace.remove(window) + workspace.insert(window, floating: false, in: displays[key.display]?.frame ?? Rect(), windows: windows) + workspaces[key] = workspace + effects.append(.announce(.stackChanged(window: window, count: 1))) + } + + private mutating func cycleStack(_ window: WindowID, key: WorkspaceKey, forward: Bool, effects: inout [Effect]) { + guard var stack = workspaces[key]?.tree?.stacks.first(where: { $0.windows.contains(window) }) else { return } + stack.cycle(forward: forward) + focus(stack.visible, effects: &effects) + } +} + +extension Workspace { + mutating func changeRatio(_ ratio: MainRatio, effects: inout [Effect]) { + self.ratio = ratio + if layout == .side { tree = tree?.settingMainRatio(ratio) } + effects.append(.announce(.ratioChanged(ratio))) + } +} diff --git a/Sources/TesseraCore/Decoding.swift b/Sources/TesseraCore/Decoding.swift new file mode 100644 index 00000000..a78ad3ca --- /dev/null +++ b/Sources/TesseraCore/Decoding.swift @@ -0,0 +1,42 @@ +extension TileTree { + var isValid: Bool { + switch self { + case .tile: true + case .split(_, let fraction, let first, let second): + fraction.isFinite && (0...1).contains(fraction) && first.isValid && second.isValid + && Set(windows).count == windows.count + } + } +} + +extension Workspace { + enum CodingKeys: String, CodingKey { + case key, layout, ratio, gaps, reservedEdges, windowCap, order, focus, tree + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let key = try container.decode(WorkspaceKey.self, forKey: .key) + let layout = try container.decode(Layout.self, forKey: .layout) + let ratio = try container.decode(MainRatio.self, forKey: .ratio) + let gaps = try container.decode(Gaps.self, forKey: .gaps) + let reserved = try container.decode(Insets.self, forKey: .reservedEdges) + let cap = try container.decode(Int.self, forKey: .windowCap) + let order = try container.decode([WindowID].self, forKey: .order) + let focus = try container.decodeIfPresent(WindowID.self, forKey: .focus) + let tree = try container.decodeIfPresent(TileTree.self, forKey: .tree) + guard cap > 0, Set(order).count == order.count, focus.map(order.contains) != false, + tree?.isValid != false, (tree?.tileCount ?? 0) <= cap, + Set(tree?.windows ?? []).isSubset(of: Set(order)) + else { + throw DecodingError.dataCorrupted( + .init( + codingPath: decoder.codingPath, debugDescription: "A workspace has inconsistent tiles or membership" + )) + } + self.init(key: key, layout: layout, ratio: ratio, gaps: gaps, reservedEdges: reserved, windowCap: cap) + self.order = order + self.focus = focus + self.tree = tree + } +} diff --git a/Sources/TesseraCore/Events.swift b/Sources/TesseraCore/Events.swift new file mode 100644 index 00000000..fa856318 --- /dev/null +++ b/Sources/TesseraCore/Events.swift @@ -0,0 +1,135 @@ +extension State { + mutating func handle(_ event: Event, baseline: inout [WindowID: Rect], effects: inout [Effect]) -> Report? { + switch event { + case .windowAppeared(let window, let key, let frame): + guard frame.isValid, window.minimumSize?.isValid != false else { return .invalidGeometry } + if let version = window.minimum?.schemaVersion, version != LearnedMinimumSize.currentVersion { + return .unsupportedMinimumVersion(version) + } + appear(window, key: key, frame: frame, baseline: &baseline, effects: &effects) + case .windowDisappeared(let window): + disappear(window, effects: &effects) + case .windowMovedByUser(let window, let frame), .windowResizedByUser(let window, let frame): + return userFrame(window, frame: frame, baseline: &baseline) + case .focusChanged(let window): + return observedFocus(window, effects: &effects) + case .displaySetChanged(let displays): + return changeDisplays(displays, effects: &effects) + case .activeSpaceChanged(let display, let space): + return changeSpace(display, space: space, effects: &effects) + case .commandIssued(let command): + apply(command, effects: &effects) + case .minimumSizeChanged(let window, let minimum): + return changeMinimum(window, minimum: minimum) + } + return nil + } + + private mutating func appear( + _ window: ManagedWindow, key: WorkspaceKey, frame: Rect, + baseline: inout [WindowID: Rect], effects: inout [Effect] + ) { + let existing = workspace(containing: window.id) + if let existing, existing != key { workspaces[existing]?.remove(window.id) } + let previous = windows[window.id] + windows[window.id] = window + observedFrames[window.id] = frame + baseline[window.id] = frame + if window.isFloating || !isActive(key) { frames[window.id] = frame } + if workspaces[key] == nil { workspaces[key] = Workspace(key: key) } + guard var workspace = workspaces[key] else { return } + if previous?.isFloating != window.isFloating { workspace.tree = workspace.tree?.removing(window.id) } + if workspace.order.contains(window.id) && !window.isFloating + && workspace.tree?.windows.contains(window.id) != true + { + workspace.order.removeAll { $0 == window.id } + } + workspace.insert( + window.id, floating: window.isFloating, in: displays[key.display]?.frame ?? frame, windows: windows) + workspaces[key] = workspace + if isActive(key) && (previous == nil || existing != key) { focus(window.id, effects: &effects) } + } + + private mutating func disappear(_ window: WindowID, effects: inout [Effect]) { + guard windows.removeValue(forKey: window) != nil else { return } + let key = workspace(containing: window) + if let key { workspaces[key]?.remove(window) } + frames.removeValue(forKey: window) + observedFrames.removeValue(forKey: window) + if focusedWindow == window { + focusedWindow = nil + if let key, isActive(key), let replacement = workspaces[key]?.focus { + focus(replacement, effects: &effects) + } + } + } + + private mutating func userFrame(_ window: WindowID, frame: Rect, baseline: inout [WindowID: Rect]) -> Report? { + guard frame.isValid else { return .invalidGeometry } + guard let managed = windows[window] else { return .unknownWindow(window) } + observedFrames[window] = frame + baseline[window] = frame + if managed.isFloating || workspace(containing: window).map(isActive) != true { frames[window] = frame } + return nil + } + + private mutating func observedFocus(_ window: WindowID?, effects: inout [Effect]) -> Report? { + guard let window else { + focusedWindow = nil + return nil + } + guard windows[window] != nil else { return .unknownWindow(window) } + guard let key = workspace(containing: window), isActive(key) else { return nil } + focus(window, requestingFocus: false, effects: &effects) + return nil + } + + private mutating func changeMinimum(_ window: WindowID, minimum: LearnedMinimumSize?) -> Report? { + guard windows[window] != nil else { return .unknownWindow(window) } + guard minimum?.size.isValid != false else { return .invalidGeometry } + if let version = minimum?.schemaVersion, version != LearnedMinimumSize.currentVersion { + return .unsupportedMinimumVersion(version) + } + windows[window]?.minimum = minimum + return nil + } + + private mutating func changeDisplays(_ updated: [Display], effects: inout [Effect]) -> Report? { + guard updated.allSatisfy({ $0.frame.isValid }), Set(updated.map(\.id)).count == updated.count else { + return .invalidGeometry + } + displays = Dictionary(uniqueKeysWithValues: updated.map { ($0.id, $0) }) + if activeDisplay.flatMap({ displays[$0] }) == nil { activeDisplay = updated.first?.id } + migrateDisconnected(effects: &effects) + if updated.isEmpty { focusedWindow = nil } + return nil + } + + private mutating func migrateDisconnected(effects: inout [Effect]) { + guard let destination = activeWorkspace, isActive(destination) else { return } + let sources = workspaces.keys.sorted().filter { + displays[$0.display] == nil && activeSpaces[$0.display] == $0.space + && workspaces[$0]?.order.isEmpty == false + } + let preserved = focusedWindow ?? sources.first.flatMap { workspaces[$0]?.focus } + for source in sources { + for window in workspaces[source]?.order ?? [] { transfer(window, to: destination) } + } + if let preserved { focus(preserved, effects: &effects) } + } + + private mutating func changeSpace(_ display: DisplayID, space: SpaceID, effects: inout [Effect]) -> Report? { + guard displays[display] != nil else { return .unavailableDisplay(display) } + let changed = activeSpaces[display] != space + activeSpaces[display] = space + let key = WorkspaceKey(display: display, space: space) + if workspaces[key] == nil { workspaces[key] = Workspace(key: key) } + if activeDisplay == nil { activeDisplay = display } + migrateDisconnected(effects: &effects) + if changed && activeDisplay == display { + focusedWindow = nil + if let window = workspaces[key]?.focus { focus(window, effects: &effects) } + } + return nil + } +} diff --git a/Sources/TesseraCore/LayoutEngine.swift b/Sources/TesseraCore/LayoutEngine.swift index e87df25e..54ff2f9d 100644 --- a/Sources/TesseraCore/LayoutEngine.swift +++ b/Sources/TesseraCore/LayoutEngine.swift @@ -42,7 +42,10 @@ public enum LayoutEngine { case .tile(let stack): return stack.windows.reduce(Size()) { size, window in let learned = windows[window]?.minimumSize ?? Size() - return Size(width: max(size.width, learned.width), height: max(size.height, learned.height)) + return Size( + width: max(size.width, learned.width.rounded(.up)), + height: max(size.height, learned.height.rounded(.up)) + ) } case .split(let axis, _, let first, let second): let left = minimum(first, gap: gap, windows: windows) @@ -69,33 +72,37 @@ public enum LayoutEngine { } case .split(let axis, let fraction, let first, let second): let extent = axis == .horizontal ? area.size.width : area.size.height - let available = max(0, extent - gap) - let firstMinimum = minimum(first, gap: gap, windows: windows) - let secondMinimum = minimum(second, gap: gap, windows: windows) + let localGap = min(gap, extent / Double(dividers(tree, axis: axis))) + let available = max(0, extent - localGap) + let firstMinimum = minimum(first, gap: localGap, windows: windows) + let secondMinimum = minimum(second, gap: localGap, windows: windows) let lower = axis == .horizontal ? firstMinimum.width : firstMinimum.height let upper = axis == .horizontal ? secondMinimum.width : secondMinimum.height - let firstGaps = Double(dividers(first, axis: axis)) * gap - let secondGaps = Double(dividers(second, axis: axis)) * gap + let firstGaps = Double(dividers(first, axis: axis)) * localGap + let secondGaps = Double(dividers(second, axis: axis)) * localGap let desired = max(0, available - firstGaps - secondGaps) * min(1, max(0, fraction)) + firstGaps let length: Double if lower + upper <= available { length = min(available - upper, max(lower, desired)) } else { // Keep every tile on-screen when constraints conflict; report the shortfall below. - length = lower + upper > 0 ? available * lower / (lower + upper) : desired + let content = max(0, available - firstGaps - secondGaps) + let firstContent = max(0, lower - firstGaps) + let totalContent = firstContent + max(0, upper - secondGaps) + length = firstGaps + (totalContent > 0 ? content * firstContent / totalContent : 0) } let left: Rect let right: Rect if axis == .horizontal { left = Rect(x: area.minX, y: area.minY, width: length, height: area.size.height) right = Rect( - x: area.minX + length + gap, y: area.minY, + x: area.minX + length + localGap, y: area.minY, width: max(0, available - length), height: area.size.height ) } else { left = Rect(x: area.minX, y: area.minY, width: area.size.width, height: length) right = Rect( - x: area.minX, y: area.minY + length + gap, + x: area.minX, y: area.minY + length + localGap, width: area.size.width, height: max(0, available - length) ) } diff --git a/Sources/TesseraCore/Model.swift b/Sources/TesseraCore/Model.swift index 818baae0..14d7727f 100644 --- a/Sources/TesseraCore/Model.swift +++ b/Sources/TesseraCore/Model.swift @@ -38,9 +38,10 @@ public struct WorkspaceKey: Sendable, Equatable, Hashable, Codable, Comparable { } public struct LearnedMinimumSize: Sendable, Equatable, Codable { + public static let currentVersion = 1 public let schemaVersion: Int public let size: Size - public init(size: Size, schemaVersion: Int = 1) { + public init(size: Size, schemaVersion: Int = LearnedMinimumSize.currentVersion) { self.size = size self.schemaVersion = schemaVersion } @@ -134,10 +135,25 @@ public struct WindowStack: Sendable, Equatable, Codable { public private(set) var visible: WindowID public init(_ first: WindowID, others: [WindowID] = []) { - windows = [first] + others.filter { $0 != first } + var seen: Set = [first] + windows = [first] + others.filter { seen.insert($0).inserted } visible = first } + private enum CodingKeys: String, CodingKey { case windows, visible } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let windows = try container.decode([WindowID].self, forKey: .windows) + let visible = try container.decode(WindowID.self, forKey: .visible) + guard !windows.isEmpty, Set(windows).count == windows.count, windows.contains(visible) else { + throw DecodingError.dataCorruptedError( + forKey: .windows, in: container, debugDescription: "A stack needs unique members and a visible member") + } + self.windows = windows + self.visible = visible + } + mutating func append(_ window: WindowID) { guard !windows.contains(window) else { return } windows.append(window) diff --git a/Sources/TesseraCore/Reducer.swift b/Sources/TesseraCore/Reducer.swift new file mode 100644 index 00000000..702169f9 --- /dev/null +++ b/Sources/TesseraCore/Reducer.swift @@ -0,0 +1,131 @@ +public func reduce(_ state: State, _ event: Event) -> (State, [Effect]) { + var next = state + var effects: [Effect] = [] + var baseline = state.frames + if let issue = next.handle(event, baseline: &baseline, effects: &effects) { + return (state, [.report(issue)]) + } + let desired = next.layoutFrames() + let writes = desired.frames.keys.sorted().compactMap { window -> WindowFrame? in + guard let frame = desired.frames[window], frame != baseline[window] else { return nil } + return WindowFrame(window: window, frame: frame) + } + for (window, frame) in desired.frames { next.frames[window] = frame } + next.cannotFit = desired.cannotFit + if !writes.isEmpty { effects.insert(.setFrames(writes), at: 0) } + if next.cannotFit != state.cannotFit && !next.cannotFit.isEmpty { + effects.append(.report(.cannotFit(next.cannotFit))) + } + next.raiseChangedStacks(previous: state, writes: writes, effects: &effects) + if let focused = next.focusedWindow, next.windows[focused]?.isFloating == true, + effects.contains(where: { if case .raiseWindow = $0 { true } else { false } }) + { + effects.removeAll { $0 == .raiseWindow(focused) } + effects.append(.raiseWindow(focused)) + } + if event == .commandIssued(.retile) && next.activeWorkspace != nil { + effects.append(.report(.retiled(moved: writes.count))) + } + return (next, effects) +} + +extension Size { + var isValid: Bool { width.isFinite && height.isFinite && width >= 0 && height >= 0 } +} + +extension Rect { + var isValid: Bool { origin.xCoordinate.isFinite && origin.yCoordinate.isFinite && size.isValid } +} + +extension State { + fileprivate func raiseChangedStacks(previous: State, writes: [WindowFrame], effects: inout [Effect]) { + for key in workspaces.keys.sorted() where isActive(key) { + let oldStacks = previous.workspaces[key]?.tree?.stacks ?? [] + for stack in workspaces[key]?.tree?.stacks ?? [] where stack.windows.count > 1 { + let changed = !oldStacks.contains(stack) || writes.contains { stack.windows.contains($0.window) } + if changed && !effects.contains(.raiseWindow(stack.visible)) { + effects.append(.raiseWindow(stack.visible)) + } + } + } + } + + func layoutFrames() -> LayoutResult { + var result = LayoutResult() + for key in workspaces.keys.sorted() where isActive(key) { + guard let workspace = workspaces[key], let display = displays[key.display] else { continue } + let layout = LayoutEngine.arrange(workspace, in: display.frame, windows: windows) + for (window, frame) in layout.frames where windows[window]?.isFloating == false { + result.frames[window] = frame + } + result.visibleWindows += layout.visibleWindows + result.cannotFit += layout.cannotFit + } + for key in workspaces.keys.sorted() where isActive(key) { + for window in workspaces[key]?.order ?? [] where windows[window]?.isFloating == true { + if let frame = frames[window] { result.frames[window] = frame } + } + } + result.cannotFit.sort() + return result + } + + mutating func focus(_ window: WindowID, requestingFocus: Bool = true, effects: inout [Effect]) { + guard let key = workspace(containing: window), isActive(key) else { return } + let changed = focusedWindow != window + focusedWindow = window + activeDisplay = key.display + workspaces[key]?.select(window) + if changed { + if requestingFocus { effects.append(.focusWindow(window)) } + effects.append(.raiseWindow(window)) + effects.append(.announce(.focused(window))) + } + } + + mutating func transfer(_ window: WindowID, to destination: WorkspaceKey) { + guard let source = workspace(containing: window), source != destination else { return } + workspaces[source]?.remove(window) + if workspaces[destination] == nil { workspaces[destination] = Workspace(key: destination) } + workspaces[destination]?.insert( + window, floating: windows[window]?.isFloating == true, + in: displays[destination.display]?.frame ?? Rect(), windows: windows + ) + relocateFloating(window, to: destination.display) + if focusedWindow == window { activeDisplay = destination.display } + } + + mutating func relocateFloating(_ window: WindowID, to display: DisplayID) { + guard windows[window]?.isFloating == true, let previous = frames[window], let screen = displays[display]?.frame + else { return } + frames[window] = Rect( + x: screen.minX + max(0, (screen.size.width - previous.size.width) / 2), + y: screen.minY + max(0, (screen.size.height - previous.size.height) / 2), + width: min(screen.size.width, previous.size.width), + height: min(screen.size.height, previous.size.height) + ).roundedToWholePoints() + } + + func neighbor(of window: WindowID, direction: Direction, tiledOnly: Bool = false) -> WindowID? { + let geometry = layoutFrames().frames.merging(frames) { target, _ in target } + guard let source = geometry[window] else { return nil } + return visibleWindows.filter { $0 != window && (!tiledOnly || windows[$0]?.isFloating == false) } + .compactMap { candidate -> (WindowID, DirectionalDistance)? in + guard let frame = geometry[candidate], let distance = direction.distance(from: source, to: frame) else { + return nil + } + return (candidate, distance) + }.sorted { + $0.1 == $1.1 ? $0.0 < $1.0 : $0.1 < $1.1 + }.first?.0 + } + + func displayNeighbor(from display: DisplayID, direction: Direction) -> DisplayID? { + guard let source = displays[display]?.frame else { return nil } + return displays.keys.filter { $0 != display }.compactMap { candidate -> (DisplayID, DirectionalDistance)? in + guard let frame = displays[candidate]?.frame, let distance = direction.distance(from: source, to: frame) + else { return nil } + return (candidate, distance) + }.sorted { $0.1 == $1.1 ? $0.0 < $1.0 : $0.1 < $1.1 }.first?.0 + } +} diff --git a/Sources/TesseraCore/Replay.swift b/Sources/TesseraCore/Replay.swift new file mode 100644 index 00000000..fe49d8e3 --- /dev/null +++ b/Sources/TesseraCore/Replay.swift @@ -0,0 +1,70 @@ +import Foundation + +public enum EventStreamError: Error, Sendable, Equatable { + case invalidLine(line: Int, reason: String) + case unsupportedVersion(line: Int, version: Int) +} + +public enum EventStream { + public static let schemaVersion = 1 + + private struct Entry: Codable { + let version: Int + let event: Event + } + + private struct Header: Decodable { let version: Int } + + public static func encode(_ events: [Event]) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return try events.map { event in + let data = try encoder.encode(Entry(version: schemaVersion, event: event)) + return String(decoding: data, as: UTF8.self) + "\n" + }.joined() + } + + public static func decode(_ jsonLines: String) throws -> [Event] { + let decoder = JSONDecoder() + var events: [Event] = [] + for (offset, line) in jsonLines.split(separator: "\n", omittingEmptySubsequences: false).enumerated() { + if line.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { continue } + let data = Data(line.utf8) + do { + let header = try decoder.decode(Header.self, from: data) + guard header.version == schemaVersion else { + throw EventStreamError.unsupportedVersion(line: offset + 1, version: header.version) + } + events.append(try decoder.decode(Entry.self, from: data).event) + } catch let error as EventStreamError { + throw error + } catch { + throw EventStreamError.invalidLine(line: offset + 1, reason: String(describing: error)) + } + } + return events + } +} + +public struct ReplayResult: Sendable, Equatable, Codable { + public let state: State + public let effects: [[Effect]] + public var finalFrames: [WindowID: Rect] { state.frames } +} + +public enum Replay { + public static func run(_ events: [Event], initial: State = State()) -> ReplayResult { + var state = initial + var trace: [[Effect]] = [] + for event in events { + let (next, effects) = reduce(state, event) + state = next + trace.append(effects) + } + return ReplayResult(state: state, effects: trace) + } + + public static func run(jsonLines: String, initial: State = State()) throws -> ReplayResult { + run(try EventStream.decode(jsonLines), initial: initial) + } +} diff --git a/Sources/TesseraCore/State.swift b/Sources/TesseraCore/State.swift new file mode 100644 index 00000000..b250d381 --- /dev/null +++ b/Sources/TesseraCore/State.swift @@ -0,0 +1,125 @@ +public struct State: Sendable, Equatable, Codable { + public var windows: [WindowID: ManagedWindow] + public var displays: [DisplayID: Display] + public var activeSpaces: [DisplayID: SpaceID] + public var workspaces: [WorkspaceKey: Workspace] + public var activeDisplay: DisplayID? + public var focusedWindow: WindowID? + public var frames: [WindowID: Rect] + public var observedFrames: [WindowID: Rect] + public var cannotFit: [WindowID] + + public init( + displays: [Display] = [], activeSpaces: [DisplayID: SpaceID] = [:], + workspaces: [WorkspaceKey: Workspace] = [:], windows: [WindowID: ManagedWindow] = [:], + activeDisplay: DisplayID? = nil, focusedWindow: WindowID? = nil, + frames: [WindowID: Rect] = [:], observedFrames: [WindowID: Rect] = [:] + ) { + self.displays = Dictionary(uniqueKeysWithValues: displays.map { ($0.id, $0) }) + self.activeSpaces = activeSpaces + self.workspaces = workspaces + self.windows = windows + self.activeDisplay = activeDisplay ?? displays.first?.id + self.focusedWindow = focusedWindow + self.frames = frames + self.observedFrames = observedFrames + cannotFit = [] + for display in displays { + if let space = activeSpaces[display.id] { + let key = WorkspaceKey(display: display.id, space: space) + if self.workspaces[key] == nil { self.workspaces[key] = Workspace(key: key) } + } + } + } + + public var activeWorkspace: WorkspaceKey? { + guard let display = activeDisplay, let space = activeSpaces[display] else { return nil } + return WorkspaceKey(display: display, space: space) + } + + public func workspace(containing window: WindowID) -> WorkspaceKey? { + workspaces.keys.sorted().first { workspaces[$0]?.order.contains(window) == true } + } + + public func isActive(_ key: WorkspaceKey) -> Bool { + displays[key.display] != nil && activeSpaces[key.display] == key.space + } + + public var visibleWindows: [WindowID] { + workspaces.keys.sorted().filter(isActive).flatMap { key in + guard let workspace = workspaces[key] else { return [WindowID]() } + return workspace.visibleWindows + workspace.order.filter { windows[$0]?.isFloating == true } + } + } +} + +public enum Command: Sendable, Equatable, Codable { + case focus(Direction) + case swap(Direction) + case move(Direction) + case cycleLayout + case setLayout(Layout) + case setRatio(MainRatio) + case nudgeRatio(Double) + case toggleFloat + case retile + case moveToDisplay(Direction) + case stack(Direction) + case unstack + case focusNextInStack + case focusPreviousInStack + case setWindowCap(Int) +} + +public enum Event: Sendable, Equatable, Codable { + case windowAppeared(ManagedWindow, workspace: WorkspaceKey, frame: Rect) + case windowDisappeared(WindowID) + case windowMovedByUser(WindowID, frame: Rect) + case windowResizedByUser(WindowID, frame: Rect) + case focusChanged(WindowID?) + case displaySetChanged([Display]) + case activeSpaceChanged(display: DisplayID, space: SpaceID) + case commandIssued(Command) + case minimumSizeChanged(WindowID, minimum: LearnedMinimumSize?) +} + +public struct WindowFrame: Sendable, Equatable, Codable { + public let window: WindowID + public let frame: Rect + public init(window: WindowID, frame: Rect) { + self.window = window + self.frame = frame + } +} + +// The UI turns these semantic messages into localized strings from its catalog. +public enum Announcement: Sendable, Equatable, Codable { + case focused(WindowID) + case layoutChanged(Layout) + case ratioChanged(MainRatio) + case floatingChanged(WindowID, isFloating: Bool) + case stackChanged(window: WindowID, count: Int) + case movedToDisplay(WindowID, DisplayID) +} + +public enum Report: Sendable, Equatable, Codable { + case retiled(moved: Int) + case cannotFit([WindowID]) + case unknownWindow(WindowID) + case unavailableDisplay(DisplayID) + case noActiveWorkspace + case noFocusedWindow + case noNeighbor(Direction) + case atWindowCap(Int) + case invalidGeometry + case invalidRatio + case unsupportedMinimumVersion(Int) +} + +public enum Effect: Sendable, Equatable, Codable { + case setFrames([WindowFrame]) + case focusWindow(WindowID) + case raiseWindow(WindowID) + case announce(Announcement) + case report(Report) +} diff --git a/Sources/TesseraCore/TesseraCore.docc/TesseraCore.md b/Sources/TesseraCore/TesseraCore.docc/TesseraCore.md new file mode 100644 index 00000000..f08f0d5f --- /dev/null +++ b/Sources/TesseraCore/TesseraCore.docc/TesseraCore.md @@ -0,0 +1,52 @@ +# TesseraCore + +The model is a value snapshot. It has no window access, timers, or file access. +Feed observations and commands into `reduce(_:_:)`, store the returned `State`, +and let the engine execute its `Effect` values. + +## Integration + +- `WindowID` is a window number; `AppID` contains a PID and bundle identifier. + Pass stable UUID strings into `DisplayID` and native identifiers into `SpaceID`. +- `WorkspaceKey` pairs a display and Space. Each workspace remembers its layout, + ratio, gaps, reserved edges, tile tree, order, and focus independently. +- `ManagedWindow.minimum` is versioned learned data. Send `minimumSizeChanged` + with `nil` to reset it. Unsupported versions produce a report, not a fallback. +- `Effect.setFrames` contains changed targets in window-number order, including + hidden stack members. The engine should apply frames before raises and focus. + `Announcement` and `Report` are semantic values: the UI supplies their short + localized messages through its String Catalog. +- `EventStream` encodes and decodes versioned JSON lines in memory. `Replay.run` + returns the final snapshot, cached frames, and an effect trace. The caller owns + reading and writing files. Frame caches include dormant Spaces and floating + windows, not just the active tiles. + +## Layout behavior + +Coordinates use a top-left global origin, including negative display origins. +`Rect.roundedToWholePoints()` rounds shared edges rather than individual widths; +layout leaves and programmatic floating relocation use that one rounding policy. +Minimum sizes reserve whole-point extents. If constraints conflict, tiles stay +on-screen and `cannotFit` identifies each window below its learned minimum. + +Balanced grids use square-ish rows; a partial final row fills the available width. +Side layout keeps a main tile beside a vertical stack. Ratios clamp to 0.2–0.8. +Reserved edges apply before outer gaps. The cap limits tiles, not managed windows: +overflow joins the newest tile, and its latest member becomes visible. + +Arrivals split the newest tile in half: horizontally for columns, vertically for +rows, and along its longest dimension for grid. Side first divides the main and +secondary areas, then splits the newest secondary tile vertically. Existing +splits survive removals and directional moves. Retile and layout changes restore +a balanced arrangement while keeping explicit stacks intact. Raising the cap +allows later insertion or unstacking; it does not dissolve existing stacks. + +A floating user move or resize is recorded without rounding or a corrective write. +A tiled user move or resize snaps back without changing order. Duplicate arrivals +update metadata without stealing focus. Inactive Spaces do not receive frame +writes; observations there are reconciled when they become active again. + +Disconnect migration moves only the removed display's active Space windows to +an available active workspace. It waits if the replacement Space is not known, +centers floating windows, and preserves the selected stack member. Dormant native +Spaces stay stored under their original key; they are not silently reassigned. diff --git a/Tests/TesseraCoreTests/CommandTests.swift b/Tests/TesseraCoreTests/CommandTests.swift new file mode 100644 index 00000000..8bd09b7e --- /dev/null +++ b/Tests/TesseraCoreTests/CommandTests.swift @@ -0,0 +1,290 @@ +import Testing + +@testable import TesseraCore + +@Test(arguments: Direction.allCases, Layout.allCases) +func focusUsesGeometryInEveryLayout(direction: Direction, layout: Layout) { + let state = focused(4, in: populated(8, layout: layout)) + let number: Int? + switch (layout, direction) { + case (.columns, .left): number = 3 + case (.columns, .right): number = 5 + case (.rows, .up), (.side, .up): number = 3 + case (.rows, .down), (.side, .down): number = 5 + case (.side, .left), (.grid, .up): number = 1 + case (.grid, .right): number = 5 + case (.grid, .down): number = 7 + default: number = nil + } + let expected = number.map(windowID) + let result = command(.focus(direction), in: state) + if let expected { + #expect(result.0.focusedWindow == expected) + #expect(result.1.contains(.focusWindow(expected))) + } else { + #expect(result.1 == [.report(.noNeighbor(direction))]) + } + #expect(frameWrites(result.1).isEmpty) +} + +@Test func focusLeftPixels() { + let result = command(.focus(.left), in: focused(2, in: populated(4, layout: .grid))) + #expect(result.0.focusedWindow == windowID(1)) +} + +@Test func focusRightPixels() { + let result = command(.focus(.right), in: focused(1, in: populated(4, layout: .grid))) + #expect(result.0.focusedWindow == windowID(2)) +} + +@Test func focusUpPixels() { + let result = command(.focus(.up), in: focused(3, in: populated(4, layout: .grid))) + #expect(result.0.focusedWindow == windowID(1)) +} + +@Test func focusDownPixels() { + let result = command(.focus(.down), in: focused(1, in: populated(4, layout: .grid))) + #expect(result.0.focusedWindow == windowID(3)) +} + +@Test func focusDoesNotWrapAtEdge() { + let state = focused(1, in: populated(4, layout: .grid)) + let result = command(.focus(.left), in: state) + #expect(result.0 == state) + #expect(result.1 == [.report(.noNeighbor(.left))]) +} + +@Test func focusCanReachFloatingWindow() { + let state = focused(1, in: populated(1)) + let floating = reduce( + state, + .windowAppeared( + managed(2, floating: true), workspace: primaryKey, frame: Rect(x: 1100, width: 100, height: 100)) + ).0 + let result = command(.focus(.right), in: focused(1, in: floating)) + #expect(result.0.focusedWindow == windowID(2)) +} + +@Test(arguments: [Direction.left, .right, .up, .down]) +func swapExchangesOnlyTwoWindowPositions(direction: Direction) { + let number = direction == .left ? 2 : (direction == .up ? 3 : 1) + let state = focused(number, in: populated(4, layout: .grid)) + let target = state.neighbor(of: windowID(number), direction: direction) + let result = command(.swap(direction), in: state) + if let target { + #expect(result.0.frames[windowID(number)] == state.frames[target]) + #expect(result.0.frames[target] == state.frames[windowID(number)]) + #expect(frameWrites(result.1).count == 2) + } + #expect(result.0.focusedWindow == windowID(number)) +} + +@Test func swapAtEdgeReportsNoNeighbor() { + let state = focused(1, in: populated()) + let result = command(.swap(.left), in: state) + #expect(result.0 == state) + #expect(result.1 == [.report(.noNeighbor(.left))]) +} + +@Test func swapExchangesVisibleMembersNotWholeStacks() { + let state = focused(1, in: populated(4, cap: 2)) + let result = command(.swap(.right), in: state) + #expect(result.0.workspaces[primaryKey]?.tree?.stacks[0].windows == [windowID(4)]) + #expect(result.0.workspaces[primaryKey]?.tree?.stacks[1].windows == [windowID(2), windowID(3), windowID(1)]) + #expect(result.0.focusedWindow == windowID(1)) +} + +@Test(arguments: Direction.allCases, Layout.allCases) +func movePreservesMembershipAndFocus(direction: Direction, layout: Layout) { + let state = focused(4, in: populated(8, layout: layout)) + let result = command(.move(direction), in: state) + #expect(Set(result.0.workspaces[primaryKey]?.order ?? []) == Set((1...8).map(windowID))) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 8) + #expect(result.0.focusedWindow == windowID(4)) + for frame in result.0.frames.values { + #expect(frame.minX >= 0 && frame.maxX <= 1200) + #expect(frame.minY >= 0 && frame.maxY <= 800) + } +} + +@Test func moveUpSplitsNeighborAboveIt() { + let result = command(.move(.up), in: focused(3, in: populated(4, layout: .grid))) + #expect(result.0.frames[windowID(3)] == Rect(width: 600, height: 200)) + #expect(result.0.frames[windowID(1)] == Rect(y: 200, width: 600, height: 200)) + #expect(result.0.workspaces[primaryKey]?.order == [windowID(3), windowID(1), windowID(2), windowID(4)]) +} + +@Test func moveAtEdgeDoesNotChangeOrder() { + let state = focused(1, in: populated()) + let result = command(.move(.left), in: state) + #expect(result.0 == state) + #expect(result.1 == [.report(.noNeighbor(.left))]) +} + +@Test func cycleLayoutFollowsStableOrder() { + var state = populated(3, layout: .grid) + for layout in [Layout.columns, .rows, .side, .grid] { + let result = command(.cycleLayout, in: state) + #expect(result.0.workspaces[primaryKey]?.layout == layout) + #expect(result.1.contains(.announce(.layoutChanged(layout)))) + state = result.0 + } +} + +@Test(arguments: Layout.allCases) +func setLayoutBalancesWithoutChangingMembership(layout: Layout) { + let result = command(.setLayout(layout), in: focused(2, in: populated(4))) + #expect(result.0.workspaces[primaryKey]?.layout == layout) + #expect(result.0.workspaces[primaryKey]?.order == (1...4).map(windowID)) + #expect(result.0.focusedWindow == windowID(2)) + #expect(result.1.contains(.announce(.layoutChanged(layout)))) +} + +@Test func setRatioUpdatesSideFrames() { + let result = command(.setRatio(.threeFifths), in: populated(2, layout: .side)) + #expect(result.0.frames[windowID(1)] == Rect(width: 720, height: 800)) + #expect(result.0.frames[windowID(2)] == Rect(x: 720, width: 480, height: 800)) + #expect(result.1.contains(.announce(.ratioChanged(.threeFifths)))) +} + +@Test func ratioStoredOutsideSideWithoutFrameWrites() { + let result = command(.setRatio(.twoThirds), in: populated()) + #expect(result.0.workspaces[primaryKey]?.ratio == .twoThirds) + #expect(frameWrites(result.1).isEmpty) + let side = command(.setLayout(.side), in: result.0) + #expect(side.0.frames[windowID(1)]?.size.width == 800) +} + +@Test func nudgeRatioMovesDivider() { + let result = command(.nudgeRatio(0.1), in: populated(2, layout: .side)) + #expect(result.0.workspaces[primaryKey]?.ratio == .threeFifths) + #expect(result.0.frames[windowID(1)]?.size.width == 720) +} + +@Test func nudgeRatioClampsBothBounds() { + let state = populated(2, layout: .side) + #expect(command(.nudgeRatio(10), in: state).0.workspaces[primaryKey]?.ratio.value == 0.8) + #expect(command(.nudgeRatio(-10), in: state).0.workspaces[primaryKey]?.ratio.value == 0.2) +} + +@Test func nonFiniteNudgeIsReported() { + let state = populated() + let result = command(.nudgeRatio(.nan), in: state) + #expect(result.0 == state) + #expect(result.1 == [.report(.invalidRatio)]) +} + +@Test func toggleFloatRemovesTileButRetainsMembership() { + let result = command(.toggleFloat, in: focused(2, in: populated())) + #expect(result.0.windows[windowID(2)]?.isFloating == true) + #expect(result.0.workspaces[primaryKey]?.order == (1...3).map(windowID)) + #expect(result.0.workspaces[primaryKey]?.tree?.windows == [windowID(1), windowID(3)]) + #expect(result.0.frames[windowID(2)] == Rect(x: 400, width: 400, height: 800)) + #expect(result.1.contains(.announce(.floatingChanged(windowID(2), isFloating: true)))) +} + +@Test func toggleFloatBackSplitsNewestTile() { + let floating = command(.toggleFloat, in: focused(2, in: populated())).0 + let result = command(.toggleFloat, in: floating) + #expect(result.0.windows[windowID(2)]?.isFloating == false) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 3) + #expect(result.0.frames[windowID(2)] == Rect(x: 800, width: 400, height: 800)) +} + +@Test func retileBalancesIncrementalSplitsAndReportsCount() { + var state = populated(0) + for number in 1...3 { + state = + reduce(state, .windowAppeared(managed(number), workspace: primaryKey, frame: Rect(width: 100, height: 100))) + .0 + } + let result = command(.retile, in: state) + #expect(result.0.frames[windowID(1)] == Rect(width: 400, height: 800)) + #expect(result.1.contains(.report(.retiled(moved: 3)))) +} + +@Test func noOpRetileReportsZeroAndDoesNotWrite() { + let result = command(.retile, in: populated()) + #expect(result.1 == [.report(.retiled(moved: 0))]) +} + +@Test func stackJoinsDirectionalNeighborAndMakesFocusVisible() { + let result = command(.stack(.right), in: focused(1, in: populated())) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 2) + #expect(result.0.frames[windowID(1)] == result.0.frames[windowID(2)]) + #expect(result.0.visibleWindows.contains(windowID(1))) + #expect(!result.0.visibleWindows.contains(windowID(2))) + #expect(result.1.contains(.announce(.stackChanged(window: windowID(1), count: 2)))) +} + +@Test func unstackCreatesNewTileWhenCapacityAllows() { + let stacked = command(.stack(.right), in: focused(1, in: populated())).0 + let result = command(.unstack, in: stacked) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 3) + #expect(result.0.focusedWindow == windowID(1)) + #expect(result.1.contains(.announce(.stackChanged(window: windowID(1), count: 1)))) +} + +@Test func unstackAtCapReportsInsteadOfLosingWindow() { + let state = focused(3, in: populated(3, cap: 2)) + let result = command(.unstack, in: state) + #expect(result.0 == state) + #expect(result.1 == [.report(.atWindowCap(2))]) +} + +@Test func unstackSingletonIsNoOp() { + let state = focused(2, in: populated()) + let result = command(.unstack, in: state) + #expect(result.0 == state) + #expect(result.1.isEmpty) +} + +@Test func focusNextInStackCyclesAndWraps() { + var state = focused(2, in: populated(4, cap: 2)) + for number in [3, 4, 2] { + let result = command(.focusNextInStack, in: state) + #expect(result.0.focusedWindow == windowID(number)) + #expect(result.1.contains(.focusWindow(windowID(number)))) + #expect(frameWrites(result.1).isEmpty) + state = result.0 + } +} + +@Test func focusPreviousInStackCyclesAndWraps() { + var state = focused(2, in: populated(4, cap: 2)) + for number in [4, 3, 2] { + state = command(.focusPreviousInStack, in: state).0 + #expect(state.focusedWindow == windowID(number)) + } +} + +@Test func stackCycleSingletonIsNoOp() { + let state = focused(2, in: populated()) + #expect(command(.focusNextInStack, in: state).1.isEmpty) + #expect(command(.focusPreviousInStack, in: state).1.isEmpty) +} + +@Test func lowerCapMergesTilesAndPreservesFocus() { + let result = command(.setWindowCap(2), in: focused(2, in: populated(5))) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 2) + #expect(result.0.workspaces[primaryKey]?.order == (1...5).map(windowID)) + #expect(result.0.visibleWindows == [windowID(1), windowID(2)]) +} + +@Test func raiseCapLeavesStacksIntact() { + let result = command(.setWindowCap(5), in: focused(3, in: populated(3, cap: 2))) + #expect(result.0.workspaces[primaryKey]?.windowCap == 5) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 2) + #expect(command(.unstack, in: result.0).0.workspaces[primaryKey]?.tree?.tileCount == 3) +} + +@Test func commandsWithoutFocusReportProblem() { + let state = populated() + let result = command(.toggleFloat, in: state) + #expect(result.0 == state) + #expect(result.1 == [.report(.noFocusedWindow)]) +} + +@Test func commandsWithoutWorkspaceReportProblem() { + #expect(command(.cycleLayout, in: State()).1 == [.report(.noActiveWorkspace)]) +} diff --git a/Tests/TesseraCoreTests/DisplaySpaceTests.swift b/Tests/TesseraCoreTests/DisplaySpaceTests.swift new file mode 100644 index 00000000..00eb3001 --- /dev/null +++ b/Tests/TesseraCoreTests/DisplaySpaceTests.swift @@ -0,0 +1,257 @@ +import Testing + +@testable import TesseraCore + +let secondaryDisplay = DisplayID(rawValue: "00000000-0000-0000-0000-000000000002") +let secondarySpace = SpaceID(rawValue: 2) +let secondaryKey = WorkspaceKey(display: secondaryDisplay, space: secondarySpace) + +func multipleDisplays(_ direction: Direction = .right, destinationCap: Int = 8) -> State { + let frame: Rect + switch direction { + case .left: frame = Rect(x: -1200, width: 1200, height: 800) + case .right: frame = Rect(x: 1200, width: 1200, height: 800) + case .up: frame = Rect(y: -800, width: 1200, height: 800) + case .down: frame = Rect(y: 800, width: 1200, height: 800) + } + let other = Workspace( + key: secondaryKey, layout: .columns, windowCap: destinationCap, order: [windowID(3), windowID(4)]) + let state = State( + displays: [Display(id: primaryDisplay, frame: testScreen), Display(id: secondaryDisplay, frame: frame)], + activeSpaces: [primaryDisplay: primarySpace, secondaryDisplay: secondarySpace], + workspaces: [primaryKey: workspace(2, layout: .columns), secondaryKey: other], + windows: Dictionary(uniqueKeysWithValues: (1...4).map { (windowID($0), managed($0)) }) + ) + return focused(1, in: command(.retile, in: state).0) +} + +@Test(arguments: Direction.allCases) +func focusCrossesDisplaysByGeometry(direction: Direction) { + let state = focused(direction == .right ? 2 : 1, in: multipleDisplays(direction)) + let result = command(.focus(direction), in: state) + #expect(result.0.focusedWindow == (direction == .left ? windowID(4) : windowID(3))) + #expect(result.0.activeDisplay == secondaryDisplay) + #expect(frameWrites(result.1).isEmpty) +} + +@Test(arguments: Direction.allCases) +func moveToDisplayUsesGlobalGeometry(direction: Direction) { + let state = multipleDisplays(direction) + let result = command(.moveToDisplay(direction), in: state) + #expect(result.0.workspace(containing: windowID(1)) == secondaryKey) + #expect(result.0.workspaces[primaryKey]?.order == [windowID(2)]) + #expect(result.0.workspaces[secondaryKey]?.order == [windowID(3), windowID(4), windowID(1)]) + #expect(result.0.focusedWindow == windowID(1)) + #expect(result.0.activeDisplay == secondaryDisplay) + #expect(result.1.contains(.announce(.movedToDisplay(windowID(1), secondaryDisplay)))) + if let frame = result.0.frames[windowID(1)], let screen = result.0.displays[secondaryDisplay]?.frame { + #expect(frame.minX >= screen.minX && frame.maxX <= screen.maxX) + #expect(frame.minY >= screen.minY && frame.maxY <= screen.maxY) + } +} + +@Test func moveToFullDisplayStacksWithoutChangingSettings() { + let state = multipleDisplays(destinationCap: 2) + let result = command(.moveToDisplay(.right), in: state) + #expect(result.0.workspaces[secondaryKey]?.tree?.tileCount == 2) + #expect(result.0.frames[windowID(1)] == result.0.frames[windowID(4)]) + #expect(result.0.workspaces[secondaryKey]?.layout == .columns) + #expect(result.0.workspaces[secondaryKey]?.windowCap == 2) +} + +@Test func moveToMissingDisplayReportsNoNeighbor() { + let state = focused(1, in: populated()) + let result = command(.moveToDisplay(.right), in: state) + #expect(result.0 == state) + #expect(result.1 == [.report(.noNeighbor(.right))]) +} + +@Test func swapAcrossDisplaysKeepsEachTileCount() { + let state = focused(2, in: multipleDisplays()) + let result = command(.swap(.right), in: state) + #expect(result.0.workspace(containing: windowID(2)) == secondaryKey) + #expect(result.0.workspace(containing: windowID(3)) == primaryKey) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 2) + #expect(result.0.workspaces[secondaryKey]?.tree?.tileCount == 2) + #expect(result.0.frames[windowID(2)] == state.frames[windowID(3)]) + #expect(result.0.frames[windowID(3)] == state.frames[windowID(2)]) +} + +@Test func moveAcrossDisplaysSplitsDirectionalTarget() { + let state = focused(2, in: multipleDisplays()) + let result = command(.move(.right), in: state) + #expect(result.0.workspace(containing: windowID(2)) == secondaryKey) + #expect(result.0.frames[windowID(2)] == Rect(x: 1500, width: 300, height: 800)) + #expect(result.0.frames[windowID(3)] == Rect(x: 1200, width: 300, height: 800)) +} + +@Test func stackAcrossDisplaysJoinsTargetTile() { + let result = command(.stack(.right), in: focused(2, in: multipleDisplays())) + #expect(result.0.workspace(containing: windowID(2)) == secondaryKey) + #expect(result.0.frames[windowID(2)] == result.0.frames[windowID(3)]) + #expect(result.0.workspaces[secondaryKey]?.tree?.tileCount == 2) +} + +@Test func floatingMoveToDisplayCentersAndWritesOnce() { + let floated = command(.toggleFloat, in: multipleDisplays()).0 + let state = reduce(floated, .windowResizedByUser(windowID(1), frame: Rect(width: 300, height: 200))).0 + let result = command(.moveToDisplay(.right), in: state) + #expect(result.0.frames[windowID(1)] == Rect(x: 1650, y: 300, width: 300, height: 200)) + #expect(frameWrites(result.1).filter { $0.window == windowID(1) }.count == 1) + #expect(result.0.windows[windowID(1)]?.isFloating == true) +} + +@Test func workspacesKeepIndependentLayoutsAndRatios() { + let state = multipleDisplays() + let first = command(.setLayout(.side), in: state).0 + let ratio = command(.setRatio(.threeFifths), in: first).0 + let second = command(.setLayout(.rows), in: focused(3, in: ratio)).0 + #expect(second.workspaces[primaryKey]?.layout == .side) + #expect(second.workspaces[primaryKey]?.ratio == .threeFifths) + #expect(second.workspaces[secondaryKey]?.layout == .rows) + #expect(second.workspaces[secondaryKey]?.ratio == .half) +} + +@Test func spaceSwitchRetainsOldWorkspaceAndCreatesNewOne() { + let state = focused(2, in: populated()) + let result = reduce(state, .activeSpaceChanged(display: primaryDisplay, space: secondarySpace)) + let key = WorkspaceKey(display: primaryDisplay, space: secondarySpace) + #expect(result.0.workspaces[primaryKey] == state.workspaces[primaryKey]) + #expect(result.0.workspaces[key]?.order.isEmpty == true) + #expect(result.0.focusedWindow == nil) + #expect(result.0.visibleWindows.isEmpty) + #expect(frameWrites(result.1).isEmpty) +} + +@Test func returningToSpaceRestoresFocusAndSettings() { + let initial = command(.setRatio(.twoThirds), in: focused(2, in: populated())).0 + let away = reduce(initial, .activeSpaceChanged(display: primaryDisplay, space: secondarySpace)).0 + let result = reduce(away, .activeSpaceChanged(display: primaryDisplay, space: primarySpace)) + #expect(result.0.workspaces[primaryKey] == initial.workspaces[primaryKey]) + #expect(result.0.focusedWindow == windowID(2)) + #expect(result.1.contains(.focusWindow(windowID(2)))) + #expect(frameWrites(result.1).isEmpty) +} + +@Test func inactiveSpaceAppearanceDoesNotWriteOrFocus() { + let state = populated() + let key = WorkspaceKey(display: primaryDisplay, space: secondarySpace) + let result = reduce(state, .windowAppeared(managed(4), workspace: key, frame: Rect(width: 100, height: 100))) + #expect(result.0.focusedWindow == state.focusedWindow) + #expect(result.0.workspaces[key]?.order == [windowID(4)]) + #expect(result.1.isEmpty) +} + +@Test func activatingPopulatedSpaceWritesItsFrames() { + let key = WorkspaceKey(display: primaryDisplay, space: secondarySpace) + let state = reduce(populated(), .windowAppeared(managed(4), workspace: key, frame: Rect(width: 100, height: 100))).0 + let result = reduce(state, .activeSpaceChanged(display: primaryDisplay, space: secondarySpace)) + #expect(frameWrites(result.1) == [WindowFrame(window: windowID(4), frame: testScreen)]) + #expect(result.0.focusedWindow == windowID(4)) + #expect(result.0.visibleWindows == [windowID(4)]) +} + +@Test func inactiveSpaceFocusNotificationIsIgnored() { + let initial = focused(2, in: populated()) + let state = reduce(initial, .activeSpaceChanged(display: primaryDisplay, space: secondarySpace)).0 + let result = reduce(state, .focusChanged(windowID(1))) + #expect(result.0 == state) + #expect(result.1.isEmpty) +} + +@Test func spaceChangeOnOtherDisplayDoesNotStealFocus() { + let state = multipleDisplays() + let result = reduce(state, .activeSpaceChanged(display: secondaryDisplay, space: SpaceID(rawValue: 3))) + #expect(result.0.focusedWindow == state.focusedWindow) + #expect(result.0.activeDisplay == primaryDisplay) +} + +@Test func missingDisplaySpaceChangeIsReported() { + let state = populated() + let result = reduce(state, .activeSpaceChanged(display: secondaryDisplay, space: secondarySpace)) + #expect(result.0 == state) + #expect(result.1 == [.report(.unavailableDisplay(secondaryDisplay))]) +} + +@Test func unchangedDisplaySetDoesNotWrite() { + let state = multipleDisplays() + let result = reduce( + state, + .displaySetChanged([ + Display(id: primaryDisplay, frame: testScreen), + state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect()), + ])) + #expect(result.0 == state) + #expect(result.1.isEmpty) +} + +@Test func displayResizeDiffsOnlyAffectedDisplay() { + let state = multipleDisplays() + let result = reduce( + state, + .displaySetChanged([ + Display(id: primaryDisplay, frame: Rect(width: 1000, height: 800)), + state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect()), + ])) + #expect(frameWrites(result.1).map(\.window) == [windowID(1), windowID(2)]) + #expect(result.0.frames[windowID(3)] == state.frames[windowID(3)]) +} + +@Test func displayDisconnectMigratesActiveWindowsAndRetainsSettings() { + let state = multipleDisplays() + let result = reduce( + state, .displaySetChanged([state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect())])) + #expect(result.0.workspace(containing: windowID(1)) == secondaryKey) + #expect(result.0.workspace(containing: windowID(2)) == secondaryKey) + #expect(result.0.workspaces[primaryKey]?.order.isEmpty == true) + #expect(result.0.workspaces[primaryKey]?.layout == .columns) + #expect(result.0.focusedWindow == windowID(1)) +} + +@Test func reconnectRestoresEmptyWorkspaceSettings() { + let state = command(.setLayout(.side), in: multipleDisplays()).0 + let disconnected = reduce( + state, .displaySetChanged([state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect())]) + ).0 + let result = reduce( + disconnected, + .displaySetChanged([ + Display(id: primaryDisplay, frame: testScreen), + state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect()), + ])) + #expect(result.0.workspaces[primaryKey]?.layout == .side) + #expect(result.0.workspaces[primaryKey]?.order.isEmpty == true) +} + +@Test func noDisplaysRetainsWindowsWithoutFrameWrites() { + let state = populated() + let result = reduce(state, .displaySetChanged([])) + #expect(result.0.windows == state.windows) + #expect(result.0.frames == state.frames) + #expect(result.0.workspaces == state.workspaces) + #expect(result.0.focusedWindow == nil) + #expect(result.1.isEmpty) +} + +@Test func duplicateDisplayIDsAreRejected() { + let state = populated() + let display = Display(id: primaryDisplay, frame: testScreen) + let result = reduce(state, .displaySetChanged([display, display])) + #expect(result.0 == state) + #expect(result.1 == [.report(.invalidGeometry)]) +} + +@Test func invalidDisplayGeometryIsRejected() { + let result = reduce( + populated(), .displaySetChanged([Display(id: primaryDisplay, frame: Rect(x: .nan, width: 10, height: 10))])) + #expect(result.1 == [.report(.invalidGeometry)]) +} + +@Test func reappearingWindowOnDifferentWorkspaceTransfersMembership() { + let state = multipleDisplays() + let result = reduce( + state, .windowAppeared(managed(1), workspace: secondaryKey, frame: Rect(x: 1200, width: 300, height: 300))) + #expect(result.0.workspace(containing: windowID(1)) == secondaryKey) + #expect(result.0.workspaces[primaryKey]?.order == [windowID(2)]) + #expect(result.0.workspaces[secondaryKey]?.order.filter { $0 == windowID(1) }.count == 1) +} diff --git a/Tests/TesseraCoreTests/Fixtures/displays-frames.json b/Tests/TesseraCoreTests/Fixtures/displays-frames.json new file mode 100644 index 00000000..81de35e7 --- /dev/null +++ b/Tests/TesseraCoreTests/Fixtures/displays-frames.json @@ -0,0 +1,5 @@ +[ + {"window": 1, "frame": {"origin": {"xCoordinate": 1200, "yCoordinate": 400}, "size": {"width": 1200, "height": 400}}}, + {"window": 2, "frame": {"origin": {"xCoordinate": 0, "yCoordinate": 0}, "size": {"width": 1200, "height": 800}}}, + {"window": 3, "frame": {"origin": {"xCoordinate": 1200, "yCoordinate": 0}, "size": {"width": 1200, "height": 400}}} +] diff --git a/Tests/TesseraCoreTests/Fixtures/displays.jsonl b/Tests/TesseraCoreTests/Fixtures/displays.jsonl new file mode 100644 index 00000000..369a9ab0 --- /dev/null +++ b/Tests/TesseraCoreTests/Fixtures/displays.jsonl @@ -0,0 +1,10 @@ +{"event":{"displaySetChanged":{"_0":[{"frame":{"origin":{"xCoordinate":0,"yCoordinate":0},"size":{"height":800,"width":1200}},"id":"00000000-0000-0000-0000-000000000001"},{"frame":{"origin":{"xCoordinate":1200,"yCoordinate":0},"size":{"height":800,"width":1200}},"id":"00000000-0000-0000-0000-000000000002"}]}},"version":1} +{"event":{"activeSpaceChanged":{"display":"00000000-0000-0000-0000-000000000001","space":1}},"version":1} +{"event":{"activeSpaceChanged":{"display":"00000000-0000-0000-0000-000000000002","space":2}},"version":1} +{"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":1,"isFloating":false,"role":"AXWindow","title":"Window 1"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000001","space":1}}},"version":1} +{"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":2,"isFloating":false,"role":"AXWindow","title":"Window 2"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000001","space":1}}},"version":1} +{"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":3,"isFloating":false,"role":"AXWindow","title":"Window 3"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000002","space":2}}},"version":1} +{"event":{"focusChanged":{"_0":1}},"version":1} +{"event":{"commandIssued":{"_0":{"setWindowCap":{"_0":1}}}},"version":1} +{"event":{"commandIssued":{"_0":{"moveToDisplay":{"_0":"right"}}}},"version":1} +{"event":{"commandIssued":{"_0":{"setLayout":{"_0":"rows"}}}},"version":1} diff --git a/Tests/TesseraCoreTests/Fixtures/side-frames.json b/Tests/TesseraCoreTests/Fixtures/side-frames.json new file mode 100644 index 00000000..e4c0d21d --- /dev/null +++ b/Tests/TesseraCoreTests/Fixtures/side-frames.json @@ -0,0 +1,5 @@ +[ + {"window": 1, "frame": {"origin": {"xCoordinate": 0, "yCoordinate": 0}, "size": {"width": 720, "height": 800}}}, + {"window": 2, "frame": {"origin": {"xCoordinate": 720, "yCoordinate": 0}, "size": {"width": 480, "height": 400}}}, + {"window": 3, "frame": {"origin": {"xCoordinate": 720, "yCoordinate": 400}, "size": {"width": 480, "height": 400}}} +] diff --git a/Tests/TesseraCoreTests/Fixtures/side.jsonl b/Tests/TesseraCoreTests/Fixtures/side.jsonl new file mode 100644 index 00000000..ee81d65f --- /dev/null +++ b/Tests/TesseraCoreTests/Fixtures/side.jsonl @@ -0,0 +1,8 @@ +{"event":{"displaySetChanged":{"_0":[{"frame":{"origin":{"xCoordinate":0,"yCoordinate":0},"size":{"height":800,"width":1200}},"id":"00000000-0000-0000-0000-000000000001"}]}},"version":1} +{"event":{"activeSpaceChanged":{"display":"00000000-0000-0000-0000-000000000001","space":1}},"version":1} +{"event":{"commandIssued":{"_0":{"setLayout":{"_0":"side"}}}},"version":1} +{"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":1,"isFloating":false,"role":"AXWindow","title":"Window 1"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000001","space":1}}},"version":1} +{"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":2,"isFloating":false,"role":"AXWindow","title":"Window 2"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000001","space":1}}},"version":1} +{"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":3,"isFloating":false,"role":"AXWindow","title":"Window 3"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000001","space":1}}},"version":1} +{"event":{"commandIssued":{"_0":{"setRatio":{"_0":0.6}}}},"version":1} +{"event":{"windowResizedByUser":{"_0":1,"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}}}},"version":1} diff --git a/Tests/TesseraCoreTests/LayoutPixelTests.swift b/Tests/TesseraCoreTests/LayoutPixelTests.swift new file mode 100644 index 00000000..9f7767e2 --- /dev/null +++ b/Tests/TesseraCoreTests/LayoutPixelTests.swift @@ -0,0 +1,80 @@ +import Testing + +@testable import TesseraCore + +private func interval(origin: Double, extent: Double, gap: Double, count: Int, index: Int) -> (Double, Double) { + let length = (extent - gap * Double(count - 1)) / Double(count) + let start = origin + Double(index) * (length + gap) + return (start, start + length) +} + +private func expectedFrame(layout: Layout, count: Int, index: Int, area: Rect, gap: Double, ratio: Double) -> Rect { + var horizontal = (area.minX, area.maxX) + var vertical = (area.minY, area.maxY) + switch layout { + case .columns: + horizontal = interval(origin: area.minX, extent: area.size.width, gap: gap, count: count, index: index) + case .rows: + vertical = interval(origin: area.minY, extent: area.size.height, gap: gap, count: count, index: index) + case .side: + if count > 1 { + let main = (area.size.width - gap) * ratio + if index == 0 { + horizontal = (area.minX, area.minX + main) + } else { + horizontal = (area.minX + main + gap, area.maxX) + vertical = interval( + origin: area.minY, extent: area.size.height, gap: gap, count: count - 1, index: index - 1) + } + } + case .grid: + let columns = Int(Double(count).squareRoot().rounded(.up)) + let rows = (count + columns - 1) / columns + let row = index / columns + let rowCount = min(columns, count - row * columns) + horizontal = interval( + origin: area.minX, extent: area.size.width, gap: gap, count: rowCount, index: index % columns) + vertical = interval(origin: area.minY, extent: area.size.height, gap: gap, count: rows, index: row) + } + let left = horizontal.0.rounded() + let top = vertical.0.rounded() + return Rect(x: left, y: top, width: horizontal.1.rounded() - left, height: vertical.1.rounded() - top) +} + +@Test(arguments: Layout.allCases, 1...8) +func exactPixelsWithGapsAndReservedEdges(layout: Layout, count: Int) { + var space = workspace(count, layout: layout, gaps: Gaps(inner: 12, outer: Insets(8))) + space.reservedEdges = Insets(top: 24, left: 10, bottom: 6, right: 20) + let result = LayoutEngine.arrange(space, in: Rect(x: -1200, y: -800, width: 1200, height: 800)) + let area = Rect(x: -1182, y: -768, width: 1154, height: 754) + for index in 0.. State { + let space = workspace(count, layout: layout, cap: cap) + let windows = Dictionary( + uniqueKeysWithValues: (1...max(1, count)).prefix(count).map { (windowID($0), managed($0)) }) + let state = State( + displays: [Display(id: primaryDisplay, frame: testScreen)], activeSpaces: [primaryDisplay: primarySpace], + workspaces: [primaryKey: space], windows: windows + ) + return reduce(state, .commandIssued(.retile)).0 +} + +func focused(_ number: Int, in state: State) -> State { reduce(state, .focusChanged(windowID(number))).0 } +func command(_ command: Command, in state: State) -> (State, [Effect]) { reduce(state, .commandIssued(command)) } +func frameWrites(_ effects: [Effect]) -> [WindowFrame] { + effects.flatMap { effect in + if case .setFrames(let writes) = effect { return writes } + return [] + } +} + +@Test func appearedWindowGetsFrameAndFocus() { + let state = populated(0) + let result = reduce(state, .windowAppeared(managed(1), workspace: primaryKey, frame: Rect(width: 100, height: 100))) + #expect(result.0.frames[windowID(1)] == testScreen) + #expect(result.0.focusedWindow == windowID(1)) + #expect(result.1.contains(.focusWindow(windowID(1)))) + #expect(result.1.contains(.raiseWindow(windowID(1)))) + #expect(result.1.contains(.announce(.focused(windowID(1))))) + #expect(frameWrites(result.1) == [WindowFrame(window: windowID(1), frame: testScreen)]) +} + +@Test func appearanceAlreadyAtTargetDoesNotWrite() { + let result = reduce(populated(0), .windowAppeared(managed(1), workspace: primaryKey, frame: testScreen)) + #expect(frameWrites(result.1).isEmpty) + #expect(result.0.frames[windowID(1)] == testScreen) +} + +@Test func duplicateAppearanceKeepsTileAndOrder() { + let state = focused(3, in: populated()) + let result = reduce( + state, .windowAppeared(managed(3), workspace: primaryKey, frame: state.frames[windowID(3)] ?? Rect())) + var expected = state + expected.observedFrames[windowID(3)] = state.frames[windowID(3)] + #expect(result.0 == expected) + #expect(result.1.isEmpty) +} + +@Test func duplicateAppearanceUpdatesMetadata() { + let state = populated() + var updated = managed(2) + updated.title = "Updated title" + let result = reduce( + state, .windowAppeared(updated, workspace: primaryKey, frame: state.frames[windowID(2)] ?? Rect())) + #expect(result.0.windows[windowID(2)]?.title == "Updated title") + #expect(result.0.workspaces[primaryKey]?.order == state.workspaces[primaryKey]?.order) +} + +@Test func floatingAppearanceOnlyRecordsFrame() { + let frame = Rect(x: 10.5, y: 20.5, width: 333.3, height: 222.2) + let result = reduce(populated(0), .windowAppeared(managed(1, floating: true), workspace: primaryKey, frame: frame)) + #expect(result.0.frames[windowID(1)] == frame) + #expect(result.0.observedFrames[windowID(1)] == frame) + #expect(result.0.workspaces[primaryKey]?.tree == nil) + #expect(frameWrites(result.1).isEmpty) +} + +@Test func appearanceAtCapRaisesNewestStackMember() { + let state = populated(2, cap: 2) + let result = reduce(state, .windowAppeared(managed(3), workspace: primaryKey, frame: Rect(width: 200, height: 200))) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 2) + #expect(result.0.frames[windowID(2)] == result.0.frames[windowID(3)]) + #expect(result.1.contains(.raiseWindow(windowID(3)))) + #expect(result.0.visibleWindows == [windowID(1), windowID(3)]) +} + +@Test func disappearedWindowRemovesAllRecords() { + let result = reduce(populated(), .windowDisappeared(windowID(2))) + #expect(result.0.windows[windowID(2)] == nil) + #expect(result.0.frames[windowID(2)] == nil) + #expect(result.0.observedFrames[windowID(2)] == nil) + #expect(result.0.workspace(containing: windowID(2)) == nil) + #expect(!frameWrites(result.1).contains { $0.window == windowID(2) }) +} + +@Test func disappearingFocusedWindowFocusesSurvivor() { + let state = focused(3, in: populated()) + let result = reduce(state, .windowDisappeared(windowID(3))) + #expect(result.0.focusedWindow == windowID(2)) + #expect(result.1.contains(.focusWindow(windowID(2)))) +} + +@Test func disappearingLastWindowClearsFocus() { + let result = reduce(focused(1, in: populated(1)), .windowDisappeared(windowID(1))) + #expect(result.0.focusedWindow == nil) + #expect(result.0.workspaces[primaryKey]?.tree == nil) + #expect(result.0.frames.isEmpty) + #expect(frameWrites(result.1).isEmpty) +} + +@Test func duplicateDisappearanceIsNoOp() { + let state = populated() + let result = reduce(state, .windowDisappeared(windowID(99))) + #expect(result.0 == state) + #expect(result.1.isEmpty) +} + +@Test func disappearingVisibleStackMemberRaisesSurvivor() { + let state = focused(3, in: populated(3, cap: 2)) + let result = reduce(state, .windowDisappeared(windowID(3))) + #expect(result.0.workspaces[primaryKey]?.visibleWindows == [windowID(1), windowID(2)]) + #expect(result.1.contains(.raiseWindow(windowID(2)))) +} + +@Test func disappearingHiddenStackMemberKeepsFocus() { + let state = focused(3, in: populated(3, cap: 2)) + let result = reduce(state, .windowDisappeared(windowID(2))) + #expect(result.0.focusedWindow == windowID(3)) + #expect(frameWrites(result.1).isEmpty) +} + +@Test func tiledUserMoveSnapsBackWithoutReordering() { + let state = populated() + let actual = Rect(x: 20, y: 20, width: 100, height: 100) + let result = reduce(state, .windowMovedByUser(windowID(2), frame: actual)) + #expect(result.0.frames == state.frames) + #expect(result.0.observedFrames[windowID(2)] == actual) + #expect(result.0.workspaces == state.workspaces) + #expect(frameWrites(result.1) == [WindowFrame(window: windowID(2), frame: Rect(x: 400, width: 400, height: 800))]) +} + +@Test func tiledUserResizeSnapsBack() { + let state = populated(1) + let result = reduce(state, .windowResizedByUser(windowID(1), frame: Rect(width: 200, height: 100))) + #expect(result.0.frames == state.frames) + #expect(frameWrites(result.1) == [WindowFrame(window: windowID(1), frame: testScreen)]) +} + +@Test func targetFrameFeedbackDoesNotLoop() { + let state = populated(1) + let result = reduce(state, .windowMovedByUser(windowID(1), frame: testScreen)) + #expect(result.1.isEmpty) +} + +@Test func floatingUserMoveOnlyRecordsFrame() { + let state = command(.toggleFloat, in: focused(2, in: populated())).0 + let actual = Rect(x: -90.2, y: 23.1, width: 230, height: 400) + let result = reduce(state, .windowMovedByUser(windowID(2), frame: actual)) + #expect(result.0.frames[windowID(2)] == actual) + #expect(result.1.isEmpty) +} + +@Test func floatingUserResizeOnlyRecordsFrame() { + let state = command(.toggleFloat, in: focused(1, in: populated(1))).0 + let actual = Rect(width: 333, height: 444) + let result = reduce(state, .windowResizedByUser(windowID(1), frame: actual)) + #expect(result.0.frames[windowID(1)] == actual) + #expect(result.1.isEmpty) +} + +@Test func unknownUserMoveReportsWindow() { + let state = populated() + let result = reduce(state, .windowMovedByUser(windowID(99), frame: testScreen)) + #expect(result.0 == state) + #expect(result.1 == [.report(.unknownWindow(windowID(99)))]) +} + +@Test func unknownUserResizeReportsWindow() { + let result = reduce(populated(), .windowResizedByUser(windowID(99), frame: testScreen)) + #expect(result.1 == [.report(.unknownWindow(windowID(99)))]) +} + +@Test func invalidGeometryDoesNotMutateState() { + let state = populated() + let result = reduce(state, .windowMovedByUser(windowID(1), frame: Rect(width: -.infinity, height: 100))) + #expect(result.0 == state) + #expect(result.1 == [.report(.invalidGeometry)]) +} + +@Test func invalidAppearanceDoesNotInsert() { + let state = populated() + let result = reduce(state, .windowAppeared(managed(4), workspace: primaryKey, frame: Rect(width: -1, height: 10))) + #expect(result.0 == state) + #expect(result.1 == [.report(.invalidGeometry)]) +} + +@Test func observedFocusDoesNotRequestFocusAgain() { + let result = reduce(populated(), .focusChanged(windowID(2))) + #expect(result.0.focusedWindow == windowID(2)) + #expect(result.0.workspaces[primaryKey]?.focus == windowID(2)) + #expect(!result.1.contains(.focusWindow(windowID(2)))) + #expect(result.1.contains(.announce(.focused(windowID(2))))) +} + +@Test func unchangedFocusIsNoOp() { + let state = focused(2, in: populated()) + let result = reduce(state, .focusChanged(windowID(2))) + #expect(result.0 == state) + #expect(result.1.isEmpty) +} + +@Test func nilFocusRemembersWorkspaceFocus() { + let state = focused(2, in: populated()) + let result = reduce(state, .focusChanged(nil)) + #expect(result.0.focusedWindow == nil) + #expect(result.0.workspaces[primaryKey]?.focus == windowID(2)) +} + +@Test func unknownFocusIsReported() { + let result = reduce(populated(), .focusChanged(windowID(99))) + #expect(result.1 == [.report(.unknownWindow(windowID(99)))]) +} + +@Test func focusHiddenStackMemberSelectsAndRaisesIt() { + let result = reduce(populated(3, cap: 2), .focusChanged(windowID(2))) + #expect(result.0.visibleWindows == [windowID(1), windowID(2)]) + #expect(result.1.contains(.raiseWindow(windowID(2)))) + #expect(frameWrites(result.1).isEmpty) +} + +@Test func minimumLearningRetilesOnlyChangedFrames() { + let state = populated(2) + let minimum = LearnedMinimumSize(size: Size(width: 900, height: 200)) + let result = reduce(state, .minimumSizeChanged(windowID(1), minimum: minimum)) + #expect(result.0.windows[windowID(1)]?.minimum == minimum) + #expect(frameWrites(result.1).count == 2) + #expect(result.0.frames[windowID(1)]?.size.width == 900) +} + +@Test func minimumResetIsInspectableAndRetiles() { + let state = reduce( + populated(2), .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: 900, height: 200))) + ).0 + let result = reduce(state, .minimumSizeChanged(windowID(1), minimum: nil)) + #expect(result.0.windows[windowID(1)]?.minimum == nil) + #expect(result.0.frames[windowID(1)]?.size.width == 600) +} + +@Test func unknownMinimumIsReported() { + let result = reduce(populated(), .minimumSizeChanged(windowID(99), minimum: nil)) + #expect(result.1 == [.report(.unknownWindow(windowID(99)))]) +} + +@Test func invalidMinimumDoesNotReplaceLearnedValue() { + let state = populated() + let result = reduce( + state, .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: -1, height: 5)))) + #expect(result.0 == state) + #expect(result.1 == [.report(.invalidGeometry)]) +} + +@Test func cannotFitReportIsNotRepeated() { + let state = reduce( + populated(1), + .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: 1500, height: 900)))) + #expect(state.1.contains(.report(.cannotFit([windowID(1)])))) + let result = command(.retile, in: state.0) + #expect(!result.1.contains(.report(.cannotFit([windowID(1)])))) + #expect(result.0.cannotFit == [windowID(1)]) +} + +@Test func frameEffectsAreSortedByWindowNumber() { + let result = command(.setLayout(.rows), in: populated(8)) + let writes = frameWrites(result.1) + #expect(writes.map(\.window) == writes.map(\.window).sorted()) +} + +@Test func reducerDoesNotMutateItsInput() { + let state = populated() + let original = state + _ = reduce(state, .windowDisappeared(windowID(1))) + #expect(state == original) +} + +@Test func stateAndEffectValuesEncode() throws { + let state = focused(3, in: populated(3, cap: 2)) + try roundTrip(state) + let result = command(.setLayout(.side), in: state) + try roundTrip(result.1) +} diff --git a/Tests/TesseraCoreTests/RegressionTests.swift b/Tests/TesseraCoreTests/RegressionTests.swift new file mode 100644 index 00000000..634f7ba7 --- /dev/null +++ b/Tests/TesseraCoreTests/RegressionTests.swift @@ -0,0 +1,154 @@ +import Foundation +import Testing + +@testable import TesseraCore + +@Test(arguments: Layout.allCases) +func conflictingMinimumsKeepGapsAndTilesOnScreen(layout: Layout) { + let space = workspace(3, layout: layout, gaps: Gaps(inner: 10)) + let windows = [windowID(1): managed(1, minimum: Size(width: 1000, height: 1000))] + let result = LayoutEngine.arrange(space, in: Rect(width: 100, height: 100), windows: windows) + for frame in result.frames.values { + #expect(frame.minX >= 0 && frame.maxX <= 100) + #expect(frame.minY >= 0 && frame.maxY <= 100) + } + #expect(result.cannotFit == [windowID(1)]) +} + +@Test func fractionalMinimumUsesNextWholePoint() { + let result = LayoutEngine.arrange( + workspace(2, layout: .columns), in: Rect(width: 100, height: 100), + windows: [windowID(1): managed(1, minimum: Size(width: 50.4, height: 0))]) + #expect(result.frames[windowID(1)]?.size.width == 51) + #expect(result.frames[windowID(2)]?.size.width == 49) + #expect(result.cannotFit.isEmpty) +} + +@Test func migrationReselectsFocusedMemberAfterFillingStack() { + let state = multipleDisplays(destinationCap: 1) + let result = reduce( + state, .displaySetChanged([state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect())])) + #expect(result.0.focusedWindow == windowID(1)) + #expect(result.0.visibleWindows == [windowID(1)]) + #expect(result.0.workspaces[secondaryKey]?.focus == windowID(1)) + #expect(result.1.contains(.raiseWindow(windowID(1)))) +} + +@Test func disconnectRecentersFloatingWindow() { + let floated = command(.toggleFloat, in: focused(3, in: multipleDisplays())).0 + let result = reduce(floated, .displaySetChanged([Display(id: primaryDisplay, frame: testScreen)])) + #expect(result.0.workspace(containing: windowID(3)) == primaryKey) + #expect(result.0.frames[windowID(3)] == Rect(x: 300, width: 600, height: 800)) + #expect(frameWrites(result.1).contains { $0.window == windowID(3) }) +} + +@Test func migrationWaitsForReplacementDisplaySpace() { + let state = focused(2, in: populated()) + let display = Display(id: secondaryDisplay, frame: testScreen) + let pending = reduce(state, .displaySetChanged([display])).0 + #expect(pending.workspace(containing: windowID(2)) == primaryKey) + let result = reduce(pending, .activeSpaceChanged(display: secondaryDisplay, space: secondarySpace)) + #expect(result.0.workspaces[primaryKey]?.order.isEmpty == true) + #expect(result.0.workspaces[secondaryKey]?.order == (1...3).map(windowID)) + #expect(result.0.focusedWindow == windowID(2)) +} + +@Test func disconnectedInactiveSpaceRemainsDormant() { + let key = WorkspaceKey(display: primaryDisplay, space: secondarySpace) + let state = reduce( + multipleDisplays(), .windowAppeared(managed(5), workspace: key, frame: Rect(width: 100, height: 100)) + ).0 + let result = reduce( + state, .displaySetChanged([state.displays[secondaryDisplay] ?? Display(id: secondaryDisplay, frame: Rect())])) + #expect(result.0.workspaces[key]?.order == [windowID(5)]) + #expect(!frameWrites(result.1).contains { $0.window == windowID(5) }) +} + +@Test func inactiveFrameObservationIsReconciledOnReturn() { + let initial = focused(2, in: populated()) + let away = reduce(initial, .activeSpaceChanged(display: primaryDisplay, space: secondarySpace)).0 + let resized = reduce(away, .windowResizedByUser(windowID(1), frame: Rect(width: 100, height: 100))) + #expect(frameWrites(resized.1).isEmpty) + let result = reduce(resized.0, .activeSpaceChanged(display: primaryDisplay, space: primarySpace)) + #expect(frameWrites(result.1) == [WindowFrame(window: windowID(1), frame: Rect(width: 400, height: 800))]) +} + +@Test func floatingStackMemberIsRaisedAboveRemainingStack() { + let state = focused(3, in: populated(3, cap: 1)) + let result = command(.toggleFloat, in: state) + #expect(result.0.visibleWindows == [windowID(2), windowID(3)]) + let raised = result.1.compactMap { effect -> WindowID? in + if case .raiseWindow(let window) = effect { return window } + return nil + } + #expect(raised.last == windowID(3)) +} + +@Test func duplicateBackgroundAppearanceDoesNotStealFocus() { + let state = focused(1, in: populated()) + let result = reduce( + state, .windowAppeared(managed(2), workspace: primaryKey, frame: Rect(x: 400, width: 400, height: 800))) + #expect(result.0.focusedWindow == windowID(1)) + #expect(result.0.workspaces[primaryKey]?.focus == windowID(1)) + #expect(result.1.isEmpty) +} + +@Test func floatingDisplayMoveDiffsInsteadOfWritingUnchangedFrame() { + let floated = command(.toggleFloat, in: multipleDisplays()).0 + let target = Rect(x: 1500, width: 600, height: 800) + let state = reduce(floated, .windowMovedByUser(windowID(1), frame: target)).0 + let result = command(.moveToDisplay(.right), in: state) + #expect(result.0.frames[windowID(1)] == target) + #expect(frameWrites(result.1).isEmpty) +} + +@Test func stackInitializerDeduplicatesEveryMember() { + let stack = WindowStack(windowID(1), others: [windowID(2), windowID(2), windowID(1), windowID(3)]) + #expect(stack.windows == (1...3).map(windowID)) +} + +@Test(arguments: [0, -1]) +func decodedInvalidCapIsRejected(cap: Int) throws { + let data = try JSONEncoder().encode(workspace(3)) + let json = String(decoding: data, as: UTF8.self).replacingOccurrences( + of: "\"windowCap\":8", with: "\"windowCap\":\(cap)") + #expect(throws: (any Error).self) { try JSONDecoder().decode(Workspace.self, from: Data(json.utf8)) } +} + +@Test func decodedEmptyStackIsRejected() { + let json = "{\"windows\":[],\"visible\":1}" + #expect(throws: (any Error).self) { try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) } +} + +@Test func decodedStackWithMissingVisibleMemberIsRejected() { + let json = "{\"windows\":[1,2],\"visible\":3}" + #expect(throws: (any Error).self) { try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) } +} + +@Test func decodedStackWithDuplicateMembersIsRejected() { + let json = "{\"windows\":[1,1],\"visible\":1}" + #expect(throws: (any Error).self) { try JSONDecoder().decode(WindowStack.self, from: Data(json.utf8)) } +} + +@Test func unsupportedLearnedVersionIsReported() { + let state = populated() + let minimum = LearnedMinimumSize(size: Size(width: 100, height: 100), schemaVersion: 2) + let result = reduce(state, .minimumSizeChanged(windowID(1), minimum: minimum)) + #expect(result.0 == state) + #expect(result.1 == [.report(.unsupportedMinimumVersion(2))]) +} + +@Test func unsupportedAppearanceMinimumIsReported() { + var window = managed(4) + window.minimum = LearnedMinimumSize(size: Size(width: 100, height: 100), schemaVersion: 2) + let state = populated() + let result = reduce(state, .windowAppeared(window, workspace: primaryKey, frame: Rect())) + #expect(result.0 == state) + #expect(result.1 == [.report(.unsupportedMinimumVersion(2))]) +} + +@Test func futureReplaySchemaIsRejectedBeforeUnknownEventShape() { + #expect(throws: EventStreamError.unsupportedVersion(line: 1, version: 9)) { + try EventStream.decode("{\"version\":9,\"event\":{\"futureEvent\":{}}}") + } +} diff --git a/Tests/TesseraCoreTests/ReplayTests.swift b/Tests/TesseraCoreTests/ReplayTests.swift new file mode 100644 index 00000000..41ec0dd3 --- /dev/null +++ b/Tests/TesseraCoreTests/ReplayTests.swift @@ -0,0 +1,142 @@ +import Foundation +import Testing + +@testable import TesseraCore + +@Test func emptyEventStreamHasEmptyEncoding() throws { + #expect(try EventStream.encode([]) == "") + #expect(try EventStream.decode("").isEmpty) +} + +@Test func eventStreamUsesVersionedOneLineEntries() throws { + let encoded = try EventStream.encode([.commandIssued(.retile), .focusChanged(nil)]) + #expect(encoded.hasSuffix("\n")) + #expect(encoded.split(separator: "\n").count == 2) + #expect(encoded.contains("\"version\":1")) +} + +@Test func eventStreamEncodingIsStable() throws { + let events: [Event] = [.commandIssued(.setRatio(.threeFifths)), .focusChanged(windowID(1))] + #expect(try EventStream.encode(events) == EventStream.encode(events)) +} + +@Test func everyCommandEncodesAndDecodes() throws { + var commands: [Command] = Direction.allCases.flatMap { + [.focus($0), .swap($0), .move($0), .moveToDisplay($0), .stack($0)] + } + commands += Layout.allCases.map(Command.setLayout) + commands += [ + .cycleLayout, .setRatio(.twoThirds), .nudgeRatio(-0.05), .toggleFloat, .retile, .unstack, + .focusNextInStack, .focusPreviousInStack, .setWindowCap(4), + ] + let events = commands.map(Event.commandIssued) + #expect(try EventStream.decode(EventStream.encode(events)) == events) +} + +@Test func everyEventEncodesAndDecodes() throws { + let frame = Rect(x: -100, y: 20, width: 300, height: 400) + let events: [Event] = [ + .windowAppeared(managed(1), workspace: primaryKey, frame: frame), .windowDisappeared(windowID(1)), + .windowMovedByUser(windowID(1), frame: frame), .windowResizedByUser(windowID(1), frame: frame), + .focusChanged(windowID(1)), .focusChanged(nil), + .displaySetChanged([Display(id: primaryDisplay, frame: testScreen)]), + .activeSpaceChanged(display: primaryDisplay, space: primarySpace), .commandIssued(.retile), + .minimumSizeChanged(windowID(1), minimum: LearnedMinimumSize(size: Size(width: 200, height: 100))), + .minimumSizeChanged(windowID(1), minimum: nil), + ] + #expect(try EventStream.decode(EventStream.encode(events)) == events) +} + +@Test func blankLinesAndCarriageReturnsAreAccepted() throws { + let events: [Event] = [.commandIssued(.retile)] + let encoded = try EventStream.encode(events) + #expect(try EventStream.decode("\n \t\n" + encoded.replacingOccurrences(of: "\n", with: "\r\n")) == events) +} + +@Test func malformedLineReportsOriginalLineNumber() throws { + let encoded = try EventStream.encode([.commandIssued(.retile)]) + do { + _ = try EventStream.decode(encoded + "\nnot-json\n") + Issue.record("Malformed JSON was accepted") + } catch let error as EventStreamError { + guard case .invalidLine(let line, let reason) = error else { + Issue.record("Unexpected stream error: \(error)") + return + } + #expect(line == 3) + #expect(!reason.isEmpty) + } +} + +@Test func unsupportedVersionReportsOriginalLineNumber() throws { + let encoded = try EventStream.encode([.commandIssued(.retile)]).replacingOccurrences( + of: "\"version\":1", with: "\"version\":9") + #expect(throws: EventStreamError.unsupportedVersion(line: 2, version: 9)) { + try EventStream.decode("\n" + encoded) + } +} + +@Test func nonFiniteEventEncodingSurfacesError() { + #expect(throws: (any Error).self) { try EventStream.encode([.commandIssued(.nudgeRatio(.infinity))]) } +} + +@Test func emptyReplayRetainsInitialState() { + let initial = focused(2, in: populated()) + let result = Replay.run([], initial: initial) + #expect(result.state == initial) + #expect(result.finalFrames == initial.frames) + #expect(result.effects.isEmpty) +} + +@Test func replayMatchesIndividualReduction() { + let initial = focused(2, in: populated()) + let events: [Event] = [ + .commandIssued(.setLayout(.rows)), .commandIssued(.swap(.up)), .windowDisappeared(windowID(3)), + ] + var state = initial + var trace: [[Effect]] = [] + for event in events { + let result = reduce(state, event) + state = result.0 + trace.append(result.1) + } + #expect(Replay.run(events, initial: initial) == ReplayResult(state: state, effects: trace)) +} + +@Test func replayJSONMatchesTypedEvents() throws { + let initial = focused(1, in: populated()) + let events: [Event] = [.commandIssued(.toggleFloat), .commandIssued(.setLayout(.side)), .commandIssued(.retile)] + #expect( + try Replay.run(jsonLines: EventStream.encode(events), initial: initial) == Replay.run(events, initial: initial)) +} + +@Test func replayIsDeterministicAcrossDictionaryInsertionOrder() throws { + let initial = multipleDisplays() + var reordered = initial + reordered.windows = Dictionary(uniqueKeysWithValues: initial.windows.sorted { $0.key > $1.key }) + reordered.displays = Dictionary(uniqueKeysWithValues: initial.displays.sorted { $0.key > $1.key }) + reordered.workspaces = Dictionary(uniqueKeysWithValues: initial.workspaces.sorted { $0.key > $1.key }) + let events: [Event] = [ + .commandIssued(.moveToDisplay(.right)), .commandIssued(.setWindowCap(1)), .commandIssued(.focusPreviousInStack), + .commandIssued(.retile), + ] + #expect(Replay.run(events, initial: initial) == Replay.run(events, initial: reordered)) +} + +@Test func replayResultCanBeSavedAndRestored() throws { + let result = Replay.run([.commandIssued(.setLayout(.side))], initial: populated()) + try roundTrip(result) +} + +@Test(arguments: ["side", "displays"]) +func fixtureReplayMatchesGoldenFrames(name: String) throws { + let eventsURL = try #require(Bundle.module.url(forResource: name, withExtension: "jsonl", subdirectory: "Fixtures")) + let goldenURL = try #require( + Bundle.module.url(forResource: name + "-frames", withExtension: "json", subdirectory: "Fixtures")) + let stream = try String(contentsOf: eventsURL, encoding: .utf8) + let golden = try JSONDecoder().decode([WindowFrame].self, from: Data(contentsOf: goldenURL)) + let result = try Replay.run(jsonLines: stream) + #expect(result.finalFrames == Dictionary(uniqueKeysWithValues: golden.map { ($0.window, $0.frame) })) + #expect(result == Replay.run(try EventStream.decode(stream))) + #expect(result == Replay.run(try EventStream.decode(EventStream.encode(EventStream.decode(stream))))) +} -- knotmirror 0.0.1 From 22cfc4927ebd4b65a970005d5c78baf1557d7415 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:08:10 -0400 Subject: [PATCH 22/44] Build the motion system --- Sources/TesseraAnimation/Animator.swift | 120 +++++++ .../TesseraAnimation/DisplayLinkDriver.swift | 184 +++++++++++ Sources/TesseraAnimation/FrameCoalescer.swift | 126 +++++++ Sources/TesseraAnimation/FramePlanner.swift | 311 ++++++++++++++++++ Sources/TesseraAnimation/MotionGeometry.swift | 140 ++++++++ Sources/TesseraAnimation/MotionTokens.swift | 150 +++++++++ Sources/TesseraAnimation/Spring.swift | 83 +++++ .../TesseraAnimation.docc/TesseraAnimation.md | 25 ++ .../TesseraAnimation/TesseraAnimation.swift | 1 - .../TesseraAnimationTests/AnimatorTests.swift | 244 ++++++++++++++ .../DisplayLinkDriverTests.swift | 147 +++++++++ .../FrameCoalescerTests.swift | 268 +++++++++++++++ .../FramePlannerTests.swift | 273 +++++++++++++++ .../MotionTokenTests.swift | 167 ++++++++++ Tests/TesseraAnimationTests/SpringTests.swift | 164 +++++++++ .../TesseraAnimationTests.swift | 4 - Tests/TesseraAnimationTests/TestSupport.swift | 47 +++ 17 files changed, 2449 insertions(+), 5 deletions(-) create mode 100644 Sources/TesseraAnimation/Animator.swift create mode 100644 Sources/TesseraAnimation/DisplayLinkDriver.swift create mode 100644 Sources/TesseraAnimation/FrameCoalescer.swift create mode 100644 Sources/TesseraAnimation/FramePlanner.swift create mode 100644 Sources/TesseraAnimation/MotionGeometry.swift create mode 100644 Sources/TesseraAnimation/MotionTokens.swift create mode 100644 Sources/TesseraAnimation/Spring.swift create mode 100644 Sources/TesseraAnimation/TesseraAnimation.docc/TesseraAnimation.md delete mode 100644 Sources/TesseraAnimation/TesseraAnimation.swift create mode 100644 Tests/TesseraAnimationTests/AnimatorTests.swift create mode 100644 Tests/TesseraAnimationTests/DisplayLinkDriverTests.swift create mode 100644 Tests/TesseraAnimationTests/FrameCoalescerTests.swift create mode 100644 Tests/TesseraAnimationTests/FramePlannerTests.swift create mode 100644 Tests/TesseraAnimationTests/MotionTokenTests.swift create mode 100644 Tests/TesseraAnimationTests/SpringTests.swift delete mode 100644 Tests/TesseraAnimationTests/TesseraAnimationTests.swift create mode 100644 Tests/TesseraAnimationTests/TestSupport.swift diff --git a/Sources/TesseraAnimation/Animator.swift b/Sources/TesseraAnimation/Animator.swift new file mode 100644 index 00000000..642c908f --- /dev/null +++ b/Sources/TesseraAnimation/Animator.swift @@ -0,0 +1,120 @@ +public struct Animator: Sendable { + public private(set) var policy: MotionPolicy + public private(set) var settings: MotionSettings + public private(set) var timestamp: Double? + public var isIdle: Bool { plans.isEmpty } + public var activeWindowIDs: [MotionWindowID] { plans.keys.sorted() } + private var plans: [MotionWindowID: FramePlan] = [:] + private var lastEmission: [MotionWindowID: Double] = [:] + private var emissionCount: [MotionWindowID: Int] = [:] + private var nextRevision: UInt64 = 0 + + public init(policy: MotionPolicy = MotionPolicy(), settings: MotionSettings = MotionSettings()) { + self.policy = policy + self.settings = settings + } + + public mutating func schedule(_ requests: [MotionRequest], at timestamp: Double) throws { + try validateTime(timestamp) + var identifiers: Set = [] + var replacements: [MotionWindowID: FramePlan] = [:] + for request in requests { + guard identifiers.insert(request.windowID).inserted else { + throw MotionError.duplicateWindow(request.windowID) + } + replacements[request.windowID] = try FramePlanner.makePlan( + request, at: timestamp, policy: policy, settings: settings, + inherited: inheritedState(for: request, at: timestamp), revision: nextRevision + 1 + ) + } + nextRevision += 1 + for (identifier, plan) in replacements { + plans[identifier] = plan + lastEmission[identifier] = nil + emissionCount[identifier] = nil + } + self.timestamp = timestamp + } + + public mutating func tick(at timestamp: Double) throws -> [MotionFrame] { + try validateTime(timestamp) + self.timestamp = timestamp + var frames: [MotionFrame] = [] + for identifier in plans.keys.sorted() { + guard let plan = plans[identifier] else { continue } + guard timestamp >= plan.startTime else { continue } + let isFinal = timestamp >= plan.endTime + if !isFinal, let maximumRedraws = plan.spec.maximumRedraws { + if emissionCount[identifier, default: 0] >= maximumRedraws - 1 { continue } + if let last = lastEmission[identifier], timestamp - last < plan.duration / Double(maximumRedraws - 1) { + continue + } + } + if lastEmission[identifier] == timestamp { continue } + frames.append(try plan.sample(at: timestamp).frame) + lastEmission[identifier] = timestamp + emissionCount[identifier, default: 0] += 1 + if isFinal { + plans[identifier] = nil + lastEmission[identifier] = nil + emissionCount[identifier] = nil + } + } + return frames + } + + public func presentation(for windowID: MotionWindowID, at timestamp: Double) throws -> MotionSample? { + guard timestamp.isFinite else { throw MotionError.invalidTimestamp } + return try plans[windowID]?.sample(at: timestamp) + } + + public mutating func cancel(_ windowID: MotionWindowID) { + plans[windowID] = nil + lastEmission[windowID] = nil + emissionCount[windowID] = nil + } + + public mutating func cancelAll() { + plans.removeAll(keepingCapacity: true) + lastEmission.removeAll(keepingCapacity: true) + emissionCount.removeAll(keepingCapacity: true) + } + + public mutating func updatePolicy(_ policy: MotionPolicy, at timestamp: Double) throws { + try replan(policy: policy, settings: settings, at: timestamp) + } + + public mutating func updateSettings(_ settings: MotionSettings, at timestamp: Double) throws { + try replan(policy: policy, settings: settings, at: timestamp) + } + + private mutating func replan(policy: MotionPolicy, settings: MotionSettings, at timestamp: Double) throws { + try validateTime(timestamp) + var replacements: [MotionWindowID: FramePlan] = [:] + for (identifier, plan) in plans { + replacements[identifier] = try FramePlanner.makePlan( + plan.request, at: timestamp, policy: policy, settings: settings, + inherited: plan.state(at: timestamp), revision: nextRevision + 1 + ) + } + self.policy = policy + self.settings = settings + self.timestamp = timestamp + nextRevision += 1 + plans = replacements + lastEmission.removeAll(keepingCapacity: true) + emissionCount.removeAll(keepingCapacity: true) + } + + private func inheritedState(for request: MotionRequest, at timestamp: Double) -> PresentationState? { + guard let plan = plans[request.windowID], plan.request.generation == request.generation, + plan.request.appID == request.appID + else { return nil } + return plan.state(at: timestamp) + } + + private func validateTime(_ timestamp: Double) throws { + guard timestamp.isFinite else { throw MotionError.invalidTimestamp } + if let previous = self.timestamp, timestamp < previous { throw MotionError.timestampWentBackwards } + } +} diff --git a/Sources/TesseraAnimation/DisplayLinkDriver.swift b/Sources/TesseraAnimation/DisplayLinkDriver.swift new file mode 100644 index 00000000..823bc9d6 --- /dev/null +++ b/Sources/TesseraAnimation/DisplayLinkDriver.swift @@ -0,0 +1,184 @@ +public import AppKit +import QuartzCore + +@MainActor +protocol DisplayLinkSource: AnyObject { + var isRunning: Bool { get } + func start(tick: @escaping @MainActor (Double) -> Void) + func stop() +} + +@MainActor +public protocol ReduceMotionSource: AnyObject { + var isEnabled: Bool { get } + func start(changed: @escaping @MainActor () -> Void) + func stop() +} + +@MainActor +public final class DisplayLinkDriver { + public private(set) var animator: Animator + public var isRunning: Bool { source.isRunning } + private let source: any DisplayLinkSource + private let reduceMotionSource: (any ReduceMotionSource)? + private var requestedPolicy: MotionPolicy + private let clock: @MainActor () -> Double + private let onFrames: @MainActor ([MotionFrame]) -> Void + private let onFailure: @MainActor (MotionError) -> Void + + public convenience init( + screen: NSScreen, policy: MotionPolicy = MotionPolicy(), settings: MotionSettings = MotionSettings(), + reduceMotionSource: (any ReduceMotionSource)? = nil, + onFrames: @escaping @MainActor ([MotionFrame]) -> Void, + onFailure: @escaping @MainActor (MotionError) -> Void + ) { + self.init( + source: ScreenDisplayLink(screen: screen), animator: Animator(policy: policy, settings: settings), + reduceMotionSource: reduceMotionSource ?? WorkspaceReduceMotionSource(), + onFrames: onFrames, onFailure: onFailure + ) + } + + init( + source: any DisplayLinkSource, animator: Animator = Animator(), + reduceMotionSource: (any ReduceMotionSource)? = nil, + clock: @escaping @MainActor () -> Double = { CACurrentMediaTime() }, + onFrames: @escaping @MainActor ([MotionFrame]) -> Void, + onFailure: @escaping @MainActor (MotionError) -> Void + ) { + precondition(animator.isIdle) + self.source = source + self.reduceMotionSource = reduceMotionSource + self.requestedPolicy = animator.policy + self.clock = clock + var policy = animator.policy + policy.reduceMotion = policy.reduceMotion || reduceMotionSource?.isEnabled == true + self.animator = Animator(policy: policy, settings: animator.settings) + self.onFrames = onFrames + self.onFailure = onFailure + reduceMotionSource?.start { [weak self] in self?.accessibilityChanged() } + } + + isolated deinit { + source.stop() + reduceMotionSource?.stop() + } + + public func schedule(_ requests: [MotionRequest], at timestamp: Double? = nil) throws { + try animator.schedule(requests, at: resolvedTime(timestamp)) + refreshSource() + } + + public func updatePolicy(_ policy: MotionPolicy, at timestamp: Double? = nil) throws { + var effective = policy + effective.reduceMotion = policy.reduceMotion || reduceMotionSource?.isEnabled == true + try animator.updatePolicy(effective, at: resolvedTime(timestamp)) + requestedPolicy = policy + refreshSource() + } + + public func updateSettings(_ settings: MotionSettings, at timestamp: Double? = nil) throws { + try animator.updateSettings(settings, at: resolvedTime(timestamp)) + refreshSource() + } + + public func cancel(_ windowID: MotionWindowID) { + animator.cancel(windowID) + refreshSource() + } + + public func stop() { + source.stop() + animator.cancelAll() + } + + private func resolvedTime(_ timestamp: Double?) -> Double { + if let timestamp { return timestamp } + // Display links predict presentation time, which can be ahead of the command clock. + return max(clock(), animator.timestamp ?? -.infinity) + } + + private func accessibilityChanged() { + do { try updatePolicy(requestedPolicy) } catch { fail(error) } + } + + private func refreshSource() { + if animator.isIdle { + source.stop() + } else if !source.isRunning { + source.start { [weak self] timestamp in self?.tick(at: timestamp) } + } + } + + private func tick(at timestamp: Double) { + do { + let frames = try animator.tick(at: timestamp) + refreshSource() + if !frames.isEmpty { onFrames(frames) } + } catch { fail(error) } + } + + private func fail(_ error: any Error) { + guard let error = error as? MotionError else { + preconditionFailure("Unexpected animation error: \(error)") + } + stop() + onFailure(error) + } +} + +@MainActor +private final class WorkspaceReduceMotionSource: ReduceMotionSource { + var isEnabled: Bool { NSWorkspace.shared.accessibilityDisplayShouldReduceMotion } + private var observer: (any NSObjectProtocol)? + + func start(changed: @escaping @MainActor () -> Void) { + stop() + observer = NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil, queue: .main + ) { _ in + Task { @MainActor in changed() } + } + } + + func stop() { + if let observer { NSWorkspace.shared.notificationCenter.removeObserver(observer) } + observer = nil + } + + isolated deinit { stop() } +} + +@MainActor +private final class ScreenDisplayLink: DisplayLinkSource { + let screen: NSScreen + private var link: CADisplayLink? + private var callback: (@MainActor (Double) -> Void)? + var isRunning: Bool { link != nil } + + init(screen: NSScreen) { self.screen = screen } + + func start(tick: @escaping @MainActor (Double) -> Void) { + guard link == nil else { return } + callback = tick + let relay = DisplayLinkRelay(source: self) + let link = screen.displayLink(target: relay, selector: #selector(DisplayLinkRelay.tick(_:))) + self.link = link + link.add(to: .main, forMode: .common) + } + + func stop() { + link?.invalidate() + link = nil + callback = nil + } + + func tick(_ link: CADisplayLink) { callback?(link.targetTimestamp) } +} + +@MainActor +private final class DisplayLinkRelay: NSObject { + weak var source: ScreenDisplayLink? + init(source: ScreenDisplayLink) { self.source = source } + @objc func tick(_ link: CADisplayLink) { source?.tick(link) } +} diff --git a/Sources/TesseraAnimation/FrameCoalescer.swift b/Sources/TesseraAnimation/FrameCoalescer.swift new file mode 100644 index 00000000..513d405f --- /dev/null +++ b/Sources/TesseraAnimation/FrameCoalescer.swift @@ -0,0 +1,126 @@ +public struct FrameBatch: Sendable, Equatable { + public let identifier: UInt64 + public let appID: MotionAppID + public let frames: [MotionFrame] + public let dispatchedAt: Double +} + +public struct FrameCoalescer: Sendable { + public let fullFrameRate: Double + public var pendingCount: Int { pending.count } + public var inFlightCount: Int { inFlight.count } + public var metricsSnapshot: [MotionAppID: AppWriteMetrics] { metrics } + private var pending: [MotionWindowID: MotionFrame] = [:] + private var newest: [MotionWindowID: MotionFrame] = [:] + private var inFlight: [MotionAppID: UInt64] = [:] + private var lastDispatch: [MotionAppID: Double] = [:] + private var metrics: [MotionAppID: AppWriteMetrics] = [:] + private var generations: [MotionWindowID: UInt64] = [:] + private var activeWindows: [MotionWindowID: MotionAppID] = [:] + private var inactiveApps: Set = [] + private var timestamp: Double? + private var nextBatch: UInt64 = 0 + + public init(fullFrameRate: Double = 120) { + precondition(fullFrameRate.isFinite && fullFrameRate > 0) + self.fullFrameRate = fullFrameRate + } + + @discardableResult + public mutating func submit(_ frame: MotionFrame) throws -> Bool { + guard frame.timestamp.isFinite else { throw MotionError.invalidTimestamp } + guard !inactiveApps.contains(frame.appID) else { return false } + if generations[frame.windowID] == nil && frame.generation == 0 { + generations[frame.windowID] = 0 + activeWindows[frame.windowID] = frame.appID + } + guard activeWindows[frame.windowID] == frame.appID, + generations[frame.windowID] == frame.generation + else { return false } + if let previous = newest[frame.windowID] { + if frame.revision < previous.revision { return false } + if frame.revision == previous.revision && frame.timestamp <= previous.timestamp { return false } + } + pending[frame.windowID] = frame + newest[frame.windowID] = frame + return true + } + + public mutating func takeReady(at timestamp: Double) throws -> [FrameBatch] { + try validateTime(timestamp) + self.timestamp = timestamp + let applications = Set(pending.values.map(\.appID)).sorted() + var batches: [FrameBatch] = [] + for appID in applications { + guard inFlight[appID] == nil else { continue } + let rate = metrics[appID]?.frameRate(fullRate: fullFrameRate) ?? fullFrameRate + if let last = lastDispatch[appID], timestamp - last + 1e-12 < 1 / rate { continue } + let frames = pending.values.filter { $0.appID == appID && $0.timestamp <= timestamp } + .sorted { $0.windowID < $1.windowID } + guard !frames.isEmpty else { continue } + nextBatch += 1 + let batch = FrameBatch(identifier: nextBatch, appID: appID, frames: frames, dispatchedAt: timestamp) + inFlight[appID] = batch.identifier + lastDispatch[appID] = timestamp + for frame in frames { pending[frame.windowID] = nil } + batches.append(batch) + } + return batches + } + + public mutating func complete( + _ batch: FrameBatch, duration: Double, timedOut: Bool = false, at timestamp: Double + ) throws { + try validateTime(timestamp) + guard inFlight[batch.appID] == batch.identifier else { throw MotionError.unknownBatch } + var appMetrics = metrics[batch.appID] ?? AppWriteMetrics() + try appMetrics.record(duration: duration, timedOut: timedOut, at: timestamp) + metrics[batch.appID] = appMetrics + inFlight[batch.appID] = nil + self.timestamp = timestamp + } + + public mutating func setMetrics(_ metrics: AppWriteMetrics, for appID: MotionAppID) { + self.metrics[appID] = metrics + } + + public mutating func resetMetrics(for appID: MotionAppID) { + metrics[appID] = nil + } + + /// Start a new generation before transferring between animators or reusing a window identifier. + public mutating func activate(_ windowID: MotionWindowID, appID: MotionAppID) -> UInt64 { + let generation = generations[windowID, default: 0] + 1 + generations[windowID] = generation + activeWindows[windowID] = appID + inactiveApps.remove(appID) + pending[windowID] = nil + newest[windowID] = nil + return generation + } + + public func generation(for windowID: MotionWindowID) -> UInt64? { + activeWindows[windowID] == nil ? nil : generations[windowID] + } + + public mutating func remove(_ windowID: MotionWindowID) { + // Keep the watermark so a late producer cannot resurrect a removed window. + if generations[windowID] == nil { generations[windowID] = 0 } + activeWindows[windowID] = nil + pending[windowID] = nil + newest[windowID] = nil + } + + public mutating func removeApp(_ appID: MotionAppID) { + for windowID in activeWindows.keys.filter({ activeWindows[$0] == appID }) { remove(windowID) } + inFlight[appID] = nil + lastDispatch[appID] = nil + metrics[appID] = nil + inactiveApps.insert(appID) + } + + private func validateTime(_ timestamp: Double) throws { + guard timestamp.isFinite else { throw MotionError.invalidTimestamp } + if let previous = self.timestamp, timestamp < previous { throw MotionError.timestampWentBackwards } + } +} diff --git a/Sources/TesseraAnimation/FramePlanner.swift b/Sources/TesseraAnimation/FramePlanner.swift new file mode 100644 index 00000000..4783750b --- /dev/null +++ b/Sources/TesseraAnimation/FramePlanner.swift @@ -0,0 +1,311 @@ +import Foundation + +public struct MotionRequest: Sendable, Equatable { + public var windowID: MotionWindowID + public var appID: MotionAppID + public var generation: UInt64 + public var start: MotionRect + public var target: MotionRect + public var screen: MotionRect + public var minimumSize: MotionSize + public var surface: MotionSurface + public var token: MotionToken + public var staggerIndex: Int + public var velocity: MotionVelocity + public var startOpacity: Double + public var targetOpacity: Double + public var metrics: AppWriteMetrics + + public init( + windowID: MotionWindowID, appID: MotionAppID, start: MotionRect, target: MotionRect, + screen: MotionRect, minimumSize: MotionSize = .zero, surface: MotionSurface = .window, + token: MotionToken = .settle, staggerIndex: Int = 0, velocity: MotionVelocity = .zero, + startOpacity: Double = 1, targetOpacity: Double = 1, metrics: AppWriteMetrics = AppWriteMetrics(), + generation: UInt64 = 0 + ) { + self.windowID = windowID + self.appID = appID + self.generation = generation + self.start = start + self.target = target + self.screen = screen + self.minimumSize = minimumSize + self.surface = surface + self.token = token + self.staggerIndex = staggerIndex + self.velocity = velocity + self.startOpacity = startOpacity + self.targetOpacity = targetOpacity + self.metrics = metrics + } +} + +public struct MotionFrame: Sendable, Equatable { + public let windowID: MotionWindowID + public let appID: MotionAppID + public let generation: UInt64 + public let rect: MotionRect + public let opacity: Double + public let scale: Double + public let offsetHorizontal: Double + public let offsetVertical: Double + public let timestamp: Double + public let revision: UInt64 + public let isFinal: Bool +} + +public struct MotionSample: Sendable, Equatable { + public let frame: MotionFrame + public let velocity: MotionVelocity +} + +struct PresentationState: Sendable { + var rect: MotionRect + var velocity: MotionVelocity + var opacity: SpringState + var scale: SpringState + var offsetHorizontal: SpringState + var offsetVertical: SpringState + + mutating func removeAccents() { + scale = SpringState(value: 1) + offsetHorizontal = SpringState(value: 0) + offsetVertical = SpringState(value: 0) + } + + mutating func apply(_ accent: MotionAccent, layers: Int) { + switch accent { + case .none: break + case .scale(let from): scale = SpringState(value: from) + case .offset(let horizontal, let vertical): + offsetHorizontal = SpringState(value: horizontal * Double(layers)) + offsetVertical = SpringState(value: vertical * Double(layers)) + } + } + + mutating func settleUnchangedAxes(target: MotionRect) { + if rect.originX == target.originX { velocity.horizontal = 0 } + if rect.originY == target.originY { velocity.vertical = 0 } + } +} + +private struct MotionTiming { + let duration: Double + let delay: Double + let curve: MotionCurve +} + +public enum FramePlanner { + public static func plan( + _ request: MotionRequest, at timestamp: Double, policy: MotionPolicy = MotionPolicy(), + settings: MotionSettings = MotionSettings() + ) throws -> FramePlan { + try makePlan(request, at: timestamp, policy: policy, settings: settings, inherited: nil, revision: 0) + } + + static func makePlan( + _ request: MotionRequest, at timestamp: Double, policy: MotionPolicy, + settings: MotionSettings, inherited: PresentationState?, revision: UInt64 + ) throws -> FramePlan { + let bounds = try validate(request, at: timestamp) + let isWindow = request.surface == .window + let spec = (isWindow ? MotionToken.settle : request.token).spec(settings: settings) + var behavior = policy.behavior(for: request.surface, level: settings.level) + if isWindow && request.metrics.shouldSnap(at: timestamp) { behavior = .instant } + let timing = timing(for: request, spec: spec, behavior: behavior, retargeting: inherited != nil) + let target = bounds.constrained(request.target, rounded: true) + var initial = initialState(request, target: target, spec: spec, inherited: inherited, level: settings.level) + initial.rect = bounds.constrained(initial.rect, rounded: false) + if timing.curve == .fade { + initial.rect = target + initial.velocity = .zero + initial.removeAccents() + } + if timing.curve == .glide && inherited == nil && timing.duration > 0 { + initial.velocity.horizontal = + request.velocity.horizontal == 0 + ? 4 * (target.originX - initial.rect.originX) / timing.duration : request.velocity.horizontal + initial.velocity.vertical = + request.velocity.vertical == 0 + ? 4 * (target.originY - initial.rect.originY) / timing.duration : request.velocity.vertical + } + if isWindow { initial.settleUnchangedAxes(target: target) } + if timing.duration == 0 { initial.velocity = .zero } + let startTime = timestamp + timing.delay + let endTime = startTime + timing.duration + guard startTime.isFinite && endTime.isFinite && (timing.duration == 0 || endTime > startTime) else { + throw MotionError.invalidTimestamp + } + return FramePlan( + request: request, spec: spec, startTime: startTime, duration: timing.duration, + curve: timing.curve, initial: initial, target: target, bounds: bounds, revision: revision + ) + } + + private static func validate(_ request: MotionRequest, at timestamp: Double) throws -> FrameBounds { + guard timestamp.isFinite else { throw MotionError.invalidTimestamp } + guard request.start.isValid && request.target.isValid && request.staggerIndex >= 0 else { + throw MotionError.invalidGeometry + } + guard request.velocity.isValid else { throw MotionError.invalidVelocity } + guard request.startOpacity.isFinite && request.targetOpacity.isFinite, + (0...1).contains(request.startOpacity) && (0...1).contains(request.targetOpacity) + else { throw MotionError.invalidOpacity } + return try FrameBounds(screen: request.screen, minimumSize: request.minimumSize) + } + + private static func timing( + for request: MotionRequest, spec: MotionSpec, behavior: MotionBehavior, retargeting: Bool + ) -> MotionTiming { + switch behavior { + case .instant: return MotionTiming(duration: 0, delay: 0, curve: spec.curve) + case .fade(let duration): return MotionTiming(duration: duration, delay: 0, curve: .fade) + case .animate: + let isWindow = request.surface == .window + return MotionTiming( + duration: spec.duration, + delay: isWindow || retargeting ? 0 : spec.delay(for: request.staggerIndex), + curve: isWindow ? .glide : spec.curve) + } + } + + private static func initialState( + _ request: MotionRequest, target: MotionRect, spec: MotionSpec, + inherited: PresentationState?, level: WhimsyLevel + ) -> PresentationState { + var initial = + inherited + ?? PresentationState( + rect: request.start, velocity: request.velocity, + opacity: SpringState(value: request.startOpacity), scale: SpringState(value: 1), + offsetHorizontal: SpringState(value: 0), offsetVertical: SpringState(value: 0) + ) + if inherited == nil { initial.apply(spec.accent, layers: request.token == .stack ? request.staggerIndex : 1) } + if level == .calm { initial.removeAccents() } + if request.surface == .window { + initial.rect.width = target.width + initial.rect.height = target.height + initial.velocity.width = 0 + initial.velocity.height = 0 + initial.opacity = SpringState(value: 1) + initial.removeAccents() + } + return initial + } +} + +public struct FramePlan: Sendable { + public let request: MotionRequest + public let spec: MotionSpec + public let startTime: Double + public let duration: Double + public var endTime: Double { startTime + duration } + let curve: MotionCurve + let initial: PresentationState + let target: MotionRect + let bounds: FrameBounds + let revision: UInt64 + + public func sample(at timestamp: Double) throws -> MotionSample { + guard timestamp.isFinite else { throw MotionError.invalidTimestamp } + let state = state(at: timestamp) + let frame = MotionFrame( + windowID: request.windowID, appID: request.appID, generation: request.generation, + rect: bounds.constrained(state.rect, rounded: true), opacity: state.opacity.value, + scale: state.scale.value, offsetHorizontal: state.offsetHorizontal.value, + offsetVertical: state.offsetVertical.value, timestamp: timestamp, revision: revision, + isFinal: timestamp >= endTime + ) + return MotionSample(frame: frame, velocity: state.velocity) + } + + func state(at timestamp: Double) -> PresentationState { + if duration == 0 || timestamp >= endTime { + return PresentationState( + rect: target, velocity: .zero, + opacity: SpringState(value: request.surface == .window ? 1 : request.targetOpacity), + scale: SpringState(value: 1), offsetHorizontal: SpringState(value: 0), + offsetVertical: SpringState(value: 0) + ) + } + let elapsed = max(0, timestamp - startTime) + let horizontal = component( + initial.rect.originX, velocity: initial.velocity.horizontal, target: target.originX, elapsed: elapsed) + let vertical = component( + initial.rect.originY, velocity: initial.velocity.vertical, target: target.originY, elapsed: elapsed) + let width = component( + initial.rect.width, velocity: initial.velocity.width, target: target.width, elapsed: elapsed) + let height = component( + initial.rect.height, velocity: initial.velocity.height, target: target.height, elapsed: elapsed) + let raw = MotionRect( + originX: horizontal.value, originY: vertical.value, width: width.value, height: height.value) + let rect = bounds.constrained(raw, rounded: false) + let velocity = MotionVelocity( + horizontal: rect.originX == raw.originX ? horizontal.velocity : 0, + vertical: rect.originY == raw.originY ? vertical.velocity : 0, + width: rect.width == raw.width ? width.velocity : 0, + height: rect.height == raw.height ? height.velocity : 0 + ) + return PresentationState( + rect: rect, velocity: velocity, + opacity: component( + initial.opacity.value, velocity: initial.opacity.velocity, + target: request.surface == .window ? 1 : request.targetOpacity, elapsed: elapsed, limit: 0), + scale: component(initial.scale.value, velocity: initial.scale.velocity, target: 1, elapsed: elapsed), + offsetHorizontal: accent(initial.offsetHorizontal, elapsed: elapsed), + offsetVertical: accent(initial.offsetVertical, elapsed: elapsed) + ) + } + + private func accent(_ initial: SpringState, elapsed: Double) -> SpringState { + let result = component(initial.value, velocity: initial.velocity, target: 0, elapsed: elapsed) + let value = min(abs(initial.value), max(-abs(initial.value), result.value)) + return SpringState(value: value, velocity: value == result.value ? result.velocity : 0) + } + + private func component( + _ start: Double, velocity: Double, target: Double, elapsed: Double, limit: Double? = nil + ) -> SpringState { + let result: SpringState + switch curve { + case .spring: + let spring = SpringState(value: start, velocity: velocity).advanced( + to: target, by: elapsed, using: spec.spring) + // A terminal envelope keeps the token deadline without cutting off spring momentum. + let tail = duration * 0.3 + let progress = max(0, (elapsed - duration * 0.7) / tail) + let envelope = 1 - 10 * pow(progress, 3) + 15 * pow(progress, 4) - 6 * pow(progress, 5) + let derivative = (-30 * pow(progress, 2) + 60 * pow(progress, 3) - 30 * pow(progress, 4)) / tail + result = SpringState( + value: target + (spring.value - target) * envelope, + velocity: spring.velocity * envelope + (spring.value - target) * derivative + ) + case .glide: + let progress = min(1, elapsed / duration) + let remaining = 1 - progress + let envelope = pow(remaining, 4) + let correction = velocity - 4 * (target - start) / duration + result = SpringState( + value: target + (start - target + correction * elapsed) * envelope, + velocity: correction * envelope - 4 * (start - target + correction * elapsed) * pow(remaining, 3) + / duration + ) + case .fade: + let progress = min(1, elapsed / duration) + let remaining = 1 - progress + result = SpringState( + value: target + (start - target) * remaining * remaining, + velocity: 2 * (target - start) * remaining / duration + ) + } + if curve == .glide && limit == nil { + // Reversals brake with the existing momentum, but never cross the new target. + let value = + target > start ? min(target, result.value) : target < start ? max(target, result.value) : result.value + return SpringState(value: value, velocity: value == result.value ? result.velocity : 0) + } + let overshoot = abs(target - start) * (limit ?? spec.overshootLimit) + let value = min(max(start, target) + overshoot, max(min(start, target) - overshoot, result.value)) + return SpringState(value: value, velocity: value == result.value ? result.velocity : 0) + } +} diff --git a/Sources/TesseraAnimation/MotionGeometry.swift b/Sources/TesseraAnimation/MotionGeometry.swift new file mode 100644 index 00000000..f9e7beca --- /dev/null +++ b/Sources/TesseraAnimation/MotionGeometry.swift @@ -0,0 +1,140 @@ +public struct MotionWindowID: RawRepresentable, Sendable, Hashable, Comparable { + public let rawValue: UInt64 + public init(rawValue: UInt64) { self.rawValue = rawValue } + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } +} + +public struct MotionAppID: RawRepresentable, Sendable, Hashable, Comparable { + public let rawValue: Int32 + public init(rawValue: Int32) { self.rawValue = rawValue } + public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue } +} + +public struct MotionSize: Sendable, Equatable { + public var width: Double + public var height: Double + + public init(width: Double, height: Double) { + self.width = width + self.height = height + } + + public static let zero = Self(width: 0, height: 0) + var isValid: Bool { width.isFinite && height.isFinite && width >= 0 && height >= 0 } +} + +public struct MotionRect: Sendable, Equatable { + public var originX: Double + public var originY: Double + public var width: Double + public var height: Double + + public init(originX: Double, originY: Double, width: Double, height: Double) { + self.originX = originX + self.originY = originY + self.width = width + self.height = height + } + + public var maxX: Double { originX + width } + public var maxY: Double { originY + height } + public var size: MotionSize { MotionSize(width: width, height: height) } + var isValid: Bool { originX.isFinite && originY.isFinite && size.isValid && maxX.isFinite && maxY.isFinite } +} + +public struct MotionVelocity: Sendable, Equatable { + public var horizontal: Double + public var vertical: Double + public var width: Double + public var height: Double + + public init(horizontal: Double = 0, vertical: Double = 0, width: Double = 0, height: Double = 0) { + self.horizontal = horizontal + self.vertical = vertical + self.width = width + self.height = height + } + + public static let zero = Self() + var isValid: Bool { horizontal.isFinite && vertical.isFinite && width.isFinite && height.isFinite } +} + +public enum MotionError: Error, Sendable, Equatable { + case invalidGeometry + case minimumSizeExceedsScreen + case invalidTimestamp + case timestampWentBackwards + case duplicateWindow(MotionWindowID) + case invalidOpacity + case invalidVelocity + case unknownBatch +} + +struct FrameBounds: Sendable { + let screen: MotionRect + let minimumSize: MotionSize + + init(screen: MotionRect, minimumSize: MotionSize) throws { + guard screen.isValid && minimumSize.isValid else { throw MotionError.invalidGeometry } + let left = screen.originX.rounded(.up) + let bottom = screen.originY.rounded(.up) + let right = screen.maxX.rounded(.down) + let top = screen.maxY.rounded(.down) + guard right >= left && top >= bottom else { throw MotionError.invalidGeometry } + guard minimumSize.width.rounded(.up) <= right - left, + minimumSize.height.rounded(.up) <= top - bottom + else { throw MotionError.minimumSizeExceedsScreen } + self.screen = MotionRect(originX: left, originY: bottom, width: right - left, height: top - bottom) + self.minimumSize = MotionSize( + width: minimumSize.width.rounded(.up), height: minimumSize.height.rounded(.up) + ) + } + + func constrained(_ rect: MotionRect, rounded: Bool) -> MotionRect { + let width = min(screen.width, max(minimumSize.width, rounded ? rect.width.rounded() : rect.width)) + let height = min(screen.height, max(minimumSize.height, rounded ? rect.height.rounded() : rect.height)) + return MotionRect( + originX: min(screen.maxX - width, max(screen.originX, rounded ? rect.originX.rounded() : rect.originX)), + originY: min(screen.maxY - height, max(screen.originY, rounded ? rect.originY.rounded() : rect.originY)), + width: width, height: height + ) + } +} + +public struct AppWriteMetrics: Sendable, Equatable { + public static let schemaVersion = 1 + public private(set) var averageWriteDuration: Double? + public private(set) var lastTimeout: Double? + public let launchedAt: Double? + public private(set) var sampleCount: Int = 0 + + public init(launchedAt: Double? = nil) { + precondition(launchedAt == nil || launchedAt?.isFinite == true) + self.launchedAt = launchedAt + } + + public mutating func record(duration: Double, timedOut: Bool = false, at timestamp: Double) throws { + guard duration.isFinite && duration >= 0 && timestamp.isFinite else { throw MotionError.invalidTimestamp } + if let averageWriteDuration { + self.averageWriteDuration = averageWriteDuration + 0.2 * (duration - averageWriteDuration) + } else { + averageWriteDuration = duration + } + sampleCount += 1 + if timedOut { lastTimeout = timestamp } + } + + public func shouldSnap(at timestamp: Double) -> Bool { + precondition(timestamp.isFinite) + if let averageWriteDuration, averageWriteDuration > 0.040 { return true } + if let lastTimeout, timestamp - lastTimeout < 5 { return true } + if let launchedAt, timestamp - launchedAt < 1.5 { return true } + return false + } + + public func frameRate(fullRate: Double = 120) -> Double { + precondition(fullRate.isFinite && fullRate > 0) + guard let averageWriteDuration, averageWriteDuration > 1 / fullRate else { return fullRate } + return min(fullRate, 30, 1 / averageWriteDuration) + } +} diff --git a/Sources/TesseraAnimation/MotionTokens.swift b/Sources/TesseraAnimation/MotionTokens.swift new file mode 100644 index 00000000..1d0db8de --- /dev/null +++ b/Sources/TesseraAnimation/MotionTokens.swift @@ -0,0 +1,150 @@ +public enum WhimsyLevel: String, Sendable, CaseIterable { + case calm + case playful + case extra +} + +public struct MotionSettings: Sendable, Equatable { + public static let supportedSpeeds = 0.1...4.0 + public var level: WhimsyLevel + public var speedMultiplier: Double { + didSet { precondition(Self.supportedSpeeds.contains(speedMultiplier)) } + } + + public init(level: WhimsyLevel = .playful, speedMultiplier: Double = 1) { + precondition(Self.supportedSpeeds.contains(speedMultiplier)) + self.level = level + self.speedMultiplier = speedMultiplier + } +} + +public enum MotionAccent: Sendable, Equatable { + case none + case scale(from: Double) + case offset(horizontal: Double, vertical: Double) +} + +public enum MotionCurve: Sendable, Equatable { + case spring + case glide + case fade +} + +public struct MotionSpec: Sendable, Equatable { + public let duration: Double + public let bounce: Double + public let stagger: Double + public let maximumStagger: Double + public let overshootLimit: Double + public let accent: MotionAccent + public let curve: MotionCurve + public let maximumRedraws: Int? + + public var spring: SpringParameters { SpringParameters(duration: duration, bounce: bounce) } + + public func delay(for index: Int) -> Double { + precondition(index >= 0) + return min(Double(index) * stagger, maximumStagger) + } +} + +public enum MotionToken: String, Sendable, CaseIterable { + case settle + case pop + case nudge + case shuffle + case stack + case fade + case glance + case drop + + public func spec(settings: MotionSettings = MotionSettings()) -> MotionSpec { + if settings.level == .calm && self != .fade { + return MotionToken.settle.makeSpec(speed: settings.speedMultiplier, calm: true) + } + return makeSpec(speed: settings.speedMultiplier, extra: settings.level == .extra) + } + + private func makeSpec(speed: Double, calm: Bool = false, extra: Bool = false) -> MotionSpec { + let duration: Double + var bounce: Double + var stagger = 0.0 + var cap = 0.0 + var accent = MotionAccent.none + var curve = MotionCurve.spring + var redraws: Int? + switch self { + case .settle: + duration = 0.20 + bounce = 0 + curve = calm ? .spring : .glide + case .pop: + duration = 0.25 + bounce = 0.15 + accent = .scale(from: 0.98) + case .nudge: + duration = 0.18 + bounce = 0.5 + accent = .offset(horizontal: 4, vertical: 0) + case .shuffle: + duration = 0.24 + bounce = 0.1 + stagger = 0.012 + cap = 0.048 + case .stack: + duration = 0.28 + bounce = 0.12 + accent = .offset(horizontal: 2, vertical: 0) + case .fade: + duration = 0.12 + bounce = 0 + curve = .fade + case .glance: + duration = 0.15 + bounce = 0 + redraws = 10 + case .drop: + duration = 0.30 + bounce = 0.25 + } + if extra { + if self == .pop || self == .drop || self == .shuffle { bounce = min(bounce + 0.1, 0.4) } + stagger *= 1.5 + cap *= 1.5 + } + return MotionSpec( + duration: duration / speed, bounce: bounce, stagger: stagger / speed, + maximumStagger: cap / speed, overshootLimit: bounce == 0 ? 0 : min(bounce, 0.25), + accent: accent, curve: curve, maximumRedraws: redraws + ) + } +} + +public enum MotionSurface: Sendable, Equatable { + case window + case overlay + case miniMap +} + +public enum MotionBehavior: Sendable, Equatable { + case instant + case animate + case fade(duration: Double) +} + +public struct MotionPolicy: Sendable, Equatable { + public var enabled: Bool + public var reduceMotion: Bool + + public init(enabled: Bool = true, reduceMotion: Bool = false) { + self.enabled = enabled + self.reduceMotion = reduceMotion + } + + public func behavior(for surface: MotionSurface, level: WhimsyLevel = .playful) -> MotionBehavior { + guard enabled else { return .instant } + if reduceMotion { return surface == .overlay ? .fade(duration: 0.12) : .instant } + if level == .calm && surface == .window { return .instant } + return .animate + } +} diff --git a/Sources/TesseraAnimation/Spring.swift b/Sources/TesseraAnimation/Spring.swift new file mode 100644 index 00000000..d8dd9446 --- /dev/null +++ b/Sources/TesseraAnimation/Spring.swift @@ -0,0 +1,83 @@ +import Foundation + +public struct SpringParameters: Sendable, Equatable { + public let mass: Double + public let stiffness: Double + public let damping: Double + + public init(mass: Double = 1, stiffness: Double, damping: Double) { + precondition(mass.isFinite && mass > 0) + precondition(stiffness.isFinite && stiffness > 0) + precondition(damping.isFinite && damping >= 0) + self.mass = mass + self.stiffness = stiffness + self.damping = damping + } + + public init(response: Double, dampingFraction: Double) { + precondition(response.isFinite && response > 0) + precondition(dampingFraction.isFinite && dampingFraction >= 0) + let frequency = 2 * Double.pi / response + self.init(stiffness: frequency * frequency, damping: 2 * dampingFraction * frequency) + } + + public init(duration: Double, bounce: Double) { + precondition(bounce.isFinite && bounce >= 0 && bounce < 1) + self.init(response: duration, dampingFraction: 1 - bounce) + } + + public var dampingFraction: Double { damping / (2 * sqrt(mass * stiffness)) } +} + +public struct SpringState: Sendable, Equatable { + public var value: Double + public var velocity: Double + + public init(value: Double, velocity: Double = 0) { + precondition(value.isFinite && velocity.isFinite) + self.value = value + self.velocity = velocity + } + + public func advanced(to target: Double, by deltaTime: Double, using spring: SpringParameters) -> Self { + precondition(target.isFinite && deltaTime.isFinite && deltaTime >= 0) + guard deltaTime > 0 else { return self } + let frequency = sqrt(spring.stiffness / spring.mass) + let decay = spring.damping / (2 * spring.mass) + let displacement = value - target + let discriminant = frequency * frequency - decay * decay + let position: Double + let speed: Double + if abs(discriminant) <= frequency * frequency * 1e-10 { + let coefficient = velocity + decay * displacement + let envelope = exp(-decay * deltaTime) + position = envelope * (displacement + coefficient * deltaTime) + speed = envelope * (velocity - decay * coefficient * deltaTime) + } else if discriminant > 0 { + let oscillation = sqrt(discriminant) + let angle = oscillation * deltaTime + let sine = sin(angle) + let cosine = cos(angle) + let coefficient = (velocity + decay * displacement) / oscillation + let envelope = exp(-decay * deltaTime) + position = envelope * (displacement * cosine + coefficient * sine) + speed = envelope * (velocity * cosine - (decay * coefficient + displacement * oscillation) * sine) + } else { + let root = sqrt(-discriminant) + // This form avoids subtracting two nearly equal roots for heavily damped springs. + let slow = -frequency * frequency / (decay + root) + let fast = -decay - root + let slowCoefficient = (velocity - fast * displacement) / (slow - fast) + let fastCoefficient = displacement - slowCoefficient + let slowEnvelope = exp(slow * deltaTime) + let fastEnvelope = exp(fast * deltaTime) + position = slowCoefficient * slowEnvelope + fastCoefficient * fastEnvelope + speed = slow * slowCoefficient * slowEnvelope + fast * fastCoefficient * fastEnvelope + } + return Self(value: target + position, velocity: speed) + } + + public mutating func advance(to target: Double, by deltaTime: Double, using spring: SpringParameters) { + self = advanced(to: target, by: deltaTime, using: spring) + } +} diff --git a/Sources/TesseraAnimation/TesseraAnimation.docc/TesseraAnimation.md b/Sources/TesseraAnimation/TesseraAnimation.docc/TesseraAnimation.md new file mode 100644 index 00000000..10cc3fbd --- /dev/null +++ b/Sources/TesseraAnimation/TesseraAnimation.docc/TesseraAnimation.md @@ -0,0 +1,25 @@ +# ``TesseraAnimation`` + +Motion planning without window writes or a built-in clock. + +## Planning and ticking + +`FramePlanner.plan` makes an independently sampleable plan. `Animator.schedule` groups requests and carries presentation position and velocity into a new target. Feed `Animator.tick` finite, monotonically increasing timestamps in seconds. Tick once at the scheduling timestamp to apply a real window's final size before its position glides. + +Windows use a front-loaded, non-bouncy position curve. Overlay tokens use analytic springs with a smooth terminal settle. All planned rectangles stay on whole points, inside the screen, and above the requested minimum size. A minimum that cannot fit the screen throws rather than silently shrinking it. + +`MotionSettings` defaults to Playful. Calm snaps windows and removes overlay accents; Extra adds a little bounce and stagger to overlays. The supported speed multiplier is `0.1...4.0`; larger numbers mean faster motion. `MotionPolicy` overrides personality: disabled means one final frame, and Reduce Motion means instant moves or a short opacity-only overlay fade. + +## Sending frames + +Keep one `FrameCoalescer` across screen drivers. Submit frames, take ready batches, then report each batch's completion with measured write duration and timeout status. It permits one outstanding batch per app and replaces pending frames per window. Its metrics are inspectable and resettable. Copy current metrics into new `MotionRequest` values so slow, recently timed-out, or newly launched apps snap. + +Before transferring a window to another animator or reusing an identifier, call `activate(_:appID:)` and put the returned generation into every new request. Frames from the old producer are then rejected, even if its local revision is higher. `remove(_:)` retains a tombstone; call `activate` before reuse. On app exit, call `removeApp(_:)` to release busy state and reject delayed completions. + +The coalescer does not perform AX calls. Send its batches to the app's owning thread. A final frame still respects the app's in-flight write and rate cap; motion completion is not a signal that the write has completed. + +## Display links + +Create a main-actor `DisplayLinkDriver` per screen. It starts `NSScreen.displayLink` when scheduled and invalidates it when idle. The native adapter observes system Reduce Motion automatically; inject a `ReduceMotionSource` for controlled environments. Explicit Reduce Motion and the system setting are combined, so an app preference cannot weaken the system requirement. + +Deliver frames through `onFrames` and surface failures through the required `onFailure` callback. Policy changes replan active motion. Logical focus and command handling should not wait for animation or app writes. diff --git a/Sources/TesseraAnimation/TesseraAnimation.swift b/Sources/TesseraAnimation/TesseraAnimation.swift deleted file mode 100644 index 8b137891..00000000 --- a/Sources/TesseraAnimation/TesseraAnimation.swift +++ /dev/null @@ -1 +0,0 @@ - diff --git a/Tests/TesseraAnimationTests/AnimatorTests.swift b/Tests/TesseraAnimationTests/AnimatorTests.swift new file mode 100644 index 00000000..53f67ee5 --- /dev/null +++ b/Tests/TesseraAnimationTests/AnimatorTests.swift @@ -0,0 +1,244 @@ +import Testing + +@testable import TesseraAnimation + +@Suite struct AnimatorTests { + @Test func newAnimatorIsIdle() { + let animator = Animator() + #expect(animator.isIdle && animator.activeWindowIDs.isEmpty) + #expect(animator.timestamp == nil) + } + + @Test func scriptedTimelineHasGoldenOutput() throws { + var animator = Animator() + try animator.schedule([request(start: rect(0), target: rect(100))], at: 0) + var origins: [Double] = [] + var finalFlags: [Bool] = [] + for timestamp in [0, 0.05, 0.1, 0.15, 0.2] { + let output = try #require(animator.tick(at: timestamp).first) + origins.append(output.rect.originX) + finalFlags.append(output.isFinal) + } + #expect(origins == [0, 68, 94, 100, 100]) + #expect(finalFlags == [false, false, false, false, true]) + #expect(animator.isIdle) + #expect(try animator.tick(at: 1).isEmpty) + } + + @Test func tickPartitionDoesNotChangePresentation() throws { + var dense = Animator() + var sparse = Animator() + let motion = request(surface: .overlay, token: .drop, velocity: MotionVelocity(horizontal: 700)) + try dense.schedule([motion], at: 0) + try sparse.schedule([motion], at: 0) + for index in 0..<100 { _ = try dense.tick(at: Double(index) / 1000) } + #expect(try dense.tick(at: 0.1) == sparse.tick(at: 0.1)) + } + + @Test func outputsAreSortedByWindowID() throws { + var animator = Animator() + try animator.schedule([request(window: 9), request(window: 2), request(window: 4)], at: 0) + #expect(try animator.tick(at: 0).map(\.windowID) == [2, 4, 9].map { MotionWindowID(rawValue: $0) }) + } + + @Test func repeatedTickAtSameTimestampDoesNotDuplicateFrame() throws { + var animator = Animator() + try animator.schedule([request()], at: 0) + #expect(try animator.tick(at: 0).count == 1) + #expect(try animator.tick(at: 0).isEmpty) + } + + @Test func retargetKeepsPositionAndVelocity() throws { + var animator = Animator() + try animator.schedule([request(start: rect(100), target: rect(500))], at: 0) + let before = try #require(try animator.presentation(for: testWindow, at: 0.04)) + try animator.schedule([request(start: rect(0), target: rect(50))], at: 0.04) + let after = try #require(try animator.presentation(for: testWindow, at: 0.04)) + #expect(after.frame.rect == before.frame.rect) + #expect(near(after.velocity.horizontal, before.velocity.horizontal)) + let justAfter = try #require(try animator.presentation(for: testWindow, at: 0.040_001)) + #expect(justAfter.velocity.horizontal > 0) + #expect(near(justAfter.velocity.horizontal, before.velocity.horizontal, tolerance: 1)) + #expect(try animator.tick(at: 0.24).first?.rect.originX == 50) + } + + @Test func overlayRetargetCarriesSpringVelocity() throws { + var animator = Animator() + try animator.schedule([request(surface: .overlay, token: .drop)], at: 0) + let before = try #require(try animator.presentation(for: testWindow, at: 0.06)) + try animator.schedule([request(target: rect(100, 50, 200, 100), surface: .overlay, token: .drop)], at: 0.06) + let after = try #require(try animator.presentation(for: testWindow, at: 0.06)) + #expect(after.frame.rect == before.frame.rect) + #expect(near(after.velocity.horizontal, before.velocity.horizontal)) + #expect(near(after.velocity.width, before.velocity.width)) + } + + @Test func retargetUsesUnroundedInternalPosition() throws { + var animator = Animator() + try animator.schedule([request(start: rect(0), target: rect(100))], at: 0) + let before = try #require(try animator.presentation(for: testWindow, at: 0.01)) + try animator.schedule([request(start: before.frame.rect, target: rect(200))], at: 0.01) + let plan = try #require(try animator.presentation(for: testWindow, at: 0.010_001)) + #expect(near(plan.velocity.horizontal, before.velocity.horizontal, tolerance: 1)) + #expect(plan.frame.rect.originX == before.frame.rect.originX) + } + + @Test func retargetCommitsNewFinalSizeImmediately() throws { + var animator = Animator() + try animator.schedule([request()], at: 0) + try animator.schedule([request(target: rect(600, 400, 500, 300))], at: 0.05) + let output = try #require(animator.tick(at: 0.05).first) + #expect(output.rect.size == MotionSize(width: 500, height: 300)) + } + + @Test func retargetRevisionWinsAtSameTick() throws { + var animator = Animator() + try animator.schedule([request()], at: 0) + let old = try #require(animator.tick(at: 0).first) + try animator.schedule([request(target: rect(700))], at: 0) + let new = try #require(animator.tick(at: 0).first) + #expect(new.revision > old.revision) + var coalescer = FrameCoalescer() + try coalescer.submit(new) + #expect(try !coalescer.submit(old)) + } + + @Test func staggeredOverlayWaitsUntilItsStart() throws { + var animator = Animator() + try animator.schedule([request(surface: .overlay, token: .shuffle, index: 3)], at: 0) + #expect(try animator.tick(at: 0).isEmpty) + #expect(try animator.tick(at: 0.035).isEmpty) + #expect(try animator.tick(at: MotionToken.shuffle.spec().delay(for: 3)).count == 1) + #expect(!animator.isIdle) + } + + @Test func glanceEmitsAtMostTenRedrawsIncludingFinal() throws { + var animator = Animator() + try animator.schedule([request(surface: .miniMap, token: .glance)], at: 0) + var frames: [MotionFrame] = [] + for step in 0...200 { frames += try animator.tick(at: Double(step) / 1000) } + #expect(frames.count <= 10) + #expect(frames.last?.isFinal == true) + } + + @Test func disablingMidFlightFlushesFinalFrame() throws { + var animator = Animator() + try animator.schedule([request(), request(window: 2, surface: .overlay, token: .pop)], at: 0) + _ = try animator.tick(at: 0.04) + try animator.updatePolicy(MotionPolicy(enabled: false), at: 0.04) + let output = try animator.tick(at: 0.04) + #expect(output.count == 2 && output.allSatisfy(\.isFinal)) + #expect(animator.isIdle) + } + + @Test func reduceMotionChangeSnapsGeometryAndFadesOverlay() throws { + var animator = Animator() + try animator.schedule([request(), request(window: 2, surface: .overlay, token: .pop, startOpacity: 0)], at: 0) + try animator.updatePolicy(MotionPolicy(reduceMotion: true), at: 0.05) + let output = try animator.tick(at: 0.05) + #expect(output[0].isFinal) + #expect(output[1].rect == request().target) + #expect(output[1].scale == 1 && output[1].offsetHorizontal == 0) + #expect(try animator.tick(at: 0.17).allSatisfy(\.isFinal)) + #expect(animator.isIdle) + } + + @Test func speedChangeKeepsMomentumAndReplansDeadline() throws { + var animator = Animator() + try animator.schedule([request()], at: 0) + let before = try #require(try animator.presentation(for: testWindow, at: 0.05)) + try animator.updateSettings(MotionSettings(speedMultiplier: 2), at: 0.05) + let after = try #require(try animator.presentation(for: testWindow, at: 0.05)) + #expect(after.frame.rect == before.frame.rect) + #expect(near(after.velocity.horizontal, before.velocity.horizontal)) + #expect(try animator.tick(at: 0.151).first?.isFinal == true) + } + + @Test func calmChangeSnapsActiveWindows() throws { + var animator = Animator() + try animator.schedule([request()], at: 0) + try animator.updateSettings(MotionSettings(level: .calm), at: 0.05) + #expect(try animator.tick(at: 0.05).first?.isFinal == true) + } + + @Test func cancelRemovesOnlyChosenWindow() throws { + var animator = Animator() + try animator.schedule([request(), request(window: 2)], at: 0) + animator.cancel(testWindow) + #expect(animator.activeWindowIDs == [MotionWindowID(rawValue: 2)]) + #expect(try animator.presentation(for: testWindow, at: 0) == nil) + } + + @Test func cancelAllReturnsToIdle() throws { + var animator = Animator() + try animator.schedule([request()], at: 0) + animator.cancelAll() + #expect(animator.isIdle) + #expect(try animator.tick(at: 0).isEmpty) + } + + @Test func badRequestBatchDoesNotPartiallySchedule() throws { + var animator = Animator() + #expect(throws: MotionError.invalidGeometry) { + try animator.schedule([request(), request(window: 2, start: rect(.nan))], at: 0) + } + #expect(animator.isIdle && animator.timestamp == nil) + } + + @Test func duplicateWindowBatchIsRejected() { + var animator = Animator() + #expect(throws: MotionError.duplicateWindow(testWindow)) { + try animator.schedule([request(), request()], at: 0) + } + #expect(animator.isIdle) + } + + @Test func timestampsMustBeMonotonic() throws { + var animator = Animator() + try animator.schedule([request()], at: 1) + #expect(throws: MotionError.timestampWentBackwards) { try animator.tick(at: 0) } + #expect(throws: MotionError.timestampWentBackwards) { try animator.schedule([request()], at: 0) } + #expect(throws: MotionError.timestampWentBackwards) { + try animator.updatePolicy(MotionPolicy(enabled: false), at: 0) + } + #expect(animator.policy.enabled) + } + + @Test func nonfiniteTimestampDoesNotMutateAnimator() { + var animator = Animator() + #expect(throws: MotionError.invalidTimestamp) { try animator.tick(at: .nan) } + #expect(animator.timestamp == nil) + } + + @Test func delayedFinalTickStillCompletesExactly() throws { + var animator = Animator() + try animator.schedule([request()], at: 0) + let output = try #require(animator.tick(at: 100).first) + #expect(output.rect == request().target && output.isFinal) + #expect(animator.isIdle) + } + + @Test func offPolicyEmitsOnlyOneFramePerWindow() throws { + var animator = Animator(policy: MotionPolicy(enabled: false)) + try animator.schedule([request(), request(window: 2, surface: .overlay, token: .shuffle, index: 10)], at: 0) + #expect(try animator.tick(at: 0).count == 2) + #expect(try animator.tick(at: 1).isEmpty) + } + + @Test func animatorAndCoalescerHaveDeterministicScriptedOutput() throws { + var animator = Animator() + var coalescer = FrameCoalescer(fullFrameRate: 60) + try animator.schedule([request(window: 2), request(window: 1)], at: 0) + var batches: [FrameBatch] = [] + for timestamp in [0, 0.05, 0.1, 0.2] { + for output in try animator.tick(at: timestamp) { try coalescer.submit(output) } + let batch = try #require(coalescer.takeReady(at: timestamp).first) + batches.append(batch) + try coalescer.complete(batch, duration: 0.001, at: timestamp + 0.001) + } + #expect(batches.count == 4) + #expect(batches.allSatisfy { $0.frames.count == 2 }) + #expect(batches.last?.frames.allSatisfy(\.isFinal) == true) + #expect(animator.isIdle && coalescer.pendingCount == 0 && coalescer.inFlightCount == 0) + } +} diff --git a/Tests/TesseraAnimationTests/DisplayLinkDriverTests.swift b/Tests/TesseraAnimationTests/DisplayLinkDriverTests.swift new file mode 100644 index 00000000..ad8b4ee4 --- /dev/null +++ b/Tests/TesseraAnimationTests/DisplayLinkDriverTests.swift @@ -0,0 +1,147 @@ +import Testing + +@testable import TesseraAnimation + +@MainActor +final class TestDisplayLink: DisplayLinkSource { + var isRunning: Bool { callback != nil } + var startCount = 0 + var stopCount = 0 + var callback: (@MainActor (Double) -> Void)? + + func start(tick: @escaping @MainActor (Double) -> Void) { + startCount += 1 + callback = tick + } + + func stop() { + if isRunning { stopCount += 1 } + callback = nil + } + + func fire(at timestamp: Double) { callback?(timestamp) } +} + +@Suite @MainActor struct DisplayLinkDriverTests { + @Test func idleDriverDoesNotStartLink() { + let source = TestDisplayLink() + let driver = DisplayLinkDriver( + source: source, onFrames: { _ in }, onFailure: { _ in Issue.record("Unexpected failure") }) + #expect(!driver.isRunning && source.startCount == 0) + } + + @Test func schedulingStartsLinkAndCompletionStopsIt() throws { + let source = TestDisplayLink() + var output: [MotionFrame] = [] + let driver = DisplayLinkDriver( + source: source, onFrames: { output += $0 }, onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()], at: 0) + #expect(driver.isRunning && source.startCount == 1) + source.fire(at: 0) + source.fire(at: 0.2) + #expect(output.count == 2 && output.last?.isFinal == true) + #expect(!driver.isRunning && source.stopCount == 1) + } + + @Test func retargetDoesNotStartSecondLink() throws { + let source = TestDisplayLink() + let driver = DisplayLinkDriver( + source: source, onFrames: { _ in }, onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()], at: 0) + try driver.schedule([request(target: rect(700))], at: 0.05) + #expect(source.startCount == 1) + } + + @Test func newWorkRestartsCompletedLink() throws { + let source = TestDisplayLink() + let driver = DisplayLinkDriver( + source: source, onFrames: { _ in }, onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()], at: 0) + source.fire(at: 0.2) + try driver.schedule([request()], at: 1) + #expect(source.startCount == 2 && driver.isRunning) + } + + @Test func policyOffStillDeliversOneFinalFrame() throws { + let source = TestDisplayLink() + var output: [MotionFrame] = [] + let driver = DisplayLinkDriver( + source: source, onFrames: { output += $0 }, onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()], at: 0) + try driver.updatePolicy(MotionPolicy(enabled: false), at: 0) + source.fire(at: 0) + #expect(output.count == 1 && output[0].isFinal) + #expect(!driver.isRunning) + } + + @Test func cancelLastWindowStopsSource() throws { + let source = TestDisplayLink() + let driver = DisplayLinkDriver( + source: source, onFrames: { _ in }, onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()], at: 0) + driver.cancel(testWindow) + #expect(!driver.isRunning && driver.animator.isIdle) + } + + @Test func stopCancelsPendingWork() throws { + let source = TestDisplayLink() + let driver = DisplayLinkDriver( + source: source, onFrames: { _ in }, onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()], at: 0) + driver.stop() + #expect(!driver.isRunning && driver.animator.isIdle) + } + + @Test func clockFailureIsSurfacedAndStopsLink() throws { + let source = TestDisplayLink() + var errors: [MotionError] = [] + let driver = DisplayLinkDriver(source: source, onFrames: { _ in }, onFailure: { errors.append($0) }) + try driver.schedule([request()], at: 1) + source.fire(at: 0) + #expect(errors == [.timestampWentBackwards]) + #expect(!driver.isRunning && driver.animator.isIdle) + } + + @Test func deinitializationInvalidatesSource() throws { + let source = TestDisplayLink() + var driver: DisplayLinkDriver? = DisplayLinkDriver( + source: source, onFrames: { _ in }, onFailure: { _ in Issue.record("Unexpected failure") }) + try #require(driver).schedule([request()], at: 0) + driver = nil + #expect(!source.isRunning) + } + + @Test func settingsChangeUsesSameSource() throws { + let source = TestDisplayLink() + var output: [MotionFrame] = [] + let driver = DisplayLinkDriver( + source: source, onFrames: { output += $0 }, onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()], at: 0) + try driver.updateSettings(MotionSettings(speedMultiplier: 2), at: 0) + source.fire(at: 0.1) + #expect(source.startCount == 1) + #expect(output.first?.isFinal == true && !driver.isRunning) + } + + @Test func frameCallbackCanSafelyScheduleAnotherTransition() throws { + let source = TestDisplayLink() + var driver: DisplayLinkDriver? + var count = 0 + driver = DisplayLinkDriver( + source: source, + onFrames: { frames in + count += 1 + if frames.first?.isFinal == true && count == 1 { + do { try driver?.schedule([request(window: 2)], at: 0.2) } catch { + Issue.record("Could not schedule callback motion: \(error)") + } + } + }, onFailure: { _ in Issue.record("Unexpected failure") }) + try #require(driver).schedule([request()], at: 0) + source.fire(at: 0.2) + #expect(source.isRunning && source.startCount == 2) + source.fire(at: 0.4) + #expect(count == 2 && !source.isRunning) + driver = nil + } +} diff --git a/Tests/TesseraAnimationTests/FrameCoalescerTests.swift b/Tests/TesseraAnimationTests/FrameCoalescerTests.swift new file mode 100644 index 00000000..ac1c7558 --- /dev/null +++ b/Tests/TesseraAnimationTests/FrameCoalescerTests.swift @@ -0,0 +1,268 @@ +import Testing + +@testable import TesseraAnimation + +@Suite struct AppWriteMetricsTests { + @Test func unknownAppCanAnimateAtFullRate() { + let metrics = AppWriteMetrics() + #expect(!metrics.shouldSnap(at: 0)) + #expect(metrics.frameRate() == 120) + #expect(metrics.sampleCount == 0) + #expect(metrics.averageWriteDuration == nil) + #expect(AppWriteMetrics.schemaVersion == 1) + } + + @Test func firstMeasurementSeedsAverage() throws { + let metrics = try measured(0.02) + #expect(metrics.averageWriteDuration == 0.02) + #expect(metrics.sampleCount == 1) + } + + @Test func averageUsesLatestMeasurementWithoutForgettingHistory() throws { + var metrics = try measured(0.01) + try metrics.record(duration: 0.06, at: 1) + #expect(near(metrics.averageWriteDuration ?? -1, 0.02)) + #expect(metrics.sampleCount == 2) + } + + @Test func fortyMillisecondsIsStrictThreshold() throws { + #expect(try !measured(0.040).shouldSnap(at: 0)) + #expect(try measured(0.040_001).shouldSnap(at: 0)) + } + + @Test func timeoutExpiresAfterFiveSeconds() throws { + let metrics = try measured(0.001, timeout: true, at: 10) + #expect(metrics.shouldSnap(at: 14.999)) + #expect(!metrics.shouldSnap(at: 15)) + } + + @Test func successDoesNotEraseRecentTimeout() throws { + var metrics = try measured(0.001, timeout: true, at: 10) + try metrics.record(duration: 0.001, at: 11) + #expect(metrics.lastTimeout == 10) + #expect(metrics.shouldSnap(at: 12)) + } + + @Test func launchGraceIsOneAndHalfSeconds() { + let metrics = AppWriteMetrics(launchedAt: 10) + #expect(metrics.shouldSnap(at: 11.499)) + #expect(!metrics.shouldSnap(at: 11.5)) + } + + @Test func fastAppUsesFullRate() throws { #expect(try measured(0.001).frameRate(fullRate: 60) == 60) } + + @Test func slowerAppIsCappedAtThirtyHz() throws { + #expect(try measured(0.02).frameRate(fullRate: 120) == 30) + } + + @Test func verySlowAppDoesNotExceedMeasuredCapacity() throws { + #expect(try measured(0.1).frameRate() == 10) + } + + @Test func capNeverExceedsDisplayRate() throws { + #expect(try measured(0.02).frameRate(fullRate: 20) == 20) + } + + @Test func zeroLatencyIsValid() throws { + #expect(try measured(0).frameRate() == 120) + } + + @Test func invalidDurationIsRejected() { + #expect(throws: MotionError.invalidTimestamp) { try measured(-0.1) } + #expect(throws: MotionError.invalidTimestamp) { try measured(.nan) } + } + + @Test func invalidMeasurementTimeIsRejected() { + #expect(throws: MotionError.invalidTimestamp) { try measured(0.01, at: .infinity) } + } + + @Test func badMeasurementLeavesMetricsUnchanged() throws { + var metrics = try measured(0.01) + let before = metrics + #expect(throws: MotionError.invalidTimestamp) { try metrics.record(duration: -1, timedOut: true, at: 1) } + #expect(metrics == before) + } +} + +@Suite struct FrameCoalescerTests { + @Test func emptyCoalescerReturnsNoWork() throws { + var coalescer = FrameCoalescer() + #expect(try coalescer.takeReady(at: 0).isEmpty) + #expect(coalescer.pendingCount == 0 && coalescer.inFlightCount == 0) + } + + @Test func newestFrameWinsBeforeDispatch() throws { + var coalescer = FrameCoalescer() + for step in 0..<100 { try coalescer.submit(frame(at: Double(step) / 100, origin: Double(step))) } + #expect(coalescer.pendingCount == 1) + let batch = try #require(coalescer.takeReady(at: 1).first) + #expect(batch.frames.count == 1) + #expect(batch.frames[0].rect.originX == 99) + } + + @Test func eachWindowHasIndependentLatestFrame() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame(window: 2)) + try coalescer.submit(frame(window: 1)) + let batch = try #require(coalescer.takeReady(at: 0).first) + #expect(batch.frames.map(\.windowID) == [MotionWindowID(rawValue: 1), MotionWindowID(rawValue: 2)]) + } + + @Test func appBatchesAreSortedAndIndependent() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame(window: 2, app: 2)) + try coalescer.submit(frame(window: 1, app: 1)) + let batches = try coalescer.takeReady(at: 0) + #expect(batches.map(\.appID) == [MotionAppID(rawValue: 1), MotionAppID(rawValue: 2)]) + #expect(coalescer.inFlightCount == 2) + } + + @Test func slowAppOnlyRetainsLatestWhileBusy() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + let first = try #require(coalescer.takeReady(at: 0).first) + for step in 1...10 { try coalescer.submit(frame(at: Double(step) / 100, origin: Double(step))) } + #expect(try coalescer.takeReady(at: 0.1).isEmpty) + #expect(coalescer.pendingCount == 1) + try coalescer.complete(first, duration: 0.1, at: 0.1) + let latest = try #require(coalescer.takeReady(at: 0.1).first) + #expect(latest.frames[0].rect.originX == 10) + } + + @Test func busyAppDoesNotBlockAnotherApp() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + _ = try coalescer.takeReady(at: 0) + try coalescer.submit(frame(at: 0.1)) + try coalescer.submit(frame(window: 2, app: 2, at: 0.1)) + let batches = try coalescer.takeReady(at: 0.1) + #expect(batches.count == 1 && batches[0].appID == MotionAppID(rawValue: 2)) + } + + @Test func oldTimestampsCannotReplaceNewFrames() throws { + var coalescer = FrameCoalescer() + #expect(try coalescer.submit(frame(at: 1))) + #expect(try !coalescer.submit(frame(at: 0.9))) + #expect(try !coalescer.submit(frame(at: 1))) + } + + @Test func oldRevisionCannotReplaceRetargetedFrame() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame(at: 1, revision: 2, origin: 200)) + #expect(try !coalescer.submit(frame(at: 10, revision: 1, origin: 10))) + let batch = try #require(coalescer.takeReady(at: 10).first) + #expect(batch.frames[0].rect.originX == 200) + } + + @Test func newRevisionWinsEvenAtSameTimestamp() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame(at: 1, revision: 1)) + #expect(try coalescer.submit(frame(at: 1, revision: 2))) + } + + @Test func dispatchedFrameCannotBeRequeuedByStaleProducer() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame(at: 1)) + let batch = try #require(coalescer.takeReady(at: 1).first) + try coalescer.complete(batch, duration: 0, at: 1) + #expect(try !coalescer.submit(frame(at: 0.9))) + #expect(coalescer.pendingCount == 0) + } + + @Test func rateCapUsesDisplayRateForFastApps() throws { + var coalescer = FrameCoalescer(fullFrameRate: 60) + try coalescer.submit(frame()) + let first = try #require(coalescer.takeReady(at: 0).first) + try coalescer.complete(first, duration: 0.001, at: 0.001) + try coalescer.submit(frame(at: 0.005)) + #expect(try coalescer.takeReady(at: 0.01).isEmpty) + #expect(try coalescer.takeReady(at: 1.0 / 60).count == 1) + } + + @Test func slowRateCapHasThirtyHzBoundary() throws { + var coalescer = FrameCoalescer() + coalescer.setMetrics(try measured(0.02), for: testApp) + try coalescer.submit(frame()) + let first = try #require(coalescer.takeReady(at: 0).first) + try coalescer.complete(first, duration: 0.02, at: 0.02) + try coalescer.submit(frame(at: 0.021)) + #expect(try coalescer.takeReady(at: 0.03).isEmpty) + #expect(try coalescer.takeReady(at: 1.0 / 30).count == 1) + } + + @Test func finalFrameWaitsForCapacityButIsNotLost() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + let first = try #require(coalescer.takeReady(at: 0).first) + try coalescer.submit(frame(at: 0.2, final: true)) + #expect(try coalescer.takeReady(at: 0.2).isEmpty) + try coalescer.complete(first, duration: 0.2, at: 0.2) + let last = try #require(coalescer.takeReady(at: 0.2).first) + #expect(last.frames[0].isFinal) + } + + @Test func futureFrameIsNotDispatchedEarly() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame(at: 2)) + #expect(try coalescer.takeReady(at: 1).isEmpty) + #expect(try coalescer.takeReady(at: 2).count == 1) + } + + @Test func completionUpdatesInspectableMetrics() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + let batch = try #require(coalescer.takeReady(at: 0).first) + try coalescer.complete(batch, duration: 0.05, timedOut: true, at: 0.05) + let metrics = try #require(coalescer.metricsSnapshot[testApp]) + #expect(metrics.averageWriteDuration == 0.05 && metrics.lastTimeout == 0.05) + #expect(coalescer.inFlightCount == 0) + } + + @Test func metricsCanBeReset() throws { + var coalescer = FrameCoalescer() + coalescer.setMetrics(try measured(0.1), for: testApp) + coalescer.resetMetrics(for: testApp) + #expect(coalescer.metricsSnapshot[testApp] == nil) + } + + @Test func invalidCompletionDoesNotReleaseApp() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + let batch = try #require(coalescer.takeReady(at: 0).first) + #expect(throws: MotionError.invalidTimestamp) { try coalescer.complete(batch, duration: -1, at: 1) } + #expect(coalescer.inFlightCount == 1) + try coalescer.complete(batch, duration: 0.01, at: 1) + } + + @Test func duplicateCompletionIsRejected() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + let batch = try #require(coalescer.takeReady(at: 0).first) + try coalescer.complete(batch, duration: 0, at: 0) + #expect(throws: MotionError.unknownBatch) { try coalescer.complete(batch, duration: 0, at: 0) } + } + + @Test func removingWindowRejectsLateProducerFrames() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame(at: 10)) + coalescer.remove(testWindow) + #expect(coalescer.pendingCount == 0) + #expect(try !coalescer.submit(frame(at: 11))) + #expect(coalescer.generation(for: testWindow) == nil) + let generation = coalescer.activate(testWindow, appID: testApp) + #expect(try coalescer.submit(frame(at: 12, generation: generation))) + #expect(try !coalescer.submit(frame(at: 13))) + } + + @Test func backwardDispatchTimeIsRejected() throws { + var coalescer = FrameCoalescer() + _ = try coalescer.takeReady(at: 1) + #expect(throws: MotionError.timestampWentBackwards) { try coalescer.takeReady(at: 0) } + } + + @Test func nonfiniteTimesAreRejected() throws { + var coalescer = FrameCoalescer() + #expect(throws: MotionError.invalidTimestamp) { try coalescer.takeReady(at: .nan) } + #expect(throws: MotionError.invalidTimestamp) { try coalescer.submit(frame(at: .infinity)) } + } +} diff --git a/Tests/TesseraAnimationTests/FramePlannerTests.swift b/Tests/TesseraAnimationTests/FramePlannerTests.swift new file mode 100644 index 00000000..8b0ff8f9 --- /dev/null +++ b/Tests/TesseraAnimationTests/FramePlannerTests.swift @@ -0,0 +1,273 @@ +import Testing + +@testable import TesseraAnimation + +@Suite struct FramePlannerTests { + @Test func windowCommitsFinalSizeAtFrameZero() throws { + let plan = try FramePlanner.plan(request(), at: 0) + let initial = try plan.sample(at: 0) + #expect(initial.frame.rect == rect(10, 20, 400, 200)) + #expect(initial.velocity.width == 0 && initial.velocity.height == 0) + } + + @Test func glideIsFrontLoaded() throws { + let plan = try FramePlanner.plan(request(start: rect(0), target: rect(100)), at: 0) + let first = try plan.sample(at: 1.0 / 60).frame.rect.originX + #expect(first >= 25 && first <= 40) + #expect(try plan.sample(at: 0.12).frame.rect.originX >= 90) + } + + @Test func finalFrameReachesExactTarget() throws { + let plan = try FramePlanner.plan(request(), at: 10) + let sample = try plan.sample(at: 10.2) + #expect(sample.frame.rect == request().target) + #expect(sample.frame.isFinal) + #expect(sample.velocity == .zero) + } + + @Test func allFrameCoordinatesAreWholePoints() throws { + let plan = try FramePlanner.plan( + request(start: rect(2.6, 3.8, 70.1, 90.8), target: rect(455.2, 233.9, 190.7, 150.2)), at: 0) + for step in 0...100 { + let sample = try plan.sample(at: Double(step) / 500).frame.rect + #expect(sample.originX == sample.originX.rounded()) + #expect(sample.originY == sample.originY.rounded()) + #expect(sample.width == sample.width.rounded()) + #expect(sample.height == sample.height.rounded()) + } + } + + @Test func minimumSizeIsRoundedUp() throws { + let plan = try FramePlanner.plan( + request(target: rect(500, 300, 2, 3), minimum: MotionSize(width: 120.1, height: 80.8)), at: 0) + for step in 0...50 { + let sample = try plan.sample(at: Double(step) / 100).frame.rect + #expect(sample.width >= 121 && sample.height >= 81) + } + } + + @Test func overlayNeverShrinksBelowMinimumDuringOvershoot() throws { + let plan = try FramePlanner.plan( + request( + start: rect(50, 50, 800, 600), target: rect(60, 60, 100, 80), + minimum: MotionSize(width: 120, height: 100), surface: .overlay, token: .drop), at: 0) + for step in 0...100 { + let sample = try plan.sample(at: Double(step) / 300).frame.rect + #expect(sample.width >= 120 && sample.height >= 100) + } + } + + @Test func overshootCannotCrossAnyScreenEdge() throws { + let screen = rect(-800, -500, 800, 500) + let plan = try FramePlanner.plan( + request( + start: rect(-700, -400), target: rect(-20, -20, 600, 400), screen: screen, surface: .overlay, + token: .drop, velocity: MotionVelocity(horizontal: 50_000, vertical: 50_000)), at: 0) + for step in 0...100 { + let sample = try plan.sample(at: Double(step) / 300).frame.rect + #expect(sample.originX >= screen.originX && sample.originY >= screen.originY) + #expect(sample.maxX <= screen.maxX && sample.maxY <= screen.maxY) + } + } + + @Test func oversizedTargetFitsWithinScreen() throws { + let plan = try FramePlanner.plan(request(target: rect(-100, -100, 10_000, 10_000)), at: 0) + #expect(try plan.sample(at: 0.2).frame.rect == testScreen) + } + + @Test func fractionalScreenEdgesRoundInward() throws { + let screen = rect(-20.8, -10.2, 100.7, 80.8) + let plan = try FramePlanner.plan(request(target: rect(-100, -100, 500, 500), screen: screen), at: 0) + #expect(try plan.sample(at: 1).frame.rect == rect(-20, -10, 99, 80)) + } + + @Test func impossibleMinimumSurfacesError() { + #expect(throws: MotionError.minimumSizeExceedsScreen) { + try FramePlanner.plan(request(minimum: MotionSize(width: 1921, height: 1)), at: 0) + } + } + + @Test func inwardRoundingCanMakeMinimumImpossible() { + #expect(throws: MotionError.minimumSizeExceedsScreen) { + try FramePlanner.plan( + request(screen: rect(0.1, 0.1, 10, 10), minimum: MotionSize(width: 9.1, height: 9.1)), at: 0) + } + } + + @Test func invalidStartGeometryIsRejected() { + #expect(throws: MotionError.invalidGeometry) { try FramePlanner.plan(request(start: rect(.nan)), at: 0) } + } + + @Test func negativeSizeIsRejected() { + #expect(throws: MotionError.invalidGeometry) { + try FramePlanner.plan(request(target: rect(0, 0, -1, 2)), at: 0) + } + } + + @Test func invalidScreenIsRejected() { + #expect(throws: MotionError.invalidGeometry) { try FramePlanner.plan(request(screen: rect(.infinity)), at: 0) } + } + + @Test func invalidMinimumIsRejected() { + #expect(throws: MotionError.invalidGeometry) { + try FramePlanner.plan(request(minimum: MotionSize(width: .nan, height: 0)), at: 0) + } + } + + @Test func invalidTimestampIsRejected() { + #expect(throws: MotionError.invalidTimestamp) { try FramePlanner.plan(request(), at: .nan) } + } + + @Test func invalidSampleTimeIsRejected() throws { + let plan = try FramePlanner.plan(request(), at: 0) + #expect(throws: MotionError.invalidTimestamp) { try plan.sample(at: .infinity) } + } + + @Test func invalidOpacityIsRejected() { + #expect(throws: MotionError.invalidOpacity) { try FramePlanner.plan(request(startOpacity: 1.1), at: 0) } + } + + @Test func invalidVelocityIsRejected() { + #expect(throws: MotionError.invalidVelocity) { + try FramePlanner.plan(request(velocity: MotionVelocity(horizontal: .infinity)), at: 0) + } + } + + @Test func negativeStaggerIndexIsRejected() { + #expect(throws: MotionError.invalidGeometry) { try FramePlanner.plan(request(index: -1), at: 0) } + } + + @Test(arguments: MotionToken.allCases) + func realWindowsNeverBounceEvenWithOverlayToken(_ token: MotionToken) throws { + let plan = try FramePlanner.plan(request(start: rect(100), target: rect(500), token: token, index: 5), at: 0) + #expect(plan.startTime == 0) + #expect(plan.spec.bounce == 0) + var previous = 100.0 + for step in 0...100 { + let sample = try plan.sample(at: Double(step) / 500).frame + #expect(sample.rect.originX >= previous && sample.rect.originX <= 500) + #expect(sample.scale == 1 && sample.offsetHorizontal == 0) + previous = sample.rect.originX + } + } + + @Test func windowVelocityCannotCauseOvershoot() throws { + let plan = try FramePlanner.plan( + request(start: rect(0), target: rect(100), velocity: MotionVelocity(horizontal: 50_000)), at: 0) + for step in 0...100 { + #expect(try plan.sample(at: Double(step) / 500).frame.rect.originX <= 100) + } + } + + @Test func overlayOvershootIsClampedByToken() throws { + let plan = try FramePlanner.plan( + request( + start: rect(100), target: rect(500), surface: .overlay, token: .drop, + velocity: MotionVelocity(horizontal: 50_000)), at: 0) + let limit = 400 * plan.spec.overshootLimit + for step in 0...100 { + let sample = try plan.sample(at: Double(step) / 300).frame.rect.originX + #expect(sample >= 100 - limit && sample <= 500 + limit) + } + } + + @Test func dropCarriesReleaseVelocity() throws { + let moving = try FramePlanner.plan( + request(surface: .overlay, token: .drop, velocity: MotionVelocity(horizontal: 1000)), at: 0) + let still = try FramePlanner.plan(request(surface: .overlay, token: .drop), at: 0) + #expect(try moving.sample(at: 0).velocity.horizontal == 1000) + #expect(try moving.sample(at: 0.01).frame.rect.originX > still.sample(at: 0.01).frame.rect.originX) + } + + @Test func popAccentReturnsToIdentity() throws { + let plan = try FramePlanner.plan(request(surface: .overlay, token: .pop), at: 0) + #expect(try plan.sample(at: 0).frame.scale == 0.98) + #expect(try plan.sample(at: 0.25).frame.scale == 1) + } + + @Test func nudgeIsLimitedToFourPoints() throws { + let plan = try FramePlanner.plan(request(surface: .overlay, token: .nudge), at: 0) + #expect(try plan.sample(at: 0).frame.offsetHorizontal == 4) + for step in 0...100 { + #expect(try abs(plan.sample(at: Double(step) / 500).frame.offsetHorizontal) <= 4) + } + #expect(try plan.sample(at: 0.18).frame.offsetHorizontal == 0) + } + + @Test func stackOffsetIsPerLayer() throws { + let plan = try FramePlanner.plan(request(surface: .overlay, token: .stack, index: 3), at: 0) + #expect(try plan.sample(at: 0).frame.offsetHorizontal == 6) + #expect(try plan.sample(at: 0.28).frame.offsetHorizontal == 0) + } + + @Test func shuffleDelaysAreCapped() throws { + let plan = try FramePlanner.plan(request(surface: .overlay, token: .shuffle, index: 20), at: 0) + #expect(plan.startTime == 0.048) + #expect(try plan.sample(at: 0).frame.rect == request().start) + } + + @Test func motionOffEndsEverythingInOneFrame() throws { + let plan = try FramePlanner.plan( + request(surface: .overlay, token: .shuffle, index: 20, targetOpacity: 0), at: 0, + policy: MotionPolicy(enabled: false)) + let sample = try plan.sample(at: 0) + #expect(sample.frame.rect == request().target) + #expect(sample.frame.opacity == 0) + #expect(sample.frame.isFinal) + #expect(sample.frame.scale == 1 && sample.frame.offsetHorizontal == 0) + } + + @Test func reduceMotionSnapsWindowsImmediately() throws { + let plan = try FramePlanner.plan(request(), at: 0, policy: MotionPolicy(reduceMotion: true)) + #expect(try plan.sample(at: 0).frame.isFinal) + #expect(try plan.sample(at: 0).frame.rect == request().target) + } + + @Test func reduceMotionUsesGentleOpacityOnly() throws { + let plan = try FramePlanner.plan( + request(surface: .overlay, token: .shuffle, index: 10, startOpacity: 0), at: 0, + policy: MotionPolicy(reduceMotion: true), settings: MotionSettings(level: .extra, speedMultiplier: 0.1)) + #expect(plan.duration == 0.12 && plan.startTime == 0) + for step in 0...12 { + let sample = try plan.sample(at: Double(step) / 100) + #expect(sample.frame.rect == request().target) + #expect(sample.frame.scale == 1 && sample.frame.offsetHorizontal == 0) + #expect((0...1).contains(sample.frame.opacity)) + #expect(sample.velocity == .zero) + } + #expect(try near(plan.sample(at: 0.06).frame.opacity, 0.75)) + } + + @Test func normalFadeAlsoOnlyChangesOpacity() throws { + let plan = try FramePlanner.plan(request(surface: .overlay, token: .fade, startOpacity: 0), at: 0) + #expect(try plan.sample(at: 0.06).frame.rect == request().target) + #expect(try near(plan.sample(at: 0.06).frame.opacity, 0.75)) + } + + @Test func slowAppSnapsButItsOverlayStillMoves() throws { + let metrics = try measured(0.041) + let window = try FramePlanner.plan(request(metrics: metrics), at: 0) + let overlay = try FramePlanner.plan(request(surface: .overlay, token: .pop, metrics: metrics), at: 0) + #expect(window.duration == 0) + #expect(overlay.duration == 0.25) + } + + @Test func recentlyTimedOutAppSnaps() throws { + let plan = try FramePlanner.plan(request(metrics: measured(0.001, timeout: true, at: 10)), at: 14.9) + #expect(plan.duration == 0) + } + + @Test func recentlyLaunchedAppSnaps() throws { + let metrics = AppWriteMetrics(launchedAt: 10) + #expect(try FramePlanner.plan(request(metrics: metrics), at: 11).duration == 0) + #expect(try FramePlanner.plan(request(metrics: metrics), at: 11.5).duration == 0.2) + } + + @Test func calmWindowsSnapAndOverlaySpringsAreQuiet() throws { + let settings = MotionSettings(level: .calm) + let window = try FramePlanner.plan(request(), at: 0, settings: settings) + let overlay = try FramePlanner.plan(request(surface: .overlay, token: .nudge), at: 0, settings: settings) + #expect(window.duration == 0) + #expect(overlay.spec.bounce == 0 && overlay.spec.accent == .none) + } +} diff --git a/Tests/TesseraAnimationTests/MotionTokenTests.swift b/Tests/TesseraAnimationTests/MotionTokenTests.swift new file mode 100644 index 00000000..5ad3d24a --- /dev/null +++ b/Tests/TesseraAnimationTests/MotionTokenTests.swift @@ -0,0 +1,167 @@ +import Testing + +@testable import TesseraAnimation + +@Suite struct MotionTokenTests { + @Test func defaultsArePlayfulAndNormalSpeed() { + #expect(MotionSettings().level == .playful) + #expect(MotionSettings().speedMultiplier == 1) + } + + @Test func settleHasNoBounce() { + let spec = MotionToken.settle.spec() + #expect(spec.duration == 0.20) + #expect(spec.bounce == 0) + #expect(spec.overshootLimit == 0) + #expect(spec.curve == .glide) + } + + @Test func popIsBriskWithScaleAccent() { + let spec = MotionToken.pop.spec() + #expect(spec.duration == 0.25) + #expect(spec.bounce == 0.15) + #expect(spec.accent == .scale(from: 0.98)) + } + + @Test func nudgeHasFourPointRubberBand() { + let spec = MotionToken.nudge.spec() + #expect(spec.duration == 0.18) + #expect(spec.bounce == 0.5) + #expect(spec.accent == .offset(horizontal: 4, vertical: 0)) + } + + @Test func shuffleUsesTwelveMillisecondStagger() { + let spec = MotionToken.shuffle.spec() + #expect(spec.duration == 0.24) + #expect(spec.bounce == 0.1) + #expect(spec.stagger == 0.012) + #expect(spec.maximumStagger == 0.048) + } + + @Test func staggerStartsFirstItemImmediately() { #expect(MotionToken.shuffle.spec().delay(for: 0) == 0) } + + @Test func staggerCapsLateItems() { + let spec = MotionToken.shuffle.spec() + #expect(spec.delay(for: 2) == 0.024) + #expect(spec.delay(for: 4) == 0.048) + #expect(spec.delay(for: 10_000) == 0.048) + } + + @Test func stackHasLayerOffset() { + let spec = MotionToken.stack.spec() + #expect(spec.duration == 0.28) + #expect(spec.bounce == 0.12) + #expect(spec.accent == .offset(horizontal: 2, vertical: 0)) + } + + @Test func fadeIsOpacityCurve() { + let spec = MotionToken.fade.spec() + #expect(spec.duration == 0.12) + #expect(spec.bounce == 0) + #expect(spec.curve == .fade) + #expect(spec.accent == .none) + } + + @Test func glanceLimitsRedraws() { + let spec = MotionToken.glance.spec() + #expect(spec.duration == 0.15) + #expect(spec.bounce == 0) + #expect(spec.maximumRedraws == 10) + } + + @Test func dropEarnsBounce() { + let spec = MotionToken.drop.spec() + #expect(spec.duration == 0.30) + #expect(spec.bounce == 0.25) + } + + @Test(arguments: MotionToken.allCases) + func speedDoublesWithoutChangingPersonality(_ token: MotionToken) { + let normal = token.spec() + let faster = token.spec(settings: MotionSettings(speedMultiplier: 2)) + #expect(near(faster.duration, normal.duration / 2)) + #expect(near(faster.stagger, normal.stagger / 2)) + #expect(near(faster.maximumStagger, normal.maximumStagger / 2)) + #expect(faster.bounce == normal.bounce) + #expect(faster.accent == normal.accent) + #expect(faster.overshootLimit == normal.overshootLimit) + } + + @Test func slowerSpeedLengthensMotion() { + #expect(MotionToken.pop.spec(settings: MotionSettings(speedMultiplier: 0.5)).duration == 0.5) + } + + @Test(arguments: MotionToken.allCases.filter { $0 != .fade }) + func calmUsesSettleWithoutAccents(_ token: MotionToken) { + let spec = token.spec(settings: MotionSettings(level: .calm)) + #expect(spec.duration == 0.2) + #expect(spec.bounce == 0) + #expect(spec.stagger == 0) + #expect(spec.accent == .none) + #expect(spec.curve == .spring) + } + + @Test func calmKeepsFadeShort() { + #expect(MotionToken.fade.spec(settings: MotionSettings(level: .calm)).duration == 0.12) + } + + @Test func extraAddsOnlySelectedBounce() { + let settings = MotionSettings(level: .extra) + #expect(near(MotionToken.pop.spec(settings: settings).bounce, 0.25)) + #expect(near(MotionToken.drop.spec(settings: settings).bounce, 0.35)) + #expect(near(MotionToken.shuffle.spec(settings: settings).bounce, 0.2)) + #expect(MotionToken.nudge.spec(settings: settings).bounce == 0.5) + #expect(MotionToken.stack.spec(settings: settings).bounce == 0.12) + #expect(MotionToken.settle.spec(settings: settings).bounce == 0) + } + + @Test func extraScalesStaggerAndCap() { + let spec = MotionToken.shuffle.spec(settings: MotionSettings(level: .extra)) + #expect(near(spec.stagger, 0.018)) + #expect(near(spec.maximumStagger, 0.072)) + } + + @Test func allSpringTokensHavePhysicalParameters() { + for token in MotionToken.allCases { + let spec = token.spec() + #expect(spec.spring.stiffness > 0) + #expect(spec.spring.damping > 0) + #expect(spec.overshootLimit <= 0.25) + } + } +} + +@Suite struct MotionPolicyTests { + @Test func enabledByDefault() { + #expect(MotionPolicy().enabled) + #expect(!MotionPolicy().reduceMotion) + } + + @Test(arguments: [MotionSurface.window, .overlay, .miniMap]) + func offDisablesEverySurface(_ surface: MotionSurface) { + #expect(MotionPolicy(enabled: false).behavior(for: surface) == .instant) + } + + @Test func offOverridesReduceMotionFade() { + #expect(MotionPolicy(enabled: false, reduceMotion: true).behavior(for: .overlay) == .instant) + } + + @Test func reduceMotionSnapsWindows() { + #expect(MotionPolicy(reduceMotion: true).behavior(for: .window) == .instant) + } + + @Test func reduceMotionOnlyFadesOverlays() { + #expect(MotionPolicy(reduceMotion: true).behavior(for: .overlay) == .fade(duration: 0.12)) + #expect(MotionPolicy(reduceMotion: true).behavior(for: .miniMap) == .instant) + } + + @Test func calmSnapsWindowsButAnimatesChrome() { + #expect(MotionPolicy().behavior(for: .window, level: .calm) == .instant) + #expect(MotionPolicy().behavior(for: .overlay, level: .calm) == .animate) + } + + @Test func systemSettingOverridesExtra() { + #expect(MotionPolicy(reduceMotion: true).behavior(for: .window, level: .extra) == .instant) + #expect(MotionPolicy(reduceMotion: true).behavior(for: .overlay, level: .extra) == .fade(duration: 0.12)) + } +} diff --git a/Tests/TesseraAnimationTests/SpringTests.swift b/Tests/TesseraAnimationTests/SpringTests.swift new file mode 100644 index 00000000..f2da8256 --- /dev/null +++ b/Tests/TesseraAnimationTests/SpringTests.swift @@ -0,0 +1,164 @@ +import Foundation +import Testing + +@testable import TesseraAnimation + +@Suite struct SpringTests { + let critical = SpringParameters(duration: 0.2, bounce: 0) + let bouncy = SpringParameters(duration: 0.25, bounce: 0.3) + + @Test func physicalParametersArePreserved() { + let spring = SpringParameters(mass: 2, stiffness: 100, damping: 8) + #expect(spring.mass == 2) + #expect(spring.stiffness == 100) + #expect(spring.damping == 8) + } + + @Test func responseMapsToNaturalFrequency() { + let spring = SpringParameters(response: 0.5, dampingFraction: 0.7) + #expect(near(spring.stiffness, pow(4 * Double.pi, 2))) + #expect(near(spring.dampingFraction, 0.7)) + } + + @Test func durationBounceMatchesPhysicalForm() { + let spring = SpringParameters(duration: 0.5, bounce: 0.3) + #expect(near(spring.stiffness, 157.91367041742973)) + #expect(near(spring.damping, 17.59291886010284)) + #expect(spring.mass == 1) + } + + @Test func zeroBounceIsCriticallyDamped() { #expect(near(critical.dampingFraction, 1)) } + + @Test func zeroStepPreservesValueAndVelocity() { + let state = SpringState(value: 42, velocity: -100) + #expect(state.advanced(to: 8, by: 0, using: bouncy) == state) + } + + @Test func equilibriumRemainsStill() { + #expect(SpringState(value: 8).advanced(to: 8, by: 0.1, using: critical) == SpringState(value: 8)) + } + + @Test func criticalSpringConverges() { + let result = SpringState(value: 0).advanced(to: 100, by: 2, using: critical) + #expect(near(result.value, 100)) + #expect(near(result.velocity, 0)) + } + + @Test func underdampedSpringConverges() { + let result = SpringState(value: -50, velocity: 200).advanced(to: 100, by: 2, using: bouncy) + #expect(near(result.value, 100)) + #expect(near(result.velocity, 0)) + } + + @Test func overdampedSpringConverges() { + let spring = SpringParameters(response: 0.2, dampingFraction: 2) + let result = SpringState(value: 0).advanced(to: 100, by: 10, using: spring) + #expect(near(result.value, 100)) + #expect(near(result.velocity, 0)) + } + + @Test func bouncySpringCrossesTarget() { + let values = (0...100).map { SpringState(value: 0).advanced(to: 1, by: Double($0) / 200, using: bouncy).value } + #expect(values.contains { $0 > 1 }) + #expect((values.max() ?? 0) < 1.06) + } + + @Test func criticalSpringIsMonotonicWithoutInitialVelocity() { + let values = (0...100).map { + SpringState(value: 0).advanced(to: 1, by: Double($0) / 200, using: critical).value + } + #expect(zip(values, values.dropFirst()).allSatisfy { $0 <= $1 }) + #expect(values.allSatisfy { (0...1).contains($0) }) + } + + @Test func negativeDirectionIsSymmetric() { + let positive = SpringState(value: 0).advanced(to: 10, by: 0.1, using: bouncy) + let negative = SpringState(value: 0).advanced(to: -10, by: 0.1, using: bouncy) + #expect(near(positive.value, -negative.value)) + #expect(near(positive.velocity, -negative.velocity)) + } + + @Test func partitionedStepsMatchSingleStep() { + var partitioned = SpringState(value: 3, velocity: -20) + for _ in 0..<100 { partitioned.advance(to: 90, by: 0.003, using: bouncy) } + let single = SpringState(value: 3, velocity: -20).advanced(to: 90, by: 0.3, using: bouncy) + #expect(near(partitioned.value, single.value)) + #expect(near(partitioned.velocity, single.velocity)) + } + + @Test func unevenStepsAreStable() { + var state = SpringState(value: 0, velocity: 100) + for step in [0.001, 0.05, 0.4, 0.009, 3.0] { state.advance(to: 10, by: step, using: bouncy) } + #expect(near(state.value, 10)) + #expect(state.velocity.isFinite) + } + + @Test func largeStepDoesNotExplode() { + let state = SpringState(value: 0, velocity: 100).advanced(to: 10, by: 1000, using: bouncy) + #expect(state == SpringState(value: 10)) + } + + @Test func heavyDampingAvoidsOverflow() { + let spring = SpringParameters(response: 0.2, dampingFraction: 1_000_000) + let state = SpringState(value: 0).advanced(to: 10, by: 1_000_000, using: spring) + #expect(state.value.isFinite && state.velocity.isFinite) + #expect(state.value > 9.99) + } + + @Test func nearCriticalDampingIsStable() { + let spring = SpringParameters(response: 0.2, dampingFraction: 1 + 1e-12) + let state = SpringState(value: 0).advanced(to: 1, by: 0.1, using: spring) + let reference = SpringState(value: 0).advanced(to: 1, by: 0.1, using: critical) + #expect(near(state.value, reference.value)) + #expect(near(state.velocity, reference.velocity)) + } + + @Test func massScalingPreservesTrajectory() { + let spring = SpringParameters(mass: 2, stiffness: bouncy.stiffness * 2, damping: bouncy.damping * 2) + let state = SpringState(value: 0, velocity: 10) + #expect(state.advanced(to: 20, by: 0.1, using: spring) == state.advanced(to: 20, by: 0.1, using: bouncy)) + } + + @Test func retargetingKeepsPresentationAndMomentum() { + let state = SpringState(value: 0).advanced(to: 100, by: 0.04, using: bouncy) + let retargeted = state.advanced(to: -20, by: 0, using: bouncy) + #expect(retargeted == state) + #expect(retargeted.velocity > 0) + } + + @Test func retargetingEventuallyChangesDirection() { + let state = SpringState(value: 0).advanced(to: 100, by: 0.04, using: bouncy) + let retargeted = state.advanced(to: -20, by: 1, using: bouncy) + #expect(near(retargeted.value, -20, tolerance: 1e-4)) + } + + @Test func velocityMatchesPositionDerivative() { + let initial = SpringState(value: 0, velocity: 30) + let state = initial.advanced(to: 10, by: 0.1, using: bouncy) + let before = initial.advanced(to: 10, by: 0.1 - 1e-6, using: bouncy) + let after = initial.advanced(to: 10, by: 0.1 + 1e-6, using: bouncy) + #expect(near(state.velocity, (after.value - before.value) / 2e-6, tolerance: 1e-6)) + } + + @Test func undampedSpringIsPeriodic() { + let spring = SpringParameters(response: 0.2, dampingFraction: 0) + let state = SpringState(value: 0, velocity: 5) + let result = state.advanced(to: 10, by: 0.2, using: spring) + #expect(near(result.value, state.value)) + #expect(near(result.velocity, state.velocity)) + } + + @Test func movingAtTargetCarriesVelocity() { + let result = SpringState(value: 10, velocity: 100).advanced(to: 10, by: 0.01, using: bouncy) + #expect(result.value > 10) + #expect(result.velocity > 0) + } + + @Test func dampingDissipatesEnergy() { + let initial = SpringState(value: 0, velocity: 100) + let after = initial.advanced(to: 10, by: 0.1, using: bouncy) + let initialEnergy = bouncy.mass * pow(initial.velocity, 2) + bouncy.stiffness * pow(initial.value - 10, 2) + let finalEnergy = bouncy.mass * pow(after.velocity, 2) + bouncy.stiffness * pow(after.value - 10, 2) + #expect(finalEnergy < initialEnergy) + } +} diff --git a/Tests/TesseraAnimationTests/TesseraAnimationTests.swift b/Tests/TesseraAnimationTests/TesseraAnimationTests.swift deleted file mode 100644 index 4a47bff9..00000000 --- a/Tests/TesseraAnimationTests/TesseraAnimationTests.swift +++ /dev/null @@ -1,4 +0,0 @@ -import Testing -@testable import TesseraAnimation - -@Test func builds() {} diff --git a/Tests/TesseraAnimationTests/TestSupport.swift b/Tests/TesseraAnimationTests/TestSupport.swift new file mode 100644 index 00000000..31bc95ff --- /dev/null +++ b/Tests/TesseraAnimationTests/TestSupport.swift @@ -0,0 +1,47 @@ +import Testing + +@testable import TesseraAnimation + +let testScreen = MotionRect(originX: 0, originY: 0, width: 1920, height: 1080) +let testWindow = MotionWindowID(rawValue: 1) +let testApp = MotionAppID(rawValue: 1) + +func rect(_ horizontal: Double = 10, _ vertical: Double = 20, _ width: Double = 200, _ height: Double = 100) + -> MotionRect +{ + MotionRect(originX: horizontal, originY: vertical, width: width, height: height) +} + +func request( + window: UInt64 = 1, app: Int32 = 1, start: MotionRect = rect(), target: MotionRect = rect(500, 300, 400, 200), + screen: MotionRect = testScreen, minimum: MotionSize = .zero, surface: MotionSurface = .window, + token: MotionToken = .settle, index: Int = 0, velocity: MotionVelocity = .zero, + startOpacity: Double = 1, targetOpacity: Double = 1, metrics: AppWriteMetrics = AppWriteMetrics(), + generation: UInt64 = 0 +) -> MotionRequest { + MotionRequest( + windowID: MotionWindowID(rawValue: window), appID: MotionAppID(rawValue: app), start: start, target: target, + screen: screen, minimumSize: minimum, surface: surface, token: token, staggerIndex: index, velocity: velocity, + startOpacity: startOpacity, targetOpacity: targetOpacity, metrics: metrics, generation: generation + ) +} + +func near(_ lhs: Double, _ rhs: Double, tolerance: Double = 1e-8) -> Bool { abs(lhs - rhs) <= tolerance } + +func frame( + window: UInt64 = 1, app: Int32 = 1, at timestamp: Double = 0, revision: UInt64 = 1, + origin: Double = 0, final: Bool = false, generation: UInt64 = 0 +) -> MotionFrame { + MotionFrame( + windowID: MotionWindowID(rawValue: window), appID: MotionAppID(rawValue: app), generation: generation, + rect: rect(origin), + opacity: 1, scale: 1, offsetHorizontal: 0, offsetVertical: 0, timestamp: timestamp, + revision: revision, isFinal: final + ) +} + +func measured(_ duration: Double, timeout: Bool = false, at timestamp: Double = 0) throws -> AppWriteMetrics { + var metrics = AppWriteMetrics() + try metrics.record(duration: duration, timedOut: timeout, at: timestamp) + return metrics +} -- knotmirror 0.0.1 From 53cd89692f79b77288c3a0866a12445b39aec9c0 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:08:13 -0400 Subject: [PATCH 23/44] Cover motion lifecycle and accessibility regressions --- .../DriverIntegrationTests.swift | 106 +++++++++++ .../MotionRegressionTests.swift | 166 ++++++++++++++++++ 2 files changed, 272 insertions(+) create mode 100644 Tests/TesseraAnimationTests/DriverIntegrationTests.swift create mode 100644 Tests/TesseraAnimationTests/MotionRegressionTests.swift diff --git a/Tests/TesseraAnimationTests/DriverIntegrationTests.swift b/Tests/TesseraAnimationTests/DriverIntegrationTests.swift new file mode 100644 index 00000000..461ae408 --- /dev/null +++ b/Tests/TesseraAnimationTests/DriverIntegrationTests.swift @@ -0,0 +1,106 @@ +import Testing + +@testable import TesseraAnimation + +@MainActor +private final class TestReduceMotion: ReduceMotionSource { + var isEnabled = false + var callback: (@MainActor () -> Void)? + var isObserving: Bool { callback != nil } + func start(changed: @escaping @MainActor () -> Void) { callback = changed } + func stop() { callback = nil } + func change(to enabled: Bool) { + isEnabled = enabled + callback?() + } +} + +@Suite @MainActor struct DriverIntegrationTests { + @Test func predictedFrameTimeDoesNotRejectCurrentClockCommands() throws { + let source = TestDisplayLink() + var now = 0.0 + let driver = DisplayLinkDriver( + source: source, clock: { now }, onFrames: { _ in }, onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()]) + source.fire(at: 0.016) + now = 0.008 + try driver.schedule([request(target: rect(700))]) + try driver.updatePolicy(MotionPolicy()) + try driver.updateSettings(MotionSettings(speedMultiplier: 2)) + #expect(driver.animator.timestamp == 0.016) + #expect(driver.isRunning) + } + + @Test func initialSystemSettingIsInjectedBeforeFirstFrame() throws { + let source = TestDisplayLink() + let system = TestReduceMotion() + system.isEnabled = true + var frames: [MotionFrame] = [] + let driver = DisplayLinkDriver( + source: source, reduceMotionSource: system, clock: { 0 }, onFrames: { frames += $0 }, + onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()]) + source.fire(at: 0) + #expect(frames.count == 1 && frames[0].isFinal) + #expect(driver.animator.policy.reduceMotion) + } + + @Test func systemChangeReplansActiveMotion() throws { + let source = TestDisplayLink() + let system = TestReduceMotion() + var now = 0.0 + var frames: [MotionFrame] = [] + let driver = DisplayLinkDriver( + source: source, reduceMotionSource: system, clock: { now }, onFrames: { frames += $0 }, + onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.schedule([request()]) + now = 0.04 + system.change(to: true) + source.fire(at: now) + #expect(frames.last?.isFinal == true && !driver.isRunning) + now = 1 + system.change(to: false) + try driver.schedule([request()]) + source.fire(at: now) + #expect(frames.last?.isFinal == false && driver.isRunning) + } + + @Test func explicitReduceMotionCannotOverrideSystemRequirement() throws { + let source = TestDisplayLink() + let system = TestReduceMotion() + system.isEnabled = true + let driver = DisplayLinkDriver( + source: source, reduceMotionSource: system, clock: { 0 }, onFrames: { _ in }, + onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.updatePolicy(MotionPolicy(reduceMotion: false)) + #expect(driver.animator.policy.reduceMotion) + try driver.updatePolicy(MotionPolicy(reduceMotion: true)) + system.change(to: false) + #expect(driver.animator.policy.reduceMotion) + } + + @Test func disabledPolicyStillOverridesSystemFade() throws { + let source = TestDisplayLink() + let system = TestReduceMotion() + system.isEnabled = true + var frames: [MotionFrame] = [] + let driver = DisplayLinkDriver( + source: source, reduceMotionSource: system, clock: { 0 }, onFrames: { frames += $0 }, + onFailure: { _ in Issue.record("Unexpected failure") }) + try driver.updatePolicy(MotionPolicy(enabled: false)) + try driver.schedule([request(surface: .overlay, token: .pop, startOpacity: 0)]) + source.fire(at: 0) + #expect(frames.first?.isFinal == true && frames.first?.opacity == 1) + } + + @Test func destructionRemovesAccessibilityObservation() { + let source = TestDisplayLink() + let system = TestReduceMotion() + var driver: DisplayLinkDriver? = DisplayLinkDriver( + source: source, reduceMotionSource: system, onFrames: { _ in }, + onFailure: { _ in Issue.record("Unexpected failure") }) + #expect(driver != nil && system.isObserving) + driver = nil + #expect(!system.isObserving) + } +} diff --git a/Tests/TesseraAnimationTests/MotionRegressionTests.swift b/Tests/TesseraAnimationTests/MotionRegressionTests.swift new file mode 100644 index 00000000..0a2139c2 --- /dev/null +++ b/Tests/TesseraAnimationTests/MotionRegressionTests.swift @@ -0,0 +1,166 @@ +import Testing + +@testable import TesseraAnimation + +@Suite struct MotionRegressionTests { + @Test func unchangedWindowPositionIgnoresReleaseVelocity() throws { + let plan = try FramePlanner.plan( + request(start: rect(100), target: rect(100), velocity: MotionVelocity(horizontal: 1000, vertical: -1000)), + at: 0) + for step in 0...20 { + let sample = try plan.sample(at: Double(step) / 100) + #expect(sample.frame.rect == rect(100)) + #expect(sample.velocity == .zero) + } + } + + @Test func unchangedRetargetAxisDoesNotBounce() throws { + var animator = Animator() + try animator.schedule( + [request(start: rect(100, 100), target: rect(500, 100), velocity: MotionVelocity(vertical: 500))], at: 0) + try animator.schedule([request(start: rect(0), target: rect(700, 100))], at: 0.04) + for step in 4...24 { + let sample = try #require(try animator.presentation(for: testWindow, at: Double(step) / 100)) + #expect(sample.frame.rect.originY == 100) + #expect(sample.velocity.vertical == 0) + } + } + + @Test(arguments: [MotionToken.pop, .nudge, .shuffle, .stack, .glance, .drop]) + func springDeadlineIsContinuous(_ token: MotionToken) throws { + let plan = try FramePlanner.plan( + request(start: rect(0), target: rect(1000), surface: .overlay, token: token, index: 2), at: 0) + let before = plan.state(at: plan.endTime - 1e-6) + let final = plan.state(at: plan.endTime) + #expect(near(before.rect.originX, final.rect.originX, tolerance: 1e-6)) + #expect(near(before.velocity.horizontal, 0, tolerance: 0.001)) + #expect(near(before.scale.value, final.scale.value, tolerance: 1e-6)) + #expect(near(before.offsetHorizontal.value, final.offsetHorizontal.value, tolerance: 1e-6)) + #expect(near(before.offsetHorizontal.velocity, 0, tolerance: 0.001)) + } + + @Test func retargetAcrossSpringDeadlineKeepsFinalPresentation() throws { + var animator = Animator() + try animator.schedule([request(surface: .overlay, token: .pop)], at: 0) + try animator.schedule([request(target: rect(700), surface: .overlay, token: .pop)], at: 0.25) + let sample = try #require(try animator.presentation(for: testWindow, at: 0.25)) + #expect(sample.frame.rect == request().target) + #expect(sample.velocity == .zero) + #expect(sample.frame.scale == 1) + } + + @Test(arguments: [MotionToken.pop, .nudge, .stack]) + func calmChangeRemovesInheritedAccents(_ token: MotionToken) throws { + var animator = Animator() + try animator.schedule([request(surface: .overlay, token: token, index: 3)], at: 0) + try animator.updateSettings(MotionSettings(level: .calm), at: 0.04) + for timestamp in [0.04, 0.10, 0.24] { + let sample = try #require(try animator.presentation(for: testWindow, at: timestamp)) + #expect(sample.frame.scale == 1) + #expect(sample.frame.offsetHorizontal == 0 && sample.frame.offsetVertical == 0) + } + } + + @Test func nudgeCanRubberBandWithoutExceedingFourPoints() throws { + let plan = try FramePlanner.plan( + request(start: rect(100), target: rect(100), surface: .overlay, token: .nudge), at: 0) + let offsets = try (0...180).map { try plan.sample(at: Double($0) / 1000).frame.offsetHorizontal } + #expect(offsets.contains { $0 < 0 }) + #expect(offsets.allSatisfy { abs($0) <= 4 }) + } + + @Test func instantPlanCanBeSampledBeforeScheduledTime() throws { + let plan = try FramePlanner.plan(request(), at: 10, policy: MotionPolicy(enabled: false)) + let sample = try plan.sample(at: 9) + #expect(sample.frame.rect == request().target) + #expect(sample.velocity == .zero) + } + + @Test func snappingAppPlanCanBeSampledBeforeScheduledTime() throws { + let plan = try FramePlanner.plan(request(metrics: measured(0.05)), at: 10) + #expect(try plan.sample(at: 9).frame.rect == request().target) + } + + @Test func enormousTimestampThatCannotRepresentDurationIsRejected() { + #expect(throws: MotionError.invalidTimestamp) { try FramePlanner.plan(request(), at: .greatestFiniteMagnitude) } + } + + @Test func supportedSpeedBoundsKeepEveryTokenFinite() { + #expect(!MotionSettings.supportedSpeeds.contains(Double.leastNonzeroMagnitude)) + #expect(!MotionSettings.supportedSpeeds.contains(Double.greatestFiniteMagnitude)) + #expect(!MotionSettings.supportedSpeeds.contains(Double.nan)) + for speed in [MotionSettings.supportedSpeeds.lowerBound, MotionSettings.supportedSpeeds.upperBound] { + for token in MotionToken.allCases { + let spec = token.spec(settings: MotionSettings(speedMultiplier: speed)) + #expect(spec.duration.isFinite && spec.duration > 0) + #expect(spec.spring.stiffness.isFinite && spec.spring.damping.isFinite) + } + } + } + + @Test func transferBetweenAnimatorsStartsNewGeneration() throws { + var old = Animator() + var new = Animator() + var coalescer = FrameCoalescer() + for _ in 0..<20 { try old.schedule([request()], at: 0) } + let oldFrame = try #require(old.tick(at: 0.05).first) + try coalescer.submit(oldFrame) + let generation = coalescer.activate(testWindow, appID: testApp) + try new.schedule([request(generation: generation)], at: 0.06) + let newFrame = try #require(new.tick(at: 0.06).first) + #expect(newFrame.revision < oldFrame.revision) + #expect(try coalescer.submit(newFrame)) + let late = try #require(old.tick(at: 0.07).first) + #expect(try !coalescer.submit(late)) + let batch = try #require(coalescer.takeReady(at: 0.07).first) + #expect(batch.frames == [newFrame]) + } + + @Test func newGenerationDoesNotInheritOldWindowMomentum() throws { + var animator = Animator() + try animator.schedule([request()], at: 0) + try animator.schedule([request(start: rect(700), target: rect(800), generation: 1)], at: 0.04) + #expect(try animator.tick(at: 0.04).first?.rect.originX == 700) + } + + @Test func unknownRemovedWindowRejectsFirstDelayedFrame() throws { + var coalescer = FrameCoalescer() + coalescer.remove(testWindow) + #expect(try !coalescer.submit(frame())) + } + + @Test func transferCannotAccidentallyChangeAppOwnership() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + #expect(try !coalescer.submit(frame(app: 2, at: 1))) + let generation = coalescer.activate(testWindow, appID: MotionAppID(rawValue: 2)) + #expect(try coalescer.submit(frame(app: 2, at: 1, generation: generation))) + } + + @Test func appTerminationReleasesBusyStateAndRejectsLateCompletion() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + let batch = try #require(coalescer.takeReady(at: 0).first) + coalescer.setMetrics(try measured(0.05), for: testApp) + coalescer.removeApp(testApp) + #expect(coalescer.inFlightCount == 0 && coalescer.pendingCount == 0) + #expect(coalescer.metricsSnapshot[testApp] == nil) + #expect(try !coalescer.submit(frame(at: 1))) + #expect(throws: MotionError.unknownBatch) { try coalescer.complete(batch, duration: 0.1, at: 1) } + let generation = coalescer.activate(testWindow, appID: testApp) + try coalescer.submit(frame(at: 1, generation: generation)) + let reused = try #require(coalescer.takeReady(at: 1).first) + #expect(reused.identifier != batch.identifier) + #expect(throws: MotionError.unknownBatch) { try coalescer.complete(batch, duration: 0.1, at: 1) } + #expect(coalescer.inFlightCount == 1) + } + + @Test func removingOneAppKeepsOtherAppWork() throws { + var coalescer = FrameCoalescer() + try coalescer.submit(frame()) + try coalescer.submit(frame(window: 2, app: 2)) + coalescer.removeApp(testApp) + #expect(coalescer.pendingCount == 1) + #expect(try coalescer.takeReady(at: 0).first?.appID == MotionAppID(rawValue: 2)) + } +} -- knotmirror 0.0.1 From 2ed8ed21976e927cd3c22b868274f26a7f0376b4 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:11:22 -0400 Subject: [PATCH 24/44] Keep large spring steps and test clocks safe --- Sources/TesseraAnimation/Spring.swift | 13 ++++++---- .../DriverIntegrationTests.swift | 24 ++++++++++++------- Tests/TesseraAnimationTests/SpringTests.swift | 17 +++++++++++++ 3 files changed, 41 insertions(+), 13 deletions(-) diff --git a/Sources/TesseraAnimation/Spring.swift b/Sources/TesseraAnimation/Spring.swift index d8dd9446..69b47a87 100644 --- a/Sources/TesseraAnimation/Spring.swift +++ b/Sources/TesseraAnimation/Spring.swift @@ -49,17 +49,22 @@ public struct SpringState: Sendable, Equatable { let position: Double let speed: Double if abs(discriminant) <= frequency * frequency * 1e-10 { - let coefficient = velocity + decay * displacement let envelope = exp(-decay * deltaTime) + guard envelope > 0 else { return Self(value: target) } + let coefficient = velocity + decay * displacement position = envelope * (displacement + coefficient * deltaTime) speed = envelope * (velocity - decay * coefficient * deltaTime) } else if discriminant > 0 { + let envelope = exp(-decay * deltaTime) + guard envelope > 0 else { return Self(value: target) } let oscillation = sqrt(discriminant) let angle = oscillation * deltaTime - let sine = sin(angle) - let cosine = cos(angle) + let phase = + angle.isFinite + ? angle : deltaTime.truncatingRemainder(dividingBy: 2 * Double.pi / oscillation) * oscillation + let sine = sin(phase) + let cosine = cos(phase) let coefficient = (velocity + decay * displacement) / oscillation - let envelope = exp(-decay * deltaTime) position = envelope * (displacement * cosine + coefficient * sine) speed = envelope * (velocity * cosine - (decay * coefficient + displacement * oscillation) * sine) } else { diff --git a/Tests/TesseraAnimationTests/DriverIntegrationTests.swift b/Tests/TesseraAnimationTests/DriverIntegrationTests.swift index 461ae408..c2b7d024 100644 --- a/Tests/TesseraAnimationTests/DriverIntegrationTests.swift +++ b/Tests/TesseraAnimationTests/DriverIntegrationTests.swift @@ -15,15 +15,21 @@ private final class TestReduceMotion: ReduceMotionSource { } } +@MainActor +private final class TestMotionClock { + var timestamp = 0.0 +} + @Suite @MainActor struct DriverIntegrationTests { @Test func predictedFrameTimeDoesNotRejectCurrentClockCommands() throws { let source = TestDisplayLink() - var now = 0.0 + let clock = TestMotionClock() let driver = DisplayLinkDriver( - source: source, clock: { now }, onFrames: { _ in }, onFailure: { _ in Issue.record("Unexpected failure") }) + source: source, clock: { clock.timestamp }, onFrames: { _ in }, + onFailure: { _ in Issue.record("Unexpected failure") }) try driver.schedule([request()]) source.fire(at: 0.016) - now = 0.008 + clock.timestamp = 0.008 try driver.schedule([request(target: rect(700))]) try driver.updatePolicy(MotionPolicy()) try driver.updateSettings(MotionSettings(speedMultiplier: 2)) @@ -48,20 +54,20 @@ private final class TestReduceMotion: ReduceMotionSource { @Test func systemChangeReplansActiveMotion() throws { let source = TestDisplayLink() let system = TestReduceMotion() - var now = 0.0 + let clock = TestMotionClock() var frames: [MotionFrame] = [] let driver = DisplayLinkDriver( - source: source, reduceMotionSource: system, clock: { now }, onFrames: { frames += $0 }, + source: source, reduceMotionSource: system, clock: { clock.timestamp }, onFrames: { frames += $0 }, onFailure: { _ in Issue.record("Unexpected failure") }) try driver.schedule([request()]) - now = 0.04 + clock.timestamp = 0.04 system.change(to: true) - source.fire(at: now) + source.fire(at: clock.timestamp) #expect(frames.last?.isFinal == true && !driver.isRunning) - now = 1 + clock.timestamp = 1 system.change(to: false) try driver.schedule([request()]) - source.fire(at: now) + source.fire(at: clock.timestamp) #expect(frames.last?.isFinal == false && driver.isRunning) } diff --git a/Tests/TesseraAnimationTests/SpringTests.swift b/Tests/TesseraAnimationTests/SpringTests.swift index f2da8256..7be255ac 100644 --- a/Tests/TesseraAnimationTests/SpringTests.swift +++ b/Tests/TesseraAnimationTests/SpringTests.swift @@ -154,6 +154,23 @@ import Testing #expect(result.velocity > 0) } + @Test(arguments: [0.5, 1.0, 2.0]) + func largestFiniteStepConvergesWithoutOverflow(_ dampingFraction: Double) { + let spring = SpringParameters(response: 0.2, dampingFraction: dampingFraction) + let result = SpringState(value: 1, velocity: 3).advanced(to: 10, by: .greatestFiniteMagnitude, using: spring) + #expect(result == SpringState(value: 10)) + } + + @Test func largestFiniteUndampedStepKeepsFiniteEnergy() { + let spring = SpringParameters(response: 0.2, dampingFraction: 0) + let initial = SpringState(value: 1, velocity: 3) + let result = initial.advanced(to: 0, by: .greatestFiniteMagnitude, using: spring) + #expect(result.value.isFinite && result.velocity.isFinite) + let initialEnergy = pow(initial.velocity, 2) + spring.stiffness * pow(initial.value, 2) + let finalEnergy = pow(result.velocity, 2) + spring.stiffness * pow(result.value, 2) + #expect(near(initialEnergy, finalEnergy, tolerance: 1e-8)) + } + @Test func dampingDissipatesEnergy() { let initial = SpringState(value: 0, velocity: 100) let after = initial.advanced(to: 10, by: 0.1, using: bouncy) -- knotmirror 0.0.1 From d66ee66980f77d65b5303ebe4b3a660c7fac5528 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:12:59 -0400 Subject: [PATCH 25/44] Ignore local agent state --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 10d7ab9c..7c09229b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ build/ *.xcodeproj/ .DS_Store /Tessera.app +.pi/ -- knotmirror 0.0.1 From d4f1e87734afc794557f0f88955c2b097d8fc073 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:17:01 -0400 Subject: [PATCH 26/44] Guard frame write recovery --- Sources/TesseraPlatform/FrameWrites.swift | 18 +++--- .../TesseraPlatformTests/AXElementTests.swift | 56 +++++++++++++++++-- 2 files changed, 61 insertions(+), 13 deletions(-) diff --git a/Sources/TesseraPlatform/FrameWrites.swift b/Sources/TesseraPlatform/FrameWrites.swift index b387b835..1dcd36f5 100644 --- a/Sources/TesseraPlatform/FrameWrites.swift +++ b/Sources/TesseraPlatform/FrameWrites.swift @@ -24,11 +24,8 @@ public struct FrameWritePlan: Sendable, Equatable { public let steps: [FrameWriteStep] public init(current: CGRect, target: CGRect) { - var steps: [FrameWriteStep] = [] - if current.size != target.size { steps.append(.size(target.size)) } - if current.origin != target.origin { steps.append(.position(target.origin)) } - if current != target { steps.append(.size(target.size)) } - self.steps = steps + self.steps = + current == target ? [] : [.size(target.size), .position(target.origin), .size(target.size)] } } @@ -65,8 +62,15 @@ func executeFrameWrite( enhancedUI = false } if enhancedUI { - try application.setEnhancedUI(false) - restoreEnhancedUI = true + do { + try application.setEnhancedUI(false) + restoreEnhancedUI = true + } catch { + do { try application.setEnhancedUI(true) } catch let restoreError { + throw FrameWriteFailure(writeError: error, restoreError: restoreError) + } + throw error + } } } diff --git a/Tests/TesseraPlatformTests/AXElementTests.swift b/Tests/TesseraPlatformTests/AXElementTests.swift index db7b0433..3b17dec5 100644 --- a/Tests/TesseraPlatformTests/AXElementTests.swift +++ b/Tests/TesseraPlatformTests/AXElementTests.swift @@ -44,13 +44,19 @@ func mapsAccessibilityErrors(error: AXError, expected: AXPlatformError) { @Test func movedFrameStillChecksSizeAfterPosition() { let old = CGRect(x: 10, y: 20, width: 300, height: 200) let new = CGRect(x: 30, y: 40, width: 300, height: 200) - #expect(FrameWritePlan(current: old, target: new).steps == [.position(new.origin), .size(new.size)]) + #expect( + FrameWritePlan(current: old, target: new).steps == [ + .size(new.size), .position(new.origin), .size(new.size), + ]) } @Test func resizedFrameChecksSizeTwice() { let old = CGRect(x: 10, y: 20, width: 300, height: 200) let new = CGRect(x: 10, y: 20, width: 400, height: 400) - #expect(FrameWritePlan(current: old, target: new).steps == [.size(new.size), .size(new.size)]) + #expect( + FrameWritePlan(current: old, target: new).steps == [ + .size(new.size), .position(new.origin), .size(new.size), + ]) } private final class FrameWriteProbe: FrameWriteAccess { @@ -61,6 +67,8 @@ private final class FrameWriteProbe: FrameWriteAccess { var failPosition = false var failRestore = false var positionResetsSize = false + var sizeChangesPosition = false + var disableAppliesBeforeFailure = false var frame: CGRect { get throws { rectangle } } var size: CGSize { get throws { rectangle.size } } @@ -70,6 +78,7 @@ private final class FrameWriteProbe: FrameWriteAccess { func setSize(_ value: CGSize) throws { actions.append("size") rectangle.size = value + if sizeChangesPosition { rectangle.origin = CGPoint(x: 99, y: 99) } } func setPosition(_ value: CGPoint) throws { actions.append("position") @@ -79,7 +88,10 @@ private final class FrameWriteProbe: FrameWriteAccess { } func setEnhancedUI(_ value: Bool) throws { actions.append(value ? "enable" : "disable") - if !value && failDisable { throw AXPlatformError.attributeUnsupported } + if !value && failDisable { + if disableAppliesBeforeFailure { enabled = false } + throw AXPlatformError.timedOut + } if value && failRestore { throw AXPlatformError.elementInvalid } enabled = value } @@ -109,16 +121,48 @@ func frameWriteKeepsEnhancedUIForAssistiveTechnology(assistive: AssistiveTechnol #expect(probe.enabled) } -@Test func frameWriteDoesNotHideFailureToDisableEnhancedUI() { +@Test func frameWriteRestoresAfterUncertainDisable() { let probe = FrameWriteProbe() probe.failDisable = true - #expect(throws: AXPlatformError.attributeUnsupported) { + probe.disableAppliesBeforeFailure = true + #expect(throws: AXPlatformError.timedOut) { try executeFrameWrite( CGRect(x: 30, y: 20, width: 300, height: 200), window: probe, application: probe, assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false) ) } - #expect(probe.actions == ["disable"]) + #expect(probe.enabled) + #expect(probe.actions == ["disable", "enable"]) +} + +@Test func frameWriteReportsDisableAndRestoreFailures() { + let probe = FrameWriteProbe() + probe.failDisable = true + probe.failRestore = true + do { + _ = try executeFrameWrite( + CGRect(x: 30, y: 20, width: 300, height: 200), window: probe, application: probe, + assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false) + ) + Issue.record("Expected disable and restore failure") + } catch let failure as FrameWriteFailure { + #expect(failure.writeError as? AXPlatformError == .timedOut) + #expect(failure.restoreError as? AXPlatformError == .elementInvalid) + } catch { + Issue.record("Unexpected failure: \(error)") + } +} + +@Test func frameWriteCorrectsPositionChangedByResize() throws { + let probe = FrameWriteProbe() + probe.sizeChangesPosition = true + let target = CGRect(x: 10, y: 20, width: 500, height: 400) + let actual = try executeFrameWrite( + target, window: probe, application: probe, + assistiveTechnology: AssistiveTechnology(voiceOver: false, switchControl: false) + ) + #expect(actual == target) + #expect(probe.actions == ["disable", "size", "position", "enable"]) } @Test func frameWriteReportsBothWriteAndRestoreFailures() { -- knotmirror 0.0.1 From 23b8ee8a0ba29d2b5738c5e73deb80ce8b357ba0 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:18:05 -0400 Subject: [PATCH 27/44] Track responsiveness from AX calls --- Sources/TesseraPlatform/AXElement.swift | 34 +++++++++++++++++-- Sources/TesseraPlatform/AppThread.swift | 23 ++++++++++--- .../TesseraPlatformTests/AppThreadTests.swift | 19 +++++++++++ 3 files changed, 69 insertions(+), 7 deletions(-) diff --git a/Sources/TesseraPlatform/AXElement.swift b/Sources/TesseraPlatform/AXElement.swift index d7fae7e1..9ee09e36 100644 --- a/Sources/TesseraPlatform/AXElement.swift +++ b/Sources/TesseraPlatform/AXElement.swift @@ -30,9 +30,18 @@ func checkAX(_ error: AXError) throws { guard error == .success else { throw AXPlatformError(error) } } +final class AXCallActivity { + private(set) var results: [AXPlatformError?] = [] + + func record(_ error: AXPlatformError?) { + results.append(error) + } +} + public struct AXElement { let raw: AXUIElement let timeout: Float + private let activity: AXCallActivity? init(applicationPID: pid_t, timeout: Float = 0.35) throws { try self.init(raw: AXUIElementCreateApplication(applicationPID), timeout: timeout) @@ -43,6 +52,17 @@ public struct AXElement { try checkAX(AXUIElementSetMessagingTimeout(raw, timeout)) self.raw = raw self.timeout = timeout + self.activity = nil + } + + private init(raw: AXUIElement, timeout: Float, activity: AXCallActivity?) { + self.raw = raw + self.timeout = timeout + self.activity = activity + } + + func tracking(_ activity: AXCallActivity) -> AXElement { + AXElement(raw: raw, timeout: timeout, activity: activity) } static func checkCall(_ error: AXError, elapsed: Double, timeout: Float) throws { @@ -57,7 +77,13 @@ public struct AXElement { let start = DispatchTime.now().uptimeNanoseconds let error = operation() let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000 - try Self.checkCall(error, elapsed: elapsed, timeout: timeout) + do { + try Self.checkCall(error, elapsed: elapsed, timeout: timeout) + activity?.record(nil) + } catch let error as AXPlatformError { + activity?.record(error) + throw error + } } private func value(_ name: String) throws -> CFTypeRef { @@ -102,7 +128,8 @@ public struct AXElement { private func element(_ name: String) throws -> AXElement { let result: AXUIElement = try checkedCF(value(name), type: AXUIElementGetTypeID(), name: name) - return try AXElement(raw: result, timeout: timeout) + let element = try AXElement(raw: result, timeout: timeout) + return AXElement(raw: element.raw, timeout: timeout, activity: activity) } private func set(_ name: String, value: CFTypeRef) throws { @@ -132,7 +159,8 @@ public struct AXElement { } let object = Unmanaged.fromOpaque(pointer).takeUnretainedValue() let element: AXUIElement = try checkedCF(object, type: AXUIElementGetTypeID(), name: name) - return try AXElement(raw: element, timeout: timeout) + let wrapped = try AXElement(raw: element, timeout: timeout) + return AXElement(raw: wrapped.raw, timeout: timeout, activity: activity) } } } diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift index 8c234992..e4e3743c 100644 --- a/Sources/TesseraPlatform/AppThread.swift +++ b/Sources/TesseraPlatform/AppThread.swift @@ -83,7 +83,6 @@ public final class AppThread: Sendable { } /// The closure runs on the owning thread. Neither it nor its result may transfer AX objects. - /// A successful closure is treated as a responsive AX operation, even if it made no AX calls. public func perform( _ operation: @escaping @Sendable (AXElement) throws -> Value ) async throws -> Value { @@ -263,12 +262,13 @@ private final class AppThreadWorker: @unchecked Sendable { continuation.resume(throwing: AppThreadFailure.stopped) return } + let activity = AXCallActivity() do { - let result = try operation(application) - recordSuccess() + let result = try operation(application.tracking(activity)) + for event in timeouts.observe(activity) { events.yield(event) } continuation.resume(returning: result) } catch { - record(error) + for event in timeouts.observe(activity) { events.yield(event) } continuation.resume(throwing: error) } } @@ -542,6 +542,21 @@ struct AppThreadTimeoutTracker { mutating func otherFailure() { count = 0 } + + mutating func observe(_ activity: AXCallActivity) -> [AppThreadEvent] { + var events: [AppThreadEvent] = [] + for result in activity.results { + switch result { + case nil: + if succeeded() { events.append(.responsive) } + case .timedOut: + if timedOut() { events.append(.unresponsive) } + case .some: + otherFailure() + } + } + return events + } } // The lock protects the queue and run-loop handles; jobs themselves only run on the owner thread. diff --git a/Tests/TesseraPlatformTests/AppThreadTests.swift b/Tests/TesseraPlatformTests/AppThreadTests.swift index a5a8676e..d1f71448 100644 --- a/Tests/TesseraPlatformTests/AppThreadTests.swift +++ b/Tests/TesseraPlatformTests/AppThreadTests.swift @@ -63,6 +63,25 @@ import Testing #expect(tracker.succeeded() == true) } +@Test func responsivenessRequiresAnActualSuccessfulAXCall() { + var tracker = AppThreadTimeoutTracker(threshold: 2) + let first = AXCallActivity() + first.record(.timedOut) + first.record(.timedOut) + #expect(tracker.observe(first) == [.unresponsive]) + + let noCalls = AXCallActivity() + #expect(tracker.observe(noCalls).isEmpty) + let caughtTimeout = AXCallActivity() + caughtTimeout.record(.timedOut) + #expect(tracker.observe(caughtTimeout).isEmpty) + + let success = AXCallActivity() + success.record(nil) + #expect(tracker.observe(success) == [.responsive]) + #expect(tracker.observe(AXCallActivity()).isEmpty) +} + @Test func frameWriteCandidatesAreWindowSpecificAndConsumedPerAxis() { var tracker = AppThreadFrameWriteTracker() let id = UUID() -- knotmirror 0.0.1 From 8ef7d74c1bc3db42bd048525e94676f814b43008 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:19:51 -0400 Subject: [PATCH 28/44] Retry observer registrations --- Sources/TesseraPlatform/AppThread.swift | 46 +++++++++++++++---- .../TesseraPlatformTests/AppThreadTests.swift | 19 ++++++++ 2 files changed, 56 insertions(+), 9 deletions(-) diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift index e4e3743c..ccd7fc27 100644 --- a/Sources/TesseraPlatform/AppThread.swift +++ b/Sources/TesseraPlatform/AppThread.swift @@ -134,6 +134,7 @@ private final class AppThreadWorker: @unchecked Sendable { private var reconciliationTimer: CFRunLoopTimer? private var windows: [(raw: AXUIElement, id: CGWindowID)] = [] private var frameWrites = AppThreadFrameWriteTracker() + private var registrations = AppThreadRegistrationTracker() init(pid: pid_t, timeout: Float, timeoutThreshold: Int, events: AsyncStream.Continuation) { self.pid = pid @@ -162,9 +163,7 @@ private final class AppThreadWorker: @unchecked Sendable { } self.observer = observer CFRunLoopAddSource(CFRunLoopGetCurrent(), AXObserverGetRunLoopSource(observer), .defaultMode) - for notification in Self.applicationNotifications { - register(notification, on: application.raw, windowID: nil) - } + registerNotifications(Self.applicationNotifications, on: application.raw, windowID: nil) do { let initialWindows = try application.windows recordSuccess() @@ -214,6 +213,7 @@ private final class AppThreadWorker: @unchecked Sendable { private func reconcile() { guard let application else { return } do { + registerNotifications(Self.applicationNotifications, on: application.raw, windowID: nil) let current = try application.windows recordSuccess() var ids: [CGWindowID] = [] @@ -227,6 +227,7 @@ private final class AppThreadWorker: @unchecked Sendable { windows.removeAll { !present.contains($0.id) } for window in missing { frameWrites.clear(windowID: window.id) + registrations.remove(windowID: window.id) if let observer { for notification in Self.windowNotifications { let result = AXObserverRemoveNotification(observer, window.raw, notification as CFString) @@ -323,14 +324,21 @@ private final class AppThreadWorker: @unchecked Sendable { kAXWindowDeminiaturizedNotification, ] + private func registerNotifications(_ notifications: [String], on element: AXUIElement, windowID: CGWindowID?) { + for notification in notifications where registrations.needs(notification, windowID: windowID) { + register(notification, on: element, windowID: windowID) + } + } + private func register(_ notification: String, on element: AXUIElement, windowID: CGWindowID?) { guard let observer else { return } let start = DispatchTime.now().uptimeNanoseconds let result = AXObserverAddNotification( observer, element, notification as CFString, Unmanaged.passUnretained(self).toOpaque()) let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000 - if result == .success { - recordSuccess() + registrations.record(result, notification: notification, windowID: windowID) + if result == .success || result == .notificationAlreadyRegistered { + if result == .success { recordSuccess() } } else { if result == .cannotComplete && elapsed >= Double(timeout) * 0.9 { if timeouts.timedOut() { events.yield(.unresponsive) } @@ -343,14 +351,15 @@ private final class AppThreadWorker: @unchecked Sendable { } private func observe(_ window: AXElement) { - guard !windows.contains(where: { CFEqual($0.raw, window.raw) }) else { return } + if let known = windows.first(where: { CFEqual($0.raw, window.raw) }) { + registerNotifications(Self.windowNotifications, on: known.raw, windowID: known.id) + return + } do { let id = try window.windowID() recordSuccess() windows.append((window.raw, id)) - for notification in Self.windowNotifications { - register(notification, on: window.raw, windowID: id) - } + registerNotifications(Self.windowNotifications, on: window.raw, windowID: id) } catch { record(error) events.yield(.failure(.windowIdentification(String(describing: error)))) @@ -386,6 +395,7 @@ private final class AppThreadWorker: @unchecked Sendable { case kAXUIElementDestroyedNotification: windows.remove(at: index) frameWrites.clear(windowID: id) + registrations.remove(windowID: id) events.yield(.windowDestroyed(id)) case kAXWindowMovedNotification: events.yield(.windowMoved(id, origin: frameOrigin(windowID: id, raw: element, axis: .position))) @@ -454,6 +464,24 @@ enum AppThreadWindowReconciler { } } +struct AppThreadRegistrationTracker { + private var completed: [CGWindowID?: Set] = [:] + + func needs(_ notification: String, windowID: CGWindowID?) -> Bool { + !(completed[windowID]?.contains(notification) ?? false) + } + + mutating func record(_ result: AXError, notification: String, windowID: CGWindowID?) { + if result == .success || result == .notificationAlreadyRegistered || result == .notificationUnsupported { + completed[windowID, default: []].insert(notification) + } + } + + mutating func remove(windowID: CGWindowID) { + completed.removeValue(forKey: windowID) + } +} + struct AppThreadFrameWriteTracker { enum Axis { case position, size } static let maximumAgeNanoseconds: UInt64 = 500_000_000 diff --git a/Tests/TesseraPlatformTests/AppThreadTests.swift b/Tests/TesseraPlatformTests/AppThreadTests.swift index d1f71448..dc683568 100644 --- a/Tests/TesseraPlatformTests/AppThreadTests.swift +++ b/Tests/TesseraPlatformTests/AppThreadTests.swift @@ -63,6 +63,25 @@ import Testing #expect(tracker.succeeded() == true) } +@Test func observerRegistrationsRetryTransientFailuresIndependently() { + var tracker = AppThreadRegistrationTracker() + #expect(tracker.needs("moved", windowID: 1)) + tracker.record(.cannotComplete, notification: "moved", windowID: 1) + #expect(tracker.needs("moved", windowID: 1)) + tracker.record(.success, notification: "moved", windowID: 1) + #expect(!tracker.needs("moved", windowID: 1)) + #expect(tracker.needs("resized", windowID: 1)) + #expect(tracker.needs("moved", windowID: 2)) + tracker.record(.notificationUnsupported, notification: "resized", windowID: 1) + #expect(!tracker.needs("resized", windowID: 1)) + tracker.record(.notificationAlreadyRegistered, notification: "focused", windowID: nil) + #expect(!tracker.needs("focused", windowID: nil)) + tracker.remove(windowID: 1) + #expect(tracker.needs("moved", windowID: 1)) + #expect(tracker.needs("resized", windowID: 1)) + #expect(!tracker.needs("focused", windowID: nil)) +} + @Test func responsivenessRequiresAnActualSuccessfulAXCall() { var tracker = AppThreadTimeoutTracker(threshold: 2) let first = AXCallActivity() -- knotmirror 0.0.1 From cd960e2bfbe9db19d09dbe99f7aacde2cc346926 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:20:41 -0400 Subject: [PATCH 29/44] Keep one AX owner per app --- Sources/TesseraPlatform/AppThread.swift | 23 +++++++++++++++++-- .../PlatformIntegrationTests.swift | 11 +++++---- .../TesseraPlatformTests/AppThreadTests.swift | 17 ++++++++++++++ 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift index ccd7fc27..3bdd95ff 100644 --- a/Sources/TesseraPlatform/AppThread.swift +++ b/Sources/TesseraPlatform/AppThread.swift @@ -3,6 +3,7 @@ import CoreFoundation public import CoreGraphics import Darwin public import Foundation +import Synchronization /// Events contain window server IDs rather than AX objects, which stay on the app thread. public enum AppThreadEvent: Sendable, Equatable { @@ -50,6 +51,7 @@ public enum AppThreadEventOrigin: Sendable, Equatable { public enum AppThreadFailure: Error, Sendable, Equatable { case stopped case runLoopUnavailable + case alreadyOwned(pid_t) case initialization(String) case observerCreation(Int32) case observerRegistration(notification: String, windowID: CGWindowID?, code: Int32) @@ -67,9 +69,10 @@ public final class AppThread: Sendable { private let worker: AppThreadWorker private let executor: AppThreadExecutor - public init(pid: pid_t, timeout: Float = 0.35, timeoutThreshold: Int = 3) { + public init(pid: pid_t, timeout: Float = 0.35, timeoutThreshold: Int = 3) throws { precondition(timeout > 0 && timeout.isFinite) precondition(timeoutThreshold > 0) + guard AppThreadOwnerRegistry.shared.acquire(pid) else { throw AppThreadFailure.alreadyOwned(pid) } let (events, continuation) = AsyncStream.makeStream() self.events = events let worker = AppThreadWorker( @@ -77,7 +80,10 @@ public final class AppThread: Sendable { self.worker = worker self.executor = AppThreadExecutor( start: { worker.start() }, - stop: { worker.stop() }, + stop: { + worker.stop() + AppThreadOwnerRegistry.shared.release(pid) + }, failure: { worker.executorFailed() } ) } @@ -122,6 +128,19 @@ public final class AppThread: Sendable { } } +final class AppThreadOwnerRegistry: Sendable { + static let shared = AppThreadOwnerRegistry() + private let owners = Mutex>([]) + + func acquire(_ pid: pid_t) -> Bool { + owners.withLock { $0.insert(pid).inserted } + } + + func release(_ pid: pid_t) { + owners.withLock { _ = $0.remove(pid) } + } +} + // This object is accessed only by its executor's thread, including observer callbacks. private final class AppThreadWorker: @unchecked Sendable { private let pid: pid_t diff --git a/Tests/TesseraE2ETests/PlatformIntegrationTests.swift b/Tests/TesseraE2ETests/PlatformIntegrationTests.swift index 2df7d819..c21f4a7e 100644 --- a/Tests/TesseraE2ETests/PlatformIntegrationTests.swift +++ b/Tests/TesseraE2ETests/PlatformIntegrationTests.swift @@ -172,8 +172,11 @@ struct PlatformIntegrationTests { let fixture = try PlatformFixture( arguments: ["--windows", "2", "--title", "Platform Frames", "--min-size", "720x540"]) defer { fixture.stop() } - let thread = AppThread(pid: fixture.process.processIdentifier) + let thread = try AppThread(pid: fixture.process.processIdentifier) defer { thread.shutdown() } + #expect(throws: AppThreadFailure.alreadyOwned(fixture.process.processIdentifier)) { + try AppThread(pid: fixture.process.processIdentifier) + } let first = try await platformWindow(thread, title: "Platform Frames 1") let second = try await platformWindow(thread, title: "Platform Frames 2") @@ -213,8 +216,8 @@ struct PlatformIntegrationTests { defer { healthyFixture.stop() } let slowFixture = try PlatformFixture(arguments: ["--title", "Platform Slow", "--slow", "1200"]) defer { slowFixture.stop() } - let healthy = AppThread(pid: healthyFixture.process.processIdentifier) - let slow = AppThread(pid: slowFixture.process.processIdentifier, timeout: 0.35) + let healthy = try AppThread(pid: healthyFixture.process.processIdentifier) + let slow = try AppThread(pid: slowFixture.process.processIdentifier, timeout: 0.35) defer { healthy.shutdown() slow.shutdown() @@ -275,7 +278,7 @@ struct PlatformIntegrationTests { try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") let fixture = try PlatformFixture(arguments: ["--title", "Platform Events"]) defer { fixture.stop() } - let thread = AppThread(pid: fixture.process.processIdentifier) + let thread = try AppThread(pid: fixture.process.processIdentifier) defer { thread.shutdown() } let window = try await platformWindow(thread, title: "Platform Events 1") let wasMinimized = try await within(8, "initial minimized state") { diff --git a/Tests/TesseraPlatformTests/AppThreadTests.swift b/Tests/TesseraPlatformTests/AppThreadTests.swift index dc683568..f6eca330 100644 --- a/Tests/TesseraPlatformTests/AppThreadTests.swift +++ b/Tests/TesseraPlatformTests/AppThreadTests.swift @@ -63,6 +63,23 @@ import Testing #expect(tracker.succeeded() == true) } +@Test func applicationOwnersAreExclusiveAndCanBeReleased() async { + let registry = AppThreadOwnerRegistry() + let results = await withTaskGroup(of: Bool.self, returning: [Bool].self) { group in + for _ in 0..<20 { + group.addTask { registry.acquire(123) } + } + var results: [Bool] = [] + for await result in group { results.append(result) } + return results + } + #expect(results.filter { $0 }.count == 1) + #expect(registry.acquire(456)) + registry.release(123) + #expect(registry.acquire(123)) + #expect(!registry.acquire(456)) +} + @Test func observerRegistrationsRetryTransientFailuresIndependently() { var tracker = AppThreadRegistrationTracker() #expect(tracker.needs("moved", windowID: 1)) -- knotmirror 0.0.1 From c7a1cb094177aa5f088188936fe9b3fd34b2bf48 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:21:19 -0400 Subject: [PATCH 30/44] Handle missing window identities --- Sources/TesseraPlatform/AppThread.swift | 47 ++++++++++++++----- .../TesseraPlatformTests/AppThreadTests.swift | 30 ++++++++++++ 2 files changed, 66 insertions(+), 11 deletions(-) diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift index 3bdd95ff..a30403b0 100644 --- a/Sources/TesseraPlatform/AppThread.swift +++ b/Sources/TesseraPlatform/AppThread.swift @@ -236,11 +236,19 @@ private final class AppThreadWorker: @unchecked Sendable { let current = try application.windows recordSuccess() var ids: [CGWindowID] = [] + var incomplete = false for window in current { - ids.append(try window.windowID()) - recordSuccess() - observe(window) + do { + ids.append(try window.windowID()) + recordSuccess() + observe(window) + } catch { + incomplete = true + record(error) + events.yield(.failure(.windowIdentification(String(describing: error)))) + } } + guard !incomplete else { return } let present = Set(ids) let missing = windows.filter { !present.contains($0.id) } windows.removeAll { !present.contains($0.id) } @@ -307,14 +315,12 @@ private final class AppThreadWorker: @unchecked Sendable { return } do { - var found: AXElement? - for window in try application.windows { - if try window.windowID() == windowID { - found = window - break - } - } - guard let window = found else { throw AppThreadFailure.windowNotFound(windowID) } + let window = try AppThreadWindowLookup.find( + in: application.windows, windowID: windowID, + identify: { try $0.windowID() }, + onFailure: { events.yield(.failure(.windowIdentification(String(describing: $0)))) } + ) + guard let window else { throw AppThreadFailure.windowNotFound(windowID) } observe(window) let before = try window.frame let actual = try window.writeFrame( @@ -483,6 +489,25 @@ enum AppThreadWindowReconciler { } } +enum AppThreadWindowLookup { + static func find( + in windows: [Window], windowID: CGWindowID, identify: (Window) throws -> CGWindowID, + onFailure: (any Error) -> Void + ) throws -> Window? { + var firstError: (any Error)? + for window in windows { + do { + if try identify(window) == windowID { return window } + } catch { + if firstError == nil { firstError = error } + onFailure(error) + } + } + if let firstError { throw firstError } + return nil + } +} + struct AppThreadRegistrationTracker { private var completed: [CGWindowID?: Set] = [:] diff --git a/Tests/TesseraPlatformTests/AppThreadTests.swift b/Tests/TesseraPlatformTests/AppThreadTests.swift index f6eca330..ee05aa58 100644 --- a/Tests/TesseraPlatformTests/AppThreadTests.swift +++ b/Tests/TesseraPlatformTests/AppThreadTests.swift @@ -63,6 +63,36 @@ import Testing #expect(tracker.succeeded() == true) } +@Test func windowLookupContinuesPastUnidentifiableWindows() throws { + var failures: [AXPlatformError] = [] + let result = try AppThreadWindowLookup.find( + in: [1, 2, 3], windowID: 3, + identify: { value in + if value == 1 { throw AXPlatformError.elementInvalid } + return CGWindowID(value) + }, + onFailure: { error in + if let error = error as? AXPlatformError { failures.append(error) } + } + ) + #expect(result == 3) + #expect(failures == [.elementInvalid]) + + #expect(throws: AXPlatformError.elementInvalid) { + try AppThreadWindowLookup.find( + in: [1, 2], windowID: 3, + identify: { value in + if value == 1 { throw AXPlatformError.elementInvalid } + return CGWindowID(value) + }, onFailure: { _ in } + ) + } + let absent = try AppThreadWindowLookup.find( + in: [1, 2], windowID: 3, identify: { CGWindowID($0) }, onFailure: { _ in } + ) + #expect(absent == nil) +} + @Test func applicationOwnersAreExclusiveAndCanBeReleased() async { let registry = AppThreadOwnerRegistry() let results = await withTaskGroup(of: Bool.self, returning: [Bool].self) { group in -- knotmirror 0.0.1 From de043f17e40e0e7f51d32bbe1bfaa193c97c0a6c Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:22:15 -0400 Subject: [PATCH 31/44] Report overdue accessibility calls --- Sources/TesseraPlatform/AXElement.swift | 65 ++++++++++++++++--- Sources/TesseraPlatform/AppThread.swift | 21 +++++- .../TesseraPlatformTests/AppThreadTests.swift | 27 ++++++++ 3 files changed, 101 insertions(+), 12 deletions(-) diff --git a/Sources/TesseraPlatform/AXElement.swift b/Sources/TesseraPlatform/AXElement.swift index 9ee09e36..a1d9bf8e 100644 --- a/Sources/TesseraPlatform/AXElement.swift +++ b/Sources/TesseraPlatform/AXElement.swift @@ -2,6 +2,7 @@ public import ApplicationServices public import CoreGraphics import Darwin import Foundation +import Synchronization public enum AXPlatformError: Error, Equatable, Sendable { case notPermitted @@ -30,6 +31,47 @@ func checkAX(_ error: AXError) throws { guard error == .success else { throw AXPlatformError(error) } } +final class AXCallWatchdog: Sendable { + private struct State { + var next: UInt64 = 0 + var active: UInt64? + } + private let state = Mutex(State()) + private let schedule: @Sendable (@escaping @Sendable () -> Void) -> Void + private let overdue: @Sendable () -> Void + + init( + schedule: @escaping @Sendable (@escaping @Sendable () -> Void) -> Void, + overdue: @escaping @Sendable () -> Void + ) { + self.schedule = schedule + self.overdue = overdue + } + + func begin() -> UInt64 { + let token = state.withLock { state in + state.next &+= 1 + state.active = state.next + return state.next + } + schedule { [self] in + let expired = state.withLock { state in + guard state.active == token else { return false } + state.active = nil + return true + } + if expired { overdue() } + } + return token + } + + func end(_ token: UInt64) { + state.withLock { state in + if state.active == token { state.active = nil } + } + } +} + final class AXCallActivity { private(set) var results: [AXPlatformError?] = [] @@ -42,27 +84,30 @@ public struct AXElement { let raw: AXUIElement let timeout: Float private let activity: AXCallActivity? + private let watchdog: AXCallWatchdog? - init(applicationPID: pid_t, timeout: Float = 0.35) throws { - try self.init(raw: AXUIElementCreateApplication(applicationPID), timeout: timeout) + init(applicationPID: pid_t, timeout: Float = 0.35, watchdog: AXCallWatchdog? = nil) throws { + try self.init(raw: AXUIElementCreateApplication(applicationPID), timeout: timeout, watchdog: watchdog) } - init(raw: AXUIElement, timeout: Float = 0.35) throws { + init(raw: AXUIElement, timeout: Float = 0.35, watchdog: AXCallWatchdog? = nil) throws { guard timeout.isFinite, timeout > 0 else { throw AXPlatformError.other(AXError.illegalArgument.rawValue) } try checkAX(AXUIElementSetMessagingTimeout(raw, timeout)) self.raw = raw self.timeout = timeout self.activity = nil + self.watchdog = watchdog } - private init(raw: AXUIElement, timeout: Float, activity: AXCallActivity?) { + private init(raw: AXUIElement, timeout: Float, activity: AXCallActivity?, watchdog: AXCallWatchdog?) { self.raw = raw self.timeout = timeout self.activity = activity + self.watchdog = watchdog } func tracking(_ activity: AXCallActivity) -> AXElement { - AXElement(raw: raw, timeout: timeout, activity: activity) + AXElement(raw: raw, timeout: timeout, activity: activity, watchdog: watchdog) } static func checkCall(_ error: AXError, elapsed: Double, timeout: Float) throws { @@ -74,6 +119,8 @@ public struct AXElement { } private func callAX(_ operation: () -> AXError) throws { + let token = watchdog?.begin() + defer { if let token { watchdog?.end(token) } } let start = DispatchTime.now().uptimeNanoseconds let error = operation() let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start) / 1_000_000_000 @@ -128,8 +175,8 @@ public struct AXElement { private func element(_ name: String) throws -> AXElement { let result: AXUIElement = try checkedCF(value(name), type: AXUIElementGetTypeID(), name: name) - let element = try AXElement(raw: result, timeout: timeout) - return AXElement(raw: element.raw, timeout: timeout, activity: activity) + let element = try AXElement(raw: result, timeout: timeout, watchdog: watchdog) + return AXElement(raw: element.raw, timeout: timeout, activity: activity, watchdog: watchdog) } private func set(_ name: String, value: CFTypeRef) throws { @@ -159,8 +206,8 @@ public struct AXElement { } let object = Unmanaged.fromOpaque(pointer).takeUnretainedValue() let element: AXUIElement = try checkedCF(object, type: AXUIElementGetTypeID(), name: name) - let wrapped = try AXElement(raw: element, timeout: timeout) - return AXElement(raw: wrapped.raw, timeout: timeout, activity: activity) + let wrapped = try AXElement(raw: element, timeout: timeout, watchdog: watchdog) + return AXElement(raw: wrapped.raw, timeout: timeout, activity: activity, watchdog: watchdog) } } } diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift index a30403b0..85f91c46 100644 --- a/Sources/TesseraPlatform/AppThread.swift +++ b/Sources/TesseraPlatform/AppThread.swift @@ -51,6 +51,7 @@ public enum AppThreadEventOrigin: Sendable, Equatable { public enum AppThreadFailure: Error, Sendable, Equatable { case stopped case runLoopUnavailable + case operationOverdue case alreadyOwned(pid_t) case initialization(String) case observerCreation(Int32) @@ -146,6 +147,7 @@ private final class AppThreadWorker: @unchecked Sendable { private let pid: pid_t private let timeout: Float private let events: AsyncStream.Continuation + private let watchdog: AXCallWatchdog private var timeouts: AppThreadTimeoutTracker private var application: AXElement? private var startupFailure: AppThreadFailure? @@ -159,14 +161,22 @@ private final class AppThreadWorker: @unchecked Sendable { self.pid = pid self.timeout = timeout self.events = events + let deadline = max(1, Double(timeout) * 2) + self.watchdog = AXCallWatchdog( + schedule: { action in + DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + deadline, execute: action) + }, + overdue: { events.yield(.failure(.operationOverdue)) } + ) self.timeouts = AppThreadTimeoutTracker(threshold: timeoutThreshold) } func start() { do { - let application = try AXElement(applicationPID: pid, timeout: timeout) + let application = try AXElement(applicationPID: pid, timeout: timeout, watchdog: watchdog) self.application = application var observer: AXObserver? + let token = watchdog.begin() let result = AXObserverCreate( pid, { _, element, notification, context in @@ -174,6 +184,7 @@ private final class AppThreadWorker: @unchecked Sendable { let worker = Unmanaged.fromOpaque(context).takeUnretainedValue() worker.receive(element: element, notification: notification as String) }, &observer) + watchdog.end(token) guard result == .success, let observer else { let failure = AppThreadFailure.observerCreation(result.rawValue) startupFailure = failure @@ -257,7 +268,9 @@ private final class AppThreadWorker: @unchecked Sendable { registrations.remove(windowID: window.id) if let observer { for notification in Self.windowNotifications { + let token = watchdog.begin() let result = AXObserverRemoveNotification(observer, window.raw, notification as CFString) + watchdog.end(token) if result != .success && result != .notificationNotRegistered { events.yield( .failure( @@ -357,6 +370,8 @@ private final class AppThreadWorker: @unchecked Sendable { private func register(_ notification: String, on element: AXUIElement, windowID: CGWindowID?) { guard let observer else { return } + let token = watchdog.begin() + defer { watchdog.end(token) } let start = DispatchTime.now().uptimeNanoseconds let result = AXObserverAddNotification( observer, element, notification as CFString, Unmanaged.passUnretained(self).toOpaque()) @@ -395,7 +410,7 @@ private final class AppThreadWorker: @unchecked Sendable { switch notification { case kAXWindowCreatedNotification: do { - let window = try AXElement(raw: element, timeout: timeout) + let window = try AXElement(raw: element, timeout: timeout, watchdog: watchdog) observe(window) if let id = windows.first(where: { CFEqual($0.raw, element) })?.id { events.yield(.windowCreated(id)) @@ -439,7 +454,7 @@ private final class AppThreadWorker: @unchecked Sendable { { guard frameWrites.hasCandidate(windowID: windowID, axis: axis) else { return .unattributed } do { - let frame = try AXElement(raw: raw, timeout: timeout).frame + let frame = try AXElement(raw: raw, timeout: timeout, watchdog: watchdog).frame recordSuccess() return frameWrites.match(windowID: windowID, axis: axis, frame: frame) } catch { diff --git a/Tests/TesseraPlatformTests/AppThreadTests.swift b/Tests/TesseraPlatformTests/AppThreadTests.swift index ee05aa58..ca58971c 100644 --- a/Tests/TesseraPlatformTests/AppThreadTests.swift +++ b/Tests/TesseraPlatformTests/AppThreadTests.swift @@ -2,6 +2,7 @@ import CoreFoundation import CoreGraphics import Darwin import Foundation +import Synchronization import Testing @testable import TesseraPlatform @@ -63,6 +64,32 @@ import Testing #expect(tracker.succeeded() == true) } +@Test func callWatchdogReportsOnlyAnOperationStillInFlight() { + let scheduled = Mutex<[@Sendable () -> Void]>([]) + let reports = Mutex(0) + let watchdog = AXCallWatchdog( + schedule: { action in scheduled.withLock { $0.append(action) } }, + overdue: { reports.withLock { $0 += 1 } } + ) + let completed = watchdog.begin() + watchdog.end(completed) + let blocked = watchdog.begin() + let callbacks = scheduled.withLock { $0 } + callbacks[0]() + #expect(reports.withLock { $0 } == 0) + callbacks[1]() + callbacks[1]() + #expect(reports.withLock { $0 } == 1) + watchdog.end(blocked) + + let next = watchdog.begin() + watchdog.end(blocked) + let last = scheduled.withLock { $0[2] } + last() + #expect(reports.withLock { $0 } == 2) + watchdog.end(next) +} + @Test func windowLookupContinuesPastUnidentifiableWindows() throws { var failures: [AXPlatformError] = [] let result = try AppThreadWindowLookup.find( -- knotmirror 0.0.1 From 3e6bcf7f1044ec4648e51b349167fc40d5db6a81 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:22:39 -0400 Subject: [PATCH 32/44] Report window identity capability --- Sources/TesseraPlatform/WindowServer.swift | 4 ++++ Tests/TesseraPlatformTests/WindowServerTests.swift | 8 ++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/Sources/TesseraPlatform/WindowServer.swift b/Sources/TesseraPlatform/WindowServer.swift index c3265633..22cf45fe 100644 --- a/Sources/TesseraPlatform/WindowServer.swift +++ b/Sources/TesseraPlatform/WindowServer.swift @@ -23,6 +23,7 @@ public struct WindowServer: Sendable { public let currentSpace: Bool public let windowListBrightness: Bool public let brightnessConnection: Bool + public let axWindowID: Bool public var canReadDisplaySpaces: Bool { mainConnection && managedDisplaySpaces } public var canReadCurrentSpace: Bool { mainConnection && currentSpace } @@ -34,6 +35,7 @@ public struct WindowServer: Sendable { managedDisplaySpaces = probe("SLSCopyManagedDisplaySpaces") currentSpace = probe("SLSManagedDisplayGetCurrentSpace") windowListBrightness = probe("CGSSetWindowListBrightness") + axWindowID = probe("_AXUIElementGetWindow") } } @@ -254,6 +256,7 @@ private final class RuntimeSymbols: @unchecked Sendable { let spaces = lookup(skyLight, "SLSCopyManagedDisplaySpaces") let current = lookup(skyLight, "SLSManagedDisplayGetCurrentSpace") let brightness = lookup(skyLight, "CGSSetWindowListBrightness") + let axWindowID = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "_AXUIElementGetWindow") mainConnection = connection managedDisplaySpaces = spaces currentSpace = current @@ -264,6 +267,7 @@ private final class RuntimeSymbols: @unchecked Sendable { case "SLSCopyManagedDisplaySpaces": spaces != nil case "SLSManagedDisplayGetCurrentSpace": current != nil case "CGSSetWindowListBrightness": brightness != nil + case "_AXUIElementGetWindow": axWindowID != nil default: false } } diff --git a/Tests/TesseraPlatformTests/WindowServerTests.swift b/Tests/TesseraPlatformTests/WindowServerTests.swift index 514136b8..ac0dde87 100644 --- a/Tests/TesseraPlatformTests/WindowServerTests.swift +++ b/Tests/TesseraPlatformTests/WindowServerTests.swift @@ -15,7 +15,9 @@ private func windowFields() -> [String: Any] { } @Test func probesCapabilitiesIndependently() { - let available: Set = ["SLSMainConnectionID", "SLSCopyManagedDisplaySpaces", "CGSSetWindowListBrightness"] + let available: Set = [ + "SLSMainConnectionID", "SLSCopyManagedDisplaySpaces", "CGSSetWindowListBrightness", "_AXUIElementGetWindow", + ] var probed: [String] = [] let capabilities = WindowServer.Capabilities { symbol in probed.append(symbol) @@ -24,9 +26,10 @@ private func windowFields() -> [String: Any] { #expect( probed == [ "SLSMainConnectionID", "SLSCopyManagedDisplaySpaces", "SLSManagedDisplayGetCurrentSpace", - "CGSSetWindowListBrightness", + "CGSSetWindowListBrightness", "_AXUIElementGetWindow", ]) #expect(capabilities.mainConnection) + #expect(capabilities.axWindowID) #expect(capabilities.managedDisplaySpaces) #expect(!capabilities.currentSpace) #expect(capabilities.experimentalBrightness) @@ -46,6 +49,7 @@ private func windowFields() -> [String: Any] { #expect(!missingBrightness.experimentalBrightness) let noSymbols = WindowServer.Capabilities { _ in false } #expect(!noSymbols.experimentalBrightness) + #expect(!noSymbols.axWindowID) #expect(!noSymbols.canReadDisplaySpaces) #expect(!noSymbols.canReadCurrentSpace) } -- knotmirror 0.0.1 From 07dec46a04bd1092bcaac75560d5ad4209b12faa Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:23:35 -0400 Subject: [PATCH 33/44] Tag repeated frame notifications --- Sources/TesseraPlatform/AppThread.swift | 39 +++++++++++-------- .../TesseraPlatformTests/AppThreadTests.swift | 20 ++++++++-- 2 files changed, 40 insertions(+), 19 deletions(-) diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift index 85f91c46..4e2bf24e 100644 --- a/Sources/TesseraPlatform/AppThread.swift +++ b/Sources/TesseraPlatform/AppThread.swift @@ -336,11 +336,23 @@ private final class AppThreadWorker: @unchecked Sendable { guard let window else { throw AppThreadFailure.windowNotFound(windowID) } observe(window) let before = try window.frame - let actual = try window.writeFrame( - target, application: application, assistiveTechnology: assistiveTechnology) - frameWrites.record(windowID: windowID, writeID: writeID, before: before, actual: actual) - recordSuccess() - continuation.resume(returning: actual) + do { + let actual = try window.writeFrame( + target, application: application, assistiveTechnology: assistiveTechnology) + frameWrites.record( + windowID: windowID, writeID: writeID, before: before, actual: actual, attempted: target) + recordSuccess() + continuation.resume(returning: actual) + } catch { + do { + let actual = try window.frame + frameWrites.record( + windowID: windowID, writeID: writeID, before: before, actual: actual, attempted: target) + } catch let readError { + events.yield(.failure(.windowFrame(String(describing: readError)))) + } + throw error + } } catch { record(error) continuation.resume(throwing: error) @@ -554,11 +566,12 @@ struct AppThreadFrameWriteTracker { private var candidates: [CGWindowID: Candidate] = [:] mutating func record( - windowID: CGWindowID, writeID: UUID, before: CGRect, actual: CGRect, + windowID: CGWindowID, writeID: UUID, before: CGRect, actual: CGRect, attempted: CGRect? = nil, now: UInt64 = DispatchTime.now().uptimeNanoseconds ) { - let position = before.origin != actual.origin - let size = before.size != actual.size + let attemptedWrite = attempted.map { $0 != before } ?? false + let position = before.origin != actual.origin || attemptedWrite + let size = before.size != actual.size || attemptedWrite candidates[windowID] = position || size ? Candidate(id: writeID, frame: actual, createdAt: now, position: position, size: size) : nil @@ -588,17 +601,11 @@ struct AppThreadFrameWriteTracker { guard hasCandidate(windowID: windowID, axis: axis, now: now), let candidateValue = candidates[windowID] else { return .unattributed } - var candidate = candidateValue - guard candidate.frame == frame else { + guard candidateValue.frame == frame else { clear(windowID: windowID) return .unattributed } - switch axis { - case .position: candidate.position = false - case .size: candidate.size = false - } - candidates[windowID] = candidate.position || candidate.size ? candidate : nil - return .possiblySelfGenerated(candidate.id) + return .possiblySelfGenerated(candidateValue.id) } } diff --git a/Tests/TesseraPlatformTests/AppThreadTests.swift b/Tests/TesseraPlatformTests/AppThreadTests.swift index ca58971c..c48a8b65 100644 --- a/Tests/TesseraPlatformTests/AppThreadTests.swift +++ b/Tests/TesseraPlatformTests/AppThreadTests.swift @@ -175,7 +175,7 @@ import Testing #expect(tracker.observe(AXCallActivity()).isEmpty) } -@Test func frameWriteCandidatesAreWindowSpecificAndConsumedPerAxis() { +@Test func frameWriteCandidatesAreWindowSpecificAndTagRepeatedNotifications() { var tracker = AppThreadFrameWriteTracker() let id = UUID() let before = CGRect(x: 0, y: 0, width: 100, height: 100) @@ -183,9 +183,10 @@ import Testing tracker.record(windowID: 1, writeID: id, before: before, actual: actual) #expect(tracker.match(windowID: 2, axis: .position, frame: actual) == .unattributed) #expect(tracker.match(windowID: 1, axis: .position, frame: actual) == .possiblySelfGenerated(id)) - #expect(tracker.match(windowID: 1, axis: .position, frame: actual) == .unattributed) + #expect(tracker.match(windowID: 1, axis: .position, frame: actual) == .possiblySelfGenerated(id)) #expect(tracker.match(windowID: 1, axis: .size, frame: actual) == .possiblySelfGenerated(id)) - #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) + #expect(tracker.match(windowID: 1, axis: .size, frame: actual) == .possiblySelfGenerated(id)) + #expect(tracker.hasCandidate(windowID: 1, axis: .size) == true) } @Test func mismatchedAndSupersededFrameCandidatesAreNotTagged() { @@ -208,6 +209,19 @@ import Testing #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) } +@Test func frameWriteCandidateCoversClampedOrPartialWrites() { + var tracker = AppThreadFrameWriteTracker() + let before = CGRect(x: 0, y: 0, width: 100, height: 100) + let requested = CGRect(x: 10, y: 20, width: 120, height: 130) + let id = UUID() + tracker.record(windowID: 1, writeID: id, before: before, actual: before, attempted: requested) + #expect(tracker.match(windowID: 1, axis: .position, frame: before) == .possiblySelfGenerated(id)) + #expect(tracker.match(windowID: 1, axis: .size, frame: before) == .possiblySelfGenerated(id)) + let userChange = CGRect(x: 20, y: 20, width: 100, height: 100) + #expect(tracker.match(windowID: 1, axis: .position, frame: userChange) == .unattributed) + #expect(tracker.hasCandidate(windowID: 1, axis: .size) == false) +} + @Test func frameWriteCandidatesExpireAtBoundedDeadline() { var tracker = AppThreadFrameWriteTracker() let before = CGRect(x: 0, y: 0, width: 100, height: 100) -- knotmirror 0.0.1 From 527df1738318687b038d45c630fb100b45fdc548 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:24:33 -0400 Subject: [PATCH 34/44] Report application exits --- Sources/TesseraPlatform/AppThread.swift | 32 ++++++++++- .../PlatformIntegrationTests.swift | 57 +++++++++++++++++++ .../TesseraPlatformTests/AppThreadTests.swift | 21 +++++++ 3 files changed, 109 insertions(+), 1 deletion(-) diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift index 4e2bf24e..1b50deb5 100644 --- a/Sources/TesseraPlatform/AppThread.swift +++ b/Sources/TesseraPlatform/AppThread.swift @@ -17,6 +17,7 @@ public enum AppThreadEvent: Sendable, Equatable { case focusedWindowChanged case applicationActivated case applicationDeactivated + case applicationTerminated case windowList([CGWindowID]) case reconciliation(AppThreadReconciliation) case unresponsive @@ -69,6 +70,7 @@ public final class AppThread: Sendable { public let events: AsyncStream private let worker: AppThreadWorker private let executor: AppThreadExecutor + private let exitObserver: AppProcessObserver public init(pid: pid_t, timeout: Float = 0.35, timeoutThreshold: Int = 3) throws { precondition(timeout > 0 && timeout.isFinite) @@ -79,7 +81,7 @@ public final class AppThread: Sendable { let worker = AppThreadWorker( pid: pid, timeout: timeout, timeoutThreshold: timeoutThreshold, events: continuation) self.worker = worker - self.executor = AppThreadExecutor( + let executor = AppThreadExecutor( start: { worker.start() }, stop: { worker.stop() @@ -87,6 +89,11 @@ public final class AppThread: Sendable { }, failure: { worker.executorFailed() } ) + self.executor = executor + self.exitObserver = AppProcessObserver(pid: pid) { [weak executor] in + continuation.yield(.applicationTerminated) + executor?.shutdown() + } } /// The closure runs on the owning thread. Neither it nor its result may transfer AX objects. @@ -121,14 +128,37 @@ public final class AppThread: Sendable { /// Requests shutdown without waiting for an in-flight AX call to return. public func shutdown() { + exitObserver.cancel() executor.shutdown() } deinit { + exitObserver.cancel() executor.shutdown() } } +final class AppProcessObserver: @unchecked Sendable { + private let source: any DispatchSourceProcess + + init( + pid: pid_t, onRegistration: @escaping @Sendable () -> Void = {}, onExit: @escaping @Sendable () -> Void + ) { + source = DispatchSource.makeProcessSource(identifier: pid, eventMask: .exit, queue: .global(qos: .utility)) + source.setRegistrationHandler(handler: onRegistration) + source.setEventHandler(handler: onExit) + source.resume() + } + + func cancel() { + source.cancel() + } + + deinit { + source.cancel() + } +} + final class AppThreadOwnerRegistry: Sendable { static let shared = AppThreadOwnerRegistry() private let owners = Mutex>([]) diff --git a/Tests/TesseraE2ETests/PlatformIntegrationTests.swift b/Tests/TesseraE2ETests/PlatformIntegrationTests.swift index c21f4a7e..0555f16a 100644 --- a/Tests/TesseraE2ETests/PlatformIntegrationTests.swift +++ b/Tests/TesseraE2ETests/PlatformIntegrationTests.swift @@ -184,6 +184,9 @@ struct PlatformIntegrationTests { let all = try await platformWindows(thread) #expect(all.contains { $0.id == first.id && $0.title == first.title }) #expect(all.contains { $0.id == second.id && $0.title == second.title }) + let serverWindows = try WindowServer().windows() + #expect(serverWindows.contains { $0.number == first.id && $0.pid == fixture.process.processIdentifier }) + #expect(serverWindows.contains { $0.number == second.id && $0.pid == fixture.process.processIdentifier }) let target = CGRect( x: first.frame.minX + 30, y: first.frame.minY + 25, @@ -205,6 +208,60 @@ struct PlatformIntegrationTests { #expect(close(clampedReadBack.frame, clamped), "Clamped frame did not match AX readback") } + @Test( + .enabled( + if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", + "Accessibility permission is required for frame notification tests" + )) + func tagsFrameWriteNotifications() async throws { + try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") + let fixture = try PlatformFixture(arguments: ["--title", "Platform Tagged"]) + defer { fixture.stop() } + let thread = try AppThread(pid: fixture.process.processIdentifier) + defer { thread.shutdown() } + let window = try await platformWindow(thread, title: "Platform Tagged 1") + let writeID = UUID() + let event = Task { + try await within(8, "tagged frame event") { + for await event in thread.events { + if case .windowMoved(let id, .possiblySelfGenerated(let candidate)) = event, + id == window.id && candidate == writeID + { + return event + } + } + throw PlatformTestError(description: "Event stream ended before a tagged frame event") + } + } + let target = window.frame.offsetBy(dx: 30, dy: 25) + _ = try await within(8, "tagged frame write") { + try await thread.writeFrame(windowID: window.id, target: target, writeID: writeID) + } + #expect(try await event.value == .windowMoved(window.id, origin: .possiblySelfGenerated(writeID))) + } + + @Test( + .enabled( + if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", + "Accessibility permission is required for platform termination tests" + )) + func reportsApplicationTermination() async throws { + try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") + let fixture = try PlatformFixture(arguments: ["--title", "Platform Exit"]) + defer { fixture.stop() } + let thread = try AppThread(pid: fixture.process.processIdentifier) + defer { thread.shutdown() } + _ = try await platformWindow(thread, title: "Platform Exit 1") + let event = Task { + try await within(8, "application termination") { + for await event in thread.events where event == .applicationTerminated { return event } + throw PlatformTestError(description: "Event stream ended before application termination") + } + } + fixture.stop() + #expect(try await event.value == .applicationTerminated) + } + @Test( .enabled( if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", diff --git a/Tests/TesseraPlatformTests/AppThreadTests.swift b/Tests/TesseraPlatformTests/AppThreadTests.swift index c48a8b65..01e4538f 100644 --- a/Tests/TesseraPlatformTests/AppThreadTests.swift +++ b/Tests/TesseraPlatformTests/AppThreadTests.swift @@ -64,6 +64,27 @@ import Testing #expect(tracker.succeeded() == true) } +@Test func processObserverReportsExitWithoutAccessibility() throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sleep") + process.arguments = ["30"] + try process.run() + defer { + if process.isRunning { process.terminate() } + process.waitUntilExit() + } + let registered = DispatchSemaphore(value: 0) + let exited = DispatchSemaphore(value: 0) + let observer = AppProcessObserver( + pid: process.processIdentifier, + onRegistration: { registered.signal() }, onExit: { exited.signal() } + ) + defer { observer.cancel() } + #expect(registered.wait(timeout: .now() + 3) == .success) + process.terminate() + #expect(exited.wait(timeout: .now() + 3) == .success) +} + @Test func callWatchdogReportsOnlyAnOperationStillInFlight() { let scheduled = Mutex<[@Sendable () -> Void]>([]) let reports = Mutex(0) -- knotmirror 0.0.1 From 64afe4e28ab844a9da841d98de542aa3720bcb59 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:28:48 -0400 Subject: [PATCH 35/44] Build the menu bar and settings shell --- Package.swift | 3 +- .../TesseraApp/SystemPermissionProvider.swift | 65 + Sources/TesseraApp/main.swift | 44 +- Sources/TesseraConfig/ConfigCommand.swift | 4 + Sources/TesseraUI/AccessibilitySettings.swift | 17 + Sources/TesseraUI/MenuBarController.swift | 250 ++++ Sources/TesseraUI/MiniMap.swift | 222 +++ Sources/TesseraUI/Onboarding.swift | 152 ++ .../TesseraUI/Resources/Brand/Keystone.svg | 24 + Sources/TesseraUI/Resources/Brand/Split.svg | 8 + .../TesseraUI/Resources/Settings.xcstrings | 1326 +++++++++++++++++ Sources/TesseraUI/Resources/UI.xcstrings | 348 +++++ .../Resources/en.lproj/Settings.strings | 246 +++ .../TesseraUI/Resources/en.lproj/UI.strings | 74 + .../TesseraUI/Settings/MotionPreview.swift | 85 ++ .../Settings/SettingsDocumentEditor.swift | 169 +++ .../TesseraUI/Settings/SettingsModel.swift | 314 ++++ .../Settings/SettingsNumberParser.swift | 41 + Sources/TesseraUI/Settings/SettingsText.swift | 115 ++ Sources/TesseraUI/Settings/SettingsView.swift | 409 +++++ .../TesseraUI/Settings/ShortcutRecorder.swift | 168 +++ Sources/TesseraUI/ShellServices.swift | 202 +++ Sources/TesseraUI/TesseraUI.docc/TesseraUI.md | 29 + Sources/TesseraUI/TesseraUI.swift | 209 +++ Tests/TesseraConfigTests/KeyChordTests.swift | 4 +- Tests/TesseraUITests/MiniMapTests.swift | 206 +++ Tests/TesseraUITests/SettingsTests.swift | 516 +++++++ Tests/TesseraUITests/ShellTests.swift | 158 ++ 28 files changed, 5404 insertions(+), 4 deletions(-) create mode 100644 Sources/TesseraApp/SystemPermissionProvider.swift create mode 100644 Sources/TesseraUI/AccessibilitySettings.swift create mode 100644 Sources/TesseraUI/MenuBarController.swift create mode 100644 Sources/TesseraUI/MiniMap.swift create mode 100644 Sources/TesseraUI/Onboarding.swift create mode 100644 Sources/TesseraUI/Resources/Brand/Keystone.svg create mode 100644 Sources/TesseraUI/Resources/Brand/Split.svg create mode 100644 Sources/TesseraUI/Resources/Settings.xcstrings create mode 100644 Sources/TesseraUI/Resources/UI.xcstrings create mode 100644 Sources/TesseraUI/Resources/en.lproj/Settings.strings create mode 100644 Sources/TesseraUI/Resources/en.lproj/UI.strings create mode 100644 Sources/TesseraUI/Settings/MotionPreview.swift create mode 100644 Sources/TesseraUI/Settings/SettingsDocumentEditor.swift create mode 100644 Sources/TesseraUI/Settings/SettingsModel.swift create mode 100644 Sources/TesseraUI/Settings/SettingsNumberParser.swift create mode 100644 Sources/TesseraUI/Settings/SettingsText.swift create mode 100644 Sources/TesseraUI/Settings/SettingsView.swift create mode 100644 Sources/TesseraUI/Settings/ShortcutRecorder.swift create mode 100644 Sources/TesseraUI/ShellServices.swift create mode 100644 Sources/TesseraUI/TesseraUI.docc/TesseraUI.md create mode 100644 Tests/TesseraUITests/MiniMapTests.swift create mode 100644 Tests/TesseraUITests/SettingsTests.swift create mode 100644 Tests/TesseraUITests/ShellTests.swift diff --git a/Package.swift b/Package.swift index 14726da6..de672bd3 100644 --- a/Package.swift +++ b/Package.swift @@ -28,7 +28,7 @@ let package = Package( .target(name: "TesseraAnimation", dependencies: ["TesseraCore"], swiftSettings: strict), .target(name: "TesseraEngine", dependencies: ["TesseraCore", "TesseraConfig", "TesseraPlatform", "TesseraAnimation"], swiftSettings: strict), .target(name: "TesseraIPC", dependencies: ["TesseraCore"], resources: [.process("Resources")], swiftSettings: strict), - .target(name: "TesseraUI", dependencies: ["TesseraCore", "TesseraConfig", "TesseraEngine", "TesseraAnimation"], swiftSettings: strict), + .target(name: "TesseraUI", dependencies: ["TesseraCore", "TesseraConfig", "TesseraEngine", "TesseraAnimation"], resources: [.process("Resources")], swiftSettings: strict), .executableTarget(name: "TesseraApp", dependencies: ["TesseraUI", "TesseraEngine", "TesseraIPC"], swiftSettings: strict), .executableTarget( name: "tessera", @@ -43,6 +43,7 @@ let package = Package( .testTarget(name: "TesseraPlatformTests", dependencies: ["TesseraPlatform"]), .testTarget(name: "TesseraEngineTests", dependencies: ["TesseraEngine"]), .testTarget(name: "TesseraAnimationTests", dependencies: ["TesseraAnimation"]), + .testTarget(name: "TesseraUITests", dependencies: ["TesseraUI", "TesseraConfig", "TesseraAnimation"]), .testTarget(name: "TesseraIPCTests", dependencies: ["TesseraIPC", "tessera"]), .testTarget(name: "TesseraE2ETests", dependencies: ["TesseraPlatform", "TesseraCore"]), ], diff --git a/Sources/TesseraApp/SystemPermissionProvider.swift b/Sources/TesseraApp/SystemPermissionProvider.swift new file mode 100644 index 00000000..5abdd7cb --- /dev/null +++ b/Sources/TesseraApp/SystemPermissionProvider.swift @@ -0,0 +1,65 @@ +import ApplicationServices +import Foundation +import TesseraUI + +@MainActor +final class SystemPermissionProvider: PermissionStatusProviding { + private var status = PermissionStatus.checking + private var subscribers: [UUID: AsyncStream.Continuation] = [:] + private var polling: Task? + + func permissionUpdates() -> AsyncStream { + let id = UUID() + let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + subscribers[id] = continuation + continuation.yield(status) + continuation.onTermination = { [weak self] _ in + Task { @MainActor in + self?.subscribers.removeValue(forKey: id) + if self?.subscribers.isEmpty == true { self?.stop() } + } + } + return stream + } + + func refreshPermission() async { + let granted = await Task.detached { AXIsProcessTrusted() }.value + guard !Task.isCancelled else { return } + publish(granted ? .granted : .missing) + if !granted, polling == nil, !subscribers.isEmpty { + polling = Task { @MainActor [weak self] in + while !Task.isCancelled { + do { try await Task.sleep(for: .seconds(2)) } catch is CancellationError { return } catch { + preconditionFailure("Unexpected clock failure: \(error)") + } + guard let self else { return } + let granted = await Task.detached { AXIsProcessTrusted() }.value + guard !Task.isCancelled else { return } + self.publish(granted ? .granted : .missing) + if granted { + self.polling = nil + return + } + } + } + } + } + + func openAccessibilitySettings() throws { try AccessibilitySettings.open() } + + func stop() { + polling?.cancel() + polling = nil + } + + private func publish(_ value: PermissionStatus) { + guard value != status else { return } + status = value + for subscriber in subscribers.values { subscriber.yield(value) } + } + + deinit { + polling?.cancel() + for subscriber in subscribers.values { subscriber.finish() } + } +} diff --git a/Sources/TesseraApp/main.swift b/Sources/TesseraApp/main.swift index bb93fa8c..e0c1d9ed 100644 --- a/Sources/TesseraApp/main.swift +++ b/Sources/TesseraApp/main.swift @@ -1 +1,43 @@ -print("Tessera") +import AppKit +import TesseraUI + +@MainActor +final class AppDelegate: NSObject, NSApplicationDelegate { + private let permissions = SystemPermissionProvider() + private let preview = PreviewShellServices() + private var shell: TesseraShell? + private var startup: Task? + private var isStopping = false + + func applicationDidFinishLaunching(_ notification: Notification) { + let shell = TesseraShell(layouts: preview, permissions: permissions, commands: preview, preview: true) + self.shell = shell + startup = Task { + do { try await shell.start() } catch { shell.showError(error) } + } + } + + func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool { + shell?.showSettings() + return true + } + + func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + guard !isStopping else { return .terminateNow } + isStopping = true + startup?.cancel() + permissions.stop() + Task { + await startup?.value + await shell?.stop() + sender.reply(toApplicationShouldTerminate: true) + } + return .terminateLater + } +} + +let application = NSApplication.shared +let delegate = AppDelegate() +application.delegate = delegate +application.setActivationPolicy(.regular) +application.run() diff --git a/Sources/TesseraConfig/ConfigCommand.swift b/Sources/TesseraConfig/ConfigCommand.swift index 1a9b73f1..a738fb08 100644 --- a/Sources/TesseraConfig/ConfigCommand.swift +++ b/Sources/TesseraConfig/ConfigCommand.swift @@ -27,6 +27,8 @@ public enum ConfigCommand: String, CaseIterable, Sendable { case displayMoveUp = "display-move-up" case displayMoveDown = "display-move-down" case openSettings = "open-settings" + case pauseTiling = "pause-tiling" + case quit } public enum DefaultKeybindings { @@ -64,5 +66,7 @@ public enum DefaultKeybindings { .displayMoveUp: KeyChord(modifiers: .cmd, key: .f3), .displayMoveDown: KeyChord(modifiers: .cmd, key: .f4), .openSettings: KeyChord(key: .comma), + .pauseTiling: KeyChord(key: .p), + .quit: KeyChord(key: .q), ] } diff --git a/Sources/TesseraUI/AccessibilitySettings.swift b/Sources/TesseraUI/AccessibilitySettings.swift new file mode 100644 index 00000000..5a1cab53 --- /dev/null +++ b/Sources/TesseraUI/AccessibilitySettings.swift @@ -0,0 +1,17 @@ +import AppKit +import Foundation + +@MainActor +public enum AccessibilitySettings { + public static func open() throws { + guard let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"), + NSWorkspace.shared.open(url) + else { throw SettingsOpenError() } + } +} + +private struct SettingsOpenError: LocalizedError { + var errorDescription: String? { + UIStrings.text("System Settings could not be opened. Open Privacy & Security, then Accessibility.") + } +} diff --git a/Sources/TesseraUI/MenuBarController.swift b/Sources/TesseraUI/MenuBarController.swift new file mode 100644 index 00000000..d480feb1 --- /dev/null +++ b/Sources/TesseraUI/MenuBarController.swift @@ -0,0 +1,250 @@ +public import AppKit +public import TesseraConfig + +public struct MenuShortcut { + public let keyEquivalent: String + public let modifierMask: NSEvent.ModifierFlags + + public init(_ chord: KeyChord?) { + guard let chord else { + keyEquivalent = "" + modifierMask = [] + return + } + keyEquivalent = Self.equivalent(chord.key) + var flags: NSEvent.ModifierFlags = [] + if chord.modifiers.contains(.ctrl) { flags.insert(.control) } + if chord.modifiers.contains(.alt) { flags.insert(.option) } + if chord.modifiers.contains(.cmd) { flags.insert(.command) } + if chord.modifiers.contains(.shift) { flags.insert(.shift) } + if chord.modifiers.contains(.fn) { flags.insert(.function) } + if chord.key.rawValue.hasPrefix("keypad") { flags.insert(.numericPad) } + modifierMask = flags + } + + private static func equivalent(_ key: ANSIKey) -> String { + switch key { + case .minus, .keypadMinus: return "-" + case .return, .keypadEnter: return "\r" + case .space: return " " + case .tab: return "\t" + case .escape: return "\u{1b}" + case .delete: return "\u{8}" + case .forwardDelete: return "\u{f728}" + case .left: return "\u{f702}" + case .right: return "\u{f703}" + case .up: return "\u{f700}" + case .down: return "\u{f701}" + case .home: return "\u{f729}" + case .end: return "\u{f72b}" + case .pageUp: return "\u{f72c}" + case .pageDown: return "\u{f72d}" + case .help: return "\u{f746}" + case .capsLock: return "⇪" + case .keypadClear: return "\u{f739}" + case .keypadDecimal: return "." + case .keypadMultiply: return "*" + case .keypadPlus: return "+" + case .keypadDivide: return "/" + case .keypadEqual: return "=" + default: + let raw = key.rawValue + if raw.hasPrefix("keypad") { return String(raw.suffix(1)) } + if raw.hasPrefix("f"), let number = Int(raw.dropFirst()), + let scalar = UnicodeScalar(0xf703 + number) + { + return String(scalar) + } + return raw + } + } +} + +@MainActor +final class CommandMenuItem: NSMenuItem { + let command: ConfigCommand + let invoke: @MainActor (ConfigCommand) -> Void + + init(title: String, command: ConfigCommand, chord: KeyChord?, invoke: @escaping @MainActor (ConfigCommand) -> Void) + { + self.command = command + self.invoke = invoke + let shortcut = MenuShortcut(chord) + super.init(title: title, action: #selector(performCommand), keyEquivalent: shortcut.keyEquivalent) + keyEquivalentModifierMask = shortcut.modifierMask + target = self + setAccessibilityLabel(title) + } + + required init(coder: NSCoder) { fatalError("init(coder:) is unavailable") } + + @objc private func performCommand() { invoke(command) } +} + +final class CommandMenu: NSMenu { + let routing = MenuRouting() + + override func performKeyEquivalent(with event: NSEvent) -> Bool { + let routing = routing + let keyCode = event.keyCode + let flags = event.modifierFlags + return MainActor.assumeIsolated { routing.perform(keyCode: keyCode, flags: flags) } + } +} + +@MainActor +final class MenuRouting { + var bindings: [ConfigCommand: KeyChord] = [:] + var invoke: (@MainActor (ConfigCommand) -> Void)? + + func perform(keyCode: UInt16, flags: NSEvent.ModifierFlags) -> Bool { + guard let key = ANSIKey.allCases.first(where: { $0.keyCode == keyCode }) else { return false } + var modifiers: KeyModifiers = [] + if flags.contains(.control) { modifiers.insert(.ctrl) } + if flags.contains(.option) { modifiers.insert(.alt) } + if flags.contains(.command) { modifiers.insert(.cmd) } + if flags.contains(.shift) { modifiers.insert(.shift) } + // AppKit marks navigation and function keys with .function even without the Fn key held. + let intrinsicFunction = + [.left, .right, .up, .down, .home, .end, .pageUp, .pageDown, .forwardDelete].contains(key) + || (key.rawValue.hasPrefix("f") && Int(key.rawValue.dropFirst()) != nil) + if flags.contains(.function), !intrinsicFunction { modifiers.insert(.fn) } + let chord = KeyChord(modifiers: modifiers, key: key) + guard let command = bindings.first(where: { $0.value == chord })?.key else { return false } + invoke?(command) + return true + } +} + +@MainActor +public final class MenuBarController { + public let statusItem: NSStatusItem + public private(set) var menu: NSMenu + private let renderer: MenuIconRenderer + private var morph: MiniMapMorph + private var animation: Task? + private var lastContrast = false + private var lastPresentation: MenuPresentation? + private let invoke: @MainActor (ConfigCommand) -> Void + + public init(invoke: @escaping @MainActor (ConfigCommand) -> Void) throws { + self.invoke = invoke + renderer = try MenuIconRenderer() + morph = MiniMapMorph(icon: .logo(count: nil)) + statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength) + statusItem.autosaveName = "Tessera" + menu = NSMenu(title: UIStrings.text("Tessera")) + statusItem.menu = menu + statusItem.button?.setAccessibilityLabel(UIStrings.text("Tessera")) + statusItem.button?.image = renderer.image(for: morph.current) + } + + public func update( + snapshot: LayoutSnapshot, configuration: TesseraConfiguration, permission: PermissionStatus, + reduceMotion: Bool, increaseContrast: Bool, notice: String? = nil + ) { + let presentation = MenuPresentation( + snapshot: snapshot, configuration: configuration, permission: permission, + reduceMotion: reduceMotion, increaseContrast: increaseContrast, notice: notice, visible: isVisible) + guard lastPresentation != presentation else { return } + lastPresentation = presentation + statusItem.button?.setAccessibilityValue(snapshot.accessibilityDescription) + statusItem.button?.toolTip = snapshot.accessibilityDescription + let menu = CommandMenu(title: UIStrings.text("Tessera")) + menu.autoenablesItems = false + menu.routing.invoke = invoke + func add(_ title: String, _ command: ConfigCommand, to destination: NSMenu) -> NSMenuItem { + let item = CommandMenuItem( + title: title, command: command, chord: configuration.keybindings[command], invoke: invoke) + destination.addItem(item) + menu.routing.bindings[command] = configuration.keybindings[command] + return item + } + let heading = NSMenuItem(title: snapshot.accessibilityDescription, action: nil, keyEquivalent: "") + heading.isEnabled = false + menu.addItem(heading) + if let notice { + let item = NSMenuItem(title: notice, action: nil, keyEquivalent: "") + item.isEnabled = false + menu.addItem(item) + } + let layoutItem = NSMenuItem(title: UIStrings.text("Layout"), action: nil, keyEquivalent: "") + let layouts = NSMenu(title: UIStrings.text("Layout")) + for layout in ConfigLayout.allCases { + let item = add(layout.uiTitle, layout.command, to: layouts) + item.state = snapshot.layout == layout ? .on : .off + } + layoutItem.submenu = layouts + menu.addItem(layoutItem) + let pause = add(UIStrings.text(snapshot.isPaused ? "Resume Tiling" : "Pause Tiling"), .pauseTiling, to: menu) + pause.state = snapshot.isPaused ? .on : .off + _ = add(UIStrings.text("Retile"), .retile, to: menu) + menu.addItem(.separator()) + _ = add(UIStrings.text("Settings…"), .openSettings, to: menu) + if permission != .granted { + let item = NSMenuItem( + title: UIStrings.text( + permission == .checking ? "Checking Accessibility access…" : "Accessibility access is needed"), + action: nil, keyEquivalent: "" + ) + item.isEnabled = false + menu.addItem(item) + } + _ = add(UIStrings.text("Quit Tessera"), .quit, to: menu) + self.menu = menu + statusItem.menu = menu + + let changed = morph.retarget( + MenuIcon(snapshot: snapshot, style: configuration.motion.menuBarIcon), + configuration: configuration.motion, reduceMotion: reduceMotion, visible: presentation.visible) + let contrastChanged = lastContrast != increaseContrast + lastContrast = increaseContrast + guard changed || contrastChanged else { return } + animation?.cancel() + if morph.remainingFrames == 0 { + draw() + } else { + animation = Task { @MainActor [weak self] in + while let self, self.morph.remainingFrames > 0 { + do { try await Task.sleep(for: .seconds(self.morph.frameInterval)) } catch is CancellationError { + return + } catch { preconditionFailure("Unexpected clock failure: \(error)") } + guard !Task.isCancelled else { return } + if self.isVisible { + self.morph.advance() + } else { + self.morph.finish() + } + self.draw() + } + } + } + } + + public func stop() { + animation?.cancel() + animation = nil + NSStatusBar.system.removeStatusItem(statusItem) + } + + private var isVisible: Bool { + statusItem.isVisible && NSMenu.menuBarVisible() + && statusItem.button?.window?.occlusionState.contains(.visible) == true + } + + private func draw() { + statusItem.button?.image = renderer.image(for: morph.current, increaseContrast: lastContrast) + } + + deinit { animation?.cancel() } +} + +private struct MenuPresentation: Equatable { + let snapshot: LayoutSnapshot + let configuration: TesseraConfiguration + let permission: PermissionStatus + let reduceMotion: Bool + let increaseContrast: Bool + let notice: String? + let visible: Bool +} diff --git a/Sources/TesseraUI/MiniMap.swift b/Sources/TesseraUI/MiniMap.swift new file mode 100644 index 00000000..b95d3b44 --- /dev/null +++ b/Sources/TesseraUI/MiniMap.swift @@ -0,0 +1,222 @@ +public import AppKit +import TesseraAnimation +public import TesseraConfig + +public struct MiniMapTile: Equatable, Sendable { + public let id: UInt64 + public var frame: CGRect + public let isFocused: Bool +} + +public enum MenuIcon: Equatable, Sendable { + case tiles([MiniMapTile]) + case logo(count: Int?) + + public init(snapshot: LayoutSnapshot, style: ConfigMenuBarIcon) { + guard style == .minimap, !snapshot.tiles.isEmpty, snapshot.tiles.count <= 6 else { + self = .logo(count: snapshot.tiles.count > 6 ? snapshot.tiles.count : nil) + return + } + let scale = min(14 / snapshot.bounds.width, 14 / snapshot.bounds.height) + let offsetX = (18 - snapshot.bounds.width * scale) / 2 + let offsetY = (18 - snapshot.bounds.height * scale) / 2 + self = .tiles( + snapshot.tiles.compactMap { tile in + let clipped = tile.frame.intersection(snapshot.bounds) + guard !clipped.isNull, !clipped.isEmpty else { return nil } + let frame = CGRect( + x: offsetX + (clipped.minX - snapshot.bounds.minX) * scale, + y: offsetY + (clipped.minY - snapshot.bounds.minY) * scale, + width: clipped.width * scale, height: clipped.height * scale + ) + let inset = min(0.5, frame.width / 4, frame.height / 4) + return MiniMapTile(id: tile.id, frame: frame.insetBy(dx: inset, dy: inset), isFocused: tile.isFocused) + }) + } +} + +public struct MiniMapMorph: Sendable { + public private(set) var current: MenuIcon + public private(set) var target: MenuIcon + public private(set) var remainingFrames = 0 + public private(set) var frameInterval = 0.0 + private var spring = MotionToken.glance.spec().spring + private var velocities: [UInt64: [Double]] = [:] + + public init(icon: MenuIcon) { + current = icon + target = icon + } + + @discardableResult + public mutating func retarget( + _ icon: MenuIcon, configuration: MotionConfiguration, reduceMotion: Bool, visible: Bool + ) -> Bool { + let policy = MotionPolicy(enabled: configuration.enabled, reduceMotion: reduceMotion) + let animate = visible && policy.behavior(for: .miniMap) == .animate + if icon == target && (animate || remainingFrames == 0) { return false } + target = icon + guard animate, current != icon, case .tiles(let previous) = current, + case .tiles(let next) = icon, !previous.isEmpty, !next.isEmpty + else { + current = icon + remainingFrames = 0 + velocities = [:] + return true + } + let spec = MotionToken.glance.spec(settings: configuration.uiMotionSettings) + remainingFrames = min(10, spec.maximumRedraws ?? 10) + frameInterval = spec.duration / Double(remainingFrames) + spring = spec.spring + let old = Dictionary(uniqueKeysWithValues: previous.map { ($0.id, $0) }) + current = .tiles( + next.map { tile in + MiniMapTile(id: tile.id, frame: old[tile.id]?.frame ?? tile.frame, isFocused: tile.isFocused) + }) + velocities = velocities.filter { id, _ in next.contains { $0.id == id } } + return true + } + + public mutating func finish() { + current = target + remainingFrames = 0 + velocities = [:] + } + + @discardableResult + public mutating func advance() -> MenuIcon { + guard remainingFrames > 0, case .tiles(let previous) = current, case .tiles(let next) = target else { + return current + } + remainingFrames -= 1 + guard remainingFrames > 0 else { + current = target + velocities = [:] + return current + } + current = .tiles( + zip(previous, next).map { old, destination in + let start = [old.frame.minX, old.frame.minY, old.frame.width, old.frame.height] + let end = [ + destination.frame.minX, destination.frame.minY, destination.frame.width, destination.frame.height, + ] + let speed = velocities[old.id] ?? [0, 0, 0, 0] + let values = start.indices.map { index in + SpringState(value: start[index], velocity: speed[index]) + .advanced(to: end[index], by: frameInterval, using: spring) + } + velocities[old.id] = values.map(\.velocity) + return MiniMapTile( + id: destination.id, + frame: CGRect( + x: values[0].value, y: values[1].value, + width: max(0.1, values[2].value), height: max(0.1, values[3].value)), + isFocused: destination.isFocused + ) + }) + return current + } +} + +extension MotionConfiguration { + var uiMotionSettings: MotionSettings { + let whimsy: WhimsyLevel + switch level { + case .calm: whimsy = .calm + case .playful: whimsy = .playful + case .extra: whimsy = .extra + } + return MotionSettings(level: whimsy, speedMultiplier: speed) + } +} + +@MainActor +public enum BrandAssets { + public static func keystone() throws -> NSImage { try load("Keystone") } + public static func split() throws -> NSImage { + let image = try load("Split") + image.isTemplate = true + return image + } + + private static func load(_ name: String) throws -> NSImage { + guard let url = Bundle.module.url(forResource: name, withExtension: "svg"), + let image = NSImage(contentsOf: url) + else { throw UIResourceError.missingBrand(name) } + return image + } +} + +public enum UIResourceError: LocalizedError { + case missingBrand(String) + case renderingFailed + + public var errorDescription: String? { + switch self { + case .missingBrand(let name): String(format: UIStrings.text("The %@ artwork could not be loaded."), name) + case .renderingFailed: UIStrings.text("The menu icon could not be rendered.") + } + } +} + +@MainActor +public final class MenuIconRenderer { + private let logo: NSImage + + public init() throws { logo = try BrandAssets.split() } + + public func image(for icon: MenuIcon, increaseContrast: Bool = false) -> NSImage { + let logo = self.logo + let image = NSImage(size: NSSize(width: 18, height: 18), flipped: true) { rect in + NSColor.black.set() + switch icon { + case .tiles(let tiles): + for tile in tiles { + let path = NSBezierPath(roundedRect: tile.frame, xRadius: 0.8, yRadius: 0.8) + if tile.isFocused { + path.fill() + } else { + path.lineWidth = increaseContrast ? 1.3 : 0.85 + path.stroke() + } + } + case .logo(let count): + if let count { + logo.draw(in: CGRect(x: 0, y: 0, width: 12, height: 12)) + let label = count > 99 ? "99+" : count.formatted() + let attributes: [NSAttributedString.Key: NSObject] = [ + .font: NSFont.monospacedDigitSystemFont(ofSize: 7, weight: .bold), + .foregroundColor: NSColor.black, + ] + let text = NSAttributedString(string: label, attributes: attributes) + text.draw(at: CGPoint(x: max(0, 18 - text.size().width), y: 10)) + } else { + logo.draw(in: rect) + } + } + return true + } + image.isTemplate = true + return image + } + + public func png(for icon: MenuIcon, scale: Int = 2, increaseContrast: Bool = false) throws -> Data { + precondition((1...4).contains(scale)) + guard + let bitmap = NSBitmapImageRep( + bitmapDataPlanes: nil, pixelsWide: 18 * scale, pixelsHigh: 18 * scale, + bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, + colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0 + ), let context = NSGraphicsContext(bitmapImageRep: bitmap) + else { throw UIResourceError.renderingFailed } + NSGraphicsContext.saveGraphicsState() + defer { NSGraphicsContext.restoreGraphicsState() } + NSGraphicsContext.current = context + context.cgContext.scaleBy(x: CGFloat(scale), y: CGFloat(scale)) + image(for: icon, increaseContrast: increaseContrast).draw(in: CGRect(x: 0, y: 0, width: 18, height: 18)) + guard let data = bitmap.representation(using: .png, properties: [:]) else { + throw UIResourceError.renderingFailed + } + return data + } +} diff --git a/Sources/TesseraUI/Onboarding.swift b/Sources/TesseraUI/Onboarding.swift new file mode 100644 index 00000000..71f33f76 --- /dev/null +++ b/Sources/TesseraUI/Onboarding.swift @@ -0,0 +1,152 @@ +import Observation +public import SwiftUI +import TesseraAnimation +public import TesseraConfig + +public enum OnboardingState: Equatable, Sendable { + case checking, needsPermission, waiting, ready, complete +} + +@MainActor +@Observable +public final class OnboardingModel { + public private(set) var state: OnboardingState = .checking + public private(set) var permission: PermissionStatus = .checking + public private(set) var celebrationCount = 0 + public private(set) var error: String? + private let provider: any PermissionStatusProviding + + public init(provider: any PermissionStatusProviding) { self.provider = provider } + + public func receive(_ status: PermissionStatus) { + permission = status + switch status { + case .checking: + if state != .complete { state = .checking } + case .missing: + if state != .waiting { state = .needsPermission } + case .granted: + if state == .needsPermission || state == .waiting { celebrationCount += 1 } + if state != .complete { state = .ready } + } + } + + public func openSettings() { + do { + try provider.openAccessibilitySettings() + error = nil + if permission != .granted { state = .waiting } + } catch { + self.error = error.localizedDescription + } + } + + public func refresh() async { await provider.refreshPermission() } + + @discardableResult + public func complete() -> Bool { + guard permission == .granted else { return false } + state = .complete + return true + } + + var statusText: String { + switch permission { + case .checking: UIStrings.text("Checking Accessibility access…") + case .missing: UIStrings.text("Accessibility access is needed") + case .granted: UIStrings.text("Accessibility access is on") + } + } +} + +public struct PermissionsView: View { + private let model: OnboardingModel + + public init(model: OnboardingModel) { self.model = model } + + public var body: some View { + VStack(alignment: .leading, spacing: 16) { + Label(model.statusText, systemImage: model.permission == .granted ? "checkmark.circle" : "hand.raised") + Text(UIStrings.text("Tessera needs Accessibility access to move and resize your windows.")) + Text(UIStrings.text("Screen Recording is optional and is not requested by this shell.")) + .foregroundStyle(.secondary) + HStack { + Button(UIStrings.text("Open Accessibility Settings")) { model.openSettings() } + Button(UIStrings.text("Check Again")) { Task { await model.refresh() } } + } + if let error = model.error { Text(error).foregroundStyle(.primary).accessibilityLabel(error) } + } + .padding() + } +} + +public struct OnboardingView: View { + private let model: OnboardingModel + private let motion: MotionConfiguration + private let finish: @MainActor () -> Void + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.accessibilityReduceTransparency) private var reduceTransparency + @Environment(\.colorSchemeContrast) private var contrast + @State private var celebrated = false + @State private var celebratedCount = 0 + + public init(model: OnboardingModel, motion: MotionConfiguration, finish: @escaping @MainActor () -> Void) { + self.model = model + self.motion = motion + self.finish = finish + } + + public var body: some View { + VStack(alignment: .leading, spacing: 20) { + Image(systemName: model.permission == .granted ? "checkmark.square.fill" : "square.split.2x2") + .font(.system(size: 44, weight: contrast == .increased ? .bold : .medium)) + .foregroundStyle(.primary) + .scaleEffect(celebrated ? 1.04 : 1) + .accessibilityHidden(true) + Text(UIStrings.text(model.permission == .granted ? "A little room to breathe." : "Make room for your day.")) + .font(.largeTitle.bold()) + if model.permission == .granted { + Text(UIStrings.text("Access is on. Your windows are ready for a little order.")) + Button(UIStrings.text("Get Started")) { + if model.complete() { finish() } + } + } else { + PermissionsView(model: model).padding(-16) + if model.state == .waiting { + Text(UIStrings.text("Turn on Tessera in System Settings, then come back here.")) + } + } + } + .padding(32) + .frame(width: 460, alignment: .leading) + .background( + reduceTransparency ? Color(nsColor: .windowBackgroundColor) : Color(nsColor: .controlBackgroundColor) + ) + .task(id: CelebrationRequest(count: model.celebrationCount, motion: motion, reduceMotion: reduceMotion)) { + await celebrate() + } + } + + private func celebrate() async { + let newGrant = model.celebrationCount > celebratedCount + celebratedCount = model.celebrationCount + guard newGrant, motion.enabled, !reduceMotion else { + var transaction = Transaction() + transaction.disablesAnimations = true + withTransaction(transaction) { celebrated = false } + return + } + let spec = MotionToken.pop.spec(settings: motion.uiMotionSettings) + withAnimation(.spring(duration: spec.duration, bounce: spec.bounce)) { celebrated = true } + do { try await Task.sleep(for: .seconds(spec.duration)) } catch is CancellationError { return } catch { + preconditionFailure("Unexpected clock failure: \(error)") + } + withAnimation(.spring(duration: spec.duration, bounce: spec.bounce)) { celebrated = false } + } +} + +private struct CelebrationRequest: Equatable { + let count: Int + let motion: MotionConfiguration + let reduceMotion: Bool +} diff --git a/Sources/TesseraUI/Resources/Brand/Keystone.svg b/Sources/TesseraUI/Resources/Brand/Keystone.svg new file mode 100644 index 00000000..0c53138a --- /dev/null +++ b/Sources/TesseraUI/Resources/Brand/Keystone.svg @@ -0,0 +1,24 @@ + + Tessera – Keystone (app icon, unmasked square for Icon Composer) + + + + + + + + + + + + + + + + + + + + + + diff --git a/Sources/TesseraUI/Resources/Brand/Split.svg b/Sources/TesseraUI/Resources/Brand/Split.svg new file mode 100644 index 00000000..aca3a700 --- /dev/null +++ b/Sources/TesseraUI/Resources/Brand/Split.svg @@ -0,0 +1,8 @@ + + Tessera – Split (menu bar template, black on clear) + + + + + + diff --git a/Sources/TesseraUI/Resources/Settings.xcstrings b/Sources/TesseraUI/Resources/Settings.xcstrings new file mode 100644 index 00000000..d6c7693c --- /dev/null +++ b/Sources/TesseraUI/Resources/Settings.xcstrings @@ -0,0 +1,1326 @@ +{ + "sourceLanguage": "en", + "strings": { + "A tiling window manager for macOS.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A tiling window manager for macOS." + } + } + } + }, + "About": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "About" + } + } + } + }, + "Accessibility role": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Accessibility role" + } + } + } + }, + "Add display override": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Add display override" + } + } + } + }, + "Add floating rule": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Add floating rule" + } + } + } + }, + "All displays": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "All displays" + } + } + } + }, + "Announce layout changes": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Announce layout changes" + } + } + } + }, + "Bundle identifier": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Bundle identifier" + } + } + } + }, + "Calm": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Calm" + } + } + } + }, + "Cancel": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Cancel" + } + } + } + }, + "Clear shortcut": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Clear shortcut" + } + } + } + }, + "Columns": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Columns" + } + } + } + }, + "Columns layout": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Columns layout" + } + } + } + }, + "Configuration diagnostics": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Configuration diagnostics" + } + } + } + }, + "Configure layout for": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Configure layout for" + } + } + } + }, + "Decrease ratio": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Decrease ratio" + } + } + } + }, + "Default layout": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Default layout" + } + } + } + }, + "Development build": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Development build" + } + } + } + }, + "Display UUID": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Display UUID" + } + } + } + }, + "Edit rule": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Edit rule" + } + } + } + }, + "Edit shortcut": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Edit shortcut" + } + } + } + }, + "Edit shortcut for %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Edit shortcut for %@" + } + } + } + }, + "Enable motion": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Enable motion" + } + } + } + }, + "Enter a number using your region’s decimal separator, without grouping separators.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Enter a number using your region’s decimal separator, without grouping separators." + } + } + } + }, + "Enter a valid display UUID.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Enter a valid display UUID." + } + } + } + }, + "Enter a whole number.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Enter a whole number." + } + } + } + }, + "Extra": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Extra" + } + } + } + }, + "Fix the configuration file before saving changes.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Fix the configuration file before saving changes." + } + } + } + }, + "Floating rule": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Floating rule" + } + } + } + }, + "Focus border": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Focus border" + } + } + } + }, + "Focus down": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Focus down" + } + } + } + }, + "Focus left": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Focus left" + } + } + } + }, + "Focus right": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Focus right" + } + } + } + }, + "Focus up": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Focus up" + } + } + } + }, + "General": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "General" + } + } + } + }, + "Ghost": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Ghost" + } + } + } + }, + "Glide": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Glide" + } + } + } + }, + "Grid": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Grid" + } + } + } + }, + "Grid layout": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Grid layout" + } + } + } + }, + "Increase ratio": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Increase ratio" + } + } + } + }, + "Inner gap": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Inner gap" + } + } + } + }, + "Launch at login": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Launch at login" + } + } + } + }, + "Layout": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Layout" + } + } + } + }, + "Licensed under the Apache License, Version 2.0.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Licensed under the Apache License, Version 2.0." + } + } + } + }, + "Listening for a shortcut…": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Listening for a shortcut…" + } + } + } + }, + "Logo": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Logo" + } + } + } + }, + "Matching windows float instead of tiling. Each rule needs at least one matcher.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Matching windows float instead of tiling. Each rule needs at least one matcher." + } + } + } + }, + "Menu bar icon": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Menu bar icon" + } + } + } + }, + "Mini map": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Mini map" + } + } + } + }, + "Motion": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Motion" + } + } + } + }, + "Motion level": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Motion level" + } + } + } + }, + "Move down": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move down" + } + } + } + }, + "Move left": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move left" + } + } + } + }, + "Move right": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move right" + } + } + } + }, + "Move to display above": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move to display above" + } + } + } + }, + "Move to display below": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move to display below" + } + } + } + }, + "Move to display on left": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move to display on left" + } + } + } + }, + "Move to display on right": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move to display on right" + } + } + } + }, + "Move up": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Move up" + } + } + } + }, + "Next stacked window": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Next stacked window" + } + } + } + }, + "Not assigned": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Not assigned" + } + } + } + }, + "One preview per press. System accessibility preferences always take priority.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "One preview per press. System accessibility preferences always take priority." + } + } + } + }, + "Open Settings": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open Settings" + } + } + } + }, + "Open Settings before editing the configuration.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open Settings before editing the configuration." + } + } + } + }, + "Outer gap": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Outer gap" + } + } + } + }, + "Pause or resume tiling": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pause or resume tiling" + } + } + } + }, + "Permissions": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Permissions" + } + } + } + }, + "Playful": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Playful" + } + } + } + }, + "Press a shortcut, including any modifiers. Tab and Escape can also be recorded.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Press a shortcut, including any modifiers. Tab and Escape can also be recorded." + } + } + } + }, + "Preview": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Preview" + } + } + } + }, + "Preview motion": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Preview motion" + } + } + } + }, + "Previous stacked window": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Previous stacked window" + } + } + } + }, + "Quit Tessera": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Quit Tessera" + } + } + } + }, + "Ratio": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Ratio" + } + } + } + }, + "Record shortcut": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Record shortcut" + } + } + } + }, + "Reload configuration": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Reload configuration" + } + } + } + }, + "Reload value": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Reload value" + } + } + } + }, + "Remove rule": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Remove rule" + } + } + } + }, + "Reserved bottom edge": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Reserved bottom edge" + } + } + } + }, + "Reserved left edge": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Reserved left edge" + } + } + } + }, + "Reserved right edge": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Reserved right edge" + } + } + } + }, + "Reserved top edge": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Reserved top edge" + } + } + } + }, + "Retile windows": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Retile windows" + } + } + } + }, + "Rows": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Rows" + } + } + } + }, + "Rows layout": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Rows layout" + } + } + } + }, + "Rules": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Rules" + } + } + } + }, + "Save": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Save" + } + } + } + }, + "Save %@": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Save %@" + } + } + } + }, + "Saving configuration": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Saving configuration" + } + } + } + }, + "Saving failed: %@. Temporary file cleanup also failed: %@.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Saving failed: %@. Temporary file cleanup also failed: %@." + } + } + } + }, + "Settings could not be saved or loaded": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Settings could not be saved or loaded" + } + } + } + }, + "Shortcut": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Shortcut" + } + } + } + }, + "Shortcut prefix": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Shortcut prefix" + } + } + } + }, + "Shortcut recorder": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Shortcut recorder" + } + } + } + }, + "Shortcuts": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Shortcuts" + } + } + } + }, + "Shortcuts use physical ANSI key positions. You can also type a shortcut using modifier and key names.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Shortcuts use physical ANSI key positions. You can also type a shortcut using modifier and key names." + } + } + } + }, + "Side": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Side" + } + } + } + }, + "Side layout": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Side layout" + } + } + } + }, + "Snap": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Snap" + } + } + } + }, + "Sound": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Sound" + } + } + } + }, + "Speed multiplier": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Speed multiplier" + } + } + } + }, + "Stack windows": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Stack windows" + } + } + } + }, + "Swap down": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Swap down" + } + } + } + }, + "Swap left": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Swap left" + } + } + } + }, + "Swap right": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Swap right" + } + } + } + }, + "Swap up": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Swap up" + } + } + } + }, + "Tessera": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tessera" + } + } + } + }, + "The configuration changed outside Settings. Review the latest values and try again.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The configuration changed outside Settings. Review the latest values and try again." + } + } + } + }, + "The configuration file could not be coordinated for saving.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The configuration file could not be coordinated for saving." + } + } + } + }, + "The configuration must be a local file.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The configuration must be a local file." + } + } + } + }, + "The configuration path is not a regular file.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The configuration path is not a regular file." + } + } + } + }, + "The prefix applies to inherited shortcuts. Explicit shortcuts keep their own modifiers.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The prefix applies to inherited shortcuts. Explicit shortcuts keep their own modifiers." + } + } + } + }, + "This key is not supported. Enter an ANSI shortcut instead.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This key is not supported. Enter an ANSI shortcut instead." + } + } + } + }, + "This rule uses a structure Settings cannot safely remove. Edit it in the configuration file.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This rule uses a structure Settings cannot safely remove. Edit it in the configuration file." + } + } + } + }, + "This value changed outside this editor. Reload it before editing.": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This value changed outside this editor. Reload it before editing." + } + } + } + }, + "Toggle floating": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Toggle floating" + } + } + } + }, + "Transition": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Transition" + } + } + } + }, + "Version": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Version" + } + } + } + }, + "Window limit (0 means unlimited)": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Window limit (0 means unlimited)" + } + } + } + }, + "Window title pattern": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Window title pattern" + } + } + } + } + }, + "version": "1.0" +} diff --git a/Sources/TesseraUI/Resources/UI.xcstrings b/Sources/TesseraUI/Resources/UI.xcstrings new file mode 100644 index 00000000..1177e827 --- /dev/null +++ b/Sources/TesseraUI/Resources/UI.xcstrings @@ -0,0 +1,348 @@ +{ + "sourceLanguage": "en", + "strings": { + "%@ layout, 1 window": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ layout, 1 window" + } + } + } + }, + "%@ layout, %lld windows": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ layout, %lld windows" + } + } + } + }, + "Tessera": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tessera" + } + } + } + }, + "Grid": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Grid" + } + } + } + }, + "Columns": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Columns" + } + } + } + }, + "Rows": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Rows" + } + } + } + }, + "Side": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Side" + } + } + } + }, + "Layout": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Layout" + } + } + } + }, + "Resume Tiling": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Resume Tiling" + } + } + } + }, + "Pause Tiling": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pause Tiling" + } + } + } + }, + "Retile": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Retile" + } + } + } + }, + "Settings…": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Settings…" + } + } + } + }, + "Quit Tessera": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Quit Tessera" + } + } + } + }, + "The %@ artwork could not be loaded.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The %@ artwork could not be loaded." + } + } + } + }, + "The menu icon could not be rendered.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The menu icon could not be rendered." + } + } + } + }, + "Checking Accessibility access…": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Checking Accessibility access…" + } + } + } + }, + "Accessibility access is needed": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Accessibility access is needed" + } + } + } + }, + "Accessibility access is on": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Accessibility access is on" + } + } + } + }, + "Tessera needs Accessibility access to move and resize your windows.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tessera needs Accessibility access to move and resize your windows." + } + } + } + }, + "Screen Recording is optional and is not requested by this shell.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Screen Recording is optional and is not requested by this shell." + } + } + } + }, + "Open Accessibility Settings": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open Accessibility Settings" + } + } + } + }, + "Check Again": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Check Again" + } + } + } + }, + "A little room to breathe.": { + "comment": "A gentle welcome after granting access. A natural, non-literal translation is welcome.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A little room to breathe." + } + } + } + }, + "Make room for your day.": { + "comment": "A short first-run greeting. A natural, non-literal translation is welcome.", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Make room for your day." + } + } + } + }, + "Access is on. Your windows are ready for a little order.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Access is on. Your windows are ready for a little order." + } + } + } + }, + "Get Started": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Get Started" + } + } + } + }, + "Turn on Tessera in System Settings, then come back here.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Turn on Tessera in System Settings, then come back here." + } + } + } + }, + "Welcome to Tessera": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Welcome to Tessera" + } + } + } + }, + "Tessera Settings": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tessera Settings" + } + } + } + }, + "Preview — your windows are not managed.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Preview — your windows are not managed." + } + } + } + }, + "Tessera Needs Your Attention": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Tessera Needs Your Attention" + } + } + } + }, + "OK": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "OK" + } + } + } + }, + "System Settings could not be opened. Open Privacy & Security, then Accessibility.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "System Settings could not be opened. Open Privacy & Security, then Accessibility." + } + } + } + }, + "The tiling engine is not connected to this shell yet.": { + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "The tiling engine is not connected to this shell yet." + } + } + } + } + }, + "version": "1.0" +} diff --git a/Sources/TesseraUI/Resources/en.lproj/Settings.strings b/Sources/TesseraUI/Resources/en.lproj/Settings.strings new file mode 100644 index 00000000..202918b9 --- /dev/null +++ b/Sources/TesseraUI/Resources/en.lproj/Settings.strings @@ -0,0 +1,246 @@ + + + + + A tiling window manager for macOS. + A tiling window manager for macOS. + About + About + Accessibility role + Accessibility role + Add display override + Add display override + Add floating rule + Add floating rule + All displays + All displays + Announce layout changes + Announce layout changes + Bundle identifier + Bundle identifier + Calm + Calm + Cancel + Cancel + Clear shortcut + Clear shortcut + Columns + Columns + Columns layout + Columns layout + Configuration diagnostics + Configuration diagnostics + Configure layout for + Configure layout for + Decrease ratio + Decrease ratio + Default layout + Default layout + Development build + Development build + Display UUID + Display UUID + Edit rule + Edit rule + Edit shortcut + Edit shortcut + Edit shortcut for %@ + Edit shortcut for %@ + Enable motion + Enable motion + Enter a number using your region’s decimal separator, without grouping separators. + Enter a number using your region’s decimal separator, without grouping separators. + Enter a valid display UUID. + Enter a valid display UUID. + Enter a whole number. + Enter a whole number. + Extra + Extra + Fix the configuration file before saving changes. + Fix the configuration file before saving changes. + Floating rule + Floating rule + Focus border + Focus border + Focus down + Focus down + Focus left + Focus left + Focus right + Focus right + Focus up + Focus up + General + General + Ghost + Ghost + Glide + Glide + Grid + Grid + Grid layout + Grid layout + Increase ratio + Increase ratio + Inner gap + Inner gap + Launch at login + Launch at login + Layout + Layout + Licensed under the Apache License, Version 2.0. + Licensed under the Apache License, Version 2.0. + Listening for a shortcut… + Listening for a shortcut… + Logo + Logo + Matching windows float instead of tiling. Each rule needs at least one matcher. + Matching windows float instead of tiling. Each rule needs at least one matcher. + Menu bar icon + Menu bar icon + Mini map + Mini map + Motion + Motion + Motion level + Motion level + Move down + Move down + Move left + Move left + Move right + Move right + Move to display above + Move to display above + Move to display below + Move to display below + Move to display on left + Move to display on left + Move to display on right + Move to display on right + Move up + Move up + Next stacked window + Next stacked window + Not assigned + Not assigned + One preview per press. System accessibility preferences always take priority. + One preview per press. System accessibility preferences always take priority. + Open Settings + Open Settings + Open Settings before editing the configuration. + Open Settings before editing the configuration. + Outer gap + Outer gap + Pause or resume tiling + Pause or resume tiling + Permissions + Permissions + Playful + Playful + Press a shortcut, including any modifiers. Tab and Escape can also be recorded. + Press a shortcut, including any modifiers. Tab and Escape can also be recorded. + Preview + Preview + Preview motion + Preview motion + Previous stacked window + Previous stacked window + Quit Tessera + Quit Tessera + Ratio + Ratio + Record shortcut + Record shortcut + Reload configuration + Reload configuration + Reload value + Reload value + Remove rule + Remove rule + Reserved bottom edge + Reserved bottom edge + Reserved left edge + Reserved left edge + Reserved right edge + Reserved right edge + Reserved top edge + Reserved top edge + Retile windows + Retile windows + Rows + Rows + Rows layout + Rows layout + Rules + Rules + Save + Save + Save %@ + Save %@ + Saving configuration + Saving configuration + Saving failed: %@. Temporary file cleanup also failed: %@. + Saving failed: %@. Temporary file cleanup also failed: %@. + Settings could not be saved or loaded + Settings could not be saved or loaded + Shortcut + Shortcut + Shortcut prefix + Shortcut prefix + Shortcut recorder + Shortcut recorder + Shortcuts + Shortcuts + Shortcuts use physical ANSI key positions. You can also type a shortcut using modifier and key names. + Shortcuts use physical ANSI key positions. You can also type a shortcut using modifier and key names. + Side + Side + Side layout + Side layout + Snap + Snap + Sound + Sound + Speed multiplier + Speed multiplier + Stack windows + Stack windows + Swap down + Swap down + Swap left + Swap left + Swap right + Swap right + Swap up + Swap up + Tessera + Tessera + The configuration changed outside Settings. Review the latest values and try again. + The configuration changed outside Settings. Review the latest values and try again. + The configuration file could not be coordinated for saving. + The configuration file could not be coordinated for saving. + The configuration must be a local file. + The configuration must be a local file. + The configuration path is not a regular file. + The configuration path is not a regular file. + The prefix applies to inherited shortcuts. Explicit shortcuts keep their own modifiers. + The prefix applies to inherited shortcuts. Explicit shortcuts keep their own modifiers. + This key is not supported. Enter an ANSI shortcut instead. + This key is not supported. Enter an ANSI shortcut instead. + This rule uses a structure Settings cannot safely remove. Edit it in the configuration file. + This rule uses a structure Settings cannot safely remove. Edit it in the configuration file. + This value changed outside this editor. Reload it before editing. + This value changed outside this editor. Reload it before editing. + Toggle floating + Toggle floating + Transition + Transition + Version + Version + Window limit (0 means unlimited) + Window limit (0 means unlimited) + Window title pattern + Window title pattern + + diff --git a/Sources/TesseraUI/Resources/en.lproj/UI.strings b/Sources/TesseraUI/Resources/en.lproj/UI.strings new file mode 100644 index 00000000..2541282c --- /dev/null +++ b/Sources/TesseraUI/Resources/en.lproj/UI.strings @@ -0,0 +1,74 @@ + + + + + %@ layout, %lld windows + %@ layout, %lld windows + %@ layout, 1 window + %@ layout, 1 window + A little room to breathe. + A little room to breathe. + Access is on. Your windows are ready for a little order. + Access is on. Your windows are ready for a little order. + Accessibility access is needed + Accessibility access is needed + Accessibility access is on + Accessibility access is on + Check Again + Check Again + Checking Accessibility access… + Checking Accessibility access… + Columns + Columns + Get Started + Get Started + Grid + Grid + Layout + Layout + Make room for your day. + Make room for your day. + OK + OK + Open Accessibility Settings + Open Accessibility Settings + Pause Tiling + Pause Tiling + Preview — your windows are not managed. + Preview — your windows are not managed. + Quit Tessera + Quit Tessera + Resume Tiling + Resume Tiling + Retile + Retile + Rows + Rows + Screen Recording is optional and is not requested by this shell. + Screen Recording is optional and is not requested by this shell. + Settings… + Settings… + Side + Side + System Settings could not be opened. Open Privacy & Security, then Accessibility. + System Settings could not be opened. Open Privacy & Security, then Accessibility. + Tessera + Tessera + Tessera Needs Your Attention + Tessera Needs Your Attention + Tessera Settings + Tessera Settings + Tessera needs Accessibility access to move and resize your windows. + Tessera needs Accessibility access to move and resize your windows. + The %@ artwork could not be loaded. + The %@ artwork could not be loaded. + The menu icon could not be rendered. + The menu icon could not be rendered. + The tiling engine is not connected to this shell yet. + The tiling engine is not connected to this shell yet. + Turn on Tessera in System Settings, then come back here. + Turn on Tessera in System Settings, then come back here. + Welcome to Tessera + Welcome to Tessera + + diff --git a/Sources/TesseraUI/Settings/MotionPreview.swift b/Sources/TesseraUI/Settings/MotionPreview.swift new file mode 100644 index 00000000..2673ebee --- /dev/null +++ b/Sources/TesseraUI/Settings/MotionPreview.swift @@ -0,0 +1,85 @@ +import SwiftUI +import TesseraAnimation +import TesseraConfig + +struct SettingsPreviewPolicy: Equatable { + let motion: MotionConfiguration + let reduceMotion: Bool + let reduceTransparency: Bool + let increaseContrast: Bool + + var level: WhimsyLevel { + switch motion.level { + case .calm: .calm + case .playful: .playful + case .extra: .extra + } + } + + var spec: MotionSpec? { + guard motion.transitions != .snap, + MotionPolicy(enabled: motion.enabled, reduceMotion: reduceMotion).behavior(for: .miniMap, level: level) + == .animate + else { return nil } + let token: MotionToken = motion.transitions == .ghost && !reduceTransparency ? .fade : .shuffle + return token.spec(settings: MotionSettings(level: level, speedMultiplier: motion.speed)) + } + + var ghost: Bool { motion.transitions == .ghost && !reduceTransparency && !reduceMotion && motion.enabled } + var borderWidth: CGFloat { increaseContrast ? 3 : 1 } +} + +struct MotionPreview: View { + let motion: MotionConfiguration + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.accessibilityReduceTransparency) private var reduceTransparency + @Environment(\.colorSchemeContrast) private var contrast + @State private var alternate = false + + private var policy: SettingsPreviewPolicy { + SettingsPreviewPolicy( + motion: motion, reduceMotion: reduceMotion, reduceTransparency: reduceTransparency, + increaseContrast: contrast == .increased) + } + + private var animation: Animation? { + guard let spec = policy.spec else { return nil } + switch spec.curve { + case .spring, .glide: return .spring(duration: spec.duration, bounce: spec.bounce) + case .fade: return .easeInOut(duration: spec.duration) + } + } + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + ZStack { + RoundedRectangle(cornerRadius: 12) + .fill(Color(nsColor: .controlBackgroundColor)) + HStack(spacing: 8) { + RoundedRectangle(cornerRadius: 6) + .fill(Color.accentColor) + .frame(width: alternate ? 110 : 160) + RoundedRectangle(cornerRadius: 6) + .fill(Color(nsColor: .secondaryLabelColor)) + .frame(width: alternate ? 160 : 110) + } + .opacity(policy.ghost && alternate ? 0.7 : 1) + .padding(12) + } + .overlay(RoundedRectangle(cornerRadius: 12).stroke(Color.primary, lineWidth: policy.borderWidth)) + .frame(width: 310, height: 110) + .accessibilityHidden(true) + Button(SettingsText.string("Preview motion")) { + withAnimation(animation) { alternate.toggle() } + } + Text(SettingsText.string("One preview per press. System accessibility preferences always take priority.")) + .font(.caption) + .foregroundStyle(.secondary) + } + .onChange(of: policy) { + var transaction = Transaction(animation: nil) + transaction.disablesAnimations = true + withTransaction(transaction) { alternate = false } + } + } +} diff --git a/Sources/TesseraUI/Settings/SettingsDocumentEditor.swift b/Sources/TesseraUI/Settings/SettingsDocumentEditor.swift new file mode 100644 index 00000000..8d6a605f --- /dev/null +++ b/Sources/TesseraUI/Settings/SettingsDocumentEditor.swift @@ -0,0 +1,169 @@ +import TesseraConfig + +enum SettingsEdit: Sendable { + case value(SettingsField, TOMLValue) + case shortcut(ConfigCommand, KeyChord?) + case addRule(FloatRule) + case replaceRule(index: Int, original: FloatRule, replacement: FloatRule) + case removeRule(index: Int, original: FloatRule) +} + +enum SettingsDocumentEditor { + static func validate(_ document: TOMLDocument) throws -> TesseraConfiguration { + let result = ConfigValidator.validate(document) + guard let configuration = result.configuration, + !result.diagnostics.contains(where: { $0.severity == .error }) + else { + throw SettingsFailure(result.diagnostics.map(\.description).joined(separator: "\n")) + } + return configuration + } + + static func apply(_ edit: SettingsEdit, to document: inout TOMLDocument) throws { + switch edit { + case .value(let field, let value): + try document.setValue(value, forKey: field.path(in: document)) + case .shortcut(let command, let chord): + try document.setValue( + chord.map { .string($0.description) } ?? .bool(false), forKey: ["keybindings", command.rawValue]) + case .addRule(let rule): + try add(rule, to: &document) + case .replaceRule(let index, let original, let replacement): + try checkRule(index, original: original, in: document) + let path: [TOMLPathComponent] = [.key("float-rules"), .index(index)] + for (key, value) in matchers(replacement) { + let field = path + [.key(key)] + if let value { + try document.setValue(.string(value), at: field) + } else if document.node(at: field) != nil { + try removeMatcher(key, rule: index, from: &document) + } + } + case .removeRule(let index, let original): + try checkRule(index, original: original, in: document) + try removeRule(index, from: &document) + } + } + + private static func matchers(_ rule: FloatRule) -> [(String, String?)] { + [("bundle-id", rule.bundleID), ("title-regex", rule.titleRegex), ("role", rule.role)] + } + + private static func checkRule(_ index: Int, original: FloatRule, in document: TOMLDocument) throws { + let configuration = try validate(document) + guard configuration.floatRules.indices.contains(index), configuration.floatRules[index] == original else { + throw SettingsFailure.conflict + } + } + + private static func add(_ rule: FloatRule, to document: inout TOMLDocument) throws { + let newline = document.source.contains("\r\n") ? "\r\n" : "\n" + let assignments = try matchers(rule).compactMap { key, value -> String? in + guard let value else { return nil } + return key + " = " + (try TOMLWriter.encode(.string(value))) + } + guard let array = document.node(forKey: ["float-rules"]) else { + let separator = document.source.isEmpty || document.source.hasSuffix("\n") ? "" : newline + document = try TOMLDocument( + parsing: document.source + separator + "[[float-rules]]" + newline + + assignments.joined(separator: newline) + newline) + return + } + let scalars = Array(document.source.unicodeScalars) + if scalars[array.range.start.offset] == "[" { + guard case .array(let entries) = array.value else { throw unsupportedRules } + let end = array.range.end.offset - 1 + var edits: [(Range, String)] = [(end.. rule.range.end.offset else { throw unsupportedRules } + switch value.value { + case .table, .array: throw unsupportedRules + default: edits.append((key.start.offset.., String)], in document: inout TOMLDocument) throws { + var scalars = Array(document.source.unicodeScalars) + for (range, replacement) in edits.sorted(by: { $0.0.lowerBound > $1.0.lowerBound }) { + scalars.replaceSubrange(range, with: replacement.unicodeScalars) + } + document = try TOMLDocument(parsing: String(String.UnicodeScalarView(scalars))) + } + + private static func hasComma(in scalars: [Unicode.Scalar], from start: Int, to end: Int) -> Bool { + comma(in: scalars, from: start, to: end) != nil + } + + private static func comma(in scalars: [Unicode.Scalar], from start: Int, to end: Int) -> Int? { + var comment = false + for index in start.. [String] { + switch self { + case .launchAtLogin: return ["general", "launch-at-login"] + case .prefix: return ["general", "prefix"] + case .announceLayoutChanges: return ["accessibility", "announce-layout-changes"] + case .motion(let field): return ["motion", field.rawValue] + case .layout(let field, let display): + var path = ["layout"] + if let display { + let existing: String? + if case .table(let entries) = document.node(forKey: ["layout", "displays"])?.value { + existing = entries.keys.first { UUID(uuidString: $0) == display } + } else { + existing = nil + } + path += ["displays", existing ?? display.uuidString] + } + return path + field.rawValue.split(separator: ".").map(String.init) + } + } +} + +public struct SettingsFailure: Error, LocalizedError, Equatable, Sendable { + public let message: String + public var errorDescription: String? { message } + + init(_ message: String) { self.message = message } + + init(error: any Error) { + if let failure = error as? SettingsFailure { + self = failure + } else if let diagnostic = error as? ConfigDiagnostic { + self.init(diagnostic.description) + } else { + self.init(error.localizedDescription) + } + } + + static var conflict: Self { + Self(SettingsText.string("The configuration changed outside Settings. Review the latest values and try again.")) + } +} + +@MainActor @Observable +public final class SettingsModel { + public let store: ConfigStore + public private(set) var configuration = TesseraConfiguration.defaults + public private(set) var diagnostics: [ConfigDiagnostic] = [] + public private(set) var isStarted = false + public private(set) var isSaving = false + public var error: SettingsFailure? { editingError ?? loadingError } + + @ObservationIgnored private let editor: SettingsFileEditor + @ObservationIgnored private var latest: ConfigSnapshot? + @ObservationIgnored private var updatesTask: Task? + @ObservationIgnored private var ownsWatcher = false + @ObservationIgnored private var locked = false + @ObservationIgnored private var waiters: [CheckedContinuation] = [] + private var editingError: SettingsFailure? + private var loadingError: SettingsFailure? + + public init(store: ConfigStore) { + self.store = store + self.editor = SettingsFileEditor(fileURL: store.fileURL) + } + + deinit { updatesTask?.cancel() } + + public func start() async { + await acquire() + defer { release() } + guard !isStarted else { return } + receive(await store.reload()) + do { + ownsWatcher = await !store.isWatching + try await store.startWatching() + let updates = await store.updates() + isStarted = true + updatesTask = Task { [weak self, store] in + for await _ in updates { + guard !Task.isCancelled else { break } + let snapshot = await store.snapshot + guard !Task.isCancelled else { break } + self?.receive(snapshot) + } + } + } catch { + loadingError = SettingsFailure(error: error) + } + } + + public func stop() async { + await acquire() + defer { release() } + let task = updatesTask + updatesTask = nil + task?.cancel() + await task?.value + if ownsWatcher { await store.stopWatching() } + ownsWatcher = false + isStarted = false + } + + public func reload() async { + await acquire() + defer { release() } + receive(await store.reload()) + editingError = nil + } + + public func setValue(_ value: TOMLValue, for field: SettingsField) async throws { + try await edit(.value(field, value)) + } + + public func setShortcut(_ chord: KeyChord?, for command: ConfigCommand) async throws { + try await edit(.shortcut(command, chord)) + } + + public func setShortcut(text: String, for command: ConfigCommand) async throws { + do { + try await setShortcut(ShortcutRecorderParser.parse(text), for: command) + } catch { + editingError = SettingsFailure(error: error) + throw error + } + } + + public func addRule(_ rule: FloatRule) async throws { + try await edit(.addRule(rule)) + } + + public func setRule(_ rule: FloatRule, at index: Int, replacing original: FloatRule) async throws { + try await edit(.replaceRule(index: index, original: original, replacement: rule)) + } + + public func removeRule(at index: Int, matching original: FloatRule) async throws { + try await edit(.removeRule(index: index, original: original)) + } + + func report(_ error: any Error) { editingError = SettingsFailure(error: error) } + + private func edit(_ edit: SettingsEdit) async throws { + await acquire() + defer { release() } + do { + try Task.checkCancellation() + guard isStarted, let latest else { + throw SettingsFailure(SettingsText.string("Open Settings before editing the configuration.")) + } + guard latest.loadState == .loaded || latest.loadState == .missingFileUsingDefaults else { + throw loadingError + ?? SettingsFailure(SettingsText.string("Fix the configuration file before saving changes.")) + } + guard latest.activeSource == .file(store.fileURL) || latest.activeSource == .defaults else { + throw SettingsFailure.conflict + } + isSaving = true + defer { isSaving = false } + let source = try await editor.commit(edit, expectedSource: latest.lastGoodDocument?.source) + let saved = await store.reload() + receive(saved) + guard saved.loadState == .loaded, saved.lastGoodDocument?.source == source else { + throw SettingsFailure.conflict + } + editingError = nil + } catch { + receive(await store.reload()) + editingError = SettingsFailure(error: error) + throw error + } + } + + private func receive(_ snapshot: ConfigSnapshot) { + latest = snapshot + configuration = snapshot.activeConfiguration + diagnostics = snapshot.diagnostics + let failures = snapshot.diagnostics.filter { $0.severity == .error } + loadingError = failures.isEmpty ? nil : SettingsFailure(failures.map(\.description).joined(separator: "\n")) + } + + private func acquire() async { + if locked { + await withCheckedContinuation { waiters.append($0) } + } else { + locked = true + } + } + + private func release() { + if waiters.isEmpty { + locked = false + } else { + waiters.removeFirst().resume() + } + } +} + +actor SettingsFileEditor { + let fileURL: URL + + init(fileURL: URL) { self.fileURL = fileURL } + + func commit(_ edit: SettingsEdit, expectedSource: String?) throws -> String { + try Self.commit(edit, fileURL: fileURL, expectedSource: expectedSource) + } + + static func commit( + _ edit: SettingsEdit, fileURL: URL, expectedSource: String?, beforeWrite: () throws -> Void = {} + ) throws -> String { + try Task.checkCancellation() + guard fileURL.isFileURL else { + throw SettingsFailure(SettingsText.string("The configuration must be a local file.")) + } + let target = fileURL.resolvingSymlinksInPath() + try FileManager.default.createDirectory( + at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + var coordinationError: NSError? + var result: Result? + NSFileCoordinator().coordinate(writingItemAt: target, options: .forReplacing, error: &coordinationError) { + url in + result = Result { + let original = try contents(at: url) + guard original == expectedSource.map({ Data($0.utf8) }) else { throw SettingsFailure.conflict } + var document = try TOMLDocument(parsing: expectedSource ?? "") + _ = try SettingsDocumentEditor.validate(document) + try SettingsDocumentEditor.apply(edit, to: &document) + _ = try SettingsDocumentEditor.validate(document) + try beforeWrite() + try Task.checkCancellation() + guard fileURL.resolvingSymlinksInPath() == target, try contents(at: url) == original else { + throw SettingsFailure.conflict + } + if document.source != expectedSource { + let data = Data(document.source.utf8) + if original == nil { + try createAtomically(data, at: url) + } else { + try data.write(to: url, options: .atomic) + } + } + return document.source + } + } + if let coordinationError { throw coordinationError } + guard let result else { + throw SettingsFailure(SettingsText.string("The configuration file could not be coordinated for saving.")) + } + return try result.get() + } + + private static func createAtomically(_ data: Data, at url: URL) throws { + let temporary = url.deletingLastPathComponent().appendingPathComponent(".tessera-\(UUID().uuidString).tmp") + do { + try data.write(to: temporary, options: .withoutOverwriting) + // Linking publishes complete contents and fails if another editor created the destination. + try FileManager.default.linkItem(at: temporary, to: url) + } catch { + let failure = error + do { + if FileManager.default.fileExists(atPath: temporary.path) { + try FileManager.default.removeItem(at: temporary) + } + } catch { + throw SettingsFailure( + SettingsText.string( + "Saving failed: \(failure.localizedDescription). Temporary file cleanup also failed: \(error.localizedDescription)." + )) + } + throw failure + } + try FileManager.default.removeItem(at: temporary) + } + + private static func contents(at url: URL) throws -> Data? { + do { + let values = try url.resourceValues(forKeys: [.isRegularFileKey]) + guard values.isRegularFile == true else { + throw SettingsFailure(SettingsText.string("The configuration path is not a regular file.")) + } + return try Data(contentsOf: url) + } catch let error as CocoaError where error.code == .fileReadNoSuchFile { + return nil + } + } +} diff --git a/Sources/TesseraUI/Settings/SettingsNumberParser.swift b/Sources/TesseraUI/Settings/SettingsNumberParser.swift new file mode 100644 index 00000000..082e4092 --- /dev/null +++ b/Sources/TesseraUI/Settings/SettingsNumberParser.swift @@ -0,0 +1,41 @@ +import Foundation + +enum SettingsNumberParser { + static func number(_ text: String, locale: Locale = .current) throws -> Double { + guard let value = Double(try normalized(text, locale: locale)), value.isFinite else { throw invalidNumber } + return value + } + + static func integer(_ text: String, locale: Locale = .current) throws -> Int64 { + guard let value = Int64(try normalized(text, locale: locale)) else { + throw SettingsFailure(SettingsText.string("Enter a whole number.")) + } + return value + } + + private static func normalized(_ text: String, locale: Locale) throws -> String { + guard let separator = locale.decimalSeparator else { throw invalidNumber } + var text = text.trimmingCharacters(in: .whitespacesAndNewlines) + var result = "" + if text.first == "-" || text.first == "+" { + result.append(text.removeFirst()) + } + let parts = text.components(separatedBy: separator) + guard parts.count <= 2 else { throw invalidNumber } + for (index, part) in parts.enumerated() { + if index > 0 { result += "." } + for character in part { + guard character.unicodeScalars.allSatisfy(CharacterSet.decimalDigits.contains), + let digit = character.wholeNumberValue, (0...9).contains(digit) + else { throw invalidNumber } + result += String(digit) + } + } + return result + } + + private static var invalidNumber: SettingsFailure { + SettingsFailure( + SettingsText.string("Enter a number using your region’s decimal separator, without grouping separators.")) + } +} diff --git a/Sources/TesseraUI/Settings/SettingsText.swift b/Sources/TesseraUI/Settings/SettingsText.swift new file mode 100644 index 00000000..32be08ba --- /dev/null +++ b/Sources/TesseraUI/Settings/SettingsText.swift @@ -0,0 +1,115 @@ +import Foundation +import TesseraConfig + +enum SettingsText { + static func string(_ value: String.LocalizationValue) -> String { + String(localized: value, table: "Settings", bundle: .module) + } +} + +extension ConfigCommand { + var settingsTitle: String { + switch self { + case .focusLeft: SettingsText.string("Focus left") + case .focusRight: SettingsText.string("Focus right") + case .focusUp: SettingsText.string("Focus up") + case .focusDown: SettingsText.string("Focus down") + case .swapLeft: SettingsText.string("Swap left") + case .swapRight: SettingsText.string("Swap right") + case .swapUp: SettingsText.string("Swap up") + case .swapDown: SettingsText.string("Swap down") + case .moveLeft: SettingsText.string("Move left") + case .moveRight: SettingsText.string("Move right") + case .moveUp: SettingsText.string("Move up") + case .moveDown: SettingsText.string("Move down") + case .layoutGrid: SettingsText.string("Grid layout") + case .layoutColumns: SettingsText.string("Columns layout") + case .layoutRows: SettingsText.string("Rows layout") + case .layoutSide: SettingsText.string("Side layout") + case .ratioIncrease: SettingsText.string("Increase ratio") + case .ratioDecrease: SettingsText.string("Decrease ratio") + case .floatToggle: SettingsText.string("Toggle floating") + case .retile: SettingsText.string("Retile windows") + case .stack: SettingsText.string("Stack windows") + case .stackNext: SettingsText.string("Next stacked window") + case .stackPrevious: SettingsText.string("Previous stacked window") + case .displayMoveLeft: SettingsText.string("Move to display on left") + case .displayMoveRight: SettingsText.string("Move to display on right") + case .displayMoveUp: SettingsText.string("Move to display above") + case .displayMoveDown: SettingsText.string("Move to display below") + case .openSettings: SettingsText.string("Open Settings") + case .pauseTiling: SettingsText.string("Pause or resume tiling") + case .quit: SettingsText.string("Quit Tessera") + } + } +} + +extension SettingsLayoutField { + var title: String { + switch self { + case .defaultLayout: SettingsText.string("Default layout") + case .ratio: SettingsText.string("Ratio") + case .innerGap: SettingsText.string("Inner gap") + case .outerGap: SettingsText.string("Outer gap") + case .reservedTop: SettingsText.string("Reserved top edge") + case .reservedRight: SettingsText.string("Reserved right edge") + case .reservedBottom: SettingsText.string("Reserved bottom edge") + case .reservedLeft: SettingsText.string("Reserved left edge") + case .windowCap: SettingsText.string("Window limit (0 means unlimited)") + } + } + + func number(in values: LayoutValues) -> Double { + switch self { + case .ratio: values.ratio + case .innerGap: values.gaps.inner + case .outerGap: values.gaps.outer + case .reservedTop: values.reserved.top + case .reservedRight: values.reserved.right + case .reservedBottom: values.reserved.bottom + case .reservedLeft: values.reserved.left + case .windowCap: Double(values.windowCap) + case .defaultLayout: preconditionFailure() + } + } +} + +extension ConfigLayout { + var settingsTitle: String { + switch self { + case .grid: SettingsText.string("Grid") + case .columns: SettingsText.string("Columns") + case .rows: SettingsText.string("Rows") + case .side: SettingsText.string("Side") + } + } +} + +extension ConfigMotionLevel { + var settingsTitle: String { + switch self { + case .calm: SettingsText.string("Calm") + case .playful: SettingsText.string("Playful") + case .extra: SettingsText.string("Extra") + } + } +} + +extension ConfigMotionTransition { + var settingsTitle: String { + switch self { + case .glide: SettingsText.string("Glide") + case .ghost: SettingsText.string("Ghost") + case .snap: SettingsText.string("Snap") + } + } +} + +extension ConfigMenuBarIcon { + var settingsTitle: String { + switch self { + case .minimap: SettingsText.string("Mini map") + case .logo: SettingsText.string("Logo") + } + } +} diff --git a/Sources/TesseraUI/Settings/SettingsView.swift b/Sources/TesseraUI/Settings/SettingsView.swift new file mode 100644 index 00000000..0f0b14a7 --- /dev/null +++ b/Sources/TesseraUI/Settings/SettingsView.swift @@ -0,0 +1,409 @@ +public import SwiftUI +import TesseraConfig + +@MainActor +public struct SettingsView: View { + private let model: SettingsModel + private let permissions: AnyView + @State private var shortcut: ConfigCommand? + @State private var ruleDraft: RuleDraft? + @State private var display: UUID? + @State private var displayText = "" + + public init(model: SettingsModel, permissions: AnyView) { + self.model = model + self.permissions = permissions + } + + public var body: some View { + VStack(spacing: 0) { + if let error = model.error { + VStack(alignment: .leading, spacing: 8) { + Label( + SettingsText.string("Settings could not be saved or loaded"), + systemImage: "exclamationmark.triangle" + ) + .font(.headline) + Text(error.message).textSelection(.enabled) + Button(SettingsText.string("Reload configuration")) { Task { await model.reload() } } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding() + Divider() + } + TabView { + general.tabItem { Label(SettingsText.string("General"), systemImage: "gearshape") } + layout.tabItem { Label(SettingsText.string("Layout"), systemImage: "rectangle.split.2x2") } + motion.tabItem { Label(SettingsText.string("Motion"), systemImage: "sparkles") } + shortcuts.tabItem { Label(SettingsText.string("Shortcuts"), systemImage: "keyboard") } + rules.tabItem { Label(SettingsText.string("Rules"), systemImage: "line.3.horizontal.decrease.circle") } + permissions.tabItem { Label(SettingsText.string("Permissions"), systemImage: "lock.shield") } + about.tabItem { Label(SettingsText.string("About"), systemImage: "info.circle") } + } + HStack { + Text(model.store.fileURL.path).font(.caption).textSelection(.enabled) + Spacer() + if model.isSaving { + ProgressView().controlSize(.small).accessibilityLabel(SettingsText.string("Saving configuration")) + } + } + .padding(12) + } + .frame(minWidth: 680, minHeight: 560) + .task { await model.start() } + .sheet(isPresented: Binding(get: { shortcut != nil }, set: { if !$0 { shortcut = nil } })) { + if let shortcut { ShortcutEditor(model: model, command: shortcut) } + } + .sheet(item: $ruleDraft) { draft in RuleEditor(model: model, draft: draft) } + } + + private var general: some View { + Form { + Toggle( + SettingsText.string("Launch at login"), + isOn: boolean(model.configuration.general.launchAtLogin, field: .launchAtLogin)) + SettingsValueEditor( + title: SettingsText.string("Shortcut prefix"), value: model.configuration.general.prefix.description + ) { text in + _ = try KeyModifiers(parsing: text) + try await model.setValue(.string(text), for: .prefix) + } + Text( + SettingsText.string( + "The prefix applies to inherited shortcuts. Explicit shortcuts keep their own modifiers.") + ) + .font(.caption).foregroundStyle(.secondary) + Toggle( + SettingsText.string("Announce layout changes"), + isOn: boolean(model.configuration.accessibility.announceLayoutChanges, field: .announceLayoutChanges)) + if !model.diagnostics.isEmpty { + Section(SettingsText.string("Configuration diagnostics")) { + ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diagnostic in + Text(diagnostic.description).textSelection(.enabled) + } + } + } + } + .formStyle(.grouped) + } + + private var layout: some View { + Form { + Picker(SettingsText.string("Configure layout for"), selection: $display) { + Text(SettingsText.string("All displays")).tag(UUID?.none) + ForEach( + model.configuration.layout.displays.keys.sorted(by: { $0.uuidString < $1.uuidString }), id: \.self + ) { id in + Text(id.uuidString).tag(Optional(id)) + } + } + HStack { + TextField(SettingsText.string("Display UUID"), text: $displayText) + Button(SettingsText.string("Add display override")) { + perform { + guard displayText.count == 36, let id = UUID(uuidString: displayText) else { + throw SettingsFailure(SettingsText.string("Enter a valid display UUID.")) + } + if model.configuration.layout.displays[id] == nil { + try await model.setValue( + .string(model.configuration.layout.global.defaultLayout.rawValue), + for: .layout(.defaultLayout, display: id)) + } + display = id + displayText = "" + } + } + } + let values = display.map { model.configuration.layout.values(for: $0) } ?? model.configuration.layout.global + Picker( + SettingsText.string("Default layout"), + selection: Binding( + get: { values.defaultLayout }, + set: { value in + perform { + try await model.setValue( + .string(value.rawValue), for: .layout(.defaultLayout, display: display)) + } + }) + ) { + ForEach(ConfigLayout.allCases, id: \.self) { Text($0.settingsTitle).tag($0) } + } + ForEach(SettingsLayoutField.allCases.filter { $0 != .defaultLayout }, id: \.self) { field in + SettingsValueEditor(title: field.title, value: valuesNumber(field, values: values)) { text in + let value: TOMLValue + if field == .windowCap { + value = .integer(try SettingsNumberParser.integer(text)) + } else { + value = .float(try SettingsNumberParser.number(text)) + } + try await model.setValue(value, for: .layout(field, display: display)) + } + .id("\(display?.uuidString ?? "global").\(field.rawValue)") + } + } + .formStyle(.grouped) + .onChange(of: model.configuration.layout.displays) { + if let display, model.configuration.layout.displays[display] == nil { self.display = nil } + } + } + + private func valuesNumber(_ field: SettingsLayoutField, values: LayoutValues) -> String { + if field == .windowCap { return values.windowCap.formatted(.number.grouping(.never)) } + return field.number(in: values).formatted(.number.grouping(.never).precision(.fractionLength(0...16))) + } + + private var motion: some View { + Form { + Toggle( + SettingsText.string("Enable motion"), + isOn: boolean(model.configuration.motion.enabled, field: .motion(.enabled))) + Picker( + SettingsText.string("Motion level"), + selection: Binding( + get: { model.configuration.motion.level }, + set: { value in + perform { try await model.setValue(.string(value.rawValue), for: .motion(.level)) } + }) + ) { + ForEach(ConfigMotionLevel.allCases, id: \.self) { Text($0.settingsTitle).tag($0) } + } + SettingsValueEditor( + title: SettingsText.string("Speed multiplier"), + value: model.configuration.motion.speed.formatted( + .number.grouping(.never).precision(.fractionLength(0...16))) + ) { text in + try await model.setValue(.float(try SettingsNumberParser.number(text)), for: .motion(.speed)) + } + Picker( + SettingsText.string("Transition"), + selection: Binding( + get: { model.configuration.motion.transitions }, + set: { value in + perform { try await model.setValue(.string(value.rawValue), for: .motion(.transitions)) } + }) + ) { + ForEach(ConfigMotionTransition.allCases, id: \.self) { Text($0.settingsTitle).tag($0) } + } + Toggle( + SettingsText.string("Focus border"), + isOn: boolean(model.configuration.motion.focusBorder, field: .motion(.focusBorder))) + Toggle( + SettingsText.string("Sound"), isOn: boolean(model.configuration.motion.sound, field: .motion(.sound))) + Picker( + SettingsText.string("Menu bar icon"), + selection: Binding( + get: { model.configuration.motion.menuBarIcon }, + set: { value in + perform { try await model.setValue(.string(value.rawValue), for: .motion(.menuBarIcon)) } + }) + ) { + ForEach(ConfigMenuBarIcon.allCases, id: \.self) { Text($0.settingsTitle).tag($0) } + } + Section(SettingsText.string("Preview")) { MotionPreview(motion: model.configuration.motion) } + } + .formStyle(.grouped) + } + + private var shortcuts: some View { + Form { + ForEach(ConfigCommand.allCases, id: \.self) { command in + LabeledContent(command.settingsTitle) { + Text(model.configuration.keybindings[command]?.description ?? SettingsText.string("Not assigned")) + .monospaced() + Button(SettingsText.string("Edit shortcut")) { shortcut = command } + .accessibilityLabel(SettingsText.string("Edit shortcut for \(command.settingsTitle)")) + } + } + } + .formStyle(.grouped) + } + + private var rules: some View { + Form { + Text(SettingsText.string("Matching windows float instead of tiling. Each rule needs at least one matcher.")) + Button(SettingsText.string("Add floating rule")) { + ruleDraft = RuleDraft(index: nil, original: FloatRule()) + } + ForEach(Array(model.configuration.floatRules.enumerated()), id: \.offset) { index, rule in + Section { + if let value = rule.bundleID { + LabeledContent(SettingsText.string("Bundle identifier"), value: value) + } + if let value = rule.titleRegex { + LabeledContent(SettingsText.string("Window title pattern"), value: value) + } + if let value = rule.role { LabeledContent(SettingsText.string("Accessibility role"), value: value) } + HStack { + Button(SettingsText.string("Edit rule")) { ruleDraft = RuleDraft(index: index, original: rule) } + Button(SettingsText.string("Remove rule"), role: .destructive) { + perform { try await model.removeRule(at: index, matching: rule) } + } + } + } + } + } + .formStyle(.grouped) + } + + private var about: some View { + Form { + Text(SettingsText.string("Tessera")).font(.largeTitle) + if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String { + LabeledContent(SettingsText.string("Version"), value: version) + } else { + Text(SettingsText.string("Development build")) + } + Text(SettingsText.string("A tiling window manager for macOS.")) + Text(SettingsText.string("Licensed under the Apache License, Version 2.0.")) + } + .formStyle(.grouped) + } + + private func boolean(_ value: Bool, field: SettingsField) -> Binding { + Binding(get: { value }, set: { newValue in perform { try await model.setValue(.bool(newValue), for: field) } }) + } + + private func perform(_ operation: @escaping @MainActor () async throws -> Void) { + Task { + do { try await operation() } catch { model.report(error) } + } + } +} + +private struct SettingsValueEditor: View { + let title: String + let value: String + let save: @MainActor (String) async throws -> Void + @State private var draft: String + @State private var latestValue: String + @State private var dirty = false + @State private var stale = false + @State private var saving = false + @State private var failure: String? + + init(title: String, value: String, save: @escaping @MainActor (String) async throws -> Void) { + self.title = title + self.value = value + self.save = save + _draft = State(initialValue: value) + _latestValue = State(initialValue: value) + } + + var body: some View { + VStack(alignment: .leading) { + HStack { + TextField( + title, + text: Binding( + get: { draft }, + set: { + draft = $0 + dirty = true + }) + ) + .onSubmit { submit() } + .disabled(saving) + Button(SettingsText.string("Save")) { submit() } + .disabled(!dirty || stale || saving) + .accessibilityLabel(SettingsText.string("Save \(title)")) + } + if stale { + Text(SettingsText.string("This value changed outside this editor. Reload it before editing.")) + Button(SettingsText.string("Reload value")) { + draft = value + dirty = false + stale = false + failure = nil + } + } + if let failure { Text(failure).foregroundStyle(.red).textSelection(.enabled) } + } + .onChange(of: value) { + latestValue = value + if dirty { + if !saving { stale = true } + } else { + draft = value + } + } + } + + private func submit() { + guard dirty, !stale, !saving else { return } + saving = true + let original = latestValue + Task { + do { + try await save(draft) + draft = latestValue + dirty = false + failure = nil + } catch { + stale = latestValue != original + failure = SettingsFailure(error: error).message + } + saving = false + } + } +} + +private struct RuleDraft: Identifiable { + let id = UUID() + let index: Int? + let original: FloatRule +} + +private struct RuleEditor: View { + let model: SettingsModel + let draft: RuleDraft + @Environment(\.dismiss) private var dismiss + @State private var bundleID: String + @State private var titleRegex: String + @State private var role: String + @State private var saving = false + @State private var failure: String? + + init(model: SettingsModel, draft: RuleDraft) { + self.model = model + self.draft = draft + _bundleID = State(initialValue: draft.original.bundleID ?? "") + _titleRegex = State(initialValue: draft.original.titleRegex ?? "") + _role = State(initialValue: draft.original.role ?? "") + } + + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text(SettingsText.string("Floating rule")).font(.headline) + TextField(SettingsText.string("Bundle identifier"), text: $bundleID) + TextField(SettingsText.string("Window title pattern"), text: $titleRegex) + TextField(SettingsText.string("Accessibility role"), text: $role) + if let failure { Text(failure).foregroundStyle(.red).textSelection(.enabled) } + HStack { + Spacer() + Button(SettingsText.string("Cancel")) { dismiss() } + Button(SettingsText.string("Save")) { + saving = true + Task { + do { + let rule = FloatRule( + bundleID: bundleID.isEmpty ? nil : bundleID, + titleRegex: titleRegex.isEmpty ? nil : titleRegex, role: role.isEmpty ? nil : role) + if let index = draft.index { + try await model.setRule(rule, at: index, replacing: draft.original) + } else { + try await model.addRule(rule) + } + dismiss() + } catch { + failure = SettingsFailure(error: error).message + } + saving = false + } + } + } + } + .disabled(saving) + .padding(24) + .frame(width: 460) + } +} diff --git a/Sources/TesseraUI/Settings/ShortcutRecorder.swift b/Sources/TesseraUI/Settings/ShortcutRecorder.swift new file mode 100644 index 00000000..e96a4852 --- /dev/null +++ b/Sources/TesseraUI/Settings/ShortcutRecorder.swift @@ -0,0 +1,168 @@ +public import AppKit +import SwiftUI +public import TesseraConfig + +public enum ShortcutRecorderParser { + public static func parse(_ text: String) throws -> KeyChord { + try KeyChord(parsing: text) + } + + public static func chord( + keyCode: UInt16, modifiers flags: NSEvent.ModifierFlags, functionKeyPressed: Bool = false + ) throws -> KeyChord { + guard let key = ANSIKey.allCases.first(where: { $0.keyCode == keyCode }) else { + throw SettingsFailure(SettingsText.string("This key is not supported. Enter an ANSI shortcut instead.")) + } + var modifiers: KeyModifiers = [] + if flags.contains(.control) { modifiers.insert(.ctrl) } + if flags.contains(.option) { modifiers.insert(.alt) } + if flags.contains(.command) { modifiers.insert(.cmd) } + if flags.contains(.shift) { modifiers.insert(.shift) } + // AppKit marks navigation and function keys as function even without a held Fn key. + if functionKeyPressed || (flags.contains(.function) && !intrinsicFunctionKeys.contains(key)) { + modifiers.insert(.fn) + } + return KeyChord(modifiers: modifiers, key: key) + } + + private static let intrinsicFunctionKeys: Set = [ + .left, .right, .up, .down, .home, .end, .pageUp, .pageDown, .forwardDelete, .help, + .f1, .f2, .f3, .f4, .f5, .f6, .f7, .f8, .f9, .f10, + .f11, .f12, .f13, .f14, .f15, .f16, .f17, .f18, .f19, .f20, + ] +} + +struct ShortcutEditor: View { + let model: SettingsModel + let command: ConfigCommand + @Environment(\.dismiss) private var dismiss + @State private var text: String + @State private var recording = false + @State private var saving = false + @State private var failure: String? + + init(model: SettingsModel, command: ConfigCommand) { + self.model = model + self.command = command + _text = State(initialValue: model.configuration.keybindings[command]?.description ?? "") + } + + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text(command.settingsTitle).font(.headline) + Text( + SettingsText.string( + "Shortcuts use physical ANSI key positions. You can also type a shortcut using modifier and key names." + )) + TextField(SettingsText.string("Shortcut"), text: $text) + .disabled(recording || saving) + .onSubmit { save() } + if recording { + RecordingKeyView { result in + switch result { + case .success(let chord): text = chord.description + case .failure(let error): failure = error.message + } + recording = false + } + .frame(height: 32) + Text( + SettingsText.string( + "Press a shortcut, including any modifiers. Tab and Escape can also be recorded.") + ) + .font(.caption) + } else { + Button(SettingsText.string("Record shortcut")) { + failure = nil + recording = true + } + .disabled(saving) + } + if let failure { Text(failure).foregroundStyle(.red).textSelection(.enabled) } + HStack { + Button(SettingsText.string("Clear shortcut")) { save(clear: true) } + .disabled(saving) + Spacer() + Button(SettingsText.string("Cancel")) { dismiss() } + .disabled(saving) + Button(SettingsText.string("Save")) { save() } + .disabled(saving || recording) + } + } + .padding(24) + .frame(width: 460) + } + + private func save(clear: Bool = false) { + saving = true + Task { + do { + if clear { + try await model.setShortcut(nil, for: command) + } else { + try await model.setShortcut(text: text, for: command) + } + dismiss() + } catch { + failure = SettingsFailure(error: error).message + } + saving = false + } + } +} + +private struct RecordingKeyView: NSViewRepresentable { + let captured: @MainActor (Result) -> Void + + func makeNSView(context: Context) -> RecordingButton { + let button = RecordingButton() + button.title = SettingsText.string("Listening for a shortcut…") + button.bezelStyle = .rounded + button.setAccessibilityLabel(SettingsText.string("Shortcut recorder")) + button.setAccessibilityHelp( + SettingsText.string("Press a shortcut, including any modifiers. Tab and Escape can also be recorded.")) + button.captured = captured + return button + } + + func updateNSView(_ nsView: RecordingButton, context: Context) { + nsView.captured = captured + } +} + +private final class RecordingButton: NSButton { + var captured: (@MainActor (Result) -> Void)? + private var finished = false + private var functionKeyPressed = false + override var acceptsFirstResponder: Bool { true } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + window?.makeFirstResponder(self) + } + + override func performKeyEquivalent(with event: NSEvent) -> Bool { + guard window?.firstResponder === self, !finished else { return false } + keyDown(with: event) + return true + } + + override func keyDown(with event: NSEvent) { + guard !finished, !event.isARepeat else { return } + finished = true + do { + captured?( + .success( + try ShortcutRecorderParser.chord( + keyCode: event.keyCode, modifiers: event.modifierFlags, functionKeyPressed: functionKeyPressed)) + ) + } catch { + captured?(.failure(SettingsFailure(error: error))) + } + } + + override func flagsChanged(with event: NSEvent) { + if event.keyCode == 63 { functionKeyPressed = event.modifierFlags.contains(.function) } + if event.keyCode == ANSIKey.capsLock.keyCode { keyDown(with: event) } + } +} diff --git a/Sources/TesseraUI/ShellServices.swift b/Sources/TesseraUI/ShellServices.swift new file mode 100644 index 00000000..ce82243a --- /dev/null +++ b/Sources/TesseraUI/ShellServices.swift @@ -0,0 +1,202 @@ +public import Foundation +public import TesseraConfig + +public struct LayoutTile: Equatable, Sendable, Identifiable { + public let id: UInt64 + public let frame: CGRect + public let isFocused: Bool + + public init(id: UInt64, frame: CGRect, isFocused: Bool = false) { + precondition(frame.isFiniteAndPositive) + self.id = id + self.frame = frame + self.isFocused = isFocused + } +} + +public struct LayoutSnapshot: Equatable, Sendable { + public let layout: ConfigLayout + public let bounds: CGRect + public let tiles: [LayoutTile] + public let isPaused: Bool + + public init(layout: ConfigLayout, bounds: CGRect, tiles: [LayoutTile], isPaused: Bool = false) { + precondition(bounds.isFiniteAndPositive) + precondition(Set(tiles.map(\.id)).count == tiles.count) + self.layout = layout + self.bounds = bounds + self.tiles = tiles + self.isPaused = isPaused + } + + public var accessibilityDescription: String { + let format = + tiles.count == 1 ? UIStrings.text("%@ layout, 1 window") : UIStrings.text("%@ layout, %lld windows") + return String(format: format, locale: .current, layout.uiTitle, tiles.count) + } +} + +@MainActor +public protocol LayoutSnapshotProviding: AnyObject { + /// Includes the current snapshot, then yields only changes. + func snapshots() -> AsyncStream +} + +public enum PermissionStatus: Equatable, Sendable { + case checking, missing, granted +} + +@MainActor +public protocol PermissionStatusProviding: AnyObject { + func permissionUpdates() -> AsyncStream + func refreshPermission() async + func openAccessibilitySettings() throws +} + +@MainActor +public protocol UICommandSink: AnyObject { + func send(_ command: ConfigCommand) async throws +} + +@MainActor +final class LatestValues { + private var value: Value + private var continuations: [UUID: AsyncStream.Continuation] = [:] + + init(_ value: Value) { self.value = value } + + func stream() -> AsyncStream { + let id = UUID() + let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + continuations[id] = continuation + continuation.yield(value) + continuation.onTermination = { [weak self] _ in + Task { @MainActor in self?.continuations.removeValue(forKey: id) } + } + return stream + } + + func yield(_ value: Value) { + self.value = value + for continuation in continuations.values { continuation.yield(value) } + } + + deinit { for continuation in continuations.values { continuation.finish() } } +} + +@MainActor +public final class PreviewShellServices: LayoutSnapshotProviding, PermissionStatusProviding, UICommandSink { + private let layouts: LatestValues + private let permissions: LatestValues + private var snapshot: LayoutSnapshot + public private(set) var commands: [ConfigCommand] = [] + public private(set) var settingsOpenCount = 0 + public private(set) var refreshCount = 0 + + public init(snapshot: LayoutSnapshot = .preview, permission: PermissionStatus = .missing) { + self.snapshot = snapshot + layouts = LatestValues(snapshot) + permissions = LatestValues(permission) + } + + public func snapshots() -> AsyncStream { layouts.stream() } + public func permissionUpdates() -> AsyncStream { permissions.stream() } + public func refreshPermission() async { refreshCount += 1 } + public func openAccessibilitySettings() throws { settingsOpenCount += 1 } + public func send(_ command: ConfigCommand) async throws { + commands.append(command) + if command == .pauseTiling { + publish( + LayoutSnapshot( + layout: snapshot.layout, bounds: snapshot.bounds, + tiles: snapshot.tiles, isPaused: !snapshot.isPaused)) + } else if let layout = ConfigLayout.allCases.first(where: { $0.command == command }) { + let count = snapshot.tiles.count + let tiles = snapshot.tiles.enumerated().map { index, tile in + let width = snapshot.bounds.width + let height = snapshot.bounds.height + let frame: CGRect + switch layout { + case .columns: + frame = CGRect( + x: Double(index) * width / Double(count), y: 0, + width: width / Double(count), height: height) + case .rows: + frame = CGRect( + x: 0, y: Double(index) * height / Double(count), + width: width, height: height / Double(count)) + case .side: + if index == 0 { + frame = CGRect(x: 0, y: 0, width: count == 1 ? width : width / 2, height: height) + } else { + frame = CGRect( + x: width / 2, y: Double(index - 1) * height / Double(count - 1), + width: width / 2, height: height / Double(count - 1)) + } + case .grid: + let columns = Int(Double(count).squareRoot().rounded(.up)) + let rows = (count + columns - 1) / columns + frame = CGRect( + x: Double(index % columns) * width / Double(columns), + y: Double(index / columns) * height / Double(rows), + width: width / Double(columns), height: height / Double(rows)) + } + return LayoutTile( + id: tile.id, + frame: frame.offsetBy(dx: snapshot.bounds.minX, dy: snapshot.bounds.minY), isFocused: tile.isFocused + ) + } + publish(LayoutSnapshot(layout: layout, bounds: snapshot.bounds, tiles: tiles, isPaused: snapshot.isPaused)) + } + } + public func publish(_ snapshot: LayoutSnapshot) { + guard self.snapshot != snapshot else { return } + self.snapshot = snapshot + layouts.yield(snapshot) + } + public func publish(permission: PermissionStatus) { permissions.yield(permission) } +} + +extension LayoutSnapshot { + public static let preview = LayoutSnapshot( + layout: .side, bounds: CGRect(x: 0, y: 0, width: 1000, height: 700), + tiles: [ + LayoutTile(id: 1, frame: CGRect(x: 0, y: 0, width: 550, height: 700), isFocused: true), + LayoutTile(id: 2, frame: CGRect(x: 550, y: 0, width: 450, height: 350)), + LayoutTile(id: 3, frame: CGRect(x: 550, y: 350, width: 450, height: 350)), + ] + ) +} + +extension CGRect { + var isFiniteAndPositive: Bool { + origin.x.isFinite && origin.y.isFinite && width.isFinite && height.isFinite + && maxX.isFinite && maxY.isFinite && width > 0 && height > 0 + } +} + +extension ConfigLayout { + var uiTitle: String { + switch self { + case .grid: UIStrings.text("Grid") + case .columns: UIStrings.text("Columns") + case .rows: UIStrings.text("Rows") + case .side: UIStrings.text("Side") + } + } + + var command: ConfigCommand { + switch self { + case .grid: .layoutGrid + case .columns: .layoutColumns + case .rows: .layoutRows + case .side: .layoutSide + } + } +} + +enum UIStrings { + static func text(_ key: String) -> String { + Bundle.module.localizedString(forKey: key, value: nil, table: "UI") + } +} diff --git a/Sources/TesseraUI/TesseraUI.docc/TesseraUI.md b/Sources/TesseraUI/TesseraUI.docc/TesseraUI.md new file mode 100644 index 00000000..9e6d3743 --- /dev/null +++ b/Sources/TesseraUI/TesseraUI.docc/TesseraUI.md @@ -0,0 +1,29 @@ +# TesseraUI + +The menu bar, settings, and first-run shell. No window-management calls live here. + +## Connecting the shell + +Create ``TesseraShell`` with a ``LayoutSnapshotProviding``, ``PermissionStatusProviding``, and ``UICommandSink``. Call `start()` once and await `stop()` before exiting. Snapshot frames use the same coordinate space as their bounds, with y increasing downward. Tile identifiers must stay stable across layout changes. + +The shell handles `open-settings` and `quit` locally. Other commands go to the command sink. `pause-tiling` is a toggle; the next snapshot confirms its state. Both new commands have configurable defaults in `TesseraConfig`. + +``PreviewShellServices`` replays current values and simulates layout and pause commands. The app currently uses that preview backend, says so in the menu, and checks real Accessibility permission. Replace the preview backend when the engine is ready. Login registration, sound, and focus-border effects are not implemented by this shell; their controls persist configuration for the owning services. + +## Settings and files + +``SettingsModel`` exposes the configuration, validation diagnostics, save state, and a visible error. ``SettingsView`` starts the model when shown; its owner stops it. A watcher that already belonged to another consumer is not stopped. + +Edits go through `TOMLDocument` and full config validation. Writes preserve comments and unknown fields, reject stale or invalid source, and serialize rapid GUI edits. File coordination protects cooperating writers. A non-cooperating editor can still race the final source check and atomic replacement; `ConfigStore` does not provide a filesystem compare-and-swap operation. Unsupported structural rule edits fail visibly instead of discarding extensions. + +## Resources and motion + +Keystone and Split SVGs live in `Resources/Brand`. String Catalogs have checked-in SwiftPM tables; regenerate them with: + +```sh +Scripts/generate-config-strings.sh Sources/TesseraUI/Resources +``` + +``MiniMapMorph`` uses the `glance` token, keeps presentation geometry and velocity on retarget, and stops after at most ten frames. Hidden icons, Reduce Motion, and disabled motion snap immediately. No animation timer runs while idle. Permission polling in the app runs only while access is missing; activation rechecks an existing grant. + +The tests cover settings round trips and conflicts, shortcut parsing, onboarding, menu wiring, mini-map geometry, and black-on-clear PNG rendering. A full keyboard/VoiceOver audit and distribution-ready app packaging still need a signed application and an authorized GUI test runner. diff --git a/Sources/TesseraUI/TesseraUI.swift b/Sources/TesseraUI/TesseraUI.swift index 8b137891..a57e8697 100644 --- a/Sources/TesseraUI/TesseraUI.swift +++ b/Sources/TesseraUI/TesseraUI.swift @@ -1 +1,210 @@ +public import AppKit +import SwiftUI +public import TesseraConfig +@MainActor +public final class TesseraShell: NSObject { + public let settings: SettingsModel + public let onboarding: OnboardingModel + public private(set) var menuBar: MenuBarController? + private let layouts: any LayoutSnapshotProviding + private let permissions: any PermissionStatusProviding + private let commands: any UICommandSink + private let defaults: UserDefaults + private let preview: Bool + private var snapshot: LayoutSnapshot? + private var configuration = TesseraConfiguration.defaults + private var tasks: [Task] = [] + private var commandTasks: [UUID: Task] = [:] + private var settingsWindow: NSWindow? + private var onboardingWindow: NSWindow? + private var isStarted = false + + public init( + layouts: any LayoutSnapshotProviding, permissions: any PermissionStatusProviding, + commands: any UICommandSink, configStore: ConfigStore = ConfigStore(), + defaults: UserDefaults = .standard, preview: Bool = false + ) { + self.layouts = layouts + self.permissions = permissions + self.commands = commands + self.defaults = defaults + self.preview = preview + settings = SettingsModel(store: configStore) + onboarding = OnboardingModel(provider: permissions) + super.init() + } + + public func start() async throws { + guard !isStarted else { return } + let icon = try BrandAssets.keystone() + let menuBar = try MenuBarController { [weak self] command in self?.dispatch(command) } + self.menuBar = menuBar + isStarted = true + NSApplication.shared.applicationIconImage = icon + await settings.start() + configuration = settings.configuration + tasks.append( + Task { @MainActor [weak self, layouts] in + for await snapshot in layouts.snapshots() { + guard !Task.isCancelled, let self else { return } + if self.snapshot != snapshot { + self.snapshot = snapshot + self.renderMenu() + } + } + }) + tasks.append( + Task { @MainActor [weak self, permissions] in + for await permission in permissions.permissionUpdates() { + guard !Task.isCancelled, let self else { return } + self.onboarding.receive(permission) + self.renderMenu() + } + }) + tasks.append( + Task { @MainActor [weak self, store = settings.store] in + for await snapshot in await store.updates() { + guard !Task.isCancelled, let self else { return } + self.configuration = snapshot.activeConfiguration + self.renderMenu() + if snapshot.loadState == .rejected { self.showSettings() } + } + }) + NSWorkspace.shared.notificationCenter.addObserver( + self, selector: #selector(accessibilityChanged), + name: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil + ) + NotificationCenter.default.addObserver( + self, selector: #selector(applicationActivated), name: NSApplication.didBecomeActiveNotification, + object: nil + ) + if !defaults.bool(forKey: "onboardingCompleted") { showOnboarding() } + if settings.error != nil { showSettings() } + await permissions.refreshPermission() + } + + public func stop() async { + guard isStarted else { return } + isStarted = false + for task in tasks { task.cancel() } + tasks = [] + for task in commandTasks.values { task.cancel() } + commandTasks = [:] + NSWorkspace.shared.notificationCenter.removeObserver(self) + NotificationCenter.default.removeObserver(self) + menuBar?.stop() + menuBar = nil + settingsWindow?.close() + onboardingWindow?.close() + settingsWindow = nil + onboardingWindow = nil + await settings.stop() + } + + public func showSettings() { + if settingsWindow == nil { + let view = SettingsView(model: settings, permissions: AnyView(PermissionsView(model: onboarding))) + settingsWindow = makeWindow(title: UIStrings.text("Tessera Settings"), view: view) + settingsWindow?.setFrameAutosaveName("TesseraSettings") + } + show(settingsWindow) + } + + public func showOnboarding() { + if onboardingWindow == nil { + let view = ShellOnboarding(model: onboarding, settings: settings) { [weak self] in + self?.defaults.set(true, forKey: "onboardingCompleted") + self?.onboardingWindow?.close() + } + onboardingWindow = makeWindow(title: UIStrings.text("Welcome to Tessera"), view: view) + } + show(onboardingWindow) + } + + public func showError(_ error: any Error) { + let alert = NSAlert() + alert.messageText = UIStrings.text("Tessera Needs Your Attention") + alert.informativeText = error.localizedDescription + alert.addButton(withTitle: UIStrings.text("OK")) + NSApplication.shared.activate(ignoringOtherApps: true) + alert.runModal() + } + + private func dispatch(_ command: ConfigCommand) { + switch command { + case .openSettings: showSettings() + case .quit: NSApplication.shared.terminate(nil) + default: + let id = UUID() + commandTasks[id] = Task { @MainActor [weak self, commands] in + defer { self?.commandTasks.removeValue(forKey: id) } + do { try await commands.send(command) } catch is CancellationError { return } catch { + self?.showError(error) + } + } + } + } + + @objc private func accessibilityChanged() { renderMenu() } + + @objc private func applicationActivated() { + let id = UUID() + commandTasks[id] = Task { @MainActor [weak self, permissions] in + await permissions.refreshPermission() + self?.commandTasks.removeValue(forKey: id) + } + } + + private func renderMenu() { + guard let snapshot else { return } + let workspace = NSWorkspace.shared + menuBar?.update( + snapshot: snapshot, configuration: configuration, permission: onboarding.permission, + reduceMotion: workspace.accessibilityDisplayShouldReduceMotion, + increaseContrast: workspace.accessibilityDisplayShouldIncreaseContrast, + notice: preview ? UIStrings.text("Preview — your windows are not managed.") : nil) + let appMenu = CommandMenu(title: UIStrings.text("Tessera")) + appMenu.routing.invoke = { [weak self] command in self?.dispatch(command) } + for (title, command) in [("Settings…", ConfigCommand.openSettings), ("Quit Tessera", ConfigCommand.quit)] { + appMenu.routing.bindings[command] = configuration.keybindings[command] + appMenu.addItem( + CommandMenuItem( + title: UIStrings.text(title), command: command, + chord: configuration.keybindings[command] + ) { [weak self] command in self?.dispatch(command) }) + } + let root = NSMenu() + let item = NSMenuItem(title: UIStrings.text("Tessera"), action: nil, keyEquivalent: "") + item.submenu = appMenu + root.addItem(item) + NSApplication.shared.mainMenu = root + } + + private func makeWindow(title: String, view: Content) -> NSWindow { + let window = NSWindow(contentViewController: NSHostingController(rootView: view)) + window.title = title + window.styleMask = [.titled, .closable, .miniaturizable, .resizable] + window.isReleasedWhenClosed = false + window.center() + return window + } + + private func show(_ window: NSWindow?) { + NSApplication.shared.activate(ignoringOtherApps: true) + window?.makeKeyAndOrderFront(nil) + } + + deinit { + for task in tasks { task.cancel() } + for task in commandTasks.values { task.cancel() } + } +} + +private struct ShellOnboarding: View { + let model: OnboardingModel + let settings: SettingsModel + let finish: @MainActor () -> Void + + var body: some View { OnboardingView(model: model, motion: settings.configuration.motion, finish: finish) } +} diff --git a/Tests/TesseraConfigTests/KeyChordTests.swift b/Tests/TesseraConfigTests/KeyChordTests.swift index 3202f655..ce8839fb 100644 --- a/Tests/TesseraConfigTests/KeyChordTests.swift +++ b/Tests/TesseraConfigTests/KeyChordTests.swift @@ -256,7 +256,7 @@ private enum KeyChordSamples { (.stackNext, "ctrl-alt-]"), (.stackPrevious, "ctrl-alt-["), (.displayMoveLeft, "ctrl-alt-cmd-f1"), (.displayMoveRight, "ctrl-alt-cmd-f2"), (.displayMoveUp, "ctrl-alt-cmd-f3"), (.displayMoveDown, "ctrl-alt-cmd-f4"), - (.openSettings, "ctrl-alt-,"), + (.openSettings, "ctrl-alt-,"), (.pauseTiling, "ctrl-alt-p"), (.quit, "ctrl-alt-q"), ] static let commands: [(ConfigCommand, String)] = [ @@ -270,6 +270,6 @@ private enum KeyChordSamples { (.stackNext, "stack-next"), (.stackPrevious, "stack-previous"), (.displayMoveLeft, "display-move-left"), (.displayMoveRight, "display-move-right"), (.displayMoveUp, "display-move-up"), (.displayMoveDown, "display-move-down"), - (.openSettings, "open-settings"), + (.openSettings, "open-settings"), (.pauseTiling, "pause-tiling"), (.quit, "quit"), ] } diff --git a/Tests/TesseraUITests/MiniMapTests.swift b/Tests/TesseraUITests/MiniMapTests.swift new file mode 100644 index 00000000..fab515ae --- /dev/null +++ b/Tests/TesseraUITests/MiniMapTests.swift @@ -0,0 +1,206 @@ +import AppKit +import Foundation +import TesseraAnimation +import TesseraConfig +import Testing + +@testable import TesseraUI + +struct MiniMapTests { + @Test(arguments: ConfigLayout.allCases, [0, 1, 3, 7]) + func accessibilityNamesLayoutAndCount(layout: ConfigLayout, count: Int) { + let snapshot = Self.snapshot(count: count, layout: layout) + let ending = count == 1 ? "1 window" : "\(count) windows" + #expect(snapshot.accessibilityDescription == "\(layout.uiTitle) layout, \(ending)") + } + + @Test(arguments: [0, 1, 6, 7, 99, 100]) + func iconFallback(count: Int) { + let snapshot = Self.snapshot(count: count) + let icon = MenuIcon(snapshot: snapshot, style: .minimap) + switch icon { + case .logo(let badge): + #expect(count == 0 || count > 6) + #expect(badge == (count > 6 ? count : nil)) + case .tiles(let tiles): + #expect((1...6).contains(count)) + #expect(tiles.count == count) + } + #expect(MenuIcon(snapshot: snapshot, style: .logo) == .logo(count: count > 6 ? count : nil)) + } + + @Test func geometryPreservesAspectOriginAndFocus() throws { + let snapshot = LayoutSnapshot( + layout: .columns, bounds: CGRect(x: -100, y: 50, width: 200, height: 100), + tiles: [ + LayoutTile(id: 4, frame: CGRect(x: -100, y: 50, width: 100, height: 100), isFocused: true), + LayoutTile(id: 5, frame: CGRect(x: 0, y: 50, width: 100, height: 100)), + ]) + guard case .tiles(let tiles) = MenuIcon(snapshot: snapshot, style: .minimap) else { + Issue.record("Expected tiles") + return + } + #expect(tiles.map(\.id) == [4, 5]) + #expect(abs(tiles[0].frame.minX - 2.5) < 1e-10) + #expect(abs(tiles[1].frame.minX - 9.5) < 1e-10) + for tile in tiles { + #expect(abs(tile.frame.minY - 6) < 1e-10) + #expect(abs(tile.frame.width - 6) < 1e-10) + #expect(abs(tile.frame.height - 6) < 1e-10) + } + #expect(tiles[0].isFocused) + #expect(!tiles[1].isFocused) + } + + @Test func clipsOffscreenGeometry() { + let snapshot = LayoutSnapshot( + layout: .grid, bounds: CGRect(x: 0, y: 0, width: 100, height: 100), + tiles: [ + LayoutTile(id: 1, frame: CGRect(x: -50, y: -20, width: 100, height: 100)), + LayoutTile(id: 2, frame: CGRect(x: 200, y: 200, width: 10, height: 10)), + ]) + guard case .tiles(let tiles) = MenuIcon(snapshot: snapshot, style: .minimap) else { + Issue.record("Expected tiles") + return + } + #expect(tiles.count == 1) + #expect(tiles[0].frame.minX >= 2) + #expect(tiles[0].frame.minY >= 2) + #expect(tiles[0].frame.maxX <= 16) + #expect(tiles[0].frame.maxY <= 16) + } + + @Test(arguments: ConfigMotionLevel.allCases, [0.1, 1.0, 4.0]) + func morphHasBoundedFrames(level: ConfigMotionLevel, speed: Double) { + let initial = MenuIcon(snapshot: Self.snapshot(count: 3), style: .minimap) + let destination = MenuIcon(snapshot: .preview, style: .minimap) + var morph = MiniMapMorph(icon: initial) + let changed = morph.retarget( + destination, configuration: MotionConfiguration(level: level, speed: speed), + reduceMotion: false, visible: true) + #expect(changed) + #expect(morph.remainingFrames == 10) + var frames = 0 + while morph.remainingFrames > 0 { + morph.advance() + frames += 1 + } + #expect(frames <= 10) + #expect(morph.current == destination) + #expect(morph.advance() == destination) + let unchanged = morph.retarget( + destination, configuration: MotionConfiguration(), reduceMotion: false, visible: true) + #expect(!unchanged) + } + + @Test(arguments: 0..<8) + func policySkipsMotion(flags: Int) { + let enabled = flags & 1 != 0 + let reduceMotion = flags & 2 != 0 + let visible = flags & 4 != 0 + let initial = MenuIcon(snapshot: Self.snapshot(count: 3), style: .minimap) + let destination = MenuIcon(snapshot: .preview, style: .minimap) + var morph = MiniMapMorph(icon: initial) + morph.retarget( + destination, configuration: MotionConfiguration(enabled: enabled), + reduceMotion: reduceMotion, visible: visible) + #expect((morph.remainingFrames > 0) == (enabled && !reduceMotion && visible)) + if morph.remainingFrames == 0 { #expect(morph.current == destination) } + } + + @Test func retargetStartsFromPresentationAndSettlesExactly() { + let initial = MenuIcon(snapshot: Self.snapshot(count: 3), style: .minimap) + let destination = MenuIcon(snapshot: .preview, style: .minimap) + var morph = MiniMapMorph(icon: initial) + morph.retarget(destination, configuration: MotionConfiguration(), reduceMotion: false, visible: true) + morph.advance() + let presentation = morph.current + #expect(presentation != initial) + #expect(presentation != destination) + morph.retarget(initial, configuration: MotionConfiguration(), reduceMotion: false, visible: true) + #expect(morph.current == presentation) + for _ in 0..<10 { morph.advance() } + #expect(morph.current == initial) + } + + @Test func disablingMotionFinishesCurrentMorph() { + var morph = MiniMapMorph(icon: MenuIcon(snapshot: Self.snapshot(count: 3), style: .minimap)) + let destination = MenuIcon(snapshot: .preview, style: .minimap) + morph.retarget(destination, configuration: MotionConfiguration(), reduceMotion: false, visible: true) + morph.advance() + morph.retarget( + destination, configuration: MotionConfiguration(enabled: false), reduceMotion: false, visible: true) + #expect(morph.remainingFrames == 0) + #expect(morph.current == destination) + } + + @Test func logoTransitionsAreInstant() { + var morph = MiniMapMorph(icon: MenuIcon(snapshot: .preview, style: .minimap)) + morph.retarget(.logo(count: 7), configuration: MotionConfiguration(), reduceMotion: false, visible: true) + #expect(morph.current == .logo(count: 7)) + #expect(morph.remainingFrames == 0) + } + + @Test func topologyChangesKeepIdentity() { + let initial = MenuIcon(snapshot: .preview, style: .minimap) + var morph = MiniMapMorph(icon: initial) + let destination = MenuIcon(snapshot: Self.snapshot(count: 2), style: .minimap) + morph.retarget(destination, configuration: MotionConfiguration(), reduceMotion: false, visible: true) + for _ in 0..<10 { morph.advance() } + #expect(morph.current == destination) + } + + static func snapshot(count: Int, layout: ConfigLayout = .columns) -> LayoutSnapshot { + let width = 1000.0 / Double(max(1, count)) + let tiles = (0.. 0.01 { + opaquePixels += 1 + #expect(color.redComponent < 0.01) + #expect(color.greenComponent < 0.01) + #expect(color.blueComponent < 0.01) + } else { + clearPixels += 1 + } + } + } + #expect(opaquePixels > 20) + #expect(clearPixels > 20) + } + + @Test func brandArtworkLoads() throws { + #expect(try BrandAssets.keystone().size == NSSize(width: 1024, height: 1024)) + #expect(try BrandAssets.split().isTemplate) + } + + @Test func increasedContrastChangesPixels() throws { + let renderer = try MenuIconRenderer() + let icon = MenuIcon(snapshot: .preview, style: .minimap) + #expect(try renderer.png(for: icon) != renderer.png(for: icon, increaseContrast: true)) + } +} diff --git a/Tests/TesseraUITests/SettingsTests.swift b/Tests/TesseraUITests/SettingsTests.swift new file mode 100644 index 00000000..1583f76b --- /dev/null +++ b/Tests/TesseraUITests/SettingsTests.swift @@ -0,0 +1,516 @@ +import AppKit +import Foundation +import SwiftUI +import TesseraAnimation +import TesseraConfig +import Testing + +@testable import TesseraUI + +@Suite(.timeLimit(.minutes(1))) +@MainActor +struct SettingsTests { + @Test func settingsRoundTripPreservesCommentsAndOtherSections() async throws { + let source = + "# 改善 café\r\n[general]\r\nlaunch-at-login = false # startup\r\n[layout]\r\nratio = 0.5 # balance\r\n[motion]\r\nlevel = 'playful' # keep\r\n" + try await withSettings(source: source) { model, file in + try await model.setValue(.float(0.65), for: .layout(.ratio)) + #expect(try file.read() == source.replacingOccurrences(of: "ratio = 0.5", with: "ratio = 0.65")) + #expect(model.configuration.layout.global.ratio == 0.65) + try await model.setValue(.bool(true), for: .launchAtLogin) + #expect(try file.read().contains("launch-at-login = true # startup\r\n") == true) + #expect(model.configuration.general.launchAtLogin) + #expect(model.error == nil) + } + } + + @Test func everyConfigurationControlWritesItsSchemaPath() async throws { + try await withSettings(source: "# Keep this\n") { model, file in + try await model.setValue(.bool(true), for: .launchAtLogin) + try await model.setValue(.string("cmd-fn"), for: .prefix) + try await model.setValue(.bool(true), for: .announceLayoutChanges) + try await model.setValue(.string("columns"), for: .layout(.defaultLayout)) + for field in SettingsLayoutField.allCases where field != .defaultLayout { + let value: TOMLValue = field == .windowCap ? .integer(12) : .float(field == .ratio ? 0.7 : 15) + try await model.setValue(value, for: .layout(field)) + } + try await model.setValue(.bool(false), for: .motion(.enabled)) + try await model.setValue(.string("extra"), for: .motion(.level)) + try await model.setValue(.float(2.5), for: .motion(.speed)) + try await model.setValue(.string("ghost"), for: .motion(.transitions)) + try await model.setValue(.bool(false), for: .motion(.focusBorder)) + try await model.setValue(.bool(true), for: .motion(.sound)) + try await model.setValue(.string("logo"), for: .motion(.menuBarIcon)) + let value = model.configuration + #expect(value.general == GeneralConfiguration(prefix: [.cmd, .fn], launchAtLogin: true)) + #expect(value.accessibility.announceLayoutChanges) + #expect( + value.layout.global + == LayoutValues( + defaultLayout: .columns, ratio: 0.7, gaps: LayoutGaps(inner: 15, outer: 15), + reserved: ReservedEdges(top: 15, right: 15, bottom: 15, left: 15), windowCap: 12)) + #expect( + value.motion + == MotionConfiguration( + enabled: false, level: .extra, speed: 2.5, transitions: .ghost, focusBorder: false, sound: true, + menuBarIcon: .logo)) + #expect(try file.read().contains("# Keep this")) + #expect(try SettingsDocumentEditor.validate(TOMLDocument(parsing: file.read())) == value) + } + } + + @Test func displayOverridesPreserveUUIDSpellingAndInheritance() async throws { + let key = "a1b2c3d4-1234-5678-9abc-0123456789ab" + let id = try #require(UUID(uuidString: key)) + let source = "[layout]\nratio=0.6\n[layout.displays.'\(key)'] # display\nwindow-cap=3\n" + try await withSettings(source: source) { model, file in + try await model.setValue(.float(12), for: .layout(.innerGap, display: id)) + #expect(model.configuration.layout.displays[id]?.gaps.inner == 12) + #expect(model.configuration.layout.displays[id]?.ratio == 0.6) + #expect(model.configuration.layout.global.gaps.inner == 8) + #expect(try file.read().contains("[layout.displays.'\(key)'] # display")) + let newID = UUID() + try await model.setValue(.string("rows"), for: .layout(.defaultLayout, display: newID)) + #expect(model.configuration.layout.displays[newID]?.defaultLayout == .rows) + #expect(model.configuration.layout.displays[newID]?.ratio == 0.6) + } + } + + @Test(arguments: [TOMLValue.float(-1), .float(.infinity), .float(.nan), .string("fast"), .float(5)]) + func invalidValuesNeverReachDisk(value: TOMLValue) async throws { + let source = "[motion]\nspeed = 1 # unchanged\n" + try await withSettings(source: source) { model, file in + await #expect(throws: SettingsFailure.self) { try await model.setValue(value, for: .motion(.speed)) } + #expect(try file.read() == source) + #expect(model.configuration.motion.speed == 1) + #expect(model.error != nil) + try await model.setValue(.float(2), for: .motion(.speed)) + #expect(model.error == nil) + } + } + + @Test func inheritedShortcutConflictIsRejectedAndClearDisablesRatherThanResets() async throws { + let source = "# bindings\n" + try await withSettings(source: source) { model, file in + let conflict = try #require(model.configuration.keybindings[.focusRight]) + await #expect(throws: SettingsFailure.self) { try await model.setShortcut(conflict, for: .focusLeft) } + #expect(try file.read() == source) + #expect(model.error?.message.contains(ConfigCommand.focusRight.rawValue) == true) + try await model.setShortcut(nil, for: .focusRight) + try await model.setShortcut(conflict, for: .focusLeft) + #expect(model.configuration.keybindings[.focusLeft] == conflict) + #expect(model.configuration.keybindings[.focusRight] == nil) + let document = try TOMLDocument(parsing: file.read()) + #expect(document.node(forKey: ["keybindings", "focus-right"])?.value == .bool(false)) + } + } + + @Test(arguments: ConfigCommand.allCases) + func everyCommandSupportsRecordingAndClearing(command: ConfigCommand) async throws { + try await withSettings(source: "") { model, file in + let chord = KeyChord(modifiers: [.cmd, .fn], key: .keypad9) + try await model.setShortcut(chord, for: command) + #expect(model.configuration.keybindings[command] == chord) + try await model.setShortcut(nil, for: command) + #expect(model.configuration.keybindings[command] == nil) + #expect( + try TOMLDocument(parsing: file.read()).node(forKey: ["keybindings", command.rawValue])?.value + == .bool(false)) + #expect(!command.settingsTitle.isEmpty) + } + } + + @Test func prefixEditsRespectAbsoluteOverridesAndValidateConflicts() async throws { + try await withSettings(source: "") { model, file in + try await model.setShortcut(KeyChord(modifiers: .cmd, key: .right), for: .focusLeft) + let original = try file.read() + await #expect(throws: SettingsFailure.self) { try await model.setValue(.string("cmd"), for: .prefix) } + #expect(try file.read() == original) + try await model.setValue(.string("fn"), for: .prefix) + #expect(model.configuration.keybindings[.focusLeft] == KeyChord(modifiers: .cmd, key: .right)) + #expect(model.configuration.keybindings[.focusRight] == KeyChord(modifiers: .fn, key: .right)) + } + } + + @Test func rapidEditsAreSerializedWithoutLosingIndependentChanges() async throws { + try await withSettings(source: "# sequence\n") { model, file in + let tasks = (1...25).map { index in + Task { @MainActor in + try await model.setValue(.integer(Int64(index)), for: .layout(.windowCap)) + try await model.setValue(.float(Double(index)), for: .layout(.innerGap)) + } + } + for task in tasks { try await task.value } + let document = try TOMLDocument(parsing: file.read()) + let value = try SettingsDocumentEditor.validate(document) + #expect(value == model.configuration) + #expect(value.layout.global.windowCap == 25) + #expect(value.layout.global.gaps.inner == 25) + #expect(try file.read().contains("# sequence")) + } + } + + @Test func invalidQueuedEditDoesNotPoisonLaterEdits() async throws { + try await withSettings(source: "") { model, _ in + let invalid = Task { try await model.setValue(.float(-1), for: .motion(.speed)) } + let valid = Task { try await model.setValue(.bool(true), for: .launchAtLogin) } + await #expect(throws: SettingsFailure.self) { try await invalid.value } + try await valid.value + #expect(model.configuration.general.launchAtLogin) + } + } + + @Test func missingInitialFileCanBeCreatedWithoutWritingDefaultsOverOtherFields() async throws { + try await withSettings(source: nil) { model, file in + #expect(!FileManager.default.fileExists(atPath: file.url.path)) + try await model.setValue(.bool(true), for: .launchAtLogin) + #expect(model.configuration.general.launchAtLogin) + #expect(try file.read().contains("launch-at-login")) + #expect(!model.diagnostics.contains { $0.severity == .error }) + } + } + + @Test func missingParentDirectoriesAreCreatedOnFirstSave() async throws { + let file = try SettingsFile() + defer { file.remove() } + let url = file.directory.appendingPathComponent("one/two/config.toml") + let model = SettingsModel(store: ConfigStore(fileURL: url)) + await model.start() + do { try await model.setValue(.bool(true), for: .launchAtLogin) } catch { + await model.stop() + throw error + } + await model.stop() + #expect(try String(contentsOf: url, encoding: .utf8).contains("launch-at-login")) + } + + @Test(arguments: ["[layout]\nratio=\n", "[motion]\nspeed=99\n"]) + func rejectedExternalChangesRemainUntouched(source: String) async throws { + try await withSettings(source: "[layout]\nratio=0.6\n") { model, file in + try file.write(source) + await #expect(throws: SettingsFailure.self) { try await model.setValue(.bool(true), for: .launchAtLogin) } + #expect(try file.read() == source) + #expect(model.configuration.layout.global.ratio == 0.6) + #expect(model.error != nil) + } + } + + @Test func initiallyInvalidFileIsNeverOverwrittenByLastGoodDefaults() async throws { + let source = "[motion]\nspeed=-1\n" + try await withSettings(source: source) { model, file async throws in + await #expect(throws: SettingsFailure.self) { try await model.setValue(.bool(true), for: .launchAtLogin) } + #expect(try file.read() == source) + #expect(model.error != nil) + } + } + + @Test func unobservedValidExternalEditCausesConflictAndRefresh() async throws { + try await withSettings(source: "[layout]\nratio=0.6\n") { model, file in + await model.store.stopWatching() + let external = "# External edit\n[layout]\nratio=0.7\n" + try file.write(external) + await #expect(throws: SettingsFailure.self) { try await model.setValue(.bool(true), for: .launchAtLogin) } + #expect(try file.read() == external) + #expect(model.configuration.layout.global.ratio == 0.7) + try await model.setValue(.bool(true), for: .launchAtLogin) + #expect(try file.read().contains("# External edit")) + #expect(model.configuration.layout.global.ratio == 0.7) + } + } + + @Test func fileReplacementBetweenValidationAndWriteIsNotOverwritten() throws { + let file = try SettingsFile() + defer { file.remove() } + let source = "[layout]\nratio=0.6\n" + let external = "# Just replaced\n[layout]\nratio=0.8\n" + try file.write(source) + #expect(throws: SettingsFailure.self) { + try SettingsFileEditor.commit( + .value(.launchAtLogin, .bool(true)), fileURL: file.url, expectedSource: source + ) { + try file.write(external) + } + } + #expect(try file.read() == external) + } + + @Test func fileCreatedBetweenValidationAndFirstWriteIsNotOverwritten() throws { + let file = try SettingsFile() + defer { file.remove() } + #expect(throws: SettingsFailure.self) { + try SettingsFileEditor.commit(.value(.launchAtLogin, .bool(true)), fileURL: file.url, expectedSource: nil) { + try file.write("# External creation\n") + } + } + #expect(try file.read() == "# External creation\n") + } + + @Test func deletingLoadedFileDoesNotRecreateIt() async throws { + try await withSettings(source: "# Keep\n") { model, file in + try FileManager.default.removeItem(at: file.url) + await #expect(throws: SettingsFailure.self) { try await model.setValue(.bool(true), for: .launchAtLogin) } + #expect(!FileManager.default.fileExists(atPath: file.url.path)) + } + } + + @Test func invalidUTF8AndDirectoriesAreNotOverwritten() async throws { + try await withSettings(source: "# Keep\n") { model, file in + let invalid = Data([0xFF, 0xFE]) + try invalid.write(to: file.url) + await #expect(throws: SettingsFailure.self) { try await model.setValue(.bool(true), for: .launchAtLogin) } + #expect(try Data(contentsOf: file.url) == invalid) + try FileManager.default.removeItem(at: file.url) + try FileManager.default.createDirectory(at: file.url, withIntermediateDirectories: false) + await #expect(throws: (any Error).self) { try await model.setValue(.bool(true), for: .launchAtLogin) } + #expect(model.error != nil) + } + } + + @Test func writesThroughSymlinkWithoutReplacingTheLink() async throws { + let file = try SettingsFile() + defer { file.remove() } + let target = file.directory.appendingPathComponent("target.toml") + try Data("# Target\n".utf8).write(to: target) + try FileManager.default.createSymbolicLink(at: file.url, withDestinationURL: target) + let model = SettingsModel(store: ConfigStore(fileURL: file.url)) + await model.start() + do { try await model.setValue(.bool(true), for: .launchAtLogin) } catch { + await model.stop() + throw error + } + await model.stop() + #expect(try file.url.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true) + #expect(try String(contentsOf: target, encoding: .utf8).contains("launch-at-login")) + } + + @Test func watcherUpdatesObservableStateRejectsInvalidAndRecovers() async throws { + try await withSettings(source: "[layout]\nratio=0.6\n") { model, file in + try file.write("[layout]\nratio=0.7\n") + try await eventually { model.configuration.layout.global.ratio == 0.7 } + try file.write("[layout]\nratio=bad\n") + try await eventually { model.error != nil } + #expect(model.configuration.layout.global.ratio == 0.7) + try file.write("[layout]\nratio=0.8\n") + try await eventually { model.configuration.layout.global.ratio == 0.8 && model.error == nil } + } + } + + @Test func lifecycleIsIdempotentAndDoesNotStopAnExistingStoreWatcher() async throws { + let file = try SettingsFile() + defer { file.remove() } + try file.write("") + let store = ConfigStore(fileURL: file.url) + try await store.startWatching() + let model = SettingsModel(store: store) + await model.start() + await model.start() + #expect(model.isStarted) + await model.stop() + await model.stop() + #expect(!model.isStarted) + #expect(await store.isWatching) + await store.stopWatching() + } + + @Test func stoppingOwnedWatcherPreventsUpdatesAndStartingAgainReloads() async throws { + try await withSettings(source: "") { model, file in + await model.stop() + #expect(await !model.store.isWatching) + try file.write("[motion]\nenabled=false\n") + #expect(model.configuration.motion.enabled) + await model.start() + #expect(!model.configuration.motion.enabled) + } + } + + @Test(arguments: [ + "[[float-rules]]\nbundle-id = 'org.example.notes' # app\nrole = 'AXDialog' # role\n", + "float-rules = [{bundle-id = 'org.example.notes', role = 'AXDialog'}] # rules\n", + ]) + func ruleEditingPreservesExistingComments(source: String) async throws { + try await withSettings(source: source) { model, file in + let original = try #require(model.configuration.floatRules.first) + let changed = FloatRule(bundleID: original.bundleID, titleRegex: "^Quick .*$", role: "AXSheet") + try await model.setRule(changed, at: 0, replacing: original) + #expect(model.configuration.floatRules == [changed]) + if source.contains("# app") { + #expect(try file.read().contains("# app")) + } else { + #expect(try file.read().contains("# rules")) + } + let withoutRole = FloatRule(bundleID: original.bundleID, titleRegex: changed.titleRegex) + try await model.setRule(withoutRole, at: 0, replacing: changed) + #expect(model.configuration.floatRules == [withoutRole]) + try await model.removeRule(at: 0, matching: withoutRole) + #expect(model.configuration.floatRules.isEmpty) + } + } + + @Test(arguments: [ + "# rules\n", "float-rules = [] # rules\n", "float-rules = [{role='AXDialog'} # rules\n]\n", + "float-rules = [{role='AXDialog'}, # rules\n]\n", + "[[float-rules]] # rules\nrole='AXDialog'\n[motion]\nenabled=false\n", + ]) + func rulesCanBeAddedToBothTOMLArrayForms(source: String) async throws { + try await withSettings(source: source) { model, file in + let previous = model.configuration.floatRules + let rule = FloatRule(titleRegex: "^Composer$", role: "AXDialog") + try await model.addRule(rule) + #expect(model.configuration.floatRules == previous + [rule]) + #expect(try file.read().contains("# rules")) + try await model.removeRule(at: previous.count, matching: rule) + #expect(model.configuration.floatRules == previous) + } + } + + @Test func removingMiddleRuleKeepsOtherRulesAndSections() async throws { + let source = + "# café\n[[float-rules]]\nrole='AXDialog' # first\n[[float-rules]] # second\nbundle-id='org.example.app' # matcher\n[[float-rules]]\nrole='AXSheet' # last\n[motion]\nenabled=false\n" + try await withSettings(source: source) { model, file in + let rules = model.configuration.floatRules + try await model.removeRule(at: 1, matching: rules[1]) + #expect(model.configuration.floatRules == [rules[0], rules[2]]) + #expect(!model.configuration.motion.enabled) + for comment in ["# café", "# first", "# second", "# matcher", "# last"] { + #expect(try file.read().contains(comment)) + } + } + } + + @Test func invalidAndStaleRulesNeverChangeTheFile() async throws { + try await withSettings(source: "[[float-rules]]\nrole='AXDialog'\n") { model, file in + let source = try file.read() + await #expect(throws: SettingsFailure.self) { try await model.addRule(FloatRule()) } + await #expect(throws: SettingsFailure.self) { try await model.addRule(FloatRule(titleRegex: "[")) } + await #expect(throws: SettingsFailure.self) { + try await model.removeRule(at: 0, matching: FloatRule(role: "AXSheet")) + } + #expect(try file.read() == source) + } + } + + @Test(arguments: ANSIKey.allCases) + func recorderUsesPhysicalANSIKeycodes(key: ANSIKey) throws { + let chord = try ShortcutRecorderParser.chord( + keyCode: key.keyCode, modifiers: [.control, .option, .command, .shift, .capsLock, .numericPad]) + #expect(chord.key == key) + #expect(chord.modifiers == [.ctrl, .alt, .cmd, .shift]) + #expect(try ShortcutRecorderParser.parse(chord.description) == chord) + } + + @Test func recorderRejectsUnknownKeysAndNormalizesAliases() throws { + #expect(throws: SettingsFailure.self) { try ShortcutRecorderParser.chord(keyCode: 0xFFFF, modifiers: []) } + #expect( + try ShortcutRecorderParser.parse("CONTROL-OPTION-SHIFT-?") + == KeyChord(modifiers: [.ctrl, .alt, .shift], key: .slash)) + #expect(try ShortcutRecorderParser.parse("cmd--") == KeyChord(modifiers: .cmd, key: .minus)) + #expect( + try ShortcutRecorderParser.chord(keyCode: ANSIKey.left.keyCode, modifiers: [.control, .function]).modifiers + == .ctrl) + #expect(try ShortcutRecorderParser.chord(keyCode: ANSIKey.a.keyCode, modifiers: [.function]).modifiers == .fn) + for input in ["", "ctrl", "ctrl-ctrl-a", "cmd-unknown-key"] { + #expect(throws: KeyChordParseError.self) { try ShortcutRecorderParser.parse(input) } + } + } + + @Test func canceledEditsDoNotWrite() async throws { + try await withSettings(source: "# unchanged\n") { model, file async throws in + let task = Task { try await model.setValue(.bool(true), for: .launchAtLogin) } + task.cancel() + await #expect(throws: CancellationError.self) { try await task.value } + #expect(try file.read() == "# unchanged\n") + } + } + + @Test func numericInputUsesRegionalDecimalsAndRejectsPartialParsing() throws { + let english = Locale(identifier: "en_US") + let german = Locale(identifier: "de_DE") + #expect(try SettingsNumberParser.number("1.25", locale: english) == 1.25) + #expect(try SettingsNumberParser.number("1,25", locale: german) == 1.25) + #expect(try SettingsNumberParser.integer("١٢", locale: english) == 12) + for value in ["1oops", "nan", "inf", "1,250", "1.2.3", "", "-", ".", "1e999"] { + #expect(throws: SettingsFailure.self) { try SettingsNumberParser.number(value, locale: english) } + } + #expect(throws: SettingsFailure.self) { try SettingsNumberParser.integer("1.5", locale: english) } + #expect( + try ShortcutRecorderParser.chord( + keyCode: ANSIKey.left.keyCode, modifiers: [.function], functionKeyPressed: true + ).modifiers == .fn) + } + + @Test func previewUsesTokensAndAccessibilityPolicies() { + let motion = MotionConfiguration(level: .extra, speed: 2) + let policy = SettingsPreviewPolicy( + motion: motion, reduceMotion: false, reduceTransparency: false, increaseContrast: false) + #expect(policy.spec == MotionToken.shuffle.spec(settings: MotionSettings(level: .extra, speedMultiplier: 2))) + #expect( + SettingsPreviewPolicy( + motion: motion, reduceMotion: true, reduceTransparency: false, increaseContrast: false + ).spec == nil) + #expect( + SettingsPreviewPolicy( + motion: MotionConfiguration(enabled: false), reduceMotion: false, reduceTransparency: false, + increaseContrast: false + ).spec == nil) + #expect( + SettingsPreviewPolicy( + motion: MotionConfiguration(transitions: .snap), reduceMotion: false, reduceTransparency: false, + increaseContrast: false + ).spec == nil) + let opaque = SettingsPreviewPolicy( + motion: MotionConfiguration(transitions: .ghost), reduceMotion: false, reduceTransparency: true, + increaseContrast: true) + #expect(!opaque.ghost) + #expect(opaque.borderWidth == 3) + #expect(opaque.spec?.curve != .fade) + } + + @Test func interpolatedSettingsStringsAreLocalized() { + #expect(SettingsText.string("Edit shortcut for \("Focus left")") == "Edit shortcut for Focus left") + #expect(SettingsText.string("Save \("Ratio")") == "Save Ratio") + } +} + +private struct SettingsFile: Sendable { + let directory: URL + var url: URL { directory.appendingPathComponent("tessera.toml") } + + init() throws { + directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + + func write(_ source: String) throws { try Data(source.utf8).write(to: url, options: .atomic) } + func read() throws -> String { try String(contentsOf: url, encoding: .utf8) } + + func remove() { + do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } + } +} + +@MainActor +private func withSettings(source: String?, body: @MainActor (SettingsModel, SettingsFile) async throws -> Void) + async throws +{ + let file = try SettingsFile() + defer { file.remove() } + if let source { try file.write(source) } + let model = SettingsModel(store: ConfigStore(fileURL: file.url)) + await model.start() + do { try await body(model, file) } catch { + await model.stop() + throw error + } + await model.stop() +} + +@MainActor +private func eventually(_ predicate: @MainActor () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(5)) + while !predicate() { + guard ContinuousClock.now < deadline else { throw SettingsTestError.timedOut } + try await Task.sleep(for: .milliseconds(10)) + } +} + +private enum SettingsTestError: Error { case timedOut } diff --git a/Tests/TesseraUITests/ShellTests.swift b/Tests/TesseraUITests/ShellTests.swift new file mode 100644 index 00000000..9e77f6ba --- /dev/null +++ b/Tests/TesseraUITests/ShellTests.swift @@ -0,0 +1,158 @@ +import AppKit +import Foundation +import TesseraConfig +import Testing + +@testable import TesseraUI + +@MainActor +struct OnboardingTests { + @Test func permissionFlow() async throws { + let provider = PreviewShellServices() + let model = OnboardingModel(provider: provider) + #expect(model.state == .checking) + #expect(!model.complete()) + model.receive(.missing) + #expect(model.state == .needsPermission) + model.openSettings() + #expect(model.state == .waiting) + #expect(provider.settingsOpenCount == 1) + model.receive(.missing) + #expect(model.state == .waiting) + await model.refresh() + #expect(provider.refreshCount == 1) + model.receive(.granted) + #expect(model.state == .ready) + #expect(model.celebrationCount == 1) + model.receive(.granted) + #expect(model.celebrationCount == 1) + #expect(model.complete()) + #expect(model.state == .complete) + model.receive(.granted) + #expect(model.state == .complete) + model.receive(.missing) + #expect(model.state == .needsPermission) + #expect(!model.complete()) + } + + @Test func initiallyGrantedDoesNotCelebrate() { + let model = OnboardingModel(provider: PreviewShellServices(permission: .granted)) + model.receive(.granted) + #expect(model.state == .ready) + #expect(model.celebrationCount == 0) + } + + @Test func openingFailureIsVisibleAndDoesNotAdvance() { + let model = OnboardingModel(provider: FailingPermissionProvider()) + model.receive(.missing) + model.openSettings() + #expect(model.error == "Settings unavailable") + #expect(model.state == .needsPermission) + } + + @Test func streamsReplayAndKeepNewestValue() async throws { + let provider = PreviewShellServices() + var layouts = provider.snapshots().makeAsyncIterator() + #expect(await layouts.next() == .preview) + provider.publish(MiniMapTests.snapshot(count: 1)) + provider.publish(MiniMapTests.snapshot(count: 2)) + #expect(await layouts.next() == MiniMapTests.snapshot(count: 2)) + var permissions = provider.permissionUpdates().makeAsyncIterator() + #expect(await permissions.next() == .missing) + provider.publish(permission: .granted) + #expect(await permissions.next() == .granted) + try await provider.send(.retile) + #expect(provider.commands == [.retile]) + } +} + +@MainActor +private final class FailingPermissionProvider: PermissionStatusProviding { + struct Failure: LocalizedError { var errorDescription: String? { "Settings unavailable" } } + func permissionUpdates() -> AsyncStream { + AsyncStream { + $0.yield(.missing) + $0.finish() + } + } + func refreshPermission() async {} + func openAccessibilitySettings() throws { throw Failure() } +} + +@MainActor +@Suite(.serialized) +struct MenuTests { + @Test func menuUsesConfigShortcutsAndStates() throws { + _ = NSApplication.shared + var commands: [ConfigCommand] = [] + let controller = try MenuBarController { commands.append($0) } + defer { controller.stop() } + var configuration = TesseraConfiguration.defaults + configuration.keybindings[.quit] = try KeyChord(parsing: "cmd-shift-q") + configuration.keybindings[.retile] = nil + let snapshot = LayoutSnapshot( + layout: .side, bounds: LayoutSnapshot.preview.bounds, + tiles: LayoutSnapshot.preview.tiles, isPaused: true) + controller.update( + snapshot: snapshot, configuration: configuration, permission: .missing, + reduceMotion: true, increaseContrast: true) + #expect(controller.statusItem.length == NSStatusItem.squareLength) + #expect(controller.statusItem.button?.accessibilityLabel() == "Tessera") + #expect(controller.statusItem.button?.accessibilityValue() as? String == "Side layout, 3 windows") + #expect(controller.statusItem.button?.image?.isTemplate == true) + #expect(controller.statusItem.menu === controller.menu) + let items = controller.menu.items.compactMap { $0 as? CommandMenuItem } + let quit = try #require(items.first { $0.command == .quit }) + #expect(quit.keyEquivalent == "q") + #expect(quit.keyEquivalentModifierMask == [.command, .shift]) + #expect(items.first { $0.command == .retile }?.keyEquivalent == "") + #expect(items.first { $0.command == .pauseTiling }?.state == .on) + #expect(controller.menu.items.contains { $0.title == "Accessibility access is needed" && !$0.isEnabled }) + let layoutItems = try #require(controller.menu.items.first { $0.submenu != nil }?.submenu?.items) + #expect(layoutItems.count == ConfigLayout.allCases.count) + #expect(layoutItems.filter { $0.state == .on }.map(\.title) == ["Side"]) + quit.invoke(quit.command) + #expect(commands == [.quit]) + } + + @Test func grantedPermissionHidesWarning() throws { + _ = NSApplication.shared + let controller = try MenuBarController { _ in } + defer { controller.stop() } + controller.update( + snapshot: .preview, configuration: .defaults, permission: .granted, + reduceMotion: true, increaseContrast: false) + #expect(!controller.menu.items.contains { $0.title == "Accessibility access is needed" }) + } + + @Test(arguments: ANSIKey.allCases) + func everyKeyHasAMenuRepresentation(key: ANSIKey) { + let shortcut = MenuShortcut(KeyChord(modifiers: .hyper, key: key)) + #expect(shortcut.keyEquivalent.count == 1) + #expect(shortcut.modifierMask.contains([.control, .option, .command, .shift])) + } + + @Test func clearedShortcutHasNoImplicitCommandModifier() { + #expect(MenuShortcut(nil).keyEquivalent.isEmpty) + #expect(MenuShortcut(nil).modifierMask.isEmpty) + } + + @Test func routesPhysicalKeysAndNormalizesNavigationFlags() throws { + let routing = MenuRouting() + var commands: [ConfigCommand] = [] + routing.bindings = [ + .focusLeft: try KeyChord(parsing: "ctrl-alt-left"), .retile: try KeyChord(parsing: "cmd-r"), + ] + routing.invoke = { commands.append($0) } + #expect(routing.perform(keyCode: ANSIKey.left.keyCode, flags: [.control, .option, .function, .numericPad])) + #expect(routing.perform(keyCode: ANSIKey.r.keyCode, flags: .command)) + #expect(!routing.perform(keyCode: ANSIKey.q.keyCode, flags: .command)) + #expect(commands == [.focusLeft, .retile]) + } + + @Test func localizedResourceTableIsBundled() { + #expect(UIStrings.text("Settings…") == "Settings…") + #expect(UIResourceError.renderingFailed.errorDescription == "The menu icon could not be rendered.") + #expect(UIResourceError.missingBrand("Split").errorDescription == "The Split artwork could not be loaded.") + } +} -- knotmirror 0.0.1 From 31737723cce95c303f32c3f3a1f6137b0041b99a Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:29:55 -0400 Subject: [PATCH 36/44] Keep executable product paths distinct --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index f5f78d58..f7b39f99 100644 --- a/Package.swift +++ b/Package.swift @@ -11,7 +11,7 @@ let package = Package( defaultLocalization: "en", platforms: [.macOS(.v15)], products: [ - .executable(name: "Tessera", targets: ["TesseraApp"]), + .executable(name: "TesseraApp", targets: ["TesseraApp"]), .executable(name: "tessera", targets: ["tessera"]), ], dependencies: [ -- knotmirror 0.0.1 From 3edd3178008bad49895b3a00ccc15a7db0396634 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:29:55 -0400 Subject: [PATCH 37/44] Keep focus during repeated window observations --- Sources/TesseraCore/Events.swift | 7 +-- Sources/TesseraCore/TileTree.swift | 9 ++-- Tests/TesseraCoreTests/RegressionTests.swift | 48 ++++++++++++++++++++ 3 files changed, 55 insertions(+), 9 deletions(-) diff --git a/Sources/TesseraCore/Events.swift b/Sources/TesseraCore/Events.swift index fa856318..e7452c4c 100644 --- a/Sources/TesseraCore/Events.swift +++ b/Sources/TesseraCore/Events.swift @@ -38,14 +38,11 @@ extension State { if window.isFloating || !isActive(key) { frames[window.id] = frame } if workspaces[key] == nil { workspaces[key] = Workspace(key: key) } guard var workspace = workspaces[key] else { return } + let rememberedFocus = workspace.focus if previous?.isFloating != window.isFloating { workspace.tree = workspace.tree?.removing(window.id) } - if workspace.order.contains(window.id) && !window.isFloating - && workspace.tree?.windows.contains(window.id) != true - { - workspace.order.removeAll { $0 == window.id } - } workspace.insert( window.id, floating: window.isFloating, in: displays[key.display]?.frame ?? frame, windows: windows) + if existing == key, let rememberedFocus { workspace.select(rememberedFocus) } workspaces[key] = workspace if isActive(key) && (previous == nil || existing != key) { focus(window.id, effects: &effects) } } diff --git a/Sources/TesseraCore/TileTree.swift b/Sources/TesseraCore/TileTree.swift index 6920c292..35c46e69 100644 --- a/Sources/TesseraCore/TileTree.swift +++ b/Sources/TesseraCore/TileTree.swift @@ -153,10 +153,11 @@ public struct Workspace: Sendable, Equatable, Codable { } mutating func insert(_ window: WindowID, floating: Bool, in frame: Rect, windows: [WindowID: ManagedWindow]) { - guard !order.contains(window) else { return } - order.append(window) - focus = window - guard !floating else { return } + if !order.contains(window) { + order.append(window) + focus = window + } + guard !floating, tree?.windows.contains(window) != true else { return } guard let current = tree, let newest = current.stacks.last else { tree = .tile(WindowStack(window)) return diff --git a/Tests/TesseraCoreTests/RegressionTests.swift b/Tests/TesseraCoreTests/RegressionTests.swift index 634f7ba7..867f814e 100644 --- a/Tests/TesseraCoreTests/RegressionTests.swift +++ b/Tests/TesseraCoreTests/RegressionTests.swift @@ -147,6 +147,54 @@ func decodedInvalidCapIsRejected(cap: Int) throws { #expect(result.1 == [.report(.unsupportedMinimumVersion(2))]) } +@Test(arguments: [false, true]) +func duplicateFloatingStatusUpdatePreservesOrderAndRememberedFocus(active: Bool) throws { + var state = focused(1, in: populated(3, cap: 2)) + if !active { + state = reduce(state, .activeSpaceChanged(display: primaryDisplay, space: secondarySpace)).0 + } + let originalOrder = try #require(state.workspaces[primaryKey]?.order) + for floating in [true, false] { + let result = reduce( + state, + .windowAppeared( + managed(2, floating: floating), workspace: primaryKey, + frame: state.frames[windowID(2)] ?? Rect())) + #expect(result.0.workspaces[primaryKey]?.order == originalOrder) + #expect(result.0.workspaces[primaryKey]?.focus == windowID(1)) + #expect(result.0.focusedWindow == state.focusedWindow) + #expect(!result.1.contains(.focusWindow(windowID(2)))) + state = result.0 + } + if !active { + let returned = reduce(state, .activeSpaceChanged(display: primaryDisplay, space: primarySpace)) + #expect(returned.0.focusedWindow == windowID(1)) + } +} + +@Test func backgroundRetilingAtCapDoesNotHideFocusedStackMember() { + var state = focused(3, in: populated(3, cap: 1)) + state = + reduce( + state, .windowAppeared(managed(1, floating: true), workspace: primaryKey, frame: testScreen) + ).0 + let result = reduce(state, .windowAppeared(managed(1), workspace: primaryKey, frame: testScreen)) + #expect(result.0.focusedWindow == windowID(3)) + #expect(result.0.workspaces[primaryKey]?.focus == windowID(3)) + #expect(result.0.visibleWindows == [windowID(3)]) + #expect(result.0.workspaces[primaryKey]?.order == (1...3).map(windowID)) + #expect(result.1.contains(.raiseWindow(windowID(3)))) +} + +@Test func duplicateRetilingOfFocusedWindowKeepsItsSelection() { + var state = command(.toggleFloat, in: focused(1, in: populated(3, cap: 1))).0 + let order = state.workspaces[primaryKey]?.order + state = reduce(state, .windowAppeared(managed(1), workspace: primaryKey, frame: testScreen)).0 + #expect(state.workspaces[primaryKey]?.order == order) + #expect(state.workspaces[primaryKey]?.focus == windowID(1)) + #expect(state.visibleWindows == [windowID(1)]) +} + @Test func futureReplaySchemaIsRejectedBeforeUnknownEventShape() { #expect(throws: EventStreamError.unsupportedVersion(line: 1, version: 9)) { try EventStream.decode("{\"version\":9,\"event\":{\"futureEvent\":{}}}") -- knotmirror 0.0.1 From 68e99818fdb4b4e021bafdfb40825ca28a4e528e Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:30:45 -0400 Subject: [PATCH 38/44] Cover shell lifecycle and idle rendering --- .../TesseraUI/Settings/SettingsModel.swift | 7 ++ Tests/TesseraUITests/SettingsTests.swift | 11 ++ .../TesseraUITests/ShellRegressionTests.swift | 113 ++++++++++++++++++ 3 files changed, 131 insertions(+) create mode 100644 Tests/TesseraUITests/ShellRegressionTests.swift diff --git a/Sources/TesseraUI/Settings/SettingsModel.swift b/Sources/TesseraUI/Settings/SettingsModel.swift index 34237719..08c106e7 100644 --- a/Sources/TesseraUI/Settings/SettingsModel.swift +++ b/Sources/TesseraUI/Settings/SettingsModel.swift @@ -135,6 +135,13 @@ public final class SettingsModel { defer { release() } receive(await store.reload()) editingError = nil + if isStarted, await !store.isWatching { + do { + try await store.startWatching() + } catch { + loadingError = SettingsFailure(error: error) + } + } } public func setValue(_ value: TOMLValue, for field: SettingsField) async throws { diff --git a/Tests/TesseraUITests/SettingsTests.swift b/Tests/TesseraUITests/SettingsTests.swift index 1583f76b..5fbb8152 100644 --- a/Tests/TesseraUITests/SettingsTests.swift +++ b/Tests/TesseraUITests/SettingsTests.swift @@ -312,6 +312,17 @@ struct SettingsTests { await store.stopWatching() } + @Test func reloadingRestartsAStoppedWatcher() async throws { + try await withSettings(source: "") { model, file in + await model.store.stopWatching() + #expect(await !model.store.isWatching) + await model.reload() + #expect(await model.store.isWatching) + try file.write("[motion]\nenabled=false\n") + try await eventually { !model.configuration.motion.enabled } + } + } + @Test func stoppingOwnedWatcherPreventsUpdatesAndStartingAgainReloads() async throws { try await withSettings(source: "") { model, file in await model.stop() diff --git a/Tests/TesseraUITests/ShellRegressionTests.swift b/Tests/TesseraUITests/ShellRegressionTests.swift new file mode 100644 index 00000000..5031603b --- /dev/null +++ b/Tests/TesseraUITests/ShellRegressionTests.swift @@ -0,0 +1,113 @@ +import AppKit +import Foundation +import TesseraConfig +import Testing + +@testable import TesseraUI + +@MainActor +@Suite(.serialized) +struct ShellRegressionTests { + @Test func unchangedMenuUpdateDoesNoRenderingOrRebuilding() throws { + _ = NSApplication.shared + let controller = try MenuBarController { _ in } + defer { controller.stop() } + controller.update( + snapshot: .preview, configuration: .defaults, permission: .granted, + reduceMotion: true, increaseContrast: false) + let image = controller.statusItem.button?.image + let menu = controller.menu + controller.update( + snapshot: .preview, configuration: .defaults, permission: .granted, + reduceMotion: true, increaseContrast: false) + #expect(controller.statusItem.button?.image === image) + #expect(controller.menu === menu) + } + + @Test func finishStopsAllRemainingFrames() { + var morph = MiniMapMorph(icon: MenuIcon(snapshot: .preview, style: .minimap)) + let target = MenuIcon(snapshot: MiniMapTests.snapshot(count: 3), style: .minimap) + morph.retarget(target, configuration: MotionConfiguration(), reduceMotion: false, visible: true) + morph.advance() + #expect(morph.remainingFrames > 0) + morph.finish() + #expect(morph.current == target) + #expect(morph.remainingFrames == 0) + #expect(morph.advance() == target) + } + + @Test(arguments: ConfigLayout.allCases, [0, 1, 3, 6]) + func previewCommandsPublishMatchingGeometry(layout: ConfigLayout, count: Int) async throws { + let original = MiniMapTests.snapshot(count: count) + let services = PreviewShellServices(snapshot: original) + var stream = services.snapshots().makeAsyncIterator() + #expect(await stream.next() == original) + try await services.send(layout.command) + // A fresh subscription observes the current value even when the command was an unchanged layout. + var current = services.snapshots().makeAsyncIterator() + let snapshot = try #require(await current.next()) + #expect(snapshot.layout == layout) + #expect(snapshot.tiles.count == count) + #expect(snapshot.tiles.map(\.id) == original.tiles.map(\.id)) + #expect(snapshot.tiles.allSatisfy { snapshot.bounds.contains($0.frame) }) + try await services.send(.pauseTiling) + var paused = services.snapshots().makeAsyncIterator() + #expect(await paused.next()?.isPaused == true) + try await services.send(.pauseTiling) + #expect(await paused.next()?.isPaused == false) + } + + @Test func shellLifecycleReleasesItsWatcherAndCanRestart() async throws { + _ = NSApplication.shared + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + defer { + do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } + } + let suiteName = "TesseraUITests.\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defaults.set(true, forKey: "onboardingCompleted") + defer { defaults.removePersistentDomain(forName: suiteName) } + let url = directory.appendingPathComponent("tessera.toml") + try "[motion]\nenabled = false\n".write(to: url, atomically: true, encoding: .utf8) + let store = ConfigStore(fileURL: url) + let services = PreviewShellServices(permission: .granted) + let shell = TesseraShell( + layouts: services, permissions: services, commands: services, + configStore: store, defaults: defaults) + for _ in 0..<2 { + try await shell.start() + try await shell.start() + #expect(shell.settings.isStarted) + #expect(await store.isWatching) + let deadline = ContinuousClock.now.advanced(by: .seconds(2)) + while shell.menuBar?.statusItem.button?.accessibilityValue() as? String != "Side layout, 3 windows", + ContinuousClock.now < deadline + { + await Task.yield() + } + #expect(shell.menuBar?.statusItem.button?.accessibilityValue() as? String == "Side layout, 3 windows") + await shell.stop() + await shell.stop() + #expect(shell.menuBar == nil) + #expect(!shell.settings.isStarted) + #expect(await !store.isWatching) + } + } + + @Test func exportsInspectableIconSnapshots() throws { + let renderer = try MenuIconRenderer() + let icons: [(String, MenuIcon)] = [ + ("minimap", MenuIcon(snapshot: .preview, style: .minimap)), + ("logo", .logo(count: nil)), + ("count", .logo(count: 12)), + ] + for (name, icon) in icons { + let png = try renderer.png(for: icon, scale: 4) + #expect(png.count > 100) + if let directory = ProcessInfo.processInfo.environment["TESSERA_UI_SNAPSHOTS"] { + try png.write(to: URL(fileURLWithPath: directory).appendingPathComponent("\(name).png")) + } + } + } +} -- knotmirror 0.0.1 From b62a6ca36f3ea9bf0a82a16479f1bbe60b0c24a4 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:38:11 -0400 Subject: [PATCH 39/44] Preserve insertion areas and side layout --- Sources/TesseraCore/Commands.swift | 3 +- Sources/TesseraCore/Decoding.swift | 2 +- Sources/TesseraCore/Events.swift | 2 +- Sources/TesseraCore/LayoutEngine.swift | 78 ++++--- .../TesseraCore.docc/TesseraCore.md | 16 +- Sources/TesseraCore/TileTree.swift | 48 +++-- .../LayoutInsertionTests.swift | 201 ++++++++++++++++++ 7 files changed, 300 insertions(+), 50 deletions(-) create mode 100644 Tests/TesseraCoreTests/LayoutInsertionTests.swift diff --git a/Sources/TesseraCore/Commands.swift b/Sources/TesseraCore/Commands.swift index 36f8a05f..0fcae35c 100644 --- a/Sources/TesseraCore/Commands.swift +++ b/Sources/TesseraCore/Commands.swift @@ -141,8 +141,7 @@ extension State { workspaces[key]?.insert( window, floating: false, in: displays[key.display]?.frame ?? Rect(), windows: windows) } else { - let remaining = workspaces[key]?.tree?.removing(window) - workspaces[key]?.tree = remaining + workspaces[key]?.removeTile(window) } effects.append(.announce(.floatingChanged(window, isFloating: !wasFloating))) } diff --git a/Sources/TesseraCore/Decoding.swift b/Sources/TesseraCore/Decoding.swift index a78ad3ca..7b4b5689 100644 --- a/Sources/TesseraCore/Decoding.swift +++ b/Sources/TesseraCore/Decoding.swift @@ -2,7 +2,7 @@ extension TileTree { var isValid: Bool { switch self { case .tile: true - case .split(_, let fraction, let first, let second): + case .split(_, let fraction, let first, let second), .partition(_, let fraction, let first, let second): fraction.isFinite && (0...1).contains(fraction) && first.isValid && second.isValid && Set(windows).count == windows.count } diff --git a/Sources/TesseraCore/Events.swift b/Sources/TesseraCore/Events.swift index e7452c4c..45e60c03 100644 --- a/Sources/TesseraCore/Events.swift +++ b/Sources/TesseraCore/Events.swift @@ -39,7 +39,7 @@ extension State { if workspaces[key] == nil { workspaces[key] = Workspace(key: key) } guard var workspace = workspaces[key] else { return } let rememberedFocus = workspace.focus - if previous?.isFloating != window.isFloating { workspace.tree = workspace.tree?.removing(window.id) } + if previous?.isFloating != window.isFloating { workspace.removeTile(window.id) } workspace.insert( window.id, floating: window.isFloating, in: displays[key.display]?.frame ?? frame, windows: windows) if existing == key, let rememberedFocus { workspace.select(rememberedFocus) } diff --git a/Sources/TesseraCore/LayoutEngine.swift b/Sources/TesseraCore/LayoutEngine.swift index 54ff2f9d..a28dbeba 100644 --- a/Sources/TesseraCore/LayoutEngine.swift +++ b/Sources/TesseraCore/LayoutEngine.swift @@ -13,30 +13,51 @@ public struct LayoutResult: Sendable, Equatable, Codable { public enum LayoutEngine { public static func arrange( _ workspace: Workspace, in screen: Rect, windows: [WindowID: ManagedWindow] = [:] + ) -> LayoutResult { + var result = arrangeUnrounded(workspace, in: screen, windows: windows) + result.frames = result.frames.mapValues { $0.roundedToWholePoints() } + result.cannotFit = result.frames.keys.sorted().filter { window in + guard let frame = result.frames[window], let minimum = windows[window]?.minimumSize else { return false } + return frame.size.width < minimum.width || frame.size.height < minimum.height + } + return result + } + + static func arrangeUnrounded( + _ workspace: Workspace, in screen: Rect, windows: [WindowID: ManagedWindow] ) -> LayoutResult { guard let tree = workspace.tree else { return LayoutResult() } let area = screen.inset(by: workspace.reservedEdges).inset(by: workspace.gaps.outer) - let horizontalDividers = dividers(tree, axis: .horizontal) - let verticalDividers = dividers(tree, axis: .vertical) + let horizontalDividers = balancingDividers(tree, axis: .horizontal) + let verticalDividers = balancingDividers(tree, axis: .vertical) var gap = max(0, workspace.gaps.inner) if horizontalDividers > 0 { gap = min(gap, area.size.width / Double(horizontalDividers)) } if verticalDividers > 0 { gap = min(gap, area.size.height / Double(verticalDividers)) } var result = LayoutResult(visibleWindows: tree.visibleWindows) place(tree, in: area, gap: gap, windows: windows, result: &result) - result.cannotFit.sort() return result } private static func dividers(_ tree: TileTree, axis: Axis) -> Int { switch tree { case .tile: return 0 - case .split(let splitAxis, _, let first, let second): + case .split(let splitAxis, _, let first, let second), .partition(let splitAxis, _, let first, let second): let left = dividers(first, axis: axis) let right = dividers(second, axis: axis) return splitAxis == axis ? left + right + 1 : max(left, right) } } + private static func balancingDividers(_ tree: TileTree, axis: Axis) -> Int { + switch tree { + case .tile, .partition: return 0 + case .split(let splitAxis, _, let first, let second): + let left = balancingDividers(first, axis: axis) + let right = balancingDividers(second, axis: axis) + return splitAxis == axis ? left + right + 1 : max(left, right) + } + } + private static func minimum(_ tree: TileTree, gap: Double, windows: [WindowID: ManagedWindow]) -> Size { switch tree { case .tile(let stack): @@ -47,12 +68,15 @@ public enum LayoutEngine { height: max(size.height, learned.height.rounded(.up)) ) } - case .split(let axis, _, let first, let second): + case .split(let axis, _, let first, let second), .partition(let axis, _, let first, let second): let left = minimum(first, gap: gap, windows: windows) let right = minimum(second, gap: gap, windows: windows) - return axis == .horizontal - ? Size(width: left.width + gap + right.width, height: max(left.height, right.height)) - : Size(width: max(left.width, right.width), height: left.height + gap + right.height) + if axis == .horizontal { + let reservedGap = left.width > 0 || right.width > 0 ? gap : 0 + return Size(width: left.width + reservedGap + right.width, height: max(left.height, right.height)) + } + let reservedGap = left.height > 0 || right.height > 0 ? gap : 0 + return Size(width: max(left.width, right.width), height: left.height + reservedGap + right.height) } } @@ -61,35 +85,37 @@ public enum LayoutEngine { ) { switch tree { case .tile(let stack): - let frame = area.roundedToWholePoints() - for window in stack.windows { - result.frames[window] = frame - if let size = windows[window]?.minimumSize, - frame.size.width < size.width || frame.size.height < size.height - { - result.cannotFit.append(window) - } - } - case .split(let axis, let fraction, let first, let second): + for window in stack.windows { result.frames[window] = area } + case .split(let axis, let fraction, let first, let second), + .partition(let axis, let fraction, let first, let second): let extent = axis == .horizontal ? area.size.width : area.size.height - let localGap = min(gap, extent / Double(dividers(tree, axis: axis))) + let localGap = min(gap, extent / Double(max(1, balancingDividers(tree, axis: axis)))) let available = max(0, extent - localGap) let firstMinimum = minimum(first, gap: localGap, windows: windows) let secondMinimum = minimum(second, gap: localGap, windows: windows) let lower = axis == .horizontal ? firstMinimum.width : firstMinimum.height let upper = axis == .horizontal ? secondMinimum.width : secondMinimum.height - let firstGaps = Double(dividers(first, axis: axis)) * localGap - let secondGaps = Double(dividers(second, axis: axis)) * localGap + let balancesContent: Bool + if case .split = tree { balancesContent = true } else { balancesContent = false } + let firstGaps = balancesContent ? Double(balancingDividers(first, axis: axis)) * localGap : 0 + let secondGaps = balancesContent ? Double(balancingDividers(second, axis: axis)) * localGap : 0 let desired = max(0, available - firstGaps - secondGaps) * min(1, max(0, fraction)) + firstGaps let length: Double if lower + upper <= available { length = min(available - upper, max(lower, desired)) } else { - // Keep every tile on-screen when constraints conflict; report the shortfall below. - let content = max(0, available - firstGaps - secondGaps) - let firstContent = max(0, lower - firstGaps) - let totalContent = firstContent + max(0, upper - secondGaps) - length = firstGaps + (totalContent > 0 ? content * firstContent / totalContent : 0) + // Conflicting minimums must not push any tile off-screen. + let firstGapBudget = Double(dividers(first, axis: axis)) * localGap + let secondGapBudget = Double(dividers(second, axis: axis)) * localGap + let gapScale = + firstGapBudget + secondGapBudget > 0 + ? min(1, available / (firstGapBudget + secondGapBudget)) : 1 + let requiredFirstGaps = firstGapBudget * gapScale + let requiredSecondGaps = secondGapBudget * gapScale + let content = max(0, available - requiredFirstGaps - requiredSecondGaps) + let firstContent = max(0, lower - requiredFirstGaps) + let totalContent = firstContent + max(0, upper - requiredSecondGaps) + length = requiredFirstGaps + (totalContent > 0 ? content * firstContent / totalContent : 0) } let left: Rect let right: Rect diff --git a/Sources/TesseraCore/TesseraCore.docc/TesseraCore.md b/Sources/TesseraCore/TesseraCore.docc/TesseraCore.md index f08f0d5f..e607d469 100644 --- a/Sources/TesseraCore/TesseraCore.docc/TesseraCore.md +++ b/Sources/TesseraCore/TesseraCore.docc/TesseraCore.md @@ -25,7 +25,8 @@ and let the engine execute its `Effect` values. Coordinates use a top-left global origin, including negative display origins. `Rect.roundedToWholePoints()` rounds shared edges rather than individual widths; -layout leaves and programmatic floating relocation use that one rounding policy. +emitted layout frames and programmatic floating relocation use that one rounding +policy. Grid insertion chooses its axis before rounding. Minimum sizes reserve whole-point extents. If constraints conflict, tiles stay on-screen and `cannotFit` identifies each window below its learned minimum. @@ -36,9 +37,16 @@ overflow joins the newest tile, and its latest member becomes visible. Arrivals split the newest tile in half: horizontally for columns, vertically for rows, and along its longest dimension for grid. Side first divides the main and -secondary areas, then splits the newest secondary tile vertically. Existing -splits survive removals and directional moves. Retile and layout changes restore -a balanced arrangement while keeping explicit stacks intact. Raising the cap +secondary areas, then splits the newest secondary tile vertically. `TileTree.split` +shares usable content after balancing gaps; `TileTree.partition` divides an existing +area at its own divider. Insertions use partitions so their gaps don't move older +tiles. Gaps shrink locally if the newest area is too small. + +Existing splits survive removals and directional moves, except that removing the +last member of the side layout's main tile promotes the first surviving tile and +balances the secondary area. This also applies when the main window floats or +leaves the display. Retile and layout changes restore a balanced arrangement +while keeping explicit stacks intact. Raising the cap allows later insertion or unstacking; it does not dissolve existing stacks. A floating user move or resize is recorded without rounding or a corrective write. diff --git a/Sources/TesseraCore/TileTree.swift b/Sources/TesseraCore/TileTree.swift index 35c46e69..d312acf7 100644 --- a/Sources/TesseraCore/TileTree.swift +++ b/Sources/TesseraCore/TileTree.swift @@ -1,11 +1,12 @@ public indirect enum TileTree: Sendable, Equatable, Codable { case tile(WindowStack) case split(axis: Axis, fraction: Double, first: TileTree, second: TileTree) + case partition(axis: Axis, fraction: Double, first: TileTree, second: TileTree) public var stacks: [WindowStack] { switch self { case .tile(let stack): [stack] - case .split(_, _, let first, let second): first.stacks + second.stacks + case .split(_, _, let first, let second), .partition(_, _, let first, let second): first.stacks + second.stacks } } @@ -49,21 +50,18 @@ public indirect enum TileTree: Sendable, Equatable, Codable { func mappingStacks(_ transform: (WindowStack) -> WindowStack) -> TileTree { switch self { case .tile(let stack): .tile(transform(stack)) - case .split(let axis, let fraction, let first, let second): - .split( - axis: axis, fraction: fraction, - first: first.mappingStacks(transform), second: second.mappingStacks(transform) - ) + case .split(_, _, let first, let second), .partition(_, _, let first, let second): + replacingChildren(first: first.mappingStacks(transform), second: second.mappingStacks(transform)) } } func removing(_ window: WindowID) -> TileTree? { switch self { case .tile(let stack): return stack.removing(window).map { .tile($0) } - case .split(let axis, let fraction, let first, let second): + case .split(_, _, let first, let second), .partition(_, _, let first, let second): let left = first.removing(window) let right = second.removing(window) - if let left, let right { return .split(axis: axis, fraction: fraction, first: left, second: right) } + if let left, let right { return replacingChildren(first: left, second: right) } return left ?? right } } @@ -73,19 +71,31 @@ public indirect enum TileTree: Sendable, Equatable, Codable { case .tile(let stack): guard stack.windows.contains(target) else { return self } let new = TileTree.tile(WindowStack(window)) - return .split(axis: axis, fraction: 0.5, first: before ? new : self, second: before ? self : new) - case .split(let splitAxis, let fraction, let first, let second): - return .split( - axis: splitAxis, fraction: fraction, + return .partition(axis: axis, fraction: 0.5, first: before ? new : self, second: before ? self : new) + case .split(_, _, let first, let second), .partition(_, _, let first, let second): + return replacingChildren( first: first.inserting(window, beside: target, axis: axis, before: before), second: second.inserting(window, beside: target, axis: axis, before: before) ) } } + private func replacingChildren(first: TileTree, second: TileTree, fraction: Double? = nil) -> TileTree { + switch self { + case .tile: return self + case .split(let axis, let existing, _, _): + return .split(axis: axis, fraction: fraction ?? existing, first: first, second: second) + case .partition(let axis, let existing, _, _): + return .partition(axis: axis, fraction: fraction ?? existing, first: first, second: second) + } + } + func settingMainRatio(_ ratio: MainRatio) -> TileTree { - guard case .split(.horizontal, _, let first, let second) = self else { return self } - return .split(axis: .horizontal, fraction: ratio.value, first: first, second: second) + switch self { + case .split(.horizontal, _, let first, let second), .partition(.horizontal, _, let first, let second): + return replacingChildren(first: first, second: second, fraction: ratio.value) + default: return self + } } } @@ -148,10 +158,16 @@ public struct Workspace: Sendable, Equatable, Codable { mutating func remove(_ window: WindowID) { order.removeAll { $0 == window } - tree = tree?.removing(window) + removeTile(window) if focus == window { focus = tree?.visibleWindows.last ?? order.last } } + mutating func removeTile(_ window: WindowID) { + let promotesMain = layout == .side && tree?.stacks.first?.windows == [window] + tree = tree?.removing(window) + if promotesMain { rebuild(stacks: tree?.stacks ?? []) } + } + mutating func insert(_ window: WindowID, floating: Bool, in frame: Rect, windows: [WindowID: ManagedWindow]) { if !order.contains(window) { order.append(window) @@ -176,7 +192,7 @@ public struct Workspace: Sendable, Equatable, Codable { case .rows: axis = .vertical case .side: axis = current.tileCount == 1 ? .horizontal : .vertical case .grid: - let area = LayoutEngine.arrange(self, in: frame, windows: windows).frames[newest.visible] ?? frame + let area = LayoutEngine.arrangeUnrounded(self, in: frame, windows: windows).frames[newest.visible] ?? frame axis = area.size.width >= area.size.height ? .horizontal : .vertical } tree = current.inserting(window, beside: newest.visible, axis: axis, before: false) diff --git a/Tests/TesseraCoreTests/LayoutInsertionTests.swift b/Tests/TesseraCoreTests/LayoutInsertionTests.swift new file mode 100644 index 00000000..0c950f9f --- /dev/null +++ b/Tests/TesseraCoreTests/LayoutInsertionTests.swift @@ -0,0 +1,201 @@ +import Foundation +import Testing + +@testable import TesseraCore + +@Test(arguments: Layout.allCases, [10.0, 3.5]) +func arrivalWithGapsKeepsOlderTilesStill(layout: Layout, gap: Double) throws { + var state = State( + displays: [Display(id: primaryDisplay, frame: testScreen)], + activeSpaces: [primaryDisplay: primarySpace], + workspaces: [primaryKey: workspace(0, layout: layout, gaps: Gaps(inner: gap))]) + for number in 1...8 { + let previous = state + let newest = state.workspaces[primaryKey]?.tree?.stacks.last?.visible + let result = reduce(state, .windowAppeared(managed(number), workspace: primaryKey, frame: Rect())) + for window in previous.visibleWindows where window != newest { + #expect(result.0.frames[window] == previous.frames[window]) + #expect(!frameWrites(result.1).contains { $0.window == window }) + } + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == number) + #expect(result.0.cannotFit.isEmpty) + state = result.0 + } + try roundTrip(state) +} + +@Test(arguments: [Layout.columns, .rows]) +func thirdArrivalSplitsOnlyTheNewestGappedArea(layout: Layout) { + var workspace = workspace(0, layout: layout, gaps: Gaps(inner: 10)) + for number in 1...3 { + workspace.insert(windowID(number), floating: false, in: testScreen, windows: [:]) + } + let expected = + layout == .columns + ? [ + windowID(1): Rect(x: 0, y: 0, width: 595, height: 800), + windowID(2): Rect(x: 605, y: 0, width: 293, height: 800), + windowID(3): Rect(x: 908, y: 0, width: 292, height: 800), + ] + : [ + windowID(1): Rect(x: 0, y: 0, width: 1200, height: 395), + windowID(2): Rect(x: 0, y: 405, width: 1200, height: 193), + windowID(3): Rect(x: 0, y: 608, width: 1200, height: 192), + ] + #expect(LayoutEngine.arrange(workspace, in: testScreen).frames == expected) +} + +@Test(arguments: [Point(), Point(x: 0.4, y: -0.4), Point(x: -300.7, y: 100.3)]) +func fractionalGridInsertionUsesUnroundedLongestAxis(origin: Point) { + let screen = Rect(origin: origin, size: Size(width: 100.3, height: 100.4)) + var workspace = workspace(0) + for number in 1...2 { + workspace.insert(windowID(number), floating: false, in: screen, windows: [:]) + } + #expect( + LayoutEngine.arrange(workspace, in: screen).frames == [ + windowID(1): Rect(origin: origin, size: Size(width: 100.3, height: 50.2)).roundedToWholePoints(), + windowID(2): Rect(x: origin.xCoordinate, y: origin.yCoordinate + 50.2, width: 100.3, height: 50.2) + .roundedToWholePoints(), + ]) +} + +@Test(arguments: [MainRatio.half, .threeFifths, .twoThirds], [false, true]) +func removingSideMainPromotesNextTileAndKeepsRatio(ratio: MainRatio, floating: Bool) throws { + var state = focused(1, in: populated(3, layout: .side)) + state.workspaces[primaryKey]?.gaps = Gaps(inner: 10) + state = command(.setRatio(ratio), in: state).0 + let previousMain = try #require(state.frames[windowID(1)]) + state = floating ? command(.toggleFloat, in: state).0 : reduce(state, .windowDisappeared(windowID(1))).0 + #expect(state.frames[windowID(2)] == previousMain) + let secondary = Rect(x: previousMain.maxX + 10, y: 0, width: 1200 - previousMain.maxX - 10, height: 800) + #expect(state.frames[windowID(3)] == secondary) + #expect(state.workspaces[primaryKey]?.layout == .side) + #expect(state.workspaces[primaryKey]?.ratio == ratio) + state = reduce(state, .windowAppeared(managed(4), workspace: primaryKey, frame: Rect())).0 + #expect(state.frames[windowID(2)] == previousMain) + #expect(state.frames[windowID(3)] == Rect(x: secondary.minX, y: 0, width: secondary.size.width, height: 395)) + #expect(state.frames[windowID(4)] == Rect(x: secondary.minX, y: 405, width: secondary.size.width, height: 395)) +} + +@Test func sideMainMetadataChangeAndTransferAlsoPromote() throws { + for transfer in [false, true] { + var state = multipleDisplays() + state = command(.setLayout(.side), in: state).0 + state = command(.setRatio(.threeFifths), in: state).0 + let main = try #require(state.frames[windowID(1)]) + state = + transfer + ? command(.moveToDisplay(.right), in: state).0 + : reduce(state, .windowAppeared(managed(1, floating: true), workspace: primaryKey, frame: main)).0 + #expect(state.frames[windowID(2)] == testScreen) + state = reduce(state, .windowAppeared(managed(5), workspace: primaryKey, frame: Rect())).0 + #expect(state.frames[windowID(2)] == main) + #expect(state.frames[windowID(5)] == Rect(x: 720, y: 0, width: 480, height: 800)) + } +} + +@Test func removingSideSecondaryKeepsMainAndSurvivingSplits() throws { + var state = focused(4, in: populated(4, layout: .side)) + state.workspaces[primaryKey]?.gaps = Gaps(inner: 10) + state = command(.retile, in: state).0 + let main = try #require(state.frames[windowID(1)]) + state = reduce(state, .windowDisappeared(windowID(3))).0 + #expect(state.frames[windowID(1)] == main) + #expect(state.workspaces[primaryKey]?.tree?.stacks.map(\.windows) == [[windowID(1)], [windowID(2)], [windowID(4)]]) + #expect(state.focusedWindow == windowID(4)) +} + +@Test func removingOneMainStackMemberDoesNotPromoteSecondary() throws { + var state = focused(2, in: populated(3, layout: .side, cap: 2)) + state = command(.stack(.left), in: state).0 + let main = try #require(state.frames[windowID(1)]) + state = reduce(state, .windowDisappeared(windowID(1))).0 + #expect(state.frames[windowID(2)] == main) + #expect(state.frames[windowID(3)] == Rect(x: 600, y: 0, width: 600, height: 800)) +} + +@Test(arguments: [-0.1, 1.1], [false, true]) +func decodedOutOfBoundsSplitFractionIsRejected(fraction: Double, partition: Bool) throws { + var workspace = workspace(2) + let first = TileTree.tile(WindowStack(windowID(1))) + let second = TileTree.tile(WindowStack(windowID(2))) + workspace.tree = + partition + ? .partition(axis: .horizontal, fraction: fraction, first: first, second: second) + : .split(axis: .horizontal, fraction: fraction, first: first, second: second) + let data = try JSONEncoder().encode(workspace) + #expect(throws: DecodingError.self) { try JSONDecoder().decode(Workspace.self, from: data) } +} + +@Test(arguments: [false, true]) +func decodedDuplicateLeavesAreRejected(partition: Bool) throws { + var workspace = workspace(2) + let tile = TileTree.tile(WindowStack(windowID(1))) + workspace.tree = + partition + ? .partition(axis: .horizontal, fraction: 0.5, first: tile, second: tile) + : .split(axis: .horizontal, fraction: 0.5, first: tile, second: tile) + let data = try JSONEncoder().encode(workspace) + #expect(throws: DecodingError.self) { try JSONDecoder().decode(Workspace.self, from: data) } +} + +@Test(arguments: Layout.allCases, [10.0, 400.0]) +func insertedTreesWithImpossibleMinimumsStayInsideTheScreen(layout: Layout, gap: Double) throws { + var workspace = workspace(0, layout: layout, gaps: Gaps(inner: gap)) + let windows = Dictionary( + uniqueKeysWithValues: (1...8).map { number in + (windowID(number), managed(number, minimum: Size(width: 300, height: 300))) + }) + for number in 1...8 { + workspace.insert(windowID(number), floating: false, in: testScreen, windows: windows) + let result = LayoutEngine.arrange(workspace, in: testScreen, windows: windows) + #expect(result.frames.count == number) + for frame in result.frames.values { + #expect(frame.minX >= 0 && frame.minY >= 0) + #expect(frame.maxX <= 1200 && frame.maxY <= 800) + #expect(frame.size.width >= 0 && frame.size.height >= 0) + } + #expect( + result.cannotFit + == result.frames.keys.sorted().filter { + guard let frame = result.frames[$0] else { return false } + return frame.size.width < 300 || frame.size.height < 300 + }) + } + try roundTrip(workspace) +} + +@Test(arguments: [false, true]) +func insertionPartitionsRemainInsideAnExistingBalancedOrPartitionedArea(balanced: Bool) throws { + var workspace = workspace(3, gaps: Gaps(inner: 10)) + let first = TileTree.tile(WindowStack(windowID(1))) + let second = TileTree.partition( + axis: .horizontal, fraction: 0.5, + first: .tile(WindowStack(windowID(2))), second: .tile(WindowStack(windowID(3)))) + workspace.tree = + balanced + ? .split(axis: .horizontal, fraction: 0.5, first: first, second: second) + : .partition(axis: .horizontal, fraction: 0.5, first: first, second: second) + #expect( + LayoutEngine.arrange(workspace, in: testScreen).frames == [ + windowID(1): Rect(x: 0, y: 0, width: 595, height: 800), + windowID(2): Rect(x: 605, y: 0, width: 293, height: 800), + windowID(3): Rect(x: 908, y: 0, width: 292, height: 800), + ]) + try roundTrip(workspace) +} + +@Test func decodedTreeBeyondCapIsRejected() throws { + var workspace = workspace(2, cap: 1) + workspace.tree = TileTree.balanced([WindowStack(windowID(1)), WindowStack(windowID(2))], layout: .columns) + let data = try JSONEncoder().encode(workspace) + #expect(throws: DecodingError.self) { try JSONDecoder().decode(Workspace.self, from: data) } +} + +@Test func decodedTileOutsideWorkspaceOrderIsRejected() throws { + var workspace = workspace(2) + workspace.tree = .tile(WindowStack(windowID(9))) + let data = try JSONEncoder().encode(workspace) + #expect(throws: DecodingError.self) { try JSONDecoder().decode(Workspace.self, from: data) } +} -- knotmirror 0.0.1 From f2e746554be1e7c638ade508016691301453ad4c Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Fri, 30 Oct 2026 23:38:11 -0400 Subject: [PATCH 40/44] Check exact directional command frames --- .../TesseraCoreTests/CommandPixelTests.swift | 217 ++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 Tests/TesseraCoreTests/CommandPixelTests.swift diff --git a/Tests/TesseraCoreTests/CommandPixelTests.swift b/Tests/TesseraCoreTests/CommandPixelTests.swift new file mode 100644 index 00000000..0020f0ac --- /dev/null +++ b/Tests/TesseraCoreTests/CommandPixelTests.swift @@ -0,0 +1,217 @@ +import Testing + +@testable import TesseraCore + +private func fourFrames(_ layout: Layout) -> [WindowID: Rect] { + let frames: [Rect] + switch layout { + case .columns: + frames = (0..<4).map { Rect(x: Double($0) * 300, y: 0, width: 300, height: 800) } + case .rows: + frames = (0..<4).map { Rect(x: 0, y: Double($0) * 200, width: 1200, height: 200) } + case .grid: + frames = [ + Rect(x: 0, y: 0, width: 600, height: 400), Rect(x: 600, y: 0, width: 600, height: 400), + Rect(x: 0, y: 400, width: 600, height: 400), Rect(x: 600, y: 400, width: 600, height: 400), + ] + case .side: + frames = [ + Rect(x: 0, y: 0, width: 600, height: 800), Rect(x: 600, y: 0, width: 600, height: 267), + Rect(x: 600, y: 267, width: 600, height: 266), Rect(x: 600, y: 533, width: 600, height: 267), + ] + } + return Dictionary(uniqueKeysWithValues: frames.enumerated().map { (windowID($0.offset + 1), $0.element) }) +} + +private func directionalPair(_ layout: Layout, _ direction: Direction) -> (source: Int, target: Int)? { + switch (layout, direction) { + case (.columns, .left), (.rows, .up), (.grid, .left), (.side, .left): (2, 1) + case (.columns, .right), (.rows, .down), (.grid, .right): (1, 2) + case (.grid, .up): (3, 1) + case (.grid, .down): (1, 3) + case (.side, .right): (1, 3) + case (.side, .up): (3, 2) + case (.side, .down): (2, 3) + default: nil + } +} + +@Test(arguments: Layout.allCases, Direction.allCases) +func swapsHaveExactFramesInEveryLayout(layout: Layout, direction: Direction) throws { + let pair = directionalPair(layout, direction) + let state = focused(pair?.source ?? 1, in: populated(4, layout: layout)) + let initial = fourFrames(layout) + #expect(state.frames == initial) + let result = command(.swap(direction), in: state) + guard let pair else { + #expect(result.0 == state) + #expect(result.1 == [.report(.noNeighbor(direction))]) + return + } + let source = windowID(pair.source) + let target = windowID(pair.target) + var expected = initial + expected[source] = initial[target] + expected[target] = initial[source] + #expect(result.0.frames == expected) + #expect( + result.0.workspaces[primaryKey]?.order + == (1...4).map { number in + windowID(number == pair.source ? pair.target : (number == pair.target ? pair.source : number)) + }) + #expect(result.0.focusedWindow == source) + let writes = try [source, target].sorted().map { window in + WindowFrame(window: window, frame: try #require(expected[window])) + } + #expect(frameWrites(result.1) == writes) +} + +private func movedFourFrames(_ layout: Layout, _ direction: Direction) -> [WindowID: Rect] { + var frames = fourFrames(layout) + switch (layout, direction) { + case (.columns, .left): + frames = [ + windowID(1): Rect(x: 150, y: 0, width: 150, height: 800), + windowID(2): Rect(x: 0, y: 0, width: 150, height: 800), + windowID(3): Rect(x: 300, y: 0, width: 450, height: 800), + windowID(4): Rect(x: 750, y: 0, width: 450, height: 800), + ] + case (.columns, .right): + frames = [ + windowID(1): Rect(x: 200, y: 0, width: 200, height: 800), + windowID(2): Rect(x: 0, y: 0, width: 200, height: 800), + windowID(3): Rect(x: 400, y: 0, width: 400, height: 800), + windowID(4): Rect(x: 800, y: 0, width: 400, height: 800), + ] + case (.rows, .up): + frames = [ + windowID(1): Rect(x: 0, y: 100, width: 1200, height: 100), + windowID(2): Rect(x: 0, y: 0, width: 1200, height: 100), + windowID(3): Rect(x: 0, y: 200, width: 1200, height: 300), + windowID(4): Rect(x: 0, y: 500, width: 1200, height: 300), + ] + case (.rows, .down): + frames = [ + windowID(1): Rect(x: 0, y: 133, width: 1200, height: 134), + windowID(2): Rect(x: 0, y: 0, width: 1200, height: 133), + windowID(3): Rect(x: 0, y: 267, width: 1200, height: 266), + windowID(4): Rect(x: 0, y: 533, width: 1200, height: 267), + ] + case (.grid, .left), (.grid, .right): + frames[windowID(1)] = Rect(x: 600, y: 0, width: 600, height: 400) + frames[windowID(2)] = Rect(x: 0, y: 0, width: 600, height: 400) + case (.grid, .up): + frames[windowID(1)] = Rect(x: 0, y: 200, width: 600, height: 200) + frames[windowID(3)] = Rect(x: 0, y: 0, width: 600, height: 200) + frames[windowID(4)] = Rect(x: 0, y: 400, width: 1200, height: 400) + case (.grid, .down): + frames[windowID(1)] = Rect(x: 0, y: 600, width: 600, height: 200) + frames[windowID(2)] = Rect(x: 0, y: 0, width: 1200, height: 400) + frames[windowID(3)] = Rect(x: 0, y: 400, width: 600, height: 200) + case (.side, .left): + frames = [ + windowID(1): Rect(x: 300, y: 0, width: 300, height: 800), + windowID(2): Rect(x: 0, y: 0, width: 300, height: 800), + windowID(3): Rect(x: 600, y: 0, width: 600, height: 400), + windowID(4): Rect(x: 600, y: 400, width: 600, height: 400), + ] + case (.side, .right): + frames = [ + windowID(1): Rect(x: 900, y: 0, width: 300, height: 400), + windowID(2): Rect(x: 0, y: 0, width: 600, height: 800), + windowID(3): Rect(x: 600, y: 0, width: 300, height: 400), + windowID(4): Rect(x: 600, y: 400, width: 600, height: 400), + ] + case (.side, .up): + frames[windowID(2)] = Rect(x: 600, y: 133, width: 600, height: 134) + frames[windowID(3)] = Rect(x: 600, y: 0, width: 600, height: 133) + frames[windowID(4)] = Rect(x: 600, y: 267, width: 600, height: 533) + case (.side, .down): + frames[windowID(2)] = Rect(x: 600, y: 200, width: 600, height: 200) + frames[windowID(3)] = Rect(x: 600, y: 0, width: 600, height: 200) + frames[windowID(4)] = Rect(x: 600, y: 400, width: 600, height: 400) + default: break + } + return frames +} + +@Test(arguments: Layout.allCases, Direction.allCases) +func directionalMovesHaveExactFrames(layout: Layout, direction: Direction) throws { + let pair = directionalPair(layout, direction) + let state = focused(pair?.source ?? 1, in: populated(4, layout: layout)) + let result = command(.move(direction), in: state) + guard let pair else { + #expect(result.0 == state) + #expect(result.1 == [.report(.noNeighbor(direction))]) + return + } + let expected = movedFourFrames(layout, direction) + #expect(result.0.frames == expected) + #expect(result.0.focusedWindow == windowID(pair.source)) + #expect(result.0.workspaces[primaryKey]?.tree?.tileCount == 4) + let writes = try expected.keys.sorted().filter { expected[$0] != state.frames[$0] }.map { + WindowFrame(window: $0, frame: try #require(expected[$0])) + } + #expect(frameWrites(result.1) == writes) +} + +@Test(arguments: Direction.allCases) +func moveToEveryDisplayDirectionHasExactFrames(direction: Direction) throws { + let state = multipleDisplays(direction) + let screen = try #require(state.displays[secondaryDisplay]?.frame) + let result = command(.moveToDisplay(direction), in: state) + let expected = [ + windowID(1): Rect(x: screen.minX + 900, y: screen.minY, width: 300, height: 800), + windowID(2): testScreen, + windowID(3): Rect(x: screen.minX, y: screen.minY, width: 600, height: 800), + windowID(4): Rect(x: screen.minX + 600, y: screen.minY, width: 300, height: 800), + ] + #expect(result.0.frames == expected) + #expect(result.0.activeDisplay == secondaryDisplay) + #expect(result.0.focusedWindow == windowID(1)) + let writes = try [1, 2, 4].map { number in + WindowFrame(window: windowID(number), frame: try #require(expected[windowID(number)])) + } + #expect(frameWrites(result.1) == writes) +} + +@Test(arguments: Direction.allCases, [2, 8]) +func directionalCrossDisplayMovesHaveExactFrames(direction: Direction, cap: Int) throws { + let number = direction == .right ? 2 : 1 + let state = focused(number, in: multipleDisplays(direction, destinationCap: cap)) + let screen = try #require(state.displays[secondaryDisplay]?.frame) + let target = windowID(direction == .left ? 4 : 3) + var expected = state.frames + expected[windowID(3 - number)] = testScreen + if cap == 2 { + expected[windowID(number)] = state.frames[target] + } else { + switch direction { + case .left: + expected[windowID(1)] = Rect(x: screen.minX + 600, y: 0, width: 300, height: 800) + expected[windowID(4)] = Rect(x: screen.minX + 900, y: 0, width: 300, height: 800) + case .right: + expected[windowID(2)] = Rect(x: screen.minX + 300, y: 0, width: 300, height: 800) + expected[windowID(3)] = Rect(x: screen.minX, y: 0, width: 300, height: 800) + case .up: + expected[windowID(1)] = Rect(x: 0, y: screen.minY, width: 600, height: 400) + expected[windowID(3)] = Rect(x: 0, y: screen.minY + 400, width: 600, height: 400) + case .down: + expected[windowID(1)] = Rect(x: 0, y: screen.minY + 400, width: 600, height: 400) + expected[windowID(3)] = Rect(x: 0, y: screen.minY, width: 600, height: 400) + } + } + let result = command(.move(direction), in: state) + #expect(result.0.frames == expected) + #expect(result.0.activeDisplay == secondaryDisplay) + #expect(result.0.focusedWindow == windowID(number)) + #expect(result.0.workspace(containing: windowID(number)) == secondaryKey) + let writes = try expected.keys.sorted().filter { expected[$0] != state.frames[$0] }.map { + WindowFrame(window: $0, frame: try #require(expected[$0])) + } + #expect(frameWrites(result.1) == writes) + if cap == 2 { + #expect(!result.0.visibleWindows.contains(target)) + #expect(result.1.contains(.raiseWindow(windowID(number)))) + } +} -- knotmirror 0.0.1 From 4db6d5473ec0e95a8b9f9d659f6da08af8d510de Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 00:02:39 -0400 Subject: [PATCH 41/44] Add batched reduction and reactor hooks --- Sources/TesseraCore/Reducer.swift | 34 ++++++++++++++++++++----- Sources/TesseraPlatform/AXElement.swift | 3 +++ Sources/TesseraPlatform/AppThread.swift | 13 +++++++--- 3 files changed, 41 insertions(+), 9 deletions(-) diff --git a/Sources/TesseraCore/Reducer.swift b/Sources/TesseraCore/Reducer.swift index 702169f9..fba9b281 100644 --- a/Sources/TesseraCore/Reducer.swift +++ b/Sources/TesseraCore/Reducer.swift @@ -1,10 +1,29 @@ public func reduce(_ state: State, _ event: Event) -> (State, [Effect]) { + let (next, effects) = reduce(state, [event]) + return (next, effects.first ?? []) +} + +/// Applies observations in order, then computes one layout. Effects retain their event index. +public func reduce(_ state: State, _ events: [Event]) -> (State, [[Effect]]) { + guard !events.isEmpty else { return (state, []) } var next = state - var effects: [Effect] = [] + var effectsByEvent = Array(repeating: [Effect](), count: events.count) var baseline = state.frames - if let issue = next.handle(event, baseline: &baseline, effects: &effects) { - return (state, [.report(issue)]) + var accepted = false + for (index, event) in events.enumerated() { + var candidate = next + var candidateBaseline = baseline + if let issue = candidate.handle(event, baseline: &candidateBaseline, effects: &effectsByEvent[index]) { + effectsByEvent[index] = [.report(issue)] + } else { + next = candidate + baseline = candidateBaseline + accepted = true + } } + guard accepted else { return (state, effectsByEvent) } + var effects = events.count == 1 ? effectsByEvent[0] : [] + if events.count == 1 { effectsByEvent[0] = [] } let desired = next.layoutFrames() let writes = desired.frames.keys.sorted().compactMap { window -> WindowFrame? in guard let frame = desired.frames[window], frame != baseline[window] else { return nil } @@ -23,10 +42,13 @@ public func reduce(_ state: State, _ event: Event) -> (State, [Effect]) { effects.removeAll { $0 == .raiseWindow(focused) } effects.append(.raiseWindow(focused)) } - if event == .commandIssued(.retile) && next.activeWorkspace != nil { - effects.append(.report(.retiled(moved: writes.count))) + effectsByEvent[0].insert(contentsOf: effects.filter { if case .setFrames = $0 { true } else { false } }, at: 0) + effectsByEvent[events.count - 1].append( + contentsOf: effects.filter { if case .setFrames = $0 { false } else { true } }) + for (index, event) in events.enumerated() where event == .commandIssued(.retile) && next.activeWorkspace != nil { + effectsByEvent[index].append(.report(.retiled(moved: writes.count))) } - return (next, effects) + return (next, effectsByEvent) } extension Size { diff --git a/Sources/TesseraPlatform/AXElement.swift b/Sources/TesseraPlatform/AXElement.swift index a1d9bf8e..648b605f 100644 --- a/Sources/TesseraPlatform/AXElement.swift +++ b/Sources/TesseraPlatform/AXElement.swift @@ -245,6 +245,9 @@ public struct AXElement { } public func setTitle(_ value: String) throws { try set(kAXTitleAttribute, value: value as CFString) } public func setFocusedWindow(_ window: AXElement) throws { try set(kAXFocusedWindowAttribute, value: window.raw) } + public func raise() throws { + try callAX { AXUIElementPerformAction(raw, kAXRaiseAction as CFString) } + } public func windowID() throws -> CGWindowID { typealias GetWindow = @convention(c) (AXUIElement, UnsafeMutablePointer) -> AXError diff --git a/Sources/TesseraPlatform/AppThread.swift b/Sources/TesseraPlatform/AppThread.swift index 1b50deb5..73fd79f9 100644 --- a/Sources/TesseraPlatform/AppThread.swift +++ b/Sources/TesseraPlatform/AppThread.swift @@ -72,14 +72,15 @@ public final class AppThread: Sendable { private let executor: AppThreadExecutor private let exitObserver: AppProcessObserver - public init(pid: pid_t, timeout: Float = 0.35, timeoutThreshold: Int = 3) throws { + public init(pid: pid_t, timeout: Float = 0.35, timeoutThreshold: Int = 3, reconcileWhileIdle: Bool = true) throws { precondition(timeout > 0 && timeout.isFinite) precondition(timeoutThreshold > 0) guard AppThreadOwnerRegistry.shared.acquire(pid) else { throw AppThreadFailure.alreadyOwned(pid) } let (events, continuation) = AsyncStream.makeStream() self.events = events let worker = AppThreadWorker( - pid: pid, timeout: timeout, timeoutThreshold: timeoutThreshold, events: continuation) + pid: pid, timeout: timeout, timeoutThreshold: timeoutThreshold, reconcileWhileIdle: reconcileWhileIdle, + events: continuation) self.worker = worker let executor = AppThreadExecutor( start: { worker.start() }, @@ -183,11 +184,16 @@ private final class AppThreadWorker: @unchecked Sendable { private var startupFailure: AppThreadFailure? private var observer: AXObserver? private var reconciliationTimer: CFRunLoopTimer? + private let reconcileWhileIdle: Bool private var windows: [(raw: AXUIElement, id: CGWindowID)] = [] private var frameWrites = AppThreadFrameWriteTracker() private var registrations = AppThreadRegistrationTracker() - init(pid: pid_t, timeout: Float, timeoutThreshold: Int, events: AsyncStream.Continuation) { + init( + pid: pid_t, timeout: Float, timeoutThreshold: Int, reconcileWhileIdle: Bool, + events: AsyncStream.Continuation + ) { + self.reconcileWhileIdle = reconcileWhileIdle self.pid = pid self.timeout = timeout self.events = events @@ -234,6 +240,7 @@ private final class AppThreadWorker: @unchecked Sendable { record(error) events.yield(.failure(.windowEnumeration(String(describing: error)))) } + guard reconcileWhileIdle else { return } guard let timer = CFRunLoopTimerCreateWithHandler( nil, CFAbsoluteTimeGetCurrent() + 10, 10, 0, 0, { [self] _ in reconcile() } -- knotmirror 0.0.1 From 051fdc8bcff4d2c45fb6756235eecc884c8b84bb Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 00:04:57 -0400 Subject: [PATCH 42/44] Build the tiling reactor --- Package.swift | 4 +- .../TesseraEngine/EngineConfiguration.swift | 120 +++ Sources/TesseraEngine/EngineIPCHandler.swift | 184 +++++ Sources/TesseraEngine/EngineInterfaces.swift | 140 ++++ .../TesseraEngine/EngineSystemServices.swift | 174 +++++ Sources/TesseraEngine/NativeEngineWorld.swift | 375 +++++++++ .../Resources/Localizable.xcstrings | 10 + .../Resources/en.lproj/Localizable.strings | 4 + .../TesseraEngine.docc/TesseraEngine.md | 37 + Sources/TesseraEngine/TesseraEngine.swift | 722 ++++++++++++++++++ .../EngineIntegrationTests.swift | 179 +++++ .../ConfigurationAndDisplayTests.swift | 417 ++++++++++ .../EchoAndLifecycleTests.swift | 339 ++++++++ Tests/TesseraEngineTests/IPCTests.swift | 289 +++++++ Tests/TesseraEngineTests/MotionTests.swift | 390 ++++++++++ Tests/TesseraEngineTests/ReplayTests.swift | 72 ++ .../TesseraEngineTests.swift | 257 ++++++- Tests/TesseraEngineTests/TestSupport.swift | 431 +++++++++++ 18 files changed, 4140 insertions(+), 4 deletions(-) create mode 100644 Sources/TesseraEngine/EngineConfiguration.swift create mode 100644 Sources/TesseraEngine/EngineIPCHandler.swift create mode 100644 Sources/TesseraEngine/EngineInterfaces.swift create mode 100644 Sources/TesseraEngine/EngineSystemServices.swift create mode 100644 Sources/TesseraEngine/NativeEngineWorld.swift create mode 100644 Sources/TesseraEngine/Resources/Localizable.xcstrings create mode 100644 Sources/TesseraEngine/Resources/en.lproj/Localizable.strings create mode 100644 Sources/TesseraEngine/TesseraEngine.docc/TesseraEngine.md create mode 100644 Tests/TesseraE2ETests/EngineIntegrationTests.swift create mode 100644 Tests/TesseraEngineTests/ConfigurationAndDisplayTests.swift create mode 100644 Tests/TesseraEngineTests/EchoAndLifecycleTests.swift create mode 100644 Tests/TesseraEngineTests/IPCTests.swift create mode 100644 Tests/TesseraEngineTests/MotionTests.swift create mode 100644 Tests/TesseraEngineTests/ReplayTests.swift create mode 100644 Tests/TesseraEngineTests/TestSupport.swift diff --git a/Package.swift b/Package.swift index 4f48c746..98b047ee 100644 --- a/Package.swift +++ b/Package.swift @@ -26,7 +26,7 @@ let package = Package( .target(name: "CPrivateAPI", linkerSettings: [.linkedFramework("ApplicationServices")]), .target(name: "TesseraPlatform", dependencies: ["TesseraCore", "CPrivateAPI"], swiftSettings: strict), .target(name: "TesseraAnimation", dependencies: ["TesseraCore"], swiftSettings: strict), - .target(name: "TesseraEngine", dependencies: ["TesseraCore", "TesseraConfig", "TesseraPlatform", "TesseraAnimation"], swiftSettings: strict), + .target(name: "TesseraEngine", dependencies: ["TesseraCore", "TesseraConfig", "TesseraPlatform", "TesseraAnimation", "TesseraIPC"], resources: [.process("Resources")], swiftSettings: strict), .target(name: "TesseraIPC", dependencies: ["TesseraCore"], resources: [.process("Resources")], swiftSettings: strict), .target(name: "TesseraUI", dependencies: ["TesseraCore", "TesseraConfig", "TesseraEngine", "TesseraAnimation"], swiftSettings: strict), .executableTarget(name: "TesseraApp", dependencies: ["TesseraUI", "TesseraEngine", "TesseraIPC"], swiftSettings: strict), @@ -44,7 +44,7 @@ let package = Package( .testTarget(name: "TesseraEngineTests", dependencies: ["TesseraEngine"]), .testTarget(name: "TesseraAnimationTests", dependencies: ["TesseraAnimation"]), .testTarget(name: "TesseraIPCTests", dependencies: ["TesseraIPC", "tessera"]), - .testTarget(name: "TesseraE2ETests", dependencies: ["TesseraPlatform", "TesseraCore"]), + .testTarget(name: "TesseraE2ETests", dependencies: ["TesseraPlatform", "TesseraCore", "TesseraEngine"]), ], swiftLanguageModes: [.v6] ) diff --git a/Sources/TesseraEngine/EngineConfiguration.swift b/Sources/TesseraEngine/EngineConfiguration.swift new file mode 100644 index 00000000..694f340d --- /dev/null +++ b/Sources/TesseraEngine/EngineConfiguration.swift @@ -0,0 +1,120 @@ +import Foundation +import TesseraAnimation +import TesseraConfig +import TesseraCore + +public enum EngineError: Error, Sendable, Equatable { + case stopped + case startInProgress + case invalidConfiguration(String) +} + +struct AppliedConfiguration { + let value: TesseraConfiguration + let rules: [(FloatRule, NSRegularExpression?)] + + init(_ value: TesseraConfiguration) throws { + guard value.version == 1 else { throw EngineError.invalidConfiguration("Unsupported configuration version") } + guard MotionSettings.supportedSpeeds.contains(value.motion.speed) else { + throw EngineError.invalidConfiguration("Motion speed is outside the supported range") + } + for layout in [value.layout.global] + Array(value.layout.displays.values) { + let edges = layout.reserved + guard layout.ratio.isFinite, (0.1...0.9).contains(layout.ratio), (0...100).contains(layout.windowCap), + [layout.gaps.inner, layout.gaps.outer].allSatisfy({ $0.isFinite && (0...256).contains($0) }), + [edges.top, edges.left, edges.bottom, edges.right].allSatisfy({ $0.isFinite && (0...4096).contains($0) } + ) + else { throw EngineError.invalidConfiguration("Invalid layout geometry") } + } + self.value = value + rules = try value.floatRules.map { rule in + (rule, try rule.titleRegex.map { try NSRegularExpression(pattern: $0) }) + } + } + + var motionSettings: MotionSettings { + let level: WhimsyLevel + switch value.motion.level { + case .calm: level = .calm + case .playful: level = .playful + case .extra: level = .extra + } + return MotionSettings(level: level, speedMultiplier: value.motion.speed) + } + + func motionPolicy(reduceMotion: Bool, snap: Bool = false) -> MotionPolicy { + MotionPolicy( + enabled: value.motion.enabled && value.motion.transitions == .glide && !snap, + reduceMotion: reduceMotion + ) + } + + func values(for display: DisplayID) -> LayoutValues { + guard let uuid = UUID(uuidString: display.rawValue) else { return value.layout.global } + return value.layout.values(for: uuid) + } + + func workspace(_ key: WorkspaceKey, existing: Workspace? = nil) -> Workspace { + let values = values(for: key.display) + let layout: Layout + switch values.defaultLayout { + case .grid: layout = .grid + case .columns: layout = .columns + case .rows: layout = .rows + case .side: layout = .side + } + var workspace = existing ?? Workspace(key: key) + workspace.layout = layout + workspace.ratio = MainRatio(values.ratio) + workspace.gaps = Gaps(inner: values.gaps.inner, outer: Insets(values.gaps.outer)) + workspace.reservedEdges = Insets( + top: values.reserved.top, left: values.reserved.left, + bottom: values.reserved.bottom, right: values.reserved.right + ) + workspace.setWindowCap(values.windowCap == 0 ? Int.max : values.windowCap) + return workspace + } + + func floats(_ window: ManagedWindow) -> Bool { + rules.contains { rule, regex in + if let bundle = rule.bundleID, bundle != window.app.bundleID { return false } + if let role = rule.role, role != window.role { return false } + if let regex, + regex.firstMatch(in: window.title, range: NSRange(window.title.startIndex..., in: window.title)) == nil + { + return false + } + return true + } + } +} + +extension Rect { + var motionRect: MotionRect { + MotionRect(originX: minX, originY: minY, width: size.width, height: size.height) + } + init(_ rect: MotionRect) { + self.init(x: rect.originX, y: rect.originY, width: rect.width, height: rect.height) + } + func matches(_ other: Rect, tolerance: Double = 1) -> Bool { + abs(minX - other.minX) <= tolerance && abs(minY - other.minY) <= tolerance + && abs(size.width - other.size.width) <= tolerance && abs(size.height - other.size.height) <= tolerance + } +} + +extension WindowID { + var motionID: MotionWindowID { MotionWindowID(rawValue: UInt64(rawValue)) } +} + +extension AppID { + var motionID: MotionAppID { MotionAppID(rawValue: pid) } +} + +extension Report { + var isFailure: Bool { + switch self { + case .retiled, .cannotFit: false + default: true + } + } +} diff --git a/Sources/TesseraEngine/EngineIPCHandler.swift b/Sources/TesseraEngine/EngineIPCHandler.swift new file mode 100644 index 00000000..f36773db --- /dev/null +++ b/Sources/TesseraEngine/EngineIPCHandler.swift @@ -0,0 +1,184 @@ +import Foundation +public import TesseraConfig +public import TesseraCore +public import TesseraIPC + +public enum EngineCommandParser { + public static func parse(_ name: String, args: [String] = []) throws -> Command { + if let configured = ConfigCommand(rawValue: name), args.isEmpty { return try command(configured) } + switch (name, args.count) { + case ("focus", 1): return .focus(try direction(args[0])) + case ("swap", 1): return .swap(try direction(args[0])) + case ("move", 1): return .move(try direction(args[0])) + case ("move-to-display", 1): return .moveToDisplay(try direction(args[0])) + case ("stack", 1): return .stack(try direction(args[0])) + case ("set-layout", 1): + guard let layout = Layout(rawValue: args[0]) else { throw invalid() } + return .setLayout(layout) + case ("set-ratio", 1): + guard let ratio = Double(args[0]), ratio.isFinite, MainRatio.bounds.contains(ratio) else { throw invalid() } + return .setRatio(MainRatio(ratio)) + case ("nudge-ratio", 1): + guard let delta = Double(args[0]), delta.isFinite else { throw invalid() } + return .nudgeRatio(delta) + case ("set-window-cap", 1): + guard let cap = Int(args[0]), cap > 0 else { throw invalid() } + return .setWindowCap(cap) + case ("cycle-layout", 0): return .cycleLayout + case ("toggle-float", 0): return .toggleFloat + case ("unstack", 0): return .unstack + case ("focus-next-in-stack", 0): return .focusNextInStack + case ("focus-previous-in-stack", 0): return .focusPreviousInStack + default: throw invalid() + } + } + + public static func command(_ command: ConfigCommand) throws -> Command { + switch command { + case .focusLeft: .focus(.left) + case .focusRight: .focus(.right) + case .focusUp: .focus(.up) + case .focusDown: .focus(.down) + case .swapLeft: .swap(.left) + case .swapRight: .swap(.right) + case .swapUp: .swap(.up) + case .swapDown: .swap(.down) + case .moveLeft: .move(.left) + case .moveRight: .move(.right) + case .moveUp: .move(.up) + case .moveDown: .move(.down) + case .layoutGrid: .setLayout(.grid) + case .layoutColumns: .setLayout(.columns) + case .layoutRows: .setLayout(.rows) + case .layoutSide: .setLayout(.side) + case .ratioIncrease: .nudgeRatio(0.05) + case .ratioDecrease: .nudgeRatio(-0.05) + case .floatToggle: .toggleFloat + case .retile: .retile + case .stack: .stack(.right) + case .stackNext: .focusNextInStack + case .stackPrevious: .focusPreviousInStack + case .displayMoveLeft: .moveToDisplay(.left) + case .displayMoveRight: .moveToDisplay(.right) + case .displayMoveUp: .moveToDisplay(.up) + case .displayMoveDown: .moveToDisplay(.down) + case .openSettings: + throw IPCError( + code: "shell_command", + message: String(localized: "This command is handled by the app shell.", bundle: .module)) + } + } + + private static func direction(_ value: String) throws -> Direction { + guard let direction = Direction(rawValue: value) else { throw invalid() } + return direction + } + private static func invalid() -> IPCError { + IPCError( + code: "invalid_command", + message: String(localized: "The command or its arguments are invalid.", bundle: .module)) + } +} + +@MainActor +public final class EngineIPCHandler: IPCHandler { + public let engine: TesseraEngine + public let configPath: String + public let version: String + private let configStore: ConfigStore? + + public init( + engine: TesseraEngine, configStore: ConfigStore? = nil, configPath: String? = nil, version: String = "0.1.0" + ) { + self.engine = engine + self.configStore = configStore + self.configPath = configPath ?? configStore?.fileURL.path ?? ConfigStore.defaultFileURL.path + self.version = version + } + + public func query(_ query: IPCQuery) async throws -> JSONValue { + let state = engine.snapshot.state + switch query { + case .windows: + return .array( + try state.windows.keys.sorted().compactMap { id in + guard let window = state.windows[id] else { return nil } + var value: [String: JSONValue] = [ + "id": .integer(Int64(id.rawValue)), "pid": .integer(Int64(window.app.pid)), + "bundle_id": .string(window.app.bundleID), "title": .string(window.title), + "role": .string(window.role), + "floating": .bool(window.isFloating), "focused": .bool(state.focusedWindow == id), + "frame": try state.frames[id].map(Self.json) ?? .null, + "minimum": try window.minimum.map(Self.json) ?? .null, + ] + value["workspace"] = state.workspace(containing: id).map(Self.workspaceID) ?? .null + return .object(value) + }) + case .workspaces: + return .array( + try state.workspaces.keys.sorted().compactMap { key in + guard let workspace = state.workspaces[key] else { return nil } + return .object([ + "id": Self.workspaceID(key), "active": .bool(state.isActive(key)), + "layout": .string(workspace.layout.rawValue), + "ratio": .number(workspace.ratio.value), "window_cap": .integer(Int64(workspace.windowCap)), + "windows": .array(workspace.order.map { .integer(Int64($0.rawValue)) }), + "tiles": try workspace.tree.map(Self.json) ?? .null, + ]) + }) + case .displays: + return .array( + try state.displays.keys.sorted().compactMap { id in + guard let display = state.displays[id] else { return nil } + return .object([ + "id": .string(id.rawValue), "frame": try Self.json(display.frame), + "active_space": state.activeSpaces[id].map { .string(String($0.rawValue)) } ?? .null, + ]) + }) + case .config: + return .object([ + "path": .string(configPath), "version": .string(version), + "schema_version": .integer(Int64(engine.configuration.version)), + "motion": .object([ + "enabled": .bool(engine.configuration.motion.enabled), + "level": .string(engine.configuration.motion.level.rawValue), + "speed": .number(engine.configuration.motion.speed), + "transitions": .string(engine.configuration.motion.transitions.rawValue), + ]), + ]) + } + } + + public func run(command: String, args: [String]) async throws -> JSONValue { + let result = try await engine.perform(EngineCommandParser.parse(command, args: args)) + return .object([ + "accepted": .bool(result.isAccepted), "revision": .string(String(result.revision)), + "reports": try Self.json(result.reports), + ]) + } + + public func reloadConfig() async throws -> JSONValue { + guard let configStore else { + throw IPCError( + code: "config_unavailable", + message: String(localized: "No configuration store is connected.", bundle: .module)) + } + let snapshot = await configStore.reload() + try engine.applyConfigSnapshot(snapshot) + guard snapshot.loadState != .rejected else { + throw IPCError( + code: "config_rejected", + message: String( + localized: "The configuration was rejected. The last good configuration is still active.", + bundle: .module)) + } + return .object(["path": .string(configPath), "reloaded": .bool(true)]) + } + + private static func json(_ value: some Encodable) throws -> JSONValue { + try JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(value)) + } + private static func workspaceID(_ key: WorkspaceKey) -> JSONValue { + .object(["display": .string(key.display.rawValue), "space": .string(String(key.space.rawValue))]) + } +} diff --git a/Sources/TesseraEngine/EngineInterfaces.swift b/Sources/TesseraEngine/EngineInterfaces.swift new file mode 100644 index 00000000..aa680de7 --- /dev/null +++ b/Sources/TesseraEngine/EngineInterfaces.swift @@ -0,0 +1,140 @@ +public import TesseraAnimation +public import TesseraConfig +public import TesseraCore + +public enum FrameChangeOrigin: Sendable, Equatable { + case user + case engine(UInt64) + case unknown +} + +public enum EnginePlatformEvent: Sendable { + case observed(Event) + case frameChanged(WindowID, frame: Rect, resized: Bool, origin: FrameChangeOrigin) + case appLaunched(AppID, at: Double) + case appExited(AppID) + case failure(EnginePlatformFailure) +} + +public enum EnginePlatformFailure: Error, Sendable, Equatable { + case timedOut(AppID) + case vanished(WindowID) + case permissionLost + case failed(String) +} + +public struct EngineFrameWrite: Sendable, Equatable { + public let window: WindowID + public let frame: Rect + public let transaction: UInt64 + + public init(window: WindowID, frame: Rect, transaction: UInt64) { + self.window = window + self.frame = frame + self.transaction = transaction + } +} + +public struct EngineWriteReceipt: Sendable { + public let frames: [WindowFrame] + public let failures: [EnginePlatformFailure] + public let duration: Double + + public init(frames: [WindowFrame], failures: [EnginePlatformFailure] = [], duration: Double) { + self.frames = frames + self.failures = failures + self.duration = duration + } +} + +@MainActor +public protocol EngineWindowWorld: AnyObject { + func start(receive: @escaping @MainActor (EnginePlatformEvent) -> Void) throws + func stop() + func write( + _ frames: [EngineFrameWrite], for app: AppID, + completion: @escaping @MainActor (EngineWriteReceipt) -> Void + ) + func focus(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) + func raise(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) +} + +@MainActor +public protocol EngineClock: AnyObject { + var now: Double { get } +} + +@MainActor +public protocol EngineCancellation: AnyObject { + func cancel() +} + +@MainActor +public protocol EngineScheduler: AnyObject { + func schedule(after delay: Double, _ action: @escaping @MainActor () -> Void) -> any EngineCancellation +} + +@MainActor +public protocol EngineDisplayLink: AnyObject { + var isRunning: Bool { get } + func start(tick: @escaping @MainActor (Double) -> Void) + func stop() +} + +@MainActor +public protocol EngineConfigurationSource: AnyObject { + func start(changed: @escaping @MainActor (ConfigSnapshot) -> Void) async throws -> TesseraConfiguration + func stop() async +} + +@MainActor +public protocol EngineAnnouncer: AnyObject { + func announce(_ announcement: Announcement) +} + +public enum EngineDiagnostic: Sendable { + case core(Report) + case platform(EnginePlatformFailure) + case motion(MotionError) + case config([ConfigDiagnostic]) + case configuration(String) +} + +@MainActor +public protocol EngineLogSink: AnyObject { + func record(_ diagnostic: EngineDiagnostic) +} + +public enum EngineTraceStage: String, Sendable { + case eventToFirstWrite, eventToSettled, reduce, plan, write +} + +@MainActor +public protocol EngineTraceSink: AnyObject { + func begin(_ stage: EngineTraceStage, transaction: UInt64) + func end(_ stage: EngineTraceStage, transaction: UInt64) +} + +public struct EngineCommandResult: Sendable, Equatable { + public let revision: UInt64 + public let reports: [Report] + public let isAccepted: Bool +} + +public struct EngineSnapshot: Sendable, Equatable { + public let revision: UInt64 + public let state: State + + public var layouts: [DisplayID: Layout] { + Dictionary( + uniqueKeysWithValues: state.workspaces.keys.sorted().filter(state.isActive).compactMap { key in + state.workspaces[key].map { (key.display, $0.layout) } + }) + } + public var tiles: [WindowFrame] { + state.visibleWindows.compactMap { window in + state.frames[window].map { WindowFrame(window: window, frame: $0) } + } + } + public var focusedWindow: WindowID? { state.focusedWindow } +} diff --git a/Sources/TesseraEngine/EngineSystemServices.swift b/Sources/TesseraEngine/EngineSystemServices.swift new file mode 100644 index 00000000..9b2cdb1d --- /dev/null +++ b/Sources/TesseraEngine/EngineSystemServices.swift @@ -0,0 +1,174 @@ +public import AppKit +import QuartzCore +public import TesseraAnimation +public import TesseraConfig +public import TesseraCore +import os + +@MainActor +public final class SystemEngineClock: EngineClock { + public init() {} + public var now: Double { CACurrentMediaTime() } +} + +@MainActor +public final class RunLoopEngineScheduler: EngineScheduler { + public init() {} + public func schedule(after delay: Double, _ action: @escaping @MainActor () -> Void) -> any EngineCancellation { + precondition(delay.isFinite && delay >= 0) + let cancellation = ScheduledEngineWork() + let work = DispatchWorkItem { [weak cancellation] in + MainActor.assumeIsolated { + guard let cancellation, !cancellation.cancelled else { return } + cancellation.work = nil + action() + } + } + cancellation.work = work + if delay == 0 { + DispatchQueue.main.async(execute: work) + } else { + DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: work) + } + return cancellation + } +} + +@MainActor +private final class ScheduledEngineWork: EngineCancellation { + var work: DispatchWorkItem? + var cancelled = false + func cancel() { + cancelled = true + work?.cancel() + work = nil + } + isolated deinit { cancel() } +} + +@MainActor +public final class ScreenEngineDisplayLink: NSObject, EngineDisplayLink { + private let screen: NSScreen + private var link: CADisplayLink? + private var callback: (@MainActor (Double) -> Void)? + public var isRunning: Bool { link != nil } + + public init(screen: NSScreen) { self.screen = screen } + public func start(tick: @escaping @MainActor (Double) -> Void) { + guard link == nil else { return } + callback = tick + let relay = EngineDisplayLinkRelay(owner: self) + let link = screen.displayLink(target: relay, selector: #selector(EngineDisplayLinkRelay.tick(_:))) + self.link = link + link.add(to: .main, forMode: .common) + } + public func stop() { + link?.invalidate() + link = nil + callback = nil + } + fileprivate func tick(_ link: CADisplayLink) { callback?(link.targetTimestamp) } + isolated deinit { stop() } +} + +@MainActor +private final class EngineDisplayLinkRelay: NSObject { + weak var owner: ScreenEngineDisplayLink? + init(owner: ScreenEngineDisplayLink) { self.owner = owner } + @objc func tick(_ link: CADisplayLink) { owner?.tick(link) } +} + +@MainActor +public final class SystemEngineReduceMotionSource: ReduceMotionSource { + private var observer: (any NSObjectProtocol)? + public init() {} + public var isEnabled: Bool { NSWorkspace.shared.accessibilityDisplayShouldReduceMotion } + public func start(changed: @escaping @MainActor () -> Void) { + stop() + observer = NSWorkspace.shared.notificationCenter.addObserver( + forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil, queue: .main + ) { _ in Task { @MainActor in changed() } } + } + public func stop() { + if let observer { NSWorkspace.shared.notificationCenter.removeObserver(observer) } + observer = nil + } + isolated deinit { stop() } +} + +@MainActor +public final class AccessibilityEngineAnnouncer: EngineAnnouncer { + private let localize: @MainActor (Announcement) -> String + public init(localize: @escaping @MainActor (Announcement) -> String) { self.localize = localize } + public func announce(_ announcement: Announcement) { + NSAccessibility.post( + element: NSApplication.shared, notification: .announcementRequested, + userInfo: [ + .announcement: localize(announcement), .priority: NSAccessibilityPriorityLevel.medium.rawValue, + ]) + } +} + +@MainActor +public final class SystemEngineLog: EngineLogSink { + private let logger = Logger(subsystem: "com.tessera", category: "engine") + public init() {} + public func record(_ diagnostic: EngineDiagnostic) { + logger.error("\(String(describing: diagnostic), privacy: .public)") + } +} + +@MainActor +public final class SignpostEngineTrace: EngineTraceSink { + private let log = OSLog(subsystem: "com.tessera", category: .pointsOfInterest) + public let isEnabled: Bool + public init(enabled: Bool = ProcessInfo.processInfo.environment["TESSERA_TRACE"] == "1") { isEnabled = enabled } + public func begin(_ stage: EngineTraceStage, transaction: UInt64) { + guard isEnabled else { return } + os_signpost(.begin, log: log, name: stage.name, signpostID: OSSignpostID(transaction)) + } + public func end(_ stage: EngineTraceStage, transaction: UInt64) { + guard isEnabled else { return } + os_signpost(.end, log: log, name: stage.name, signpostID: OSSignpostID(transaction)) + } +} + +extension EngineTraceStage { + fileprivate var name: StaticString { + switch self { + case .eventToFirstWrite: "Event to first write" + case .eventToSettled: "Event to settled" + case .reduce: "Reduce" + case .plan: "Plan" + case .write: "Write" + } + } +} + +@MainActor +public final class ConfigStoreEngineSource: EngineConfigurationSource { + public let store: ConfigStore + private var task: Task? + public init(store: ConfigStore) { self.store = store } + public func start(changed: @escaping @MainActor (ConfigSnapshot) -> Void) async throws -> TesseraConfiguration { + try await store.startWatching() + let initial = await store.reload() + let updates = await store.updates() + task?.cancel() + task = Task { @MainActor in + for await update in updates { + guard !Task.isCancelled else { return } + changed(update) + } + } + return initial.activeConfiguration + } + public func stop() async { + let previous = task + task = nil + previous?.cancel() + await previous?.value + await store.stopWatching() + } + isolated deinit { task?.cancel() } +} diff --git a/Sources/TesseraEngine/NativeEngineWorld.swift b/Sources/TesseraEngine/NativeEngineWorld.swift new file mode 100644 index 00000000..fca93bc8 --- /dev/null +++ b/Sources/TesseraEngine/NativeEngineWorld.swift @@ -0,0 +1,375 @@ +public import AppKit +import ApplicationServices +public import TesseraCore +import TesseraPlatform + +@MainActor +public final class NativeEngineWorld: EngineWindowWorld { + private let displays = Displays() + private let applicationFilter: @MainActor (NSRunningApplication) -> Bool + private var receive: (@MainActor (EnginePlatformEvent) -> Void)? + private var threads: [AppID: AppThread] = [:] + private var tasks: [AppID: Task] = [:] + private var displayTask: Task? + private var spaceTask: Task? + private var observers: [any NSObjectProtocol] = [] + private var windowApps: [WindowID: AppID] = [:] + private var knownFrames: [WindowID: Rect] = [:] + private var screenFrames: [DisplayID: Rect] = [:] + private var spaces: [DisplayID: SpaceID] = [:] + private var lifetime: UInt64 = 0 + + public init(applicationFilter: @escaping @MainActor (NSRunningApplication) -> Bool = { _ in true }) { + self.applicationFilter = applicationFilter + } + + public func start(receive: @escaping @MainActor (EnginePlatformEvent) -> Void) throws { + guard self.receive == nil else { return } + guard Permissions.accessibilityStatus() == .granted else { throw EnginePlatformFailure.permissionLost } + self.receive = receive + lifetime += 1 + updateDisplays(try displays.current()) + let names: [Notification.Name] = [ + NSWorkspace.didLaunchApplicationNotification, NSWorkspace.didTerminateApplicationNotification, + NSWorkspace.didActivateApplicationNotification, NSWorkspace.didHideApplicationNotification, + NSWorkspace.didUnhideApplicationNotification, NSWorkspace.activeSpaceDidChangeNotification, + ] + for name in names { + observers.append( + NSWorkspace.shared.notificationCenter.addObserver(forName: name, object: nil, queue: .main) { + [weak self] _ in + Task { @MainActor in + self?.refreshApplications() + self?.refreshSpaces() + } + }) + } + refreshApplications() + let changes = displays.changes() + displayTask = Task { @MainActor [weak self] in + do { + for try await update in changes { + guard !Task.isCancelled else { return } + self?.updateDisplays(update) + } + } catch { self?.receive?(.failure(.failed(String(describing: error)))) } + } + } + + public func stop() { + lifetime += 1 + receive = nil + for observer in observers { NSWorkspace.shared.notificationCenter.removeObserver(observer) } + observers.removeAll() + displayTask?.cancel() + displayTask = nil + spaceTask?.cancel() + spaceTask = nil + for task in tasks.values { task.cancel() } + tasks.removeAll() + for thread in threads.values { thread.shutdown() } + threads.removeAll() + windowApps.removeAll() + knownFrames.removeAll() + } + + isolated deinit { stop() } + + public func write( + _ frames: [EngineFrameWrite], for app: AppID, completion: @escaping @MainActor (EngineWriteReceipt) -> Void + ) { + guard let thread = threads[app] else { + completion(EngineWriteReceipt(frames: [], failures: frames.map { .vanished($0.window) }, duration: 0)) + return + } + Task { @MainActor in + let started = ProcessInfo.processInfo.systemUptime + var actual: [WindowFrame] = [] + var failures: [EnginePlatformFailure] = [] + for write in frames { + do { + let frame = try await thread.writeFrame(windowID: write.window.rawValue, target: write.frame.cgRect) + actual.append(WindowFrame(window: write.window, frame: Rect(frame))) + } catch { failures.append(Self.failure(error, app: app, window: write.window)) } + } + completion( + EngineWriteReceipt( + frames: actual, failures: failures, duration: ProcessInfo.processInfo.systemUptime - started)) + } + } + + public func focus(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { + guard let app = windowApps[window], let thread = threads[app], + let running = NSRunningApplication(processIdentifier: app.pid) + else { + completion(.vanished(window)) + return + } + guard running.activate(options: []) else { + completion(.failed("Application activation was refused")) + return + } + Task { @MainActor in + do { + try await thread.perform { application in + let target = try Self.find(window, in: application) + try target.setMain(true) + try application.setFocusedWindow(target) + guard try application.focusedWindow.windowID() == window.rawValue else { + throw EnginePlatformFailure.failed("Window focus did not change") + } + } + completion(nil) + } catch { completion(Self.failure(error, app: app, window: window)) } + } + } + + public func raise(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { + guard let app = windowApps[window], let thread = threads[app] else { + completion(.vanished(window)) + return + } + Task { @MainActor in + do { + try await thread.perform { application in try Self.find(window, in: application).raise() } + completion(nil) + } catch { completion(Self.failure(error, app: app, window: window)) } + } + } + + public func displayLink(for display: DisplayID) throws -> any EngineDisplayLink { + for screen in NSScreen.screens { + guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber, + let uuid = CGDisplayCreateUUIDFromDisplayID(number.uint32Value)?.takeRetainedValue(), + let string = CFUUIDCreateString(nil, uuid) + else { continue } + if (string as String).caseInsensitiveCompare(display.rawValue) == .orderedSame { + return ScreenEngineDisplayLink(screen: screen) + } + } + throw EnginePlatformFailure.failed("No display link is available for \(display.rawValue)") + } + + private func updateDisplays(_ updated: [TesseraPlatform.Display]) { + let height = CGDisplayBounds(CGMainDisplayID()).height + let core = updated.map { display in + TesseraCore.Display( + id: DisplayID(rawValue: display.id.uuidString), + frame: Rect( + x: display.visibleFrame.minX, y: height - display.visibleFrame.maxY, + width: display.visibleFrame.width, height: display.visibleFrame.height)) + } + screenFrames = Dictionary(uniqueKeysWithValues: core.map { ($0.id, $0.frame) }) + receive?(.observed(.displaySetChanged(core))) + refreshSpaces() + } + + private func refreshApplications() { + guard receive != nil else { return } + let applications = NSWorkspace.shared.runningApplications.filter { + $0.processIdentifier != ProcessInfo.processInfo.processIdentifier && $0.activationPolicy == .regular + && !$0.isTerminated && applicationFilter($0) + } + let apps = Set(applications.map { AppID(pid: $0.processIdentifier, bundleID: $0.bundleIdentifier ?? "") }) + for app in threads.keys where !apps.contains(app) { + tasks[app]?.cancel() + tasks[app] = nil + threads[app]?.shutdown() + threads[app] = nil + receive?(.appExited(app)) + for window in windowApps.keys where windowApps[window] == app { + windowApps[window] = nil + knownFrames[window] = nil + } + } + for app in apps where threads[app] == nil { + do { + let thread = try AppThread(pid: app.pid, reconcileWhileIdle: false) + threads[app] = thread + let generation = lifetime + tasks[app] = Task { @MainActor [weak self] in + await self?.refresh(app) + for await event in thread.events { + guard !Task.isCancelled, let self, self.receive != nil, self.lifetime == generation else { + return + } + await self.handle(event, app: app) + } + } + if applications.first(where: { $0.processIdentifier == app.pid })?.launchDate.map({ + Date().timeIntervalSince($0) < 1.5 + }) == true { + receive?(.appLaunched(app, at: ProcessInfo.processInfo.systemUptime)) + } + } catch { receive?(.failure(.failed(String(describing: error)))) } + } + } + + private func refreshSpaces() { + guard receive != nil else { return } + spaceTask?.cancel() + let ids = screenFrames.keys.sorted() + let generation = lifetime + spaceTask = Task { @MainActor [weak self] in + do { + let updated = try await Task.detached { + try ids.map { id in (id, SpaceID(rawValue: try WindowServer().currentSpace(displayID: id.rawValue))) + } + }.value + guard !Task.isCancelled, let self, self.receive != nil, self.lifetime == generation else { return } + for (display, space) in updated { + self.spaces[display] = space + self.receive?(.observed(.activeSpaceChanged(display: display, space: space))) + } + let apps = Array(self.threads.keys) + await withTaskGroup(of: Void.self) { group in + for app in apps { group.addTask { [weak self] in await self?.refresh(app) } } + } + } catch { + guard !Task.isCancelled else { return } + self?.receive?(.failure(.failed(String(describing: error)))) + } + } + } + + private func refresh(_ app: AppID) async { + guard let thread = threads[app] else { return } + let generation = lifetime + do { + let onscreen = try await Task.detached { + Set(try WindowServer().windows(options: .optionOnScreenOnly).map(\.number)) + }.value + let windows = try await thread.perform { application in + try application.windows.map { try Self.read($0, app: app) } + } + guard receive != nil, lifetime == generation else { return } + let present = Set(windows.map(\.window.id)) + for window in windowApps.keys where windowApps[window] == app && !present.contains(window) { + windowApps[window] = nil + knownFrames[window] = nil + receive?(.observed(.windowDisappeared(window))) + } + for window in windows where onscreen.contains(window.window.id.rawValue) { observe(window) } + } catch { + guard lifetime == generation, !Task.isCancelled else { return } + receive?(.failure(Self.failure(error, app: app))) + } + } + + private func handle(_ event: AppThreadEvent, app: AppID) async { + let generation = lifetime + switch event { + case .windowDestroyed(let raw), .windowMinimized(let raw): + let id = WindowID(rawValue: raw) + windowApps[id] = nil + knownFrames[id] = nil + receive?(.observed(.windowDisappeared(id))) + case .windowMoved(let raw, _), .windowResized(let raw, _): + guard let thread = threads[app] else { return } + do { + let id = WindowID(rawValue: raw) + let frame = try await thread.perform { application in try Self.find(id, in: application).frame } + guard lifetime == generation, receive != nil, !Task.isCancelled else { return } + let resized: Bool + if case .windowResized = event { resized = true } else { resized = false } + knownFrames[id] = Rect(frame) + receive?(.frameChanged(id, frame: Rect(frame), resized: resized, origin: .unknown)) + } catch { + guard lifetime == generation, !Task.isCancelled else { return } + receive?(.failure(Self.failure(error, app: app, window: WindowID(rawValue: raw)))) + } + case .focusedWindowChanged, .applicationActivated: + guard let thread = threads[app] else { return } + do { + let id = try await thread.perform { application in + try Self.optional { try application.focusedWindow.windowID() } + } + guard lifetime == generation, receive != nil, !Task.isCancelled else { return } + receive?(.observed(.focusChanged(id.map { WindowID(rawValue: $0) }))) + } catch { + guard lifetime == generation, !Task.isCancelled else { return } + receive?(.failure(Self.failure(error, app: app))) + } + case .windowCreated, .windowDeminimized, .windowTitleChanged, .windowList, .reconciliation: + await refresh(app) + case .applicationTerminated: + receive?(.appExited(app)) + case .unresponsive: receive?(.failure(.timedOut(app))) + case .failure(let failure): receive?(.failure(.failed(String(describing: failure)))) + case .responsive, .applicationDeactivated: break + } + } + + private func observe(_ observed: NativeWindowSnapshot) { + let window = observed.window + windowApps[window.id] = window.app + knownFrames[window.id] = observed.frame + if observed.excluded { + receive?(.observed(.windowDisappeared(window.id))) + return + } + guard + let display = screenFrames.keys.sorted().max(by: { + Self.intersection(screenFrames[$0], observed.frame) + < Self.intersection(screenFrames[$1], observed.frame) + }), let space = spaces[display] + else { return } + receive?( + .observed( + .windowAppeared(window, workspace: WorkspaceKey(display: display, space: space), frame: observed.frame)) + ) + } + + nonisolated private static func intersection(_ screen: Rect?, _ frame: Rect) -> Double { + guard let screen else { return 0 } + return max(0, min(screen.maxX, frame.maxX) - max(screen.minX, frame.minX)) + * max(0, min(screen.maxY, frame.maxY) - max(screen.minY, frame.minY)) + } + + nonisolated private static func find(_ window: WindowID, in application: AXElement) throws -> AXElement { + for candidate in try application.windows where try candidate.windowID() == window.rawValue { return candidate } + throw EnginePlatformFailure.vanished(window) + } + + nonisolated private static func optional(_ read: () throws -> Value) throws -> Value? { + do { return try read() } catch AXPlatformError.attributeUnsupported, AXPlatformError.noValue { return nil } + } + + nonisolated private static func read(_ element: AXElement, app: AppID) throws -> NativeWindowSnapshot { + let id = WindowID(rawValue: try element.windowID()) + let subrole = try optional { try element.subrole } + let window = ManagedWindow( + id: id, app: app, title: try optional { try element.title } ?? "", role: try element.role, + subrole: subrole, isFloating: subrole != nil && subrole != "AXStandardWindow") + return NativeWindowSnapshot( + window: window, frame: Rect(try element.frame), + excluded: try (optional { try element.minimized } == true) || (optional { try element.fullscreen } == true)) + } + + nonisolated private static func failure(_ error: any Error, app: AppID, window: WindowID? = nil) + -> EnginePlatformFailure + { + if let failure = error as? EnginePlatformFailure { return failure } + if let error = error as? AXPlatformError { + switch error { + case .notPermitted: return .permissionLost + case .timedOut: return .timedOut(app) + case .elementInvalid: if let window { return .vanished(window) } + default: break + } + } + if case AppThreadFailure.windowNotFound(let raw) = error { return .vanished(WindowID(rawValue: raw)) } + return .failed(String(describing: error)) + } +} + +private struct NativeWindowSnapshot: Sendable { + let window: ManagedWindow + let frame: Rect + let excluded: Bool +} + +extension Rect { + var cgRect: CGRect { CGRect(x: minX, y: minY, width: size.width, height: size.height) } + init(_ frame: CGRect) { self.init(x: frame.minX, y: frame.minY, width: frame.width, height: frame.height) } +} diff --git a/Sources/TesseraEngine/Resources/Localizable.xcstrings b/Sources/TesseraEngine/Resources/Localizable.xcstrings new file mode 100644 index 00000000..20ee3e42 --- /dev/null +++ b/Sources/TesseraEngine/Resources/Localizable.xcstrings @@ -0,0 +1,10 @@ +{ + "sourceLanguage" : "en", + "strings" : { + "This command is handled by the app shell." : {}, + "The command or its arguments are invalid." : {}, + "No configuration store is connected." : {}, + "The configuration was rejected. The last good configuration is still active." : {} + }, + "version" : "1.0" +} diff --git a/Sources/TesseraEngine/Resources/en.lproj/Localizable.strings b/Sources/TesseraEngine/Resources/en.lproj/Localizable.strings new file mode 100644 index 00000000..5e6857d0 --- /dev/null +++ b/Sources/TesseraEngine/Resources/en.lproj/Localizable.strings @@ -0,0 +1,4 @@ +"This command is handled by the app shell." = "This command is handled by the app shell."; +"The command or its arguments are invalid." = "The command or its arguments are invalid."; +"No configuration store is connected." = "No configuration store is connected."; +"The configuration was rejected. The last good configuration is still active." = "The configuration was rejected. The last good configuration is still active."; diff --git a/Sources/TesseraEngine/TesseraEngine.docc/TesseraEngine.md b/Sources/TesseraEngine/TesseraEngine.docc/TesseraEngine.md new file mode 100644 index 00000000..035a9a22 --- /dev/null +++ b/Sources/TesseraEngine/TesseraEngine.docc/TesseraEngine.md @@ -0,0 +1,37 @@ +# ``TesseraEngine`` + +The main-actor reactor owns logical state, not AX objects. Observations queued in one run-loop turn use Core's batched reducer, then one target diff and motion-planning pass. Commands use the same queue. + +## Composition + +Create a `NativeEngineWorld`, `SystemEngineClock`, and `RunLoopEngineScheduler`. Supply the world's `displayLink(for:)` as the display-link factory. `ConfigStoreEngineSource` connects a `ConfigStore`; `EngineIPCHandler` connects IPC. The app shell still owns startup, permission onboarding, the IPC server, and localized announcement text. + +Call `start()` before accepting commands and `stop()` before releasing the composition. `perform(_:)` returns after logical state and frame-0 scheduling, not after AX confirms a frame. Its result contains event-specific reports and an acceptance flag. Canceling a queued command removes it; cancellation after acceptance is not an undo. + +`snapshots()` includes the current value and buffers only the newest value. `EngineSnapshot` carries active-display layouts, visible tile targets, focus, and the full Core state. No frames are published just because an animation ticks. + +## Motion and writes + +`Animator` supplies final size at frame 0 and position-only glide. A shared `FrameCoalescer` permits one outstanding batch per app, carries generations across display transfers, and replaces pending targets. Actual readbacks drive the final diff. Logical focus does not wait for a slow app or an animation. + +System Reduce Motion is observed automatically. Explicit Reduce Motion can strengthen that policy. Disabled motion, Calm, snap transitions, Space switches, and display changes snap. Ghost transitions snap real windows; the shell can animate its own chrome separately. Launch age, timeouts, and measured app-batch latency feed Animation's snap and rate policies. `writeMetrics` is inspectable; `resetWriteMetrics(for:)` clears it. + +Unknown move/resize events match a bounded, half-second ring of recent writes, including size-before-position intermediates. Explicit user events are never suppressed. A plain tiled drag preserves tile order and returns to its tile; a floating drag keeps its exact frame. + +A refused final frame is reported. Two matching size refusals establish a versioned Core minimum; an accepted final frame clears the pending candidate. Send `minimumSizeChanged` with `nil` to reset learned data. Minimum conflicts use Core's on-screen target and `cannotFit` report instead of making Animation shrink a window silently. + +## Configuration and protocol decisions + +Hot reload updates workspace defaults only when that display's layout configuration changes. An unrelated reload does not overwrite a layout chosen by a command. Float-rule matchers are ANDed within a rule and ORed across rules; removing a rule restores the observed floating classification. Invalid configurations leave the active value unchanged and reach the log sink. + +Config accepts ratios from 0.1 through 0.9; Core supports 0.2 through 0.8. The engine reports that mismatch and applies Core's clamped ratio. Unlimited config window caps map to `Int.max`. + +IPC `workspaces` includes layouts and tile trees. `config` includes the path and app version; IPCServer handles the protocol's separate version command. Space IDs and revisions are decimal strings to preserve all 64 bits. Pass the same app version to the handler and server. `EngineCommandParser.command(_:)` maps configurable actions to the same Core commands used by IPC. The settings action stays with the shell. + +## Native boundary and idle + +`NativeEngineWorld` discovers regular apps, consumes per-app AX streams, debounced display snapshots, and workspace notifications. It assigns only on-screen windows to the current native Space and retains dormant Core workspaces. AX reads, focus, raise, and writes stay on each app's `AppThread`. Window-server reads run off the main actor. `applicationFilter` can restrict a fixture or an embedded composition. + +The engine schedules only run-loop turns and one-shot rate-limit deadlines while work is pending. Display links stop when motion ends. Native app threads opt out of periodic idle reconciliation; window, application, display, and Space activity trigger snapshots instead. This trades timer-based recovery from completely missing notifications for zero idle polling. + +Set `TESSERA_TRACE=1` for event-to-first-write, reduction, planning, per-app write, and event-to-settled signpost intervals. Stop and app-exit paths close outstanding intervals too. Hardware latency budgets still need measurements with an Accessibility-granted runner; deterministic tests establish ordering and scheduling, not real AX latency. diff --git a/Sources/TesseraEngine/TesseraEngine.swift b/Sources/TesseraEngine/TesseraEngine.swift index 8b137891..ac2857fa 100644 --- a/Sources/TesseraEngine/TesseraEngine.swift +++ b/Sources/TesseraEngine/TesseraEngine.swift @@ -1 +1,723 @@ +import Foundation +public import TesseraAnimation +public import TesseraConfig +public import TesseraCore +@MainActor +public final class TesseraEngine { + public private(set) var snapshot: EngineSnapshot + public private(set) var configuration: TesseraConfiguration + public private(set) var isRunning = false + public private(set) var layoutPassCount = 0 + public var isIdle: Bool { + !isStarting && !isFlushing && !pumping && queue.isEmpty && turn == nil && pumpWake == nil + && animators.values.allSatisfy(\.isIdle) + && coalescer.pendingCount == 0 && coalescer.inFlightCount == 0 && focusOperations == 0 + } + public var writeMetrics: [MotionAppID: AppWriteMetrics] { coalescer.metricsSnapshot } + + private struct Pending { + let event: Event + let reply: CheckedContinuation? + var commandID: UUID? = nil + } + private struct Echo { + let frame: Rect + let transaction: UInt64 + let time: Double + } + private let world: any EngineWindowWorld + private let clock: any EngineClock + private let scheduler: any EngineScheduler + private let makeDisplayLink: @MainActor (DisplayID) throws -> any EngineDisplayLink + private let announcer: any EngineAnnouncer + private let log: any EngineLogSink + private let trace: (any EngineTraceSink)? + private let configSource: (any EngineConfigurationSource)? + private let reduceMotionSource: (any ReduceMotionSource)? + private var applied: AppliedConfiguration + private var queue: [Pending] = [] + private var turn: (any EngineCancellation)? + private var pumpWake: (any EngineCancellation)? + private var animators: [DisplayID: Animator] = [:] + private var links: [DisplayID: any EngineDisplayLink] = [:] + private var coalescer = FrameCoalescer() + private var pendingFrames: [MotionWindowID: MotionFrame] = [:] + private var busyApps: Set = [] + private var activeBatches: [MotionAppID: UInt64] = [:] + private var writesPermitted = true + private var isStarting = false + private var isFlushing = false + private var lastDispatch: [MotionAppID: Double] = [:] + private var actualFrames: [WindowID: Rect] = [:] + private var targets: [WindowID: Rect] = [:] + private var placements: [WindowID: DisplayID] = [:] + private var echoes: [WindowID: [Echo]] = [:] + private var intrinsicFloating: [WindowID: Bool] = [:] + private var minimumCandidates: [WindowID: (size: Size, confirmations: Int)] = [:] + private var subscribers: [UUID: AsyncStream.Continuation] = [:] + private var revision: UInt64 = 0 + private var lifetime: UInt64 = 0 + private var focusOperations = 0 + private var pumping = false + private var reduceMotion = false + private var snapNextPass = false + private var needsRetile = false + private var traced: Set = [] + private var firstWriteTraces: Set = [] + private var openWrites: Set = [] + + public init( + world: any EngineWindowWorld, clock: any EngineClock, scheduler: any EngineScheduler, + displayLink: @escaping @MainActor (DisplayID) throws -> any EngineDisplayLink, + announcer: any EngineAnnouncer, log: any EngineLogSink, + configuration: TesseraConfiguration = .defaults, initialState: State = State(), + configSource: (any EngineConfigurationSource)? = nil, trace: (any EngineTraceSink)? = SignpostEngineTrace(), + reduceMotionSource: (any ReduceMotionSource)? = SystemEngineReduceMotionSource() + ) throws { + self.world = world + self.clock = clock + self.scheduler = scheduler + self.makeDisplayLink = displayLink + self.announcer = announcer + self.log = log + self.configSource = configSource + self.trace = trace + self.reduceMotionSource = reduceMotionSource + reduceMotion = reduceMotionSource?.isEnabled == true + self.configuration = configuration + applied = try AppliedConfiguration(configuration) + var state = initialState + for key in state.workspaces.keys { + state.workspaces[key] = applied.workspace(key, existing: state.workspaces[key]) + } + snapshot = EngineSnapshot(revision: 0, state: state) + actualFrames = state.observedFrames.merging(state.frames) { observed, _ in observed } + intrinsicFloating = state.windows.mapValues(\.isFloating) + reportRatioBounds() + } + + public func start() async throws { + guard !isRunning else { return } + guard !isStarting else { throw EngineError.startInProgress } + lifetime += 1 + let generation = lifetime + isStarting = true + writesPermitted = true + reduceMotionSource?.start { [weak self] in + guard let self else { return } + self.setReduceMotion(self.reduceMotionSource?.isEnabled == true) + } + do { + if let configSource { + let initial = try await configSource.start { [weak self] update in + guard let self, self.isStarting || self.isRunning, self.lifetime == generation else { return } + do { try self.applyConfigSnapshot(update) } catch { + self.log.record(.configuration(String(describing: error))) + } + } + guard isStarting, lifetime == generation else { throw EngineError.stopped } + try applyConfiguration(initial) + } + try world.start { [weak self] event in + guard let self, self.isStarting || self.isRunning, self.lifetime == generation else { return } + self.receive(event) + } + isStarting = false + isRunning = true + needsRetile = true + scheduleTurn() + } catch { + if lifetime == generation { await stop() } + throw error + } + } + + public func stop() async { + isRunning = false + isStarting = false + lifetime += 1 + turn?.cancel() + turn = nil + pumpWake?.cancel() + pumpWake = nil + for link in links.values { link.stop() } + links.removeAll() + animators.removeAll() + coalescer = FrameCoalescer() + pendingFrames.removeAll() + busyApps.removeAll() + activeBatches.removeAll() + for transaction in openWrites { trace?.end(.write, transaction: transaction) } + openWrites.removeAll() + lastDispatch.removeAll() + targets.removeAll() + placements.removeAll() + echoes.removeAll() + focusOperations = 0 + world.stop() + reduceMotionSource?.stop() + for pending in queue { pending.reply?.resume(throwing: EngineError.stopped) } + queue.removeAll() + needsRetile = false + finishTracing() + for subscriber in subscribers.values { subscriber.finish() } + subscribers.removeAll() + await configSource?.stop() + } + + isolated deinit { + turn?.cancel() + pumpWake?.cancel() + for link in links.values { link.stop() } + world.stop() + reduceMotionSource?.stop() + for pending in queue { pending.reply?.resume(throwing: EngineError.stopped) } + for subscriber in subscribers.values { subscriber.finish() } + } + + public func snapshots() -> AsyncStream { + let id = UUID() + let (stream, continuation) = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) + subscribers[id] = continuation + continuation.yield(snapshot) + continuation.onTermination = { [weak self] _ in + Task { @MainActor in self?.subscribers[id] = nil } + } + return stream + } + + public func send(_ event: Event) { + guard isRunning else { return } + enqueue(event) + } + + public func perform(_ command: Command) async throws -> EngineCommandResult { + guard isRunning else { throw EngineError.stopped } + try Task.checkCancellation() + let id = UUID() + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { reply in + guard !Task.isCancelled else { + reply.resume(throwing: CancellationError()) + return + } + queue.append(Pending(event: .commandIssued(command), reply: reply, commandID: id)) + scheduleTurn() + } + } onCancel: { + Task { @MainActor [weak self] in self?.cancelCommand(id) } + } + } + + private func cancelCommand(_ id: UUID) { + guard let index = queue.firstIndex(where: { $0.commandID == id }) else { return } + queue.remove(at: index).reply?.resume(throwing: CancellationError()) + if queue.isEmpty && !needsRetile { + turn?.cancel() + turn = nil + settleIfIdle() + } + } + + public func applyConfigSnapshot(_ snapshot: ConfigSnapshot) throws { + if !snapshot.diagnostics.isEmpty { log.record(.config(snapshot.diagnostics)) } + try applyConfiguration(snapshot.activeConfiguration) + } + + public func applyConfiguration(_ configuration: TesseraConfiguration) throws { + let updated = try AppliedConfiguration(configuration) + guard configuration != self.configuration else { return } + var state = snapshot.state + for key in state.workspaces.keys where applied.values(for: key.display) != updated.values(for: key.display) { + state.workspaces[key] = updated.workspace(key, existing: state.workspaces[key]) + } + if configuration.floatRules != self.configuration.floatRules { + for window in state.windows.values { + guard let key = state.workspace(containing: window.id), + let frame = actualFrames[window.id] ?? state.frames[window.id] + else { continue } + var observed = window + observed.isFloating = intrinsicFloating[window.id] ?? window.isFloating + queue.append(Pending(event: .windowAppeared(observed, workspace: key, frame: frame), reply: nil)) + } + } + applied = updated + self.configuration = configuration + reportRatioBounds() + snapshot = EngineSnapshot(revision: revision, state: state) + needsRetile = true + if isRunning { scheduleTurn() } + } + + private func reportRatioBounds() { + for values in [configuration.layout.global] + Array(configuration.layout.displays.values) + where !MainRatio.bounds.contains(values.ratio) { + log.record(.configuration("Layout ratio \(values.ratio) is clamped to \(MainRatio(values.ratio).value)")) + } + } + + public func setReduceMotion(_ enabled: Bool) { + guard reduceMotion != enabled else { return } + reduceMotion = enabled + updateMotion() + } + + public func resetWriteMetrics(for app: AppID) { coalescer.resetMetrics(for: app.motionID) } + + private func receive(_ event: EnginePlatformEvent) { + switch event { + case .observed(let event): enqueue(event) + case .frameChanged(let window, let frame, let resized, let origin): + guard !isEcho(window, frame: frame, origin: origin) else { return } + cancelMotion(window, remove: false) + enqueue(resized ? .windowResizedByUser(window, frame: frame) : .windowMovedByUser(window, frame: frame)) + case .appLaunched(let app, let timestamp): + guard timestamp.isFinite else { + log.record(.configuration("Invalid application launch timestamp")) + return + } + coalescer.setMetrics(AppWriteMetrics(launchedAt: timestamp), for: app.motionID) + case .appExited(let app): + let windows = + snapshot.state.windows.values.filter { $0.app == app }.map(\.id) + + queue.compactMap { pending in + if case .windowAppeared(let window, _, _) = pending.event, window.app == app { return window.id } + return nil + } + for window in Set(windows) { enqueue(.windowDisappeared(window)) } + coalescer.removeApp(app.motionID) + busyApps.remove(app.motionID) + if let batch = activeBatches.removeValue(forKey: app.motionID), openWrites.remove(batch) != nil { + trace?.end(.write, transaction: batch) + } + case .failure(let failure): handle(failure) + } + } + + private func enqueue(_ event: Event) { + queue.append(Pending(event: event, reply: nil)) + scheduleTurn() + } + + private func scheduleTurn() { + guard isRunning, turn == nil else { return } + let transaction = revision + 1 + traced.insert(transaction) + firstWriteTraces.insert(transaction) + trace?.begin(.eventToFirstWrite, transaction: transaction) + trace?.begin(.eventToSettled, transaction: transaction) + turn = scheduler.schedule(after: 0) { [weak self] in + self?.turn = nil + self?.flush() + } + } + + private func flush() { + guard isRunning else { return } + isFlushing = true + defer { + isFlushing = false + settleIfIdle() + } + let pending = queue + queue.removeAll(keepingCapacity: true) + var state = snapshot.state + var events: [Event] = [] + for item in pending { + var event = item.event + switch event { + case .windowAppeared(var window, let key, let frame): + if intrinsicFloating[window.id] == nil { intrinsicFloating[window.id] = window.isFloating } + window.isFloating = window.isFloating || applied.floats(window) + event = .windowAppeared(window, workspace: key, frame: frame) + if state.workspaces[key] == nil { state.workspaces[key] = applied.workspace(key) } + actualFrames[window.id] = frame + case .activeSpaceChanged(let display, let space): + let key = WorkspaceKey(display: display, space: space) + if state.workspaces[key] == nil { state.workspaces[key] = applied.workspace(key) } + snapNextPass = snapNextPass || state.activeSpaces[display] != space + case .displaySetChanged(let displays): + snapNextPass = + snapNextPass || state.displays.values.sorted { $0.id < $1.id } != displays.sorted { $0.id < $1.id } + case .windowMovedByUser(let window, let frame), .windowResizedByUser(let window, let frame): + actualFrames[window] = frame + cancelMotion(window, remove: false) + case .windowDisappeared(let window): cancelMotion(window, remove: true) + case .minimumSizeChanged(let window, _): minimumCandidates[window] = nil + default: break + } + events.append(event) + } + if needsRetile && events.isEmpty { events.append(.focusChanged(state.focusedWindow)) } + needsRetile = false + guard !events.isEmpty else { + settleIfIdle() + return + } + revision += 1 + trace?.begin(.reduce, transaction: revision) + let (next, effectsByEvent) = reduce(state, events) + trace?.end(.reduce, transaction: revision) + layoutPassCount += 1 + snapshot = EngineSnapshot(revision: revision, state: next) + for effect in effectsByEvent.flatMap({ $0 }) { + if case .announce(.floatingChanged(let window, let floating)) = effect { + intrinsicFloating[window] = floating + } + } + pruneMotion() + trace?.begin(.plan, transaction: revision) + planFrames() + trace?.end(.plan, transaction: revision) + snapNextPass = false + let effects = effectsByEvent.flatMap { $0 } + execute(effects) + for (index, item) in pending.enumerated() { + let reports = effectsByEvent[index].compactMap { effect -> Report? in + if case .report(let report) = effect { return report } + return nil + } + item.reply?.resume( + returning: EngineCommandResult( + revision: revision, reports: reports, isAccepted: !reports.contains(where: \.isFailure))) + } + for subscriber in subscribers.values { subscriber.yield(snapshot) } + settleIfIdle() + } + + private func planFrames() { + guard writesPermitted else { return } + let now = animationTime + updateMotion() + for window in snapshot.state.frames.keys.sorted() { + guard let managed = snapshot.state.windows[window], let key = snapshot.state.workspace(containing: window), + snapshot.state.isActive(key), let target = snapshot.state.frames[window], + let screen = snapshot.state.displays[key.display] + else { continue } + if targets[window] == target + && (actualFrames[window] == target + || animators[key.display]?.activeWindowIDs.contains(window.motionID) == true) + { + continue + } + if actualFrames[window] == target && targets[window] == nil { + targets[window] = target + continue + } + do { + if placements[window] != key.display { + cancelMotion(window, remove: false) + _ = coalescer.activate(window.motionID, appID: managed.app.motionID) + placements[window] = key.display + } + if coalescer.generation(for: window.motionID) == nil { + _ = coalescer.activate(window.motionID, appID: managed.app.motionID) + } + var animator = + animators[key.display] + ?? Animator( + policy: applied.motionPolicy(reduceMotion: reduceMotion, snap: snapNextPass), + settings: applied.motionSettings) + let minimum = managed.minimumSize ?? Size() + let request = MotionRequest( + windowID: window.motionID, appID: managed.app.motionID, + start: (actualFrames[window] ?? target).motionRect, target: target.motionRect, + screen: screen.frame.motionRect, + minimumSize: MotionSize( + width: min(minimum.width, target.size.width), height: min(minimum.height, target.size.height)), + metrics: coalescer.metricsSnapshot[managed.app.motionID] ?? AppWriteMetrics(), + generation: coalescer.generation(for: window.motionID) ?? 0 + ) + try animator.schedule([request], at: now) + targets[window] = target + animators[key.display] = animator + if links[key.display] == nil { links[key.display] = try makeDisplayLink(key.display) } + } catch { motionFailure(error, window: window) } + } + for display in animators.keys.sorted() { tick(display, at: now) } + } + + private var animationTime: Double { max(clock.now, animators.values.compactMap(\.timestamp).max() ?? clock.now) } + + private func updateMotion() { + let now = animationTime + for display in animators.keys { + do { + try animators[display]?.updatePolicy( + applied.motionPolicy(reduceMotion: reduceMotion, snap: snapNextPass), at: now) + try animators[display]?.updateSettings(applied.motionSettings, at: now) + } catch { motionFailure(error) } + } + if reduceMotion { for display in animators.keys.sorted() { tick(display, at: now) } } + } + + private func tick(_ display: DisplayID, at timestamp: Double) { + guard isRunning else { return } + do { + let now = max(timestamp, animationTime) + let frames = try animators[display]?.tick(at: now) ?? [] + for frame in frames where try coalescer.submit(frame) { pendingFrames[frame.windowID] = frame } + if animators[display]?.isIdle == true { + links[display]?.stop() + } else if links[display]?.isRunning == false { + links[display]?.start { [weak self] timestamp in self?.tick(display, at: timestamp) } + } + pump() + } catch { motionFailure(error) } + settleIfIdle() + } + + private func pump() { + guard isRunning, !pumping else { return } + pumping = true + pumpWake?.cancel() + pumpWake = nil + do { + for batch in try coalescer.takeReady(at: animationTime) { + busyApps.insert(batch.appID) + activeBatches[batch.appID] = batch.identifier + lastDispatch[batch.appID] = batch.dispatchedAt + for frame in batch.frames { pendingFrames[frame.windowID] = nil } + let writes = batch.frames.compactMap { frame -> EngineFrameWrite? in + guard let window = WindowID(exactly: frame.windowID), let managed = snapshot.state.windows[window], + managed.app.motionID == batch.appID + else { return nil } + let rect = Rect(frame.rect) + guard actualFrames[window] != rect else { return nil } + rememberEcho(window, frame: rect, transaction: batch.identifier) + return EngineFrameWrite(window: window, frame: rect, transaction: batch.identifier) + } + let generation = lifetime + if writes.isEmpty { + complete(batch, receipt: EngineWriteReceipt(frames: [], duration: 0), recordMetrics: false) + continue + } + guard let first = writes.first, let app = snapshot.state.windows[first.window]?.app else { continue } + for transaction in firstWriteTraces { trace?.end(.eventToFirstWrite, transaction: transaction) } + firstWriteTraces.removeAll() + openWrites.insert(batch.identifier) + trace?.begin(.write, transaction: batch.identifier) + world.write(writes, for: app) { [weak self] receipt in + guard let self, self.isRunning, self.lifetime == generation, + self.activeBatches[batch.appID] == batch.identifier + else { return } + self.openWrites.remove(batch.identifier) + self.trace?.end(.write, transaction: batch.identifier) + self.complete(batch, receipt: receipt) + } + } + } catch { motionFailure(error) } + pumping = false + schedulePumpIfNeeded() + } + + private func complete(_ batch: FrameBatch, receipt: EngineWriteReceipt, recordMetrics: Bool = true) { + do { + let previousMetrics = coalescer.metricsSnapshot[batch.appID] + try coalescer.complete( + batch, duration: receipt.duration, + timedOut: receipt.failures.contains { if case .timedOut = $0 { true } else { false } }, + at: animationTime) + if !recordMetrics { + if let previousMetrics { + coalescer.setMetrics(previousMetrics, for: batch.appID) + } else { + coalescer.resetMetrics(for: batch.appID) + } + } + busyApps.remove(batch.appID) + activeBatches[batch.appID] = nil + for observed in receipt.frames { + guard let sent = batch.frames.first(where: { $0.windowID == observed.window.motionID }), + coalescer.generation(for: sent.windowID) == sent.generation + else { continue } + actualFrames[observed.window] = observed.frame + if sent.isFinal && !observed.frame.matches(Rect(sent.rect)) { + let old = snapshot.state.windows[observed.window]?.minimumSize ?? Size() + let requested = Rect(sent.rect) + let minimum = Size( + width: observed.frame.size.width > requested.size.width + 1 + ? observed.frame.size.width : old.width, + height: observed.frame.size.height > requested.size.height + 1 + ? observed.frame.size.height : old.height) + log.record(.platform(.failed("Window \(observed.window.rawValue) refused its target frame"))) + if minimum != old { + let previous = minimumCandidates[observed.window] + let confirmations = previous?.size == minimum ? (previous?.confirmations ?? 0) + 1 : 1 + minimumCandidates[observed.window] = (minimum, confirmations) + if confirmations >= 2 { + enqueue(.minimumSizeChanged(observed.window, minimum: LearnedMinimumSize(size: minimum))) + } + } + } else if sent.isFinal { + minimumCandidates[observed.window] = nil + } + } + for failure in receipt.failures { + if case .vanished(let window) = failure, + let sent = batch.frames.first(where: { $0.windowID == window.motionID }), + coalescer.generation(for: sent.windowID) != sent.generation + { + continue + } + handle(failure) + } + } catch { + coalescer.removeApp(batch.appID) + busyApps.remove(batch.appID) + activeBatches[batch.appID] = nil + for window in snapshot.state.windows.values where window.app.motionID == batch.appID { + cancelMotion(window.id, remove: false) + } + if let motion = error as? MotionError { + log.record(.motion(motion)) + } else { + log.record(.configuration(String(describing: error))) + } + } + pump() + settleIfIdle() + } + + private func schedulePumpIfNeeded() { + guard pumpWake == nil, !pendingFrames.isEmpty, animators.values.allSatisfy(\.isIdle) else { return } + let now = animationTime + let apps = Set(pendingFrames.values.map(\.appID)).subtracting(busyApps) + let delays = apps.map { app in + let rate = + coalescer.metricsSnapshot[app]?.frameRate(fullRate: coalescer.fullFrameRate) ?? coalescer.fullFrameRate + return max(0, (lastDispatch[app] ?? now - 1 / rate) + 1 / rate - now) + } + guard let delay = delays.min() else { return } + pumpWake = scheduler.schedule(after: max(delay, 0.000_001)) { [weak self] in + self?.pumpWake = nil + self?.pump() + self?.settleIfIdle() + } + } + + private func execute(_ effects: [Effect]) { + var raised: Set = [] + for effect in effects { + switch effect { + case .setFrames: break + case .focusWindow(let window): + guard snapshot.focusedWindow == window else { continue } + focusEffect(window, raise: false) + case .raiseWindow(let window): + guard snapshot.state.visibleWindows.contains(window), raised.insert(window).inserted else { continue } + if window != snapshot.focusedWindow { focusEffect(window, raise: true) } + case .announce(let value): + if case .layoutChanged = value, !configuration.accessibility.announceLayoutChanges { continue } + if case .focused(let window) = value, snapshot.focusedWindow != window { continue } + announcer.announce(value) + case .report(let report): log.record(.core(report)) + } + } + if let focused = snapshot.focusedWindow, raised.contains(focused) { focusEffect(focused, raise: true) } + } + + private func focusEffect(_ window: WindowID, raise: Bool) { + let generation = lifetime + focusOperations += 1 + let completion: @MainActor (EnginePlatformFailure?) -> Void = { [weak self] failure in + guard let self, self.isStarting || self.isRunning, self.lifetime == generation else { return } + self.focusOperations -= 1 + if let failure { self.handle(failure) } + self.settleIfIdle() + } + if raise { world.raise(window, completion: completion) } else { world.focus(window, completion: completion) } + } + + private func cancelMotion(_ window: WindowID, remove: Bool) { + for display in animators.keys { + animators[display]?.cancel(window.motionID) + if animators[display]?.isIdle == true { links[display]?.stop() } + } + coalescer.remove(window.motionID) + pendingFrames[window.motionID] = nil + targets[window] = nil + placements[window] = nil + if remove { + actualFrames[window] = nil + echoes[window] = nil + intrinsicFloating[window] = nil + minimumCandidates[window] = nil + } + } + + private func pruneMotion() { + for window in placements.keys { + guard let key = snapshot.state.workspace(containing: window), snapshot.state.isActive(key) else { + cancelMotion(window, remove: snapshot.state.windows[window] == nil) + continue + } + if placements[window] != key.display { cancelMotion(window, remove: false) } + } + for display in animators.keys where snapshot.state.displays[display] == nil { + links[display]?.stop() + links[display] = nil + animators[display] = nil + } + } + + private func rememberEcho(_ window: WindowID, frame: Rect, transaction: UInt64) { + var recent = echoes[window, default: []].filter { clock.now - $0.time <= 0.5 } + if let previous = actualFrames[window], previous.size != frame.size { + recent.append( + Echo(frame: Rect(origin: previous.origin, size: frame.size), transaction: transaction, time: clock.now)) + } + recent.append(Echo(frame: frame, transaction: transaction, time: clock.now)) + echoes[window] = Array(recent.suffix(64)) + } + + private func isEcho(_ window: WindowID, frame: Rect, origin: FrameChangeOrigin) -> Bool { + if origin == .user { return false } + return echoes[window, default: []].contains { echo in + guard clock.now - echo.time <= 0.5, frame.matches(echo.frame) else { return false } + if case .engine(let transaction) = origin { return transaction == echo.transaction } + return true + } + } + + private func handle(_ failure: EnginePlatformFailure) { + log.record(.platform(failure)) + if case .vanished(let window) = failure { + cancelMotion(window, remove: true) + enqueue(.windowDisappeared(window)) + } + if failure == .permissionLost { + writesPermitted = false + for window in placements.keys { cancelMotion(window, remove: false) } + } + } + + private func motionFailure(_ error: any Error, window: WindowID? = nil) { + if let window { + cancelMotion(window, remove: false) + } else { + for window in Array(placements.keys) { cancelMotion(window, remove: false) } + } + if let motion = error as? MotionError { + log.record(.motion(motion)) + } else { + log.record(.configuration(String(describing: error))) + } + } + + private func settleIfIdle() { if isIdle { finishTracing() } } + private func finishTracing() { + for transaction in firstWriteTraces { trace?.end(.eventToFirstWrite, transaction: transaction) } + for transaction in traced { trace?.end(.eventToSettled, transaction: transaction) } + firstWriteTraces.removeAll() + traced.removeAll() + } +} + +extension WindowID { + fileprivate init?(exactly id: MotionWindowID) { + guard let rawValue = UInt32(exactly: id.rawValue) else { return nil } + self.init(rawValue: rawValue) + } +} diff --git a/Tests/TesseraE2ETests/EngineIntegrationTests.swift b/Tests/TesseraE2ETests/EngineIntegrationTests.swift new file mode 100644 index 00000000..1d691397 --- /dev/null +++ b/Tests/TesseraE2ETests/EngineIntegrationTests.swift @@ -0,0 +1,179 @@ +import AppKit +import ApplicationServices +import Darwin +import Foundation +import TesseraConfig +import TesseraCore +import TesseraEngine +import TesseraPlatform +import Testing + +private struct EngineIntegrationError: Error { + let message: String +} + +private final class EngineFixture { + let process = Process() + private let output = Pipe() + + init(title: String) throws { + var directory = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + var executable: URL? + while directory.path != "/" { + let candidate = directory.appendingPathComponent(".build/debug/FixtureApp") + if FileManager.default.isExecutableFile(atPath: candidate.path) { + executable = candidate + break + } + directory.deleteLastPathComponent() + } + guard let executable else { + throw EngineIntegrationError(message: "Build FixtureApp before running engine integration tests") + } + process.executableURL = executable + process.arguments = ["--title", title] + process.standardOutput = output + try process.run() + do { + let deadline = Date().addingTimeInterval(10) + var bytes: [UInt8] = [] + while Date() < deadline { + var descriptor = pollfd( + fd: output.fileHandleForReading.fileDescriptor, events: Int16(POLLIN), revents: 0) + let result = poll(&descriptor, 1, 100) + if result < 0 { + if errno == EINTR { continue } + throw EngineIntegrationError(message: "Fixture output poll failed") + } + if result == 0 { continue } + var byte: UInt8 = 0 + guard Darwin.read(descriptor.fd, &byte, 1) == 1 else { + throw EngineIntegrationError(message: "Fixture exited before readiness") + } + if byte == 10 { + guard String(decoding: bytes, as: UTF8.self) == "ready \(process.processIdentifier)" else { + throw EngineIntegrationError(message: "Unexpected fixture readiness") + } + return + } + bytes.append(byte) + guard bytes.count < 1_024 else { + throw EngineIntegrationError(message: "Fixture readiness exceeded its limit") + } + } + throw EngineIntegrationError(message: "Fixture readiness timed out") + } catch { + stop() + throw error + } + } + + func stop() { + guard process.isRunning else { return } + let result = Darwin.kill(process.processIdentifier, SIGKILL) + #expect(result == 0 || errno == ESRCH) + let deadline = Date().addingTimeInterval(2) + while process.isRunning && Date() < deadline { usleep(10_000) } + #expect(!process.isRunning) + } +} + +@MainActor +private final class IntegrationAnnouncer: EngineAnnouncer { + func announce(_ announcement: Announcement) {} +} + +@MainActor +private final class IntegrationLog: EngineLogSink { + var diagnostics: [EngineDiagnostic] = [] + func record(_ diagnostic: EngineDiagnostic) { diagnostics.append(diagnostic) } +} + +@MainActor +private func waitForEngine(_ label: String, condition: @MainActor () -> Bool) async throws { + let deadline = ContinuousClock.now.advanced(by: .seconds(10)) + while ContinuousClock.now < deadline { + if condition() { return } + try await Task.sleep(for: .milliseconds(20)) + } + throw EngineIntegrationError(message: "Timed out waiting for \(label)") +} + +@Suite(.serialized) +struct EngineIntegrationTests { + @MainActor + @Test( + .enabled( + if: AXIsProcessTrusted() || ProcessInfo.processInfo.environment["TESSERA_E2E"] == "1", + "Accessibility permission is required for engine integration tests" + )) + func tilesFixtureWindowsFocusesAndRetilesAfterAppExit() async throws { + try #require(AXIsProcessTrusted(), "Grant Accessibility permission to the test runner") + let first = try EngineFixture(title: "Engine First") + defer { first.stop() } + let second = try EngineFixture(title: "Engine Second") + defer { second.stop() } + let pids = Set([first.process.processIdentifier, second.process.processIdentifier]) + let world = NativeEngineWorld(applicationFilter: { pids.contains($0.processIdentifier) }) + let log = IntegrationLog() + var configuration = TesseraConfiguration.defaults + configuration.motion.transitions = .snap + configuration.layout.global.defaultLayout = .columns + let engine = try TesseraEngine( + world: world, clock: SystemEngineClock(), scheduler: RunLoopEngineScheduler(), + displayLink: { try world.displayLink(for: $0) }, announcer: IntegrationAnnouncer(), log: log, + configuration: configuration, reduceMotionSource: nil + ) + do { + try await engine.start() + try await waitForEngine("two tiled fixture windows") { + engine.snapshot.state.windows.count == 2 && engine.isIdle + } + let state = engine.snapshot.state + #expect(Set(state.windows.values.map(\.app.pid)) == pids) + let serverFrames = try await Task.detached { + Dictionary( + uniqueKeysWithValues: try WindowServer().windows().filter { pids.contains($0.pid) }.map { + ($0.number, $0.bounds) + }) + }.value + for (window, target) in state.frames { + let actual = try #require(serverFrames[window.rawValue]) + #expect(abs(actual.minX - target.minX) <= 1) + #expect(abs(actual.minY - target.minY) <= 1) + #expect(abs(actual.width - target.size.width) <= 1) + #expect(abs(actual.height - target.size.height) <= 1) + } + #expect(!engine.writeMetrics.isEmpty) + let layout = try await engine.perform(.setLayout(.columns)) + #expect(layout.isAccepted) + let focused = try #require(engine.snapshot.focusedWindow) + let direction: Direction = + engine.snapshot.state.frames[focused]?.minX == engine.snapshot.state.frames.values.map(\.minX).min() + ? .right : .left + let focus = try await engine.perform(.focus(direction)) + #expect(focus.isAccepted) + try await waitForEngine("verified fixture focus") { + engine.isIdle + && NSWorkspace.shared.frontmostApplication?.processIdentifier + == engine.snapshot.state.windows[engine.snapshot.focusedWindow ?? focused]?.app.pid + } + second.stop() + try await waitForEngine("retile after fixture exit") { + engine.snapshot.state.windows.count == 1 && engine.isIdle + } + let remaining = try #require(engine.snapshot.state.windows.values.first) + #expect(remaining.app.pid == first.process.processIdentifier) + let key = try #require(engine.snapshot.state.workspace(containing: remaining.id)) + let screen = try #require(engine.snapshot.state.displays[key.display]) + #expect( + engine.snapshot.state.frames[remaining.id] + == screen.frame.inset(by: Insets(configuration.layout.global.gaps.outer)).roundedToWholePoints()) + await engine.stop() + #expect(engine.isIdle) + } catch { + await engine.stop() + throw error + } + } +} diff --git a/Tests/TesseraEngineTests/ConfigurationAndDisplayTests.swift b/Tests/TesseraEngineTests/ConfigurationAndDisplayTests.swift new file mode 100644 index 00000000..43de1f5f --- /dev/null +++ b/Tests/TesseraEngineTests/ConfigurationAndDisplayTests.swift @@ -0,0 +1,417 @@ +import Foundation +import TesseraConfig +import TesseraCore +import TesseraEngine +import Testing + +@Suite("Engine displays and Spaces") +@MainActor +struct TesseraEngineDisplayTests { + @Test func switchingSpacesCancelsOldMotionAndSnapsNewWorkspace() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + try await harness.start() + try harness.add([1, 2]) + let secondSpace = SpaceID(rawValue: 9) + let hiddenWorkspace = WorkspaceKey(display: engineDisplay, space: secondSpace) + harness.world.appear(engineWindow(3), workspace: hiddenWorkspace) + try harness.scheduler.runReady() + #expect(harness.world.writes(for: WindowID(rawValue: 3)).isEmpty) + let priorWrites = harness.world.allWrites.count + + harness.world.emit(.observed(.activeSpaceChanged(display: engineDisplay, space: secondSpace))) + try harness.scheduler.runReady() + try harness.finishMotion() + + #expect(harness.engine.snapshot.state.activeSpaces[engineDisplay] == secondSpace) + #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 3)) + #expect(harness.engine.snapshot.tiles == [WindowFrame(window: WindowID(rawValue: 3), frame: engineScreen)]) + #expect( + harness.world.allWrites.dropFirst(priorWrites).allSatisfy { + $0.window == WindowID(rawValue: 3) && $0.frame == engineScreen + }) + #expect(harness.world.frames[WindowID(rawValue: 3)] == engineScreen) + #expect(harness.links.runningCount == 0) + #expect(harness.engine.isIdle) + + harness.world.emit(.observed(.activeSpaceChanged(display: engineDisplay, space: engineSpace))) + try harness.scheduler.runReady() + try harness.finishMotion() + #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 2)) + #expect(harness.engine.snapshot.tiles.map(\.window) == [WindowID(rawValue: 1), WindowID(rawValue: 2)]) + #expect( + harness.world.frames[WindowID(rawValue: 2)] == harness.engine.snapshot.state.frames[WindowID(rawValue: 2)]) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func displayUnplugDuringAnimationMigratesAndStopsRemovedLink() async throws { + let harness = try EngineHarness( + configuration: engineConfiguration(glide: true), initialState: engineInitialState(twoDisplays: true)) + try await harness.start() + harness.world.appear(engineWindow(1)) + harness.world.appear( + engineWindow(2), workspace: WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)), + frame: Rect(x: 1300, y: 100, width: 300, height: 200)) + try harness.scheduler.runReady() + let removedLink = try #require(harness.links.links[secondEngineDisplay]) + #expect(removedLink.isRunning) + + harness.world.emit(.observed(.displaySetChanged([Display(id: engineDisplay, frame: engineScreen)]))) + try harness.scheduler.runReady() + try harness.finishMotion() + + #expect(harness.engine.snapshot.state.displays[secondEngineDisplay] == nil) + #expect(harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 2)) == engineWorkspace) + #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 2)) + #expect(!removedLink.isRunning) + #expect(removedLink.stopCount > 0) + for tile in harness.engine.snapshot.tiles { + #expect(tile.frame.minX >= engineScreen.minX) + #expect(tile.frame.maxX <= engineScreen.maxX) + #expect(harness.world.frames[tile.window] == tile.frame) + } + let writes = harness.world.writes.count + removedLink.fireLate(at: harness.clock.now + 1) + #expect(harness.world.writes.count == writes) + #expect(harness.log.motionErrors.isEmpty) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func allDisplaysRemovedLeavesNoVisibleWritesOrRunningLinks() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + try await harness.start() + try harness.add([1, 2]) + harness.world.emit(.observed(.displaySetChanged([]))) + try harness.scheduler.runReady() + let writes = harness.world.writes.count + try harness.finishMotion() + + #expect(harness.engine.snapshot.tiles.isEmpty) + #expect(harness.engine.snapshot.focusedWindow == nil) + #expect(harness.engine.snapshot.state.windows.count == 2) + #expect(harness.links.runningCount == 0) + #expect(harness.world.writes.count == writes) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } +} + +@Suite("Engine hot configuration") +@MainActor +struct TesseraEngineConfigurationTests { + @Test func hotGeometryRebuildsLayoutWithGapsRatioReservedEdgesAndCap() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2, 3]) + let before = harness.engine.layoutPassCount + var configuration = harness.engine.configuration + configuration.layout.global = LayoutValues( + defaultLayout: .side, ratio: 0.7, gaps: LayoutGaps(inner: 20, outer: 10), + reserved: ReservedEdges(top: 30), windowCap: 2 + ) + try harness.engine.applyConfiguration(configuration) + #expect(harness.scheduler.pendingCount == 1) + try harness.scheduler.runReady() + try harness.finishMotion() + let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) + + #expect(harness.engine.layoutPassCount == before + 1) + #expect(workspace.layout == .side) + #expect(workspace.ratio == MainRatio(0.7)) + #expect(workspace.gaps == Gaps(inner: 20, outer: Insets(10))) + #expect(workspace.reservedEdges == Insets(top: 30)) + #expect(workspace.windowCap == 2) + #expect(workspace.tree?.tileCount == 2) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] == Rect(x: 10, y: 40, width: 812, height: 750)) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 3)] == Rect(x: 842, y: 40, width: 348, height: 750)) + #expect( + harness.world.frames[WindowID(rawValue: 3)] == harness.engine.snapshot.state.frames[WindowID(rawValue: 3)]) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func perDisplayConfigurationDoesNotChangeOtherWorkspace() async throws { + let harness = try EngineHarness(initialState: engineInitialState(twoDisplays: true)) + try await harness.start() + try harness.add([1, 2]) + let secondWorkspace = WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2)) + try harness.add([3, 4], workspace: secondWorkspace) + let originalFirst = harness.engine.snapshot.state.workspaces[engineWorkspace] + var configuration = harness.engine.configuration + let uuid = try #require(UUID(uuidString: secondEngineDisplay.rawValue)) + configuration.layout.displays[uuid] = LayoutValues(defaultLayout: .rows, gaps: LayoutGaps(inner: 12, outer: 6)) + try harness.engine.applyConfiguration(configuration) + try harness.scheduler.runReady() + try harness.finishMotion() + + #expect(harness.engine.snapshot.state.workspaces[engineWorkspace] == originalFirst) + #expect(harness.engine.snapshot.state.workspaces[secondWorkspace]?.layout == .rows) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 3)] == Rect(x: 1206, y: 6, width: 1188, height: 388) + ) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 4)] + == Rect(x: 1206, y: 406, width: 1188, height: 388)) + await harness.engine.stop() + } + + @Test func floatRulesHotReloadAndRemovalPreserveIntrinsicFloating() async throws { + let harness = try EngineHarness() + try await harness.start() + let matched = engineWindow(1, title: "Inspector 12") + let unmatched = engineWindow(2, title: "Document") + let intrinsic = engineWindow(3, app: secondEngineApp, floating: true) + harness.world.appear(matched) + harness.world.appear(unmatched) + harness.world.appear(intrinsic) + try harness.scheduler.runReady() + let oldFocus = harness.engine.snapshot.focusedWindow + var configuration = harness.engine.configuration + configuration.floatRules = [ + FloatRule(bundleID: engineApp.bundleID, titleRegex: "^Inspector [0-9]+$", role: "AXWindow") + ] + try harness.engine.applyConfiguration(configuration) + try harness.scheduler.runReady() + try harness.finishMotion() + + #expect(harness.engine.snapshot.state.windows[matched.id]?.isFloating == true) + #expect(harness.engine.snapshot.state.windows[unmatched.id]?.isFloating == false) + #expect(harness.engine.snapshot.state.windows[intrinsic.id]?.isFloating == true) + #expect(harness.engine.snapshot.focusedWindow == oldFocus) + #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree?.windows == [unmatched.id]) + + configuration.floatRules = [] + try harness.engine.applyConfiguration(configuration) + try harness.scheduler.runReady() + try harness.finishMotion() + #expect(harness.engine.snapshot.state.windows[matched.id]?.isFloating == false) + #expect(harness.engine.snapshot.state.windows[intrinsic.id]?.isFloating == true) + #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree?.windows.contains(matched.id) == true) + #expect(harness.engine.snapshot.focusedWindow == oldFocus) + await harness.engine.stop() + } + + @Test func nonGeometryConfigurationKeepsCommandSelectedLayout() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + harness.engine.send(.commandIssued(.setLayout(.rows))) + try harness.scheduler.runReady() + try harness.finishMotion() + var configuration = harness.engine.configuration + configuration.accessibility.announceLayoutChanges = true + configuration.motion.speed = 2 + try harness.engine.applyConfiguration(configuration) + try harness.scheduler.runReady() + + #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) + harness.engine.send(.commandIssued(.setLayout(.side))) + try harness.scheduler.runReady() + #expect(harness.announcer.announcements.contains(.layoutChanged(.side))) + #expect(!harness.announcer.announcements.contains(.layoutChanged(.rows))) + await harness.engine.stop() + } + + @Test(arguments: [false, true]) + func hotMotionDisableSettlesExistingAnimation(useReduceMotion: Bool) async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + try await harness.start() + try harness.add([1, 2]) + #expect(harness.links.runningCount == 1) + try harness.scheduler.advance(by: 0.05) + if useReduceMotion { + harness.engine.setReduceMotion(true) + } else { + var configuration = harness.engine.configuration + configuration.motion.enabled = false + try harness.engine.applyConfiguration(configuration) + try harness.scheduler.runReady() + } + try harness.scheduler.runReady() + + #expect(harness.links.runningCount == 0) + #expect(harness.world.frames == harness.engine.snapshot.state.frames) + #expect(harness.engine.isIdle) + let writes = harness.world.writes.count + try harness.finishMotion() + #expect(harness.world.writes.count == writes) + await harness.engine.stop() + } + + @Test func unchangedConfigurationDoesNotScheduleAnotherPass() async throws { + let harness = try EngineHarness() + try await harness.start() + let count = harness.engine.layoutPassCount + try harness.engine.applyConfiguration(harness.engine.configuration) + #expect(harness.scheduler.pendingCount == 0) + #expect(harness.engine.layoutPassCount == count) + await harness.engine.stop() + } + + @Test func invalidHotConfigurationLeavesStateAndMotionUntouched() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + try await harness.start() + try harness.add([1, 2]) + let before = harness.engine.snapshot + let previous = harness.engine.configuration + var invalid = previous + invalid.layout.global.gaps.inner = -1 + #expect(throws: EngineError.self) { try harness.engine.applyConfiguration(invalid) } + invalid = previous + invalid.motion.speed = .infinity + #expect(throws: EngineError.self) { try harness.engine.applyConfiguration(invalid) } + invalid = previous + invalid.floatRules = [FloatRule(titleRegex: "[")] + #expect(throws: (any Error).self) { try harness.engine.applyConfiguration(invalid) } + + #expect(harness.engine.configuration == previous) + #expect(harness.engine.snapshot == before) + #expect(harness.links.runningCount == 1) + #expect(harness.scheduler.pendingCount == 0) + try harness.finishMotion() + await harness.engine.stop() + } +} + +@Suite("Engine configuration subscriptions") +@MainActor +struct TesseraEngineConfigurationSourceTests { + @Test func sourceStartupAppliesInitialConfigurationAndStopUnsubscribes() async throws { + let initial = engineConfiguration(layout: .rows) + let source = FakeEngineConfigurationSource(initial: initial) + let harness = try EngineHarness(configSource: source) + try await harness.start() + #expect(source.startCount == 1) + #expect(source.isSubscribed) + #expect(harness.world.startCount == 1) + #expect(harness.engine.configuration == initial) + try harness.add([1, 2]) + #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 2)] == Rect(x: 0, y: 400, width: 1200, height: 400)) + try await harness.engine.start() + #expect(source.startCount == 1) + await harness.engine.stop() + #expect(source.stopCount == 1) + #expect(!source.isSubscribed) + #expect(harness.scheduler.pendingCount == 0) + } + + @Test func hotSubscriptionUpdatesCoalesceIntoOneFinalLayout() async throws { + let source = FakeEngineConfigurationSource() + let harness = try EngineHarness(configSource: source) + try await harness.start() + try harness.add([1, 2]) + let passes = harness.engine.layoutPassCount + let store = ConfigStore() + let rows = await store.load( + source: + "[layout]\ndefault = \"rows\"\n[layout.gaps]\ninner = 0\nouter = 0\n[motion]\ntransitions = \"snap\"\n") + let side = await store.load( + source: + "[layout]\ndefault = \"side\"\nratio = 0.7\n[layout.gaps]\ninner = 20\nouter = 10\n[motion]\ntransitions = \"snap\"\n" + ) + try #require(rows.loadState == .loaded) + try #require(side.loadState == .loaded) + source.emit(rows) + source.emit(side) + #expect(harness.scheduler.pendingCount == 1) + try harness.scheduler.runReady() + try harness.finishMotion() + + #expect(harness.engine.layoutPassCount == passes + 1) + #expect(harness.engine.configuration == side.activeConfiguration) + #expect(harness.engine.snapshot.layouts[engineDisplay] == .side) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] == Rect(x: 10, y: 10, width: 812, height: 780)) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 2)] == Rect(x: 842, y: 10, width: 348, height: 780)) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func rejectedSubscriptionUpdateSurfacesDiagnosticsAndKeepsLastGood() async throws { + let store = ConfigStore() + let good = await store.load(source: "[layout]\ndefault = \"side\"\nratio = 0.7\n[motion]\nenabled = false\n") + let source = FakeEngineConfigurationSource(initial: good.activeConfiguration) + let harness = try EngineHarness(configSource: source) + try await harness.start() + let before = harness.engine.snapshot + let rejected = await store.load(source: "[layout]\nratio = 8\n") + try #require(rejected.loadState == .rejected) + source.emit(rejected) + + #expect(harness.engine.configuration == good.activeConfiguration) + #expect(harness.engine.snapshot == before) + #expect(harness.scheduler.pendingCount == 0) + #expect( + harness.log.diagnostics.contains { diagnostic in + if case .config(let diagnostics) = diagnostic { diagnostics == rejected.diagnostics } else { false } + }) + await harness.engine.stop() + } + + @Test func stoppedAndPreviousLifetimeSubscriptionsCannotChangeConfiguration() async throws { + let source = FakeEngineConfigurationSource() + let harness = try EngineHarness(configSource: source) + let store = ConfigStore() + let update = await store.load(source: "[layout]\ndefault = \"rows\"\n[motion]\nenabled = false\n") + try await harness.start() + await harness.engine.stop() + let stopped = harness.engine.snapshot + source.emitFromStart(0, snapshot: update) + #expect(harness.engine.snapshot == stopped) + #expect(harness.engine.configuration == source.initial) + #expect(harness.scheduler.pendingCount == 0) + + try await harness.start() + let restarted = harness.engine.snapshot + source.emitFromStart(0, snapshot: update) + #expect(harness.engine.snapshot == restarted) + #expect(harness.engine.configuration == source.initial) + source.emit(update) + try harness.scheduler.runReady() + #expect(harness.engine.configuration == update.activeConfiguration) + #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) + await harness.engine.stop() + #expect(source.startCount == 2) + #expect(source.stopCount == 2) + } + + @Test func failedSubscriptionStartStopsSourceBeforeStartingWorld() async throws { + let source = FakeEngineConfigurationSource() + source.startError = .startup + let harness = try EngineHarness(configSource: source) + await #expect(throws: HarnessError.self) { try await harness.engine.start() } + + #expect(source.startCount == 1) + #expect(source.stopCount == 1) + #expect(!source.isSubscribed) + #expect(harness.world.startCount == 0) + #expect(!harness.engine.isRunning) + #expect(harness.engine.isIdle) + #expect(harness.scheduler.pendingCount == 0) + } + + @Test func stoppingDuringDeferredSubscriptionStartRejectsLateInitialConfiguration() async throws { + let source = FakeEngineConfigurationSource(initial: engineConfiguration(layout: .rows)) + source.deferStart = true + let harness = try EngineHarness(configSource: source) + let startup = Task { @MainActor in try await harness.engine.start() } + for _ in 0..<100 where !source.isAwaitingStart { await Task.yield() } + try #require(source.isAwaitingStart) + await harness.engine.stop() + try source.completeStart() + await #expect(throws: EngineError.stopped) { try await startup.value } + + #expect(harness.engine.configuration == engineConfiguration()) + #expect(harness.world.startCount == 0) + #expect(!source.isSubscribed) + #expect(!harness.engine.isRunning) + #expect(harness.engine.isIdle) + #expect(harness.scheduler.pendingCount == 0) + } +} diff --git a/Tests/TesseraEngineTests/EchoAndLifecycleTests.swift b/Tests/TesseraEngineTests/EchoAndLifecycleTests.swift new file mode 100644 index 00000000..7a47c260 --- /dev/null +++ b/Tests/TesseraEngineTests/EchoAndLifecycleTests.swift @@ -0,0 +1,339 @@ +import TesseraAnimation +import TesseraCore +import TesseraEngine +import Testing + +@Suite("Engine write echoes") +@MainActor +struct TesseraEngineEchoTests { + @Test func synchronousEngineEchoesDoNotQueueAnotherPass() async throws { + let harness = try EngineHarness() + harness.world.emitsEngineEchoes = true + try await harness.start() + let before = harness.engine.layoutPassCount + try harness.add([1, 2]) + + #expect(harness.engine.layoutPassCount == before + 1) + #expect(harness.scheduler.pendingCount == 0) + #expect(harness.engine.snapshot.state.observedFrames[WindowID(rawValue: 2)] == initialEngineFrame) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func matchingUnknownAndTransactionEchoesAreFiltered() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let write = try #require(harness.world.allWrites.last) + let revision = harness.engine.snapshot.revision + harness.world.emit(.frameChanged(write.window, frame: write.frame, resized: false, origin: .unknown)) + harness.world.emit( + .frameChanged(write.window, frame: write.frame, resized: true, origin: .engine(write.transaction))) + try harness.scheduler.runReady() + + #expect(harness.engine.snapshot.revision == revision) + #expect(harness.scheduler.pendingCount == 0) + #expect(harness.world.writes.count == 1) + await harness.engine.stop() + } + + @Test func explicitUserOriginWinsEvenWhenFrameMatchesEcho() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let write = try #require(harness.world.allWrites.last) + let revision = harness.engine.snapshot.revision + harness.world.userFrame(write.window, frame: write.frame, resized: true, origin: .user) + #expect(harness.scheduler.pendingCount == 1) + try harness.scheduler.runReady() + + #expect(harness.engine.snapshot.revision == revision + 1) + #expect(harness.engine.snapshot.state.observedFrames[write.window] == write.frame) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func expiredUnknownEchoIsHandledAsObservation() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let write = try #require(harness.world.allWrites.last) + let revision = harness.engine.snapshot.revision + try harness.scheduler.advance(by: 0.501) + harness.world.userFrame(write.window, frame: write.frame, origin: .unknown) + try harness.scheduler.runReady() + + #expect(harness.engine.snapshot.revision == revision + 1) + #expect(harness.engine.snapshot.state.observedFrames[write.window] == write.frame) + await harness.engine.stop() + } + + @Test func wrongTransactionOrDifferentFrameIsNotAnEcho() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let write = try #require(harness.world.allWrites.last) + let revision = harness.engine.snapshot.revision + harness.world.userFrame(write.window, frame: write.frame, origin: .engine(write.transaction + 1)) + try harness.scheduler.runReady() + #expect(harness.engine.snapshot.revision == revision + 1) + let moved = Rect(x: 200, y: 20, width: write.frame.size.width, height: write.frame.size.height) + harness.world.userFrame(write.window, frame: moved, origin: .engine(write.transaction)) + try harness.scheduler.runReady() + #expect(harness.engine.snapshot.revision == revision + 2) + #expect(harness.engine.snapshot.state.observedFrames[write.window] == moved) + try harness.finishMotion() + await harness.engine.stop() + } +} + +@Suite("Engine lifetime and snapshot streams") +@MainActor +struct TesseraEngineLifecycleTests { + @Test func stopResumesPendingCommandsAndCancelsTurn() async throws { + let harness = try EngineHarness() + try await harness.start() + let before = harness.engine.snapshot + let batch = EngineCommandBatch([.retile, .setLayout(.rows)], engine: harness.engine) + try await batch.waitUntilEnqueued() + #expect(harness.scheduler.pendingCount == 1) + await harness.engine.stop() + + for task in batch.tasks { + await #expect(throws: EngineError.stopped) { try await task.value } + } + #expect(harness.engine.snapshot == before) + #expect(!harness.engine.isRunning) + #expect(harness.engine.isIdle) + #expect(harness.scheduler.pendingCount == 0) + #expect(harness.scheduler.cancelledCount == 1) + harness.scheduler.fireCancelledWork() + #expect(harness.engine.snapshot == before) + await #expect(throws: EngineError.stopped) { try await harness.engine.perform(.retile) } + } + + @Test func stopIgnoresLatePlatformEventsTicksAndCompletions() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + harness.world.deferWrites = true + harness.world.deferActions = true + try await harness.start() + try harness.add([1, 2]) + let link = try #require(harness.links.links[engineDisplay]) + let before = harness.engine.snapshot + let oldWrites = harness.world.allWrites + let count = harness.world.writes.count + await harness.engine.stop() + + harness.world.emitLate( + .observed(.windowAppeared(engineWindow(9), workspace: engineWorkspace, frame: initialEngineFrame))) + link.fireLate(at: harness.clock.now + 2) + try harness.world.completeNextWrite( + receipt: EngineWriteReceipt( + frames: oldWrites.map { WindowFrame(window: $0.window, frame: $0.frame) }, failures: [.permissionLost], + duration: 0.5)) + let actions = harness.world.pendingActionCount + for _ in 0.. JSONValue { + try JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(value)) +} + +@MainActor +private func expectEngineIPCError(_ code: String, action: @MainActor () async throws -> JSONValue) async throws { + do { + _ = try await action() + Issue.record("Expected IPC rejection with code \(code)") + } catch let error as IPCError { + #expect(error.code == code) + #expect(!error.message.isEmpty) + } +} + +@MainActor +private func waitForEngineTurn(_ harness: EngineHarness) async throws { + for _ in 0..<100 where harness.scheduler.readyCount == 0 { await Task.yield() } + try #require(harness.scheduler.readyCount > 0, "IPC action did not enter the engine queue") +} + +@Suite("Engine IPC handler") +@MainActor +struct TesseraEngineIPCTests { + @Test func allQueryPayloadsExposeSortedTypedSnapshotFields() async throws { + let harness = try EngineHarness() + try await harness.start() + let first = ManagedWindow( + id: WindowID(rawValue: 9), app: engineApp, title: "Inspecteur café", + minimumSize: Size(width: 100, height: 80)) + harness.world.appear(first) + harness.world.appear(engineWindow(1, app: secondEngineApp, floating: true, title: "Floating")) + try harness.scheduler.runReady() + let handler = EngineIPCHandler( + engine: harness.engine, configPath: "/tmp/tessera-test.toml", version: "test-version") + let workspaceID = JSONValue.object(["display": .string(engineDisplay.rawValue), "space": .string("1")]) + let windows = try await handler.query(.windows) + #expect( + windows + == .array([ + .object([ + "id": .integer(1), "pid": .integer(200), "bundle_id": .string(secondEngineApp.bundleID), + "title": .string("Floating"), "role": .string("AXWindow"), "floating": .bool(true), + "focused": .bool(true), + "frame": try engineJSON(initialEngineFrame), "minimum": .null, "workspace": workspaceID, + ]), + .object([ + "id": .integer(9), "pid": .integer(100), "bundle_id": .string(engineApp.bundleID), + "title": .string("Inspecteur café"), "role": .string("AXWindow"), "floating": .bool(false), + "focused": .bool(false), + "frame": try engineJSON(engineScreen), + "minimum": try engineJSON(LearnedMinimumSize(size: Size(width: 100, height: 80))), + "workspace": workspaceID, + ]), + ])) + let workspace = try #require(harness.engine.snapshot.state.workspaces[engineWorkspace]) + #expect( + try await handler.query(.workspaces) + == .array([ + .object([ + "id": workspaceID, "active": .bool(true), "layout": .string("columns"), "ratio": .number(0.5), + "window_cap": .integer(Int64(Int.max)), "windows": .array([.integer(9), .integer(1)]), + "tiles": try engineJSON(try #require(workspace.tree)), + ]) + ])) + #expect( + try await handler.query(.displays) + == .array([ + .object([ + "id": .string(engineDisplay.rawValue), "frame": try engineJSON(engineScreen), + "active_space": .string("1"), + ]) + ])) + #expect( + try await handler.query(.config) + == .object([ + "path": .string("/tmp/tessera-test.toml"), "version": .string("test-version"), + "schema_version": .integer(1), + "motion": .object([ + "enabled": .bool(true), "level": .string("playful"), "speed": .number(1), + "transitions": .string("snap"), + ]), + ])) + await harness.engine.stop() + } + + @Test func emptyQueriesAndDisplayWithoutActiveSpaceUseExplicitNulls() async throws { + let state = State(displays: [Display(id: engineDisplay, frame: engineScreen)]) + let harness = try EngineHarness(initialState: state) + try await harness.start() + let handler = EngineIPCHandler(engine: harness.engine) + #expect(try await handler.query(.windows) == .array([])) + #expect(try await handler.query(.workspaces) == .array([])) + #expect( + try await handler.query(.displays) + == .array([ + .object([ + "id": .string(engineDisplay.rawValue), "frame": try engineJSON(engineScreen), + "active_space": .null, + ]) + ])) + await harness.engine.stop() + } + + @Test func inactiveWorkspacesRemainQueryable() async throws { + let harness = try EngineHarness() + try await harness.start() + let hiddenKey = WorkspaceKey(display: engineDisplay, space: SpaceID(rawValue: 99)) + harness.world.appear(engineWindow(5), workspace: hiddenKey) + try harness.scheduler.runReady() + let handler = EngineIPCHandler(engine: harness.engine) + let payload = try await handler.query(.workspaces) + guard case .array(let workspaces) = payload else { + Issue.record("Workspace query must return an array") + return + } + #expect(workspaces.count == 2) + guard case .object(let hidden) = workspaces[1] else { + Issue.record("Workspace query elements must be objects") + return + } + #expect(hidden["active"] == .bool(false)) + #expect(hidden["windows"] == .array([.integer(5)])) + #expect(hidden["id"] == .object(["display": .string(engineDisplay.rawValue), "space": .string("99")])) + await harness.engine.stop() + } + + @Test func actionRoutesThroughAsyncPerformAndReturnsRevisionAndReports() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let handler = EngineIPCHandler(engine: harness.engine) + let action = Task { @MainActor in try await handler.run(command: "set-layout", args: ["rows"]) } + try await waitForEngineTurn(harness) + let previousRevision = harness.engine.snapshot.revision + try harness.scheduler.runReady() + #expect( + try await action.value + == .object([ + "accepted": .bool(true), "revision": .string(String(previousRevision + 1)), "reports": .array([]), + ])) + #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) + let rejected = Task { @MainActor in try await handler.run(command: "focus", args: ["right"]) } + try await waitForEngineTurn(harness) + try harness.scheduler.runReady() + #expect( + try await rejected.value + == .object([ + "accepted": .bool(false), "revision": .string(String(previousRevision + 2)), + "reports": try engineJSON([Report.noNeighbor(.right)]), + ])) + await harness.engine.stop() + } + + @Test func parserAndShellRejectionsDoNotReachReducer() async throws { + let harness = try EngineHarness() + try await harness.start() + let handler = EngineIPCHandler(engine: harness.engine) + let before = harness.engine.snapshot + try await expectEngineIPCError("invalid_command") { try await handler.run(command: "set-ratio", args: ["nan"]) } + try await expectEngineIPCError("shell_command") { try await handler.run(command: "open-settings", args: []) } + #expect(harness.engine.snapshot == before) + #expect(harness.scheduler.pendingCount == 0) + await harness.engine.stop() + await #expect(throws: EngineError.stopped) { try await handler.run(command: "retile", args: []) } + } + + @Test func reloadWithoutStoreIsRejected() async throws { + let harness = try EngineHarness() + try await harness.start() + let handler = EngineIPCHandler(engine: harness.engine) + try await expectEngineIPCError("config_unavailable") { try await handler.reloadConfig() } + #expect(harness.scheduler.pendingCount == 0) + await harness.engine.stop() + } + + @Test func reloadAppliesGoodFileAndRejectsBadFileKeepingLastGood() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent( + "tessera-engine-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { + do { try FileManager.default.removeItem(at: directory) } catch { Issue.record(error) } + } + let file = directory.appendingPathComponent("config.toml") + let source = "[layout]\ndefault = \"side\"\nratio = 0.7\n[motion]\nenabled = false\n" + try source.write(to: file, atomically: true, encoding: .utf8) + let store = ConfigStore(fileURL: file) + let harness = try EngineHarness() + try await harness.start() + let handler = EngineIPCHandler(engine: harness.engine, configStore: store) + #expect(try await handler.reloadConfig() == .object(["path": .string(file.path), "reloaded": .bool(true)])) + try harness.scheduler.runReady() + let lastGood = harness.engine.configuration + #expect(lastGood.layout.global.defaultLayout == .side) + #expect(lastGood.layout.global.ratio == 0.7) + #expect(!lastGood.motion.enabled) + #expect(harness.engine.snapshot.layouts[engineDisplay] == .side) + + try "[layout]\nratio = 8\n".write(to: file, atomically: true, encoding: .utf8) + try await expectEngineIPCError("config_rejected") { try await handler.reloadConfig() } + #expect(harness.engine.configuration == lastGood) + #expect(harness.engine.snapshot.layouts[engineDisplay] == .side) + #expect(harness.scheduler.pendingCount == 0) + let rejected = await store.snapshot + #expect(rejected.loadState == .rejected) + #expect(rejected.lastGoodDocument?.render() == source) + await harness.engine.stop() + } +} diff --git a/Tests/TesseraEngineTests/MotionTests.swift b/Tests/TesseraEngineTests/MotionTests.swift new file mode 100644 index 00000000..691beb24 --- /dev/null +++ b/Tests/TesseraEngineTests/MotionTests.swift @@ -0,0 +1,390 @@ +import TesseraAnimation +import TesseraConfig +import TesseraCore +import TesseraEngine +import Testing + +@Suite("Engine motion and write completion") +@MainActor +struct TesseraEngineMotionTests { + @Test(arguments: [false, true]) + func targetSizeIsWrittenOnFrameZero(glide: Bool) async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: glide)) + try await harness.start() + try harness.add([1, 2]) + + #expect(harness.world.writes.count == 1) + for write in harness.world.allWrites { + let target = try #require(harness.engine.snapshot.state.frames[write.window]) + #expect(write.frame.size == target.size) + if !glide { #expect(write.frame == target) } + } + #expect(harness.links.runningCount == (glide ? 1 : 0)) + #expect(harness.engine.isIdle == !glide) + if glide { + #expect( + harness.world.frames[WindowID(rawValue: 2)]?.minX + != harness.engine.snapshot.state.frames[WindowID(rawValue: 2)]?.minX) + try harness.finishMotion() + #expect(harness.world.frames == harness.engine.snapshot.state.frames) + #expect(harness.engine.isIdle) + #expect(harness.links.runningCount == 0) + } + await harness.engine.stop() + } + + @Test func idleWaitsForFinalWriteReceiptNotAnimationEnd() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + harness.world.deferWrites = true + try await harness.start() + try harness.add([1, 2]) + #expect(harness.world.pendingWriteCount == 1) + #expect(!harness.engine.isIdle) + + try harness.finishMotion() + #expect(harness.links.runningCount == 0) + #expect(!harness.engine.isIdle) + #expect(harness.world.pendingWriteCount == 1) + try harness.world.completeNextWrite() + #expect(harness.world.pendingWriteCount == 1) + #expect(!harness.engine.isIdle) + #expect(harness.trace.balance(for: .eventToSettled) > 0) + + try harness.world.completeNextWrite() + #expect(harness.world.frames == harness.engine.snapshot.state.frames) + #expect(harness.engine.isIdle) + #expect(harness.scheduler.pendingCount == 0) + #expect(harness.trace.balance(for: .eventToSettled) == 0) + #expect(harness.trace.balance(for: .eventToFirstWrite) == 0) + #expect(harness.trace.balance(for: .write) == 0) + await harness.engine.stop() + } + + @Test func rateLimitedFinalFrameUsesOneShotAndThenStaysIdle() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let writes = harness.world.writes.count + harness.engine.send(.commandIssued(.setLayout(.rows))) + try harness.scheduler.runReady() + + #expect(harness.world.writes.count == writes) + #expect(harness.links.runningCount == 0) + #expect(harness.scheduler.pendingCount == 1) + #expect(!harness.engine.isIdle) + let scheduled = harness.scheduler.scheduledCount + try harness.scheduler.runNext() + + #expect(harness.world.writes.count == writes + 1) + #expect(harness.scheduler.scheduledCount == scheduled) + #expect(harness.scheduler.pendingCount == 0) + #expect(harness.world.frames == harness.engine.snapshot.state.frames) + #expect(harness.engine.isIdle) + let settledWrites = harness.world.writes.count + try harness.scheduler.advance(by: 100) + harness.links.tickAll(at: harness.clock.now) + #expect(harness.world.writes.count == settledWrites) + #expect(harness.scheduler.pendingCount == 0) + await harness.engine.stop() + } + + @Test func latestTargetWinsWhileAppWriteIsDeferred() async throws { + let harness = try EngineHarness() + harness.world.deferWrites = true + try await harness.start() + try harness.add([1, 2]) + harness.engine.send(.commandIssued(.setLayout(.rows))) + try harness.scheduler.runReady() + harness.engine.send(.commandIssued(.setLayout(.side))) + harness.engine.send(.commandIssued(.setRatio(MainRatio(0.7)))) + try harness.scheduler.runReady() + let newest = harness.engine.snapshot.state.frames + #expect(harness.world.writes.count == 1) + #expect(harness.world.pendingWriteCount == 1) + + try harness.scheduler.advance(by: 0.1) + try harness.world.completeNextWrite() + #expect(harness.world.writes.count == 2) + #expect(harness.world.writes.last?.writes.allSatisfy { $0.frame == newest[$0.window] } == true) + try harness.world.completeNextWrite() + + #expect(harness.world.frames == newest) + #expect(harness.world.writes.count == 2) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func closingWindowDiscardsQueuedAnimationWrites() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + harness.world.deferWrites = true + try await harness.start() + try harness.add([1, 2]) + let closed = WindowID(rawValue: 2) + let stale = harness.world.allWrites + harness.world.disappear(closed) + try harness.scheduler.runReady() + try harness.finishMotion() + let writeCount = harness.world.allWrites.count + try harness.world.completeNextWrite( + receipt: EngineWriteReceipt( + frames: stale.map { WindowFrame(window: $0.window, frame: $0.frame) }, duration: 0.001)) + while harness.world.pendingWriteCount > 0 { try harness.world.completeNextWrite() } + try harness.scheduler.runReady() + + #expect(harness.engine.snapshot.state.windows[closed] == nil) + #expect(harness.world.allWrites.dropFirst(writeCount).allSatisfy { $0.window != closed }) + #expect(harness.engine.isIdle) + #expect(harness.log.motionErrors.isEmpty) + await harness.engine.stop() + } + + @Test func reusedWindowIDRejectsOldGenerationReadback() async throws { + let harness = try EngineHarness() + harness.world.deferWrites = true + try await harness.start() + try harness.add([1, 2]) + let reused = WindowID(rawValue: 2) + let stale = try #require(harness.world.allWrites.first { $0.window == reused }) + harness.world.disappear(reused) + harness.world.appear(engineWindow(2), frame: Rect(x: 990, y: 100, width: 200, height: 300)) + harness.engine.send(.commandIssued(.setLayout(.rows))) + try harness.scheduler.runReady() + let newest = try #require(harness.engine.snapshot.state.frames[reused]) + try harness.scheduler.advance(by: 0.1) + + try harness.world.completeNextWrite( + receipt: EngineWriteReceipt(frames: [WindowFrame(window: reused, frame: stale.frame)], duration: 0.001)) + #expect(harness.world.writes(for: reused).last?.frame == newest) + #expect(harness.engine.snapshot.state.windows[reused]?.minimumSize == nil) + while harness.world.pendingWriteCount > 0 { try harness.world.completeNextWrite() } + #expect(harness.world.frames[reused] == newest) + #expect(harness.engine.isIdle) + #expect(harness.log.motionErrors.isEmpty) + await harness.engine.stop() + } + + @Test func appExitAndPIDReuseIgnoreLateOldBatch() async throws { + let harness = try EngineHarness() + harness.world.deferWrites = true + try await harness.start() + try harness.add([1]) + let oldWrites = harness.world.allWrites + harness.world.emit(.appExited(engineApp)) + try harness.scheduler.runReady() + harness.world.emit(.appLaunched(engineApp, at: harness.clock.now)) + harness.world.appear(engineWindow(8)) + try harness.scheduler.runReady() + #expect(harness.world.pendingWriteCount == 2) + + try harness.world.completeNextWrite( + receipt: EngineWriteReceipt( + frames: oldWrites.map { WindowFrame(window: $0.window, frame: $0.frame) }, duration: 0.5)) + #expect(harness.log.motionErrors.isEmpty) + #expect(harness.engine.writeMetrics[MotionAppID(rawValue: engineApp.pid)]?.sampleCount == 0) + try harness.world.completeNextWrite() + #expect(harness.engine.snapshot.state.windows[WindowID(rawValue: 1)] == nil) + #expect(harness.world.frames[WindowID(rawValue: 8)] == engineScreen) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } +} + +@Suite("Engine app feedback") +@MainActor +struct TesseraEngineMetricsTests { + @Test func launchingAppsSnapThenResumeGlidingAfterWarmup() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + try await harness.start() + harness.world.emit(.appLaunched(engineApp, at: harness.clock.now)) + try harness.add([1, 2]) + let app = MotionAppID(rawValue: engineApp.pid) + + #expect(harness.links.runningCount == 0) + #expect(harness.engine.isIdle) + #expect(harness.engine.writeMetrics[app]?.launchedAt == 10) + #expect(harness.engine.writeMetrics[app]?.sampleCount == 1) + try harness.scheduler.advance(by: 1.6) + harness.engine.send(.commandIssued(.setLayout(.rows))) + try harness.scheduler.runReady() + #expect(harness.links.runningCount == 1) + #expect(!harness.engine.isIdle) + try harness.finishMotion() + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func slowReadbackChangesFuturePlansAndMetricsAreResettable() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + harness.world.behaviors[engineApp] = FakeEngineWorld.Behavior(duration: 0.05) + try await harness.start() + try harness.add([1, 2]) + try harness.finishMotion() + let app = MotionAppID(rawValue: engineApp.pid) + let metrics = try #require(harness.engine.writeMetrics[app]) + #expect(metrics.averageWriteDuration == 0.05) + #expect(metrics.frameRate() == 20) + #expect(metrics.shouldSnap(at: harness.clock.now)) + + harness.engine.send(.commandIssued(.setLayout(.rows))) + try harness.scheduler.runReady() + try harness.scheduler.advance(by: 0.1) + #expect(harness.links.runningCount == 0) + #expect(harness.world.frames == harness.engine.snapshot.state.frames) + #expect(harness.engine.isIdle) + harness.engine.resetWriteMetrics(for: engineApp) + #expect(harness.engine.writeMetrics[app] == nil) + harness.world.behaviors[engineApp] = FakeEngineWorld.Behavior() + harness.engine.send(.commandIssued(.setLayout(.columns))) + try harness.scheduler.runReady() + #expect(harness.links.runningCount == 1) + try harness.finishMotion() + await harness.engine.stop() + } + + @Test func timeoutIsLoggedAndStoredWithoutInventingSuccessfulReadback() async throws { + let harness = try EngineHarness() + harness.world.behaviors[engineApp] = FakeEngineWorld.Behavior(duration: 0.3, timesOut: true) + try await harness.start() + try harness.add([1]) + let app = MotionAppID(rawValue: engineApp.pid) + + #expect(harness.log.platformFailures == [.timedOut(engineApp)]) + #expect(harness.world.frames[WindowID(rawValue: 1)] == initialEngineFrame) + #expect(harness.engine.writeMetrics[app]?.lastTimeout == harness.clock.now) + #expect(harness.engine.writeMetrics[app]?.sampleCount == 1) + #expect(harness.engine.writeMetrics[app]?.shouldSnap(at: harness.clock.now) == true) + await harness.engine.stop() + } + + @Test func clampedFinalReadbackNeedsTwoMatchingConfirmationsBeforeLearning() async throws { + let harness = try EngineHarness() + harness.world.behaviors[engineApp] = FakeEngineWorld.Behavior(minimumSize: Size(width: 700, height: 200)) + try await harness.start() + try harness.add([1, 2]) + let ids = [WindowID(rawValue: 1), WindowID(rawValue: 2)] + for id in ids { #expect(harness.engine.snapshot.state.windows[id]?.minimum == nil) } + #expect(harness.log.platformFailures.count == 2) + #expect(harness.log.platformFailures.allSatisfy { if case .failed = $0 { true } else { false } }) + #expect(harness.engine.isIdle) + #expect(harness.scheduler.pendingCount == 0) + let writes = harness.world.writes.count + try harness.scheduler.advance(by: 100) + #expect(harness.world.writes.count == writes) + + harness.engine.send(.commandIssued(.retile)) + try harness.scheduler.runReady() + for id in ids { + #expect( + harness.engine.snapshot.state.windows[id]?.minimum + == LearnedMinimumSize(size: Size(width: 700, height: 0))) + } + #expect(harness.engine.snapshot.state.cannotFit == ids) + #expect(harness.log.reports.contains(.cannotFit(ids))) + #expect(harness.log.platformFailures.count >= 4) + try harness.scheduler.advance(by: 0.1) + #expect(harness.engine.isIdle) + #expect(harness.log.motionErrors.isEmpty) + await harness.engine.stop() + } + + @Test func acceptedFinalFrameClearsTransientMinimumCandidate() async throws { + let harness = try EngineHarness() + let clamp = FakeEngineWorld.Behavior(minimumSize: Size(width: 1300, height: 900)) + harness.world.behaviors[engineApp] = clamp + try await harness.start() + try harness.add([1]) + let window = WindowID(rawValue: 1) + #expect(harness.engine.snapshot.state.windows[window]?.minimum == nil) + #expect(harness.engine.isIdle) + + harness.world.behaviors[engineApp] = FakeEngineWorld.Behavior() + try harness.scheduler.advance(by: 0.1) + harness.engine.send(.commandIssued(.retile)) + try harness.scheduler.runReady() + #expect(harness.world.frames[window] == engineScreen) + #expect(harness.engine.snapshot.state.windows[window]?.minimum == nil) + + harness.world.behaviors[engineApp] = clamp + try harness.scheduler.advance(by: 0.1) + harness.world.userFrame(window, frame: initialEngineFrame) + try harness.scheduler.runReady() + #expect(harness.world.writes.count == 3) + #expect(harness.engine.snapshot.state.windows[window]?.minimum == nil) + #expect(harness.log.platformFailures.count == 2) + #expect(harness.scheduler.pendingCount == 0) + #expect(harness.engine.isIdle) + + try harness.scheduler.advance(by: 0.1) + harness.engine.send(.commandIssued(.retile)) + try harness.scheduler.runReady() + #expect( + harness.engine.snapshot.state.windows[window]?.minimum + == LearnedMinimumSize(size: Size(width: 1300, height: 900))) + try harness.scheduler.advance(by: 0.1) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func unchangedFinalAnimationBatchPreservesExistingWriteMetrics() async throws { + let harness = try EngineHarness(configuration: engineConfiguration(glide: true)) + harness.world.behaviors[engineApp] = FakeEngineWorld.Behavior(duration: 0.02) + try await harness.start() + try harness.add([1]) + let app = MotionAppID(rawValue: engineApp.pid) + let measured = try #require(harness.engine.writeMetrics[app]) + #expect(measured.sampleCount == 1) + #expect(measured.averageWriteDuration == 0.02) + #expect(harness.links.runningCount == 1) + #expect(harness.world.frames[WindowID(rawValue: 1)] == engineScreen) + + try harness.finishMotion() + #expect(harness.world.writes.count == 1) + #expect(harness.engine.writeMetrics[app] == measured) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func invalidReceiptMetricsReleaseAppAndAllowLaterWrite() async throws { + let harness = try EngineHarness() + harness.world.deferWrites = true + try await harness.start() + try harness.add([1]) + try harness.world.completeNextWrite(receipt: EngineWriteReceipt(frames: [], duration: .nan)) + #expect(harness.log.motionErrors == [.invalidTimestamp]) + #expect(harness.engine.writeMetrics.isEmpty) + #expect(harness.engine.isIdle) + #expect(harness.scheduler.pendingCount == 0) + + try harness.scheduler.advance(by: 0.1) + harness.engine.send(.commandIssued(.retile)) + try harness.scheduler.runReady() + #expect(harness.world.pendingWriteCount == 1) + try harness.world.completeNextWrite() + #expect(harness.world.frames[WindowID(rawValue: 1)] == engineScreen) + #expect(harness.engine.writeMetrics[MotionAppID(rawValue: engineApp.pid)]?.sampleCount == 1) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func vanishingAppReportsFailureAndRemovesWindows() async throws { + let harness = try EngineHarness() + harness.world.behaviors[engineApp] = FakeEngineWorld.Behavior(vanishes: true) + try await harness.start() + try harness.add([1, 2]) + + #expect(harness.log.platformFailures == [.vanished(WindowID(rawValue: 1)), .vanished(WindowID(rawValue: 2))]) + #expect(harness.engine.snapshot.state.windows.isEmpty) + #expect(harness.engine.snapshot.state.frames.isEmpty) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func invalidLaunchTimestampIsSurfaced() async throws { + let harness = try EngineHarness() + try await harness.start() + harness.world.emit(.appLaunched(engineApp, at: .nan)) + #expect(harness.engine.writeMetrics.isEmpty) + #expect(harness.log.diagnostics.contains { if case .configuration = $0 { true } else { false } }) + await harness.engine.stop() + } +} diff --git a/Tests/TesseraEngineTests/ReplayTests.swift b/Tests/TesseraEngineTests/ReplayTests.swift new file mode 100644 index 00000000..ff72a9c4 --- /dev/null +++ b/Tests/TesseraEngineTests/ReplayTests.swift @@ -0,0 +1,72 @@ +import TesseraCore +import Testing + +private let recordedEngineEvents = #""" + {"event":{"displaySetChanged":{"_0":[{"frame":{"origin":{"xCoordinate":0,"yCoordinate":0},"size":{"height":800,"width":1200}},"id":"00000000-0000-0000-0000-000000000001"},{"frame":{"origin":{"xCoordinate":1200,"yCoordinate":0},"size":{"height":800,"width":1200}},"id":"00000000-0000-0000-0000-000000000002"}]}},"version":1} + {"event":{"activeSpaceChanged":{"display":"00000000-0000-0000-0000-000000000001","space":1}},"version":1} + {"event":{"activeSpaceChanged":{"display":"00000000-0000-0000-0000-000000000002","space":2}},"version":1} + {"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":1,"isFloating":false,"role":"AXWindow","title":"Window 1"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000001","space":1}}},"version":1} + {"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":2,"isFloating":false,"role":"AXWindow","title":"Window 2"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000001","space":1}}},"version":1} + {"event":{"windowAppeared":{"_0":{"app":{"bundleID":"test.fixture","pid":100},"id":3,"isFloating":false,"role":"AXWindow","title":"Window 3"},"frame":{"origin":{"xCoordinate":30,"yCoordinate":40},"size":{"height":200,"width":300}},"workspace":{"display":"00000000-0000-0000-0000-000000000002","space":2}}},"version":1} + {"event":{"focusChanged":{"_0":1}},"version":1} + {"event":{"commandIssued":{"_0":{"setWindowCap":{"_0":1}}}},"version":1} + {"event":{"commandIssued":{"_0":{"moveToDisplay":{"_0":"right"}}}},"version":1} + {"event":{"commandIssued":{"_0":{"setLayout":{"_0":"rows"}}}},"version":1} + """# + +@Suite("Engine recorded event replay") +@MainActor +struct TesseraEngineReplayTests { + @Test func recordedJSONLinesMatchCoreReplayThroughEngine() async throws { + var configuration = engineConfiguration(layout: .grid) + configuration.layout.global.windowCap = 8 + let harness = try EngineHarness(configuration: configuration, initialState: State()) + try await harness.start() + let events = try EventStream.decode(recordedEngineEvents) + #expect(events.count == 10) + let expected = try Replay.run(jsonLines: recordedEngineEvents) + + for event in events { + harness.engine.send(event) + try harness.scheduler.runReady() + try harness.scheduler.advance(by: 0.1) + } + + #expect(harness.engine.snapshot.state == expected.state) + #expect(harness.engine.snapshot.focusedWindow == WindowID(rawValue: 1)) + #expect( + harness.engine.snapshot.state.workspace(containing: WindowID(rawValue: 1)) + == WorkspaceKey(display: secondEngineDisplay, space: SpaceID(rawValue: 2))) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] + == Rect(x: 1200, y: 400, width: 1200, height: 400)) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 3)] == Rect(x: 1200, y: 0, width: 1200, height: 400) + ) + for tile in harness.engine.snapshot.tiles { #expect(harness.world.frames[tile.window] == tile.frame) } + #expect(harness.engine.isIdle) + #expect(harness.log.platformFailures.isEmpty) + #expect(harness.log.motionErrors.isEmpty) + await harness.engine.stop() + } + + @Test func recordedJSONLinesCanBeCoalescedIntoOnePass() async throws { + var configuration = engineConfiguration(layout: .grid) + configuration.layout.global.windowCap = 8 + let harness = try EngineHarness(configuration: configuration, initialState: State()) + try await harness.start() + let events = try EventStream.decode(recordedEngineEvents) + let expected = Replay.run(events) + let passes = harness.engine.layoutPassCount + for event in events { harness.engine.send(event) } + try harness.scheduler.runReady() + + #expect(harness.engine.layoutPassCount == passes + 1) + #expect(harness.engine.snapshot.state == expected.state) + #expect(harness.scheduler.pendingCount == 1) + try harness.scheduler.runNext() + for tile in harness.engine.snapshot.tiles { #expect(harness.world.frames[tile.window] == tile.frame) } + #expect(harness.engine.isIdle) + await harness.engine.stop() + } +} diff --git a/Tests/TesseraEngineTests/TesseraEngineTests.swift b/Tests/TesseraEngineTests/TesseraEngineTests.swift index 9eade55b..baa02b8a 100644 --- a/Tests/TesseraEngineTests/TesseraEngineTests.swift +++ b/Tests/TesseraEngineTests/TesseraEngineTests.swift @@ -1,4 +1,257 @@ +import TesseraCore +import TesseraEngine import Testing -@testable import TesseraEngine -@Test func builds() {} +@Suite("Engine observations") +@MainActor +struct TesseraEngineTests { + @Test func newWindowsProduceOneLayoutAndOnlyChangedWrites() async throws { + let harness = try EngineHarness() + try await harness.start() + let passes = harness.engine.layoutPassCount + try harness.add([1, 2]) + + let first = WindowID(rawValue: 1) + let second = WindowID(rawValue: 2) + #expect(harness.engine.layoutPassCount == passes + 1) + #expect(harness.engine.snapshot.state.frames[first] == Rect(x: 0, y: 0, width: 600, height: 800)) + #expect(harness.engine.snapshot.state.frames[second] == Rect(x: 600, y: 0, width: 600, height: 800)) + #expect(harness.world.writes.count == 1) + #expect(harness.world.allWrites.map(\.window) == [first, second]) + #expect(harness.world.frames == harness.engine.snapshot.state.frames) + #expect(harness.engine.snapshot.focusedWindow == second) + #expect(harness.world.focused == [second]) + #expect(harness.announcer.announcements == [.focused(second)]) + #expect(harness.engine.isIdle) + + let writeCount = harness.world.writes.count + harness.world.emit(.observed(.focusChanged(second))) + try harness.scheduler.runReady() + #expect(harness.world.writes.count == writeCount) + #expect(harness.engine.snapshot.tiles.map(\.window) == [first, second]) + #expect(harness.engine.snapshot.layouts[engineDisplay] == .columns) + await harness.engine.stop() + } + + @Test func closingFocusedWindowExpandsSurvivorAndRestoresFocus() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let first = WindowID(rawValue: 1) + let second = WindowID(rawValue: 2) + let previousWrites = harness.world.allWrites.count + + harness.world.disappear(second) + try harness.scheduler.runReady() + try harness.finishMotion() + + #expect(harness.engine.snapshot.state.windows[second] == nil) + #expect(harness.engine.snapshot.state.frames[second] == nil) + #expect(harness.engine.snapshot.state.observedFrames[second] == nil) + #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.order == [first]) + #expect(harness.engine.snapshot.focusedWindow == first) + #expect(harness.world.focused.last == first) + #expect(harness.world.frames[first] == engineScreen) + #expect(harness.world.allWrites.dropFirst(previousWrites).allSatisfy { $0.window == first }) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test(arguments: [false, true]) + func tiledUserDragSnapsWithoutRearranging(resized: Bool) async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2, 3]) + let first = WindowID(rawValue: 1) + let before = harness.engine.snapshot.state + let dragged = Rect(x: 760, y: 140, width: 250, height: 350) + + harness.world.userFrame(first, frame: dragged, resized: resized) + try harness.scheduler.runReady() + try harness.finishMotion() + + #expect( + harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree == before.workspaces[engineWorkspace]?.tree) + #expect( + harness.engine.snapshot.state.workspaces[engineWorkspace]?.order + == before.workspaces[engineWorkspace]?.order) + #expect(harness.engine.snapshot.state.frames == before.frames) + #expect(harness.engine.snapshot.state.observedFrames[first] == dragged) + #expect(harness.world.frames[first] == before.frames[first]) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test(arguments: [false, true]) + func floatingUserFrameIsPreservedExactly(resized: Bool) async throws { + let harness = try EngineHarness() + try await harness.start() + let floating = engineWindow(7, floating: true) + harness.world.appear(floating) + try harness.scheduler.runReady() + let writes = harness.world.writes.count + let exact = Rect(x: -35.25, y: 99.75, width: 1350.5, height: 901.125) + + harness.world.userFrame(floating.id, frame: exact, resized: resized) + try harness.scheduler.runReady() + + #expect(harness.engine.snapshot.state.frames[floating.id] == exact) + #expect(harness.engine.snapshot.state.observedFrames[floating.id] == exact) + #expect(harness.world.frames[floating.id] == exact) + #expect(harness.world.writes.count == writes) + #expect(harness.engine.snapshot.state.workspaces[engineWorkspace]?.tree == nil) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func oneHundredEventsHaveOneLayoutPass() async throws { + let harness = try EngineHarness() + try await harness.start() + let passes = harness.engine.layoutPassCount + let revision = harness.engine.snapshot.revision + let scheduled = harness.scheduler.scheduledCount + for id in UInt32(1)...100 { harness.world.appear(engineWindow(id)) } + + #expect(harness.scheduler.pendingCount == 1) + #expect(harness.scheduler.scheduledCount == scheduled + 1) + try harness.scheduler.runReady() + + #expect(harness.engine.layoutPassCount == passes + 1) + #expect(harness.engine.snapshot.revision == revision + 1) + #expect(harness.engine.snapshot.state.windows.count == 100) + #expect(harness.engine.snapshot.state.frames.count == 100) + #expect(harness.world.focused == [WindowID(rawValue: 100)]) + #expect(harness.world.writes.count == 1) + #expect(harness.world.allWrites.count == 100) + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func repeatedObservationKeepsExistingFocus() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let first = WindowID(rawValue: 1) + harness.world.emit(.observed(.focusChanged(first))) + try harness.scheduler.runReady() + let before = harness.engine.snapshot.state.workspaces[engineWorkspace] + + harness.world.appear(engineWindow(2), frame: try #require(harness.world.frames[WindowID(rawValue: 2)])) + try harness.scheduler.runReady() + + #expect(harness.engine.snapshot.focusedWindow == first) + #expect(harness.engine.snapshot.state.workspaces[engineWorkspace] == before) + await harness.engine.stop() + } + + @Test func unknownWindowAndInvalidGeometryAreSurfaced() async throws { + let harness = try EngineHarness() + try await harness.start() + let unknown = WindowID(rawValue: 999) + harness.engine.send(.windowMovedByUser(unknown, frame: initialEngineFrame)) + harness.world.appear(engineWindow(1), frame: Rect(x: .nan, y: 0, width: 10, height: 10)) + try harness.scheduler.runReady() + + #expect(harness.log.reports == [.unknownWindow(unknown), .invalidGeometry]) + #expect(harness.engine.snapshot.state.windows.isEmpty) + #expect(harness.world.writes.isEmpty) + await harness.engine.stop() + } +} + +@MainActor +final class EngineCommandBatch { + private(set) var started = 0 + private(set) var tasks: [Task] = [] + + init(_ commands: [Command], engine: TesseraEngine) { + for command in commands { + tasks.append( + Task { @MainActor in + self.started += 1 + return try await engine.perform(command) + }) + } + } + + func waitUntilEnqueued() async throws { + for _ in 0..<100 where started < tasks.count { await Task.yield() } + try #require(started == tasks.count, "Command tasks did not enter perform") + } + + func results() async throws -> [EngineCommandResult] { + var results: [EngineCommandResult] = [] + for task in tasks { results.append(try await task.value) } + return results + } +} + +@Suite("Engine commands") +@MainActor +struct TesseraEngineCommandTests { + @Test func asyncCommandsCoalesceAndRetainIndividualReports() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + let passes = harness.engine.layoutPassCount + let beforeRevision = harness.engine.snapshot.revision + let batch = EngineCommandBatch([.setLayout(.rows), .focus(.right), .retile], engine: harness.engine) + try await batch.waitUntilEnqueued() + + #expect(harness.engine.layoutPassCount == passes) + #expect(harness.scheduler.pendingCount == 1) + try harness.scheduler.runReady() + let results = try await batch.results() + + #expect(harness.engine.layoutPassCount == passes + 1) + #expect(results.allSatisfy { $0.revision == beforeRevision + 1 }) + #expect(results[0].isAccepted) + #expect(results[0].reports.isEmpty) + #expect(!results[1].isAccepted) + #expect(results[1].reports == [.noNeighbor(.right)]) + #expect(results[2].isAccepted) + #expect(results[2].reports == [.retiled(moved: 2)]) + #expect(harness.engine.snapshot.layouts[engineDisplay] == .rows) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 1)] == Rect(x: 0, y: 0, width: 1200, height: 400)) + #expect( + harness.engine.snapshot.state.frames[WindowID(rawValue: 2)] == Rect(x: 0, y: 400, width: 1200, height: 400)) + try harness.finishMotion() + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func acceptedCommandReturnsBeforeDeferredWindowWrite() async throws { + let harness = try EngineHarness() + try await harness.start() + try harness.add([1, 2]) + try harness.scheduler.advance(by: 0.01) + harness.world.deferWrites = true + let batch = EngineCommandBatch([.setLayout(.rows)], engine: harness.engine) + try await batch.waitUntilEnqueued() + try harness.scheduler.runReady() + let result = try #require(try await batch.results().first) + + #expect(result.isAccepted) + #expect(result.revision == harness.engine.snapshot.revision) + #expect(harness.world.pendingWriteCount == 1) + #expect(!harness.engine.isIdle) + try harness.world.completeNextWrite() + #expect(harness.engine.isIdle) + await harness.engine.stop() + } + + @Test func commandsWithoutWorkspaceReturnFailureReports() async throws { + let harness = try EngineHarness(initialState: State()) + try await harness.start() + let batch = EngineCommandBatch([.retile, .toggleFloat], engine: harness.engine) + try await batch.waitUntilEnqueued() + try harness.scheduler.runReady() + let results = try await batch.results() + + #expect(results.map(\.isAccepted) == [false, false]) + #expect(results.map(\.reports) == [[.noActiveWorkspace], [.noFocusedWindow]]) + #expect(harness.log.reports == [.noActiveWorkspace, .noFocusedWindow]) + await harness.engine.stop() + } +} diff --git a/Tests/TesseraEngineTests/TestSupport.swift b/Tests/TesseraEngineTests/TestSupport.swift new file mode 100644 index 00000000..5dec85e4 --- /dev/null +++ b/Tests/TesseraEngineTests/TestSupport.swift @@ -0,0 +1,431 @@ +import TesseraAnimation +import TesseraConfig +import TesseraCore +import TesseraEngine +import Testing + +let engineDisplay = DisplayID(rawValue: "00000000-0000-0000-0000-000000000001") +let secondEngineDisplay = DisplayID(rawValue: "00000000-0000-0000-0000-000000000002") +let engineSpace = SpaceID(rawValue: 1) +let engineWorkspace = WorkspaceKey(display: engineDisplay, space: engineSpace) +let engineApp = AppID(pid: 100, bundleID: "test.fixture") +let secondEngineApp = AppID(pid: 200, bundleID: "test.second") +let engineScreen = Rect(x: 0, y: 0, width: 1200, height: 800) +let initialEngineFrame = Rect(x: 40, y: 60, width: 300, height: 200) + +func engineWindow(_ id: UInt32, app: AppID = engineApp, floating: Bool = false, title: String = "Document") + -> ManagedWindow +{ + ManagedWindow(id: WindowID(rawValue: id), app: app, title: title, isFloating: floating) +} + +func engineConfiguration(glide: Bool = false, layout: ConfigLayout = .columns) -> TesseraConfiguration { + TesseraConfiguration( + layout: LayoutConfiguration(global: LayoutValues(defaultLayout: layout, gaps: LayoutGaps(inner: 0, outer: 0))), + motion: MotionConfiguration(transitions: glide ? .glide : .snap) + ) +} + +func engineInitialState(twoDisplays: Bool = false) -> State { + let first = Display(id: engineDisplay, frame: engineScreen) + if twoDisplays { + let second = Display(id: secondEngineDisplay, frame: Rect(x: 1200, y: 0, width: 1200, height: 800)) + return State( + displays: [first, second], + activeSpaces: [engineDisplay: engineSpace, secondEngineDisplay: SpaceID(rawValue: 2)]) + } + return State(displays: [first], activeSpaces: [engineDisplay: engineSpace]) +} + +@MainActor +final class ManualEngineClock: EngineClock { + var now: Double = 10 +} + +@MainActor +final class ManualEngineCancellation: EngineCancellation { + private(set) var isCancelled = false + func cancel() { isCancelled = true } +} + +@MainActor +final class ManualEngineScheduler: EngineScheduler { + private struct Work { + let identifier: Int + let deadline: Double + let cancellation: ManualEngineCancellation + let action: @MainActor () -> Void + } + + private let clock: ManualEngineClock + private var work: [Work] = [] + private var nextIdentifier = 0 + private(set) var scheduledCount = 0 + var pendingCount: Int { work.filter { !$0.cancellation.isCancelled }.count } + var readyCount: Int { work.filter { !$0.cancellation.isCancelled && $0.deadline <= clock.now }.count } + var cancelledCount: Int { work.filter { $0.cancellation.isCancelled }.count } + var nextDeadline: Double? { work.filter { !$0.cancellation.isCancelled }.map(\.deadline).min() } + + init(clock: ManualEngineClock) { self.clock = clock } + + func schedule(after delay: Double, _ action: @escaping @MainActor () -> Void) -> any EngineCancellation { + precondition(delay.isFinite && delay >= 0) + let cancellation = ManualEngineCancellation() + nextIdentifier += 1 + scheduledCount += 1 + work.append( + Work(identifier: nextIdentifier, deadline: clock.now + delay, cancellation: cancellation, action: action)) + return cancellation + } + + func runReady(limit: Int = 1000) throws { + var executed = 0 + while let index = work.indices.filter({ !work[$0].cancellation.isCancelled && work[$0].deadline <= clock.now }) + .min(by: { + let lhs = work[$0] + let rhs = work[$1] + return lhs.deadline == rhs.deadline ? lhs.identifier < rhs.identifier : lhs.deadline < rhs.deadline + }) + { + guard executed < limit else { throw HarnessError.schedulerDidNotQuiesce } + let ready = work.remove(at: index) + ready.action() + executed += 1 + } + } + + func advance(by interval: Double) throws { + precondition(interval >= 0) + clock.now += interval + try runReady() + } + + func runNext() throws { + guard let deadline = nextDeadline else { throw HarnessError.noScheduledWork } + clock.now = max(clock.now, deadline) + try runReady() + } + + func fireCancelledWork() { + let cancelled = work.filter { $0.cancellation.isCancelled } + work.removeAll { $0.cancellation.isCancelled } + for item in cancelled { item.action() } + } +} + +enum HarnessError: Error { + case schedulerDidNotQuiesce + case noScheduledWork + case missingWrite + case missingAction + case missingConfigurationStart + case startup +} + +@MainActor +final class FakeEngineWorld: EngineWindowWorld { + struct Behavior { + var duration: Double = 0.001 + var minimumSize: Size? + var timesOut = false + var vanishes = false + } + + struct WriteRecord { + let app: AppID + let writes: [EngineFrameWrite] + let at: Double + } + + private struct PendingWrite { + let record: WriteRecord + let completion: @MainActor (EngineWriteReceipt) -> Void + } + + private let clock: ManualEngineClock + private var receive: (@MainActor (EnginePlatformEvent) -> Void)? + private var retainedReceive: (@MainActor (EnginePlatformEvent) -> Void)? + private var receivers: [@MainActor (EnginePlatformEvent) -> Void] = [] + private var pendingWrites: [PendingWrite] = [] + private var pendingActions: [@MainActor (EnginePlatformFailure?) -> Void] = [] + var frames: [WindowID: Rect] = [:] + var behaviors: [AppID: Behavior] = [:] + var deferWrites = false + var deferActions = false + var startError: HarnessError? + var emitsEngineEchoes = false + private(set) var writes: [WriteRecord] = [] + private(set) var focused: [WindowID] = [] + private(set) var raised: [WindowID] = [] + private(set) var startCount = 0 + private(set) var stopCount = 0 + var pendingWriteCount: Int { pendingWrites.count } + var pendingActionCount: Int { pendingActions.count } + var allWrites: [EngineFrameWrite] { writes.flatMap(\.writes) } + + init(clock: ManualEngineClock) { self.clock = clock } + + func start(receive: @escaping @MainActor (EnginePlatformEvent) -> Void) throws { + startCount += 1 + if let startError { throw startError } + self.receive = receive + retainedReceive = receive + receivers.append(receive) + } + + func stop() { + stopCount += 1 + receive = nil + } + + func emit(_ event: EnginePlatformEvent) { receive?(event) } + func emitLate(_ event: EnginePlatformEvent) { retainedReceive?(event) } + func emitFromStart(_ index: Int, event: EnginePlatformEvent) { receivers[index](event) } + + func appear(_ window: ManagedWindow, workspace: WorkspaceKey = engineWorkspace, frame: Rect = initialEngineFrame) { + frames[window.id] = frame + emit(.observed(.windowAppeared(window, workspace: workspace, frame: frame))) + } + + func disappear(_ window: WindowID) { + frames[window] = nil + emit(.observed(.windowDisappeared(window))) + } + + func userFrame(_ window: WindowID, frame: Rect, resized: Bool = false, origin: FrameChangeOrigin = .user) { + frames[window] = frame + emit(.frameChanged(window, frame: frame, resized: resized, origin: origin)) + } + + func write( + _ frames: [EngineFrameWrite], for app: AppID, completion: @escaping @MainActor (EngineWriteReceipt) -> Void + ) { + let record = WriteRecord(app: app, writes: frames, at: clock.now) + writes.append(record) + if deferWrites { + pendingWrites.append(PendingWrite(record: record, completion: completion)) + } else { + completion(makeReceipt(record)) + } + } + + func focus(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { + focused.append(window) + completeAction(completion) + } + + func raise(_ window: WindowID, completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { + raised.append(window) + completeAction(completion) + } + + func completeNextWrite(receipt: EngineWriteReceipt? = nil) throws { + guard !pendingWrites.isEmpty else { throw HarnessError.missingWrite } + let pending = pendingWrites.removeFirst() + pending.completion(receipt ?? makeReceipt(pending.record)) + } + + func completeNextAction(failure: EnginePlatformFailure? = nil) throws { + guard !pendingActions.isEmpty else { throw HarnessError.missingAction } + pendingActions.removeFirst()(failure) + } + + func writes(for window: WindowID) -> [EngineFrameWrite] { allWrites.filter { $0.window == window } } + + private func completeAction(_ completion: @escaping @MainActor (EnginePlatformFailure?) -> Void) { + if deferActions { pendingActions.append(completion) } else { completion(nil) } + } + + private func makeReceipt(_ record: WriteRecord) -> EngineWriteReceipt { + let behavior = behaviors[record.app] ?? Behavior() + if behavior.vanishes { + for write in record.writes { frames[write.window] = nil } + return EngineWriteReceipt( + frames: [], failures: record.writes.map { .vanished($0.window) }, duration: behavior.duration) + } + if behavior.timesOut { + return EngineWriteReceipt(frames: [], failures: [.timedOut(record.app)], duration: behavior.duration) + } + let observed = record.writes.map { write in + var frame = write.frame + if let minimum = behavior.minimumSize { + frame.size = Size( + width: max(frame.size.width, minimum.width), height: max(frame.size.height, minimum.height)) + } + frames[write.window] = frame + if emitsEngineEchoes { + emit(.frameChanged(write.window, frame: frame, resized: true, origin: .engine(write.transaction))) + } + return WindowFrame(window: write.window, frame: frame) + } + return EngineWriteReceipt(frames: observed, duration: behavior.duration) + } +} + +@MainActor +final class FakeEngineDisplayLink: EngineDisplayLink { + private var tick: (@MainActor (Double) -> Void)? + private var retainedTick: (@MainActor (Double) -> Void)? + private(set) var isRunning = false + private(set) var startCount = 0 + private(set) var stopCount = 0 + + func start(tick: @escaping @MainActor (Double) -> Void) { + self.tick = tick + retainedTick = tick + isRunning = true + startCount += 1 + } + + func stop() { + isRunning = false + tick = nil + stopCount += 1 + } + + func fire(at timestamp: Double) { tick?(timestamp) } + func fireLate(at timestamp: Double) { retainedTick?(timestamp) } +} + +@MainActor +final class FakeEngineLinks { + private(set) var links: [DisplayID: FakeEngineDisplayLink] = [:] + var creationFailure = false + var runningCount: Int { links.values.filter(\.isRunning).count } + + func make(_ display: DisplayID) throws -> any EngineDisplayLink { + if creationFailure { throw HarnessError.startup } + let link = FakeEngineDisplayLink() + links[display] = link + return link + } + + func tickAll(at timestamp: Double) { + for display in links.keys.sorted() { links[display]?.fire(at: timestamp) } + } +} + +@MainActor +final class FakeEngineAnnouncer: EngineAnnouncer { + private(set) var announcements: [Announcement] = [] + func announce(_ announcement: Announcement) { announcements.append(announcement) } +} + +@MainActor +final class FakeEngineLog: EngineLogSink { + private(set) var diagnostics: [EngineDiagnostic] = [] + var platformFailures: [EnginePlatformFailure] { + diagnostics.compactMap { if case .platform(let failure) = $0 { failure } else { nil } } + } + var reports: [Report] { + diagnostics.compactMap { if case .core(let report) = $0 { report } else { nil } } + } + var motionErrors: [MotionError] { + diagnostics.compactMap { if case .motion(let error) = $0 { error } else { nil } } + } + func record(_ diagnostic: EngineDiagnostic) { diagnostics.append(diagnostic) } +} + +@MainActor +final class FakeEngineTrace: EngineTraceSink { + struct Entry: Equatable { + let stage: EngineTraceStage + let transaction: UInt64 + let begins: Bool + } + private(set) var entries: [Entry] = [] + func begin(_ stage: EngineTraceStage, transaction: UInt64) { + entries.append(Entry(stage: stage, transaction: transaction, begins: true)) + } + func end(_ stage: EngineTraceStage, transaction: UInt64) { + entries.append(Entry(stage: stage, transaction: transaction, begins: false)) + } + + func balance(for stage: EngineTraceStage) -> Int { + entries.filter { $0.stage == stage }.reduce(0) { $0 + ($1.begins ? 1 : -1) } + } +} + +@MainActor +final class FakeEngineConfigurationSource: EngineConfigurationSource { + var initial: TesseraConfiguration + var startError: HarnessError? + var deferStart = false + private var changed: (@MainActor (ConfigSnapshot) -> Void)? + private var retainedChanges: [@MainActor (ConfigSnapshot) -> Void] = [] + private var startContinuation: CheckedContinuation? + private(set) var startCount = 0 + private(set) var stopCount = 0 + var isSubscribed: Bool { changed != nil } + var isAwaitingStart: Bool { startContinuation != nil } + + init(initial: TesseraConfiguration = engineConfiguration()) { self.initial = initial } + + func start(changed: @escaping @MainActor (ConfigSnapshot) -> Void) async throws -> TesseraConfiguration { + startCount += 1 + self.changed = changed + retainedChanges.append(changed) + if let startError { throw startError } + if deferStart { + return try await withCheckedThrowingContinuation { startContinuation = $0 } + } + return initial + } + + func stop() async { + stopCount += 1 + changed = nil + } + + func emit(_ snapshot: ConfigSnapshot) { changed?(snapshot) } + func emitFromStart(_ index: Int, snapshot: ConfigSnapshot) { retainedChanges[index](snapshot) } + + func completeStart() throws { + guard let continuation = startContinuation else { throw HarnessError.missingConfigurationStart } + startContinuation = nil + continuation.resume(returning: initial) + } +} + +@MainActor +final class EngineHarness { + let clock = ManualEngineClock() + let scheduler: ManualEngineScheduler + let world: FakeEngineWorld + let links = FakeEngineLinks() + let announcer = FakeEngineAnnouncer() + let log = FakeEngineLog() + let trace = FakeEngineTrace() + let engine: TesseraEngine + + init( + configuration: TesseraConfiguration = engineConfiguration(), initialState: State = engineInitialState(), + configSource: (any EngineConfigurationSource)? = nil + ) throws { + scheduler = ManualEngineScheduler(clock: clock) + world = FakeEngineWorld(clock: clock) + let links = links + engine = try TesseraEngine( + world: world, clock: clock, scheduler: scheduler, displayLink: { try links.make($0) }, + announcer: announcer, log: log, configuration: configuration, initialState: initialState, + configSource: configSource, trace: trace, + reduceMotionSource: nil + ) + } + + func start() async throws { + try await engine.start() + try scheduler.runReady() + } + + func add(_ ids: [UInt32], app: AppID = engineApp, workspace: WorkspaceKey = engineWorkspace) throws { + for id in ids { world.appear(engineWindow(id, app: app), workspace: workspace) } + try scheduler.runReady() + } + + func finishMotion(after interval: Double = 2) throws { + clock.now += interval + links.tickAll(at: clock.now) + try scheduler.runReady() + } +} -- knotmirror 0.0.1 From 562108f162dc469d17475d25d64f897adb6f19c9 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 00:06:08 -0400 Subject: [PATCH 43/44] Route shell-only commands away from the engine --- Sources/TesseraEngine/EngineIPCHandler.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/TesseraEngine/EngineIPCHandler.swift b/Sources/TesseraEngine/EngineIPCHandler.swift index f36773db..285d3a16 100644 --- a/Sources/TesseraEngine/EngineIPCHandler.swift +++ b/Sources/TesseraEngine/EngineIPCHandler.swift @@ -62,7 +62,7 @@ public enum EngineCommandParser { case .displayMoveRight: .moveToDisplay(.right) case .displayMoveUp: .moveToDisplay(.up) case .displayMoveDown: .moveToDisplay(.down) - case .openSettings: + case .openSettings, .pauseTiling, .quit: throw IPCError( code: "shell_command", message: String(localized: "This command is handled by the app shell.", bundle: .module)) -- knotmirror 0.0.1 From 0eb09e499f0173ff3470941d4de0ae8010d19f0e Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sat, 31 Oct 2026 00:06:29 -0400 Subject: [PATCH 44/44] Cover all shell-only commands in the parser test --- Tests/TesseraEngineTests/IPCTests.swift | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/Tests/TesseraEngineTests/IPCTests.swift b/Tests/TesseraEngineTests/IPCTests.swift index de1b572a..5f5bc038 100644 --- a/Tests/TesseraEngineTests/IPCTests.swift +++ b/Tests/TesseraEngineTests/IPCTests.swift @@ -21,18 +21,22 @@ private let configuredEngineCommands: [(ConfigCommand, Command)] = [ (.displayMoveUp, .moveToDisplay(.up)), (.displayMoveDown, .moveToDisplay(.down)), ] +private let shellCommands: Set = [.openSettings, .pauseTiling, .quit] + @Suite("Engine command parser") struct TesseraEngineParserTests { @Test func everyConfigCommandHasExplicitMappingOrShellRejection() throws { - #expect(Set(configuredEngineCommands.map { $0.0 }).union([.openSettings]) == Set(ConfigCommand.allCases)) + #expect(Set(configuredEngineCommands.map { $0.0 }).union(shellCommands) == Set(ConfigCommand.allCases)) for (configured, expected) in configuredEngineCommands { #expect(try EngineCommandParser.command(configured) == expected) #expect(try EngineCommandParser.parse(configured.rawValue) == expected) } - do { - _ = try EngineCommandParser.command(.openSettings) - Issue.record("The settings command must remain with the app shell") - } catch let error as IPCError { #expect(error.code == "shell_command") } + for command in shellCommands { + do { + _ = try EngineCommandParser.command(command) + Issue.record("\(command) must stay with the app shell") + } catch let error as IPCError { #expect(error.code == "shell_command") } + } } @Test func directionalAndLayoutArgumentsAreMappedExhaustively() throws {