import Foundation import ParcelConfig enum SettingsEdit: Sendable { case value(SettingsField, TOMLValue) case values([(SettingsField, TOMLValue)]) case removeAppearanceValues([String]) case reservedEdgesShared(Bool, connectedDisplays: [UUID]) case restoreSource(expected: String, original: String) case shortcut(ConfigCommand, KeyChord?) case revertShortcuts([ConfigCommand], resetPrefix: Bool) case hoverPreferences(HoverBarConfiguration, onlyMissing: Bool) case addRule(FloatRule) case replaceRule(index: Int, original: FloatRule, replacement: FloatRule) case removeRule(index: Int, original: FloatRule) case addWindowRule(RuleConfiguration) case removeWindowRule(index: Int, original: RuleConfiguration) case appTiling(bundleID: String, enabled: Bool) case windowRuleConsent(index: Int, original: RuleConfiguration, enabled: Bool) } enum SettingsDocumentEditor { static func validate(_ document: TOMLDocument) throws -> ParcelConfiguration { let result = ConfigValidator.validate(document) guard let configuration = result.configuration, !result.diagnostics.contains(where: { $0.severity == .error }) else { throw SettingsFailure(result.diagnostics.map(\.description).joined(separator: "\n")) } return configuration } static func apply(_ edit: SettingsEdit, to document: inout TOMLDocument) throws { switch edit { case .value(let field, let value): try document.setValue(value, forKey: field.path(in: document)) case .values(let values): for (field, value) in values { try document.setValue(value, forKey: field.path(in: document)) } case .reservedEdgesShared(let shared, let connectedDisplays): let configuration = try validate(document) if shared { var expected = configuration for display in configuration.layout.displays.keys { expected.layout.displays[display]?.reserved = configuration.layout.global.reserved for field in ReservedEdgeSettings.fields { try removeValue( at: SettingsField.layout(field, display: display).path(in: document), from: &document) } } guard try validate(document) == expected else { throw SettingsFailure.conflict } } else { for display in Set(connectedDisplays).sorted(by: { $0.uuidString < $1.uuidString }) { for field in ReservedEdgeSettings.fields { try document.setValue( .float(ReservedEdgeSettings.value(field, in: configuration.layout.global.reserved)), forKey: SettingsField.layout(field, display: display).path(in: document)) } } } case .restoreSource(let expected, let original): guard document.source == expected else { throw SettingsFailure.conflict } document = try TOMLDocument(parsing: original) case .removeAppearanceValues(let keys): for key in keys { try removeValue(key, table: "appearance", from: &document) } case .revertShortcuts(let commands, let resetPrefix): for command in commands { try removeValue(command.rawValue, table: "keybindings", from: &document) } if commands.contains(.toggleAutomaticTiling) { try removeValue("pause-tiling", table: "keybindings", from: &document) } if resetPrefix { try removeValue("prefix", table: "general", from: &document) } case .shortcut(let command, let chord): try document.setValue( chord.map { .string($0.description) } ?? .bool(false), forKey: ["keybindings", command.rawValue]) case .hoverPreferences(let preferences, let onlyMissing): for (key, value) in [ ("enabled", TOMLValue.bool(preferences.enabled)), ("delay", .float(preferences.delay)), ] { let path = ["hover-bar", key] if !onlyMissing || document.node(forKey: path) == nil { try document.setValue(value, forKey: path) } } case .addRule(let rule): try add(rule, to: &document) case .replaceRule(let index, let original, let replacement): try checkRule(index, original: original, in: document) let path: [TOMLPathComponent] = [.key("float-rules"), .index(index)] for (key, value) in matchers(replacement) { let field = path + [.key(key)] if let value { try document.setValue(.string(value), at: field) } else if document.node(at: field) != nil { try removeMatcher(key, rule: index, from: &document) } } case .removeRule(let index, let original): try checkRule(index, original: original, in: document) try removeRule(index, from: &document) case .addWindowRule(let rule): guard (try validate(document)).rules.last != rule else { return } try addAssignments(WindowRuleEditing.assignments(rule), listName: "rules", to: &document) case .appTiling(let bundleID, let enabled): try setAppTiling(bundleID, enabled: enabled, in: &document) case .removeWindowRule(let index, let original): try checkWindowRule(index, original: original, in: document) try removeRule(index, listName: "rules", from: &document) case .windowRuleConsent(let index, let original, let enabled): try checkWindowRule(index, original: original, in: document) guard original.space != nil else { throw SettingsFailure.conflict } try document.setValue(.bool(enabled), at: [.key("rules"), .index(index), .key("move-to-space")]) } } private static func setAppTiling(_ bundleID: String, enabled: Bool, in document: inout TOMLDocument) throws { guard !bundleID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw SettingsFailure(SettingsText.string("A bundle identifier is required to change app tiling.")) } let configuration = try validate(document) let indices = configuration.rules.indices.filter { WindowRuleEditing.isBareAppRule(configuration.rules[$0], bundleID: bundleID) } var baseline = configuration baseline.rules.removeAll { WindowRuleEditing.isBareAppRule($0, bundleID: bundleID) } let needsOverride = WindowRuleEditing.tilesApp(bundleID, configuration: baseline) != enabled let retained = indices.last.flatMap { index -> Int? in guard needsOverride, !configuration.rules.dropFirst(index + 1).contains(where: { WindowRuleEditing.isAppWide($0, bundleID: bundleID) }) else { return nil } return index } if let retained { let path: [TOMLPathComponent] = [.key("rules"), .index(retained), .key("action")] try document.setValue(.string(enabled ? "tile" : "float"), at: path) } for index in indices.reversed() where index != retained { try removeRule(index, listName: "rules", from: &document) } if needsOverride, retained == nil { try addAssignments( WindowRuleEditing.assignments(RuleConfiguration(bundleID: bundleID, action: enabled ? .tile : .float)), listName: "rules", to: &document) } } private static func matchers(_ rule: FloatRule) -> [(String, String?)] { [("bundle-id", rule.bundleID), ("title-regex", rule.titleRegex), ("role", rule.role)] } private static func checkWindowRule(_ index: Int, original: RuleConfiguration, in document: TOMLDocument) throws { let configuration = try validate(document) guard configuration.rules.indices.contains(index), configuration.rules[index] == original else { throw SettingsFailure.conflict } } private static func checkRule(_ index: Int, original: FloatRule, in document: TOMLDocument) throws { let configuration = try validate(document) guard configuration.floatRules.indices.contains(index), configuration.floatRules[index] == original else { throw SettingsFailure.conflict } } private static func add(_ rule: FloatRule, to document: inout TOMLDocument) throws { let fields = matchers(rule).compactMap { key, value in value.map { (key, TOMLValue.string($0)) } } try addAssignments(fields, listName: "float-rules", to: &document) } private static func addAssignments( _ fields: [(String, TOMLValue)], listName: String, to document: inout TOMLDocument ) throws { let newline = document.source.contains("\r\n") ? "\r\n" : "\n" let assignments = try fields.map { key, value in key + " = " + (try TOMLWriter.encode(value)) } guard let array = document.node(forKey: [listName]) else { let separator = document.source.isEmpty || document.source.hasSuffix("\n") ? "" : newline document = try TOMLDocument( parsing: document.source + separator + "[[\(listName)]]" + newline + assignments.joined(separator: newline) + newline) return } let scalars = Array(document.source.unicodeScalars) if scalars[array.range.start.offset] == "[" { guard case .array(let entries) = array.value else { throw unsupportedRules } let end = array.range.end.offset - 1 var edits: [(Range, String)] = [(end.. rule.range.end.offset else { throw unsupportedRules } switch value.value { case .table, .array: throw unsupportedRules default: edits.append((removalRange(key.start.offset.., in scalars: [Unicode.Scalar]) -> Range { var lower = range.lowerBound while lower > 0, scalars[lower - 1] == " " || scalars[lower - 1] == "\t" { lower -= 1 } guard lower == 0 || scalars[lower - 1] == "\n" else { return range } var upper = range.upperBound while upper < scalars.count, scalars[upper] == " " || scalars[upper] == "\t" || scalars[upper] == "\r" { upper += 1 } if upper == scalars.count { return lower.. 0, scalars[assignmentStart - 1] != "\n" { assignmentStart -= 1 } try replace([(removalRange(assignmentStart.. 0 { preceding = comma(in: scalars, from: ordered[index - 1].range.end.offset, to: key.start.offset) guard preceding != nil else { throw SettingsFailure.conflict } } else { preceding = nil } var start = preceding.map { $0 + 1 } ?? container.range.start.offset + 1 while start < key.start.offset { if scalars[start] == "#" { while start < key.start.offset, scalars[start] != "\n" { start += 1 } } else if [" ", "\t", "\r", "\n"].contains(scalars[start]) { start += 1 } else { break } } var edits = [(start.. [TOMLNode] { entries.values.flatMap { node in // Dotted keys have virtual table nodes, not a single editable assignment. if case .table(let children) = node.value, scalars[node.range.start.offset] != "{" { return inlineAssignments(children, scalars: scalars) } return [node] } } private static func removeMatcher(_ key: String, rule index: Int, from document: inout TOMLDocument) throws { let path: [TOMLPathComponent] = [.key("float-rules"), .index(index)] guard let rule = document.node(at: path), let value = rule[key], let keyRange = value.keyRange else { throw unsupportedRules } let scalars = Array(document.source.unicodeScalars) var edits = [(keyRange.start.offset.., String)], in document: inout TOMLDocument) throws { var scalars = Array(document.source.unicodeScalars) for (range, replacement) in edits.sorted(by: { $0.0.lowerBound > $1.0.lowerBound }) { scalars.replaceSubrange(range, with: replacement.unicodeScalars) } document = try TOMLDocument(parsing: String(String.UnicodeScalarView(scalars))) } private static func hasComma(in scalars: [Unicode.Scalar], from start: Int, to end: Int) -> Bool { comma(in: scalars, from: start, to: end) != nil } private static func comma(in scalars: [Unicode.Scalar], from start: Int, to end: Int) -> Int? { var comment = false for index in start..