import ArgumentParser import Foundation import ParcelConfig import ParcelIPC @main struct ParcelCLI: AsyncParsableCommand { static let version = "0.1.0" static var resourceBundle: Bundle { .module } static let configuration = CommandConfiguration( commandName: "prcl", abstract: String(localized: "Talk to Parcel from your terminal.", bundle: .module), version: version, subcommands: [ QueryCommand.self, DirectionCommand.self, DirectionCommand.self, DirectionCommand.self, NameCommand.self, NameCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SetWindowCapCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, NameCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, SubscribeCommand.self, PingCommand.self, ReloadCommand.self, VersionCommand.self, RunCommand.self, WhyCommand.self, DiagnosticsCommand.self, SchemaCommand.self, MinimumsCommand.self, MemoryCommand.self, ConfigurationCommand.self, SetupCommand.self, SpaceFocusCommand.self, WindowToSpaceCommand.self, SimpleCommand.self, SimpleCommand.self, SimpleCommand.self, WindowToAdjacentSpaceCommand.self, WindowToAdjacentSpaceCommand.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 case schema case configCheck(path: String, json: Bool) 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 ParcelCLI.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, native Spaces, displays, or configuration.", bundle: .module) ) @OptionGroup var output: CLIOptions @Argument( help: ArgumentHelp( String(localized: "What to inspect: windows, workspaces, spaces, 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 SnapShortcut: NamedShortcut { static let name = "snap" static var abstract: String { String(localized: "Snap the focused window.", bundle: .module) } static var argumentHelp: String { String(localized: "Snap action, such as left-half.", bundle: .module) } } enum MakePrimaryShortcut: Shortcut { static let name = "make-primary" static var abstract: String { String(localized: "Make the focused window primary.", bundle: .module) } } enum WindowNextShortcut: Shortcut { static let name = "window-next" static var abstract: String { String(localized: "Focus the next window in this workspace.", bundle: .module) } } enum WindowPreviousShortcut: Shortcut { static let name = "window-previous" static var abstract: String { String(localized: "Focus the previous window in this workspace.", bundle: .module) } } enum ResetSizesShortcut: Shortcut { static let name = "reset-sizes" static var abstract: String { String(localized: "Reset window sizes in the focused workspace.", bundle: .module) } } enum UnstackShortcut: Shortcut { static let name = "unstack" static var abstract: String { String(localized: "Move the focused window out of its stack.", bundle: .module) } } struct SetWindowCapCommand: CLICommand { static let configuration = CommandConfiguration( commandName: "set-window-cap", abstract: String(localized: "Set the tile count for the focused workspace.", bundle: .module) ) @OptionGroup var output: CLIOptions @Argument(help: ArgumentHelp(String(localized: "Maximum number of tiles; 0 means no limit.", bundle: .module))) var count: Int var invocation: CLIInvocation { .engine("set-window-cap", args: [String(count)], json: output.json) } } enum AlwaysFloatShortcut: Shortcut { static let name = "always-float" static var abstract: String { String(localized: "Save a floating rule for the focused window.", bundle: .module) } } enum ToggleFocusShortcut: Shortcut { static let name = "focus-toggle" static var abstract: String { String(localized: "Toggle Focus mode, which expands the focused tiled window.", bundle: .module) } } enum ToggleNoPeekShortcut: Shortcut { static let name = "no-peek-toggle" static var abstract: String { String(localized: "Toggle No Peek, which dims the background.", bundle: .module) } } enum ToggleCleanSpaceShortcut: Shortcut { static let name = "clean-space-toggle" static var abstract: String { String(localized: "Toggle Clean Space, which conceals background clutter.", bundle: .module) } } enum ToggleBordersShortcut: Shortcut { static let name = "borders-toggle" static var abstract: String { String(localized: "Toggle window highlights.", bundle: .module) } } enum ToggleHoverFocusShortcut: Shortcut { static let name = "hover-focus-toggle" static var abstract: String { String(localized: "Toggle focusing windows when the pointer settles over them.", bundle: .module) } } enum UndoShortcut: Shortcut { static let name = "undo" static var abstract: String { String(localized: "Undo the focused window's latest change.", 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 RotateShortcut: Shortcut { static let name = "rotate" static var abstract: String { String(localized: "Rotate the tile tree clockwise.", bundle: .module) } } enum MirrorHorizontalShortcut: Shortcut { static let name = "mirror-horizontal" static var abstract: String { String(localized: "Mirror the tile tree horizontally.", bundle: .module) } } enum MirrorVerticalShortcut: Shortcut { static let name = "mirror-vertical" static var abstract: String { String(localized: "Mirror the tile tree vertically.", bundle: .module) } } enum SplitHorizontalShortcut: Shortcut { static let name = "split-horizontal" static var abstract: String { String(localized: "Split the focused tile horizontally.", bundle: .module) } } enum SplitVerticalShortcut: Shortcut { static let name = "split-vertical" static var abstract: String { String(localized: "Split the focused tile vertically.", bundle: .module) } } enum JoinLeftShortcut: Shortcut { static let name = "join-left" static var abstract: String { String(localized: "Join the focused tile with its left neighbor.", bundle: .module) } } enum JoinRightShortcut: Shortcut { static let name = "join-right" static var abstract: String { String(localized: "Join the focused tile with its right neighbor.", bundle: .module) } } enum JoinUpShortcut: Shortcut { static let name = "join-up" static var abstract: String { String(localized: "Join the focused tile with its upper neighbor.", bundle: .module) } } enum JoinDownShortcut: Shortcut { static let name = "join-down" static var abstract: String { String(localized: "Join the focused tile with its lower neighbor.", bundle: .module) } } enum EnterModeShortcut: NamedShortcut { static let name = "enter-mode" static var abstract: String { String(localized: "Enter a named binding mode.", bundle: .module) } static var argumentHelp: String { String(localized: "Binding mode name.", bundle: .module) } } enum ExitModeShortcut: Shortcut { static let name = "exit-mode" static var abstract: String { String(localized: "Return to the default binding mode.", 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 Parcel 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 WhyCommand: CLICommand { static let configuration = CommandConfiguration( commandName: "why", abstract: String(localized: "Explain how a window is classified.", bundle: .module) ) @OptionGroup var output: CLIOptions @Argument(help: ArgumentHelp(String(localized: "Nonzero decimal window ID.", bundle: .module))) var window: String mutating func validate() throws { guard IPCProtocol.parseWindowID(window) != nil else { throw ValidationError( String(localized: "Provide a nonzero decimal window ID within UInt32 range.", bundle: .module)) } } var invocation: CLIInvocation { .request(command: "why", args: [window], query: nil, json: output.json) } } struct PingCommand: CLICommand { static let configuration = CommandConfiguration( commandName: "ping", abstract: String(localized: "Check whether Parcel 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 Parcel'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 Parcel.", 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(ParcelCLI.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 { switch invocation { case .version: try write(ParcelCLI.version + "\n") return case .schema: try write(ConfigJSONSchema.string + "\n") return case .configCheck(let path, let json): let source: String do { source = try String(contentsOfFile: path, encoding: .utf8) } catch { let failure = error as NSError let cause = failure.userInfo[NSUnderlyingErrorKey] as? NSError ?? failure guard cause.domain == NSPOSIXErrorDomain, cause.code == ENOENT else { throw error } source = "" } let report = ConfigCheckReport.validate(source) try write(report.format(json: json)) if !report.valid { throw ExitCode.failure } return case .request, .subscribe: break } 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, why: command == "why", diagnostics: command == "diagnostics" )) 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, .schema, .configCheck: break } await client.close() } catch { await client.close() throw error } } }