Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729public import Foundationimport Observationpublic import ParcelConfigpublic import ParcelCorepublic import ParcelEngine
public enum SettingsLayoutField: String, CaseIterable, Sendable { case defaultLayout = "default" case portraitLayout = "portrait-layout" case ratio case innerGap = "gaps.inner" case outerGap = "gaps.outer" case reservedTop = "reserved.top" case reservedRight = "reserved.right" case reservedBottom = "reserved.bottom" case reservedLeft = "reserved.left" case windowCap = "window-cap" case whenFull = "when-full"}
public enum SettingsMotionField: String, CaseIterable, Sendable { case enabled, level, speed, transitions, sound, highlight case highlightWidth = "highlight-width" case focusBorder = "focus-border" case menuBarIcon = "menu-bar-icon"}
public enum SettingsAppearanceField: String, CaseIterable, Sendable { case palette, mode case stackControls = "stack-controls" case borderOpacity = "border-opacity" case borderRadius = "border-radius"}
public enum SettingsMouseField: String, CaseIterable, Sendable { case enabled case swapModifiers = "swap-modifiers" case stackModifiers = "stack-modifiers" case moveModifiers = "move-modifiers" case resizeModifiers = "resize-modifiers" case edgeSnapping = "edge-snapping" case dropToRatio = "drop-to-ratio" case focusFollowsMouse = "focus-follows-mouse" case focusDelay = "focus-delay" case typingCooldown = "typing-cooldown"}
public enum SettingsMemoryField: String, CaseIterable, Sendable { case enabled case restoreWindows = "restore-windows"}
public enum SettingsHoverBarField: String, CaseIterable, Sendable { case enabled, delay}
public enum SettingsFocusModeField: String, CaseIterable, Sendable { case noPeekLevel = "no-peek-level" case noPeekBlur = "no-peek-blur" case cleanSpaceColor = "clean-space-color"}
public enum SettingsField: Sendable { case launchAtLogin case prefix case shortcutsEnabled case collectActivity case whenDisplayFull case announceLayoutChanges case disabledDefaultFloatApps case layout(SettingsLayoutField, display: UUID? = nil) case motion(SettingsMotionField) case appearance(SettingsAppearanceField) case focusModes(SettingsFocusModeField) case mouse(SettingsMouseField) case hoverBar(SettingsHoverBarField) case memory(SettingsMemoryField)
func path(in document: TOMLDocument) -> [String] { switch self { case .launchAtLogin: return ["general", "launch-at-login"] case .prefix: return ["general", "prefix"] case .shortcutsEnabled: return ["general", "shortcuts-enabled"] case .collectActivity: return ["general", "collect-activity"] case .whenDisplayFull: return ["general", "when-display-full"] case .announceLayoutChanges: return ["accessibility", "announce-layout-changes"] case .disabledDefaultFloatApps: return ["classification", "disabled-default-float-apps"] case .motion(let field): return ["motion", field.rawValue] case .appearance(let field): return ["appearance", field.rawValue] case .focusModes(let field): return ["focus-modes", field.rawValue] case .mouse(let field): return ["mouse", field.rawValue] case .hoverBar(let field): return ["hover-bar", field.rawValue] case .memory(let field): return ["memory", field.rawValue] case .layout(let field, let display): var path = ["layout"] if let display { let existing: String? if case .table(let entries) = document.node(forKey: ["layout", "displays"])?.value { existing = entries.keys.first { UUID(uuidString: $0) == display } } else { existing = nil } path += ["displays", existing ?? display.uuidString] } return path + field.rawValue.split(separator: ".").map(String.init) } }}
public struct SettingsFailure: Error, LocalizedError, Equatable, Sendable { public let message: String public var errorDescription: String? { message }
init(_ message: String) { self.message = message }
init(error: any Error) { if let failure = error as? SettingsFailure { self = failure } else if let diagnostic = error as? ConfigDiagnostic { self.init(diagnostic.description) } else { self.init(error.localizedDescription) } }
static var conflict: Self { Self(SettingsText.string("The configuration changed outside Settings. Review the latest values and try again.")) }}
@MainActor @Observablepublic final class SettingsModel { public let store: ConfigStore public var minimums: SettingsMinimumsModel? public var feedback: FeedbackModel? public var onWhatsNewRequested: (@MainActor () -> Void)? public var onSupportRequested: (@MainActor (SupportKind) -> Void)? public var language = LanguagePreferences() public var workspaceMemory: WorkspaceMemorySettingsModel? public var appIcons: AppIconPreferences? public var setups: SetupCoordinator? public var activity: ActivityCollector? let motionSpeedSave = MotionSpeedSave() var pendingWindowRuleUndo: WindowRuleUndo? var pendingReservedEdgesUndo: ReservedEdgesUndo? private(set) var reservedEdgeOverrideDisplays: Set<UUID> = [] var sourceDocument: TOMLDocument? { latest?.lastGoodDocument } @ObservationIgnored let reservedEdgePreview = ReservedEdgePreview() public private(set) var configuration = ParcelConfiguration.defaults public private(set) var diagnostics: [ConfigDiagnostic] = [] public private(set) var isStarted = false public private(set) var isSaving = false public private(set) var runningLayouts: [DisplayID: ConfigLayout] = [:] public private(set) var runningMainSizeRatios: [DisplayID: Double] = [:] public private(set) var runningWorkspaces: [DisplayID: WorkspaceKey] = [:] public private(set) var activeDisplay: DisplayID? public var error: SettingsFailure? { editingError ?? loadingError } public private(set) var shortcutWarnings: [SettingsShortcutWarning] = [] private var explicitShortcutOverrides: Set<ConfigCommand> = [] private var hasExplicitShortcutPrefix = false private(set) var modeShortcutNoticeDetails: [ModeShortcutNotice] = [] public var modeShortcutNotices: [String] { modeShortcutNoticeDetails.map(\.display) } public private(set) var shortcutCheckLimitations: [String] = [] private(set) var checkedShortcutEnvironment = SettingsShortcutEnvironment() public var onShortcutNoticeChanged: (@MainActor () -> Void)? @ObservationIgnored public var onRecordedShortcut: (@MainActor (KeyChord) -> Void)?
public func recordRegisteredShortcut(_ chord: KeyChord) -> Bool { guard let capture = onRecordedShortcut else { return false } onRecordedShortcut = nil capture(chord) return true } public var shortcutNotice: String? { if !shortcutWarnings.isEmpty || !modeShortcutNotices.isEmpty { return SettingsText.string( "Some shortcuts are also used by macOS or an app. Review alternatives in Settings → Shortcuts.") } // Unchecked sources stay inline; only actual conflicts need a notice. return nil }
@ObservationIgnored private let editor: SettingsFileEditor @ObservationIgnored private let shortcutChecker: SettingsShortcutChecker? @ObservationIgnored private let commands: (any UICommandSink)? @ObservationIgnored private var shortcutCheckTask: Task<Void, Never>? @ObservationIgnored private var shortcutCheckRevision = 0 @ObservationIgnored private var latest: ConfigSnapshot? @ObservationIgnored private var updatesTask: Task<Void, Never>? @ObservationIgnored private var ownsWatcher = false @ObservationIgnored private var locked = false @ObservationIgnored private var waiters: [CheckedContinuation<Void, Never>] = [] private var editingError: SettingsFailure? private var loadingError: SettingsFailure?
public init( store: ConfigStore, shortcutChecker: SettingsShortcutChecker? = nil, commands: (any UICommandSink)? = nil ) { self.store = store self.shortcutChecker = shortcutChecker self.commands = commands self.editor = SettingsFileEditor(fileURL: store.fileURL) }
public var canSendFocusModes: Bool { commands != nil }
public func sendFocusMode(_ command: ConfigCommand) async throws { guard [.toggleFocus, .toggleNoPeek, .toggleCleanSpace].contains(command) else { throw SettingsFailure(SettingsText.string("Choose a Focus, No peek, or Clean Space command.")) } guard let commands else { throw SettingsFailure(SettingsText.string("Start tiling before changing focus modes.")) } try await commands.send(command) }
deinit { updatesTask?.cancel() shortcutCheckTask?.cancel() }
public func updateRunningLayouts( _ layouts: [DisplayID: ConfigLayout], activeDisplay: DisplayID?, mainSizeRatios: [DisplayID: Double] = [:], workspaces: [DisplayID: WorkspaceKey] = [:] ) { precondition(mainSizeRatios.values.allSatisfy { $0.isFinite && (0...1).contains($0) }) precondition(workspaces.allSatisfy { $0.key == $0.value.display }) runningLayouts = layouts runningMainSizeRatios = mainSizeRatios.filter { layouts[$0.key] != nil } runningWorkspaces = workspaces.filter { layouts[$0.key] != nil } self.activeDisplay = activeDisplay }
public func runningMainSizeRatio(for display: UUID?) -> Double? { if let display { return runningMainSizeRatios.first { UUID(uuidString: $0.key.rawValue) == display }?.value } guard let activeDisplay else { return nil } return runningMainSizeRatios[activeDisplay] }
public func runningLayout(for display: UUID?) -> ConfigLayout? { if let display { return runningLayouts.first { UUID(uuidString: $0.key.rawValue) == display }?.value } guard let activeDisplay else { return nil } return runningLayouts[activeDisplay] }
public func shortcutEnvironment() async throws -> SettingsShortcutEnvironment { guard let shortcutChecker else { return SettingsShortcutEnvironment() } return try await shortcutChecker.environment() }
func waitForShortcutCheck() async { await shortcutCheckTask?.value }
public func refreshShortcutWarnings() { shortcutCheckTask?.cancel() shortcutCheckRevision += 1 let revision = shortcutCheckRevision let configuration = configuration let bindings = configuration.keybindings shortcutCheckTask = Task { [weak self] in guard let self else { return } do { let environment = try await self.shortcutEnvironment() guard !Task.isCancelled, revision == self.shortcutCheckRevision else { return } self.checkedShortcutEnvironment = environment self.shortcutWarnings = SettingsShortcutChecker.warnings( bindings: bindings, environment: environment, additionalBindings: Array(configuration.defaultModeEntries.values)) self.modeShortcutNoticeDetails = SettingsShortcutChecker.modeNoticeDetails( configuration: configuration, environment: environment) self.shortcutCheckLimitations = environment.limitations } catch is CancellationError { return } catch { guard !Task.isCancelled, revision == self.shortcutCheckRevision else { return } self.shortcutWarnings = [] self.modeShortcutNoticeDetails = [] self.shortcutCheckLimitations = [ SettingsText.string("Shortcut conflicts could not be checked: \(error.localizedDescription)") ] self.checkedShortcutEnvironment = SettingsShortcutEnvironment( limitations: self.shortcutCheckLimitations) } self.onShortcutNoticeChanged?() } }
public func start() async { await acquire() defer { release() } guard !isStarted else { return } receive(await store.reload()) do { ownsWatcher = await !store.isWatching try await store.startWatching() let updates = await store.updates() isStarted = true updatesTask = Task { [weak self, store] in for await _ in updates { guard !Task.isCancelled else { break } let snapshot = await store.snapshot guard !Task.isCancelled else { break } self?.receive(snapshot) } } } catch { loadingError = SettingsFailure(error: error) } }
func settingsWindowDidClose() { motionSpeedSave.cancel() }
public func stop() async { motionSpeedSave.cancel() await acquire() defer { release() } let task = updatesTask updatesTask = nil task?.cancel() await task?.value if ownsWatcher { await store.stopWatching() } ownsWatcher = false isStarted = false reservedEdgePreview.stop() onRecordedShortcut = nil shortcutCheckTask?.cancel() shortcutCheckTask = nil shortcutCheckRevision += 1 }
public func reload() async { await acquire() defer { release() } receive(await store.reload()) editingError = nil refreshShortcutWarnings() if isStarted, await !store.isWatching { do { try await store.startWatching() } catch { loadingError = SettingsFailure(error: error) } } }
public func setValue(_ value: TOMLValue, for field: SettingsField) async throws { try await edit(.value(field, value)) }
public func setValues(_ values: [(SettingsField, TOMLValue)]) async throws { try await edit(.values(values)) }
public func setMainSizePreset(_ command: ConfigCommand, for display: UUID? = nil) async throws { do { let unavailable = SettingsFailure(SettingsText.string("This control isn’t available in the current state.")) guard let preset = MainSizePreset.allCases.first(where: { $0.command == command }), let ratio = preset.ratio else { throw unavailable } if let reason = MainSizePreset.disabledReason(layout: runningLayout(for: display)) { throw SettingsFailure(reason) } guard runningLayout(for: display) != nil else { try await setValue(.float(ratio), for: .layout(.ratio, display: display)) return } let targetDisplay: DisplayID? = if let display { runningLayouts.keys.first { UUID(uuidString: $0.rawValue) == display } } else { activeDisplay } guard let targetDisplay, let workspace = runningWorkspaces[targetDisplay], let commands = commands as? any UIWorkspaceCommandSink else { throw unavailable } try await edit( .value(.layout(.ratio, display: display), .float(ratio)), beforeCommit: { try self.requireMainSizeWorkspace(workspace) }) try requireMainSizeWorkspace(workspace) // A saved preset may still differ from manually resized live windows. try await commands.send(command, in: workspace) editingError = nil } catch { if !(error is CancellationError) { report(error) } throw error } }
private func requireMainSizeWorkspace(_ workspace: WorkspaceKey) throws { guard runningWorkspaces[workspace.display] == workspace, runningLayouts[workspace.display] != .accordion else { throw SettingsFailure(SettingsText.string("This control isn’t available in the current state.")) } }
public func setAppearanceBorderRadius(_ radius: Double?) async throws { if let radius { try await setValue(.float(radius), for: .appearance(.borderRadius)) } else { try await edit(.removeAppearanceValues([SettingsAppearanceField.borderRadius.rawValue])) } }
public func resetAppearanceColors(_ roles: [AppearanceColorRole] = AppearanceColorRole.allCases) async throws { try await edit(.removeAppearanceValues(roles.map(\.rawValue))) }
public func setHoverPreferences(_ preferences: HoverBarConfiguration, onlyMissing: Bool = false) async throws { guard preferences.isValid else { throw SettingsFailure(SettingsText.string("Hover delay must be between 0.1 and 3 seconds.")) } try await edit(.hoverPreferences(preferences, onlyMissing: onlyMissing)) }
public func setShortcut(_ chord: KeyChord?, for command: ConfigCommand) async throws { try await edit(.shortcut(command, chord)) }
public func revertShortcut(for command: ConfigCommand) async throws { try await edit(.revertShortcuts([command], resetPrefix: false)) }
public func resetAllShortcuts() async throws { try await edit(.revertShortcuts(ConfigCommand.allCases, resetPrefix: true)) }
public func canRevertShortcut(for command: ConfigCommand) -> Bool { explicitShortcutOverrides.contains(command) }
public var canResetAllShortcuts: Bool { !explicitShortcutOverrides.isEmpty || hasExplicitShortcutPrefix }
public func shortcutStatus(for command: ConfigCommand) -> String? { if let displacement = configuration.inheritedShortcutDisplacements.first(where: { $0.command == command }) { let owner: String = switch displacement.binding { case .command(let command): command.settingsTitle case .enterMode(let name): SettingsText.string("Enter mode \(name)") case .exitMode: SettingsText.string("Exit mode") } return SettingsText.string("Unbound because \(owner) uses this key") } guard let chord = configuration.keybindings[command] else { return SettingsText.string("Not assigned") } guard configuration.general.shortcutsEnabled else { return SettingsText.string("Left to macOS") } return SettingsShortcutChecker.isLeftToMacOS(chord, environment: checkedShortcutEnvironment) ? SettingsText.string("Left to macOS") : nil }
public func setShortcut(text: String, for command: ConfigCommand) async throws { do { try await setShortcut(ShortcutRecorderParser.parse(text), for: command) } catch { editingError = SettingsFailure(error: error) throw error } }
public func addRule(_ rule: FloatRule) async throws { try await edit(.addRule(rule)) }
public func setRule(_ rule: FloatRule, at index: Int, replacing original: FloatRule) async throws { try await edit(.replaceRule(index: index, original: original, replacement: rule)) }
public func removeRule(at index: Int, matching original: FloatRule) async throws { try await edit(.removeRule(index: index, original: original)) }
func report(_ error: any Error) { editingError = SettingsFailure(error: error) }
func configurationFileForEditing() async throws -> URL { await acquire() defer { release() } isSaving = true defer { isSaving = false } do { try Task.checkCancellation() let url = try await editor.prepareForOpening() receive(await store.reload()) try Task.checkCancellation() editingError = nil return url } catch { guard !Task.isCancelled, !(error is CancellationError) else { throw CancellationError() } editingError = SettingsFailure(error: error) throw error } }
func edit( _ edit: SettingsEdit, didSave: (@MainActor (ParcelConfiguration, ParcelConfiguration) -> Void)? = nil ) async throws { try await self.edit(edit, beforeCommit: {}, didSave: didSave) }
func edit( _ edit: SettingsEdit, beforeCommit: @MainActor () throws -> Void, didSave: (@MainActor (ParcelConfiguration, ParcelConfiguration) -> Void)? = nil ) async throws { await acquire() defer { release() } do { try Task.checkCancellation() guard isStarted, let latest else { throw SettingsFailure(SettingsText.string("Open Settings before editing the configuration.")) } guard latest.loadState == .loaded || latest.loadState == .missingFileUsingDefaults else { throw loadingError ?? SettingsFailure(SettingsText.string("Fix the configuration file before saving changes.")) } guard latest.activeSource == .file(store.fileURL) || latest.activeSource == .defaults else { throw SettingsFailure.conflict } isSaving = true defer { isSaving = false } try beforeCommit() let before = configuration let source = try await editor.commit(edit, expectedSource: latest.lastGoodDocument?.source) // Published writes need readback before the next queued edit, even if cancellation arrived too late. let saved = await store.reload() receive(saved) try Task.checkCancellation() guard saved.loadState == .loaded, saved.lastGoodDocument?.source == source else { throw SettingsFailure.conflict } editingError = nil didSave?(before, configuration) } catch { guard !Task.isCancelled, !(error is CancellationError) else { throw CancellationError() } let snapshot = await store.reload() try Task.checkCancellation() receive(snapshot) editingError = SettingsFailure(error: error) throw error } }
private func receive(_ snapshot: ConfigSnapshot) { let changed = latest == nil || configuration.keybindings != snapshot.activeConfiguration.keybindings || configuration.defaultModeEntries != snapshot.activeConfiguration.defaultModeEntries || configuration.modes != snapshot.activeConfiguration.modes if latest?.lastGoodDocument?.source != snapshot.lastGoodDocument?.source { pendingWindowRuleUndo = nil if let undo = pendingReservedEdgesUndo { feedback?.dismiss(undo.noticeID) pendingReservedEdgesUndo = nil } } latest = snapshot explicitShortcutOverrides = Set( ConfigCommand.allCases.filter { snapshot.lastGoodDocument?.node(forKey: ["keybindings", $0.rawValue]) != nil }) if snapshot.lastGoodDocument?.node(forKey: ["keybindings", "pause-tiling"]) != nil { explicitShortcutOverrides.insert(.toggleAutomaticTiling) } hasExplicitShortcutPrefix = snapshot.lastGoodDocument?.node(forKey: ["general", "prefix"]) != nil configuration = snapshot.activeConfiguration reservedEdgeOverrideDisplays = Set( configuration.layout.displays.keys.filter { display in guard let document = snapshot.lastGoodDocument else { return false } return ReservedEdgeSettings.fields.contains { field in document.node(forKey: SettingsField.layout(field, display: display).path(in: document)) != nil } }) if !configuration.general.shortcutsEnabled { onRecordedShortcut = nil } if changed { refreshShortcutWarnings() } diagnostics = snapshot.diagnostics let failures = snapshot.diagnostics.filter { $0.severity == .error } loadingError = failures.isEmpty ? nil : SettingsFailure(failures.map(\.description).joined(separator: "\n")) }
private func acquire() async { if locked { await withCheckedContinuation { waiters.append($0) } } else { locked = true } }
private func release() { if waiters.isEmpty { locked = false } else { waiters.removeFirst().resume() } }}
actor SettingsFileEditor { let fileURL: URL
init(fileURL: URL) { self.fileURL = fileURL }
func prepareForOpening() throws -> URL { try Self.prepareForOpening(fileURL: fileURL) }
static func prepareForOpening(fileURL: URL, beforeCreate: () throws -> Void = {}) throws -> URL { try Task.checkCancellation() guard fileURL.isFileURL else { throw SettingsFailure(SettingsText.string("The configuration must be a local file.")) } let target = fileURL.resolvingSymlinksInPath() try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) var coordinationError: NSError? var result: Result<URL, any Error>? NSFileCoordinator().coordinate(writingItemAt: target, options: .forReplacing, error: &coordinationError) { url in result = Result { if try contents(at: url) == nil { try beforeCreate() try Task.checkCancellation() guard fileURL.resolvingSymlinksInPath() == target else { throw SettingsFailure.conflict } if try contents(at: url) == nil { do { try createAtomically(Data(ConfigStore.defaultFileContents.utf8), at: url) } catch let error as CocoaError where error.code == .fileWriteFileExists { // Another editor can publish the file before our exclusive link succeeds. guard try contents(at: url) != nil else { throw error } } } } guard fileURL.resolvingSymlinksInPath() == target else { throw SettingsFailure.conflict } return fileURL } } if let coordinationError { throw coordinationError } guard let result else { throw SettingsFailure(SettingsText.string("The configuration file could not be coordinated for saving.")) } return try result.get() }
func commit(_ edit: SettingsEdit, expectedSource: String?) throws -> String { try Self.commit(edit, fileURL: fileURL, expectedSource: expectedSource) }
static func commit( _ edit: SettingsEdit, fileURL: URL, expectedSource: String?, beforeWrite: () throws -> Void = {} ) throws -> String { try Task.checkCancellation() guard fileURL.isFileURL else { throw SettingsFailure(SettingsText.string("The configuration must be a local file.")) } let target = fileURL.resolvingSymlinksInPath() try FileManager.default.createDirectory( at: target.deletingLastPathComponent(), withIntermediateDirectories: true) var coordinationError: NSError? var result: Result<String, any Error>? NSFileCoordinator().coordinate(writingItemAt: target, options: .forReplacing, error: &coordinationError) { url in result = Result { let original = try contents(at: url) guard original == expectedSource.map({ Data($0.utf8) }) else { throw SettingsFailure.conflict } var document = try TOMLDocument(parsing: expectedSource ?? "") _ = try SettingsDocumentEditor.validate(document) try SettingsDocumentEditor.apply(edit, to: &document) _ = try SettingsDocumentEditor.validate(document) try beforeWrite() try Task.checkCancellation() guard fileURL.resolvingSymlinksInPath() == target, try contents(at: url) == original else { throw SettingsFailure.conflict } if document.source != expectedSource { let data = Data(document.source.utf8) if original == nil { try createAtomically(data, at: url) } else { try data.write(to: url, options: .atomic) } } return document.source } } if let coordinationError { throw coordinationError } guard let result else { throw SettingsFailure(SettingsText.string("The configuration file could not be coordinated for saving.")) } return try result.get() }
private static func createAtomically(_ data: Data, at url: URL) throws { let temporary = url.deletingLastPathComponent().appendingPathComponent(".parcel-\(UUID().uuidString).tmp") do { try data.write(to: temporary, options: .withoutOverwriting) // Linking publishes complete contents and fails if another editor created the destination. try FileManager.default.linkItem(at: temporary, to: url) } catch { let failure = error do { if FileManager.default.fileExists(atPath: temporary.path) { try FileManager.default.removeItem(at: temporary) } } catch { throw SettingsFailure( SettingsText.string( "Saving failed: \(failure.localizedDescription). Temporary file cleanup also failed: \(error.localizedDescription)." )) } throw failure } try FileManager.default.removeItem(at: temporary) }
private static func contents(at url: URL) throws -> Data? { do { let values = try url.resourceValues(forKeys: [.isRegularFileKey]) guard values.isRegularFile == true else { throw SettingsFailure(SettingsText.string("The configuration path is not a regular file.")) } return try Data(contentsOf: url) } catch let error as CocoaError where error.code == .fileReadNoSuchFile { return nil } }}