Skip to content
Swift

Add the app: its window, settings and menu bar.

Andy Gao61ae4d2740cb
diff --git a/AirPointer.swift b/AirPointer.swift
new file mode 100644
index 0000000..4d56e71
--- /dev/null
+++ b/AirPointer.swift
@@ -0,0 +1,197 @@
+import AppKit
+import ApplicationServices
+import Carbon
+
+func screenPoint(_ normalized: CGPoint, bounds: CGRect) -> CGPoint {
+ CGPoint(x: bounds.minX + 1 + normalized.x * (bounds.width - 2),
+ y: bounds.minY + 1 + normalized.y * (bounds.height - 2))
+}
+
+final class App: NSObject, NSApplicationDelegate {
+ var statusBar:StatusBarController?
+ lazy var hud=ControlHUD()
+ var hudPhase=HomeControlPhase.needsInputs
+ var macAudioProtectionItem:NSMenuItem?
+ var macAudioProtectionEnabled=true
+ var closedCaseOwnsInput=false
+ lazy var calibrator = CaseCalibrator()
+ // Persisted pointer prefs. Settings UI and sessions read/write this value; no invisible AppKit controls.
+ var pointerSettings=PointerSettingsState.loadPersisted()
+ var closedCaseSession:ClosedCaseSession?
+ var tapTestWindow:TapTestWindow?
+ var setupTaps=SetupTaps()
+ // Set when the person backs out of closed-case calibration, so the dots don't reopen on the next tick.
+ var closedCalibrationDeclined=false
+ // Paired AirPods Pro, refreshed when Settings opens.
+ var closedCasePairs:[ClosedCaseAirPods]=[]
+ var timer: Timer?
+ var homeMenuItems:[NSMenuItem]=[]
+ var disconnectMenuItem:NSMenuItem?
+ var home:AirPointerHome?
+ let homePreview=AimPadView()
+ var homePhase=HomeControlPhase.needsInputs
+ var setup:SetupAssistant?
+ var notch:NotchFlow?
+
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ DispatchQueue.global(qos: .utility).async { pruneClosedCaseSessions(in: ClosedCaseSession.pointerSessions, keeping: ClosedCaseSession.keptSessions) }
+ NSApp.setActivationPolicy(.regular)
+ if let url=Bundle.main.url(forResource:"AppIcon",withExtension:"icns"),let icon=NSImage(contentsOf:url){
+ NSApp.applicationIconImage=icon
+ NSApp.dockTile.display()
+ }
+ refreshScreenList()
+ calibrator.onCancel = { [weak self] in
+ if self?.closedCaseSession?.isActive == true { self?.closedCalibrationDeclined = true; self?.refreshHome() }
+ }
+ CursorSize.shared.restore()
+ setupMenu()
+ installNotch()
+ let stateTimer=Timer(timeInterval:0.08,repeats:true){[weak self] _ in self?.checkState()}
+ RunLoop.main.add(stateTimer,forMode:.common);timer=stateTimer
+ NotificationCenter.default.addObserver(self, selector: #selector(screensChanged), name: NSApplication.didChangeScreenParametersNotification, object: nil)
+ NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(willSleep), name: NSWorkspace.willSleepNotification, object: nil)
+ if needsSetup{showSetup()}
+ else{showHome()}
+ }
+
+ @objc func recalibrate() {
+ if let session=closedCaseSession,session.isActive{closedCalibrationDeclined=false;session.recalibrate();return}
+ // Calibration captures from the closed case, so it needs a connection first.
+ pause();showHome();home?.setNotice("Connect your AirPods first, then recalibrate.")
+ }
+ func refreshScreenList() {
+ let count=NSScreen.screens.count
+ if count==0{pointerSettings.screen=0;return}
+ if pointerSettings.screen>=count{pointerSettings.screen=count-1}
+ }
+ @objc func screensChanged() {
+ pause("Your displays changed. Resume when you’re ready."); refreshScreenList(); pointerSettings.persist()
+ closedCaseSession?.refreshDisplays(selecting: pointerSettings.screen)
+ }
+ @objc func willSleep() { pause(); calibrator.disconnected() }
+
+ func setupMenu() {
+ let main=NSMenu()
+ func addMenu(_ title:String)->NSMenu {
+ let menu=NSMenu(title:title),item=NSMenuItem(title:title,action:nil,keyEquivalent:"")
+ item.submenu=menu;main.addItem(item);return menu
+ }
+ func item(_ title:String,_ action:Selector,_ key:String="")->NSMenuItem {
+ let value=NSMenuItem(title:title,action:action,keyEquivalent:key);value.target=self;return value
+ }
+ let appMenu=addMenu("AirPointer")
+ appMenu.addItem(withTitle:"About AirPointer",action:#selector(NSApplication.orderFrontStandardAboutPanel(_:)),keyEquivalent:"")
+ appMenu.addItem(.separator())
+ appMenu.addItem(item("Settings…",#selector(openHomeSettings),","))
+ appMenu.addItem(item("Run Setup Again…",#selector(runSetupAgain)))
+ appMenu.addItem(.separator())
+ appMenu.addItem(withTitle:"Hide AirPointer",action:#selector(NSApplication.hide(_:)),keyEquivalent:"h")
+ let others=appMenu.addItem(withTitle:"Hide Others",action:#selector(NSApplication.hideOtherApplications(_:)),keyEquivalent:"h");others.keyEquivalentModifierMask=[.command,.option]
+ appMenu.addItem(withTitle:"Show All",action:#selector(NSApplication.unhideAllApplications(_:)),keyEquivalent:"")
+ appMenu.addItem(.separator())
+ appMenu.addItem(withTitle:"Quit AirPointer",action:#selector(NSApplication.terminate(_:)),keyEquivalent:"q")
+ let file=addMenu("File")
+ let start=item("Start Pointing",#selector(homeMenuControl));file.addItem(start);homeMenuItems.append(start)
+ file.addItem(item("Recenter",#selector(homeMenuRecenter),"r"))
+ file.addItem(item("Recalibrate…",#selector(recalibrate)))
+ let disconnect=item("Disconnect",#selector(disconnectClosedCase));file.addItem(disconnect);disconnectMenuItem=disconnect
+ file.addItem(.separator())
+ let developer=NSMenu(title:"Developer"),developerItem=NSMenuItem(title:"Developer",action:nil,keyEquivalent:"")
+ developerItem.submenu=developer;file.addItem(developerItem)
+ let macAudio=item("Keep sound and mic on Mac",#selector(toggleMacAudioProtection));macAudio.state = .on
+ developer.addItem(macAudio);macAudioProtectionItem=macAudio
+ developer.addItem(item("Tap Test…",#selector(showTapTest)))
+ let edit=addMenu("Edit")
+ edit.addItem(withTitle:"Undo",action:Selector(("undo:")),keyEquivalent:"z")
+ let redo=edit.addItem(withTitle:"Redo",action:Selector(("redo:")),keyEquivalent:"z");redo.keyEquivalentModifierMask=[.command,.shift]
+ edit.addItem(.separator())
+ edit.addItem(withTitle:"Cut",action:#selector(NSText.cut(_:)),keyEquivalent:"x")
+ edit.addItem(withTitle:"Copy",action:#selector(NSText.copy(_:)),keyEquivalent:"c")
+ edit.addItem(withTitle:"Paste",action:#selector(NSText.paste(_:)),keyEquivalent:"v")
+ edit.addItem(withTitle:"Select All",action:#selector(NSText.selectAll(_:)),keyEquivalent:"a")
+ let view=addMenu("View")
+ view.addItem(item("Pointer",#selector(showPointerPage),"1"))
+ let windows=addMenu("Window")
+ windows.addItem(withTitle:"Minimize",action:#selector(NSWindow.performMiniaturize(_:)),keyEquivalent:"m")
+ windows.addItem(withTitle:"Close",action:#selector(NSWindow.performClose(_:)),keyEquivalent:"w")
+ windows.addItem(.separator())
+ windows.addItem(item("AirPointer",#selector(showWindow),"0"))
+ NSApp.windowsMenu=windows
+ NSApp.mainMenu=main
+ installStatusBar()
+ }
+ @objc func showWindow() { showHome() }
+ @objc func toggleMacAudioProtection(){
+ macAudioProtectionEnabled.toggle()
+ macAudioProtectionItem?.state=macAudioProtectionEnabled ? .on:.off
+ AudioOutputGuard.shared.protects=macAudioProtectionEnabled
+ }
+ @objc func showTapTest(){
+ if tapTestWindow==nil{tapTestWindow=TapTestWindow{[weak self] in self?.closedCaseSession}}
+ tapTestWindow?.show()
+ }
+ func pause(_ reason:String="Paused") {
+ let wasActive=closedCaseSession?.isActive == true
+ closedCaseSession?.pause(reason)
+ if wasActive{homePhase = .paused(reason)}
+ }
+ func checkState() {
+ guard !closedCaseOwnsInput else{return}
+ refreshHome();refreshSetup();refreshStatusBar()
+ }
+ func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
+ // The Dock brings back a hidden, minimized or closed window. The notch and HUD panels don't count as windows.
+ func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
+ sender.unhide(nil)
+ let windows=sender.windows.filter{ !($0 is NSPanel) }
+ if !windows.contains(where:{ $0.isVisible && !$0.isMiniaturized }){
+ if let minimized=windows.first(where:\.isMiniaturized){minimized.deminiaturize(nil)}else{showHome()}
+ }
+ sender.activate(ignoringOtherApps:true)
+ return false
+ }
+ func applicationWillTerminate(_ notification: Notification) {
+ closedCaseSession?.shutdown()
+ CursorSize.shared.restore()
+ timer?.invalidate()
+ calibrator.disconnected()
+ AudioOutputGuard.shared.stop()
+ }
+}
+
+@main
+struct AirPointerMain {
+static func main() {
+if CommandLine.arguments.contains("--check-audio-output-policy") {
+ runAudioOutputPolicyChecks()
+} else if let index=CommandLine.arguments.firstIndex(of:"--check-closed-case-tap") {
+ let fixtures=CommandLine.arguments.indices.contains(index+1) ? URL(fileURLWithPath:CommandLine.arguments[index+1]):nil
+ do{try runClosedCaseTapChecks(fixtures:fixtures)}catch{fputs("Closed-case tap check failed: \(error.localizedDescription)\n",stderr);exit(1)}
+} else if CommandLine.arguments.contains("--check-closed-case-native") {
+ do{try runClosedCaseNativeChecks()}catch{fputs("Closed-case native check failed: \(error.localizedDescription)\n",stderr);exit(1)}
+} else if CommandLine.arguments.contains("--check-home") {
+ do{try runHomeChecks()}catch{fputs("Home check failed: \(error.localizedDescription)\n",stderr);exit(1)}
+} else if CommandLine.arguments.contains("--check-pointer-settings") {
+ do{try runPointerSettingsChecks()}catch{fputs("Pointer settings check failed: \(error.localizedDescription)\n",stderr);exit(1)}
+} else if CommandLine.arguments.contains("--self-test") {
+ runAudioOutputPolicyChecks()
+ let bounds = CGRect(x: -1920, y: 0, width: 1920, height: 1080)
+ precondition(screenPoint(CGPoint(x: 0.5, y: 0.5), bounds: bounds) == CGPoint(x: -960, y: 540))
+ precondition(screenPoint(.zero, bounds: bounds) == CGPoint(x: -1919, y: 1))
+ precondition(screenPoint(CGPoint(x: 1, y: 1), bounds: bounds) == CGPoint(x: -1, y: 1079))
+ runPoseChecks()
+ do{try runPointerSettingsChecks()}catch{fputs("Pointer settings check failed: \(error.localizedDescription)\n",stderr);exit(1)}
+ do{try runClosedCaseStageChecks()}catch{fputs("Closed-case stage check failed: \(error.localizedDescription)\n",stderr);exit(1)}
+ do{try runClosedCaseTapChecks(fixtures:nil)}catch{fputs("Closed-case tap check failed: \(error.localizedDescription)\n",stderr);exit(1)}
+ do{try runTapTestChecks()}catch{fputs("Tap test check failed: \(error.localizedDescription)\n",stderr);exit(1)}
+ print("PASS: audio output policy, screen mapping, pose math, pointer settings, session stages, closed-case tap detection and the tap test")
+} else {
+ let app = NSApplication.shared
+ let delegate = App()
+ app.delegate = delegate
+ app.run()
+}
+
+}
+}
diff --git a/AirPointerHome.swift b/AirPointerHome.swift
new file mode 100644
index 0000000..fa8daf8
--- /dev/null
+++ b/AirPointerHome.swift
@@ -0,0 +1,559 @@
+import AppKit
+
+// The closed-case steps between connecting and ready: shut the lid, turn the
+// case upright while it settles, then point at the calibration dots.
+enum ClosedCaseStep:Equatable {case openLid,closeLid,turnUpright,holdStill,calibrate,recenter}
+enum HomeControlPhase:Equatable {case needsInputs,connecting,needsAccessibility,ready,running,paused(String),closedCase(ClosedCaseStep)}
+
+struct PointerSettingsState:Equatable {
+ var screens:[String]=[]
+ var screen=0
+ // Paired AirPods Pro by name; -1 until one is chosen among several.
+ var pairs:[String]=[]
+ var pair=0
+ var speed=1.0
+ var clickSound=true
+ // The way this person's taps push the sensor, when setup learned one other than the usual.
+ var tapDirection:[Double]?=nil
+
+ // Slider legacy: 10…60 stored as pointerSensitivity; speed is that value / 25.
+ private static let sensitivityKey="pointerSensitivity"
+ private static let clickSoundKey="tapClickSound"
+ private static let tapDirectionKey="tapDirection"
+ private static let screenKey="pointerScreen"
+
+ static func loadPersisted()->PointerSettingsState {
+ var value=PointerSettingsState()
+ if let saved=UserDefaults.standard.object(forKey:sensitivityKey) as? Double,saved.isFinite{
+ value.speed=min(60,max(10,saved))/25
+ }
+ value.clickSound=UserDefaults.standard.object(forKey:clickSoundKey) as? Bool ?? true
+ value.tapDirection=(UserDefaults.standard.array(forKey:tapDirectionKey) as? [Double]).flatMap{$0.count==3 ? $0:nil}
+ if let saved=UserDefaults.standard.object(forKey:screenKey) as? Int{value.screen=max(0,saved)}
+ return value
+ }
+
+ mutating func clampSpeed(){speed=min(60,max(10,speed*25))/25}
+
+ func persist(){
+ UserDefaults.standard.set(min(60,max(10,speed*25)),forKey:Self.sensitivityKey)
+ UserDefaults.standard.set(clickSound,forKey:Self.clickSoundKey)
+ if let tapDirection{UserDefaults.standard.set(tapDirection,forKey:Self.tapDirectionKey)}else{UserDefaults.standard.removeObject(forKey:Self.tapDirectionKey)}
+ UserDefaults.standard.set(screen,forKey:Self.screenKey)
+ }
+}
+
+func runPointerSettingsChecks()throws {
+ let defaults=UserDefaults.standard
+ let keys=["pointerSensitivity","tapClickSound","pointerScreen","tapDirection"]
+ let prior=Dictionary(uniqueKeysWithValues:keys.map{($0,defaults.object(forKey:$0))})
+ defer{for key in keys{if let value=prior[key]{defaults.set(value,forKey:key)}else{defaults.removeObject(forKey:key)}}}
+ defaults.removeObject(forKey:"pointerSensitivity")
+ defaults.removeObject(forKey:"tapClickSound")
+ defaults.removeObject(forKey:"pointerScreen")
+ defaults.removeObject(forKey:"tapDirection")
+ let fresh=PointerSettingsState.loadPersisted()
+ guard fresh.speed==1,fresh.clickSound,fresh.screen==0,fresh.tapDirection==nil else{
+ throw LessonError.message("Default pointer settings should be speed 1, click sound on, screen 0.")
+ }
+ var sample=PointerSettingsState(screen:1,speed:1.4,clickSound:false,tapDirection:[0.6,0,-0.8])
+ sample.clampSpeed();sample.persist()
+ let loaded=PointerSettingsState.loadPersisted()
+ guard abs(loaded.speed-1.4)<1e-9,!loaded.clickSound,loaded.screen==1,loaded.tapDirection==[0.6,0,-0.8] else{
+ throw LessonError.message("Pointer settings did not round-trip through UserDefaults.")
+ }
+}
+
+// MARK: - Copy
+
+private struct HomeControlKey:Equatable {let phase:HomeControlPhase;let inputs:Bool}
+
+private func hmCommand(_ phase:HomeControlPhase)->(title:String,hint:String?) {
+ switch phase {
+ case .needsInputs:return ("Connect AirPods",nil)
+ case .connecting:return ("Cancel","esc")
+ case .needsAccessibility:return ("Allow",nil)
+ case .ready:return ("Start Pointing",PointerShortcut.current.label)
+ case .running:return ("Pause",PointerShortcut.current.label)
+ case .paused:return ("Resume",PointerShortcut.current.label)
+ case .closedCase(.openLid):return ("Cancel","esc")
+ case .closedCase(.closeLid):return ("Lid Closed","Return")
+ case .closedCase(.turnUpright),.closedCase(.holdStill):return ("Cancel","esc")
+ case .closedCase(.calibrate):return ("Start Calibration",nil)
+ case .closedCase(.recenter):return ("Recenter",nil)
+ }
+}
+private func hmHero(_ phase:HomeControlPhase)->(String,String) {
+ switch phase {
+ case .needsInputs:return ("Connect your AirPods","Hold the closed case with both AirPods inside. Connect, then open the lid.")
+ case .connecting:return ("Looking for your AirPods…","Keep the lid open for a moment.")
+ case .needsAccessibility:return ("Allow control","Press Allow to open the Accessibility list, then drag AirPointer into it so it can move the pointer and click.")
+ case .ready:return ("Ready to point","Hold the closed case upright and aim at the screen.")
+ case .running:return ("Pointing","Aim with the case. Tap its front to click.")
+ case .paused(let reason):return ("Paused",reason=="Paused" || reason.isEmpty ? "Resume when you’re ready.":reason)
+ case .closedCase(.openLid):return ("Open the lid","AirPointer connects when you open it. Keep both AirPods inside.")
+ case .closedCase(.closeLid):return ("Close the lid","Keep both AirPods inside. AirPointer goes on by itself, or press Return.")
+ case .closedCase(.turnUpright):return ("Turn it upright","Give the closed case a quarter turn clockwise.")
+ case .closedCase(.holdStill):return ("Set it down","Put the closed case on a flat surface for a moment.")
+ case .closedCase(.calibrate):return ("Point at the dots","Aim at each dot on your screen and hold still. Esc cancels.")
+ case .closedCase(.recenter):return ("Point at the center","Your edges are saved, so one dot is enough. Esc cancels.")
+ }
+}
+
+// MARK: - Building blocks
+
+// A vertical page column whose full-width rows track the column's width.
+private final class PageColumn:NSStackView {
+ init(spacing:CGFloat=12) {
+ super.init(frame:.zero)
+ orientation = .vertical;alignment = .leading;self.spacing=spacing
+ translatesAutoresizingMaskIntoConstraints=false
+ }
+ required init?(coder:NSCoder){fatalError("init(coder:) is not used")}
+ func addFull(_ view:NSView) {
+ view.translatesAutoresizingMaskIntoConstraints=false
+ addArrangedSubview(view)
+ view.widthAnchor.constraint(equalTo:widthAnchor).isActive=true
+ }
+ // The column pins leading edges, so centered rows sit in a full-width holder.
+ func addCentered(_ view:NSView) {
+ let holder=NSView();view.translatesAutoresizingMaskIntoConstraints=false;holder.addSubview(view)
+ NSLayoutConstraint.activate([
+ view.centerXAnchor.constraint(equalTo:holder.centerXAnchor),
+ view.topAnchor.constraint(equalTo:holder.topAnchor),view.bottomAnchor.constraint(equalTo:holder.bottomAnchor),
+ view.leadingAnchor.constraint(greaterThanOrEqualTo:holder.leadingAnchor),
+ ])
+ addFull(holder)
+ }
+ func gap(_ value:CGFloat){if let last=arrangedSubviews.last{setCustomSpacing(value,after:last)}}
+ @discardableResult func addHeader(_ text:String)->NSTextField {
+ gap(24)
+ let label=hmEyebrow(text);addFull(label);setCustomSpacing(8,after:label)
+ return label
+ }
+}
+private func hmEyebrow(_ text:String)->NSTextField {
+ let label=rkLabel(text,11,.semibold,.secondaryLabelColor)
+ label.attributedStringValue=NSAttributedString(string:text.uppercased(),attributes:[.font:NSFont.systemFont(ofSize:11,weight:.semibold),.foregroundColor:NSColor.secondaryLabelColor,.kern:0.6])
+ label.setAccessibilityLabel(text)
+ return label
+}
+private func hmScrollPage(top:CGFloat=8)->(NSScrollView,PageColumn) {
+ let scroll=NSScrollView();scroll.drawsBackground=false;scroll.hasVerticalScroller=true;scroll.autohidesScrollers=true
+ scroll.borderType = .noBorder;scroll.scrollerStyle = .overlay;scroll.translatesAutoresizingMaskIntoConstraints=false
+ let document=RemoteFlipped();document.translatesAutoresizingMaskIntoConstraints=false
+ scroll.documentView=document
+ let column=PageColumn();document.addSubview(column)
+ let clip=scroll.contentView
+ NSLayoutConstraint.activate([
+ document.leadingAnchor.constraint(equalTo:clip.leadingAnchor),
+ document.trailingAnchor.constraint(equalTo:clip.trailingAnchor),
+ document.topAnchor.constraint(equalTo:clip.topAnchor),
+ column.leadingAnchor.constraint(equalTo:document.leadingAnchor,constant:24),
+ column.trailingAnchor.constraint(equalTo:document.trailingAnchor,constant:-24),
+ column.topAnchor.constraint(equalTo:document.topAnchor,constant:top),
+ column.bottomAnchor.constraint(equalTo:document.bottomAnchor,constant:-24),
+ ])
+ return (scroll,column)
+}
+private func hmRow(_ leading:[NSView],trailing:[NSView]=[],spacing:CGFloat=8)->NSStackView {
+ let row=rkHStack(leading+[rkSpacer()]+trailing,spacing:spacing)
+ return row
+}
+private func hmSettingRow(_ title:String,_ caption:String?,_ control:NSView)->NSStackView {
+ hmSettingRow(title,detail:caption.map{rkWrap($0,12)},control)
+}
+private func hmSettingRow(_ title:String,detail:NSView?,_ control:NSView)->NSStackView {
+ let text=rkVStack([rkLabel(title,13,.medium)],spacing:2)
+ if let detail{text.addArrangedSubview(detail)}
+ text.setContentCompressionResistancePriority(.defaultLow,for:.horizontal)
+ control.setContentHuggingPriority(.required,for:.horizontal)
+ let row=rkHStack([text,rkSpacer(),control],spacing:16)
+ row.heightAnchor.constraint(greaterThanOrEqualToConstant:44).isActive=true
+ return row
+}
+
+// A dismissible line at the top of the window for things that went wrong.
+private final class NoticeBar:NSView {
+ private let text=rkWrap("",12,.labelColor)
+ private let icon=rkSymbolView("exclamationmark.circle",13,.secondaryLabelColor)
+ private let close=NSButton()
+ init() {
+ super.init(frame:.zero);translatesAutoresizingMaskIntoConstraints=false
+ close.image=rkSymbol("xmark",10,.semibold);close.isBordered=false;close.imagePosition = .imageOnly
+ close.contentTintColor = .secondaryLabelColor;close.target=self;close.action=#selector(dismiss)
+ close.setAccessibilityLabel("Dismiss")
+ // The message takes the width left over, so the dismiss button sits at the trailing edge.
+ text.setContentHuggingPriority(.init(1),for:.horizontal);close.setContentHuggingPriority(.required,for:.horizontal)
+ let row=rkHStack([icon,text,close],spacing:10);row.alignment = .firstBaseline;row.distribution = .fill
+ let surface=RemoteSurface(HomePalette.raised,radius:10)
+ rkPin(surface,in:self,insets:NSEdgeInsets(top:4,left:16,bottom:8,right:16))
+ rkPin(row,in:surface,insets:NSEdgeInsets(top:10,left:12,bottom:10,right:10))
+ isHidden=true
+ }
+ required init?(coder:NSCoder){fatalError("init(coder:) is not used")}
+ func set(_ value:String?) {
+ let value=value?.trimmingCharacters(in:.whitespacesAndNewlines)
+ isHidden=value?.isEmpty ?? true
+ if let value,!value.isEmpty,text.stringValue != value {
+ text.stringValue=value
+ NSAccessibility.post(element:text,notification:.announcementRequested,userInfo:[.announcement:value,.priority:NSAccessibilityPriorityLevel.high.rawValue])
+ }
+ }
+ @objc private func dismiss(){isHidden=true}
+}
+
+// MARK: - Window
+
+private enum HomePage:Equatable {case pointer,settings}
+
+// A key window where bare Esc goes to the page unless a field is being edited.
+final class HomeWindow:NSWindow {
+ var onEscape:(()->Void)?
+ override func sendEvent(_ event:NSEvent) {
+ if event.type == .keyDown,!event.isARepeat,
+ event.modifierFlags.intersection([.command,.control,.option]).isEmpty {
+ let editing=firstResponder is NSTextView || firstResponder is NSTextField
+ if event.keyCode==53,!editing,let onEscape{onEscape();return}
+ }
+ super.sendEvent(event)
+ }
+}
+
+final class AirPointerHome:NSObject,NSWindowDelegate {
+ let window:HomeWindow
+ var onControl:(()->Void)?
+ var onRecenter:(()->Void)?
+ var onLearnGrip:(()->Void)?
+ var onDisconnect:(()->Void)?
+ var onSetup:(()->Void)?
+ var onTeachTap:(()->Void)?
+ var onSettings:(()->Void)?
+ var onPointerSettingsChange:((PointerSettingsState)->Void)?
+ var onClose:(()->Void)?
+
+ fileprivate var phase=HomeControlPhase.needsInputs
+ fileprivate var inputsReady=false
+ fileprivate var pointerSettings=PointerSettingsState()
+
+ let pad:AimPadView
+ private let pageHost=NSView()
+ private let notice=NoticeBar()
+ private lazy var pointerPage=PointerPage(home:self)
+ private lazy var settingsPage=SettingsPage(home:self)
+ fileprivate private(set) var page=HomePage.pointer
+ private var controlKey:HomeControlKey?
+
+ init(pad:AimPadView=AimPadView()) {
+ self.pad=pad
+ window=HomeWindow(contentRect:NSRect(x:0,y:0,width:440,height:700),styleMask:[.titled,.closable,.miniaturizable,.resizable,.fullSizeContentView],backing:.buffered,defer:false)
+ super.init()
+ window.title="AirPointer";window.titleVisibility = .hidden
+ window.isReleasedWhenClosed=false;window.delegate=self
+ window.titlebarAppearsTransparent=true;window.titlebarSeparatorStyle = .none
+ window.backgroundColor=HomePalette.canvas
+ window.contentMinSize=NSSize(width:400,height:620);window.contentMaxSize=NSSize(width:560,height:4000)
+ let toolbar=NSToolbar(identifier:"AirPointerRemote")
+ toolbar.delegate=self;toolbar.displayMode = .iconOnly;toolbar.allowsUserCustomization=false
+ if #available(macOS 15,*){toolbar.allowsDisplayModeCustomization=false}
+ window.toolbar=toolbar;window.toolbarStyle = .unified
+ let root=RemoteSurface(HomePalette.canvas)
+ let stack=rkVStack([notice,pageHost],spacing:0,align:.leading)
+ pageHost.translatesAutoresizingMaskIntoConstraints=false
+ root.addSubview(stack)
+ NSLayoutConstraint.activate([
+ stack.topAnchor.constraint(equalTo:root.safeAreaLayoutGuide.topAnchor),
+ stack.leadingAnchor.constraint(equalTo:root.leadingAnchor),
+ stack.trailingAnchor.constraint(equalTo:root.trailingAnchor),
+ stack.bottomAnchor.constraint(equalTo:root.bottomAnchor),
+ notice.widthAnchor.constraint(equalTo:stack.widthAnchor),
+ pageHost.widthAnchor.constraint(equalTo:stack.widthAnchor),
+ ])
+ window.contentView=root
+ window.setContentSize(NSSize(width:440,height:700))
+ window.center()
+ window.onEscape={[weak self] in self?.handleEscape()}
+ present(.pointer)
+ }
+
+ // MARK: Public API
+
+ func show() {
+ if window.isMiniaturized{window.deminiaturize(nil)}
+ window.makeKeyAndOrderFront(nil)
+ NSApp.activate(ignoringOtherApps:true)
+ }
+
+ // Called about 12 times a second: returns early unless something visible changed.
+ func updateControl(phase:HomeControlPhase,inputsReady:Bool) {
+ let key=HomeControlKey(phase:phase,inputs:inputsReady)
+ guard key != controlKey else{return}
+ let announce=controlKey != nil && phase != self.phase
+ controlKey=key
+ self.phase=phase;self.inputsReady=inputsReady
+ pointerPage.render()
+ if announce{NSAccessibility.post(element:window,notification:.announcementRequested,userInfo:[.announcement:hmHero(phase).0,.priority:NSAccessibilityPriorityLevel.high.rawValue])}
+ }
+
+ func updateHold(_ progress:CGFloat?){pointerPage.updateHold(progress)}
+ func setNotice(_ text:String?){notice.set(text)}
+ func selectPointer(){present(.pointer)}
+ func selectSettings() {
+ guard page != .settings else{return}
+ present(.settings)
+ NSAccessibility.post(element:window,notification:.announcementRequested,userInfo:[.announcement:"Settings",.priority:NSAccessibilityPriorityLevel.medium.rawValue])
+ }
+ func updatePointerSettings(_ value:PointerSettingsState) {
+ guard value != pointerSettings else{return}
+ pointerSettings=value;settingsPage.apply();pointerPage.render()
+ }
+
+ // MARK: Shared with pages
+
+ fileprivate func changePointerSettings(_ value:PointerSettingsState) {
+ pointerSettings=value;settingsPage.apply();pointerPage.render();onPointerSettingsChange?(value)
+ }
+
+ fileprivate func present(_ next:HomePage) {
+ if next != page {
+ if let responder=window.firstResponder as? NSView,responder.isDescendant(of:pageHost){_ = window.makeFirstResponder(nil)}
+ }
+ page=next
+ let view:NSView
+ switch next {
+ case .pointer:pointerPage.render();view=pointerPage.view
+ case .settings:settingsPage.apply();view=settingsPage.view
+ }
+ guard pageHost.subviews.first !== view else{return}
+ pageHost.subviews.forEach{$0.removeFromSuperview()}
+ rkPin(view,in:pageHost)
+ }
+
+ // MARK: Actions and keys
+
+ @objc fileprivate func openSettings(){onSettings?()}
+
+ private func handleEscape() {
+ switch phase {
+ case .running,.connecting,.closedCase(.turnUpright),.closedCase(.holdStill):onControl?();return
+ default:break
+ }
+ if page == .settings{present(.pointer)}
+ }
+
+ func windowWillClose(_ notification:Notification) {
+ onClose?()
+ }
+}
+
+private extension NSToolbarItem.Identifier {
+ static let homeSettings=NSToolbarItem.Identifier("AirPointerSettings")
+}
+
+extension AirPointerHome:NSToolbarDelegate {
+ func toolbarDefaultItemIdentifiers(_ toolbar:NSToolbar)->[NSToolbarItem.Identifier]{[.flexibleSpace,.homeSettings]}
+ func toolbarAllowedItemIdentifiers(_ toolbar:NSToolbar)->[NSToolbarItem.Identifier]{toolbarDefaultItemIdentifiers(toolbar)}
+ func toolbar(_ toolbar:NSToolbar,itemForItemIdentifier identifier:NSToolbarItem.Identifier,willBeInsertedIntoToolbar flag:Bool)->NSToolbarItem? {
+ let item=NSToolbarItem(itemIdentifier:identifier)
+ if identifier == .homeSettings {
+ item.image=rkSymbol("gearshape",15);item.label="Settings";item.toolTip="Settings (⌘,)"
+ item.isBordered=true;item.target=self;item.action=#selector(openSettings)
+ } else{return nil}
+ return item
+ }
+}
+
+// MARK: - Pointer
+
+private final class PointerPage:NSObject {
+ unowned let home:AirPointerHome
+ let view:NSScrollView
+ private let stage=RemoteSurface(HomePalette.stage,radius:18)
+ private let art=CaseStepView()
+ private let chip=StatusChip()
+ private let title=rkTitle("",26,align:.center)
+ private let subtitle=rkWrap("",13,align:.center)
+ private let primary=RemoteButton("Start Pointing",height:48)
+ private let recenter=RemoteButton("Recenter",style:.tertiary,symbol:"scope",height:32)
+ private let recalibrate=RemoteButton("Recalibrate…",style:.tertiary,symbol:"dot.viewfinder",height:32)
+ private let disconnect=RemoteButton("Disconnect",style:.tertiary,symbol:"xmark.circle",height:32)
+ private let secondary=NSStackView()
+ private var showingPad:Bool?
+
+ init(home:AirPointerHome) {
+ self.home=home
+ let page=hmScrollPage(top:4);view=page.0
+ super.init()
+ let column=page.1
+ stage.translatesAutoresizingMaskIntoConstraints=false
+ stage.heightAnchor.constraint(equalToConstant:228).isActive=true
+ art.fill=0.86
+ for view in [art,home.pad] as [NSView] {
+ view.translatesAutoresizingMaskIntoConstraints=false;stage.addSubview(view)
+ }
+ NSLayoutConstraint.activate([
+ art.topAnchor.constraint(equalTo:stage.topAnchor,constant:8),art.bottomAnchor.constraint(equalTo:stage.bottomAnchor,constant:-8),
+ art.leadingAnchor.constraint(equalTo:stage.leadingAnchor),art.trailingAnchor.constraint(equalTo:stage.trailingAnchor),
+ home.pad.centerXAnchor.constraint(equalTo:stage.centerXAnchor),home.pad.centerYAnchor.constraint(equalTo:stage.centerYAnchor),
+ home.pad.heightAnchor.constraint(equalTo:stage.heightAnchor,constant:-32),
+ home.pad.widthAnchor.constraint(equalTo:home.pad.heightAnchor,multiplier:1.6),
+ ])
+ column.addFull(stage);column.gap(18)
+ column.addCentered(chip);column.gap(12)
+ column.addFull(title);column.gap(6)
+ column.addFull(subtitle);column.gap(22)
+ primary.target=self;primary.action=#selector(primaryPressed)
+ column.addFull(primary);column.gap(8)
+ recenter.target=self;recenter.action=#selector(recenterPressed)
+ recalibrate.target=self;recalibrate.action=#selector(recalibratePressed)
+ disconnect.target=self;disconnect.action=#selector(disconnectPressed)
+ recenter.toolTip="Recenter on where you’re aiming";recalibrate.toolTip="Point at three dots so AirPointer knows where your screen is"
+ disconnect.toolTip="End the connection. To reconnect, connect again and open the lid."
+ secondary.orientation = .horizontal;secondary.spacing=4
+ secondary.addArrangedSubview(recenter);secondary.addArrangedSubview(recalibrate);secondary.addArrangedSubview(disconnect)
+ column.addCentered(secondary)
+ render()
+ }
+
+ func render() {
+ let phase=home.phase
+ let hero=hmHero(phase),command=hmCommand(phase)
+ rkSetText(title,hero.0);rkSetText(subtitle,hero.1)
+ if primary.title != command.title{primary.title=command.title}
+ if primary.hint != command.hint{primary.hint=command.hint}
+ // The hint names the key: Return confirms the closed lid, esc cancels.
+ let key=command.hint=="Return" ? "\r":command.hint=="esc" ? "\u{1b}":""
+ if primary.keyEquivalent != key{primary.keyEquivalent=key}
+ // Until the closed case is upright and held, the stage shows the step to do with it.
+ let connected:Bool
+ switch phase {
+ // Closed before Connect and while asking for Accessibility, the lid opening while Connect waits, then the open case.
+ case .needsInputs:connected=false;art.step = .closed
+ case .closedCase(.openLid):connected=false;art.step = .opening
+ case .connecting:connected=false;art.step = .open
+ case .closedCase(.closeLid):connected=false;art.step = .close
+ case .closedCase(.turnUpright):connected=false;art.step = .turn
+ case .closedCase(.holdStill):connected=false;art.step = .closed
+ case .needsAccessibility:connected=home.inputsReady;art.step = .closed
+ default:connected=true
+ }
+ let live:Bool
+ switch phase {
+ case .needsInputs:chip.set("Not connected",dot:false);live=false
+ case .connecting:chip.set("Connecting…",dot:false);live=false
+ case .closedCase(.openLid):chip.set("Waiting for the lid",dot:false);live=false
+ case .needsAccessibility:chip.set(connected ? "Connected":"Not connected",dot:connected);live=false
+ case .ready:chip.set("Connected");live=false
+ case .running:chip.set("Pointing",live:true);live=true
+ case .paused:chip.set("Paused");live=false
+ case .closedCase(.closeLid):chip.set("Connected");live=false
+ case .closedCase(.turnUpright):chip.set("Connected");live=false
+ case .closedCase(.holdStill):chip.set("Keep it still",dot:false);live=false
+ case .closedCase(.calibrate):chip.set("Calibrating",dot:false);live=false
+ case .closedCase(.recenter):chip.set("Recentering",dot:false);live=false
+ }
+ if showingPad != connected {
+ showingPad=connected
+ home.pad.isHidden = !connected;art.isHidden=connected
+ }
+ home.pad.live=live
+ let screens=home.pointerSettings.screens
+ home.pad.caption=screens.indices.contains(home.pointerSettings.screen) && screens.count>1 ? screens[home.pointerSettings.screen]:""
+ // Centered rows live in holders; hiding the holder collapses the row.
+ // The closed case stays connected through Pause until Disconnect.
+ switch phase {
+ case .running,.paused:recenter.isHidden=false;recalibrate.isHidden=false;disconnect.isHidden=false;secondary.superview?.isHidden=false
+ case .ready:recenter.isHidden=true;recalibrate.isHidden=false;disconnect.isHidden=false;secondary.superview?.isHidden=false
+ case .closedCase(.calibrate):recenter.isHidden=true;recalibrate.isHidden=true;disconnect.isHidden=false;secondary.superview?.isHidden=false
+ // Saved edges might not suit a new grip, so all three dots stay one click away.
+ case .closedCase(.recenter):recenter.isHidden=true;recalibrate.isHidden=false;disconnect.isHidden=false;secondary.superview?.isHidden=false
+ default:secondary.superview?.isHidden=true
+ }
+ }
+
+ func updateHold(_ progress:CGFloat?){art.holdProgress=progress}
+ @objc private func primaryPressed(){home.onControl?()}
+ @objc private func recenterPressed(){home.onRecenter?()}
+ @objc private func recalibratePressed(){home.onLearnGrip?()}
+ @objc private func disconnectPressed(){home.onDisconnect?()}
+}
+
+// MARK: - Settings
+
+private final class SettingsPage:NSObject {
+ unowned let home:AirPointerHome
+ let view:NSScrollView
+ private let screens=NSPopUpButton()
+ private let pairs=NSPopUpButton()
+ private let speed=NSSlider(value:1,minValue:0.4,maxValue:2.4,target:nil,action:nil)
+ private let clickSound=InkSwitch()
+ private let shortcutControl=PointerShortcutControl()
+ private let speedValue=rkLabel("1.0×",13,.medium)
+
+ init(home:AirPointerHome) {
+ self.home=home
+ let page=hmScrollPage(top:2);view=page.0
+ super.init()
+ let column=page.1
+ // With no section tabs, this is the way back besides esc and ⌘1.
+ let back=RemoteButton("Pointer",style:.tertiary,symbol:"chevron.left",height:28,target:self,action:#selector(backPressed))
+ back.setAccessibilityLabel("Back to Pointer")
+ column.addFull(hmRow([back]));column.gap(4)
+ column.addFull(rkLabel("Settings",22,.bold))
+ column.addHeader("AirPods")
+ pairs.target=self;pairs.action=#selector(changed(_:));pairs.setAccessibilityLabel("AirPods to connect to")
+ column.addFull(hmSettingRow("Connect to",nil,pairs))
+ column.addHeader("Screen")
+ screens.target=self;screens.action=#selector(changed(_:));screens.setAccessibilityLabel("Screen to control")
+ column.addFull(hmSettingRow("Point at",nil,screens))
+ column.addHeader("Pointer speed")
+ speed.target=self;speed.action=#selector(changed(_:));speed.isContinuous=true;speed.setAccessibilityLabel("Pointer speed")
+ speedValue.font = .monospacedDigitSystemFont(ofSize:13,weight:.medium)
+ speedValue.setContentHuggingPriority(.required,for:.horizontal)
+ let ends=hmRow([rkLabel("Slower",12,.regular,.secondaryLabelColor)],trailing:[rkLabel("Faster",12,.regular,.secondaryLabelColor)])
+ let track=rkVStack([speed,ends],spacing:2,align:.leading)
+ ends.widthAnchor.constraint(equalTo:speed.widthAnchor).isActive=true
+ speed.widthAnchor.constraint(equalTo:track.widthAnchor).isActive=true
+ track.setHuggingPriority(.init(1),for:.horizontal)
+ let slider=rkHStack([track,speedValue],spacing:14);slider.alignment = .top
+ column.addFull(slider)
+ column.addHeader("Tap to click")
+ clickSound.setAccessibilityLabel("Click sound");clickSound.onChange={[weak self] _ in self?.changed(nil)}
+ column.addFull(hmSettingRow("Click sound","Plays on this Mac when a tap on the case clicks.",clickSound))
+ let teachTap=RemoteButton("Teach Tap…",style:.secondary,height:32,target:self,action:#selector(teachTap))
+ column.addFull(hmSettingRow("Your tap","Tap the case three times so AirPointer knows how your taps feel.",teachTap))
+ column.addHeader("Calibration")
+ let recalibrate=RemoteButton("Recalibrate…",style:.secondary,height:32,target:self,action:#selector(recalibrate))
+ column.addFull(hmSettingRow("Your screen","Point at three dots so AirPointer knows where your screen is.",recalibrate))
+ column.addHeader("Shortcut")
+ column.addFull(hmSettingRow("Turn the pointer on or off",detail:shortcutControl.note,shortcutControl))
+ column.addFull(RemoteRule())
+ let setup=RemoteButton("Run Setup Again…",style:.secondary,height:32,target:self,action:#selector(setup))
+ column.addFull(hmSettingRow("Setup","Walk through connecting, permissions and calibration again.",setup))
+ apply()
+ }
+
+ func apply() {
+ let state=home.pointerSettings
+ if screens.itemTitles != state.screens{screens.removeAllItems();screens.addItems(withTitles:state.screens)}
+ if screens.itemArray.indices.contains(state.screen){screens.selectItem(at:state.screen)}
+ screens.isEnabled=state.screens.count>1
+ let pairTitles=state.pairs.isEmpty ? ["No AirPods Pro found"]:state.pair<0 ? ["Choose your AirPods"]+state.pairs:state.pairs
+ if pairs.itemTitles != pairTitles{pairs.removeAllItems();pairs.addItems(withTitles:pairTitles)}
+ pairs.selectItem(at:max(0,state.pair));pairs.isEnabled=state.pairs.count>1
+ speed.doubleValue=state.speed
+ rkSetText(speedValue,String(format:"%.1f×",state.speed))
+ speed.setAccessibilityValueDescription(String(format:"%.1f times normal speed",state.speed))
+ clickSound.setOn(state.clickSound,animated:false)
+ }
+ @objc private func changed(_ sender:Any?) {
+ var value=home.pointerSettings
+ value.screen=max(0,screens.indexOfSelectedItem);value.speed=(speed.doubleValue*10).rounded()/10;value.clickSound=clickSound.isOn
+ if !value.pairs.isEmpty{value.pair=pairs.indexOfSelectedItem-(value.pair<0 ? 1:0)}
+ home.changePointerSettings(value)
+ }
+ @objc private func backPressed(){home.present(.pointer)}
+ @objc private func recalibrate(){home.onLearnGrip?()}
+ @objc private func setup(){home.onSetup?()}
+ @objc private func teachTap(){home.onTeachTap?()}
+}
diff --git a/AppHome.swift b/AppHome.swift
new file mode 100644
index 0000000..abc3e72
--- /dev/null
+++ b/AppHome.swift
@@ -0,0 +1,312 @@
+import AppKit
+import ApplicationServices
+
+extension App {
+ func startClosedPointerSession(fromNotch:Bool=false){
+ startClosedPointerSession(ClosedCaseSessionLaunch(fromNotch:fromNotch))
+ }
+ func startClosedPointerSession(_ launch:ClosedCaseSessionLaunch){
+ // A session still running ends first, without holding up the window.
+ if let old=closedCaseSession,old.isActive{old.disconnect{[weak self] in self?.startClosedPointerSession(launch)};return}
+ pause();calibrator.disconnected()
+ let session=ClosedCaseSession();closedCaseSession=session
+ session.usesNotch=launch.fromNotch;session.opensLidFirst=launch.afterLoss
+ session.pointsWhenReady=launch.pointsWhenReady(setupVisible:setup?.window.isVisible == true);notch?.stage=nil
+ applyPointerSettings(pointerSettings,to:session)
+ session.onPoint={ [weak self] point in self?.homePreview.point=point;self?.statusBar?.updatePointer(point) }
+ session.onFrame={ [weak self] frame in if self?.calibrator.closedCase != nil{self?.calibrator.feed(frame)} }
+ closedCalibrationDeclined=false
+ session.onUpdate={ [weak self] session in
+ guard let self,self.closedCaseSession === session else{return}
+ self.closedCaseOwnsInput=session.isActive
+ // Setup asks for calibration on its own step; elsewhere the dots appear as soon as the case is upright.
+ // A finished calibration leaves the overlay to show "Calibrated"; anything else ends it.
+ if session.stage == .calibrating{if self.setup?.window.isVisible != true && !session.centersItself{self.presentClosedCalibration(session)}}
+ else if self.calibrator.closedCase != nil && !session.calibrated{
+ let declined=self.closedCalibrationDeclined;self.calibrator.cancel();self.closedCalibrationDeclined=declined
+ }
+ // The state timer stands down while the session owns the input, so the menu bar, HUD and setup follow the session here.
+ self.refreshHome();self.refreshStatusBar();self.refreshSetup();self.refreshNotch()
+ }
+ // A connection that drops on its own says why above the page; Disconnect stays quiet.
+ session.onEnded={ [weak self] reason in
+ // The window is often out of sight while pointing, so the notch says what happened and pointing returns once the lid opens and closes.
+ if session.lostContact{
+ DispatchQueue.main.async{self?.startClosedPointerSession(ClosedCaseSessionLaunch(fromNotch:true,afterLoss:true))}
+ return
+ }
+ guard let reason else{return}
+ self?.home?.setNotice(reason)
+ if reason==ClosedCaseAirPods.Choice.several.failure{self?.showHomeSettings()}
+ }
+ home?.setNotice(nil)
+ session.beginSession()
+ }
+ // Pause keeps the case connected; this is the one way to end the connection on purpose.
+ @objc func disconnectClosedCase(){
+ guard let session=closedCaseSession,session.isActive else{return}
+ if calibrator.closedCase != nil{calibrator.cancel()}
+ session.disconnect();refreshHome();refreshStatusBar()
+ }
+ // The closed case calibrates through the same full-screen dots as the rest of the app.
+ func presentClosedCalibration(_ session:ClosedCaseSession){
+ guard !calibrator.isActive,!closedCalibrationDeclined else{return}
+ calibrator.closedCase={ [weak session] center,right,up in
+ guard let session else{throw LessonError.message("The case lost its connection. Connect again, then open the lid.")}
+ try session.applyCalibration(center:center,right:right,up:up)
+ }
+ calibrator.closedCenter=session.centerOnly ? { [weak session] center in
+ guard let session else{throw LessonError.message("The case lost its connection. Connect again, then open the lid.")}
+ return try session.applyCenter(center)
+ }:nil
+ calibrator.show(on:controlledScreen)
+ }
+ func showHome(){
+ if home==nil {
+ let view=AirPointerHome(pad:homePreview)
+ view.onControl={ [weak self] in self?.homeControlAction() }
+ view.onRecenter={ [weak self] in self?.homeRecenter() }
+ view.onLearnGrip={ [weak self] in self?.recalibrate() }
+ view.onDisconnect={ [weak self] in self?.disconnectClosedCase() }
+ view.onSetup={ [weak self] in self?.runSetupAgain() }
+ view.onTeachTap={ [weak self] in self?.teachTap() }
+ view.onSettings={ [weak self] in self?.showHomeSettings() }
+ view.onPointerSettingsChange={ [weak self] value in self?.applyHomePointerSettings(value) }
+ view.onClose={ [weak self] in self?.pause() }
+ home=view
+ }
+ refreshHome();home?.show()
+ }
+ var homeInputsReady:Bool{closedCaseSession?.inputReady == true}
+ func homeControlAction(){
+ if let session=closedCaseSession,session.isActive{
+ switch session.stage {
+ case .closeLid:session.confirmLidClosed()
+ case .calibrating:closedCalibrationDeclined=false;presentClosedCalibration(session)
+ case .ready:session.resumeCursor()
+ case .pointing:pause()
+ default:disconnectClosedCase()
+ }
+ refreshHome();return
+ }
+ guard !closedCaseOwnsInput else{return}
+ home?.setNotice(nil)
+ guard AXIsProcessTrusted() else{
+ homePhase = .needsAccessibility;home?.setNotice(nil)
+ AccessibilityGuide.shared.open()
+ refreshHome();return
+ }
+ startClosedPointerSession()
+ }
+ func homeRecenter(){if let session=closedCaseSession,session.isActive{session.recenter()}else{pause();refreshHome()}}
+ // The phase drives the window, the menu bar and the HUD, so it is
+ // computed even while the window has never been opened.
+ func refreshHome(){
+ let trusted=AXIsProcessTrusted(),ready=homeInputsReady
+ if let session=closedCaseSession{homePhase=trusted ? session.homePhase:.needsAccessibility}
+ else if !trusted{homePhase = .needsAccessibility}
+ else{homePhase = .needsInputs}
+ let title:String
+ if let session=closedCaseSession,session.isActive {
+ switch session.stage {
+ case .pointing:title="Pause"
+ case .ready:title="Start Pointing"
+ case .closeLid:title="Lid Closed"
+ case .calibrating:title="Start Calibration"
+ default:title="Cancel Connecting"
+ }
+ }else{title="Start Pointing"}
+ for item in homeMenuItems{item.title=title}
+ disconnectMenuItem?.isHidden=closedCaseSession?.isActive != true
+ guard let home else{return}
+ home.updatePointerSettings(homePointerSettings())
+ home.updateControl(phase:homePhase,inputsReady:ready)
+ home.updateHold(homePhase == .closedCase(.holdStill) ? CGFloat(closedCaseSession?.holdProgress ?? 0):nil)
+ }
+ func homePointerSettings()->PointerSettingsState {
+ let chosen=ClosedCaseAirPods.choose(ClosedCaseAirPods.Survey(poweredOn:true,pairs:closedCasePairs),saved:ClosedCaseAirPods.saved)
+ var pair = -1;if case .chosen(let found)=chosen{pair=closedCasePairs.firstIndex(of:found) ?? -1}
+ var value=pointerSettings
+ value.screens=NSScreen.screens.map(\.localizedName)
+ value.pairs=closedCasePairs.map(\.title)
+ value.pair=pair
+ if !value.screens.isEmpty,value.screen>=value.screens.count{value.screen=value.screens.count-1}
+ return value
+ }
+ func showHomeSettings(){
+ guard let home else{return};pause()
+ home.updatePointerSettings(homePointerSettings());home.selectSettings()
+ ClosedCaseAirPods.survey{[weak self] survey in
+ guard let self,let survey else{return}
+ self.closedCasePairs=survey.pairs;self.home?.updatePointerSettings(self.homePointerSettings())
+ }
+ }
+ private func applyPointerSettings(_ value:PointerSettingsState,to session:ClosedCaseSession){
+ session.speed=value.speed;session.clickSound=value.clickSound;session.tapDirection=value.tapDirection
+ session.screenIndex=value.screen
+ }
+ func applyHomePointerSettings(_ value:PointerSettingsState){
+ // Another pair is a different connection, so a session on the old one ends.
+ if closedCasePairs.indices.contains(value.pair),closedCasePairs[value.pair].address != ClosedCaseAirPods.saved {
+ disconnectClosedCase()
+ do{try ClosedCaseAirPods.save(closedCasePairs[value.pair])}catch{home?.setNotice("AirPointer couldn’t save which AirPods to use. Try again.")}
+ }
+ var next=value;next.clampSpeed()
+ let screenChanged=pointerSettings.screen != next.screen
+ pointerSettings.speed=next.speed
+ pointerSettings.clickSound=next.clickSound
+ if NSScreen.screens.indices.contains(next.screen){pointerSettings.screen=next.screen}
+ pointerSettings.persist()
+ if screenChanged{pause()}
+ if let session=closedCaseSession{applyPointerSettings(pointerSettings,to:session)}
+ home?.updatePointerSettings(homePointerSettings())
+ }
+ @objc func openHomeSettings(){showHome();showHomeSettings()}
+ @objc func homeMenuControl(){showHome();homeControlAction()}
+ @objc func homeMenuRecenter(){homeRecenter()}
+ @objc func showPointerPage(){showHome();home?.selectPointer()}
+}
+
+extension App {
+ // First run: setup never finished.
+ var needsSetup:Bool{!UserDefaults.standard.bool(forKey:"setupComplete")}
+ @objc func showSetup(){
+ if setup==nil {
+ let assistant=SetupAssistant()
+ // Setup always connects the closed case.
+ assistant.onConnect={ [weak self] in self?.startClosedPointerSession() }
+ assistant.onChooseAirPods={ [weak self] in self?.chooseAirPods() }
+ assistant.onLidClosed={ [weak self] in self?.closedCaseSession?.confirmLidClosed() }
+ assistant.onRequestAccessibility={AccessibilityGuide.shared.open()}
+ assistant.onCalibrate={ [weak self] in
+ guard let self,let session=self.closedCaseSession,session.isActive else{self?.recalibrate();return}
+ // Setup always aims at all three dots, even when edges were saved before.
+ self.closedCalibrationDeclined=false;session.recalibrate()
+ if session.stage == .calibrating{self.presentClosedCalibration(session)}
+ }
+ assistant.onFinish={ [weak self] in UserDefaults.standard.set(true,forKey:"setupComplete");self?.showHome() }
+ assistant.onLearnTap={ [weak self] in self?.learnTap() }
+ assistant.onStopLearningTap={ [weak self] in self?.stopLearningTap() }
+ assistant.onClose={ [weak self] in self?.closedCaseSession?.stopLearningTaps();self?.setup=nil }
+ setupTaps=SetupTaps()
+ setup=assistant
+ refreshSetup()
+ }
+ home?.window.orderOut(nil)
+ setup?.show()
+ }
+ private func chooseAirPods(){
+ ClosedCaseAirPods.survey{[weak self] survey in
+ guard let self,let survey else{return}
+ let menu=NSMenu()
+ for pair in survey.pairs{
+ let item=NSMenuItem(title:pair.title,action:#selector(self.pickAirPods(_:)),keyEquivalent:"")
+ item.target=self;item.representedObject=pair;menu.addItem(item)
+ }
+ menu.popUp(positioning:nil,at:NSEvent.mouseLocation,in:nil)
+ }
+ }
+ @objc private func pickAirPods(_ item:NSMenuItem){
+ guard let pair=item.representedObject as? ClosedCaseAirPods,(try? ClosedCaseAirPods.save(pair)) != nil else{return}
+ startClosedPointerSession()
+ }
+ @objc func runSetupAgain(){pause();showSetup();setup?.go(to:AXIsProcessTrusted() ? 1:0)}
+ func teachTap(){pause();showSetup();setupTaps=SetupTaps();refreshSetup();setup?.go(to:3)}
+ private func learnTap(){
+ setupTaps=SetupTaps(listening:true)
+ closedCaseSession?.learnTaps{ [weak self] event in
+ guard let self else{return}
+ switch event {
+ case .tap(let agreeing,let total):self.setupTaps.heard=agreeing;self.setupTaps.mixed=total>agreeing;self.setupTaps.soft=false
+ case .tooSoft:self.setupTaps.soft=true
+ case .finished(let direction):
+ self.setupTaps=SetupTaps(heard:ClosedCaseTapLearner.taps,learned:true)
+ self.pointerSettings.tapDirection=direction==ClosedCaseTapDetector.tapDirection ? nil:[direction.x,direction.y,direction.z]
+ self.pointerSettings.persist()
+ self.closedCaseSession?.tapDirection=self.pointerSettings.tapDirection
+ case .failed:self.setupTaps=SetupTaps(failed:true)
+ }
+ self.refreshSetup()
+ }
+ refreshSetup()
+ }
+ private func stopLearningTap(){
+ closedCaseSession?.stopLearningTaps()
+ if setupTaps.listening{setupTaps=SetupTaps();refreshSetup()}
+ }
+ func refreshSetup(){
+ guard let setup else{return}
+ let session=closedCaseSession
+ let stage=session?.stage ?? .off
+ let link=stage.setupLink
+ let problem=stage == .off ? session?.endReason:nil
+ setup.update(SetupState(link:link,problem:problem,
+ accessibilityTrusted:AXIsProcessTrusted(),
+ calibrating:calibrator.isActive,
+ calibrated:session?.calibrated == true,
+ holdProgress:session?.holdProgress ?? 0,
+ taps:setupTaps))
+ }
+}
+
+// MARK: - Menu bar and HUD
+
+extension App {
+ func installStatusBar(){
+ let bar=StatusBarController()
+ bar.onToggleControl={ [weak self] in
+ guard let self else{return}
+ self.homeControlAction()
+ }
+ bar.onRecenter={ [weak self] in self?.homeRecenter() }
+ bar.onPause={ [weak self] in self?.pause();self?.refreshHome() }
+ bar.onDisconnect={ [weak self] in self?.disconnectClosedCase() }
+ bar.onOpen={ [weak self] in self?.showPointerPage() }
+ bar.onCalibrate={ [weak self] in self?.recalibrate() }
+ bar.onSettings={ [weak self] in self?.openHomeSettings() }
+ bar.onQuit={ NSApp.terminate(nil) }
+ bar.onSpeedChange={ [weak self] speed in
+ guard let self else{return}
+ var value=self.homePointerSettings();value.speed=speed;self.applyHomePointerSettings(value)
+ }
+ statusBar=bar
+ }
+ var controlledScreen:NSScreen? {
+ let index=pointerSettings.screen
+ return NSScreen.screens.indices.contains(index) ? NSScreen.screens[index]:NSScreen.main
+ }
+ func refreshStatusBar(){
+ var status:MenuBarState.Status,detail:String
+ switch homePhase {
+ case .needsInputs:status = .notConnected;detail="Connect, then open the lid."
+ case .connecting:status = .connecting;detail="Keep the lid open for a moment."
+ case .needsAccessibility:status = .needsAccess;detail="Allow AirPointer in Accessibility to move the pointer."
+ case .closedCase(.openLid):status = .connecting;detail="Open the lid to connect."
+ case .closedCase(.closeLid):status = .connecting;detail="Close the lid."
+ case .closedCase(.turnUpright):status = .connecting;detail="Turn the closed case upright."
+ case .closedCase(.holdStill):status = .connecting;detail="Put the closed case on a flat surface."
+ case .closedCase(.calibrate):status = .connecting;detail="Point at the dots on your screen."
+ case .closedCase(.recenter):status = .connecting;detail="Point at the dot in the center of your screen."
+ case .ready:status = .ready;detail="Hold the closed case upright."
+ case .running:status = .live;detail="Press \(PointerShortcut.current.label) to pause from any app"
+ case .paused(let reason):status = .paused(reason=="Paused" ? "":reason);detail="Resume when you’re ready."
+ }
+ statusBar?.update(MenuBarState(status:status,detail:detail,speed:pointerSettings.speed,canDisconnect:closedCaseSession?.isActive == true))
+ announcePhaseChange()
+ }
+ // The HUD answers "what just happened?" on the screen being presented.
+ private func announcePhaseChange(){
+ guard homePhase != hudPhase else{return}
+ let previous=hudPhase;hudPhase=homePhase
+ // A session from the notch says it there; the HUD stays for a pointer on another screen.
+ if closedCaseSession?.usesNotch == true,let notch,notch.screen == controlledScreen{return}
+ switch (previous,homePhase) {
+ case (_,.running):hud.show("Pointing",live:true,on:controlledScreen)
+ case (.running,.paused(let reason)):
+ let short=reason=="Paused" || reason.isEmpty ? "":" — "+(reason.split(separator:".").first.map(String.init) ?? reason)
+ hud.show("Paused"+short,symbol:"pause.fill",on:controlledScreen)
+ case (.running,.needsInputs),(.paused,.needsInputs):hud.show("Disconnected — connect again, then open the lid",symbol:"xmark.circle",on:controlledScreen)
+ default:break
+ }
+ }
+}
diff --git a/StatusBarUI.swift b/StatusBarUI.swift
new file mode 100644
index 0000000..84ae012
--- /dev/null
+++ b/StatusBarUI.swift
@@ -0,0 +1,555 @@
+import AppKit
+import QuartzCore
+
+// The menu-bar item, its popover (the everyday control surface) and a brief
+// bubble that says what just happened.
+
+struct MenuBarState:Equatable {
+ enum Status:Equatable{case notConnected,connecting,needsAccess,ready,live,paused(String)}
+ var status:Status = .notConnected
+ var detail=""
+ var speed=1.0
+ var canDisconnect=false
+}
+enum MenuBarCommand{case toggleControl,recenter,pause,open,calibrate,disconnect,settings,quit}
+
+private enum MenuGlyph:Equatable{case off,idle,pending,live}
+private extension MenuBarState.Status {
+ var running:Bool{switch self{case .live,.connecting:return true;default:return false}}
+ var connected:Bool{switch self{case .notConnected,.connecting,.needsAccess:return false;default:return true}}
+ var glyph:MenuGlyph{switch self{case .notConnected:return .off;case .connecting:return .pending;case .live:return .live;default:return .idle}}
+ var title:String {
+ switch self {
+ case .notConnected:return "Not connected"
+ case .connecting:return "Connecting…"
+ case .needsAccess:return "Allow control"
+ case .ready:return "Ready"
+ case .live:return "Pointing"
+ case .paused:return "Paused"
+ }
+ }
+ var spoken:String {
+ switch self {
+ case .needsAccess:return "needs permission"
+ case .connecting:return "connecting"
+ default:return title.lowercased()
+ }
+ }
+ // Why the pointer is still, for the aim pad caption.
+ var reason:String {
+ switch self {
+ case .notConnected:return "AirPods not connected"
+ case .connecting:return "Waiting for AirPods motion…"
+ case .needsAccess:return "Allow Accessibility to move the pointer"
+ case .ready:return "Ready — switch on to start"
+ case .live:return ""
+ case .paused(let why):
+ let why=why.trimmingCharacters(in:.whitespacesAndNewlines)
+ return why.isEmpty || why == "Paused" ? "Paused":why.hasPrefix("Paused") ? why:"Paused — \(why)"
+ }
+ }
+}
+
+// Graphite stand-in for the accent color in the slider fill.
+private let menuFill=rkAdaptive("AirPointerMenuFill"){dark,contrast in dark ? NSColor(white:contrast ? 1:0.72,alpha:1):rkRGB(contrast ? 0x000000:0x1D1D1F)}
+
+private func menuFit(_ text:String,_ width:CGFloat,_ font:NSFont)->String {
+ let attributes:[NSAttributedString.Key:Any]=[.font:font]
+ guard (text as NSString).size(withAttributes:attributes).width>width else{return text}
+ var characters=Array(text)
+ while !characters.isEmpty && ((String(characters)+"…") as NSString).size(withAttributes:attributes).width>width{characters.removeLast()}
+ return String(characters).trimmingCharacters(in:.whitespaces)+"…"
+}
+
+// MARK: - Status item
+
+final class StatusBarController:NSObject,NSPopoverDelegate {
+ var onToggleControl,onRecenter,onPause,onOpen,onCalibrate,onDisconnect,onSettings,onQuit:(()->Void)?
+ var onSpeedChange:((Double)->Void)?
+ private let item:NSStatusItem
+ private let popover=NSPopover()
+ private let content=MenuBarContentController()
+ private var state=MenuBarState()
+ private var glyph:MenuGlyph?
+ private var iconAppearance:Int?
+ private var appearanceObservation:NSKeyValueObservation?
+ private var closedAt:CFTimeInterval=0
+ private var returnTo:NSRunningApplication?
+
+ override init() {
+ item=NSStatusBar.system.statusItem(withLength:NSStatusItem.squareLength)
+ super.init()
+ popover.behavior = .transient;popover.delegate=self;popover.contentViewController=content
+ content.onCommand={[weak self] in self?.run($0)}
+ content.onSpeedChange={[weak self] in self?.onSpeedChange?($0)}
+ if let button=item.button {
+ button.target=self;button.action=#selector(clicked);button.sendAction(on:[.leftMouseUp,.rightMouseUp])
+ button.imagePosition = .imageOnly
+ appearanceObservation=button.observe(\.effectiveAppearance){[weak self] _,_ in DispatchQueue.main.async{self?.refreshIcon()}}
+ }
+ refreshIcon()
+ }
+
+ // The closed case in outline, upright as it's held to point,
+ // with its pill-shaped ridge and a laser dot while live. Drawn for one
+ // appearance so light and dark menu bars each get their own ink; the red
+ // dot is why this can't be a template image.
+ private static func iconAppearanceKey(_ appearance:NSAppearance)->Int{
+ let name=appearance.bestMatch(from:[.aqua,.darkAqua,.vibrantLight,.vibrantDark,.accessibilityHighContrastAqua,.accessibilityHighContrastDarkAqua,
+ .accessibilityHighContrastVibrantLight,.accessibilityHighContrastVibrantDark]) ?? .aqua
+ let dark=[.darkAqua,.vibrantDark,.accessibilityHighContrastDarkAqua,.accessibilityHighContrastVibrantDark].contains(name)
+ let contrast=name.rawValue.contains("HighContrast")
+ return (dark ? 1:0) | (contrast ? 2:0)
+ }
+ static func menuBarImage(for status:MenuBarState.Status,appearance:NSAppearance)->NSImage {
+ let glyph=status.glyph,key=iconAppearanceKey(appearance)
+ let dark=key & 1 != 0,contrast=key & 2 != 0
+ // Matches the menu bar's own glyph ink, which labelColor only reaches through vibrancy.
+ let ink=NSColor(white:dark ? 1:0,alpha:glyph == .off ? 0.35:dark || contrast ? 1:0.85)
+ let image=NSImage(size:NSSize(width:18,height:18),flipped:true){_ in
+ appearance.performAsCurrentDrawingAppearance {
+ // The mark's proportions: 0.754 as wide as tall, the ridge 47% of the height, 68% across.
+ let body=NSRect(x:3.345,y:1.5,width:11.31,height:15)
+ let outline=NSBezierPath(roundedRect:body,xRadius:2.83,yRadius:2.83)
+ outline.lineWidth=1.5;ink.setStroke();outline.stroke()
+ // Solid rather than an outlined pill, which reads as a zero at this size.
+ let ridge=body.minX+body.width*0.68
+ ink.setFill();NSBezierPath(roundedRect:NSRect(x:ridge-0.8,y:body.midY-3.525,width:1.6,height:7.05),xRadius:0.8,yRadius:0.8).fill()
+ let dot=NSPoint(x:body.minX+body.width*0.34,y:body.midY)
+ switch glyph {
+ case .live:HomePalette.laser.setFill();NSBezierPath(ovalIn:NSRect(x:dot.x-2,y:dot.y-2,width:4,height:4)).fill()
+ case .pending:let ring=NSBezierPath(ovalIn:NSRect(x:dot.x-1.7,y:dot.y-1.7,width:3.4,height:3.4));ring.lineWidth=1.1;ring.stroke()
+ case .idle,.off:break
+ }
+ }
+ return true
+ }
+ image.isTemplate=false
+ return image
+ }
+
+ func showPopover() {
+ guard let button=item.button,!popover.isShown else{return}
+ let front=NSWorkspace.shared.frontmostApplication
+ returnTo=front == NSRunningApplication.current ? nil:front
+ content.apply(state)
+ popover.animates = !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
+ button.highlight(true)
+ // Shown before activating, so activation never switches Spaces away from a full-screen app.
+ popover.show(relativeTo:button.bounds,of:button,preferredEdge:.minY)
+ NSApp.activate()
+ popover.contentViewController?.view.window?.makeKey()
+ }
+ func update(_ state:MenuBarState) {
+ guard state != self.state else{return}
+ let statusChanged=state.status != self.state.status
+ self.state=state
+ if statusChanged{refreshIcon()}
+ if popover.isShown{content.apply(state)}
+ }
+ func updatePointer(_ point:CGPoint) {
+ guard popover.isShown else{return}
+ content.setPointer(point)
+ }
+
+ private func refreshIcon() {
+ guard let button=item.button else{return}
+ let status=state.status
+ let appearance=Self.iconAppearanceKey(button.effectiveAppearance)
+ // AppKit can notify effectiveAppearance while snapshotting a status item.
+ // Replacing its image for an equivalent palette schedules another snapshot.
+ if glyph != status.glyph || iconAppearance != appearance {
+ glyph=status.glyph;iconAppearance=appearance
+ button.image=Self.menuBarImage(for:status,appearance:button.effectiveAppearance)
+ }
+ let label="AirPointer, \(status.spoken)"
+ if button.accessibilityLabel() != label{button.setAccessibilityLabel(label);button.toolTip="AirPointer — \(status.title)"}
+ }
+ @objc private func clicked() {
+ if popover.isShown{popover.performClose(nil)}
+ else if CACurrentMediaTime()-closedAt>0.3{showPopover()}
+ }
+ private func run(_ command:MenuBarCommand) {
+ switch command {
+ case .toggleControl:onToggleControl?()
+ case .recenter:onRecenter?()
+ case .pause:onPause?()
+ case .open:dismiss(then:onOpen)
+ case .calibrate:dismiss(then:onCalibrate)
+ case .disconnect:onDisconnect?()
+ case .settings:dismiss(then:onSettings)
+ case .quit:dismiss(then:onQuit ?? {NSApp.terminate(nil)})
+ }
+ }
+ // Closes first so the window it opens comes up in front, and keeps focus here.
+ private func dismiss(then action:(()->Void)?) {
+ returnTo=nil;popover.close();item.button?.highlight(false)
+ action?()
+ }
+ func popoverDidShow(_ notification:Notification){item.button?.highlight(true)}
+ func popoverWillClose(_ notification:Notification){closedAt=CACurrentMediaTime()}
+ func popoverDidClose(_ notification:Notification) {
+ closedAt=CACurrentMediaTime();item.button?.highlight(false)
+ // Hand focus back to the previous app so its keys keep working.
+ if let app=returnTo,NSApp.isActive,!app.isTerminated{_=app.activate(from:.current,options:[])}
+ returnTo=nil
+ }
+}
+
+// MARK: - Popover content
+
+// Everything inside the popover; it needs no status item, so it can be
+// shown on its own for previews and checks.
+final class MenuBarContentController:NSViewController {
+ static let width:CGFloat=320
+ var onCommand:((MenuBarCommand)->Void)?
+ var onSpeedChange:((Double)->Void)?
+ private(set) var state:MenuBarState?
+ private let chip=StatusChip()
+ private let power=InkSwitch()
+ private let detail=rkLabel("",12,.regular,.secondaryLabelColor)
+ private let pad=AimPadView()
+ private let recenter=RemoteButton("Recenter",style:.secondary,symbol:"scope",height:32)
+ private let pause=RemoteButton("Pause",style:.secondary,hint:PointerShortcut.current.label,symbol:"pause.fill",height:32)
+ private let speed=NSSlider(value:1,minValue:0.4,maxValue:2.4,target:nil,action:nil)
+ private var powerHeld:CFTimeInterval=0,speedHeld:CFTimeInterval=0
+ private var layoutKey=""
+ private var resync:DispatchWorkItem?
+ private let inner=MenuBarContentController.width-32
+ private let body=NSView()
+ private var menuRows:[MenuRow]=[]
+
+ override func loadView() {
+ // The root carries NSViewController's preferredContentSize constraints and
+ // the popover's own sizing, so the content sizes itself in a top-anchored body.
+ let root=RemoteFlipped(frame:NSRect(x:0,y:0,width:Self.width,height:600))
+ body.translatesAutoresizingMaskIntoConstraints=false;root.addSubview(body)
+ NSLayoutConstraint.activate([
+ body.topAnchor.constraint(equalTo:root.topAnchor),body.leadingAnchor.constraint(equalTo:root.leadingAnchor),
+ body.widthAnchor.constraint(equalToConstant:Self.width),
+ ])
+
+ let title=rkLabel("AirPointer",15,.semibold)
+ title.setContentCompressionResistancePriority(.required,for:.horizontal)
+ power.setAccessibilityLabel("Pointer control")
+ power.onChange={[weak self] _ in self?.hold(\.powerHeld);self?.onCommand?(.toggleControl)}
+ let header=rkHStack([title,chip,rkSpacer(),power],spacing:8)
+ header.setCustomSpacing(10,after:title)
+
+ pad.cornerRadius=10;pad.setAccessibilityElement(true);pad.setAccessibilityRole(.image)
+ pad.heightAnchor.constraint(equalTo:pad.widthAnchor,multiplier:10.0/16).isActive=true
+
+ recenter.target=self;recenter.action=#selector(recenterPressed)
+ pause.target=self;pause.action=#selector(pausePressed)
+ let buttons=rkHStack([recenter,pause],spacing:8);buttons.distribution = .fillEqually
+
+ speed.target=self;speed.action=#selector(speedChanged);speed.isContinuous=true
+ speed.trackFillColor=menuFill;speed.setAccessibilityLabel("Pointer speed")
+ speed.setContentHuggingPriority(.init(1),for:.horizontal)
+ let slow=rkLabel("Slow",12,.regular,.secondaryLabelColor),fast=rkLabel("Fast",12,.regular,.secondaryLabelColor)
+ for label in [slow,fast]{label.setContentHuggingPriority(.required,for:.horizontal);label.setAccessibilityElement(false)}
+ let speedRow=rkHStack([slow,speed,fast],spacing:10)
+
+ let top=rkVStack([header,detail],spacing:2)
+ for view in top.arrangedSubviews{view.widthAnchor.constraint(equalTo:top.widthAnchor).isActive=true}
+ let column=rkVStack([top,pad,buttons,speedRow],spacing:0)
+ for view in column.arrangedSubviews{view.widthAnchor.constraint(equalTo:column.widthAnchor).isActive=true}
+ column.setCustomSpacing(12,after:top);column.setCustomSpacing(8,after:pad)
+ column.setCustomSpacing(16,after:buttons)
+ body.addSubview(column)
+
+ let rule=RemoteRule();rule.translatesAutoresizingMaskIntoConstraints=false;body.addSubview(rule)
+ let quitRule=RemoteRule();quitRule.translatesAutoresizingMaskIntoConstraints=false
+ menuRows=[
+ MenuRow("Open AirPointer",.open,target:self),MenuRow("Calibrate…",.calibrate,target:self),
+ MenuRow("Disconnect",.disconnect,target:self),MenuRow("Settings…",.settings,key:",",target:self),
+ MenuRow("Quit AirPointer",.quit,key:"q",target:self),
+ ]
+ let footer=rkVStack(Array(menuRows[0..<4])+[quitRule,menuRows[4]],spacing:0)
+ for row in menuRows{row.widthAnchor.constraint(equalTo:footer.widthAnchor).isActive=true}
+ footer.setCustomSpacing(4,after:menuRows[3]);footer.setCustomSpacing(4,after:quitRule)
+ body.addSubview(footer)
+ NSLayoutConstraint.activate([
+ column.topAnchor.constraint(equalTo:body.topAnchor,constant:16),
+ column.leadingAnchor.constraint(equalTo:body.leadingAnchor,constant:16),
+ column.trailingAnchor.constraint(equalTo:body.trailingAnchor,constant:-16),
+ rule.topAnchor.constraint(equalTo:column.bottomAnchor,constant:12),
+ rule.leadingAnchor.constraint(equalTo:body.leadingAnchor,constant:16),
+ rule.trailingAnchor.constraint(equalTo:body.trailingAnchor,constant:-16),
+ quitRule.leadingAnchor.constraint(equalTo:footer.leadingAnchor,constant:8),
+ quitRule.trailingAnchor.constraint(equalTo:footer.trailingAnchor,constant:-8),
+ footer.topAnchor.constraint(equalTo:rule.bottomAnchor,constant:6),
+ footer.leadingAnchor.constraint(equalTo:body.leadingAnchor,constant:8),
+ footer.trailingAnchor.constraint(equalTo:body.trailingAnchor,constant:-8),
+ footer.bottomAnchor.constraint(equalTo:body.bottomAnchor,constant:-8),
+ ])
+ view=root
+ }
+ // A row clicked just before the popover closed would otherwise reopen highlighted.
+ override func viewWillAppear(){super.viewWillAppear();for row in menuRows{row.hovering=false}}
+
+ // Diffs against what is on screen, so it is cheap to call on every tick.
+ func apply(_ state:MenuBarState){apply(state,force:false)}
+ func setPointer(_ point:CGPoint){if isViewLoaded && pad.point != point{pad.point=point}}
+
+ private func apply(_ state:MenuBarState,force:Bool) {
+ loadViewIfNeeded()
+ let old=self.state
+ guard force || state != old else{return}
+ self.state=state
+ let status=state.status,now=CACurrentMediaTime()
+ if force || old?.status != status {
+ let live=status == .live
+ chip.set(status.title,live:live,dot:status.connected)
+ if pad.live != live{pad.live=live}
+ let reason=status.reason
+ pad.caption=menuFit(reason,inner-24,.systemFont(ofSize:11,weight:.medium))
+ pad.toolTip=reason.isEmpty ? nil:reason
+ pad.setAccessibilityLabel(live ? "Pointer preview, live":"Pointer preview. \(reason)")
+ // A still pointer rests at the center; a paused one stays where it was aimed.
+ if !live{if case .paused=status{}else{pad.point=CGPoint(x:0.5,y:0.5)}}
+ if recenter.isEnabled != status.connected{recenter.isEnabled=status.connected}
+ if pause.isEnabled != status.running{pause.isEnabled=status.running}
+ }
+ // The key chip is for pausing, so it shows only while there is something to pause.
+ let hint=status.running ? PointerShortcut.current.label:nil
+ if pause.hint != hint{pause.hint=hint}
+ if now>=powerHeld && power.isOn != status.running{power.setOn(status.running,animated:old != nil)}
+ rkSetText(detail,state.detail)
+ if detail.toolTip != state.detail{detail.toolTip=state.detail.isEmpty ? nil:state.detail}
+ if detail.isHidden != state.detail.isEmpty{detail.isHidden=state.detail.isEmpty}
+ if now>=speedHeld && abs(speed.doubleValue-state.speed)>0.0001{speed.doubleValue=state.speed}
+ let spoken=String(format:"%.1f times normal",speed.doubleValue)
+ if speed.accessibilityValueDescription() != spoken{speed.setAccessibilityValueDescription(spoken)}
+ // Disconnect is there only while the closed case is connected.
+ if let row=menuRows.first(where:{$0.command == .disconnect}),row.isHidden == state.canDisconnect{row.isHidden = !state.canDisconnect}
+ let key="\(state.detail.isEmpty)|\(state.canDisconnect)"
+ if key != layoutKey{layoutKey=key;body.layoutSubtreeIfNeeded();preferredContentSize=NSSize(width:Self.width,height:ceil(body.fittingSize.height))}
+ }
+ // A control the user just changed keeps its new value briefly, so a
+ // state tick that predates the change can't flick it back.
+ private func hold(_ field:ReferenceWritableKeyPath<MenuBarContentController,CFTimeInterval>) {
+ self[keyPath:field]=CACurrentMediaTime()+0.8
+ resync?.cancel()
+ let work=DispatchWorkItem{[weak self] in
+ guard let self,let state=self.state else{return}
+ self.apply(state,force:true)
+ }
+ resync=work;DispatchQueue.main.asyncAfter(deadline:.now()+0.85,execute:work)
+ }
+ @objc private func recenterPressed(){onCommand?(.recenter)}
+ @objc private func pausePressed(){onCommand?(.pause)}
+ @objc private func speedChanged(){hold(\.speedHeld);onSpeedChange?(speed.doubleValue)}
+ @objc fileprivate func rowPressed(_ sender:MenuRow){onCommand?(sender.command)}
+}
+
+// An ink switch: NSSwitch can only draw in the system accent color.
+final class InkSwitch:NSView {
+ var onChange:((Bool)->Void)?
+ private(set) var isOn=false
+ var isEnabled=true{didSet{if isEnabled != oldValue{needsDisplay=true}}}
+ @objc dynamic var progress:CGFloat=0{didSet{needsDisplay=true}}
+ init(){super.init(frame:.zero);translatesAutoresizingMaskIntoConstraints=false;setContentHuggingPriority(.required,for:.horizontal)}
+ required init?(coder:NSCoder){fatalError("init(coder:) is not used")}
+ override class func defaultAnimation(forKey key:NSAnimatablePropertyKey)->Any? {
+ key == "progress" ? CABasicAnimation():super.defaultAnimation(forKey:key)
+ }
+ override var intrinsicContentSize:NSSize{NSSize(width:40,height:24)}
+ override var acceptsFirstResponder:Bool{isEnabled}
+ override func acceptsFirstMouse(for event:NSEvent?)->Bool{true}
+ func setOn(_ on:Bool,animated:Bool) {
+ guard on != isOn else{return}
+ isOn=on
+ if animated && window != nil && !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion {
+ NSAnimationContext.runAnimationGroup{context in context.duration=0.16;context.timingFunction=CAMediaTimingFunction(name:.easeOut);animator().progress=on ? 1:0}
+ } else{progress=on ? 1:0}
+ NSAccessibility.post(element:self,notification:.valueChanged)
+ }
+ private func toggle(){guard isEnabled else{return};setOn(!isOn,animated:true);onChange?(isOn)}
+ override func mouseDown(with event:NSEvent){toggle()}
+ override func keyDown(with event:NSEvent) {
+ if event.charactersIgnoringModifiers == " " || event.keyCode == 36{toggle()}else{super.keyDown(with:event)}
+ }
+ override var focusRingMaskBounds:NSRect{bounds}
+ override func drawFocusRingMask(){NSBezierPath(roundedRect:bounds,xRadius:bounds.height/2,yRadius:bounds.height/2).fill()}
+ override func draw(_ dirtyRect:NSRect) {
+ let match=effectiveAppearance.bestMatch(from:[.aqua,.darkAqua,.accessibilityHighContrastAqua,.accessibilityHighContrastDarkAqua])
+ let dark=match == .darkAqua || match == .accessibilityHighContrastDarkAqua
+ guard let context=NSGraphicsContext.current?.cgContext else{return}
+ context.saveGState();defer{context.restoreGState()}
+ if !isEnabled{context.setAlpha(0.4);context.beginTransparencyLayer(auxiliaryInfo:nil)}
+ let track=NSBezierPath(roundedRect:bounds.insetBy(dx:0.5,dy:0.5),xRadius:bounds.height/2-0.5,yRadius:bounds.height/2-0.5)
+ HomePalette.track.setFill();track.fill()
+ HomePalette.ink.withAlphaComponent(progress).setFill();track.fill()
+ if match == .accessibilityHighContrastAqua || match == .accessibilityHighContrastDarkAqua{HomePalette.rule.setStroke();track.lineWidth=1;track.stroke()}
+ let side=bounds.height-4
+ let knob=NSRect(x:2+(bounds.width-4-side)*progress,y:2,width:side,height:side)
+ NSGraphicsContext.saveGraphicsState()
+ if !dark{let shadow=NSShadow();shadow.shadowColor=NSColor.black.withAlphaComponent(0.22);shadow.shadowBlurRadius=2;shadow.shadowOffset=NSSize(width:0,height:-1);shadow.set()}
+ (dark && progress>0.5 ? HomePalette.canvas:NSColor(white:dark ? 0.92:1,alpha:1)).setFill()
+ NSBezierPath(ovalIn:knob).fill()
+ NSGraphicsContext.restoreGraphicsState()
+ if !isEnabled{context.endTransparencyLayer()}
+ }
+ override func isAccessibilityElement()->Bool{true}
+ override func accessibilityRole()->NSAccessibility.Role?{.checkBox}
+ override func accessibilitySubrole()->NSAccessibility.Subrole?{.switch}
+ override func accessibilityValue()->Any?{NSNumber(value:isOn ? 1:0)}
+ override func isAccessibilityEnabled()->Bool{isEnabled}
+ override func accessibilityPerformPress()->Bool{guard isEnabled else{return false};toggle();return true}
+}
+
+// A menu-style row: left-aligned title, optional shortcut, gray hover.
+private final class MenuRow:NSButton {
+ let command:MenuBarCommand
+ private let shortcut:String?
+ var hovering=false{didSet{if hovering != oldValue{needsDisplay=true}}}
+ private var area:NSTrackingArea?
+ init(_ title:String,_ command:MenuBarCommand,key:String?=nil,target:MenuBarContentController) {
+ self.command=command;shortcut=key.map{"⌘"+$0.uppercased()}
+ super.init(frame:.zero)
+ self.title=title;isBordered=false;setButtonType(.momentaryPushIn);translatesAutoresizingMaskIntoConstraints=false
+ self.target=target;action=#selector(MenuBarContentController.rowPressed(_:))
+ if let key{keyEquivalent=key;keyEquivalentModifierMask = .command}
+ }
+ required init?(coder:NSCoder){fatalError("init(coder:) is not used")}
+ override var intrinsicContentSize:NSSize{NSSize(width:NSView.noIntrinsicMetric,height:24)}
+ override func updateTrackingAreas() {
+ super.updateTrackingAreas()
+ if let area{removeTrackingArea(area)}
+ let next=NSTrackingArea(rect:.zero,options:[.mouseEnteredAndExited,.activeAlways,.inVisibleRect],owner:self,userInfo:nil)
+ addTrackingArea(next);area=next
+ }
+ override func mouseEntered(with event:NSEvent){hovering=true}
+ override func mouseExited(with event:NSEvent){hovering=false}
+ override var focusRingMaskBounds:NSRect{bounds}
+ override func drawFocusRingMask(){NSBezierPath(roundedRect:bounds,xRadius:6,yRadius:6).fill()}
+ override func draw(_ dirtyRect:NSRect) {
+ let pressed=cell?.isHighlighted == true
+ if isEnabled && (hovering || pressed) {
+ NSColor.labelColor.withAlphaComponent(pressed ? 0.14:0.08).setFill()
+ NSBezierPath(roundedRect:bounds,xRadius:6,yRadius:6).fill()
+ }
+ let font=NSFont.systemFont(ofSize:13)
+ let size=(title as NSString).size(withAttributes:[.font:font])
+ let y=floor((bounds.height-size.height)/2)
+ var trailing=bounds.width-8
+ if let shortcut {
+ let width=(shortcut as NSString).size(withAttributes:[.font:font]).width
+ trailing-=width
+ (shortcut as NSString).draw(at:NSPoint(x:trailing,y:y),withAttributes:[.font:font,.foregroundColor:NSColor.tertiaryLabelColor])
+ trailing-=12
+ }
+ let style=NSMutableParagraphStyle();style.lineBreakMode = .byTruncatingTail
+ (title as NSString).draw(in:NSRect(x:8,y:y,width:max(0,trailing-8),height:size.height),
+ withAttributes:[.font:font,.foregroundColor:isEnabled ? NSColor.labelColor:.tertiaryLabelColor,.paragraphStyle:style])
+ }
+}
+
+// MARK: - HUD
+
+// The bubble itself: a dark capsule with white text, an optional symbol
+// and a laser dot while live.
+final class ControlHUDView:NSView {
+ private(set) var text=""
+ private(set) var symbol:String?
+ private(set) var live=false
+ var maxWidth:CGFloat=480{didSet{invalidateIntrinsicContentSize()}}
+ private let font=NSFont.systemFont(ofSize:15,weight:.semibold)
+ private var image:NSImage?
+ override init(frame:NSRect){super.init(frame:frame);setAccessibilityElement(false)}
+ required init?(coder:NSCoder){fatalError("init(coder:) is not used")}
+ func set(_ text:String,symbol:String?,live:Bool) {
+ guard text != self.text || symbol != self.symbol || live != self.live else{return}
+ if symbol != self.symbol{image=symbol.flatMap{rkSymbol($0,15,.semibold)?.withSymbolConfiguration(.init(paletteColors:[.white]))}}
+ self.text=text;self.symbol=symbol;self.live=live
+ needsDisplay=true;invalidateIntrinsicContentSize()
+ }
+ private var leading:CGFloat{(live ? 16:0)+(image.map{$0.size.width+8} ?? 0)}
+ override var intrinsicContentSize:NSSize {
+ let width=ceil((text as NSString).size(withAttributes:[.font:font]).width)+leading+40
+ return NSSize(width:min(maxWidth,max(96,width)),height:40)
+ }
+ override func draw(_ dirtyRect:NSRect) {
+ let solid=NSWorkspace.shared.accessibilityDisplayShouldIncreaseContrast || NSWorkspace.shared.accessibilityDisplayShouldReduceTransparency
+ let shape=NSBezierPath(roundedRect:bounds.insetBy(dx:0.5,dy:0.5),xRadius:(bounds.height-1)/2,yRadius:(bounds.height-1)/2)
+ NSColor(white:0,alpha:solid ? 0.94:0.82).setFill();shape.fill()
+ NSColor(white:1,alpha:solid ? 0.45:0.14).setStroke();shape.lineWidth=1;shape.stroke()
+ let textWidth=ceil((text as NSString).size(withAttributes:[.font:font]).width)
+ var x=max(20,floor((bounds.width-textWidth-leading)/2))
+ if live {
+ let dot=NSRect(x:x,y:bounds.midY-4,width:8,height:8)
+ HomePalette.laser.withAlphaComponent(0.3).setFill();NSBezierPath(ovalIn:dot.insetBy(dx:-3,dy:-3)).fill()
+ HomePalette.laser.setFill();NSBezierPath(ovalIn:dot).fill()
+ x+=16
+ }
+ if let image {
+ image.draw(in:NSRect(x:x,y:floor(bounds.midY-image.size.height/2),width:image.size.width,height:image.size.height))
+ x+=image.size.width+8
+ }
+ let style=NSMutableParagraphStyle();style.lineBreakMode = .byTruncatingTail
+ let height=ceil(font.ascender-font.descender)
+ (text as NSString).draw(in:NSRect(x:x,y:floor((bounds.height-height)/2),width:max(0,bounds.width-x-20),height:height),
+ withAttributes:[.font:font,.foregroundColor:NSColor.white,.paragraphStyle:style])
+ }
+}
+
+private final class HUDPanel:NSPanel {
+ override var canBecomeKey:Bool{false}
+ override var canBecomeMain:Bool{false}
+}
+
+// A brief, click-through status bubble near the bottom of the screen that
+// floats over full-screen apps and never takes focus.
+final class ControlHUD {
+ private let panel=HUDPanel(contentRect:NSRect(x:0,y:0,width:160,height:40),styleMask:[.borderless,.nonactivatingPanel],backing:.buffered,defer:true)
+ private let bubble=ControlHUDView()
+ private var generation=0
+ private var hold:DispatchWorkItem?
+ init() {
+ panel.isOpaque=false;panel.backgroundColor = .clear;panel.hasShadow=true;panel.ignoresMouseEvents=true
+ panel.level = .statusBar;panel.collectionBehavior=[.canJoinAllSpaces,.fullScreenAuxiliary,.stationary,.ignoresCycle]
+ panel.isExcludedFromWindowsMenu=true;panel.hidesOnDeactivate=false;panel.isReleasedWhenClosed=false
+ panel.animationBehavior = .none;panel.alphaValue=0
+ panel.appearance=NSAppearance(named:.darkAqua);panel.contentView=bubble
+ }
+ func show(_ text:String,symbol:String?=nil,live:Bool=false,on screen:NSScreen?) {
+ guard let screen=screen ?? NSScreen.main ?? NSScreen.screens.first else{return}
+ generation+=1;hold?.cancel()
+ let area=screen.visibleFrame
+ bubble.maxWidth=min(480,area.width-64);bubble.set(text,symbol:symbol,live:live)
+ let size=bubble.intrinsicContentSize
+ let frame=NSRect(x:round(area.midX-size.width/2),y:round(area.minY+72),width:size.width,height:size.height)
+ let showing=panel.isVisible && panel.alphaValue>0.01
+ let still=NSWorkspace.shared.accessibilityDisplayShouldReduceMotion
+ if showing {
+ // Replace in place without fading from zero; new animations supersede a slide or fade in flight.
+ NSAnimationContext.runAnimationGroup{context in context.duration=still ? 0:0.15;panel.animator().setFrame(frame,display:true)}
+ NSAnimationContext.runAnimationGroup{context in context.duration=0.15;panel.animator().alphaValue=1}
+ } else {
+ panel.setFrame(still ? frame:frame.offsetBy(dx:0,dy:-8),display:true)
+ panel.alphaValue=0;panel.orderFrontRegardless()
+ NSAnimationContext.runAnimationGroup{context in
+ context.duration=0.15;context.timingFunction=CAMediaTimingFunction(name:.easeOut)
+ panel.animator().alphaValue=1
+ if !still{panel.animator().setFrame(frame,display:true)}
+ }
+ }
+ panel.invalidateShadow()
+ let generation=self.generation
+ let work=DispatchWorkItem{[weak self] in self?.fadeOut(generation)}
+ hold=work;DispatchQueue.main.asyncAfter(deadline:.now()+(showing ? 1.2:1.35),execute:work)
+ NSAccessibility.post(element:NSApp as Any,notification:.announcementRequested,
+ userInfo:[.announcement:text,.priority:NSAccessibilityPriorityLevel.high.rawValue])
+ }
+ private func fadeOut(_ generation:Int) {
+ guard generation == self.generation else{return}
+ NSAnimationContext.runAnimationGroup({context in
+ context.duration=0.3;context.timingFunction=CAMediaTimingFunction(name:.easeIn)
+ panel.animator().alphaValue=0
+ },completionHandler:{[weak self] in
+ guard let self,generation == self.generation else{return}
+ self.panel.orderOut(nil)
+ })
+ }
+}