Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444import AppKitimport Foundationimport ParcelConfigimport ParcelCoreimport ParcelEngineimport ParcelPlatformimport ParcelUI
@MainActorfinal class EngineShellServices: LayoutSnapshotProviding, UIWorkspaceCommandSink { var engine: ParcelEngine? { didSet { applyAutomaticTiling() } } weak var composition: AppComposition? var quit: @MainActor () -> Void = {} #if DEBUG && PARCEL_REALITY var restartForLanguage: (@MainActor () -> Void)? #endif var overlayActiveAnimations: @MainActor () -> Int = { 0 } var privacyPanelCount: @MainActor () -> Int = { 0 } var cleanSpaceBackdropCount: @MainActor () -> Int = { 0 } var toggleHoverFocus: (@MainActor () async throws -> Void)? var toggleBorders: (@MainActor () async throws -> Void)? var onInputActivityChanged: (@MainActor () -> Void)? var onTransientNotice: (@MainActor (_ message: String, _ accessibilityMessage: String) -> Void)? private var shortcutUpgradeHandled = false private var shortcutUpgradeEligible = false private static let shortcutUpgradeKey = "treeShortcutUpgradeNoticeShown" private let defaults: UserDefaults? private var automaticTilingEnabled: Bool private var tourHold: Bool private var layoutNotices: LayoutNoticePolicy private(set) var tourEpoch = UUID() private(set) var tourRecoveryNotice: String? private(set) var isTourUnresolved: Bool private(set) var tourPersistenceFailure: (any Error)?
init(defaults: UserDefaults? = nil, tourUnresolved: Bool = false, automaticOffAtLaunch: Bool = false) { self.defaults = defaults isTourUnresolved = tourUnresolved tourHold = tourUnresolved layoutNotices = LayoutNoticePolicy(held: tourUnresolved) let enabled: Bool if automaticOffAtLaunch { enabled = false defaults?.set(false, forKey: "automaticTilingEnabled") if let defaults, !defaults.synchronize() || defaults.bool(forKey: "automaticTilingEnabled") { tourPersistenceFailure = TourProgressFailure.saveFailed } } else if defaults?.object(forKey: "automaticTilingEnabled") != nil { enabled = defaults?.bool(forKey: "automaticTilingEnabled") == true } else if defaults?.object(forKey: "tilingPaused") != nil { enabled = defaults?.bool(forKey: "tilingPaused") != true defaults?.set(enabled, forKey: "automaticTilingEnabled") } else { enabled = true } automaticTilingEnabled = enabled current = LayoutSnapshot( layout: .side, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), tiles: [], isAutomaticTilingEnabled: enabled && !tourUnresolved, isWaitingForSetup: tourUnresolved) defaults?.removeObject(forKey: "tilingPaused") } private var current: LayoutSnapshot private var workspaceSizing: [WorkspaceKey: (workspace: Workspace, ratio: Double, custom: Bool)] = [:] private var subscribers: [UUID: AsyncStream<LayoutSnapshot>.Continuation] = [:]
func snapshots() -> AsyncStream<LayoutSnapshot> { let id = UUID() let (stream, continuation) = AsyncStream<LayoutSnapshot>.makeStream(bufferingPolicy: .bufferingNewest(1)) subscribers[id] = continuation continuation.yield(current) continuation.onTermination = { [weak self] _ in Task { @MainActor in self?.subscribers.removeValue(forKey: id) } } return stream }
func publish(_ snapshot: EngineSnapshot, settings: SettingsModel? = nil) { let activeDisplay = snapshot.state.activeDisplay ?? snapshot.state.displays.keys.sorted().first let activeWorkspaces = snapshot.state.workspaces.filter { snapshot.state.displays[$0.key.display] != nil && snapshot.state.isActive($0.key) } workspaceSizing = workspaceSizing.filter { activeWorkspaces[$0.key] != nil } if let settings { settings.updateRunningLayouts( snapshot.layouts.filter { snapshot.state.displays[$0.key] != nil }.mapValues(Self.configLayout), activeDisplay: activeDisplay, mainSizeRatios: Dictionary( uniqueKeysWithValues: activeWorkspaces.map { key, workspace in (key.display, sizing(for: workspace).ratio) }), workspaces: Dictionary(uniqueKeysWithValues: activeWorkspaces.keys.map { ($0.display, $0) })) } guard let key = snapshot.state.activeWorkspace, let current = menuSnapshot(snapshot, in: key) else { current = LayoutSnapshot( layout: current.layout, bounds: current.bounds, tiles: [], isAutomaticTilingEnabled: isAutomaticTilingEnabled, ratio: current.ratio, arrangementStatus: tourRecoveryNotice ?? Self.arrangementStatus(snapshot), isWaitingForSetup: tourHold) for subscriber in subscribers.values { subscriber.yield(current) } return } self.current = current for subscriber in subscribers.values { subscriber.yield(current) } }
func menuSnapshot(_ snapshot: EngineSnapshot, in key: WorkspaceKey) -> LayoutSnapshot? { let displayID = key.display guard snapshot.state.isActive(key), let display = snapshot.state.displays[displayID], let space = snapshot.state.activeSpaces[displayID], let workspace = snapshot.state.workspaces[WorkspaceKey(display: displayID, space: space)] else { return nil } let tiles = snapshot.tiles.filter { snapshot.state.workspace(containing: $0.window) == key && snapshot.state.windows[$0.window]?.isFloating == false && $0.frame.size.width > 0 && $0.frame.size.height > 0 }.map { tile in let application = snapshot.state.windows[tile.window].map { window in let running = NSRunningApplication(processIdentifier: window.app.pid) let name = (running?.bundleIdentifier ?? "") == window.app.bundleID ? running?.localizedName ?? running?.executableURL?.lastPathComponent : nil return MenuApplicationIdentity( bundleIdentifier: window.app.bundleID, name: name ?? window.app.bundleID, processIdentifier: window.app.pid) } return LayoutTile( id: UInt64(tile.window.rawValue), frame: tile.frame.cgRect, isFocused: snapshot.focusedWindow == tile.window, application: application) } let modes = snapshot.state.modes(for: key) let sizes = sizing(for: workspace) return LayoutSnapshot( layout: Self.configLayout(workspace.layout), bounds: display.frame.cgRect, tiles: tiles, isAutomaticTilingEnabled: isAutomaticTilingEnabled, windowCap: workspace.windowCap, ratio: workspace.ratio.value, capabilityBounds: display.fullFrame.cgRect, isFocused: modes.focusedWindow != nil, noPeek: modes.noPeek, cleanSpace: modes.cleanSpace, hoverFocus: snapshot.state.hoverFocusEnabled, arrangementStatus: tourRecoveryNotice ?? Self.arrangementStatus(snapshot, display: displayID), isWaitingForSetup: tourHold, mainSizeRatio: sizes.ratio, hasCustomSizes: sizes.custom, primaryWindow: workspace.primaryWindow.map { UInt64($0.rawValue) }, primaryExpandsTile: workspace.primaryExpandsTile) }
private func sizing(for workspace: Workspace) -> (ratio: Double, custom: Bool) { if let cached = workspaceSizing[workspace.key], cached.workspace == workspace { return (cached.ratio, cached.custom) } let ratio = workspace.mainSizeRatio let custom = workspace.hasCustomSizes workspaceSizing[workspace.key] = (workspace, ratio, custom) return (ratio, custom) }
func menuDisabledReasons(_ snapshot: EngineSnapshot, in key: WorkspaceKey) -> [ConfigCommand: String] { guard let workspace = snapshot.state.workspaces[key], let display = snapshot.state.displays[key.display], snapshot.state.isActive(key) else { preconditionFailure("A menu preview needs an active display and workspace") } let reason = AppText.string("The windows need more room with this choice.") var reasons: [ConfigCommand: String] = [:] func check(_ candidate: Workspace, command: ConfigCommand) { var candidate = candidate candidate.adapt(to: display.frame, fullFrame: display.fullFrame) if !LayoutEngine.arrange(candidate, in: display.frame, windows: snapshot.state.windows).cannotFit.isEmpty { reasons[command] = reason } } for layout in Layout.allCases { var candidate = workspace candidate.changeLayout(layout) let command: ConfigCommand = switch layout { case .grid: .layoutGrid case .columns: .layoutColumns case .rows: .layoutRows case .side: .layoutSide case .tree: .layoutTree case .bsp: .layoutBSP case .accordion: .layoutAccordion } check(candidate, command: command) } for count in [1, 2, 3, 4, 5, 0] { var candidate = workspace candidate.adapt(to: display.frame, fullFrame: display.fullFrame) if !candidate.setWindowCap(count == 0 ? Int.max : count, in: display.frame, windows: snapshot.state.windows) { reasons[.setWindowCap(count)] = reason } check(candidate, command: .setWindowCap(count)) } return reasons }
private static func arrangementStatus(_ snapshot: EngineSnapshot, display: DisplayID? = nil) -> String? { snapshot.displaySuspensions.first { display == nil || $0.display == display } .map { AppMenuSuspension.text($0.reason) } }
private static func configLayout(_ layout: Layout) -> ConfigLayout { switch layout { case .grid: .grid case .columns: .columns case .rows: .rows case .side: .side case .tree: .tree case .bsp: .bsp case .accordion: .accordion } }
var awaitTourDiscovery: @MainActor () async throws -> Void = {} var tourSkippedApplications: @MainActor () -> [NativeDiscoverySkippedApplication] = { [] }
var isAutomaticTilingEnabled: Bool { automaticTilingEnabled && !tourHold } var selectedTourIntent: TourStartIntent { automaticTilingEnabled ? .automatic : .manual }
func persistTourOff() throws { automaticTilingEnabled = false defaults?.set(false, forKey: "automaticTilingEnabled") guard defaults == nil || (defaults?.synchronize() == true && defaults?.bool(forKey: "automaticTilingEnabled") == false) else { throw TourProgressFailure.saveFailed } applyAutomaticTiling() }
func setTourRecoveryNotice(_ notice: String?) { tourRecoveryNotice = notice applyAutomaticTiling() }
func allowsLayoutNotice(_ report: Report) -> Bool { layoutNotices.allows(report) }
func allowsLayoutNotice(_ announcement: Announcement, state: State) -> Bool { layoutNotices.allows(announcement, state: state) }
func finishTour(automatic: Bool) { layoutNotices.commit(engine?.snapshot.state ?? State()) tourRecoveryNotice = nil automaticTilingEnabled = automatic isTourUnresolved = false tourHold = false applyAutomaticTiling(animatedResume: automatic) }
func persistTourAutomaticChoice(_ automatic: Bool) throws { defaults?.set(automatic, forKey: "automaticTilingEnabled") guard defaults == nil || (defaults?.synchronize() == true && defaults?.bool(forKey: "automaticTilingEnabled") == automatic) else { throw TourProgressFailure.saveFailed } }
struct AutomaticTilingRestorePoint { fileprivate let enabled: Bool fileprivate let tourHold: Bool fileprivate let tourUnresolved: Bool fileprivate let layoutNotices: LayoutNoticePolicy }
func captureAutomaticTilingState() -> AutomaticTilingRestorePoint { AutomaticTilingRestorePoint( enabled: automaticTilingEnabled, tourHold: tourHold, tourUnresolved: isTourUnresolved, layoutNotices: layoutNotices) }
func restoreAutomaticTilingState(_ point: AutomaticTilingRestorePoint) { automaticTilingEnabled = point.enabled tourHold = point.tourHold layoutNotices = point.layoutNotices isTourUnresolved = point.tourUnresolved defaults?.set(automaticTilingEnabled, forKey: "automaticTilingEnabled") applyAutomaticTiling() }
func setAutomaticTilingEnabled(_ enabled: Bool, animatedResume: Bool = false) { layoutNotices.resume() automaticTilingEnabled = enabled tourHold = false defaults?.set(enabled, forKey: "automaticTilingEnabled") applyAutomaticTiling(animatedResume: animatedResume) }
func configureShortcutUpgradeHint(_ configuration: ParcelConfiguration, existingInstallation: Bool) { guard !shortcutUpgradeHandled, defaults?.bool(forKey: Self.shortcutUpgradeKey) != true else { return } guard existingInstallation else { shortcutUpgradeHandled = true defaults?.set(true, forKey: Self.shortcutUpgradeKey) return } shortcutUpgradeEligible = usesChangedDefaultShortcuts(configuration) }
private func usesChangedDefaultShortcuts(_ configuration: ParcelConfiguration) -> Bool { let bindings = DefaultKeybindings.bindings(prefix: configuration.general.prefix) return configuration.general.shortcutsEnabled && bindings[.layoutTree]?.key == .t && configuration.keybindings[.layoutTree] == bindings[.layoutTree] && configuration.keybindings[.toggleAutomaticTiling] == bindings[.toggleAutomaticTiling] }
private func announceAutomaticTiling(_ configuration: ParcelConfiguration) { guard let onTransientNotice else { return } var message = automaticTilingEnabled ? AppText.string("Automatic tiling is on.") : AppText.string("Automatic tiling is off. Explicit commands still work.") var accessibilityMessage = message if configuration.general.shortcutsEnabled, let chord = configuration.keybindings[.toggleAutomaticTiling] { let format = automaticTilingEnabled ? "Automatic tiling on — %@ to turn off" : "Automatic tiling off — %@ to turn on" message = AppText.detail(format, chord.displayString).message accessibilityMessage = AppText.detail(format, chord.accessibilityLabel).message } if shortcutUpgradeEligible, !shortcutUpgradeHandled, defaults?.bool(forKey: Self.shortcutUpgradeKey) != true, usesChangedDefaultShortcuts(configuration), let tree = configuration.keybindings[.layoutTree] { message += ". " + AppText.detail("Default shortcuts changed. Tree layout now uses %@.", tree.displayString).message accessibilityMessage += ". " + AppText.detail("Default shortcuts changed. Tree layout now uses %@.", tree.accessibilityLabel).message shortcutUpgradeHandled = true defaults?.set(true, forKey: Self.shortcutUpgradeKey) } onTransientNotice(message, accessibilityMessage) }
func holdForTour() { layoutNotices.hold() tourEpoch = UUID() isTourUnresolved = true tourHold = true applyAutomaticTiling() }
func resolveTour() { layoutNotices.commit(engine?.snapshot.state ?? State()) isTourUnresolved = false tourHold = false applyAutomaticTiling() }
private func applyAutomaticTiling(animatedResume: Bool = false) { engine?.setWaitingForTour(tourHold) engine?.setAutomaticTilingEnabled(isAutomaticTilingEnabled, animatedResume: animatedResume) if let engine { publish(engine.snapshot) } else { current = LayoutSnapshot( layout: current.layout, bounds: current.bounds, tiles: [], isAutomaticTilingEnabled: isAutomaticTilingEnabled, ratio: current.ratio, arrangementStatus: tourRecoveryNotice, isWaitingForSetup: tourHold) for subscriber in subscribers.values { subscriber.yield(current) } } onInputActivityChanged?() }
func requireTourResolved() throws { guard !isTourUnresolved else { throw AppText.failure("Shortcuts start after you tidy.") } }
func send(_ command: ConfigCommand, in workspace: WorkspaceKey) async throws { try requireTourResolved() guard let engine else { throw AppText.failure("Accessibility access is required before tiling can start.") } let result = try await engine.perform( EngineCommandParser.command(command), in: workspace, activitySource: .mouse) guard result.isAccepted else { throw Self.menuFailure(reports: result.reports) } }
static func menuFailure(reports: [Report]) -> AppFailure { if reports.contains(.noFocusedWindow) { return AppText.failure("Focus a window on this display first.") } if reports.contains(where: { if case .unavailableDisplay = $0 { true } else { false } }) { return AppText.failure("This display is no longer connected. Reopen the menu on a connected display.") } if reports.contains(.noActiveWorkspace) { return AppText.failure("This desktop is no longer active. Reopen the menu and try again.") } return AppText.failure("The menu action could not finish. Reopen the menu and try again.") }
func send(_ command: ConfigCommand) async throws { try await send(command, activitySource: .mouse) }
func send(_ command: ConfigCommand, activitySource: ActivitySource) async throws { switch command { case .toggleBorders: guard let toggleBorders else { throw AppText.failure("Parcel is shutting down.") } try await toggleBorders() case .openSettings: composition?.showSettings() case .toggleHoverFocus: guard let toggleHoverFocus else { throw AppText.failure("Hover focus controls are unavailable. Start tiling and try again.") } try await toggleHoverFocus() case .quit: quit() case .toggleAutomaticTiling: guard !isTourUnresolved else { throw AppText.failure( "Use the Parcel menu to finish setup or resolve a problem before turning on Automatic tiling.") } guard let engine, engine.isRunning else { throw AppText.failure("Accessibility access is required before tiling can start.") } setAutomaticTilingEnabled(!automaticTilingEnabled) announceAutomaticTiling(engine.configuration) default: try requireTourResolved() guard let engine else { throw AppText.failure("Accessibility access is required before tiling can start.") } let result = try await engine.performConfigured(command, activitySource: activitySource) if [.toggleFocus, .toggleNoPeek, .toggleCleanSpace].contains(command), !result.isAccepted { throw AppText.failure("The focus mode could not change. Focus a window and try again.") } } }
deinit { for subscriber in subscribers.values { subscriber.finish() } }}
struct MenuHighlightPreference { private(set) var lastEnabled: ConfigHighlight = .active
mutating func observe(_ style: ConfigHighlight) { if style != .none { lastEnabled = style } }
mutating func toggled(from current: ConfigHighlight) -> ConfigHighlight { observe(current) return current == .none ? lastEnabled : .none }}
extension Rect { var cgRect: CGRect { CGRect(x: minX, y: minY, width: size.width, height: size.height) }}