// The window the settings panes live in. // // One window for the life of the process: `show(pane:)` brings the existing one // to the front rather than opening a second, and closing it hides it. An // `LSUIElement` app has no Dock icon to reopen from, so a window that terminated // the app on close — or that could be opened twice — would be a dead end // (`frmMatrix` on Windows is likewise a single form the tray menu re-shows). import AppKit import Foundation import MWBCore import SwiftUI /// Shows and hides the settings window. @MainActor public final class SettingsWindowController: NSObject, NSWindowDelegate { private let model: SettingsViewModel private var window: NSWindow? private let pane = PaneSelection() /// Binds the window to a view model. Nothing is created until `show`. public init(model: SettingsViewModel) { self.model = model super.init() } /// Brings the window up, on `pane` when one is named. public func show(pane: SettingsPane? = nil) { if let pane { self.pane.selected = pane } model.storeChanged() // Re-opening starts from what is saved; bringing an already-open window // forward must not throw away what the user is halfway through typing. if !isVisible { model.refreshDrafts() } let window = window ?? makeWindow() self.window = window NSApp.activate(ignoringOtherApps: true) window.makeKeyAndOrderFront(nil) } /// True while the window is on screen; the bridge uses it to keep the /// permission state in the pane fresh without asking TCC itself. public var isVisible: Bool { window?.isVisible ?? false } private func makeWindow() -> NSWindow { let root = SettingsView(model: model, pane: pane.binding) let window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 560, height: 520), styleMask: [.titled, .closable, .miniaturizable], backing: .buffered, defer: false) window.title = "Mouse Without Borders" window.contentView = NSHostingView(rootView: root) window.isReleasedWhenClosed = false window.center() window.delegate = self return window } /// Hide, never terminate: this is the only window an accessory app has. public func windowShouldClose(_ sender: NSWindow) -> Bool { sender.orderOut(nil) return false } } /// The selected tab, shared between the controller and the view. /// /// A tiny observable box rather than `@State` inside `SettingsView`, because the /// menu bar has to be able to open a particular pane on a window that already /// exists. @MainActor final class PaneSelection: ObservableObject { @Published var selected: SettingsPane = .machines var binding: Binding { Binding(get: { self.selected }, set: { self.selected = $0 }) } }