Files
lucioandClaude Opus 5 679dee27af app-engine: Settings in the PowerToys schema, and the rotating log
Settings.swift keeps the raw property tree so properties this port does
not implement round-trip untouched (README D3), with typed accessors for
the ones we do: the `{"value": …}` boxing, the HotkeySettings shape
(HotkeySettings.cs:121-136) and the defaults of
MouseWithoutBordersProperties.cs:165-206. SettingsStore loads, saves
atomically at 0600 and watches the file (Setting.cs:197-207); a corrupt
file throws rather than being replaced by defaults, which would discard
the user's security key.

Log.swift is os.Logger plus a 1 MB x 3 rotating file. Nothing here can
take a KeyboardData or a key string (CLAUDE.md invariant 2).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-09-16 03:19:17 -07:00

164 lines
6.0 KiB
Swift

// 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()
}
}