// The settings file: the PowerToys `MouseWithoutBorders` schema, the defaults // that go with it, and the store that loads, saves and watches it. // See docs/protocol.md §8 and README.md §Settings. // // The file is byte-compatible with the Windows one on purpose (README D3): same // envelope, same property names, same `{"value": …}` boxing, so a key and a // matrix can be copied between a Mac and a PC by copying the file. Properties we // do not implement are still round-tripped — the raw property dictionary is what // is stored and only the keys we understand are overwritten — so a shared file // never loses the Windows side's settings. // // Ported from src/settings-ui/Settings.UI.Library/MouseWithoutBordersProperties.cs // (165-206 defaults), MouseWithoutBordersSettings.cs (the envelope), // HotkeySettings.cs (121-136), App/Class/Setting.cs (197-207 file watch, // 479-511 MyKey, 1048-1083 MachineId). import Foundation /// Anything that can appear in the settings file. /// /// The settings file is edited by the PowerToys UI on Windows and by a text /// editor here, and it carries properties this port does not implement. Keeping /// the raw tree is what lets `Settings.save(to:)` write those back untouched. public enum JSONValue: Sendable, Equatable { /// JSON `null`. case null /// JSON `true` / `false`. case bool(Bool) /// A whole number. case int(Int) /// A number that is not whole. case double(Double) /// A string. case string(String) /// An array. case array([JSONValue]) /// An object. case object([String: JSONValue]) } extension JSONValue: Codable { public init(from decoder: any Decoder) throws { let container = try decoder.singleValueContainer() if container.decodeNil() { self = .null } else if let value = try? container.decode(Bool.self) { self = .bool(value) } else if let value = try? container.decode(Int.self) { self = .int(value) } else if let value = try? container.decode(Double.self) { self = .double(value) } else if let value = try? container.decode(String.self) { self = .string(value) } else if let value = try? container.decode([JSONValue].self) { self = .array(value) } else { self = .object(try container.decode([String: JSONValue].self)) } } public func encode(to encoder: any Encoder) throws { var container = encoder.singleValueContainer() switch self { case .null: try container.encodeNil() case .bool(let value): try container.encode(value) case .int(let value): try container.encode(value) case .double(let value): try container.encode(value) case .string(let value): try container.encode(value) case .array(let value): try container.encode(value) case .object(let value): try container.encode(value) } } /// The `{"value": …}` box PowerToys wraps every scalar property in. static func boxed(_ inner: JSONValue) -> JSONValue { .object(["value": inner]) } } /// Why a settings file could not be used. public enum SettingsError: Error, Equatable { /// The file exists but is not the PowerToys settings envelope. case malformed(String) } /// The `settings.json` contents, in the PowerToys schema. /// /// Every accessor reads and writes one property of the `properties` object; /// properties this port does not know are carried along unchanged. public struct Settings: Sendable, Equatable, Codable { /// The `name` field every PowerToys module settings file carries. public static let schemaName = "MouseWithoutBorders" /// The `version` field (`MouseWithoutBordersSettings.cs:33`). public static let schemaVersion = "1.1" private var name: String private var version: String private var properties: [String: JSONValue] private enum CodingKeys: String, CodingKey { case name, version, properties } /// A fresh settings object with the PowerToys defaults. public init() { name = Settings.schemaName version = Settings.schemaVersion properties = Settings.defaultProperties } public init(from decoder: any Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) name = (try? container.decode(String.self, forKey: .name)) ?? Settings.schemaName version = (try? container.decode(String.self, forKey: .version)) ?? Settings.schemaVersion let decoded = try container.decode([String: JSONValue].self, forKey: .properties) properties = Settings.defaultProperties.merging(decoded) { _, fromFile in fromFile } } public func encode(to encoder: any Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(name, forKey: .name) try container.encode(version, forKey: .version) try container.encode(properties, forKey: .properties) } // MARK: - Defaults (`MouseWithoutBordersProperties.cs:165-206`) /// Every property PowerToys writes, with its constructor default. static let defaultProperties: [String: JSONValue] = [ "SecurityKey": .boxed(.string("")), "UseService": .boxed(.bool(false)), "ShowOriginalUI": .boxed(.bool(false)), "WrapMouse": .boxed(.bool(true)), "ShareClipboard": .boxed(.bool(true)), "TransferFile": .boxed(.bool(true)), "HideMouseAtScreenEdge": .boxed(.bool(true)), "DrawMouseCursor": .boxed(.bool(true)), "ValidateRemoteMachineIP": .boxed(.bool(false)), "SameSubnetOnly": .boxed(.bool(false)), "BlockScreenSaverOnOtherMachines": .boxed(.bool(true)), "MoveMouseRelatively": .boxed(.bool(false)), "BlockMouseAtScreenCorners": .boxed(.bool(false)), "ShowClipboardAndNetworkStatusMessages": .boxed(.bool(false)), "MachineMatrixString": .array([]), "MachinePool": .boxed(.string(":,:,:,:")), "MatrixOneRow": .boxed(.bool(true)), "EasyMouse": .boxed(.int(1)), "DisableEasyMouseWhenForegroundWindowIsFullscreen": .boxed(.bool(true)), "EasyMouseFullscreenSwitchBlockExcludedApps": .boxed(.array([])), "MachineID": .boxed(.int(0)), "LastX": .boxed(.int(0)), "LastY": .boxed(.int(0)), "PackageID": .boxed(.int(0)), "FirstRun": .boxed(.bool(false)), "HotKeySwitchMachine": .boxed(.int(0x70)), "ToggleEasyMouseShortcut": HotkeyJSON.encode(HotkeyConfig().toggleEasyMouse), "LockMachineShortcut": HotkeyJSON.encode(HotkeyConfig().lock), "ReconnectShortcut": HotkeyJSON.encode(HotkeyConfig().reconnect), "Switch2AllPCShortcut": HotkeyJSON.encode(HotkeyConfig().switchToAll), "TCPPort": .boxed(.int(15100)), "DrawMouseEx": .boxed(.bool(true)), "Name2IP": .boxed(.string("")), "FirstCtrlShiftS": .boxed(.bool(false)), "DeviceID": .boxed(.string("")), ] // MARK: - Properties /// `SecurityKey`: the shared secret the whole matrix is keyed by (§2). public var securityKey: String { get { string("SecurityKey") } set { setBoxed("SecurityKey", .string(newValue)) } } /// `WrapMouse` (`MatrixCircle`): the ends of the matrix join up. public var wrapMouse: Bool { get { bool("WrapMouse") } set { setBoxed("WrapMouse", .bool(newValue)) } } /// `ShareClipboard`: clipboard contents follow the control. public var shareClipboard: Bool { get { bool("ShareClipboard") } set { setBoxed("ShareClipboard", .bool(newValue)) } } /// `TransferFile`: files may travel on the bulk channel. public var transferFile: Bool { get { bool("TransferFile") } set { setBoxed("TransferFile", .bool(newValue)) } } /// `HideMouseAtScreenEdge`: park the pointer in the menu bar rather than the /// middle of the screen while a peer has control. public var hideMouseAtScreenEdge: Bool { get { bool("HideMouseAtScreenEdge") } set { setBoxed("HideMouseAtScreenEdge", .bool(newValue)) } } /// `DrawMouseCursor`: draw an arrow where the remote pointer is while a peer /// is driving this Mac (`CustomCursor.cs:68-146`). `DrawMouseEx`, which /// selects the richer Windows drawing path, is accepted and ignored. public var drawMouseCursor: Bool { get { bool("DrawMouseCursor") } set { setBoxed("DrawMouseCursor", .bool(newValue)) } } /// `ValidateRemoteMachineIP`: only accept peers whose address resolves back /// to their name. public var validateRemoteMachineIP: Bool { get { bool("ValidateRemoteMachineIP") } set { setBoxed("ValidateRemoteMachineIP", .bool(newValue)) } } /// `SameSubnetOnly`: only dial and accept addresses on our own subnet. public var sameSubnetOnly: Bool { get { bool("SameSubnetOnly") } set { setBoxed("SameSubnetOnly", .bool(newValue)) } } /// `BlockScreenSaverOnOtherMachines`: beat every 60 s and send `Awake` when /// the user has been active (§3.3). public var blockScreenSaverOnOtherMachines: Bool { get { bool("BlockScreenSaverOnOtherMachines") } set { setBoxed("BlockScreenSaverOnOtherMachines", .bool(newValue)) } } /// `MoveMouseRelatively`: send deltas rather than absolute positions (§4.4). public var moveMouseRelatively: Bool { get { bool("MoveMouseRelatively") } set { setBoxed("MoveMouseRelatively", .bool(newValue)) } } /// `BlockMouseAtScreenCorners`: no edge switch within 100 px of a corner. public var blockMouseAtScreenCorners: Bool { get { bool("BlockMouseAtScreenCorners") } set { setBoxed("BlockMouseAtScreenCorners", .bool(newValue)) } } /// `ShowClipboardAndNetworkStatusMessages`: chatty notifications. public var showClipboardAndNetworkStatusMessages: Bool { get { bool("ShowClipboardAndNetworkStatusMessages") } set { setBoxed("ShowClipboardAndNetworkStatusMessages", .bool(newValue)) } } /// `DisableEasyMouseWhenForegroundWindowIsFullscreen`. public var disableEasyMouseWhenFullscreen: Bool { get { bool("DisableEasyMouseWhenForegroundWindowIsFullscreen") } set { setBoxed("DisableEasyMouseWhenForegroundWindowIsFullscreen", .bool(newValue)) } } /// `EasyMouseFullscreenSwitchBlockExcludedApps`: apps the fullscreen rule /// does not apply to. public var easyMouseFullscreenExcludedApps: [String] { get { strings(boxedValue("EasyMouseFullscreenSwitchBlockExcludedApps")) } set { setBoxed("EasyMouseFullscreenSwitchBlockExcludedApps", .array(newValue.map { .string($0) })) } } /// `MatrixOneRow`: four machines side by side rather than two rows of two. public var matrixOneRow: Bool { get { bool("MatrixOneRow") } set { setBoxed("MatrixOneRow", .bool(newValue)) } } /// `EasyMouse`: whether sliding off an edge switches machines. public var easyMouse: EasyMouseMode { get { EasyMouseMode(rawValue: int("EasyMouse")) ?? .enable } set { setBoxed("EasyMouse", .int(newValue.rawValue)) } } /// `MachineMatrixString`: the four slot names, as a list. public var machineMatrixNames: [String] { get { strings(rawValue("MachineMatrixString")) } set { properties["MachineMatrixString"] = .array(newValue.map { .string($0) }) } } /// `MachinePool`: `"Name:Id,…"` for every machine we have ever met. public var machinePoolString: String { get { string("MachinePool") } set { setBoxed("MachinePool", .string(newValue)) } } /// `MachineID`: this machine's id on the wire (§1.5). public var machineID: Int32 { get { Int32(truncatingIfNeeded: int("MachineID")) } set { setBoxed("MachineID", .int(Int(newValue))) } } /// `LastX`: the pointer's last x, remembered across restarts. public var lastX: Int32 { get { Int32(truncatingIfNeeded: int("LastX")) } set { setBoxed("LastX", .int(Int(newValue))) } } /// `LastY`: the pointer's last y. public var lastY: Int32 { get { Int32(truncatingIfNeeded: int("LastY")) } set { setBoxed("LastY", .int(Int(newValue))) } } /// `PackageID`: the outgoing packet `Id` counter, so ids keep rising across /// restarts (`Common.cs:906`). public var packageID: Int32 { get { Int32(truncatingIfNeeded: int("PackageID")) } set { setBoxed("PackageID", .int(Int(newValue))) } } /// `TCPPort`: the data port; the control channel listens on `port + 1`. public var tcpPort: UInt16 { get { UInt16(truncatingIfNeeded: int("TCPPort")) } set { setBoxed("TCPPort", .int(Int(newValue))) } } /// `Name2IP`: `"name address"` lines for machines DNS cannot resolve (§7). public var name2IP: String { get { string("Name2IP") } set { setBoxed("Name2IP", .string(newValue)) } } /// `DeviceID`: a stable per-install UUID; telemetry on Windows, identity /// only here. public var deviceID: String { get { string("DeviceID") } set { setBoxed("DeviceID", .string(newValue)) } } /// `HotKeySwitchMachine`: the first of four consecutive virtual-key codes, /// ⌃⌥F1..F4 by default. public var hotKeySwitchMachine: Int32 { get { Int32(truncatingIfNeeded: int("HotKeySwitchMachine")) } set { setBoxed("HotKeySwitchMachine", .int(Int(newValue))) } } /// `ToggleEasyMouseShortcut`, default ⌘⌃⌥E. public var toggleEasyMouseShortcut: Hotkey { get { hotkey("ToggleEasyMouseShortcut", default: HotkeyConfig().toggleEasyMouse) } set { properties["ToggleEasyMouseShortcut"] = HotkeyJSON.encode(newValue) } } /// `LockMachineShortcut`, default ⌘⌃⌥L. public var lockMachineShortcut: Hotkey { get { hotkey("LockMachineShortcut", default: HotkeyConfig().lock) } set { properties["LockMachineShortcut"] = HotkeyJSON.encode(newValue) } } /// `ReconnectShortcut`, default ⌘⌃⌥R. public var reconnectShortcut: Hotkey { get { hotkey("ReconnectShortcut", default: HotkeyConfig().reconnect) } set { properties["ReconnectShortcut"] = HotkeyJSON.encode(newValue) } } /// `Switch2AllPCShortcut`, disabled by default. public var switch2AllPCShortcut: Hotkey { get { hotkey("Switch2AllPCShortcut", default: HotkeyConfig().switchToAll) } set { properties["Switch2AllPCShortcut"] = HotkeyJSON.encode(newValue) } } // MARK: - Derived views /// The matrix these settings describe, with its two layout flags. public var matrix: Matrix { get { Matrix(names: machineMatrixNames, oneRow: matrixOneRow, wrap: wrapMouse) } set { machineMatrixNames = newValue.names matrixOneRow = newValue.oneRow wrapMouse = newValue.wrap } } /// The machine pool these settings describe. `now` is the clock the pool's /// timestamps are measured on — `MachinePool` has no clock of its own. public func pool(now: TimeInterval) -> MachinePool { MachinePool(string: machinePoolString, now: now) } /// Writes a pool back as `MachinePool`. public mutating func setPool(_ pool: MachinePool) { machinePoolString = pool.string } /// The five hotkeys as the tap wants them (contracts C4). public var hotkeys: HotkeyConfig { HotkeyConfig( switchMachineVK: hotKeySwitchMachine, lock: lockMachineShortcut, reconnect: reconnectShortcut, toggleEasyMouse: toggleEasyMouseShortcut, switchToAll: switch2AllPCShortcut) } /// Generates the three identities Windows generates lazily on first use: /// the security key (`Setting.cs:479-495`), the machine id /// (`Setting.cs:1048-1070`, `Random.Next()` so non-negative) and the device /// id. Returns whether anything changed, so the caller knows to save. @discardableResult public mutating func generateMissingIdentities() -> Bool { var changed = false if !SecurityKey.isValid(securityKey) { securityKey = SecurityKey.random() changed = true } if machineID == 0 { machineID = Int32.random(in: 1...Int32.max) changed = true } if deviceID.isEmpty { deviceID = UUID().uuidString changed = true } return changed } // MARK: - Files /// `~/Library/Application Support/mwb-mac/settings.json` (README D3). public static func defaultURL() -> URL { let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask) let base = support.first ?? URL(fileURLWithPath: NSHomeDirectory()) return base.appendingPathComponent("mwb-mac", isDirectory: true) .appendingPathComponent("settings.json") } /// Reads and parses the file. Throws if it cannot be read or is not the /// PowerToys envelope — never silently falls back to defaults, because that /// would replace the user's security key and matrix with fresh ones. public static func load(from url: URL) throws -> Settings { let data = try Data(contentsOf: url) do { return try JSONDecoder().decode(Settings.self, from: data) } catch { throw SettingsError.malformed("\(url.lastPathComponent): \(error)") } } /// Writes the file atomically with mode 0600, creating the directory. public func save(to url: URL) throws { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys] let data = try encoder.encode(self) let directory = url.deletingLastPathComponent() try FileManager.default.createDirectory( at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) let temp = directory.appendingPathComponent(".\(url.lastPathComponent).new") try data.write(to: temp, options: .atomic) try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: temp.path) let written: URL if FileManager.default.fileExists(atPath: url.path) { // `.usingNewMetadataOnly`: without it `replaceItemAt` copies the // *original* file's metadata — permissions included — onto the // replacement, so a settings file that arrived from somewhere else // (README D3 makes copying `settings.json` between machines a // supported way to share the key and the matrix) would keep its // permissive mode forever, and this file holds `SecurityKey` in the // clear. written = try FileManager.default.replaceItemAt( url, withItemAt: temp, backupItemName: nil, options: .usingNewMetadataOnly) ?? url } else { try FileManager.default.moveItem(at: temp, to: url) written = url } // Belt and braces: whichever path got us here, the file on disk is 0600 // before this function returns, regardless of what was there before. try FileManager.default.setAttributes( [.posixPermissions: 0o600], ofItemAtPath: written.path) } // MARK: - Typed access to the raw tree private func rawValue(_ key: String) -> JSONValue? { properties[key] ?? Settings.defaultProperties[key] } /// The inside of a `{"value": …}` box, falling back to the default when the /// file holds something of the wrong shape. private func boxedValue(_ key: String) -> JSONValue? { if case .object(let fields) = properties[key], let inner = fields["value"] { return inner } if case .object(let fields) = Settings.defaultProperties[key] { return fields["value"] } return nil } private mutating func setBoxed(_ key: String, _ inner: JSONValue) { properties[key] = .boxed(inner) } private func bool(_ key: String) -> Bool { if case .bool(let value) = boxedValue(key) { return value } return false } private func int(_ key: String) -> Int { switch boxedValue(key) { case .int(let value): return value case .double(let value): return Int(value) default: return 0 } } private func string(_ key: String) -> String { if case .string(let value) = boxedValue(key) { return value } return "" } private func strings(_ value: JSONValue?) -> [String] { guard case .array(let items) = value else { return [] } return items.compactMap { if case .string(let s) = $0 { return s } else { return nil } } } private func hotkey(_ key: String, default fallback: Hotkey) -> Hotkey { HotkeyJSON.decode(rawValue(key)) ?? fallback } } /// The `HotkeySettings` JSON shape (`HotkeySettings.cs:121-136`): lower-case /// `win`/`ctrl`/`alt`/`shift`/`code`, plus the `key` field FancyZones needs and /// PowerToys always writes. enum HotkeyJSON { static func encode(_ hotkey: Hotkey) -> JSONValue { .object([ "win": .bool(hotkey.command), "ctrl": .bool(hotkey.control), "alt": .bool(hotkey.option), "shift": .bool(hotkey.shift), "code": .int(Int(hotkey.vk)), "key": .string(""), ]) } static func decode(_ value: JSONValue?) -> Hotkey? { guard case .object(let fields) = value else { return nil } func flag(_ name: String) -> Bool { if case .bool(let on) = fields[name] { return on } return false } guard case .int(let code) = fields["code"] else { return nil } return Hotkey( vk: Int32(truncatingIfNeeded: code), command: flag("win"), control: flag("ctrl"), option: flag("alt"), shift: flag("shift")) } } /// The settings file as a live object: the current value, edits that persist, /// and a watcher that notices the file changing underneath us. /// /// `@unchecked Sendable`: every stored property is guarded by `lock`, and the /// watcher's callback is `@Sendable`. public final class SettingsStore: @unchecked Sendable { private let url: URL private let lock = NSLock() private var settings: Settings private var watcher: (any DispatchSourceFileSystemObject)? private var changeHandler: (@Sendable (Settings) -> Void)? /// Loads the file, creating it with fresh identities if it is not there. /// /// Throws when the file exists but cannot be read or parsed: a corrupt file /// must stop the app, not be replaced by defaults. public init(url: URL = Settings.defaultURL()) throws { self.url = url if FileManager.default.fileExists(atPath: url.path) { settings = try Settings.load(from: url) if settings.generateMissingIdentities() { try settings.save(to: url) } } else { var fresh = Settings() fresh.generateMissingIdentities() try fresh.save(to: url) settings = fresh } } /// Where the file lives. public var fileURL: URL { url } /// The settings as they stand. public var current: Settings { lock.lock() defer { lock.unlock() } return settings } /// Edits and saves in one step. The edited value is published immediately; /// a write failure is thrown after the in-memory value has been updated, so /// a read-only disk does not desynchronise the running app. public func update(_ body: (inout Settings) -> Void) throws { lock.lock() var edited = settings body(&edited) let changed = edited != settings settings = edited lock.unlock() guard changed else { return } try edited.save(to: url) } /// Called after the file changed on disk and the new contents were loaded — /// the PowerToys settings UI writing over it, or the user editing it by hand /// (`Setting.cs:197-207`). Never called for our own `update(_:)`. public func onExternalChange(_ handler: @escaping @Sendable (Settings) -> Void) { lock.lock() changeHandler = handler lock.unlock() } /// Starts watching the file. Idempotent. public func startWatching() { lock.lock() let alreadyWatching = watcher != nil lock.unlock() guard !alreadyWatching else { return } installWatcher() } /// Stops watching. Idempotent. public func stopWatching() { lock.lock() let source = watcher watcher = nil lock.unlock() source?.cancel() } /// One watcher generation: a settings file replaced by `save(to:)` — ours or /// the PowerToys UI's — is a *new* vnode, so the source has to be torn down /// and re-armed on the new file rather than reused. private func installWatcher() { let descriptor = open(url.path, O_EVTONLY) guard descriptor >= 0 else { return } let queue = DispatchQueue(label: "com.mwb-mac.settings-watch", qos: .utility) let source = DispatchSource.makeFileSystemObjectSource( fileDescriptor: descriptor, eventMask: [.write, .rename, .delete, .extend], queue: queue) source.setEventHandler { [weak self] in guard let self else { return } self.stopWatching() self.reloadAfterExternalChange() self.installWatcher() } source.setCancelHandler { close(descriptor) } lock.lock() watcher = source lock.unlock() source.resume() } private func reloadAfterExternalChange() { guard let loaded = try? Settings.load(from: url) else { return } lock.lock() let changed = loaded != settings if changed { settings = loaded } let handler = changeHandler lock.unlock() if changed { handler?(loaded) } } }