diff --git a/Sources/MWBCore/Settings.swift b/Sources/MWBCore/Settings.swift new file mode 100644 index 0000000..93a8c62 --- /dev/null +++ b/Sources/MWBCore/Settings.swift @@ -0,0 +1,628 @@ +// 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)) } + } + + /// `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) + if FileManager.default.fileExists(atPath: url.path) { + _ = try FileManager.default.replaceItemAt(url, withItemAt: temp) + } else { + try FileManager.default.moveItem(at: temp, to: url) + } + } + + // 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) } + } +} diff --git a/Sources/MWBMac/Log.swift b/Sources/MWBMac/Log.swift new file mode 100644 index 0000000..aad739f --- /dev/null +++ b/Sources/MWBMac/Log.swift @@ -0,0 +1,163 @@ +// Logging: `os.Logger` for Console.app plus a small rotating file the user can +// attach to a bug report. +// +// There is no Windows counterpart worth porting — `Class/Logger.cs` writes a +// ring buffer, a telemetry event and, in debug builds, every keystroke. We log +// far less on purpose: CLAUDE.md invariant 2 forbids the security key and +// decrypted keystrokes at any level, so nothing here ever takes a `KeyboardData` +// or a key string. Peer names, socket statuses and recovery reasons are fine. + +import Foundation +import os + +/// A named logger. One per subsystem area; the categories are the ones that +/// show up in Console.app. +public struct Log: Sendable { + /// The Engine: switching, packets dispatched, recovery. + public static let engine = Log(category: "engine") + /// The process: startup, permissions, quit. + public static let app = Log(category: "app") + /// Settings loading and saving. + public static let settings = Log(category: "settings") + + private let category: String + private let logger: Logger + + /// A logger for one category. + public init(category: String) { + self.category = category + logger = Logger(subsystem: Log.subsystem, category: category) + } + + /// Something worth seeing in a bug report. + public func info(_ message: String) { + logger.info("\(message, privacy: .public)") + LogFile.shared.append(level: "INFO", category: category, message: message) + } + + /// Something went wrong. + public func error(_ message: String) { + logger.error("\(message, privacy: .public)") + LogFile.shared.append(level: "ERROR", category: category, message: message) + } + + /// Detail that is only interesting while chasing a problem. Not written to + /// the file, so the file stays small enough to read. + public func debug(_ message: String) { + logger.debug("\(message, privacy: .public)") + } + + /// The bundle identifier the whole app logs under. + public static let subsystem = "com.luciochen.mwb-mac" + + /// `~/Library/Logs/mwb-mac/mwb.log`. + public static func fileURL() -> URL { + LogFile.directory().appendingPathComponent("mwb.log") + } + + /// Starts writing `info` and `error` lines to the file as well. Off until + /// the app asks for it, so a `--version` run creates nothing. + public static func startFileLogging() { + LogFile.shared.enable() + } + + /// Flushes and stops the file sink. Safe from an `atexit` handler: it blocks + /// until the queue has drained. + public static func stopFileLogging() { + LogFile.shared.disable() + } +} + +/// The rotating file behind `Log`. +/// +/// `@unchecked Sendable`: every stored property is only touched on `queue`, +/// except `enabled`, which is atomic by way of the same queue's barrier-free +/// `sync` in `disable()`. +final class LogFile: @unchecked Sendable { + static let shared = LogFile() + + /// One file, then two older generations (`mwb.1.log`, `mwb.2.log`). + static let maximumBytes = 1024 * 1024 + static let generations = 3 + + private let queue = DispatchQueue(label: "com.mwb-mac.log", qos: .utility) + private var handle: FileHandle? + private var written = 0 + private var enabled = false + + /// A value type, unlike `ISO8601DateFormatter`, so it can be a `let` here + /// under strict concurrency. + private static let timestamp = Date.ISO8601FormatStyle(includingFractionalSeconds: true) + + static func directory() -> URL { + let logs = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask) + let base = logs.first ?? URL(fileURLWithPath: NSHomeDirectory() + "/Library") + return base.appendingPathComponent("Logs/mwb-mac", isDirectory: true) + } + + func enable() { + queue.async { [self] in + guard !enabled else { return } + enabled = true + openFile() + } + } + + func disable() { + queue.sync { [self] in + enabled = false + try? handle?.close() + handle = nil + } + } + + func append(level: String, category: String, message: String) { + let stamp = LogFile.timestamp.format(Date()) + queue.async { [self] in + guard enabled else { return } + let line = "\(stamp) \(level) [\(category)] \(message)\n" + guard let data = line.data(using: .utf8) else { return } + rotateIfNeeded(adding: data.count) + guard let handle else { return } + try? handle.write(contentsOf: data) + written += data.count + } + } + + private func openFile() { + let directory = LogFile.directory() + try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent("mwb.log") + if !FileManager.default.fileExists(atPath: url.path) { + FileManager.default.createFile(atPath: url.path, contents: nil) + } + handle = try? FileHandle(forWritingTo: url) + if let handle, let end = try? handle.seekToEnd() { + written = Int(end) + } else { + written = 0 + } + } + + /// Renames `mwb.log` down the generations once it passes the size cap, the + /// way `newsyslog` does, and starts a fresh one. + private func rotateIfNeeded(adding bytes: Int) { + guard written + bytes > LogFile.maximumBytes else { return } + try? handle?.close() + handle = nil + let directory = LogFile.directory() + let manager = FileManager.default + for generation in stride(from: LogFile.generations - 1, through: 1, by: -1) { + let older = directory.appendingPathComponent("mwb.\(generation).log") + let newer = + generation == 1 + ? directory.appendingPathComponent("mwb.log") + : directory.appendingPathComponent("mwb.\(generation - 1).log") + try? manager.removeItem(at: older) + if manager.fileExists(atPath: newer.path) { + try? manager.moveItem(at: newer, to: older) + } + } + openFile() + } +}