Files
lucioandClaude Opus 5 6b2b3fc65a app-ui: menu bar, settings window, notifications, login item
The real user interface, replacing app-engine's placeholder status item.

- MWBMac/StatusItem.swift: NSStatusItem with a code-drawn icon, the
  documented status colours (doc/devdocs/modules/mousewithoutborders.md)
  and the menu the Windows tray menu offers (frmScreen.Designer.cs:91-180).
- MWBMac/SettingsWindow/*: one NSWindow hosting a SwiftUI TabView with six
  panes; every property in README §Settings is reachable. Labels and help
  text taken from MouseWithoutBordersPage.xaml + Resources.resw, cited per
  file.
- MWBMac/Notifications.swift, LaunchAgent.swift: UNUserNotificationCenter
  and SMAppService.mainApp, both guarded on a bundle identifier.
- mwb/UIBridge.swift: EngineSnapshot -> StatusModel, clicks -> Engine, and
  the connected/lost/invalid-key notification diff.

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

222 lines
8.9 KiB
Swift

// The one object the settings panes bind to.
//
// Two doors, and only two (app-engine Review): everything the user changes goes
// through `SettingsStore.update`, and the Engine is then told to re-read with
// `apply`. The store is the only writer of `settings.json`; this object never
// touches the file itself and never reaches into the Engine's state.
//
// Most edits commit as they are made. The security key, the TCP port and the
// matrix are drafts with a Save button, because a half-typed key or port would
// otherwise tear down every socket on each keystroke
// (`frmMatrix.Designer.cs:440`: the Windows form has one "&Apply" with the
// tooltip "Save changes and reconnect to the machines in the matrix").
import AppKit
import Foundation
import MWBCore
import SwiftUI
/// The settings window's state: the saved settings, the unsaved drafts, and the
/// two doors back out.
@MainActor public final class SettingsViewModel: ObservableObject {
/// The settings as last read from the store.
@Published public private(set) var settings: MWBCore.Settings
/// The security key as typed, in the grouped display form.
@Published public var securityKeyDraft = ""
/// Whether the key is shown in clear.
@Published public var showSecurityKey = false
/// The TCP port as typed.
@Published public var portDraft = ""
/// The four matrix slot names as typed.
@Published public var slotDrafts: [String] = []
/// The `Name2IP` mapping list as typed.
@Published public var name2IPDraft = ""
/// The fullscreen-exclusion list as typed, one app per line.
@Published public var excludedAppsDraft = ""
/// The last thing the window has to say — a save, or why one was refused.
@Published public private(set) var message: String?
/// The grants as the Engine last reported them. Never queried here: asking
/// TCC is the Engine's health check's job (contracts C2).
@Published public var permissions = PermissionState(listen: false, post: false)
/// This Mac's name on the wire (README D7).
public let localName: String
private let store: SettingsStore
private let applyToEngine: @Sendable (MWBCore.Settings) async -> Void
/// Binds to a store and the Engine's `apply`.
public init(
store: SettingsStore, localName: String,
apply: @escaping @Sendable (MWBCore.Settings) async -> Void
) {
self.store = store
self.localName = localName
self.applyToEngine = apply
settings = store.current
refreshDrafts()
}
/// Where the settings file lives, for the Advanced pane.
public var settingsFileURL: URL { store.fileURL }
// MARK: - Editing
/// Reads one property, writes it back through the store, and tells the
/// Engine. Use this for every control that commits as it changes.
public func binding<T: Equatable>(_ keyPath: WritableKeyPath<MWBCore.Settings, T>) -> Binding<T> {
Binding(
get: { self.settings[keyPath: keyPath] },
set: { newValue in self.commit { $0[keyPath: keyPath] = newValue } })
}
/// Applies an edit: store first, then the Engine (app-engine request 1).
public func commit(_ body: (inout MWBCore.Settings) -> Void) {
do {
try store.update(body)
} catch {
message = "Could not save settings: \(error.localizedDescription)"
Log.settings.error("settings window could not save: \(error)")
}
settings = store.current
publishToEngine()
}
/// Picks up a change made elsewhere — a hotkey toggling Easy Mouse, the
/// Engine persisting the matrix after an edge switch, or the file being
/// edited by hand. Called from the UI bridge on every engine snapshot.
public func storeChanged() {
let current = store.current
guard current != settings else { return }
settings = current
refreshDrafts()
}
private func publishToEngine() {
let latest = settings
Task { await applyToEngine(latest) }
}
/// Fills every draft from the saved settings, discarding unsaved edits.
public func refreshDrafts() {
securityKeyDraft = SecurityKey.displayText(settings.securityKey)
portDraft = String(settings.tcpPort)
slotDrafts = settings.matrix.names
name2IPDraft = settings.name2IP
excludedAppsDraft = settings.easyMouseFullscreenExcludedApps.joined(separator: "\n")
}
// MARK: - Security (`SetupPage2a.cs:92`, `Encryption.cs:209-242`)
/// Whether Save would be refused.
public var securityKeyIsValid: Bool {
SecurityKey.isValid(SecurityKey.normalize(securityKeyDraft))
}
/// A fresh key in the draft. Nothing is saved until Save is pressed, so the
/// old key keeps the matrix alive while the user copies the new one down.
public func generateKey() {
securityKeyDraft = SecurityKey.displayText(SecurityKey.random())
showSecurityKey = true
message = "New key generated. Save it here, then type the same key on every other machine."
}
/// Puts the key on the pasteboard so it can be typed into the other machines
/// ("Copy to clipboard", `MouseWithoutBorders_CopyMachineName`).
public func copyKey() {
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString(SecurityKey.normalize(securityKeyDraft), forType: .string)
message = "Security key copied to the clipboard."
}
/// Puts this Mac's name on the pasteboard; the other machines need it in
/// their matrix.
public func copyLocalName() {
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString(localName, forType: .string)
message = "Host name copied to the clipboard."
}
/// Saves the key and the port together, which is what makes the Engine
/// rebuild every connection once rather than twice.
public func saveConnection() {
let key = SecurityKey.normalize(securityKeyDraft)
guard SecurityKey.isValid(key) else {
message =
"The security key must be at least \(SecurityKey.minimumLength) characters, "
+ "and must be the same on every machine."
return
}
guard let port = UInt16(portDraft.trimmingCharacters(in: .whitespaces)), port > 1024 else {
message = "The port must be a number between 1025 and 65535."
return
}
commit { settings in
settings.securityKey = key
settings.tcpPort = port
}
securityKeyDraft = SecurityKey.displayText(key)
message = "Saved. Reconnecting to the machines in the matrix."
}
// MARK: - The matrix (`MachineStuff.cs:883-933`)
/// Whether a slot draft differs from what is saved.
public var matrixHasEdits: Bool { slotDrafts != settings.matrix.names }
/// Saves the four slot names. The Engine replicates the new matrix to the
/// peers and re-dials, exactly as it does for a matrix that arrived on the
/// wire (`EngineActions.apply`).
public func saveMatrix() {
let names = slotDrafts.map { $0.trimmingCharacters(in: .whitespaces) }
commit { settings in
var matrix = settings.matrix
for (slot, name) in names.enumerated() { matrix.setName(name, at: slot) }
settings.matrix = matrix
}
slotDrafts = settings.matrix.names
message = "Device layout saved."
}
/// Swaps two slots in the draft ("Drag and drop a machine to rearrange the
/// order", `MouseWithoutBorders_DeviceLayoutSettings.Description`; buttons
/// here, because a four-cell drag target is more work than it is worth).
public func swapSlots(_ first: Int, _ second: Int) {
guard slotDrafts.indices.contains(first), slotDrafts.indices.contains(second) else {
return
}
slotDrafts.swapAt(first, second)
}
/// Puts this Mac's own name in a slot.
public func useLocalName(inSlot slot: Int) {
guard slotDrafts.indices.contains(slot) else { return }
slotDrafts[slot] = localName
}
// MARK: - The multi-line lists
/// Saves the `Name2IP` mappings (`MouseWithoutBorders_IPAddressMapping`).
public func saveName2IP() {
commit { $0.name2IP = name2IPDraft }
message = "IP address mappings saved."
}
/// Saves the fullscreen exclusion list, one executable or bundle name per
/// line (`MouseWithoutBorders_DisableEasyMouseWhenForegroundWindowIsFullscreen_Expander`).
public func saveExcludedApps() {
let apps = excludedAppsDraft.split(separator: "\n").map {
$0.trimmingCharacters(in: .whitespaces)
}
commit { $0.easyMouseFullscreenExcludedApps = apps.filter { !$0.isEmpty } }
message = "Ignored full-screen applications saved."
}
/// Clears the status line.
public func clearMessage() {
message = nil
}
}