import Foundation public import ParcelConfig public import ParcelCore public import ParcelIPC public enum EngineCommandParser { public static func parse(_ name: String, args: [String] = []) throws -> Command { if args.isEmpty { if let configured = ConfigCommand(rawValue: name) { return try command(configured) } return try noArguments(name) } guard args.count == 1 else { throw invalid() } return try oneArgument(name, value: args[0]) } public static func command(_ command: ConfigCommand) throws -> Command { if command.rawValue.hasPrefix("snap-") { guard let action = SnapAction(rawValue: String(command.rawValue.dropFirst("snap-".count))) else { throw invalid() } return .snap(action) } if case .setWindowCap(let cap) = command { return .setWindowCap(cap) } if let result = configuredCommands[command] { return result } throw IPCError( code: "shell_command", message: String(localized: "This command is handled by the app shell.", bundle: .module)) } private static let configuredCommands: [ConfigCommand: Command] = [ .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: .setLayout(.grid), .layoutColumns: .setLayout(.columns), .layoutRows: .setLayout(.rows), .layoutSide: .setLayout(.side), .layoutTree: .setLayout(.tree), .layoutBSP: .setLayout(.bsp), .layoutAccordion: .setLayout(.accordion), .splitHorizontal: .split(.horizontal), .splitVertical: .split(.vertical), .joinLeft: .join(.left), .joinRight: .join(.right), .joinUp: .join(.up), .joinDown: .join(.down), .balance: .balance, .rotate: .rotate, .mirrorHorizontal: .mirror(.horizontal), .mirrorVertical: .mirror(.vertical), .ratioIncrease: .nudgeRatio(0.05), .ratioDecrease: .nudgeRatio(-0.05), .ratioHalf: .setRatio(.half), .ratioThreeFifths: .setRatio(.threeFifths), .ratioTwoThirds: .setRatio(.twoThirds), .floatToggle: .toggleFloat, .retile: .retile, .stack: .stack(.right), .stackNext: .focusNextInStack, .stackPrevious: .focusPreviousInStack, .displayMoveLeft: .moveToDisplay(.left), .displayMoveRight: .moveToDisplay(.right), .displayMoveUp: .moveToDisplay(.up), .displayMoveDown: .moveToDisplay(.down), .makePrimary: .makePrimary, .windowNext: .focusNextWindow, .windowPrevious: .focusPreviousWindow, .resetSizes: .resetSizes, .unstack: .unstack, .close: .close, .toggleFullscreen: .toggleFullscreen, .alwaysFloat: .alwaysFloat, .undoLastRule: .undoLastRule, .toggleFocus: .toggleFocus, .toggleNoPeek: .toggleNoPeek, .toggleCleanSpace: .toggleCleanSpace, .toggleBorders: .toggleBorders, .toggleHoverFocus: .toggleHoverFocus, .undo: .undo, ] private static func noArguments(_ name: String) throws -> Command { switch name { case "cycle-layout": .cycleLayout case "toggle-float", "toggle-floating": .toggleFloat case "unstack": .unstack case "exit-mode": .enterMode(nil) case "focus-next-in-stack": .focusNextInStack case "focus-previous-in-stack": .focusPreviousInStack default: throw invalid() } } private static func oneArgument(_ name: String, value: String) throws -> Command { switch name { case "enter-mode": guard !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw invalid() } return .enterMode(value) case "snap": guard let action = SnapAction(rawValue: value) else { throw invalid() } return .snap(action) case "focus": return .focus(try direction(value)) case "swap": return .swap(try direction(value)) case "move": return .move(try direction(value)) case "move-to-display": return .moveToDisplay(try direction(value)) case "stack": return .stack(try direction(value)) default: return try valueArgument(name, value: value) } } private static func valueArgument(_ name: String, value: String) throws -> Command { switch name { case "set-layout", "layout": guard let layout = Layout(rawValue: value) else { throw invalid() } return .setLayout(layout) case "set-ratio": guard let ratio = Double(value), ratio.isFinite, MainRatio.bounds.contains(ratio) else { throw invalid() } return .setRatio(MainRatio(ratio)) case "nudge-ratio": guard let delta = Double(value), delta.isFinite else { throw invalid() } return .nudgeRatio(delta) case "tile-window": guard let id = UInt32(value), id > 0 else { throw invalid() } return .tileWindow(WindowID(rawValue: id)) case "set-window-cap": guard let cap = Int(value) else { throw invalid() } return .setWindowCap(cap) default: throw invalid() } } 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: ParcelEngine public let configPath: String public let version: String private let configStore: ConfigStore? public init( engine: ParcelEngine, 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 (engine.actualFrames[id] ?? engine.snapshot.readbackFrames[id] ?? state.observedFrames[id]) .map(Self.json) ?? .null, "target_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 .spaces: return .array( try await engine.querySpaces().flatMap { display in display.spaces.map { space in .object([ "id": .string(String(space.id)), "display": .string(display.displayID), "active": .bool(space.id == display.currentSpace), "kind": .string(String(describing: space.kind)), "desktop_number": space.desktopNumber.map { .integer(Int64($0)) } ?? .null, ]) } }) 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), "layout_variant": .string(workspace.layoutVariant.rawValue), "effective_window_cap": .integer(Int64(workspace.effectiveWindowCap)), "ratio": .number(workspace.ratio.value), "window_cap": .integer(Int64(workspace.windowCap)), "when_full": .string(workspace.whenFull.rawValue), "focus_modes": try Self.json(state.modes(for: key)), "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 .setups: throw IPCError( code: "unavailable", message: String(localized: "Setups are managed by the Parcel application.", bundle: .module)) case .config: return .object([ "path": .string(configPath), "version": .string(version), "schema_version": .integer(Int64(engine.configuration.version)), "active_mode": state.activeMode.map(JSONValue.string) ?? .null, "hover_focus": .bool(state.hoverFocusEnabled), "automatic_tiling": .bool(engine.isAutomaticTilingEnabled), "shortcuts_enabled": .bool(engine.configuration.general.shortcutsEnabled), "when_display_full": .string(state.whenDisplayFull.rawValue), "focus-modes": .object([ "no-peek-level": .number(engine.configuration.focusModes.noPeekLevel), "no-peek-blur": .bool(engine.configuration.focusModes.noPeekBlur), "clean-space-color": .string(engine.configuration.focusModes.cleanSpaceColor.rawValue), ]), "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 { if let result = try await minimums(command: command, args: args) { return result } if command == "memory" { return try await workspaceMemoryCommand(args) } let result: EngineCommandResult if let native = try EngineCommandParser.spaceCommand(command, args: args) { result = try await engine.performConfigured(native) } else { let parsed = try EngineCommandParser.parse(command, args: args) do { result = try await engine.perform(parsed) } catch { guard parsed == .close || parsed == .toggleFullscreen || parsed == .toggleFloat || parsed == .alwaysFloat, !(error is CancellationError), !(error is EngineError), !(error is IPCError) else { throw error } throw IPCError(code: "window_command_failed", message: Self.windowCommandMessage(error)) } } 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 windowCommandMessage(_ error: any Error) -> String { if let error = error as? EngineWindowCommandError { return error.localizedDescription } if let failure = error as? EnginePlatformFailure { if failure.isPermissionLoss { return String( localized: "Accessibility access was lost. Grant Parcel access and try again.", bundle: .module) } if failure.isTimeout { return String(localized: "The application did not answer the window command in time.", bundle: .module) } if failure.vanishedWindow != nil { return String(localized: "The window is no longer available.", bundle: .module) } switch failure { case .accessibility(_, _, .attributeUnsupported), .accessibility(_, _, .noValue), .accessibility(_, _, .unavailable): return String( localized: "This application does not support the requested window action.", bundle: .module) case .appUnavailable, .appThread: return String(localized: "The application is unavailable for window commands.", bundle: .module) default: break } } return String( format: String(localized: "The window command could not finish: %@", bundle: .module), String(describing: error)) } 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))]) } }