Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271import AppKitimport Carbonimport Foundationimport ParcelPlatformimport RealityDriverSupport
@MainActorfunc checkTabView(_ session: RealitySession) async throws { try TabViewConsoleSession.requireUnlockedConsole() try requireTabViewModifierReleaseRouting() try session.configure() var owned = try await session.startingWindows([.textEdit, .textEdit, .textEdit]) try await session.start() try await session.tiles(owned) let starting = try session.readFrames(owned) owned = zip(owned, starting).sorted { $0.1.x < $1.1.x }.map(\.0) let frames = try session.readFrames(owned) guard FrameOracle.stripeShape(frames, visible: session.visible, vertical: true) else { throw RealityError("Tab View requires three independently observed column tiles") }
// The opening selection is the previous focus; right then selects the third column. try await session.apps.focus(owned[1]) try await Task.sleep(for: .milliseconds(300)) try await session.apps.focus(owned[0]) try await Task.sleep(for: .milliseconds(300)) try await tabViewInput(session, arrow: UInt16(kVK_RightArrow), stage: "other-tile") try await session.expect("Tab View focuses third column \(owned[2].id) without moving \(frames)") { rows in try RealApps.focusedID(rows) == owned[2].id && TabViewRealityOracle.onscreenOrder(try FrameOracle.read(onScreenOnly: true), ids: owned.map(\.id)).first == owned[2].id && zip(try FrameOracle.frames(rows, ids: owned.map(\.id)), frames).allSatisfy { $0.matches($1) } }
try await Task.sleep(for: .milliseconds(300)) _ = try await session.driver.send(.minimize(pid: owned[2].pid, windowID: owned[2].id)) try await session.expect("Minimized owned window \(owned[2].id) is no longer onscreen") { rows in !rows.contains { $0.id == owned[2].id && $0.onscreen } } try await session.tiles(Array(owned.prefix(2))) try await session.apps.focus(owned[0]) try await Task.sleep(for: .milliseconds(500)) let minimizedFrames = try session.readFrames(Array(owned.prefix(2))) try await tabViewInput(session, arrow: UInt16(kVK_DownArrow), stage: "minimized") try await session.expect( "Tab View restores and focuses \(owned[2].id); original tile frames return to \(frames)", timeout: .seconds(10) ) { rows in guard RealApps.focusedID(rows) == owned[2].id, TabViewRealityOracle.onscreenOrder(try FrameOracle.read(onScreenOnly: true), ids: owned.map(\.id)).first == owned[2].id, owned.allSatisfy({ window in rows.contains { $0.id == window.id && $0.onscreen } }) else { return false } let restored = try FrameOracle.frames(rows, ids: owned.map(\.id)) return FrameOracle.tiles(restored, visible: session.visible) && zip(restored, frames).allSatisfy { $0.matches($1) } && zip(restored.prefix(2), minimizedFrames).contains { !$0.matches($1) } }
_ = try await session.driver.send(.minimize(pid: owned[2].pid, windowID: owned[2].id)) try await session.expect("Second minimize leaves only the two owned windows onscreen") { rows in !rows.contains { $0.id == owned[2].id && $0.onscreen } } try await session.command("layout-rows") try await session.tiles(Array(owned.prefix(2))) try await session.apps.focus(owned[0]) try await Task.sleep(for: .milliseconds(500)) try await tabViewInput(session, arrow: UInt16(kVK_DownArrow), stage: "changed-layout") try await session.expect("Changed layout restores into the focused workspace's next row slot") { rows in guard owned.allSatisfy({ window in rows.contains { $0.id == window.id && $0.onscreen } }) else { return false } let restored = try FrameOracle.frames(rows, ids: owned.map(\.id)) return RealApps.focusedID(rows) == owned[2].id && FrameOracle.stripeShape(restored, visible: session.visible, vertical: false) }}
@MainActorfunc checkTabViewAutomaticTilingOff(_ session: RealitySession) async throws { try TabViewConsoleSession.requireUnlockedConsole() try requireTabViewModifierReleaseRouting() try session.configure() let owned = try await session.startingWindows([.textEdit, .textEdit, .textEdit]) try await session.start() try await session.tiles(owned) let starting = try session.readFrames(owned) let ordered = zip(owned, starting).sorted { $0.1.x < $1.1.x }.map(\.0) guard FrameOracle.stripeShape(try session.readFrames(ordered), visible: session.visible, vertical: true) else { throw RealityError("Automatic tiling off check requires three independently observed column tiles") } let acceptance = try await session.command("toggle-automatic-tiling") guard acceptance.automaticTiling == false else { throw RealityError("Automatic tiling must be off before the Tab View off-state check") } try await requireAutomaticTilingOff(session) let neighbors = Array(ordered.prefix(2)) let neighborIDs = neighbors.map(\.id) let before = try session.readFrames(neighbors) session.recordExpectation( "Automatic tiling off: neighbors \(neighborIDs) retain \(before) throughout switch and restore")
let artifact = session.directory.appendingPathComponent("tab-view-off-frames.json") let monitor = Task { @MainActor in try await observeTabViewNeighbors(ids: neighborIDs, frames: before, artifact: artifact) } do { try await session.apps.focus(ordered[1]) try await Task.sleep(for: .milliseconds(300)) try await session.apps.focus(ordered[0]) try await Task.sleep(for: .milliseconds(300)) try await tabViewInput(session, arrow: UInt16(kVK_RightArrow), stage: "off-other-tile") try await session.expect("Automatic tiling off: Tab View focuses the third column") { rows in try RealApps.focusedID(rows) == ordered[2].id && TabViewRealityOracle.onscreenOrder(try FrameOracle.read(onScreenOnly: true), ids: ordered.map(\.id)) .first == ordered[2].id } _ = try await session.driver.send(.minimize(pid: ordered[2].pid, windowID: ordered[2].id)) try await session.expect("Automatic tiling off: selected window is minimized") { rows in !rows.contains { $0.id == ordered[2].id && $0.onscreen } } try await session.apps.focus(ordered[0]) try await Task.sleep(for: .milliseconds(500)) try await tabViewInput(session, arrow: UInt16(kVK_DownArrow), stage: "off-minimized") try await session.expect( "Automatic tiling off: Tab View restores and focuses the minimized window", timeout: .seconds(10) ) { rows in try rows.contains { $0.id == ordered[2].id && $0.onscreen } && RealApps.focusedID(rows) == ordered[2].id && TabViewRealityOracle.onscreenOrder(try FrameOracle.read(onScreenOnly: true), ids: ordered.map(\.id)) .first == ordered[2].id } try await Task.sleep(for: .seconds(1)) try await requireAutomaticTilingOff(session) } catch { let actionError = error monitor.cancel() do { _ = try await monitor.value } catch { throw RealityError("\(actionError); neighbor observation failed: \(error)") } throw actionError } monitor.cancel() guard try await monitor.value > 0 else { throw RealityError("Automatic tiling off: no independent neighbor frame observations") }}
@MainActorprivate func observeTabViewNeighbors(ids: [UInt32], frames: [ScreenRect], artifact: URL) async throws -> Int { let start = ContinuousClock.now var samples: [Observation] = [] do { while !Task.isCancelled { let rows = try FrameOracle.read() let elapsed = start.duration(to: .now).components samples.append( Observation(elapsedSeconds: Double(elapsed.seconds) + Double(elapsed.attoseconds) / 1e18, windows: rows) ) let actual = try FrameOracle.frames(rows, ids: ids) guard ids.allSatisfy({ id in rows.contains { $0.id == id && $0.onscreen } }), zip(actual, frames).allSatisfy({ $0.matches($1, tolerance: 0) }) else { throw RealityError("Automatic tiling off: neighbor frames changed from \(frames) to \(actual)") } do { try await Task.sleep(for: .milliseconds(40)) } catch is CancellationError { break } } } catch { let observationError = error do { try encodeJSON(samples, to: artifact) } catch { throw RealityError("\(observationError); neighbor observation artifact failed: \(error)") } throw observationError } try encodeJSON(samples, to: artifact) return samples.count}
@MainActorprivate func requireAutomaticTilingOff(_ session: RealitySession) async throws { struct Configuration: Decodable { let automaticTiling: Bool enum CodingKeys: String, CodingKey { case automaticTiling = "automatic_tiling" } } let result = try await session.cli(["query", "--json", "config"]) guard result.status == 0 else { throw RealityError("Could not query Automatic tiling state: \(result.output) \(result.errors)") } let configuration = try JSONDecoder().decode(Configuration.self, from: Data(result.output.utf8)) guard !configuration.automaticTiling else { throw RealityError("Automatic tiling unexpectedly enabled during the Tab View off-state check") } session.recordExpectation("Configuration reports Automatic tiling off")}
@MainActorfunc requireTabViewModifierReleaseRouting(voiceOverEnabled: Bool = VoiceOverStatus.isRunning) throws { guard !voiceOverEnabled else { throw RealitySkip( "Normal modifier-release routing requires VoiceOver off; this lane will not change an existing session") }}
enum TabViewRealityOracle { static func onscreenOrder(_ rows: [RealWindow], ids: [UInt32]) -> [UInt32] { let ids = Set(ids) return rows.filter { $0.onscreen && ids.contains($0.id) }.map(\.id) }
static func newPanels(_ rows: [RealWindow], initial: [RealWindow], pid: Int32, display: ScreenRect) -> [RealWindow] { let initialIDs = Set(initial.filter(\.onscreen).map(\.id)) return newPanels(rows, initialIDs: initialIDs, pid: pid, display: display) }
static func newPanels(_ rows: [RealWindow], initialIDs: Set<UInt32>, pid: Int32, display: ScreenRect) -> [RealWindow] { return VisualOracle.overlayWindows(rows, pid: pid, display: display).filter { !initialIDs.contains($0.id) } }}
@MainActorfunc tabViewInput( _ session: RealitySession, arrow: UInt16, stage: String, holdMilliseconds: UInt16 = 2000) async throws { guard let parcel = session.parcel else { throw RealityError("Tab View requires the tested Parcel process") } let display = try RealityDisplays.primaryFrame() let initial = try FrameOracle.read(allLayers: true) let shortcut = RealityInputDefaults.tabView guard !shortcut.flags.isEmpty else { throw RealityError("Tab View default shortcut must hold a modifier") } session.recordExpectation("\(stage): \(shortcut.chord), held modifier, arrow, then modifier release") let input = Task { @MainActor in try TabViewConsoleSession.requireUnlockedConsole() return try await session.driver.send( .heldKeys( first: shortcut.virtualKey, second: arrow, flags: shortcut.flags.rawValue, holdMilliseconds: holdMilliseconds) ) } var panelIDs: Set<UInt32> = [] var observationError: (any Error)? do { let deadline = ContinuousClock.now.advanced(by: .milliseconds(Int(holdMilliseconds) - 100)) repeat { let rows = try FrameOracle.read(allLayers: true) let panels = TabViewRealityOracle.newPanels( rows, initial: initial, pid: parcel.processIdentifier, display: display) if !panels.isEmpty { panelIDs = Set(panels.map(\.id)) try encodeJSON(rows, to: session.directory.appendingPathComponent("tab-view-\(stage)-open.json")) break } try await Task.sleep(for: .milliseconds(40)) } while ContinuousClock.now < deadline guard !panelIDs.isEmpty else { throw RealityError("Tab View panel was not observed while the modifier was held") } try session.requireProtectedFrames() } catch { observationError = error } do { _ = try await input.value } catch { throw RealityError( "Tab View keyboard input failed: \(error); panel observation: \(String(describing: observationError))") } if let observationError { throw observationError } try await session.expect("\(stage): Tab View panel closes after modifier release") { _ in let rows = try FrameOracle.read(allLayers: true) return !rows.contains { panelIDs.contains($0.id) && $0.onscreen } }}