Swift
Clean up the helper, the build, the checks and the license.
Andy Gao8ebd4d6969ec
diff --git a/Assets/LICENSE.md b/Assets/LICENSE.mdnew file mode 100644index 0000000..158b6e2--- /dev/null+++ b/Assets/LICENSE.md@@ -0,0 +1,11 @@+# License for this folder++The MIT License at the top of this project does not cover the files in this+folder.++- Apple owns the AirPods Pro 3 AR model. The case images and the images in+ `Readme/` include renders of it.+- The app icon and `CaseLid/lid.json` belong to AirPointer.+- The two sounds use parts from cuelume. See `TapClick/LICENSE-cuelume.txt`.++[README.md](README.md) lists each file and its source.diff --git a/Docs/DESIGN-SYSTEM.md b/Docs/DESIGN-SYSTEM.mdindex cae36fb..cf62bd0 100644--- a/Docs/DESIGN-SYSTEM.md+++ b/Docs/DESIGN-SYSTEM.md@@ -41,7 +41,7 @@ Never show or describe tapping the back of the case, holding the open case uprig| Menu-bar popover | Live aim pad, Recenter, Pause, speed, then menu rows: Open AirPointer, Calibrate…, Disconnect (only while the closed case is connected), Settings…, Quit. | 320 wide || Control HUD | A small non-activating capsule: "Pointing", "Paused — reason", "Disconnected — connect again, then open the lid". | 40 tall, ≤ 480 wide || Sheets | Attached to the main window, for a task that starts there. None are in use. | ≈ 420 wide |-| Developer tools | Keep sound and mic on Mac and the tap test window. Under **File ▸ Developer** only; never linked from the main flows. The test window uses the same parts as the product: a DEVELOPER eyebrow and status chip, a 22 pt title, one primary bottom-right. | 480 × 440 |+| Developer tools | Keep audio on Mac and the tap test window. Under **File ▸ Developer** only; never linked from the main flows. The test window uses the same parts as the product: a DEVELOPER eyebrow and status chip, a 22 pt title, one primary bottom-right. | 480 × 440 |A flow should never open a second regular window to finish a task that started in the main window. Use the overlay, a sheet, or the page itself.diff --git a/LICENSE b/LICENSEindex 0b95100..e4cbf17 100644--- a/LICENSE+++ b/LICENSE@@ -1,6 +1,3 @@-The MIT License below covers the code in this repository. It does not cover the-Assets folder. See Assets/README.md for the owners and terms of those files.-MIT LicenseCopyright (c) 2026 Andy Gaodiff --git a/README.md b/README.mdindex 4321f7d..0345de3 100644--- a/README.md+++ b/README.md@@ -21,6 +21,7 @@| **AirPods settings** | Some AirPods connection settings stay as the session set them. We do not know yet if this change, or the case data change, lasts after the Bluetooth link resets. || **Audio** | Each connection drops the AirPods' Bluetooth link for a moment, and their audio stops. Do not connect during a call. || **Microphone** | During a session, the app keeps Mac sound and the microphone off all AirPods. It restores them when the session ends. |+| **Silent audio** | During a session, the app plays silence to the AirPods to keep their audio link active. You do not hear it. || **Cursor size** | A cursor smaller than 2× grows to 2× while you point. It returns to its size when you pause or disconnect. After a force quit, it returns when you next open the app. This uses a private macOS call. |## Requirements@@ -47,7 +48,8 @@ zsh ./build.shopen AirPointer.app```-The build also runs the offline checks. Do not build during a pointer session.+The build also runs `--self-test` and the tap check. The other offline checks are+under [For developers](#for-developers). Do not build during a pointer session.If AirPointer does not appear in the Accessibility list after a rebuild, run:@@ -79,7 +81,8 @@ different shortcut, go to Settings.<img src="Assets/Readme/screens.png" width="100%" alt="The AirPointer window, the menu bar panel, and the notch while pointing"></p>-A session ends 30 minutes after the lid closes. To continue, open and close the lid.+On the tested AirPods, a session ends about 30 minutes after the lid closes. The app+does not set this limit. To continue, open and close the lid.<details><summary><strong>The connect steps as a chart</strong></summary>@@ -171,7 +174,7 @@ Sources/App/ Startup, the link to the windows, and the shortcutSession/ The session, motion math, taps, audio guard, cursor sizeInterface/ The window, menu bar, notch, setup and Tap Test- Checks/ Offline checks, built into the app+ Checks/ Window and pose checks; other checks sit beside their codeClosedCaseMotion/ The helper that talks to the AirPodsClosedCaseRestore/ The helper that brings the Bluetooth link upTests/ Recorded taps and handling for the tap check@@ -204,7 +207,7 @@ send any of this anywhere.In a session's `native.log`:- `STEP` lines show the time of each connection step.-- `HOLD` lines show the motion rate and delay, about once a second.+- `HOLD` lines show the motion count so far and its delay, about once a second.- `tap` lines explain each tap.- The `EXIT` line shows why the session ended.@@ -218,8 +221,8 @@ Taps are tuned on one person so far, so your score may differ.Connect, then go to **File > Developer > Tap Test**. The test takes about 75seconds and tells you when to tap.-To also save a session's raw motion, run this before you connect. A session-records up to about 20 MB.+To also save a session's raw motion, run this before you connect. The recording has+no size limit. Expect roughly 20 MB for a 30-minute session.```shdefaults write local.airpointer recordMotion -bool true@@ -230,9 +233,11 @@ defaults write local.airpointer recordMotion -bool true<details><summary><strong>Offline checks</strong></summary>-These checks do not use Bluetooth.+These checks do not use Bluetooth. `--check-home` opens real windows, so run it on+a logged-in Mac.```sh+AirPointer.app/Contents/MacOS/AirPointer --self-testAirPointer.app/Contents/MacOS/AirPointer --check-homeAirPointer.app/Contents/MacOS/AirPointer --check-pointer-settingsAirPointer.app/Contents/MacOS/AirPointer --check-closed-case-native@@ -258,4 +263,4 @@ tccutil reset BluetoothAlways local.airpointerThe code uses the [MIT License](LICENSE). The license does not cover `Assets/`.Apple owns the AirPods model that the case images are made from, and the sounds-have their own license. See [Assets/README.md](Assets/README.md).+have their own license. See [Assets/LICENSE.md](Assets/LICENSE.md).diff --git a/Sources/AirPointer/App/AirPointer.swift b/Sources/AirPointer/App/AirPointer.swiftindex 4d56e71..699c3fd 100644--- a/Sources/AirPointer/App/AirPointer.swift+++ b/Sources/AirPointer/App/AirPointer.swift@@ -99,7 +99,7 @@ final class App: NSObject, NSApplicationDelegate {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+ let macAudio=item("Keep audio on Mac",#selector(toggleMacAudioProtection));macAudio.state = .ondeveloper.addItem(macAudio);macAudioProtectionItem=macAudiodeveloper.addItem(item("Tap Test…",#selector(showTapTest)))let edit=addMenu("Edit")@@ -177,9 +177,9 @@ if CommandLine.arguments.contains("--check-audio-output-policy") {} 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))+ selfCheck(screenPoint(CGPoint(x: 0.5, y: 0.5), bounds: bounds) == CGPoint(x: -960, y: 540))+ selfCheck(screenPoint(.zero, bounds: bounds) == CGPoint(x: -1919, y: 1))+ selfCheck(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)}diff --git a/Sources/AirPointer/Checks/Checks.swift b/Sources/AirPointer/Checks/Checks.swiftindex f7b5e8f..eff78f8 100644--- a/Sources/AirPointer/Checks/Checks.swift+++ b/Sources/AirPointer/Checks/Checks.swift@@ -1,9 +1,14 @@import Foundation+// A failed check names its line. A plain precondition traps with no message in an optimized build.+func selfCheck(_ condition:@autoclosure()->Bool,_ message:String="",file:StaticString=#fileID,line:UInt=#line) {+ guard !condition() else{return}+ fputs("Check failed at \(file):\(line) \(message)\n",stderr);exit(1)+}func runPoseChecks() {func rotation(_ v:V3)->Pose {let a=v.length;guard a>0 else{return Pose(w:1,x:0,y:0,z:0)};let s=sin(a/2)/a;return Pose(w:cos(a/2),x:v.x*s,y:v.y*s,z:v.z*s)}let neutral=rotation(V3(x:0.6,y:-0.8,z:1.2))let turn=V3(x:0.25,y:0.08,z:-0.03),found=neutral.multiplied(by:rotation(turn)).rotation(from:neutral)- precondition(abs(found.x-turn.x)<1e-7 && abs(found.y-turn.y)<1e-7 && abs(found.z-turn.z)<1e-7)+ selfCheck(abs(found.x-turn.x)<1e-7 && abs(found.y-turn.y)<1e-7 && abs(found.z-turn.z)<1e-7)let signFlipped=Pose(w:-neutral.w,x:-neutral.x,y:-neutral.y,z:-neutral.z)- precondition(Pose.mean([neutral,signFlipped])!.rotation(from:neutral).length<1e-7)+ selfCheck(Pose.mean([neutral,signFlipped])!.rotation(from:neutral).length<1e-7)}diff --git a/Sources/AirPointer/Interface/AccessibilityGuide.swift b/Sources/AirPointer/Interface/AccessibilityGuide.swiftindex 5ef00ab..f92c1f2 100644--- a/Sources/AirPointer/Interface/AccessibilityGuide.swift+++ b/Sources/AirPointer/Interface/AccessibilityGuide.swift@@ -32,8 +32,10 @@ final class AccessibilityGuide {if ProcessInfo.processInfo.systemUptime-openedAt>Self.giveUpAfter{stop()}else{panel.orderOut(nil)}return}+ // Only list windows while System Settings is in front, since the panel has nothing to follow otherwise.+ guard app.isActive else{panel.orderOut(nil);return}let windows=CGWindowListCopyWindowInfo([.optionOnScreenOnly,.excludeDesktopElements],kCGNullWindowID) as? [[String:Any]] ?? []- guard app.isActive,let settings=Self.settingsWindow(in:windows,owner:app.processIdentifier,primaryHeight:NSScreen.screens.first?.frame.maxY ?? 0) else{+ guard let settings=Self.settingsWindow(in:windows,owner:app.processIdentifier,primaryHeight:NSScreen.screens.first?.frame.maxY ?? 0) else{panel.orderOut(nil);return}let frame=Self.placement(settings)diff --git a/Sources/AirPointer/Interface/AirPointerHome.swift b/Sources/AirPointer/Interface/AirPointerHome.swiftindex fa8daf8..5ca737b 100644--- a/Sources/AirPointer/Interface/AirPointerHome.swift+++ b/Sources/AirPointer/Interface/AirPointerHome.swift@@ -245,7 +245,7 @@ final class AirPointerHome:NSObject,NSWindowDelegate {private var controlKey:HomeControlKey?init(pad:AimPadView=AimPadView()) {- self.pad=pad+ self.pad=pad;pad.setAccessibilityElement(true);pad.setAccessibilityRole(.image)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@@ -456,7 +456,7 @@ private final class PointerPage:NSObject {showingPad=connectedhome.pad.isHidden = !connected;art.isHidden=connected}- home.pad.live=live+ home.pad.live=live;home.pad.setAccessibilityLabel(live ? "Pointer preview, live":"Pointer preview")let screens=home.pointerSettings.screenshome.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.diff --git a/Sources/AirPointer/Interface/NotchFlow.swift b/Sources/AirPointer/Interface/NotchFlow.swiftindex 950cc91..925afdb 100644--- a/Sources/AirPointer/Interface/NotchFlow.swift+++ b/Sources/AirPointer/Interface/NotchFlow.swift@@ -195,7 +195,12 @@ final class NotchSurface:NSView {func show(_ content:NotchContent,fade:Bool) {art.step=content.step;rkSetText(title,content.title);rkSetText(detail,content.detail)progress.filled=content.progress;progress.isHidden=content.progress==nil;dot.isHidden = !content.live- setAccessibilityValue(content.title+". "+content.detail)+ let spoken=content.title+". "+content.detail+ // The notch never takes focus, so VoiceOver only hears a new step if it's announced.+ if accessibilityValue() as? String != spoken{+ NSAccessibility.post(element:NSApp as Any,notification:.announcementRequested,userInfo:[.announcement:spoken,.priority:NSAccessibilityPriorityLevel.high.rawValue])+ }+ setAccessibilityValue(spoken)needsLayout=trueif fade{contents.alphaValue=0.15;NSAnimationContext.runAnimationGroup{context in context.duration=0.18;contents.animator().alphaValue=1}}}diff --git a/Sources/AirPointer/Session/AudioOutputGuard.swift b/Sources/AirPointer/Session/AudioOutputGuard.swiftindex 92f6330..1a8cec7 100644--- a/Sources/AirPointer/Session/AudioOutputGuard.swift+++ b/Sources/AirPointer/Session/AudioOutputGuard.swift@@ -216,38 +216,38 @@ func runAudioOutputPolicyChecks(){let pods=PointerAudioDevice(id:3,uid:"01-23-45-67-89-AB:output",name:"My pointer",transport:kAudioDeviceTransportTypeBluetooth)let other=PointerAudioDevice(id:4,uid:"other",name:"Headphones",transport:kAudioDeviceTransportTypeBluetooth)var policy=PointerAudioOutputPolicy(targetAddress:"01:23:45:67:89:ab")- precondition(policy.isAirPods(pods) && !policy.isAirPods(other))- precondition(policy.replacement(for:.playback,current:pods,devices:[pods,speakers,usb])?.id==speakers.id)- precondition(policy.replacement(for:.playback,current:usb,devices:[pods,speakers,usb])==nil)- precondition(policy.replacement(for:.playback,current:pods,devices:[pods,speakers,usb])?.id==usb.id)+ selfCheck(policy.isAirPods(pods) && !policy.isAirPods(other))+ selfCheck(policy.replacement(for:.playback,current:pods,devices:[pods,speakers,usb])?.id==speakers.id)+ selfCheck(policy.replacement(for:.playback,current:usb,devices:[pods,speakers,usb])==nil)+ selfCheck(policy.replacement(for:.playback,current:pods,devices:[pods,speakers,usb])?.id==usb.id)let reconnected=PointerAudioDevice(id:22,uid:"usb",name:"USB speakers",transport:kAudioDeviceTransportTypeUSB)- precondition(policy.replacement(for:.playback,current:pods,devices:[pods,speakers,reconnected])?.id==22)- precondition(policy.replacement(for:.playback,current:pods,devices:[pods,speakers])?.id==speakers.id)- precondition(policy.replacement(for:.playback,current:other,devices:[pods,speakers,other])==nil)- precondition(policy.replacement(for:.playback,current:pods,devices:[pods,speakers,other])?.id==other.id)- precondition(policy.replacement(for:.systemSounds,current:pods,devices:[pods,speakers,usb])?.id==speakers.id)- precondition(policy.replacement(for:.playback,current:pods,devices:[pods])==nil)+ selfCheck(policy.replacement(for:.playback,current:pods,devices:[pods,speakers,reconnected])?.id==22)+ selfCheck(policy.replacement(for:.playback,current:pods,devices:[pods,speakers])?.id==speakers.id)+ selfCheck(policy.replacement(for:.playback,current:other,devices:[pods,speakers,other])==nil)+ selfCheck(policy.replacement(for:.playback,current:pods,devices:[pods,speakers,other])?.id==other.id)+ selfCheck(policy.replacement(for:.systemSounds,current:pods,devices:[pods,speakers,usb])?.id==speakers.id)+ selfCheck(policy.replacement(for:.playback,current:pods,devices:[pods])==nil)let named=PointerAudioDevice(id:5,uid:"different",name:"Renamed AirPods Pro",transport:kAudioDeviceTransportTypeBluetoothLE)- precondition(PointerAudioOutputPolicy(targetAddress:nil).isAirPods(named))+ selfCheck(PointerAudioOutputPolicy(targetAddress:nil).isAirPods(named))let podsMic=PointerAudioDevice(id:6,uid:"01-23-45-67-89-AB:input",name:"My pointer",transport:kAudioDeviceTransportTypeBluetooth,playback:false,systemSounds:false,input:true)let macMic=PointerAudioDevice(id:7,uid:"BuiltInMicrophoneDevice",name:"Mac microphone",transport:kAudioDeviceTransportTypeBuiltIn,playback:false,systemSounds:false,input:true)let usbMic=PointerAudioDevice(id:8,uid:"usb-mic",name:"USB microphone",transport:kAudioDeviceTransportTypeUSB,playback:false,systemSounds:false,input:true)var microphones=PointerAudioOutputPolicy(targetAddress:"01:23:45:67:89:ab")- precondition(microphones.replacement(for:.input,current:podsMic,devices:[podsMic,macMic,usbMic])?.id==macMic.id)- precondition(microphones.replacement(for:.input,current:podsMic,devices:[podsMic,speakers])==nil)- precondition(microphones.replacement(for:.input,current:usbMic,devices:[podsMic,macMic,usbMic])==nil)- precondition(microphones.replacement(for:.input,current:podsMic,devices:[podsMic,macMic,usbMic])?.id==usbMic.id)+ selfCheck(microphones.replacement(for:.input,current:podsMic,devices:[podsMic,macMic,usbMic])?.id==macMic.id)+ selfCheck(microphones.replacement(for:.input,current:podsMic,devices:[podsMic,speakers])==nil)+ selfCheck(microphones.replacement(for:.input,current:usbMic,devices:[podsMic,macMic,usbMic])==nil)+ selfCheck(microphones.replacement(for:.input,current:podsMic,devices:[podsMic,macMic,usbMic])?.id==usbMic.id)var session=PointerAudioOutputPolicy(targetAddress:"01:23:45:67:89:ab")- precondition(session.restoration(for:.playback,current:speakers,devices:[pods,speakers])==nil)- precondition(session.replacement(for:.playback,current:pods,devices:[pods,speakers])?.id==speakers.id)- precondition(session.restoration(for:.playback,current:speakers,devices:[pods,speakers])?.id==pods.id)- precondition(session.restoration(for:.playback,current:speakers,devices:[pods,speakers])==nil)+ selfCheck(session.restoration(for:.playback,current:speakers,devices:[pods,speakers])==nil)+ selfCheck(session.replacement(for:.playback,current:pods,devices:[pods,speakers])?.id==speakers.id)+ selfCheck(session.restoration(for:.playback,current:speakers,devices:[pods,speakers])?.id==pods.id)+ selfCheck(session.restoration(for:.playback,current:speakers,devices:[pods,speakers])==nil)_ = session.replacement(for:.playback,current:pods,devices:[pods,speakers])- precondition(session.restoration(for:.playback,current:usb,devices:[pods,speakers,usb])==nil)+ selfCheck(session.restoration(for:.playback,current:usb,devices:[pods,speakers,usb])==nil)_ = session.replacement(for:.playback,current:pods,devices:[pods,speakers])- precondition(session.restoration(for:.playback,current:speakers,devices:[speakers])==nil)+ selfCheck(session.restoration(for:.playback,current:speakers,devices:[speakers])==nil)_ = session.replacement(for:.input,current:podsMic,devices:[podsMic,macMic])- precondition(session.restoration(for:.playback,current:speakers,devices:[pods,speakers])==nil)- precondition(session.restoration(for:.input,current:macMic,devices:[podsMic,macMic])?.id==podsMic.id)+ selfCheck(session.restoration(for:.playback,current:speakers,devices:[pods,speakers])==nil)+ selfCheck(session.restoration(for:.input,current:macMic,devices:[podsMic,macMic])?.id==podsMic.id)print("PASS: AirPods UID matching, renamed devices, speaker fallback, independent playback/alerts, preferred-output changes, reconnect IDs, the default input moved off the AirPods, and only what moved going back unless changed since")}diff --git a/Sources/AirPointer/Session/ClosedCaseAirPods.swift b/Sources/AirPointer/Session/ClosedCaseAirPods.swiftindex 8699d9c..f6aaaf0 100644--- a/Sources/AirPointer/Session/ClosedCaseAirPods.swift+++ b/Sources/AirPointer/Session/ClosedCaseAirPods.swift@@ -74,18 +74,26 @@ struct ClosedCaseAirPods:Equatable {// Asks the system on a utility queue and answers on the main one; nil when it couldn't be read.static func survey(completion:@escaping(Survey?)->Void) {DispatchQueue.global(qos:.userInitiated).async{- let process=Process(),output=Pipe()- process.executableURL=URL(fileURLWithPath:"/usr/sbin/system_profiler")- process.arguments=["SPBluetoothDataType","-json"]- process.standardOutput=output;process.standardError=FileHandle.nullDevice- var result:Survey?- if (try? process.run()) != nil {- let data=output.fileHandleForReading.readDataToEndOfFile();process.waitUntilExit()- if process.terminationStatus==0{result=parse(data)}- }+ let result=toolOutput("/usr/sbin/system_profiler",["SPBluetoothDataType","-json"],timeout:20).flatMap{parse($0)}DispatchQueue.main.async{completion(result)}}}+ // A system tool's output, or nil if it fails or outlasts the timeout, so a hung tool can't leave Connect waiting.+ static func toolOutput(_ path:String,_ arguments:[String],timeout:TimeInterval)->Data? {+ let process=Process(),output=Pipe()+ process.executableURL=URL(fileURLWithPath:path);process.arguments=arguments+ process.standardOutput=output;process.standardError=FileHandle.nullDevice+ guard (try? process.run()) != nil else{return nil}+ var data=Data();let finished=DispatchSemaphore(value:0)+ DispatchQueue.global(qos:.userInitiated).async{+ data=output.fileHandleForReading.readDataToEndOfFile();process.waitUntilExit();finished.signal()+ }+ guard finished.wait(timeout:.now()+timeout) == .success else{+ if process.isRunning{process.terminate()}+ return nil+ }+ return process.terminationStatus==0 ? data:nil+ }static let bluetoothDenied="AirPointer needs Bluetooth to reach your AirPods. Allow it in System Settings → Privacy & Security → Bluetooth, then connect again."// ClosedCaseRestore's exit codes, in plain words.static func restoreFailure(_ status:Int32)->String {@@ -124,7 +132,7 @@ struct ClosedCaseAirPods:Equatable {case 32:return "These earbuds don’t report as AirPods Pro. The closed-case pointer needs AirPods Pro."case 34:return "The case didn’t report as an AirPods charging case. Use the case that came with these AirPods, then connect again."case 35:return "The charging case stopped responding. Connect again, then open the lid."- case 36:return "The charging case wouldn’t stay connected. Open the lid, wait a few seconds, then connect again."+ case 36:return "The charging case turned down AirPointer’s request. Open the lid, wait a few seconds, then connect again."case 40:return "Your AirPods stopped answering. Connect again, then open the lid."case 41:return "Your AirPods sent something unexpected, so AirPointer stopped to be safe. Connect again, then open the lid."case 42:return "AirPointer couldn’t send to your AirPods. Connect again, then open the lid. If it keeps happening, turn Bluetooth off and on."diff --git a/Sources/AirPointer/Session/ClosedCaseSession.swift b/Sources/AirPointer/Session/ClosedCaseSession.swiftindex 39c760d..45c54eb 100644--- a/Sources/AirPointer/Session/ClosedCaseSession.swift+++ b/Sources/AirPointer/Session/ClosedCaseSession.swift@@ -262,6 +262,10 @@ func runClosedCaseNativeChecks() throws {let temporary=FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString,isDirectory:true)try FileManager.default.createDirectory(at:temporary,withIntermediateDirectories:true)defer{try? FileManager.default.removeItem(at:temporary)}+ guard ClosedCaseAirPods.toolOutput("/bin/echo",["ok"],timeout:5)==Data("ok\n".utf8) else{throw LessonError.message("A system tool’s output should come back.")}+ guard ClosedCaseAirPods.toolOutput("/usr/bin/false",[],timeout:5)==nil else{throw LessonError.message("A failed system tool should give nothing.")}+ let toolBegan=ProcessInfo.processInfo.systemUptime+ guard ClosedCaseAirPods.toolOutput("/bin/sleep",["5"],timeout:0.2)==nil,ProcessInfo.processInfo.systemUptime-toolBegan<2 else{throw LessonError.message("A hung system tool should time out.")}let first=Data("1,11,1000000,1,0,0,100000\n".utf8)let pipe=Pipe();defer{try? pipe.fileHandleForReading.close();try? pipe.fileHandleForWriting.close()}let flags=fcntl(pipe.fileHandleForReading.fileDescriptor,F_GETFL)diff --git a/Sources/ClosedCaseMotion/CaseSustainedRenewal.m b/Sources/ClosedCaseMotion/CaseSustainedRenewal.mindex 417710c..acdb4ce 100644--- a/Sources/ClosedCaseMotion/CaseSustainedRenewal.m+++ b/Sources/ClosedCaseMotion/CaseSustainedRenewal.m@@ -118,9 +118,8 @@ static BOOL motionOnStdout=NO;// recorded even while the main thread is inside a synchronous Bluetooth call).// The main thread notices it within one 20-50 ms pump and runs the ordinary// cleanup path with shortened waits, then returns SIGNALED.-// Repeated signals are expected (the app re-sends SIGTERM on every tick once a-// stop is 8 s old), so only the first one counts and later ones never cut the-// cleanup short. Because SIGTERM no longer kills the process outright, a+// The app sends one SIGTERM, 3 s after a stop. Only the first signal counts, so+// a repeat from anywhere else never cuts the cleanup short. Because SIGTERM no longer kills the process outright, a// watchdog armed by that first signal exits with CLEANUP_TIMEOUT if the main// thread is still busy 30 s later (longer than the worst-case link restore of// about 23 s, so it only fires when the main thread is really stuck).@@ -686,8 +685,8 @@ static uint16_t nextIdentifier(uint16_t current) {return current==UINT16_MAX ? 1// distinguish Abandon from completion, so staged analytics are consumed.// Skipping the Abandon would leave the case's own 480 s active-transfer watchdog to end the transfer on// its "unsuccessful, restore the records" path, but the case would stay awake-// until then; that trade is the product owner's. The same watchdog may also-// end a held asset during a session longer than 8 minutes (not yet measured).+// until then; that trade is the product owner's. Sessions on the tested pair ran+// past that watchdog while holding the asset, to about 30 minutes.- (void)beginCleanup:(double)now {self.cleanupStarted=YES;if(!self.accepted || !self.caseActive) return;uint8_t body[]={self.assetID>>8,self.assetID,0,3};@@ -704,12 +703,16 @@ static NSData *varintData(uint32_t value) {// The sequence carries on across sessions, so it lives in the app's data folder,// beside the target file rather than wherever the helper happened to be started.static NSString *sensorSequencePath=nil;+// Set only when the file couldn't be written, so one session never repeats a number.+static unsigned unsavedSensorSequence=0;static NSData *sensorSetting(uint8_t service,uint32_t interval) {NSString *path=sensorSequencePath;NSString *saved=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];- unsigned sequence=[saved intValue];+ unsigned sequence=unsavedSensorSequence?:[saved intValue];sequence=sequence<8000 || sequence>=16000 ? 8001 : sequence+1;- [[NSString stringWithFormat:@"%u",sequence] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];+ BOOL written=[[NSString stringWithFormat:@"%u",sequence] writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];+ unsavedSensorSequence=written?0:sequence;+ if(!written) printf("sensor sequence not saved\n");uint8_t setting[]={8,service,16,2,26,5,1,(uint8_t)interval,(uint8_t)(interval>>8),(uint8_t)(interval>>16),(uint8_t)(interval>>24)};uint8_t tag=8;NSMutableData *message=[NSMutableData dataWithBytes:&tag length:1];[message appendData:varintData(sequence)];uint8_t field[]={66,sizeof(setting)};[message appendBytes:field length:sizeof(field)];[message appendBytes:setting length:sizeof(setting)];@@ -756,6 +759,8 @@ static BOOL phaseIsStop(NSURL *phaseURL) {}static int runPointerSession(CBL2CAPChannel *channel, NSURL *directory) {double began=NSProcessInfo.processInfo.systemUptime;+ // Only bounds setup. The live loop moves this to now+15 on every pass, so a+ // session has no fixed length here.operationDeadline=began+720;ConsoleReader *reader=ConsoleReader.new;NSInputStream *input=channel.inputStream;NSOutputStream *output=channel.outputStream;@@ -798,6 +803,7 @@ static int runPointerSession(CBL2CAPChannel *channel, NSURL *directory) {if(exitCode) printf("Session setup ended: %s\n",reason.UTF8String);NSURL *phaseURL=[directory URLByAppendingPathComponent:@"phase.txt"];double nextStatus=0;NSUInteger publishedStates=0;BOOL publishedBaseline=NO;+ // The deadline moves on every pass, so this only ends a session if one pass stalls for about 9 s.while(sensorsStarted && !exitCode && NSProcessInfo.processInfo.systemUptime<operationDeadline-6) { @autoreleasepool {if(terminationRequested()) {exitCode=HelperExitSignaled;reason=@"termination signal";break;}// Before any write this cycle: a channel the link already closed ends the session as INPUT_ENDED.@@ -854,7 +860,6 @@ static int runPointerSession(CBL2CAPChannel *channel, NSURL *directory) {if(fresh && transfer.rootVerified && !baselineVerified) step("open baseline verified");if(fresh && transfer.rootVerified) baselineVerified=YES;}- if(transfer.closedWindowStarted && now>=operationDeadline-6) {reason=@"confirmed closed deadline with cleanup reserve";break;}if(transfer.error) {reason=transfer.error;break;}// A new in-case report goes out at once: the app confirms the closed lid from it.if(reader.earbudStateEvents.count!=publishedStates) nextStatus=0;@@ -1155,6 +1160,9 @@ static void hardeningChecks(void) {assetOnly.offer=testOffer(9,35);assetOnly.offerMetadata=mticOffer(assetOnly.offer);[assetOnly tick:NSProcessInfo.processInfo.systemUptime];mark=wireLength(assetOnly.output);stopSensorsThenRelease(assetOnly.output,assetOnly,NO,NO,&accelStop,&gyroStop);frames=wireFramesSince(assetOnly.output,mark);check(frames.count==1 && frameAt(frames,0).childType==9 && !accelStop && !gyroStop,@"sensors that were never started get no STOP; the held asset is still released");+ sensorSequencePath=@"/nonexistent-closed-case-folder/sequence.txt";+ check(![sensorSetting(11,5000) isEqualToData:sensorSetting(11,5000)],@"a sequence file that can't be written never repeats a number");+ unsavedSensorSequence=0;[NSFileManager.defaultManager removeItemAtPath:sequenceFile error:nil];sensorSequencePath=nil;// Stop requests written while the helper starts are honoured, not overwritten.@@ -1174,7 +1182,7 @@ static void hardeningChecks(void) {while(!terminationRequested() && NSProcessInfo.processInfo.systemUptime<until) pump(.01);check(atomic_load(&terminationSignal)==signals[i] && terminationNoticedAt>0,[NSString stringWithFormat:@"signal %d runs the cleanup path instead of terminating",signals[i]]);kill(getpid(),SIGINT);pump(.05);- check(atomic_load(&terminationSignal)==signals[i],@"a repeated signal (the app re-sends SIGTERM every tick) cannot restart or cut the cleanup");+ check(atomic_load(&terminationSignal)==signals[i],@"a repeated signal cannot restart or cut the cleanup");}resetTerminationForTest();// Watchdog, in a child copy of this binary in a self-test-only mode (nodiff --git a/build.sh b/build.shindex cf1fd57..bb5f956 100755--- a/build.sh+++ b/build.sh@@ -1,17 +1,22 @@#!/bin/zshset -euo pipefailcd -- "${0:A:h}"-mkdir -p AirPointer.app/Contents/MacOS AirPointer.app/Contents/Resourcesairpointer_build_mode="${AIRPOINTER_OPTIMIZATION:--O}"airpointer_signing_identity="${AIRPOINTER_SIGNING_IDENTITY:--}"+# Compile first, so a failed build leaves the last good app as it was.+compiled="$(mktemp -d)"+trap 'rm -rf "$compiled"' EXIT+clang -fobjc-arc -Wall -Wextra -Werror -framework Foundation -framework CoreBluetooth -framework IOBluetooth Sources/ClosedCaseMotion/CaseSustainedRenewal.m -o "$compiled/ClosedCaseMotion.bin"+xcrun swiftc -swift-version 5 -O Sources/ClosedCaseRestore/ClosedCaseRestore.swift -o "$compiled/ClosedCaseRestore.bin" -framework Foundation -framework CoreBluetooth -framework IOBluetooth+xcrun swiftc -swift-version 5 "$airpointer_build_mode" Sources/AirPointer/**/*.swift -o "$compiled/AirPointer" -framework AppKit -framework JavaScriptCore -framework QuartzCore -framework ApplicationServices -framework Carbon -framework AVFoundation -framework CoreAudio -framework CoreBluetooth+mkdir -p AirPointer.app/Contents/MacOS AirPointer.app/Contents/Resourcescp Assets/CaseFront.png Assets/AppIcon.icns AirPointer.app/Contents/Resources/for frame in Assets/CaseLid/lid-*.png; do cp "$frame" "AirPointer.app/Contents/Resources/Case${frame:t:r:s/lid/Lid/}.png"; donecp Assets/TapClick/click.wav AirPointer.app/Contents/Resources/TapClick.wavcp Assets/NotchShimmer.wav AirPointer.app/Contents/Resources/NotchShimmer.wavcp Assets/TapClick/LICENSE-cuelume.txt AirPointer.app/Contents/Resources/LICENSE-cuelume.txt-clang -fobjc-arc -Wall -Wextra -Werror -framework Foundation -framework CoreBluetooth -framework IOBluetooth Sources/ClosedCaseMotion/CaseSustainedRenewal.m -o AirPointer.app/Contents/Resources/ClosedCaseMotion.bin-xcrun swiftc -swift-version 5 -O Sources/ClosedCaseRestore/ClosedCaseRestore.swift -o AirPointer.app/Contents/Resources/ClosedCaseRestore.bin -framework Foundation -framework CoreBluetooth -framework IOBluetoothcp Sources/AirPointer/Session/Orientation.js AirPointer.app/Contents/Resources/ClosedCaseOrientation.js+mv -f "$compiled/ClosedCaseMotion.bin" "$compiled/ClosedCaseRestore.bin" AirPointer.app/Contents/Resources/# The app finds the paired AirPods itself; no address is built in.cat > AirPointer.app/Contents/Info.plist <<'PLIST'<?xml version="1.0" encoding="UTF-8"?>@@ -29,8 +34,7 @@ cat > AirPointer.app/Contents/Info.plist <<'PLIST'<key>NSBluetoothAlwaysUsageDescription</key><string>AirPointer connects to your paired AirPods to keep motion available with the case closed.</string></dict></plist>PLIST-xcrun swiftc -swift-version 5 "$airpointer_build_mode" Sources/AirPointer/**/*.swift -o AirPointer.app/Contents/MacOS/.AirPointer-next -framework AppKit -framework JavaScriptCore -framework QuartzCore -framework ApplicationServices -framework Carbon -framework AVFoundation -framework CoreAudio -framework CoreBluetooth-mv -f AirPointer.app/Contents/MacOS/.AirPointer-next AirPointer.app/Contents/MacOS/AirPointer+mv -f "$compiled/AirPointer" AirPointer.app/Contents/MacOS/AirPointerif [[ "$airpointer_signing_identity" != "-" ]]; thencodesign --force --sign "$airpointer_signing_identity" --timestamp=none --identifier local.airpointer.closed-case-motion AirPointer.app/Contents/Resources/ClosedCaseMotion.bincodesign --force --sign "$airpointer_signing_identity" --timestamp=none --identifier local.airpointer.closed-case-restore AirPointer.app/Contents/Resources/ClosedCaseRestore.bin