Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272import Foundation
public enum ConfigValidator { public static func validate(_ document: TOMLDocument) -> ConfigValidationResult { var validation = Validation(document: document) return validation.run() }}
private struct Validation { let document: TOMLDocument var diagnostics: [ConfigDiagnostic] = []
mutating func run() -> ConfigValidationResult { let root = table(document.root, path: "configuration", example: "version = 1") unknownKeys( root, allowed: [ "version", "general", "layout", "motion", "mouse", "hover-bar", "keybindings", "float-rules", "rules", "accessibility", "mode", "classification", "callbacks", "focus-modes", "memory", "appearance", ] ) var configuration = ParcelConfiguration.defaults configuration.version = integer(root["version"], path: "version", fallback: 1, bounds: 1...1) configuration.general = general(root["general"]) configuration.layout = layout(root["layout"]) configuration.motion = motion(root["motion"]) configuration.appearance = appearance(root["appearance"]) configuration.focusModes = focusModes(root["focus-modes"]) configuration.mouse = mouse(root["mouse"]) configuration.hoverBar = hoverBar(root["hover-bar"]) configuration.memory = memory(root["memory"]) configuration.accessibility = accessibility(root["accessibility"]) configuration.floatRules = floatRules(root["float-rules"]) configuration.rules = rules(root["rules"]) configuration.classification = classification(root["classification"]) configuration.callbacks = callbacks(root["callbacks"]) let namedTables = modeTables(root["mode"]) let modeNames = Set(namedTables.keys) configuration.modes = modes(namedTables, names: modeNames) let bindings = keybindings( root["keybindings"], prefix: configuration.general.prefix, prefixLocation: root["general"]?["prefix"]?.range.start ?? document.root.range.start, modeNames: modeNames ) configuration.keybindings = bindings.commands configuration.defaultModeEntries = bindings.entries configuration.inheritedShortcutDisplacements = bindings.displacements diagnostics.sort { if $0.location.offset != $1.location.offset { return $0.location.offset < $1.location.offset } return $0.message < $1.message } return ConfigValidationResult( configuration: diagnostics.contains { $0.severity == .error } ? nil : configuration, diagnostics: diagnostics ) }
mutating func callbacks(_ node: TOMLNode?) -> CallbackConfiguration { guard let node else { return CallbackConfiguration() } let values = table(node, path: "callbacks", example: "[callbacks]") unknownKeys(values, allowed: CallbackEvent.allCases.map(\.rawValue), path: "callbacks") var commands: [CallbackEvent: [String]] = [:] for event in CallbackEvent.allCases { guard let value = values[event.rawValue] else { continue } guard case .array(let entries) = value.value else { failure( value, String( localized: "A callback must be an argument array, starting with an absolute executable path.", table: "Schema", bundle: .module)) continue } var arguments: [String] = [] for entry in entries { guard case .string(let argument) = entry.value else { failure( entry, String(localized: "Every callback argument must be a string.", table: "Schema", bundle: .module) ) continue } arguments.append(argument) } guard CallbackConfiguration.valid(arguments) else { failure( value, String( localized: "A callback needs an absolute executable path, at most 64 arguments, and at most 16384 bytes. Empty arrays disable callbacks.", table: "Schema", bundle: .module)) continue } commands[event] = arguments } return CallbackConfiguration(commands: commands) }
mutating func general(_ node: TOMLNode?) -> GeneralConfiguration { var result = GeneralConfiguration() guard let node else { return result } let values = table(node, path: "general", example: "[general]\nlaunch-at-login = false") unknownKeys( values, allowed: ["prefix", "launch-at-login", "shortcuts-enabled", "when-display-full", "collect-activity"], path: "general") result.collectActivity = boolean( values["collect-activity"], path: "general.collect-activity", fallback: result.collectActivity) result.shortcutsEnabled = boolean( values["shortcuts-enabled"], path: "general.shortcuts-enabled", fallback: result.shortcutsEnabled) result.whenDisplayFull = choice( values["when-display-full"], path: "general.when-display-full", fallback: result.whenDisplayFull) result.launchAtLogin = boolean( values["launch-at-login"], path: "general.launch-at-login", fallback: result.launchAtLogin ) if let prefix = string(values["prefix"], path: "general.prefix", example: "prefix = \"ctrl-alt\"") { do { result.prefix = try KeyModifiers(parsing: prefix) } catch { if let node = values["prefix"] { failure( node, String( localized: "Invalid general.prefix: \(String(describing: error)). For example: prefix = \"ctrl-alt\".", table: "Schema", bundle: .module ) ) } } } return result }
mutating func layout(_ node: TOMLNode?) -> LayoutConfiguration { guard let node else { return LayoutConfiguration() } let values = table(node, path: "layout", example: "[layout]\ndefault = \"grid\"") let global = layoutValues(values, path: "layout", inherited: LayoutValues(), allowsDisplays: true) var displays: [UUID: LayoutValues] = [:] if let displayNode = values["displays"] { let example = "[layout.displays.\"00000000-0000-0000-0000-000000000001\"]\ndefault = \"columns\"" let entries = table(displayNode, path: "layout.displays", example: example) var locations: [UUID: SourceLocation] = [:] for key in entries.keys.sorted() { guard let entry = entries[key] else { continue } guard key.count == 36, let id = UUID(uuidString: key) else { failure( entry, String( localized: "Display key “\(key)” must be a UUID. For example:\n\(example)", table: "Schema", bundle: .module ) ) continue } if let previous = locations[id] { failure( entry, String( localized: "Display UUID “\(key)” is configured twice with different letter casing. Keep one table, for example:\n\(example)", table: "Schema", bundle: .module ), relatedLocation: previous ) continue } locations[id] = entry.range.start let path = "layout.displays.\"\(key)\"" let overrides = table(entry, path: path, example: example) displays[id] = layoutValues(overrides, path: path, inherited: global) } } return LayoutConfiguration(global: global, displays: displays) }
mutating func layoutValues( _ values: [String: TOMLNode], path: String, inherited: LayoutValues, allowsDisplays: Bool = false ) -> LayoutValues { var allowed = ["default", "portrait-layout", "ratio", "gaps", "reserved", "window-cap", "when-full"] if allowsDisplays { allowed.append("displays") } unknownKeys(values, allowed: allowed, path: path) var result = inherited result.defaultLayout = choice(values["default"], path: "\(path).default", fallback: result.defaultLayout) result.portraitLayout = choice( values["portrait-layout"], path: "\(path).portrait-layout", fallback: result.portraitLayout) result.whenFull = choice(values["when-full"], path: "\(path).when-full", fallback: result.whenFull) result.ratio = number( values["ratio"], path: "\(path).ratio", fallback: result.ratio, bounds: ConfigLimits.ratio) result.windowCap = integer( values["window-cap"], path: "\(path).window-cap", fallback: result.windowCap, bounds: ConfigLimits.windowCap ) if let node = values["gaps"] { let gaps = table(node, path: "\(path).gaps", example: "[\(path).gaps]\ninner = 8") unknownKeys(gaps, allowed: ["inner", "outer"], path: "\(path).gaps") result.gaps.inner = number( gaps["inner"], path: "\(path).gaps.inner", fallback: result.gaps.inner, bounds: ConfigLimits.gap ) result.gaps.outer = number( gaps["outer"], path: "\(path).gaps.outer", fallback: result.gaps.outer, bounds: ConfigLimits.gap ) } if let node = values["reserved"] { let reserved = table(node, path: "\(path).reserved", example: "[\(path).reserved]\ntop = 0") unknownKeys(reserved, allowed: ["top", "right", "bottom", "left"], path: "\(path).reserved") result.reserved.top = number( reserved["top"], path: "\(path).reserved.top", fallback: result.reserved.top, bounds: ConfigLimits.reserved ) result.reserved.right = number( reserved["right"], path: "\(path).reserved.right", fallback: result.reserved.right, bounds: ConfigLimits.reserved ) result.reserved.bottom = number( reserved["bottom"], path: "\(path).reserved.bottom", fallback: result.reserved.bottom, bounds: ConfigLimits.reserved ) result.reserved.left = number( reserved["left"], path: "\(path).reserved.left", fallback: result.reserved.left, bounds: ConfigLimits.reserved ) } return result }
mutating func memory(_ node: TOMLNode?) -> MemoryConfiguration { var result = MemoryConfiguration() guard let node else { return result } let values = table(node, path: "memory", example: "[memory]\nenabled = true") unknownKeys(values, allowed: ["enabled", "restore-windows"], path: "memory") result.enabled = boolean(values["enabled"], path: "memory.enabled", fallback: result.enabled) result.restoreWindows = boolean( values["restore-windows"], path: "memory.restore-windows", fallback: result.restoreWindows) return result }
mutating func motion(_ node: TOMLNode?) -> MotionConfiguration { var result = MotionConfiguration() guard let node else { return result } let values = table(node, path: "motion", example: "[motion]\nenabled = true") unknownKeys( values, allowed: [ "enabled", "level", "speed", "transitions", "sound", "highlight", "focus-border", "drop-hints", "experimental-dimming", "menu-bar-icon", "highlight-width", ], path: "motion" ) result.enabled = boolean(values["enabled"], path: "motion.enabled", fallback: result.enabled) result.level = choice(values["level"], path: "motion.level", fallback: result.level) result.speed = number(values["speed"], path: "motion.speed", fallback: result.speed, bounds: ConfigLimits.speed) result.transitions = choice(values["transitions"], path: "motion.transitions", fallback: result.transitions) result.focusBorder = boolean(values["focus-border"], path: "motion.focus-border", fallback: result.focusBorder) result.highlight = choice(values["highlight"], path: "motion.highlight", fallback: result.highlight) result.highlightWidth = number( values["highlight-width"], path: "motion.highlight-width", fallback: result.highlightWidth, bounds: MotionConfiguration.highlightWidths) result.dropHints = boolean(values["drop-hints"], path: "motion.drop-hints", fallback: result.dropHints) result.experimentalDimming = boolean( values["experimental-dimming"], path: "motion.experimental-dimming", fallback: result.experimentalDimming) result.sound = boolean(values["sound"], path: "motion.sound", fallback: result.sound) result.menuBarIcon = choice(values["menu-bar-icon"], path: "motion.menu-bar-icon", fallback: result.menuBarIcon) return result }
mutating func appearance(_ node: TOMLNode?) -> AppearanceConfiguration { var result = AppearanceConfiguration() guard let node else { return result } let values = table(node, path: "appearance", example: "[appearance]\npalette = \"system\"") unknownKeys( values, allowed: ["palette", "mode", "border-opacity", "border-radius", "stack-controls"] + AppearanceColorRole.allCases.map(\.rawValue), path: "appearance") result.stackControls = choice( values["stack-controls"], path: "appearance.stack-controls", fallback: result.stackControls) result.palette = choice(values["palette"], path: "appearance.palette", fallback: result.palette) result.mode = choice(values["mode"], path: "appearance.mode", fallback: result.mode) result.borderOpacity = number( values["border-opacity"], path: "appearance.border-opacity", fallback: result.borderOpacity, bounds: AppearanceConfiguration.borderOpacities) if let radius = values["border-radius"] { result.borderRadius = number( radius, path: "appearance.border-radius", fallback: AppearanceConfiguration.borderRadii.lowerBound, bounds: AppearanceConfiguration.borderRadii) } for role in AppearanceColorRole.allCases { let path = "appearance.\(role.rawValue)" let example = "\(role.rawValue) = \"#B65C44\"" guard let node = values[role.rawValue], let hex = string(node, path: path, example: example) else { continue } guard let color = AppearanceHexColor(hex: hex) else { failure( node, String( localized: "“\(path)” must use #RRGGBB with exactly six hexadecimal digits. For example: \(example).", table: "Schema", bundle: .module)) continue } result.colors[role] = color } return result }
mutating func focusModes(_ node: TOMLNode?) -> FocusModeConfiguration { var result = FocusModeConfiguration() guard let node else { return result } let values = table(node, path: "focus-modes", example: "[focus-modes]\nno-peek-level = 0.25") unknownKeys(values, allowed: ["no-peek-level", "no-peek-blur", "clean-space-color"], path: "focus-modes") result.noPeekLevel = number( values["no-peek-level"], path: "focus-modes.no-peek-level", fallback: result.noPeekLevel, bounds: FocusModeConfiguration.noPeekLevels) result.noPeekBlur = boolean( values["no-peek-blur"], path: "focus-modes.no-peek-blur", fallback: result.noPeekBlur) result.cleanSpaceColor = choice( values["clean-space-color"], path: "focus-modes.clean-space-color", fallback: result.cleanSpaceColor) return result }
mutating func hoverBar(_ node: TOMLNode?) -> HoverBarConfiguration { var result = HoverBarConfiguration() guard let node else { return result } let values = table(node, path: "hover-bar", example: "[hover-bar]\nenabled = true") unknownKeys(values, allowed: ["enabled", "delay"], path: "hover-bar") result.enabled = boolean(values["enabled"], path: "hover-bar.enabled", fallback: result.enabled) result.delay = number( values["delay"], path: "hover-bar.delay", fallback: result.delay, bounds: HoverBarConfiguration.delays) return result }
mutating func mouse(_ node: TOMLNode?) -> MouseConfiguration { var result = MouseConfiguration() guard let node else { return result } let values = table(node, path: "mouse", example: "[mouse]\nenabled = true") unknownKeys( values, allowed: [ "enabled", "swap-modifiers", "stack-modifiers", "move-modifiers", "resize-modifiers", "edge-snapping", "drop-to-ratio", "focus-follows-mouse", "focus-delay", "typing-cooldown", ], path: "mouse") result.edgeSnapping = boolean( values["edge-snapping"], path: "mouse.edge-snapping", fallback: result.edgeSnapping) result.dropToRatio = boolean(values["drop-to-ratio"], path: "mouse.drop-to-ratio", fallback: result.dropToRatio) result.focusFollowsMouse = boolean( values["focus-follows-mouse"], path: "mouse.focus-follows-mouse", fallback: result.focusFollowsMouse) result.focusDelay = number( values["focus-delay"], path: "mouse.focus-delay", fallback: result.focusDelay, bounds: MouseConfiguration.focusDelays) result.typingCooldown = number( values["typing-cooldown"], path: "mouse.typing-cooldown", fallback: result.typingCooldown, bounds: MouseConfiguration.typingCooldowns) let move = mouseModifiers( values["move-modifiers"], path: "mouse.move-modifiers", fallback: result.moveModifiers) let resize = mouseModifiers( values["resize-modifiers"], path: "mouse.resize-modifiers", fallback: result.resizeModifiers) if let move { result.moveModifiers = move } if let resize { result.resizeModifiers = resize } result.enabled = boolean(values["enabled"], path: "mouse.enabled", fallback: result.enabled) let swap = mouseModifiers( values["swap-modifiers"], path: "mouse.swap-modifiers", fallback: result.swapModifiers) let stack = mouseModifiers( values["stack-modifiers"], path: "mouse.stack-modifiers", fallback: result.stackModifiers) if let swap { result.swapModifiers = swap } if let stack { result.stackModifiers = stack } let sets: [(String, MouseModifiers?)] = [ ("swap-modifiers", swap), ("stack-modifiers", stack), ("move-modifiers", move), ("resize-modifiers", resize), ] for (index, first) in sets.enumerated() { for second in sets.dropFirst(max(2, index + 1)) { guard let firstModifiers = first.1, let secondModifiers = second.1, firstModifiers == secondModifiers, let explicit = values[first.0] ?? values[second.0] else { continue } failure( explicit, String( localized: "Mouse gestures need distinct modifier combinations. Change mouse.\(first.0) or mouse.\(second.0).", table: "Schema", bundle: .module)) } } if let swap, let stack, swap == stack { if let swapNode = values["swap-modifiers"], let stackNode = values["stack-modifiers"] { let later = swapNode.range.start.offset > stackNode.range.start.offset ? swapNode : stackNode let earlier = swapNode.range.start.offset > stackNode.range.start.offset ? stackNode : swapNode failure( later, String( localized: "mouse.swap-modifiers and mouse.stack-modifiers both resolve to \(swap.description). Use different nonempty combinations so swap and stack are unambiguous.", table: "Schema", bundle: .module ), relatedLocation: earlier.range.start ) } else if let explicitNode = values["swap-modifiers"] ?? values["stack-modifiers"] { let explicitPath = values["swap-modifiers"] == nil ? "mouse.stack-modifiers" : "mouse.swap-modifiers" let inheritedPath = values["swap-modifiers"] == nil ? "mouse.swap-modifiers" : "mouse.stack-modifiers" failure( explicitNode, String( localized: "“\(explicitPath)” uses \(swap.description), which conflicts with the inherited default for “\(inheritedPath)”. Assign different nonempty mouse modifier combinations.", table: "Schema", bundle: .module ) ) } } return result }
mutating func mouseModifiers(_ node: TOMLNode?, path: String, fallback: MouseModifiers) -> MouseModifiers? { guard let node else { return fallback } let example = "\(path) = \"\(fallback.description)\"" guard let text = string(node, path: path, example: example) else { return nil } do { return try MouseModifiers(parsing: text) } catch { failure( node, String( localized: "Invalid mouse modifiers for “\(path)”: \(error.description). For example: \(example).", table: "Schema", bundle: .module ) ) return nil } }
mutating func accessibility(_ node: TOMLNode?) -> AccessibilityConfiguration { var result = AccessibilityConfiguration() guard let node else { return result } let values = table(node, path: "accessibility", example: "[accessibility]\nannounce-layout-changes = false") unknownKeys(values, allowed: ["announce-layout-changes"], path: "accessibility") result.announceLayoutChanges = boolean( values["announce-layout-changes"], path: "accessibility.announce-layout-changes", fallback: result.announceLayoutChanges ) return result }
mutating func floatRules(_ node: TOMLNode?) -> [FloatRule] { guard let node else { return [] } let example = "[[float-rules]]\nbundle-id = \"com.example.app\"" guard case .array(let entries) = node.value else { failure( node, String( localized: "float-rules must be an array of tables. For example:\n\(example)", table: "Schema", bundle: .module ) ) return [] } var result: [FloatRule] = [] for (index, entry) in entries.enumerated() { let path = "float-rules[\(index)]" let values = table(entry, path: path, example: example) unknownKeys(values, allowed: ["bundle-id", "title-regex", "role"], path: path) if !["bundle-id", "title-regex", "role"].contains(where: { values[$0] != nil }) { failure( entry, String( localized: "“\(path)” needs at least one matcher: bundle-id, title-regex, or role. For example:\n\(example)", table: "Schema", bundle: .module ) ) } let bundleID = matcher( values["bundle-id"], path: "\(path).bundle-id", example: "bundle-id = \"com.example.app\"") let titleRegex = matcher( values["title-regex"], path: "\(path).title-regex", example: "title-regex = \"^Preferences$\"") let role = matcher(values["role"], path: "\(path).role", example: "role = \"AXDialog\"") if let titleRegex, let regexNode = values["title-regex"] { do { _ = try NSRegularExpression(pattern: titleRegex) } catch { failure( regexNode, String( localized: "“\(path).title-regex” is not a valid regular expression. For example: title-regex = \"^Preferences$\".", table: "Schema", bundle: .module ) ) } } result.append(FloatRule(bundleID: bundleID, titleRegex: titleRegex, role: role)) } return result }
}
extension Validation { fileprivate mutating func classification(_ node: TOMLNode?) -> ClassificationConfiguration { guard let node else { return ClassificationConfiguration() } let values = table(node, path: "classification", example: "[classification]\ndisabled-default-float-apps = []") unknownKeys(values, allowed: ["disabled-default-float-apps"], path: "classification") guard let list = values["disabled-default-float-apps"] else { return ClassificationConfiguration() } guard case .array(let entries) = list.value else { failure( list, String( localized: "Disabled default float apps must be an array of bundle identifiers.", table: "Schema", bundle: .module)) return ClassificationConfiguration() } var disabled: Set<String> = [] for entry in entries { guard let bundle = matcher( entry, path: "classification.disabled-default-float-apps", example: "disabled-default-float-apps = [\"com.apple.calculator\"]") else { continue } guard disabled.insert(bundle).inserted else { failure( entry, String( localized: "Each disabled bundle identifier must appear only once.", table: "Schema", bundle: .module)) continue } } return ClassificationConfiguration(disabledDefaultFloatApps: disabled) }
fileprivate mutating func rules(_ node: TOMLNode?) -> [RuleConfiguration] { guard let node else { return [] } let example = "[[rules]]\nbundle-id = \"com.example.app\"\naction = \"float\"" guard case .array(let entries) = node.value else { failure( node, String( localized: "rules must be an array of tables. For example:\n\(example)", table: "Schema", bundle: .module) ) return [] } let matchers = ["bundle-id", "app-name", "title-contains", "title-regex", "role", "subrole"] let outcomes = ["action", "display", "position", "layout", "space"] var result: [RuleConfiguration] = [] for (index, entry) in entries.enumerated() { let path = "rules[\(index)]" guard case .table(let values) = entry.value else { _ = table(entry, path: path, example: example) continue } unknownKeys(values, allowed: matchers + outcomes + ["move-to-space"], path: path) if !matchers.contains(where: { values[$0] != nil }) { failure( entry, String( localized: "“\(path)” needs at least one matcher: bundle-id, app-name, title-contains, title-regex, role, or subrole. For example:\n\(example)", table: "Schema", bundle: .module ) ) } if !outcomes.contains(where: { values[$0] != nil }) { failure( entry, String( localized: "“\(path)” needs at least one action or placement: action, display, or position. For example:\n\(example)", table: "Schema", bundle: .module ) ) } if let contains = values["title-contains"], let regex = values["title-regex"] { let later = contains.range.start.offset > regex.range.start.offset ? contains : regex let earlier = contains.range.start.offset > regex.range.start.offset ? regex : contains failure( later, String( localized: "“\(path)” cannot use both title-contains and title-regex. Choose one.", table: "Schema", bundle: .module ), relatedLocation: earlier.range.start ) } let bundleID = matcher( values["bundle-id"], path: "\(path).bundle-id", example: "bundle-id = \"com.example.app\"") let appName = matcher(values["app-name"], path: "\(path).app-name", example: "app-name = \"Example\"") let titleContains = matcher( values["title-contains"], path: "\(path).title-contains", example: "title-contains = \"Preferences\"") let titleRegex = matcher( values["title-regex"], path: "\(path).title-regex", example: "title-regex = \"^Preferences$\"") let role = matcher(values["role"], path: "\(path).role", example: "role = \"AXWindow\"") let subrole = matcher(values["subrole"], path: "\(path).subrole", example: "subrole = \"AXDialog\"") if let titleRegex, let regexNode = values["title-regex"] { do { _ = try NSRegularExpression(pattern: titleRegex) } catch { failure( regexNode, String( localized: "“\(path).title-regex” is not a valid regular expression. For example: title-regex = \"^Preferences$\".", table: "Schema", bundle: .module ) ) } } let action: RuleAction? = values["action"].map { choice($0, path: "\(path).action", fallback: .float) } let display = string(values["display"], path: "\(path).display", example: "display = \"main\"") let position = values["position"].map { integer($0, path: "\(path).position", fallback: 0, bounds: 0...Int.max) } let layout: ConfigLayout? = values["layout"].map { choice($0, path: "\(path).layout", fallback: .grid) } let space = values["space"].map { integer($0, path: "\(path).space", fallback: 1, bounds: 1...16) } result.append( RuleConfiguration( bundleID: bundleID, appName: appName, titleContains: titleContains, titleRegex: titleRegex, role: role, subrole: subrole, action: action, display: display, position: position, layout: layout, space: space, moveToSpace: boolean(values["move-to-space"], path: "\(path).move-to-space", fallback: false) ) ) } return result }
fileprivate mutating func matcher(_ node: TOMLNode?, path: String, example: String) -> String? { guard let value = string(node, path: path, example: example), let node else { return nil } guard !value.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { failure( node, String( localized: "“\(path)” cannot be empty. For example: \(example).", table: "Schema", bundle: .module ) ) return nil } return value }
}
private struct ModeBindingRecord { let name: String let chord: KeyChord let location: SourceLocation? let fallbackLocation: SourceLocation let isCommand: Bool}
extension Validation { fileprivate mutating func modeTables(_ node: TOMLNode?) -> [String: TOMLNode] { guard let node else { return [:] } let entries = table(node, path: "mode", example: "[mode.resize]") var result: [String: TOMLNode] = [:] for name in entries.keys.sorted() { guard let entry = entries[name] else { continue } guard BindingModeRules.validName(name) else { keyFailure(entry, BindingModeRules.invalidNameMessage(name)) continue } guard case .table = entry.value else { _ = table(entry, path: "mode.\(name)", example: "[mode.resize]") continue } result[name] = entry } return result }
fileprivate static func isModeActionKey(_ key: String) -> Bool { let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines) return trimmed.hasPrefix("enter-mode") || trimmed.hasPrefix("exit-mode") }
fileprivate mutating func bindingAction( _ key: String, node: TOMLNode, names: Set<String>, inDefault: Bool ) -> BindingAction? { if let command = ConfigCommand(rawValue: key), !inDefault { return .command(command) } if key == "exit-mode", !inDefault { return .exitMode } if key.hasPrefix("enter-mode ") { let target = String(key.dropFirst("enter-mode ".count)) if let message = BindingModeRules.targetError(target, key: key, names: names) { keyFailure(node, message) return nil } return .enterMode(target) } keyFailure(node, BindingModeRules.invalidActionMessage(key)) return nil }
fileprivate mutating func bindingChord(_ node: TOMLNode, key: String, path: String) -> KeyChord? { if case .bool(false) = node.value { return nil } guard case .string(let text) = node.value else { failure( node, String( localized: "“\(path).\(key)” needs a shortcut string or false to disable it.", table: "Schema", bundle: .module)) return nil } do { return try KeyChord(parsing: text) } catch { failure( node, String( localized: "Invalid shortcut for “\(path).\(key)”: \(String(describing: error)).", table: "Schema", bundle: .module)) return nil } }
fileprivate static let retiredAutomaticTilingKey = "pause-tiling"
fileprivate mutating func retiredAutomaticTilingBinding(_ values: [String: TOMLNode], path: String) -> Bool { guard let entry = values[Self.retiredAutomaticTilingKey] else { return false } let retired = "\(path).\(Self.retiredAutomaticTilingKey)" let current = "\(path).\(ConfigCommand.toggleAutomaticTiling.rawValue)" let hasCurrentBinding = values[ConfigCommand.toggleAutomaticTiling.rawValue] != nil let message: String if hasCurrentBinding { message = String( localized: "“\(retired)” is retired; its shortcut is ignored. Your explicit “\(current)” binding is unchanged.", table: "Schema", bundle: .module) } else { message = String( localized: "“\(retired)” is retired; this shortcut is unbound. Bind “\(current)” explicitly to restore it.", table: "Schema", bundle: .module) } diagnostics.append( ConfigDiagnostic( severity: .warning, location: entry.keyRange?.start ?? entry.range.start, message: message)) return !hasCurrentBinding }
fileprivate mutating func modes(_ tables: [String: TOMLNode], names: Set<String>) -> [String: [BindingAction: KeyChord]] { var result: [String: [BindingAction: KeyChord]] = [:] for name in tables.keys.sorted() { guard let node = tables[name], case .table(let values) = node.value else { continue } var bindings: [BindingAction: KeyChord] = [.exitMode: DefaultKeybindings.modeExit] var locations: [BindingAction: SourceLocation] = [:] _ = retiredAutomaticTilingBinding(values, path: "mode.\(name)") for key in values.keys.sorted() where key != Self.retiredAutomaticTilingKey { guard let entry = values[key], let action = bindingAction(key, node: entry, names: names, inDefault: false) else { continue } bindings.removeValue(forKey: action) if let chord = bindingChord(entry, key: key, path: "mode.\(name)") { bindings[action] = chord locations[action] = entry.range.start } } let records = bindings.map { action, chord in ModeBindingRecord( name: BindingModeRules.actionName(action), chord: chord, location: locations[action], fallbackLocation: node.range.start, isCommand: false) } duplicateModeChords(records, path: "mode.\(name)", skipCommandPairs: false) result[name] = bindings } return result }
fileprivate mutating func duplicateModeChords( _ records: [ModeBindingRecord], path: String, skipCommandPairs: Bool ) { diagnostics += BindingModeRules.duplicateChords(records, path: path, skipCommandPairs: skipCommandPairs) }
fileprivate mutating func keyFailure(_ node: TOMLNode, _ message: String) { diagnostics.append( ConfigDiagnostic(severity: .error, location: node.keyRange?.start ?? node.range.start, message: message)) }
fileprivate mutating func keybindings( _ node: TOMLNode?, prefix: KeyModifiers, prefixLocation: SourceLocation, modeNames: Set<String> ) -> ( commands: [ConfigCommand: KeyChord], entries: [String: KeyChord], displacements: [InheritedShortcutDisplacement] ) { var result = DefaultKeybindings.bindings(prefix: prefix) var entries: [String: KeyChord] = [:] var entryLocations: [String: SourceLocation] = [:] var explicitLocations: [ConfigCommand: SourceLocation] = [:] if let node { let examples = DefaultKeybindings.bindings() let example = ConfigCommand.allCases.first.flatMap { command in examples[command].map { "\(command.tomlKey) = \"\($0.description)\"" } } ?? "[keybindings]" let values = table(node, path: "keybindings", example: "[keybindings]\n\(example)") let modeKeys = values.keys.filter { Self.isModeActionKey($0) } unknownKeys( values, allowed: ConfigCommand.allCases.map(\.rawValue) + modeKeys + [Self.retiredAutomaticTilingKey], path: "keybindings") if retiredAutomaticTilingBinding(values, path: "keybindings") { result.removeValue(forKey: .toggleAutomaticTiling) } for key in modeKeys.sorted() { guard let entry = values[key], let action = bindingAction(key, node: entry, names: modeNames, inDefault: true), case .enterMode(let target) = action else { continue } if let chord = bindingChord(entry, key: key, path: "keybindings") { entries[target] = chord entryLocations[target] = entry.range.start } } for command in ConfigCommand.allCases { guard let entry = values[command.rawValue] else { continue } if case .bool(false) = entry.value { result.removeValue(forKey: command) continue } let assignment = examples[command].map { "\(command.tomlKey) = \"\($0.description)\"" } ?? "\(command.tomlKey) = false" guard case .string(let text) = entry.value else { failure( entry, String( localized: "“keybindings.\(command.rawValue)” needs a shortcut string or false to disable it. For example: \(assignment).", table: "Schema", bundle: .module ) ) continue } do { result[command] = try KeyChord(parsing: text) explicitLocations[command] = entry.range.start } catch { failure( entry, String( localized: "Invalid shortcut for “\(command.rawValue)”: \(String(describing: error)). For example: \(assignment).", table: "Schema", bundle: .module ) ) } } } var displacements: [InheritedShortcutDisplacement] = [] let explicit = explicitLocations.keys.compactMap { command in result[command].map { (BindingAction.command(command), $0, explicitLocations[command]) } } + entries.keys.compactMap { target in entries[target].map { (BindingAction.enterMode(target), $0, entryLocations[target]) } } for command in result.keys.sorted(by: { $0.rawValue < $1.rawValue }) where explicitLocations[command] == nil { guard let chord = result[command], let owner = explicit.first(where: { $0.1 == chord }) else { continue } result.removeValue(forKey: command) displacements.append(InheritedShortcutDisplacement(command: command, chord: chord, binding: owner.0)) let binding = "keybindings.\(BindingModeRules.actionName(owner.0))" diagnostics.append( ConfigDiagnostic( severity: .warning, location: owner.2 ?? prefixLocation, message: String( localized: "keybindings.\(command.rawValue): Unbound because \(binding) uses this key (\(chord.description)).", table: "Schema", bundle: .module), relatedLocation: prefixLocation)) } duplicateChords(result, explicitLocations: explicitLocations, prefixLocation: prefixLocation) var records = result.map { command, chord in ModeBindingRecord( name: command.rawValue, chord: chord, location: explicitLocations[command], fallbackLocation: prefixLocation, isCommand: true) } records += entries.map { target, chord in ModeBindingRecord( name: "enter-mode \(target)", chord: chord, location: entryLocations[target], fallbackLocation: prefixLocation, isCommand: false) } duplicateModeChords(records, path: "keybindings", skipCommandPairs: true) return (result, entries, displacements) }
fileprivate mutating func duplicateChords( _ bindings: [ConfigCommand: KeyChord], explicitLocations: [ConfigCommand: SourceLocation], prefixLocation: SourceLocation ) { var seen: [KeyChord: ConfigCommand] = [:] let commands = bindings.keys.sorted { let lhs = explicitLocations[$0]?.offset ?? -1 let rhs = explicitLocations[$1]?.offset ?? -1 return lhs == rhs ? $0.rawValue < $1.rawValue : lhs < rhs } for command in commands { guard let chord = bindings[command] else { continue } guard let previous = seen[chord] else { seen[chord] = command continue } let location = explicitLocations[command] ?? prefixLocation let related = explicitLocations[previous] ?? prefixLocation let message: String if explicitLocations[previous] == nil, explicitLocations[command] == nil { message = String( localized: """ Inherited defaults “\(previous.rawValue)” and “\(command.rawValue)” both resolve to \(chord.description) with this prefix. \ Change general.prefix or disable one with \(command.tomlKey) = false. """, table: "Schema", bundle: .module ) } else if explicitLocations[previous] == nil { message = String( localized: """ “\(command.rawValue)” uses \(chord.description), which conflicts with the inherited default for “\(previous.rawValue)”. \ Override that default or disable it with \(previous.rawValue) = false. """, table: "Schema", bundle: .module ) } else { message = String( localized: """ “\(command.rawValue)” and “\(previous.rawValue)” both use \(chord.description); the earlier binding is at line \(related.line), \ column \(related.column). Assign different shortcuts, or disable one with \(command.tomlKey) = false. """, table: "Schema", bundle: .module ) } diagnostics.append( ConfigDiagnostic(severity: .error, location: location, message: message, relatedLocation: related) ) } }
fileprivate mutating func table(_ node: TOMLNode, path: String, example: String) -> [String: TOMLNode] { guard case .table(let entries) = node.value else { failure( node, String( localized: "Expected a table for “\(path)”. For example:\n\(example)", table: "Schema", bundle: .module ) ) return [:] } return entries }
fileprivate mutating func boolean(_ node: TOMLNode?, path: String, fallback: Bool) -> Bool { guard let node else { return fallback } guard case .bool(let value) = node.value else { let example = "\(path) = \(fallback)" failure( node, String( localized: "Expected true or false for “\(path)”. For example: \(example).", table: "Schema", bundle: .module ) ) return fallback } return value }
fileprivate mutating func string(_ node: TOMLNode?, path: String, example: String) -> String? { guard let node else { return nil } guard case .string(let value) = node.value else { failure( node, String( localized: "Expected a quoted string for “\(path)”. For example: \(example).", table: "Schema", bundle: .module ) ) return nil } return value }
fileprivate mutating func integer(_ node: TOMLNode?, path: String, fallback: Int, bounds: ClosedRange<Int>) -> Int { guard let node else { return fallback } let example = "\(path) = \(fallback)" guard case .integer(let value) = node.value else { failure( node, String( localized: "Expected a whole number for “\(path)”. For example: \(example).", table: "Schema", bundle: .module ) ) return fallback } guard let converted = Int(exactly: value), bounds.contains(converted) else { failure( node, String( localized: "“\(path)” must be a whole number between \(bounds.lowerBound) and \(bounds.upperBound). For example: \(example).", table: "Schema", bundle: .module ) ) return fallback } return converted }
fileprivate mutating func number(_ node: TOMLNode?, path: String, fallback: Double, bounds: ClosedRange<Double>) -> Double { guard let node else { return fallback } let example = "\(path) = \(fallback)" let value: Double switch node.value { case .float(let number): value = number case .integer(let number): value = Double(number) default: failure( node, String( localized: "Expected a number for “\(path)”. For example: \(example).", table: "Schema", bundle: .module ) ) return fallback } guard value.isFinite, bounds.contains(value) else { let lower = String(bounds.lowerBound) let upper = String(bounds.upperBound) failure( node, String( localized: "“\(path)” must be a finite number between \(lower) and \(upper). For example: \(example).", table: "Schema", bundle: .module ) ) return fallback } return value }
fileprivate mutating func choice<Choice: RawRepresentable & CaseIterable>( _ node: TOMLNode?, path: String, fallback: Choice ) -> Choice where Choice.RawValue == String { let example = "\(path) = \"\(fallback.rawValue)\"" guard let text = string(node, path: path, example: example), let node else { return fallback } guard let value = Choice(rawValue: text) else { let options = Choice.allCases.map { "\"\($0.rawValue)\"" }.joined(separator: ", ") failure( node, String( localized: "“\(path)” must be one of \(options). For example: \(example).", table: "Schema", bundle: .module ) ) return fallback } return value }
fileprivate mutating func unknownKeys(_ values: [String: TOMLNode], allowed: [String], path: String = "") { for key in values.keys.sorted() where !allowed.contains(key) { guard let node = values[key] else { continue } let qualified = path.isEmpty ? key : "\(path).\(key)" let dashedKey = key.replacingOccurrences(of: "_", with: "-") let suggestedKey: String? if dashedKey != key, allowed.contains(dashedKey) { suggestedKey = dashedKey } else { let closest = allowed.sorted { let lhs = Self.editDistance(key, $0) let rhs = Self.editDistance(key, $1) return lhs == rhs ? $0 < $1 : lhs < rhs }.first if let closest, Self.editDistance(key, closest) <= (key.count < 3 ? 1 : 2) { suggestedKey = closest } else { suggestedKey = nil } } let message: String if let suggestedKey { let suggestion = path.isEmpty ? suggestedKey : "\(path).\(suggestedKey)" message = String( localized: "Unknown key “\(qualified)”. Did you mean “\(suggestion)”?", table: "Schema", bundle: .module ) } else { message = String( localized: "Unknown key “\(qualified)”; this setting is ignored.", table: "Schema", bundle: .module ) } diagnostics.append( ConfigDiagnostic( severity: .warning, location: node.keyRange?.start ?? node.range.start, message: message) ) } }
fileprivate mutating func failure(_ node: TOMLNode, _ message: String, relatedLocation: SourceLocation? = nil) { diagnostics.append( ConfigDiagnostic( severity: .error, location: node.range.start, message: message, relatedLocation: relatedLocation) ) }
fileprivate static func editDistance(_ lhs: String, _ rhs: String) -> Int { let right = Array(rhs) var previous = Array(0...right.count) for (leftIndex, character) in lhs.enumerated() { var row = [leftIndex + 1] for (rightIndex, other) in right.enumerated() { row.append( min( row[rightIndex] + 1, previous[rightIndex + 1] + 1, previous[rightIndex] + (character == other ? 0 : 1)) ) } previous = row } return previous[right.count] }}
extension ParcelConfiguration { public func validateBindingModes() throws { let names = Set(modes.keys) for name in names.sorted() where !BindingModeRules.validName(name) { throw ConfigDiagnostic(message: BindingModeRules.invalidNameMessage(name)) } var defaults: [ModeBindingRecord] = [] for command in keybindings.keys.sorted(by: { $0.rawValue < $1.rawValue }) { guard let chord = keybindings[command] else { continue } try BindingModeRules.validateAction(.command(command), names: names) defaults.append(BindingModeRules.record(.command(command), chord: chord)) } for target in defaultModeEntries.keys.sorted() { guard let chord = defaultModeEntries[target] else { continue } let action = BindingAction.enterMode(target) try BindingModeRules.validateAction(action, names: names) defaults.append(BindingModeRules.record(action, chord: chord)) } if let diagnostic = BindingModeRules.duplicateChords(defaults, path: "keybindings").first { throw diagnostic } for name in names.sorted() { guard let bindings = modes[name] else { continue } var records: [ModeBindingRecord] = [] for action in bindings.keys.sorted(by: { BindingModeRules.actionName($0) < BindingModeRules.actionName($1) }) { guard let chord = bindings[action] else { continue } try BindingModeRules.validateAction(action, names: names) records.append(BindingModeRules.record(action, chord: chord)) } if let diagnostic = BindingModeRules.duplicateChords(records, path: "mode.\(name)").first { throw diagnostic } } }}
private enum BindingModeRules { static func validName(_ name: String) -> Bool { !name.isEmpty && name.lowercased() != "default" && name.utf8.allSatisfy { (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 95 } }
static func invalidNameMessage(_ name: String) -> String { String( localized: "Invalid mode name “\(name)”. Use ASCII letters, digits, underscores, or hyphens; default is reserved.", table: "Schema", bundle: .module) }
static func invalidActionMessage(_ key: String) -> String { String( localized: "Invalid binding action “\(key)”. Use a command, enter-mode followed by a mode name, or exit-mode inside a named mode.", table: "Schema", bundle: .module) }
static func targetError(_ target: String, key: String, names: Set<String>) -> String? { guard validName(target) else { return String( localized: "Invalid target in “\(key)”. Use a valid named mode after enter-mode.", table: "Schema", bundle: .module) } guard names.contains(target) else { return String( localized: "Unknown mode “\(target)” in “\(key)”. Declare [mode.\(target)].", table: "Schema", bundle: .module) } return nil }
static func actionName(_ action: BindingAction) -> String { switch action { case .command(let command): command.rawValue case .enterMode(let name): "enter-mode \(name)" case .exitMode: "exit-mode" } }
static func validateAction(_ action: BindingAction, names: Set<String>) throws { switch action { case .command(let command): guard ConfigCommand(rawValue: command.rawValue) == command else { throw ConfigDiagnostic(message: invalidActionMessage(command.rawValue)) } case .enterMode(let target): if let message = targetError(target, key: actionName(action), names: names) { throw ConfigDiagnostic(message: message) } case .exitMode: break } }
static func record(_ action: BindingAction, chord: KeyChord) -> ModeBindingRecord { ModeBindingRecord( name: actionName(action), chord: chord, location: SourceLocation(), fallbackLocation: SourceLocation(), isCommand: false) }
static func duplicateChords( _ records: [ModeBindingRecord], path: String, skipCommandPairs: Bool = false ) -> [ConfigDiagnostic] { var diagnostics: [ConfigDiagnostic] = [] var seen: [KeyChord: ModeBindingRecord] = [:] for record in records.sorted(by: { let lhs = $0.location?.offset ?? -1 let rhs = $1.location?.offset ?? -1 return lhs == rhs ? $0.name < $1.name : lhs < rhs }) { guard let previous = seen[record.chord] else { seen[record.chord] = record continue } if skipCommandPairs && record.isCommand && previous.isCommand { continue } let inherited = previous.location == nil ? String(localized: " (an inherited default)", table: "Schema", bundle: .module) : "" let message = String( localized: """ “\(path).\(record.name)” and “\(previous.name)” both use \(record.chord.description)\(inherited). \ Assign different shortcuts or disable one with false. """, table: "Schema", bundle: .module) diagnostics.append( ConfigDiagnostic( severity: .error, location: record.location ?? record.fallbackLocation, message: message, relatedLocation: previous.location ?? previous.fallbackLocation)) } return diagnostics }}