Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468import Foundation
public enum ConfigJSONSchema { public static let publishedURL = "https://tangled.org/vinnymac.dev/parcel/raw/main/docs/parcel.schema.json"
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 = ParcelConfiguration.defaults let bindings = DefaultKeybindings.bindings() let bindingValue = binding() let namePattern = "(?![dD][eE][fF][aA][uU][lL][tT]$)[A-Za-z0-9_-]+$(?![\\s\\S])" let entryPattern = "^enter-mode \(namePattern)" var modeBindings = Dictionary( uniqueKeysWithValues: ConfigCommand.bindableCases.map { ($0.rawValue, binding($0)) }) modeBindings["exit-mode"] = binding(defaultChord: DefaultKeybindings.modeExit) let modeTable: SchemaValue = .object([ "type": .string("object"), "properties": .object(modeBindings), "patternProperties": .object([entryPattern: bindingValue]), "additionalProperties": .bool(false), "description": .string( "Named modes start with a configurable exit-mode shortcut; commands are otherwise unbound. " + "Enter-mode targets are case-sensitive declared mode names; exit-mode returns to default bindings." ), ]) var keybindings: [String: SchemaValue] = [:] for command in ConfigCommand.bindableCases { keybindings[command.rawValue] = binding(command, defaultChord: bindings[command]) } 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("parcel-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)])]) }) ] ) let matchers = ["bundle-id", "app-name", "title-contains", "title-regex", "role", "subrole"] let outcomes = ["action", "display", "position", "layout", "space"] var ruleFields: [String: SchemaValue] = [:] for key in matchers { var field: [String: SchemaValue] = [ "type": .string("string"), "minLength": .integer(1), "pattern": .string("\\S"), ] if key == "title-regex" { field["format"] = .string("parcel-title-regex") } ruleFields[key] = .object(field) } ruleFields["action"] = choice(RuleAction.allCases.map(\.rawValue), defaultValue: nil) ruleFields["layout"] = choice(ConfigLayout.allCases.map(\.rawValue), defaultValue: nil) ruleFields["space"] = .object([ "type": .string("integer"), "minimum": .integer(1), "maximum": .integer(16), "description": .string( "Native desktop number. Moving a newly created window requires move-to-space = true."), ]) ruleFields["move-to-space"] = boolean(false) ruleFields["display"] = .object(["type": .string("string")]) ruleFields["position"] = .object([ "type": .string("integer"), "minimum": .integer(0), "maximum": .integer(Int.max), ]) let rule = object( ruleFields, extra: [ "allOf": .array([ .object(["anyOf": .array(matchers.map { .object(["required": .array([.string($0)])]) })]), .object(["anyOf": .array(outcomes.map { .object(["required": .array([.string($0)])]) })]), .object([ "not": .object(["required": .array([.string("title-contains"), .string("title-regex")])]) ]), ]) ] ) return object( [ "version": .object([ "type": .string("integer"), "const": .integer(1), "default": .integer(defaults.version), ]), "general": object([ "prefix": .object([ "type": .string("string"), "format": .string("parcel-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), "shortcuts-enabled": boolean(defaults.general.shortcutsEnabled), "collect-activity": boolean(defaults.general.collectActivity), "when-display-full": choice( ConfigWhenDisplayFull.allCases.map(\.rawValue), defaultValue: defaults.general.whenDisplayFull.rawValue, description: "When a directional swap arrow reaches a full display, swap windows or stack them. Explicit display moves and new windows are unchanged." ), ]), "callbacks": object( Dictionary( uniqueKeysWithValues: CallbackEvent.allCases.map { event in ( event.rawValue, .object([ "type": .string("array"), "default": .array([]), "maxItems": .integer(64), "items": .object([ "type": .string("string"), "maxLength": .integer(4096), "pattern": .string("^[^\\u0000]*$"), ]), "prefixItems": .array([ .object(["type": .string("string"), "pattern": .string("^/")]) ]), "description": .string( "Argument array with an absolute executable path; no implicit shell. Empty disables this callback. Total UTF-8 size is limited to 16384 bytes." ), ]) ) })), "layout": object(layout), "classification": object([ "disabled-default-float-apps": .object([ "type": .string("array"), "uniqueItems": .bool(true), "default": .array([]), "items": .object([ "type": .string("string"), "minLength": .integer(1), "pattern": .string("\\S"), ]), "description": .string( "Bundle identifiers removed from the built-in float list. Safety heuristics still apply."), ]) ]), "memory": object([ "enabled": boolean(defaults.memory.enabled), "restore-windows": boolean(defaults.memory.restoreWindows), ]), "motion": motion(defaults.motion), "appearance": appearance(defaults.appearance), "focus-modes": object([ "no-peek-level": number( FocusModeConfiguration.noPeekLevels, defaultValue: defaults.focusModes.noPeekLevel), "no-peek-blur": boolean(defaults.focusModes.noPeekBlur), "clean-space-color": choice( ConfigCleanSpaceColor.allCases.map(\.rawValue), defaultValue: defaults.focusModes.cleanSpaceColor.rawValue), ]), "mouse": object( [ "enabled": boolean(defaults.mouse.enabled), "swap-modifiers": mouseModifiers(defaults.mouse.swapModifiers), "stack-modifiers": mouseModifiers(defaults.mouse.stackModifiers), "move-modifiers": mouseModifiers(defaults.mouse.moveModifiers), "resize-modifiers": mouseModifiers(defaults.mouse.resizeModifiers), "edge-snapping": boolean(defaults.mouse.edgeSnapping), "drop-to-ratio": boolean(defaults.mouse.dropToRatio), "focus-follows-mouse": boolean(defaults.mouse.focusFollowsMouse), "focus-delay": number(MouseConfiguration.focusDelays, defaultValue: defaults.mouse.focusDelay), "typing-cooldown": number( MouseConfiguration.typingCooldowns, defaultValue: defaults.mouse.typingCooldown), ], extra: [ "description": .string( "All mouse gestures require distinct nonempty modifier sets. A subset is allowed; equal resolved sets are ambiguous." ) ] ), "hover-bar": object([ "enabled": boolean(defaults.hoverBar.enabled), "delay": number(HoverBarConfiguration.delays, defaultValue: defaults.hoverBar.delay), ]), "keybindings": object( keybindings, extra: [ "description": .string( "Shortcuts inherit generated defaults. Explicit chords take priority and leave conflicting inherited defaults unbound with a warning. Set any command to false to remove it. " + "Enter-mode targets must name declared modes, even when disabled; exit-mode is only valid in named modes." ), "propertyNames": .object([ "anyOf": .array([ .object(["pattern": .string(entryPattern)]), .object(["pattern": .string("^(?!\\s*(?:enter-mode|exit-mode))")]), ]) ]), "patternProperties": .object([entryPattern: bindingValue]), "default": .object( Dictionary( uniqueKeysWithValues: bindings.map { ($0.key.rawValue, .string($0.value.description)) }) ), ] ), "mode": .object([ "type": .string("object"), "default": .object([:]), "propertyNames": .object(["pattern": .string("^\(namePattern)")]), "additionalProperties": modeTable, "description": .string( "Case-sensitive named modes use ASCII letters, digits, underscores, or hyphens; default is reserved in every letter casing." ), ]), "float-rules": .object(["type": .string("array"), "items": floatRule, "default": .array([])]), "rules": .object([ "type": .string("array"), "items": rule, "default": .array([]), "description": .string("All matchers are combined with AND; the last matching rule wins."), ]), "accessibility": object([ "announce-layout-changes": boolean(defaults.accessibility.announceLayoutChanges) ]), ], extra: [ "$schema": .string("https://json-schema.org/draft/2020-12/schema"), "$id": .string(publishedURL), "title": .string("Parcel configuration, version 1"), "$comment": .string( "This schema describes parsed TOML. Unknown settings, including underscore spellings, are ignored with warnings by ConfigValidator; only dashed setting names are recognized. " + "ConfigValidator also checks the parcel-modifiers, parcel-key-chord, and parcel-mouse-modifiers formats, " + "nonempty and distinct resolved mouse modifier sets (including inherited defaults), " + "ICU expressions in parcel-title-regex, case-insensitive duplicate display UUIDs, " + "named mode targets and reserved names, and duplicate resolved shortcuts, including inherited defaults. " + "Display overrides have no fixed defaults: omitted fields inherit the global layout." ), ] ) }
private static func appearance(_ defaults: AppearanceConfiguration) -> SchemaValue { var properties: [String: SchemaValue] = [ "palette": choice( ConfigAppearancePalette.allCases.map(\.rawValue), defaultValue: defaults.palette.rawValue), "stack-controls": choice( StackControlsPresentation.allCases.map(\.rawValue), defaultValue: defaults.stackControls.rawValue), "mode": choice(ConfigAppearanceMode.allCases.map(\.rawValue), defaultValue: defaults.mode.rawValue), "border-opacity": number(AppearanceConfiguration.borderOpacities, defaultValue: defaults.borderOpacity), "border-radius": number( AppearanceConfiguration.borderRadii, defaultValue: nil, description: "Optional radius in points; omitted means match each window's native corner radius."), ] for role in AppearanceColorRole.allCases { properties[role.rawValue] = .object([ "type": .string("string"), "minLength": .integer(7), "maxLength": .integer(7), "pattern": .string("^#[0-9A-Fa-f]{6}$"), "description": .string("Optional exact sRGB #RRGGBB override; omitted roles use the selected palette."), ]) } return object( properties, extra: [ "description": .string( "System uses native colors. Appearance updates instantly without changing layout; mode affects Parcel's windows and chrome, not other apps. Accessibility preferences take priority over color overrides." ) ]) }
private static func motion(_ defaults: MotionConfiguration) -> SchemaValue { let properties: [String: SchemaValue] = [ "enabled": boolean(defaults.enabled), "level": choice(ConfigMotionLevel.allCases.map(\.rawValue), defaultValue: defaults.level.rawValue), "speed": number(ConfigLimits.speed, defaultValue: defaults.speed), "transitions": choice( ConfigMotionTransition.allCases.map(\.rawValue), defaultValue: defaults.transitions.rawValue), "focus-border": .object([ "type": .string("boolean"), "default": .bool(defaults.focusBorder), "deprecated": .bool(true), "description": .string( "Legacy active border switch. Used only when highlight is absent; explicit highlight takes precedence." ), ]), "highlight": choice(ConfigHighlight.allCases.map(\.rawValue), defaultValue: defaults.highlight.rawValue), "highlight-width": number(MotionConfiguration.highlightWidths, defaultValue: defaults.highlightWidth), "drop-hints": boolean(defaults.dropHints), "experimental-dimming": boolean(defaults.experimentalDimming), "sound": boolean(defaults.sound), "menu-bar-icon": choice( ConfigMenuBarIcon.allCases.map(\.rawValue), defaultValue: defaults.menuBarIcon.rawValue), ] return object(properties) }
private static func binding(_ command: ConfigCommand? = nil, defaultChord: KeyChord? = nil) -> SchemaValue { var property: [String: SchemaValue] = [ "oneOf": .array([ .object([ "type": .string("string"), "minLength": .integer(1), "format": .string("parcel-key-chord"), ]), .object(["const": .bool(false)]), ]) ] if let defaultChord { property["default"] = .string(defaultChord.description) } if let command, let description = commandDescription(command) { property["description"] = .string(description) } return .object(property) }
private static func commandDescription(_ command: ConfigCommand) -> String? { switch command { case .makePrimary: "Move the focused window into the primary tile." case .windowNext, .windowPrevious: "Focus the next or previous managed window on the active display." case .windowControls: "Open window controls for the selected window." case .tabView: "Open the window switcher. Release the shortcut modifiers to focus the selection." case .resetSizes: "Reset tile sizes on the active display to the configured ratio." case .unstack: "Separate the focused window from its stack." case .ratioHalf: "Set the main tile size to one half. Unbound by default." case .ratioThreeFifths: "Set the main tile size to three fifths. Unbound by default." case .ratioTwoThirds: "Set the main tile size to two thirds. Unbound by default." case .setWindowCap(0): "Remove the tile cap, bypassing the layout's display-dependent capability limit." case .setWindowCap: "Set the requested tile cap to 1–5; the effective cap is limited by the layout's display-dependent capability without changing the request." case .toggleAutomaticTiling: "Toggle automatic window arrangement. Explicit shortcuts and menu commands remain available when off." case .close: "Ask the focused window to close, preserving the app's confirmation dialogs." case .toggleFullscreen: "Toggle native full screen for the focused window." case .undo: "Undo the focused window's latest layout or frame change when its placement is still valid." case .undoLastRule: "Remove only the last window rule added through Settings or Always float." case .toggleFocus: "Fill the usable display area with the focused window until focus or layout changes." case .toggleNoPeek: "Dim background windows across all displays, keeping the active app's menus and sheets bright." case .toggleCleanSpace: "Place a plain background around the focused window on its display." case .toggleHoverFocus: "Toggle settled-pointer focus; pointer movement just after typing is ignored." case .alwaysFloat: "Save an app/title floating rule. Shift prefixes use F16 to keep this distinct from ordinary floating." case .toggleBorders: "Toggle window highlights. The app saves this choice in motion.highlight." case .layoutTree: "Select the editable tree layout." case .layoutBSP: "Select the balanced binary partition layout." case .layoutAccordion: "Select the accordion layout." case .splitHorizontal, .splitVertical: "Choose the next insertion's split axis in the tree layout." case .joinLeft, .joinRight, .joinUp, .joinDown: "Reinsert the focused stack beside its neighbor in this direction." case .balance: "Balance split proportions without changing the tree topology." case .rotate: "Rotate the tree clockwise by a quarter turn." case .mirrorHorizontal: "Mirror the tree left to right." case .mirrorVertical: "Mirror the tree top to bottom." case .spaceFocus: "Focus system desktop 1–16 on the active display using enabled Mission Control shortcuts." case .spaceNext, .spacePrevious: "Focus the adjacent native Space using an enabled Mission Control shortcut." case .spaceBackAndForth: "Focus the previously active native Space on this display." case .windowToSpace, .windowToSpaceNext, .windowToSpacePrevious: "Move the focused window to a native Space on the active display; --follow stays there instead of returning." default: nil } }
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, description: "Default layout for landscape and square displays; portrait displays use portrait-layout."), "portrait-layout": choice( ConfigLayout.allCases.map(\.rawValue), defaultValue: includeDefaults ? values.portraitLayout.rawValue : nil, description: "Default layout for displays taller than they are wide. Defaults to rows."), "when-full": choice( ConfigWhenFull.allCases.map(\.rawValue), defaultValue: includeDefaults ? values.whenFull.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: "Requested tile cap from 0 to 100, default 3; 0 means unlimited and explicitly bypasses layout capability limits. Positive caps are limited by the layout's display-dependent capability without changing the request. Excess windows follow when-full." ), ] }
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 mouseModifiers(_ defaultValue: MouseModifiers) -> SchemaValue { .object([ "type": .string("string"), "minLength": .integer(1), "pattern": .string("\\S"), "format": .string("parcel-mouse-modifiers"), "default": .string(defaultValue.description), "description": .string( "Control, Option, Command, and Shift only; use ctrl, alt (or opt), cmd, shift, or hyper."), ]) }
private static func choice(_ values: [String], defaultValue: String?, description: String? = nil) -> SchemaValue { var result: [String: SchemaValue] = ["type": .string("string"), "enum": .array(values.map(SchemaValue.string))] if let defaultValue { result["default"] = .string(defaultValue) } if let description { result["description"] = .string(description) } return .object(result) }
private static func number(_ range: ClosedRange<Double>, defaultValue: Double?, description: String? = nil) -> SchemaValue { var result: [String: SchemaValue] = [ "type": .string("number"), "minimum": .number(range.lowerBound), "maximum": .number(range.upperBound), ] if let defaultValue { result["default"] = .number(defaultValue) } if let description { result["description"] = .string(description) } return .object(result) }
private static func integer(_ range: ClosedRange<Int>, 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) } }}