forked from Blendman974/faceclaw
Add an Apple Watch app that can control the glasses
This commit is contained in:
1 parent
c896ce9ac8
commit
2696f3b76c
46 files changed
+3877
-88
No files matched your search
Binary file not shown.
|
After Width: | Height: | Size: 1.3 MiB |
@@ -0,0 +1 @@
|
||||
{"images":[{"filename":"AppIcon.png","idiom":"universal","platform":"watchos","size":"1024x1024"}],"info":{"author":"xcode","version":1}}
|
||||
@@ -0,0 +1 @@
|
||||
{"info":{"author":"xcode","version":1}}
|
||||
@@ -0,0 +1,59 @@
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct FaceclawWatchApp: App {
|
||||
private let link: PhoneLink
|
||||
private let prefs: WatchPrefs
|
||||
|
||||
init() {
|
||||
link = PhoneLink()
|
||||
prefs = WatchPrefs()
|
||||
// Here rather than in a view: a background launch never builds one.
|
||||
link.start()
|
||||
}
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
RootView()
|
||||
.environment(link)
|
||||
.environment(prefs)
|
||||
}
|
||||
.backgroundTask(.appRefresh(WatchBattery.refreshIdentifier)) { [link] in
|
||||
await link.reportBatteryFromBackground()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Destination: Hashable {
|
||||
case assistant, apps, status, settings
|
||||
}
|
||||
|
||||
private struct RootView: View {
|
||||
@Environment(PhoneLink.self) private var link
|
||||
@Environment(WatchPrefs.self) private var prefs
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
@State private var path: [Destination] = []
|
||||
|
||||
var body: some View {
|
||||
NavigationStack(path: $path) {
|
||||
RemoteScreen(link: link, prefs: prefs, open: { path.append($0) })
|
||||
.navigationDestination(for: Destination.self) { destination in
|
||||
switch destination {
|
||||
case .assistant: AssistantScreen()
|
||||
case .apps: AppsScreen()
|
||||
case .status: StatusScreen(openSettings: { path.append(.settings) })
|
||||
case .settings: SettingsScreen()
|
||||
}
|
||||
}
|
||||
}
|
||||
.overlay(alignment: .bottom) { NoticeOverlay(notice: link.notice) }
|
||||
.onChange(of: scenePhase, initial: true) { _, phase in
|
||||
if phase == .active { link.becameActive() } else { link.resignedActive() }
|
||||
}
|
||||
// A refused or unanswered gesture gets a distinct buzz, so the wrist
|
||||
// knows without looking; the notice pill says why.
|
||||
.onChange(of: link.notice?.id) { _, _ in
|
||||
if link.notice?.isError == true { Haptics(prefs: prefs).error() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
import Observation
|
||||
import os
|
||||
|
||||
/**
|
||||
What the pad's touches and crown turns mean: the watch-side half of the remote,
|
||||
the twin of the callbacks in wear/.../RemoteScreen.kt.
|
||||
*/
|
||||
@MainActor
|
||||
@Observable
|
||||
final class PadController {
|
||||
/** The action buttons, hidden until a swipe up from the bottom edge. */
|
||||
var controlsVisible = false
|
||||
|
||||
@ObservationIgnored private let log = Logger(subsystem: "com.faceclaw.watch", category: "Pad")
|
||||
@ObservationIgnored private let link: PhoneLink
|
||||
@ObservationIgnored private let haptics: Haptics
|
||||
@ObservationIgnored private let recognizer = PadGestureRecognizer()
|
||||
@ObservationIgnored private var deadlineTask: Task<Void, Never>?
|
||||
@ObservationIgnored private var longPressSent = false
|
||||
@ObservationIgnored private var touchStartedAt: Date?
|
||||
@ObservationIgnored private var crownRemainder = 0.0
|
||||
/** Pad height in points, for the edge-reveal zone. */
|
||||
@ObservationIgnored var padHeight: CGFloat = 200
|
||||
|
||||
init(link: PhoneLink, prefs: WatchPrefs) {
|
||||
self.link = link
|
||||
self.haptics = Haptics(prefs: prefs)
|
||||
recognizer.onEvent = { [weak self] event in self?.handle(event) }
|
||||
}
|
||||
|
||||
// MARK: - Touch input
|
||||
|
||||
func touchChanged(start: CGPoint, location: CGPoint, time: Date) {
|
||||
if !recognizer.isTouching {
|
||||
touchStartedAt = time
|
||||
recognizer.touchDown(at: start, time: now())
|
||||
}
|
||||
recognizer.touchMoved(to: location)
|
||||
syncDeadline()
|
||||
}
|
||||
|
||||
func touchEnded(location: CGPoint) {
|
||||
recognizer.touchUp(at: location, time: now())
|
||||
syncDeadline()
|
||||
}
|
||||
|
||||
/** The touch ended without a touch-up: the system took it, or the wrist dropped. */
|
||||
func touchCancelled() {
|
||||
recognizer.cancel()
|
||||
syncDeadline()
|
||||
}
|
||||
|
||||
/**
|
||||
SwiftUI says a touch is over. If it's the current one and it hasn't ended, no
|
||||
touch-up is coming, and a hold still has to be released on the phone.
|
||||
*/
|
||||
func touchWentAway(startedAt: Date) {
|
||||
if recognizer.isTouching && startedAt == touchStartedAt { touchCancelled() }
|
||||
}
|
||||
|
||||
private func now() -> TimeInterval { ProcessInfo.processInfo.systemUptime }
|
||||
|
||||
private func syncDeadline() {
|
||||
deadlineTask?.cancel()
|
||||
deadlineTask = nil
|
||||
guard let deadline = recognizer.deadline else { return }
|
||||
let delay = max(0, deadline - now())
|
||||
deadlineTask = Task { [weak self] in
|
||||
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
|
||||
guard !Task.isCancelled, let self else { return }
|
||||
self.recognizer.advance(to: self.now())
|
||||
self.syncDeadline()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - What gestures mean
|
||||
|
||||
private var glassesScreenIsOff: Bool {
|
||||
guard let state = link.state else { return false }
|
||||
return state.takesInput && !state.screenOn
|
||||
}
|
||||
|
||||
/**
|
||||
A dark display still takes a double-click (wake), and a tap or a hold (the
|
||||
phone's Glanceboard). Scrolls, swipes and the menu gesture mean nothing there,
|
||||
so they're dropped here without a buzz.
|
||||
*/
|
||||
private func gestureAllowed(_ gesture: RingGesture) -> Bool {
|
||||
guard glassesScreenIsOff else { return true }
|
||||
switch gesture {
|
||||
case .doubleClick, .click, .longPressStart, .longPressRelease: return true
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
private func handle(_ event: PadEvent) {
|
||||
log.debug("pad \(String(describing: event), privacy: .public)")
|
||||
switch event {
|
||||
case .press:
|
||||
link.sendPress()
|
||||
case .tap:
|
||||
click()
|
||||
case .doubleTap:
|
||||
haptics.doubleClick()
|
||||
link.sendGesture(.doubleClick)
|
||||
case .shortThenLongPress:
|
||||
guard !glassesScreenIsOff else { return }
|
||||
haptics.heavy()
|
||||
link.sendGesture(.shortThenLongPress)
|
||||
case .longPressStart:
|
||||
longPressSent = gestureAllowed(.longPressStart)
|
||||
if longPressSent {
|
||||
haptics.heavy()
|
||||
link.sendGesture(.longPressStart)
|
||||
}
|
||||
case .longPressEnd:
|
||||
if longPressSent {
|
||||
longPressSent = false
|
||||
haptics.click()
|
||||
link.sendGesture(.longPressRelease)
|
||||
}
|
||||
case let .swipe(start, dx, dy):
|
||||
swipe(start: start, dx: dx, dy: dy)
|
||||
}
|
||||
}
|
||||
|
||||
/** The system's double-tap hand gesture lands here too. */
|
||||
func click() {
|
||||
guard gestureAllowed(.click) else { return }
|
||||
haptics.click()
|
||||
link.sendGesture(.click)
|
||||
}
|
||||
|
||||
private func swipe(start: CGPoint, dx: CGFloat, dy: CGFloat) {
|
||||
let vertical = abs(dy) >= abs(dx)
|
||||
if vertical && !controlsVisible && dy < 0 && start.y >= padHeight - Self.edgeRevealZone {
|
||||
controlsVisible = true
|
||||
haptics.click()
|
||||
} else if vertical && controlsVisible && dy > 0 && start.y >= padHeight - Self.buttonTrayHeight {
|
||||
controlsVisible = false
|
||||
haptics.click()
|
||||
} else if vertical {
|
||||
// One step per swipe, regardless of length: the glasses repaint per
|
||||
// step, and multi-step swipes overshoot lists when the display lags
|
||||
// the finger. Repeated flicks or the crown cover long distances.
|
||||
send(dy < 0 ? .swipeUp : .swipeDown, steps: 1)
|
||||
} else {
|
||||
send(dx < 0 ? .swipeLeft : .swipeRight, steps: 1)
|
||||
}
|
||||
}
|
||||
|
||||
private func send(_ gesture: RingGesture, steps: Int) {
|
||||
guard gestureAllowed(gesture) else { return }
|
||||
haptics.click()
|
||||
link.sendGesture(gesture, steps: steps)
|
||||
}
|
||||
|
||||
func dismissControls() {
|
||||
guard controlsVisible else { return }
|
||||
controlsVisible = false
|
||||
haptics.click()
|
||||
}
|
||||
|
||||
// MARK: - Crown
|
||||
|
||||
/** A crown turn, in detents; positive is clockwise seen from the crown's end. */
|
||||
func crownTurned(by delta: Double) {
|
||||
crownRemainder += delta
|
||||
let steps = Int(crownRemainder.rounded(.towardZero))
|
||||
guard steps != 0 else { return }
|
||||
crownRemainder -= Double(steps)
|
||||
let clockwiseNext = link.state?.crownClockwiseNext == true
|
||||
let gesture: RingGesture = (steps > 0) == clockwiseNext ? .scrollDown : .scrollUp
|
||||
guard gestureAllowed(gesture) else { return }
|
||||
// Capped low: a fast twirl otherwise outruns the display. The crown's
|
||||
// own detent haptics are the feedback, so there's no buzz here.
|
||||
link.sendGesture(gesture, steps: min(abs(steps), Self.maxCrownSteps))
|
||||
}
|
||||
|
||||
static let edgeRevealZone: CGFloat = 28
|
||||
static let buttonTrayHeight: CGFloat = 56
|
||||
private static let maxCrownSteps = 2
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import CoreGraphics
|
||||
import Foundation
|
||||
|
||||
/** What the remote's touch surface can report. */
|
||||
enum PadEvent: Equatable {
|
||||
/** A finger landed (the second tap of a pair included), before it's known what the touch will become. */
|
||||
case press
|
||||
case tap
|
||||
case doubleTap
|
||||
/** A tap whose immediate second press was held: the G2 tap-then-hold gesture. */
|
||||
case shortThenLongPress
|
||||
case longPressStart
|
||||
case longPressEnd
|
||||
/** The finger travelled past touch slop; dx/dy are the total displacement. */
|
||||
case swipe(start: CGPoint, dx: CGFloat, dy: CGFloat)
|
||||
}
|
||||
|
||||
/**
|
||||
One detector for everything the pad does, so a gesture is reported exactly
|
||||
once: tap, double-tap (a second tap inside the double-tap timeout), a hold
|
||||
(reported at the long-press timeout and again on release), tap-then-hold (a
|
||||
second tap held past the long-press timeout) and a swipe. The same state
|
||||
machine as wear/.../TouchpadGestures.kt, without its two-finger gestures:
|
||||
SwiftUI on watchOS only ever sees one finger.
|
||||
|
||||
It has no clock of its own. The owner passes the time with each event and calls
|
||||
`advance(to:)` once `deadline` passes, which is what makes it testable.
|
||||
Every longPressStart is paired with a longPressEnd, whatever ends the touch:
|
||||
the phone treats a start without a release as a hold still in progress.
|
||||
*/
|
||||
final class PadGestureRecognizer {
|
||||
struct Timing {
|
||||
var longPress: TimeInterval = 0.4
|
||||
var doubleTap: TimeInterval = 0.3
|
||||
var slop: CGFloat = 8
|
||||
}
|
||||
|
||||
private enum Phase {
|
||||
case idle
|
||||
case firstTouch(start: CGPoint, moved: Bool)
|
||||
case holding
|
||||
case awaitingSecondTouch
|
||||
case secondTouch(held: Bool)
|
||||
}
|
||||
|
||||
private var phase = Phase.idle
|
||||
private let timing: Timing
|
||||
|
||||
/** When `advance(to:)` next has something to do; nil when only a touch event can move things on. */
|
||||
private(set) var deadline: TimeInterval?
|
||||
var onEvent: (PadEvent) -> Void = { _ in }
|
||||
|
||||
init(timing: Timing = Timing()) {
|
||||
self.timing = timing
|
||||
}
|
||||
|
||||
/** A finger is on the pad, as far as this recognizer knows. */
|
||||
var isTouching: Bool {
|
||||
switch phase {
|
||||
case .firstTouch, .holding, .secondTouch: return true
|
||||
case .idle, .awaitingSecondTouch: return false
|
||||
}
|
||||
}
|
||||
|
||||
func touchDown(at location: CGPoint, time: TimeInterval) {
|
||||
if isTouching { cancel() }
|
||||
onEvent(.press)
|
||||
if case .awaitingSecondTouch = phase {
|
||||
phase = .secondTouch(held: false)
|
||||
} else {
|
||||
phase = .firstTouch(start: location, moved: false)
|
||||
}
|
||||
deadline = time + timing.longPress
|
||||
}
|
||||
|
||||
func touchMoved(to location: CGPoint) {
|
||||
guard case let .firstTouch(start, moved) = phase, !moved else { return }
|
||||
if hypot(location.x - start.x, location.y - start.y) > timing.slop {
|
||||
phase = .firstTouch(start: start, moved: true)
|
||||
deadline = nil
|
||||
}
|
||||
}
|
||||
|
||||
func touchUp(at location: CGPoint, time: TimeInterval) {
|
||||
switch phase {
|
||||
case let .firstTouch(start, moved):
|
||||
if moved {
|
||||
reset()
|
||||
onEvent(.swipe(start: start, dx: location.x - start.x, dy: location.y - start.y))
|
||||
} else {
|
||||
// A plain tap; give a second tap a chance to make it a double.
|
||||
phase = .awaitingSecondTouch
|
||||
deadline = time + timing.doubleTap
|
||||
}
|
||||
case .holding:
|
||||
reset()
|
||||
onEvent(.longPressEnd)
|
||||
case let .secondTouch(held):
|
||||
reset()
|
||||
if !held { onEvent(.doubleTap) }
|
||||
case .idle, .awaitingSecondTouch:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func advance(to time: TimeInterval) {
|
||||
guard let deadline, time >= deadline else { return }
|
||||
self.deadline = nil
|
||||
switch phase {
|
||||
case .firstTouch:
|
||||
phase = .holding
|
||||
onEvent(.longPressStart)
|
||||
case .secondTouch:
|
||||
phase = .secondTouch(held: true)
|
||||
onEvent(.shortThenLongPress)
|
||||
case .awaitingSecondTouch:
|
||||
reset()
|
||||
onEvent(.tap)
|
||||
case .idle, .holding:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
The touch is over but no touch-up will come: the system took the gesture or
|
||||
the wrist dropped. A touch in progress is dropped rather than mistaken for a
|
||||
tap; a tap already completed and a hold already reported are both honoured.
|
||||
*/
|
||||
func cancel() {
|
||||
let cancelled = phase
|
||||
reset()
|
||||
switch cancelled {
|
||||
case .holding: onEvent(.longPressEnd)
|
||||
case .awaitingSecondTouch: onEvent(.tap)
|
||||
case .idle, .firstTouch, .secondTouch: break
|
||||
}
|
||||
}
|
||||
|
||||
private func reset() {
|
||||
phase = .idle
|
||||
deadline = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import Foundation
|
||||
|
||||
/** What we know about the phone and the Faceclaw app on it. */
|
||||
struct LinkStatus: Equatable {
|
||||
/** The WatchConnectivity session is up; until then nothing below is known. */
|
||||
var activated = false
|
||||
/** The iPhone can be messaged right now. */
|
||||
var phoneReachable = false
|
||||
/** That iPhone has Faceclaw installed. */
|
||||
var phoneAppInstalled = false
|
||||
/**
|
||||
Whether the phone app's dashboard (the JS side) answered our last message;
|
||||
nil until we have heard anything. False means Faceclaw is installed but its
|
||||
dashboard isn't running, so the user has to open it.
|
||||
*/
|
||||
var appRunning: Bool?
|
||||
}
|
||||
|
||||
enum StatusTone { case good, busy, off, problem }
|
||||
|
||||
/**
|
||||
The pad's indicator line, with a tone that picks its colour, and an optional
|
||||
smaller line under it (the charging case's level while charging).
|
||||
*/
|
||||
struct StatusLine: Equatable {
|
||||
var text: String
|
||||
var tone: StatusTone
|
||||
var detail: String?
|
||||
}
|
||||
|
||||
/**
|
||||
The pad's indicator: what the next gesture lands on when everything is
|
||||
connected (the foreground app, or the screen/lock state in the way of it),
|
||||
otherwise the connection problem to fix first.
|
||||
*/
|
||||
func padLine(state: PhoneState?, link: LinkStatus) -> StatusLine {
|
||||
guard link.activated else { return StatusLine(text: "Waiting for phone", tone: .busy) }
|
||||
guard link.phoneAppInstalled else { return StatusLine(text: "Install Faceclaw on phone", tone: .problem) }
|
||||
guard link.phoneReachable else { return StatusLine(text: "No phone", tone: .problem) }
|
||||
if link.appRunning == false { return StatusLine(text: "Open Faceclaw on phone", tone: .problem) }
|
||||
guard let state else { return StatusLine(text: "Waiting for phone", tone: .busy) }
|
||||
if !state.remoteEnabled { return StatusLine(text: "Watch control off", tone: .problem) }
|
||||
if state.connected {
|
||||
if state.charging || state.phase == "charging" {
|
||||
return StatusLine(text: chargingLine(state.battery), tone: .busy, detail: caseLine(state))
|
||||
}
|
||||
if state.silentMode { return StatusLine(text: "Silent mode", tone: .off) }
|
||||
if state.locked { return StatusLine(text: "Locked", tone: .off) }
|
||||
if !state.screenOn { return StatusLine(text: "●● Wake", tone: .off) }
|
||||
if state.listening { return StatusLine(text: "Listening…", tone: .busy) }
|
||||
return StatusLine(text: state.foreground?.title ?? "Launcher", tone: .good)
|
||||
}
|
||||
switch state.phase {
|
||||
case "connecting": return StatusLine(text: "Connecting…", tone: .busy)
|
||||
case "retrying": return StatusLine(text: "Reconnecting…", tone: .busy)
|
||||
case "disconnecting": return StatusLine(text: "Disconnecting…", tone: .busy)
|
||||
default: break
|
||||
}
|
||||
if state.preview {
|
||||
if state.locked { return StatusLine(text: "Locked", tone: .off) }
|
||||
if !state.screenOn { return StatusLine(text: "●● Wake", tone: .off) }
|
||||
return StatusLine(text: state.foreground?.title ?? "Launcher", tone: .good, detail: "Phone preview")
|
||||
}
|
||||
return StatusLine(text: "Disconnected", tone: .off)
|
||||
}
|
||||
|
||||
private func chargingLine(_ battery: Int?) -> String {
|
||||
battery.map { "Charging · G2 \($0)%" } ?? "Charging"
|
||||
}
|
||||
|
||||
/**
|
||||
"Case 64%", with ⚡ while the case is on USB; nil when the level is unknown. The
|
||||
case only reports while the glasses are docked, so this is only drawn while they charge.
|
||||
*/
|
||||
private func caseLine(_ state: PhoneState) -> String? {
|
||||
state.caseBattery.map { "Case \($0)%" + (state.caseCharging == true ? " ⚡" : "") }
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import WatchConnectivity
|
||||
import WatchKit
|
||||
import os
|
||||
|
||||
/** A transient message for the UI (ack failures, confirmations). */
|
||||
struct Notice: Equatable {
|
||||
var text: String
|
||||
var isError: Bool
|
||||
var id: UUID
|
||||
}
|
||||
|
||||
/**
|
||||
The watch's end of the WatchConnectivity conversation with the phone: sends
|
||||
gestures, commands and text as messages, receives acks and events, and mirrors
|
||||
the phone's state. The twin of wear/.../PhoneLink.kt, with these differences:
|
||||
|
||||
- Live messages only work while this app is in front. The iPhone app can't wake
|
||||
us, so the phone also leaves its state and latest event in the application
|
||||
context, which is delivered whenever we next run.
|
||||
- `isReachable` lags a moment behind a wrist raise, which is exactly when a
|
||||
gesture arrives, so messages are held briefly instead of failing at once.
|
||||
*/
|
||||
@MainActor
|
||||
@Observable
|
||||
final class PhoneLink: NSObject {
|
||||
private(set) var state: PhoneState?
|
||||
private(set) var link = LinkStatus()
|
||||
private(set) var assistant = AssistantMirror()
|
||||
private(set) var notice: Notice?
|
||||
|
||||
@ObservationIgnored private let log = Logger(subsystem: "com.faceclaw.watch", category: "PhoneLink")
|
||||
@ObservationIgnored private var nextSeq: Int64 = 1
|
||||
@ObservationIgnored private var pendingAcks: [Int64: Task<Void, Never>] = [:]
|
||||
@ObservationIgnored private var held: [Outgoing] = []
|
||||
@ObservationIgnored private var heldExpiry: Task<Void, Never>?
|
||||
@ObservationIgnored private var noticeTask: Task<Void, Never>?
|
||||
@ObservationIgnored private var batteryTimer: Task<Void, Never>?
|
||||
@ObservationIgnored private var lastBatteryReported: WatchBatteryReading?
|
||||
@ObservationIgnored private var lastEventAt: Int64 = 0
|
||||
|
||||
private struct Outgoing {
|
||||
var path: String
|
||||
var json: String
|
||||
var seq: Int64
|
||||
var quiet: Bool
|
||||
}
|
||||
|
||||
private var session: WCSession { WCSession.default }
|
||||
|
||||
/** Activate the session. Called during launch, including a background launch. */
|
||||
func start() {
|
||||
guard WCSession.isSupported() else { return }
|
||||
session.delegate = self
|
||||
session.activate()
|
||||
}
|
||||
|
||||
// MARK: - App lifecycle
|
||||
|
||||
/** The app came to the front: catch up on everything that happened while suspended. */
|
||||
func becameActive() {
|
||||
refresh()
|
||||
batteryTimer?.cancel()
|
||||
// watchOS has no battery-change notification, and the app is only awake to be polled here.
|
||||
batteryTimer = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(nanoseconds: Self.batteryPollNanos)
|
||||
guard !Task.isCancelled else { return }
|
||||
self?.reportBattery(force: false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resignedActive() {
|
||||
batteryTimer?.cancel()
|
||||
batteryTimer = nil
|
||||
WatchBattery.scheduleBackgroundRefresh()
|
||||
}
|
||||
|
||||
/** Re-read the session, the cached state and ask the phone for a fresh one. */
|
||||
func refresh() {
|
||||
updateLink()
|
||||
guard session.activationState == .activated else { return }
|
||||
applyContext(session.receivedApplicationContext)
|
||||
if link.phoneAppInstalled {
|
||||
requestState()
|
||||
reportBattery(force: true)
|
||||
}
|
||||
}
|
||||
|
||||
/** The system gave us background time: leave the battery level for the phone to find. */
|
||||
func reportBatteryFromBackground() async {
|
||||
for _ in 0..<50 where session.activationState != .activated {
|
||||
try? await Task.sleep(nanoseconds: 100_000_000)
|
||||
}
|
||||
reportBattery(force: true)
|
||||
WatchBattery.scheduleBackgroundRefresh()
|
||||
}
|
||||
|
||||
// MARK: - Outbound
|
||||
|
||||
func sendGesture(_ gesture: RingGesture, steps: Int = 1) {
|
||||
send(WirePath.input, ["gesture": gesture.rawValue, "steps": steps])
|
||||
}
|
||||
|
||||
/**
|
||||
A finger landed: the phone delivers it as the ring's touch-down (ring-press)
|
||||
ahead of whatever gesture the touch becomes. Fire-and-forget and silent, since
|
||||
the gesture that follows reports any failure; never held, since a late
|
||||
touch-down would be worse than none.
|
||||
*/
|
||||
func sendPress() {
|
||||
guard let state, state.takesInput, state.screenOn, session.isReachable else { return }
|
||||
transmit(path: WirePath.press, json: "{}")
|
||||
}
|
||||
|
||||
func sendCommand(_ command: String, extras: [String: String] = [:]) {
|
||||
var body: [String: Any] = ["command": command]
|
||||
for (key, value) in extras { body[key] = value }
|
||||
send(WirePath.command, body)
|
||||
}
|
||||
|
||||
func sendAssistantQuery(_ text: String) {
|
||||
assistant = AssistantMirror(phase: "thinking", text: "")
|
||||
send(WirePath.assistant, ["text": text])
|
||||
}
|
||||
|
||||
func sendText(_ text: String) {
|
||||
send(WirePath.text, ["text": text])
|
||||
}
|
||||
|
||||
func requestState() {
|
||||
send(WirePath.stateRequest, [:], quiet: true)
|
||||
}
|
||||
|
||||
func clearAssistant() {
|
||||
assistant = AssistantMirror()
|
||||
}
|
||||
|
||||
private func send(_ path: String, _ body: [String: Any], quiet: Bool = false) {
|
||||
let seq = nextSeq
|
||||
nextSeq += 1
|
||||
var body = body
|
||||
body["seq"] = seq
|
||||
guard let json = encodeJSON(body) else { return }
|
||||
let message = Outgoing(path: path, json: json, seq: seq, quiet: quiet)
|
||||
if session.activationState == .activated && session.isReachable {
|
||||
transmit(message)
|
||||
} else if quiet {
|
||||
// Only state requests are quiet, and reachability returning sends a fresh one.
|
||||
} else {
|
||||
hold(message)
|
||||
}
|
||||
}
|
||||
|
||||
private func hold(_ message: Outgoing) {
|
||||
log.debug("hold \(message.path, privacy: .public) seq=\(message.seq) (not reachable)")
|
||||
held.append(message)
|
||||
if held.count > Self.heldLimit { held.removeFirst() }
|
||||
guard heldExpiry == nil else { return }
|
||||
heldExpiry = Task { [weak self] in
|
||||
try? await Task.sleep(nanoseconds: Self.holdNanos)
|
||||
guard !Task.isCancelled else { return }
|
||||
self?.expireHeld()
|
||||
}
|
||||
}
|
||||
|
||||
private func flushHeld() {
|
||||
heldExpiry?.cancel()
|
||||
heldExpiry = nil
|
||||
let messages = held
|
||||
held = []
|
||||
messages.forEach(transmit)
|
||||
}
|
||||
|
||||
private func expireHeld() {
|
||||
heldExpiry = nil
|
||||
guard !held.isEmpty else { return }
|
||||
held = []
|
||||
showNotice(link.phoneAppInstalled ? "The phone is out of range." : "Faceclaw isn't installed on the phone.", isError: true)
|
||||
}
|
||||
|
||||
private func transmit(_ message: Outgoing) {
|
||||
log.debug("send \(message.path, privacy: .public) seq=\(message.seq)")
|
||||
transmit(path: message.path, json: message.json) { [weak self] error in
|
||||
self?.sendFailed(message, error)
|
||||
}
|
||||
// The phone acks every message; silence means its app process never received it.
|
||||
pendingAcks[message.seq] = Task { [weak self] in
|
||||
try? await Task.sleep(nanoseconds: Self.ackTimeoutNanos)
|
||||
guard !Task.isCancelled, let self, self.pendingAcks.removeValue(forKey: message.seq) != nil else { return }
|
||||
if self.link.appRunning == nil { self.link.appRunning = false }
|
||||
if !message.quiet { self.showNotice("No reply from the phone.", isError: true) }
|
||||
}
|
||||
}
|
||||
|
||||
private func transmit(path: String, json: String, onError: (@MainActor (Error) -> Void)? = nil) {
|
||||
session.sendMessage([WireKey.path: path, WireKey.json: json], replyHandler: nil) { [log] error in
|
||||
log.error("send \(path, privacy: .public) failed: \(error.localizedDescription, privacy: .public)")
|
||||
Task { @MainActor in onError?(error) }
|
||||
}
|
||||
}
|
||||
|
||||
private func sendFailed(_ message: Outgoing, _ error: Error) {
|
||||
pendingAcks.removeValue(forKey: message.seq)?.cancel()
|
||||
updateLink()
|
||||
guard !message.quiet else { return }
|
||||
let code = (error as? WCError)?.code
|
||||
switch code {
|
||||
case .notReachable: showNotice("The phone is out of range.", isError: true)
|
||||
case .companionAppNotInstalled: showNotice("Faceclaw isn't installed on the phone.", isError: true)
|
||||
default: showNotice("Couldn't reach the phone.", isError: true)
|
||||
}
|
||||
}
|
||||
|
||||
/** Send our battery to the phone (for the glasses' Watch indicator), live and for later. */
|
||||
private func reportBattery(force: Bool) {
|
||||
guard session.activationState == .activated else { return }
|
||||
let reading = WatchBattery.read()
|
||||
if !force && reading == lastBatteryReported { return }
|
||||
lastBatteryReported = reading
|
||||
guard let json = encodeJSON(reading.payload(at: Date())) else { return }
|
||||
if session.isReachable { transmit(path: WirePath.battery, json: json) }
|
||||
do {
|
||||
try session.updateApplicationContext([WireKey.battery: json])
|
||||
} catch {
|
||||
log.debug("battery context not sent: \(error.localizedDescription, privacy: .public)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Inbound
|
||||
|
||||
private func handleMessage(path: String, json: String, updatedAt: Int64, at: Int64) {
|
||||
switch path {
|
||||
case WirePath.ack:
|
||||
if let ack = Ack.parse(json) { handleAck(ack) }
|
||||
case WirePath.event:
|
||||
handleEvent(json: json, at: at, fromContext: false)
|
||||
case WirePath.state:
|
||||
// A live state comes from the running dashboard, unlike one left in the context.
|
||||
applyState(json: json, updatedAt: updatedAt)
|
||||
link.appRunning = true
|
||||
case WirePath.batteryRequest:
|
||||
reportBattery(force: true)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
private func handleAck(_ ack: Ack) {
|
||||
pendingAcks.removeValue(forKey: ack.seq)?.cancel()
|
||||
link.appRunning = ack.jsReady
|
||||
if !ack.ok {
|
||||
showNotice(ack.message.isEmpty ? "The phone refused that." : ack.message, isError: true)
|
||||
} else if !ack.message.isEmpty {
|
||||
showNotice(ack.message, isError: false)
|
||||
}
|
||||
}
|
||||
|
||||
private func handleEvent(json: String, at: Int64, fromContext: Bool) {
|
||||
guard let event = PhoneEvent.parse(json) else { return }
|
||||
// The same event can arrive both live and in the context.
|
||||
if at != 0 {
|
||||
guard at > lastEventAt else { return }
|
||||
lastEventAt = at
|
||||
}
|
||||
let age = at == 0 ? 0 : Date().timeIntervalSince1970 - Double(at) / 1000
|
||||
switch event {
|
||||
case let .assistant(phase, text):
|
||||
if fromContext && age > Self.assistantEventMaxAge { return }
|
||||
assistant = assistant.applying(phase: phase, text: text)
|
||||
case let .alert(text):
|
||||
if fromContext && age > Self.alertEventMaxAge { return }
|
||||
showNotice(text, isError: false)
|
||||
}
|
||||
}
|
||||
|
||||
private func applyContext(_ context: [String: Any]) {
|
||||
if let json = context[WireKey.json] as? String {
|
||||
applyState(json: json, updatedAt: (context[WireKey.updatedAt] as? NSNumber)?.int64Value ?? 0)
|
||||
}
|
||||
if let json = context[WireKey.event] as? String {
|
||||
handleEvent(json: json, at: (context[WireKey.eventAt] as? NSNumber)?.int64Value ?? 0, fromContext: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func applyState(json: String, updatedAt: Int64) {
|
||||
// A live message and the context can carry the same or an older state, in either order.
|
||||
if let state, updatedAt < state.updatedAt { return }
|
||||
if let parsed = PhoneState.parse(json, updatedAt: updatedAt) { state = parsed }
|
||||
}
|
||||
|
||||
private func updateLink() {
|
||||
// The session logs an error for each property read before activation.
|
||||
guard WCSession.isSupported(), session.activationState == .activated else { return }
|
||||
link.activated = true
|
||||
link.phoneReachable = session.isReachable
|
||||
link.phoneAppInstalled = session.isCompanionAppInstalled
|
||||
if !link.phoneAppInstalled { link.appRunning = nil }
|
||||
}
|
||||
|
||||
private func reachabilityChanged() {
|
||||
updateLink()
|
||||
log.debug("reachable=\(self.link.phoneReachable)")
|
||||
if session.isReachable {
|
||||
flushHeld()
|
||||
requestState()
|
||||
reportBattery(force: true)
|
||||
}
|
||||
}
|
||||
|
||||
private func activated() {
|
||||
updateLink()
|
||||
applyContext(session.receivedApplicationContext)
|
||||
reachabilityChanged()
|
||||
}
|
||||
|
||||
private func showNotice(_ text: String, isError: Bool) {
|
||||
noticeTask?.cancel()
|
||||
notice = Notice(text: text, isError: isError, id: UUID())
|
||||
noticeTask = Task { [weak self] in
|
||||
try? await Task.sleep(nanoseconds: isError ? Self.noticeErrorNanos : Self.noticeInfoNanos)
|
||||
guard !Task.isCancelled else { return }
|
||||
self?.notice = nil
|
||||
}
|
||||
}
|
||||
|
||||
private static let ackTimeoutNanos: UInt64 = 4_000_000_000
|
||||
/** How long a message waits for reachability, e.g. right after a wrist raise. */
|
||||
private static let holdNanos: UInt64 = 1_500_000_000
|
||||
private static let heldLimit = 8
|
||||
private static let batteryPollNanos: UInt64 = 60_000_000_000
|
||||
private static let noticeInfoNanos: UInt64 = 1_800_000_000
|
||||
private static let noticeErrorNanos: UInt64 = 3_200_000_000
|
||||
/** A reply that finished while we slept is still worth showing for this long. */
|
||||
private static let assistantEventMaxAge: TimeInterval = 600
|
||||
private static let alertEventMaxAge: TimeInterval = 60
|
||||
}
|
||||
|
||||
extension PhoneLink: WCSessionDelegate {
|
||||
nonisolated func session(_ session: WCSession, activationDidCompleteWith state: WCSessionActivationState, error: Error?) {
|
||||
let log = Logger(subsystem: "com.faceclaw.watch", category: "PhoneLink")
|
||||
log.info("session activation finished: state \(state.rawValue), error \(error?.localizedDescription ?? "none", privacy: .public)")
|
||||
Task { @MainActor in self.activated() }
|
||||
}
|
||||
|
||||
nonisolated func sessionReachabilityDidChange(_ session: WCSession) {
|
||||
Task { @MainActor in self.reachabilityChanged() }
|
||||
}
|
||||
|
||||
nonisolated func sessionCompanionAppInstalledDidChange(_ session: WCSession) {
|
||||
Task { @MainActor in self.updateLink() }
|
||||
}
|
||||
|
||||
nonisolated func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {
|
||||
guard let path = message[WireKey.path] as? String else { return }
|
||||
let json = message[WireKey.json] as? String ?? "{}"
|
||||
let updatedAt = (message[WireKey.updatedAt] as? NSNumber)?.int64Value ?? 0
|
||||
let at = (message[WireKey.at] as? NSNumber)?.int64Value ?? 0
|
||||
Task { @MainActor in self.handleMessage(path: path, json: json, updatedAt: updatedAt, at: at) }
|
||||
}
|
||||
|
||||
nonisolated func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
|
||||
Task { @MainActor in self.refreshFromContext() }
|
||||
}
|
||||
|
||||
@MainActor private func refreshFromContext() {
|
||||
applyContext(session.receivedApplicationContext)
|
||||
}
|
||||
}
|
||||
|
||||
private func encodeJSON(_ object: [String: Any]) -> String? {
|
||||
guard let data = try? JSONSerialization.data(withJSONObject: object) else { return nil }
|
||||
return String(data: data, encoding: .utf8)
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import Foundation
|
||||
|
||||
/**
|
||||
Wire format shared with the phone app. Mirror of app/native/wear-bridge-types.ts
|
||||
(paths), app/g2/wear-remote.ts (payloads) and App_Resources/iOS/src/FaceclawWatchBridge.m
|
||||
(WatchConnectivity keys); see wear/PROTOCOL.md.
|
||||
*/
|
||||
enum WirePath {
|
||||
static let input = "/faceclaw/input"
|
||||
/** Watch -> phone: a finger landed on the pad, ahead of the gesture it becomes; no seq, never acked. */
|
||||
static let press = "/faceclaw/press"
|
||||
static let command = "/faceclaw/command"
|
||||
static let assistant = "/faceclaw/assistant"
|
||||
static let text = "/faceclaw/text"
|
||||
static let stateRequest = "/faceclaw/state/request"
|
||||
/** Watch -> phone: our own battery ({battery, charging, at}); no seq, never acked. */
|
||||
static let battery = "/faceclaw/battery"
|
||||
/** Phone -> watch: please send `battery` now. Only reaches an app that's in front. */
|
||||
static let batteryRequest = "/faceclaw/battery/request"
|
||||
static let ack = "/faceclaw/ack"
|
||||
static let event = "/faceclaw/event"
|
||||
static let state = "/faceclaw/state"
|
||||
}
|
||||
|
||||
/** Keys of the WatchConnectivity dictionaries that carry those messages. */
|
||||
enum WireKey {
|
||||
static let path = "path"
|
||||
static let json = "json"
|
||||
static let updatedAt = "updatedAt"
|
||||
/** The time a live event was sent, matching `eventAt` when it's also in the context. */
|
||||
static let at = "at"
|
||||
/** Application context: the latest event a suspended app would otherwise have missed. */
|
||||
static let event = "event"
|
||||
static let eventAt = "eventAt"
|
||||
/** Application context, watch -> phone: the battery report, as JSON. */
|
||||
static let battery = "battery"
|
||||
}
|
||||
|
||||
/** Ring-style gestures, as the phone's synthetic ring input understands them. */
|
||||
enum RingGesture: String {
|
||||
case click
|
||||
case doubleClick = "double-click"
|
||||
case scrollUp = "scroll-up"
|
||||
case scrollDown = "scroll-down"
|
||||
/** Finger down: the hold lasts until longPressRelease. */
|
||||
case longPressStart = "long-press-start"
|
||||
case longPressRelease = "long-press-release"
|
||||
/** Tap then hold: opens the app's context menu on the glasses. */
|
||||
case shortThenLongPress = "short-then-long-press"
|
||||
/** The spoken "Hey Even": opens the glasses' own voice dialog. */
|
||||
case wakeword
|
||||
/**
|
||||
Spatial (four-way) input the ring cannot produce. The glasses UI gives it a
|
||||
spatial meaning where one exists (grid rows and columns, panel columns,
|
||||
tracks) and otherwise treats up/down as scroll, right as select and left as back.
|
||||
*/
|
||||
case swipeUp = "swipe-up"
|
||||
case swipeDown = "swipe-down"
|
||||
case swipeLeft = "swipe-left"
|
||||
case swipeRight = "swipe-right"
|
||||
}
|
||||
|
||||
/** Shell commands; things the ring cannot express. */
|
||||
enum PhoneCommand {
|
||||
static let launchApp = "launch-app"
|
||||
static let focusWindow = "focus-window"
|
||||
static let closeWindow = "close-window"
|
||||
static let wake = "wake"
|
||||
static let sleep = "sleep"
|
||||
static let lock = "lock"
|
||||
static let unlock = "unlock"
|
||||
static let connect = "connect"
|
||||
static let disconnect = "disconnect"
|
||||
static let closeAssistant = "close-assistant"
|
||||
static let sidebar = "sidebar"
|
||||
}
|
||||
|
||||
struct AppEntry: Equatable, Identifiable {
|
||||
var appId: String
|
||||
var title: String
|
||||
var id: String { appId }
|
||||
}
|
||||
|
||||
struct WindowEntry: Equatable, Identifiable {
|
||||
var windowId: String
|
||||
var title: String
|
||||
var appId: String
|
||||
var focused: Bool
|
||||
var closeable: Bool
|
||||
var acceptsText: Bool
|
||||
var id: String { windowId }
|
||||
}
|
||||
|
||||
/** The phone's mirrored dashboard state (/faceclaw/state). */
|
||||
struct PhoneState: Equatable {
|
||||
var version = ""
|
||||
var phase = "disconnected"
|
||||
var status = ""
|
||||
var connected = false
|
||||
/** The shell is running on the phone's preview with no glasses, so gestures still land. */
|
||||
var preview = false
|
||||
var screenOn = false
|
||||
var locked = false
|
||||
var worn: Bool?
|
||||
var listening = false
|
||||
/** Current or last-known G2 charge percentage. */
|
||||
var battery: Int?
|
||||
var charging = false
|
||||
/** Last-known charging-case percentage; live only while the glasses are docked. */
|
||||
var caseBattery: Int?
|
||||
/** The case is on USB; nil while the glasses are out of the case. */
|
||||
var caseCharging: Bool?
|
||||
var silentMode = false
|
||||
var foreground: AppEntry?
|
||||
var windows: [WindowEntry] = []
|
||||
var apps: [AppEntry] = []
|
||||
var remoteEnabled = true
|
||||
/** False by default: clockwise moves to the previous item. */
|
||||
var crownClockwiseNext = false
|
||||
var canUnlock = true
|
||||
var mirrorAssistant = true
|
||||
var assistantAvailable = false
|
||||
var updatedAt: Int64 = 0
|
||||
|
||||
/** Gestures have a display to act on, whether that's the glasses or the phone's preview. */
|
||||
var takesInput: Bool { connected || preview }
|
||||
|
||||
static func parse(_ json: String, updatedAt: Int64) -> PhoneState? {
|
||||
guard let o = parseObject(json) else { return nil }
|
||||
var state = PhoneState()
|
||||
state.version = o["version"] as? String ?? ""
|
||||
state.phase = o["phase"] as? String ?? "disconnected"
|
||||
state.status = o["status"] as? String ?? ""
|
||||
state.connected = o["connected"] as? Bool ?? false
|
||||
state.preview = o["preview"] as? Bool ?? false
|
||||
state.screenOn = o["screenOn"] as? Bool ?? false
|
||||
state.locked = o["locked"] as? Bool ?? false
|
||||
state.worn = o["worn"] as? Bool
|
||||
state.listening = o["listening"] as? Bool ?? false
|
||||
state.battery = percent(o["battery"])
|
||||
state.charging = o["charging"] as? Bool ?? false
|
||||
state.caseBattery = percent(o["caseBattery"])
|
||||
state.caseCharging = o["caseCharging"] as? Bool
|
||||
state.silentMode = o["silentMode"] as? Bool ?? false
|
||||
if let foreground = o["foreground"] as? [String: Any] { state.foreground = appEntry(foreground) }
|
||||
state.windows = (o["windows"] as? [[String: Any]] ?? []).map { w in
|
||||
WindowEntry(
|
||||
windowId: w["windowId"] as? String ?? "",
|
||||
title: w["title"] as? String ?? "",
|
||||
appId: w["appId"] as? String ?? "",
|
||||
focused: w["focused"] as? Bool ?? false,
|
||||
closeable: w["closeable"] as? Bool ?? true,
|
||||
acceptsText: w["acceptsText"] as? Bool ?? false
|
||||
)
|
||||
}
|
||||
state.apps = (o["apps"] as? [[String: Any]] ?? []).map(appEntry)
|
||||
state.remoteEnabled = o["remoteEnabled"] as? Bool ?? true
|
||||
state.crownClockwiseNext = o["crownClockwiseNext"] as? Bool ?? false
|
||||
state.canUnlock = o["canUnlock"] as? Bool ?? true
|
||||
state.mirrorAssistant = o["mirrorAssistant"] as? Bool ?? true
|
||||
state.assistantAvailable = o["assistantAvailable"] as? Bool ?? false
|
||||
state.updatedAt = updatedAt
|
||||
return state
|
||||
}
|
||||
|
||||
private static func appEntry(_ o: [String: Any]) -> AppEntry {
|
||||
AppEntry(appId: o["appId"] as? String ?? "", title: o["title"] as? String ?? "")
|
||||
}
|
||||
|
||||
private static func percent(_ value: Any?) -> Int? {
|
||||
guard let number = value as? NSNumber, (0...100).contains(number.intValue) else { return nil }
|
||||
return number.intValue
|
||||
}
|
||||
}
|
||||
|
||||
/** The phone's reply to one of our messages. */
|
||||
struct Ack: Equatable {
|
||||
var seq: Int64
|
||||
var ok: Bool
|
||||
/** False: the phone's app process answered, but its dashboard isn't up. */
|
||||
var jsReady: Bool
|
||||
var message: String
|
||||
|
||||
static func parse(_ json: String) -> Ack? {
|
||||
guard let o = parseObject(json) else { return nil }
|
||||
return Ack(
|
||||
seq: (o["seq"] as? NSNumber)?.int64Value ?? 0,
|
||||
ok: o["ok"] as? Bool ?? false,
|
||||
jsReady: o["jsReady"] as? Bool ?? true,
|
||||
message: o["message"] as? String ?? ""
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Phone -> watch events (/faceclaw/event). */
|
||||
enum PhoneEvent: Equatable {
|
||||
/** phase: thinking | streaming | done | error | closed; text is the reply so far. */
|
||||
case assistant(phase: String, text: String)
|
||||
case alert(text: String)
|
||||
|
||||
static func parse(_ json: String) -> PhoneEvent? {
|
||||
guard let o = parseObject(json) else { return nil }
|
||||
switch o["type"] as? String {
|
||||
case "assistant": return .assistant(phase: o["phase"] as? String ?? "", text: o["text"] as? String ?? "")
|
||||
case "alert": return .alert(text: o["text"] as? String ?? "")
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The assistant overlay as mirrored from the glasses. */
|
||||
struct AssistantMirror: Equatable {
|
||||
/** idle | thinking | streaming | done | error */
|
||||
var phase = "idle"
|
||||
var text = ""
|
||||
|
||||
func applying(phase next: String, text nextText: String) -> AssistantMirror {
|
||||
switch next {
|
||||
case "thinking": return AssistantMirror(phase: "thinking", text: "")
|
||||
case "streaming": return AssistantMirror(phase: "streaming", text: nextText)
|
||||
case "done": return AssistantMirror(phase: "done", text: nextText.isEmpty ? text : nextText)
|
||||
case "error": return AssistantMirror(phase: "error", text: nextText)
|
||||
case "closed": return AssistantMirror(phase: "idle", text: text)
|
||||
default: return self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func parseObject(_ json: String) -> [String: Any]? {
|
||||
guard let data = json.data(using: .utf8) else { return nil }
|
||||
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import SwiftUI
|
||||
|
||||
/**
|
||||
The touchpad. The whole screen is the pad: tap = select, double-tap = back, hold
|
||||
= long press (released when the finger lifts), tap then hold = the app's menu,
|
||||
swipes in four directions = spatial navigation, crown = plain scrolling. An upward
|
||||
swipe that begins at the bottom edge reveals the otherwise-hidden action buttons.
|
||||
*/
|
||||
struct RemoteScreen: View {
|
||||
let link: PhoneLink
|
||||
let prefs: WatchPrefs
|
||||
let open: (Destination) -> Void
|
||||
|
||||
@Environment(\.isLuminanceReduced) private var isDimmed
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
@State private var pad: PadController
|
||||
@State private var crownValue = 0.0
|
||||
/** When the touch in progress began; nil once it's over, however it ended. */
|
||||
@GestureState private var touchStart: Date?
|
||||
@FocusState private var crownFocused: Bool
|
||||
|
||||
init(link: PhoneLink, prefs: WatchPrefs, open: @escaping (Destination) -> Void) {
|
||||
self.link = link
|
||||
self.prefs = prefs
|
||||
self.open = open
|
||||
_pad = State(initialValue: PadController(link: link, prefs: prefs))
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geometry in
|
||||
ZStack {
|
||||
padSurface
|
||||
primaryActionShortcut
|
||||
clockAndStatus.allowsHitTesting(false)
|
||||
if pad.controlsVisible && !isDimmed { tray }
|
||||
}
|
||||
.onChange(of: geometry.size.height, initial: true) { _, height in pad.padHeight = height }
|
||||
}
|
||||
.ignoresSafeArea()
|
||||
.toolbar(.hidden, for: .navigationBar)
|
||||
.animation(.easeOut(duration: 0.18), value: pad.controlsVisible)
|
||||
// Crown events only reach a focused view, and the focus is lost to every screen pushed on top.
|
||||
.focusable(true)
|
||||
.focused($crownFocused)
|
||||
.focusEffectDisabled()
|
||||
.digitalCrownRotation(
|
||||
$crownValue,
|
||||
from: -Self.crownRange,
|
||||
through: Self.crownRange,
|
||||
by: 1,
|
||||
sensitivity: prefs.crownSensitivity.digitalCrown,
|
||||
isContinuous: true,
|
||||
isHapticFeedbackEnabled: prefs.haptics
|
||||
)
|
||||
.digitalCrownAccessory(.hidden)
|
||||
.onChange(of: crownValue) { old, new in
|
||||
// A jump across the whole range is the value wrapping, not a turn.
|
||||
let delta = new - old
|
||||
if abs(delta) < Self.crownRange { pad.crownTurned(by: delta) }
|
||||
}
|
||||
// A touch-up also clears this, which arrives late enough to fall inside the next
|
||||
// touch of a quick double-tap; the pad checks which touch it's being told about.
|
||||
.onChange(of: touchStart) { old, new in
|
||||
if new == nil, let old { pad.touchWentAway(startedAt: old) }
|
||||
}
|
||||
.onChange(of: scenePhase) { _, phase in
|
||||
if phase == .active { crownFocused = true } else { pad.touchCancelled() }
|
||||
}
|
||||
.onAppear { crownFocused = true }
|
||||
}
|
||||
|
||||
private var padSurface: some View {
|
||||
Color.black
|
||||
.contentShape(Rectangle())
|
||||
.gesture(
|
||||
DragGesture(minimumDistance: 0, coordinateSpace: .local)
|
||||
.updating($touchStart) { value, state, _ in
|
||||
if state == nil { state = value.time }
|
||||
}
|
||||
.onChanged { pad.touchChanged(start: $0.startLocation, location: $0.location, time: $0.time) }
|
||||
.onEnded { pad.touchEnded(location: $0.location) }
|
||||
)
|
||||
.accessibilityIdentifier("pad")
|
||||
}
|
||||
|
||||
/**
|
||||
The double-tap hand gesture (Series 9, Ultra 2, SE 3 and later) selects. It needs a
|
||||
control to attach to, and the pad surface is a gesture rather than a control,
|
||||
so this one sits underneath everything as a transparent stand-in.
|
||||
*/
|
||||
@ViewBuilder
|
||||
private var primaryActionShortcut: some View {
|
||||
if #available(watchOS 11.0, *) {
|
||||
Button("Select") { pad.click() }
|
||||
.buttonStyle(.plain)
|
||||
.handGestureShortcut(.primaryAction)
|
||||
.frame(width: 1, height: 1)
|
||||
.opacity(0.01)
|
||||
.allowsHitTesting(false)
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
|
||||
private var clockAndStatus: some View {
|
||||
let status = padLine(state: link.state, link: link.link)
|
||||
return ZStack {
|
||||
// A large, straight clock fixed on the vertical centre of the pad.
|
||||
TimelineView(.everyMinute) { context in
|
||||
Text(context.date.formatted(.dateTime.hour(.defaultDigits(amPM: .omitted)).minute()))
|
||||
.font(.system(size: 44, weight: .regular, design: .rounded))
|
||||
.monospacedDigit()
|
||||
.foregroundStyle(.white)
|
||||
.lineLimit(1)
|
||||
.minimumScaleFactor(0.7)
|
||||
}
|
||||
if !pad.controlsVisible {
|
||||
// Offset rather than stacked, so the clock stays put whatever this says.
|
||||
VStack(spacing: 0) {
|
||||
Text(status.text)
|
||||
.font(.headline)
|
||||
.foregroundStyle(statusColor(status.tone))
|
||||
.accessibilityIdentifier("padStatus")
|
||||
if let detail = status.detail {
|
||||
Text(detail)
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.lineLimit(1)
|
||||
.minimumScaleFactor(0.7)
|
||||
.padding(.horizontal, 12)
|
||||
.offset(y: 46)
|
||||
.transition(.opacity)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func statusColor(_ tone: StatusTone) -> Color {
|
||||
if isDimmed { return .gray }
|
||||
return tone == .good ? .white : tone.color
|
||||
}
|
||||
|
||||
private var tray: some View {
|
||||
VStack {
|
||||
Spacer()
|
||||
HStack(spacing: 6) {
|
||||
TrayButton(symbol: "sparkles", label: "Assistant") { openFromTray(.assistant) }
|
||||
TextFieldLink(prompt: Text("Type into app")) {
|
||||
TrayIcon(symbol: "keyboard")
|
||||
} onSubmit: { text in
|
||||
send(typed: text)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel("Type into app")
|
||||
.accessibilityIdentifier("Type into app")
|
||||
TrayButton(symbol: "square.grid.2x2", label: "Apps") { openFromTray(.apps) }
|
||||
TrayButton(symbol: "ellipsis", label: "Status and settings") { openFromTray(.status) }
|
||||
}
|
||||
.padding(.bottom, 10)
|
||||
// A swipe down that starts on a button dismisses the tray; a tap stays the button's.
|
||||
.simultaneousGesture(
|
||||
DragGesture(minimumDistance: 12).onEnded { value in
|
||||
if value.translation.height > abs(value.translation.width) { pad.dismissControls() }
|
||||
}
|
||||
)
|
||||
}
|
||||
.transition(.move(edge: .bottom).combined(with: .opacity))
|
||||
}
|
||||
|
||||
/** The tray has done its job: coming back should show the pad's status, not the buttons. */
|
||||
private func openFromTray(_ destination: Destination) {
|
||||
pad.controlsVisible = false
|
||||
open(destination)
|
||||
}
|
||||
|
||||
private func send(typed text: String) {
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return }
|
||||
Haptics(prefs: prefs).click()
|
||||
link.sendText(trimmed)
|
||||
}
|
||||
|
||||
/** Far more detents than a session will ever turn; only the changes matter. */
|
||||
private static let crownRange = 1_000_000.0
|
||||
}
|
||||
|
||||
private struct TrayButton: View {
|
||||
let symbol: String
|
||||
let label: String
|
||||
let action: () -> Void
|
||||
|
||||
var body: some View {
|
||||
Button(action: action) { TrayIcon(symbol: symbol) }
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel(label)
|
||||
.accessibilityIdentifier(label)
|
||||
}
|
||||
}
|
||||
|
||||
private struct TrayIcon: View {
|
||||
let symbol: String
|
||||
|
||||
var body: some View {
|
||||
Image(systemName: symbol)
|
||||
.font(.system(size: 16, weight: .medium))
|
||||
.foregroundStyle(.white)
|
||||
.frame(width: 36, height: 36)
|
||||
.background(Circle().fill(Color(white: 0.2)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import SwiftUI
|
||||
|
||||
extension StatusTone {
|
||||
var color: Color {
|
||||
switch self {
|
||||
case .good: return Color(red: 0.48, green: 0.85, blue: 0.56)
|
||||
case .busy: return Color(red: 0.95, green: 0.76, blue: 0.31)
|
||||
case .off: return Color(white: 0.54)
|
||||
case .problem: return Color(red: 1.0, green: 0.54, blue: 0.5)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** A transient pill at the bottom of the screen: ack failures and confirmations. */
|
||||
struct NoticeOverlay: View {
|
||||
let notice: Notice?
|
||||
|
||||
var body: some View {
|
||||
Group {
|
||||
if let notice {
|
||||
Text(notice.text)
|
||||
.font(.caption2)
|
||||
.multilineTextAlignment(.center)
|
||||
.lineLimit(2)
|
||||
.foregroundStyle(notice.isError ? Color(red: 1, green: 0.71, blue: 0.66) : .white)
|
||||
.padding(.horizontal, 10)
|
||||
.padding(.vertical, 5)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: 12)
|
||||
.fill(notice.isError ? Color(red: 0.29, green: 0.12, blue: 0.1) : Color(white: 0.16))
|
||||
)
|
||||
.padding(.horizontal, 8)
|
||||
.padding(.bottom, 4)
|
||||
.transition(.opacity)
|
||||
.accessibilityIdentifier("notice")
|
||||
}
|
||||
}
|
||||
.animation(.easeOut(duration: 0.15), value: notice?.id)
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
}
|
||||
|
||||
/** A list row: a title with an optional smaller line beneath it. */
|
||||
private struct RowLabel: View {
|
||||
let title: String
|
||||
var detail: String?
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(title).lineLimit(1)
|
||||
if let detail {
|
||||
Text(detail).font(.caption2).foregroundStyle(.secondary).lineLimit(1)
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
|
||||
private struct SectionHeader: View {
|
||||
let title: String
|
||||
init(_ title: String) { self.title = title }
|
||||
|
||||
var body: some View {
|
||||
Text(title)
|
||||
.font(.footnote)
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.top, 6)
|
||||
.padding(.leading, 4)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Apps
|
||||
|
||||
/**
|
||||
The glasses' sidebar and launcher, on the wrist: open windows first (tap to bring
|
||||
one to the front, × to close it), then every launchable app.
|
||||
*/
|
||||
struct AppsScreen: View {
|
||||
@Environment(PhoneLink.self) private var link
|
||||
@Environment(WatchPrefs.self) private var prefs
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
var body: some View {
|
||||
let windows = link.state?.windows ?? []
|
||||
let apps = link.state?.apps ?? []
|
||||
let onScreen = windows.filter(\.focused)
|
||||
let others = windows.filter { !$0.focused }
|
||||
ScrollView {
|
||||
LazyVStack(spacing: 4) {
|
||||
if !onScreen.isEmpty {
|
||||
SectionHeader("On screen")
|
||||
ForEach(onScreen) { windowRow($0) }
|
||||
}
|
||||
if !others.isEmpty {
|
||||
SectionHeader("Also open")
|
||||
ForEach(others) { windowRow($0) }
|
||||
}
|
||||
SectionHeader(apps.isEmpty ? "No app list yet" : "Launch")
|
||||
ForEach(apps) { app in
|
||||
Button {
|
||||
Haptics(prefs: prefs).click()
|
||||
link.sendCommand(PhoneCommand.launchApp, extras: ["appId": app.appId])
|
||||
dismiss()
|
||||
} label: {
|
||||
RowLabel(title: app.title)
|
||||
}
|
||||
.accessibilityIdentifier("app:\(app.appId)")
|
||||
}
|
||||
if apps.isEmpty {
|
||||
Text("Open Faceclaw on the phone and connect the glasses.")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle("Apps")
|
||||
}
|
||||
|
||||
/** One open window: tap to bring it to the front, × to close it. */
|
||||
private func windowRow(_ window: WindowEntry) -> some View {
|
||||
HStack(spacing: 4) {
|
||||
Button {
|
||||
Haptics(prefs: prefs).click()
|
||||
link.sendCommand(PhoneCommand.focusWindow, extras: ["windowId": window.windowId])
|
||||
dismiss()
|
||||
} label: {
|
||||
// The launcher's window is titled "Apps" on the glasses; here
|
||||
// that would read as this very screen.
|
||||
RowLabel(
|
||||
title: window.appId == "launcher" ? "Launcher" : window.title,
|
||||
detail: window.acceptsText ? "takes typed text" : nil
|
||||
)
|
||||
}
|
||||
.tint(window.focused ? StatusTone.good.color : nil)
|
||||
if window.closeable {
|
||||
Button {
|
||||
Haptics(prefs: prefs).click()
|
||||
link.sendCommand(PhoneCommand.closeWindow, extras: ["windowId": window.windowId])
|
||||
} label: {
|
||||
Image(systemName: "xmark").font(.system(size: 12, weight: .semibold))
|
||||
}
|
||||
.frame(width: 40)
|
||||
.accessibilityLabel("Close \(window.title)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Assistant
|
||||
|
||||
/**
|
||||
Ask the assistant from the wrist (the system text sheet, which offers dictation)
|
||||
and read its reply here as it streams, mirrored from the glasses overlay. "Hey
|
||||
Even" instead uses the glasses' own microphone and voice dialog.
|
||||
*/
|
||||
struct AssistantScreen: View {
|
||||
@Environment(PhoneLink.self) private var link
|
||||
@Environment(WatchPrefs.self) private var prefs
|
||||
|
||||
var body: some View {
|
||||
let available = link.state?.assistantAvailable != false
|
||||
let mirror = link.assistant
|
||||
let haptics = Haptics(prefs: prefs)
|
||||
ScrollView {
|
||||
VStack(spacing: 6) {
|
||||
TextFieldLink(prompt: Text("Ask the assistant")) {
|
||||
Label("Ask", systemImage: "mic.fill").frame(maxWidth: .infinity)
|
||||
} onSubmit: { text in
|
||||
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !trimmed.isEmpty else { return }
|
||||
haptics.click()
|
||||
link.sendAssistantQuery(trimmed)
|
||||
}
|
||||
.disabled(!available)
|
||||
.accessibilityIdentifier("assistantAsk")
|
||||
|
||||
Text(phaseLabel(mirror.phase, available: available))
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
.accessibilityIdentifier("assistantPhase")
|
||||
|
||||
if !mirror.text.isEmpty {
|
||||
Text(mirror.text)
|
||||
.font(.body)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.padding(.horizontal, 4)
|
||||
}
|
||||
|
||||
Button {
|
||||
haptics.click()
|
||||
link.sendGesture(.wakeword)
|
||||
} label: {
|
||||
RowLabel(title: "“Hey Even”", detail: "uses the glasses mic")
|
||||
}
|
||||
|
||||
if mirror.phase != "idle" {
|
||||
Button(mirror.phase == "thinking" || mirror.phase == "streaming" ? "Cancel" : "Dismiss") {
|
||||
haptics.click()
|
||||
link.sendCommand(PhoneCommand.closeAssistant)
|
||||
link.clearAssistant()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle("Assistant")
|
||||
// A finished reply deserves a nudge: the wrist may be down while it streams.
|
||||
.onChange(of: mirror.phase) { _, phase in
|
||||
if phase == "done" || phase == "error" { haptics.done() }
|
||||
}
|
||||
}
|
||||
|
||||
private func phaseLabel(_ phase: String, available: Bool) -> String {
|
||||
switch phase {
|
||||
case "thinking": return "Thinking…"
|
||||
case "streaming": return "Replying…"
|
||||
case "error": return "Error"
|
||||
case "done": return "Reply"
|
||||
default: return available ? "Ask something" : "Set up the assistant in Faceclaw's Settings"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Status
|
||||
|
||||
/** Glasses and phone status, with the connection / display / lock switches. */
|
||||
struct StatusScreen: View {
|
||||
@Environment(PhoneLink.self) private var link
|
||||
@Environment(WatchPrefs.self) private var prefs
|
||||
let openSettings: () -> Void
|
||||
|
||||
var body: some View {
|
||||
let state = link.state
|
||||
let connected = state?.connected == true
|
||||
let takesInput = state?.takesInput == true
|
||||
let haptics = Haptics(prefs: prefs)
|
||||
ScrollView {
|
||||
VStack(spacing: 4) {
|
||||
SectionHeader("Glasses")
|
||||
Button {
|
||||
haptics.click()
|
||||
link.sendCommand(connected ? PhoneCommand.disconnect : PhoneCommand.connect)
|
||||
} label: {
|
||||
RowLabel(title: connectionLabel(state), detail: connected ? "tap to disconnect" : "tap to connect")
|
||||
}
|
||||
.tint(connected ? StatusTone.good.color : nil)
|
||||
.disabled(link.link.appRunning == false)
|
||||
|
||||
let screenOn = state?.screenOn == true
|
||||
Button {
|
||||
haptics.click()
|
||||
link.sendCommand(screenOn ? PhoneCommand.sleep : PhoneCommand.wake)
|
||||
} label: {
|
||||
RowLabel(title: screenOn ? "Display on" : "Display off", detail: screenOn ? "tap to turn off" : "tap to wake")
|
||||
}
|
||||
.disabled(!takesInput || state?.locked == true)
|
||||
|
||||
let locked = state?.locked == true
|
||||
Button {
|
||||
haptics.click()
|
||||
link.sendCommand(locked ? PhoneCommand.unlock : PhoneCommand.lock)
|
||||
} label: {
|
||||
RowLabel(title: locked ? "Locked" : "Unlocked", detail: lockDetail(locked: locked, state: state))
|
||||
}
|
||||
.disabled(!takesInput || (locked && state?.canUnlock == false))
|
||||
|
||||
if let foreground = state?.foreground {
|
||||
Button {
|
||||
haptics.click()
|
||||
link.sendCommand(PhoneCommand.sidebar)
|
||||
} label: {
|
||||
RowLabel(title: "On screen: \(foreground.title)", detail: "tap to open the sidebar")
|
||||
}
|
||||
.disabled(!takesInput)
|
||||
}
|
||||
|
||||
SectionHeader("Phone")
|
||||
Button {
|
||||
haptics.click()
|
||||
link.refresh()
|
||||
} label: {
|
||||
Label {
|
||||
RowLabel(title: phoneLabel, detail: phoneDetail(state))
|
||||
} icon: {
|
||||
Image(systemName: "arrow.clockwise")
|
||||
}
|
||||
}
|
||||
|
||||
if state?.remoteEnabled == false {
|
||||
Text("Watch control is turned off in Faceclaw's Settings > Watch.")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
}
|
||||
|
||||
Button(action: openSettings) {
|
||||
Label("Watch settings", systemImage: "gearshape").frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
}
|
||||
}
|
||||
.navigationTitle("Status")
|
||||
}
|
||||
|
||||
private func connectionLabel(_ state: PhoneState?) -> String {
|
||||
guard let state else { return "No status yet" }
|
||||
if state.charging || state.phase == "charging" { return "Charging" }
|
||||
if state.connected { return "Connected" }
|
||||
switch state.phase {
|
||||
case "connecting": return "Connecting…"
|
||||
case "retrying": return "Reconnecting…"
|
||||
case "disconnecting": return "Disconnecting…"
|
||||
default: return state.preview ? "Phone preview" : "Disconnected"
|
||||
}
|
||||
}
|
||||
|
||||
private func lockDetail(locked: Bool, state: PhoneState?) -> String {
|
||||
if locked && state?.canUnlock == false { return "unlock from the phone" }
|
||||
return locked ? "tap to unlock" : "tap to lock"
|
||||
}
|
||||
|
||||
private var phoneLabel: String {
|
||||
let status = link.link
|
||||
if !status.phoneAppInstalled { return "Faceclaw not installed" }
|
||||
if !status.phoneReachable { return "No phone connected" }
|
||||
if status.appRunning == false { return "Faceclaw not running" }
|
||||
return "iPhone"
|
||||
}
|
||||
|
||||
private func phoneDetail(_ state: PhoneState?) -> String {
|
||||
let status = link.link
|
||||
if !status.phoneAppInstalled { return "install it on the phone" }
|
||||
if !status.phoneReachable { return "check Bluetooth" }
|
||||
if status.appRunning == false { return "open it on the phone" }
|
||||
if let version = state?.version, !version.isEmpty { return "Faceclaw v\(version)" }
|
||||
return "tap to refresh"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Settings
|
||||
|
||||
/** Watch-local preferences: feel of the pad and crown. */
|
||||
struct SettingsScreen: View {
|
||||
@Environment(WatchPrefs.self) private var prefs
|
||||
|
||||
var body: some View {
|
||||
@Bindable var prefs = prefs
|
||||
ScrollView {
|
||||
VStack(spacing: 4) {
|
||||
Toggle("Vibrate on input", isOn: $prefs.haptics)
|
||||
Button {
|
||||
prefs.crownSensitivity = prefs.crownSensitivity.next
|
||||
} label: {
|
||||
RowLabel(title: "Crown sensitivity", detail: prefs.crownSensitivity.rawValue)
|
||||
}
|
||||
Text("To keep the remote open between glances, set Settings > General > Return to Clock > Faceclaw on the watch.")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
.multilineTextAlignment(.center)
|
||||
.padding(.top, 6)
|
||||
Text("Faceclaw watch v\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "?")")
|
||||
.font(.caption2)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
.navigationTitle("Settings")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import Foundation
|
||||
import WatchKit
|
||||
|
||||
/** The watch's own charge level and charging state, for the glasses' battery indicators. */
|
||||
struct WatchBatteryReading: Equatable {
|
||||
var battery: Int?
|
||||
var charging: Bool
|
||||
|
||||
/** `at` lets the phone discount a report it finds long after it was left in the application context. */
|
||||
func payload(at date: Date) -> [String: Any] {
|
||||
[
|
||||
"battery": battery ?? NSNull(),
|
||||
"charging": charging,
|
||||
"at": Int64(date.timeIntervalSince1970 * 1000),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
enum WatchBattery {
|
||||
/** The `.backgroundTask(.appRefresh(...))` identifier. */
|
||||
static let refreshIdentifier = "battery"
|
||||
|
||||
private static let refreshInterval: TimeInterval = 30 * 60
|
||||
|
||||
@MainActor
|
||||
static func read() -> WatchBatteryReading {
|
||||
let device = WKInterfaceDevice.current()
|
||||
device.isBatteryMonitoringEnabled = true
|
||||
// Unknown (the simulator, or just after enabling monitoring) is not a reading of 0%.
|
||||
let level = device.batteryLevel
|
||||
let known = device.batteryState != .unknown && level >= 0
|
||||
let percent = known ? min(100, Int((level * 100).rounded())) : nil
|
||||
return WatchBatteryReading(
|
||||
battery: percent,
|
||||
charging: device.batteryState == .charging || device.batteryState == .full
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
A closed app can't answer the phone's battery polls, so it asks to be woken
|
||||
now and then to leave a report behind. The system decides when, and may
|
||||
decline; the phone discards the level once it goes stale.
|
||||
*/
|
||||
@MainActor
|
||||
static func scheduleBackgroundRefresh() {
|
||||
WKApplication.shared().scheduleBackgroundRefresh(
|
||||
withPreferredDate: Date(timeIntervalSinceNow: refreshInterval),
|
||||
userInfo: refreshIdentifier as NSString
|
||||
) { _ in }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import Foundation
|
||||
import Observation
|
||||
import SwiftUI
|
||||
import WatchKit
|
||||
|
||||
enum CrownSensitivity: String, CaseIterable {
|
||||
case low = "Low"
|
||||
case normal = "Normal"
|
||||
case high = "High"
|
||||
|
||||
var next: CrownSensitivity {
|
||||
let all = Self.allCases
|
||||
return all[(all.firstIndex(of: self)! + 1) % all.count]
|
||||
}
|
||||
|
||||
var digitalCrown: DigitalCrownRotationalSensitivity {
|
||||
switch self {
|
||||
case .low: return .low
|
||||
case .normal: return .medium
|
||||
case .high: return .high
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Watch-local preferences (nothing here is synced to the phone). */
|
||||
@MainActor
|
||||
@Observable
|
||||
final class WatchPrefs {
|
||||
/** Buzz on every gesture sent, and tick on crown detents. */
|
||||
var haptics: Bool {
|
||||
didSet { store.set(haptics, forKey: Keys.haptics) }
|
||||
}
|
||||
|
||||
var crownSensitivity: CrownSensitivity {
|
||||
didSet { store.set(crownSensitivity.rawValue, forKey: Keys.crown) }
|
||||
}
|
||||
|
||||
@ObservationIgnored private let store = UserDefaults.standard
|
||||
|
||||
private enum Keys {
|
||||
static let haptics = "haptics"
|
||||
static let crown = "crownSensitivity"
|
||||
}
|
||||
|
||||
init() {
|
||||
haptics = store.object(forKey: Keys.haptics) as? Bool ?? true
|
||||
crownSensitivity = store.string(forKey: Keys.crown).flatMap(CrownSensitivity.init(rawValue:)) ?? .normal
|
||||
}
|
||||
}
|
||||
|
||||
/** The wrist's confirmation of what was sent. */
|
||||
@MainActor
|
||||
struct Haptics {
|
||||
let prefs: WatchPrefs
|
||||
|
||||
/** A sent click, swipe or command. */
|
||||
func click() { play(.click) }
|
||||
/** A sent double-click: back. */
|
||||
func doubleClick() { play(.directionDown) }
|
||||
/** The start of a hold. */
|
||||
func heavy() { play(.start) }
|
||||
/** A reply finished arriving. */
|
||||
func done() { play(.success) }
|
||||
|
||||
/** The phone refused or did not answer; always plays. */
|
||||
func error() { WKInterfaceDevice.current().play(.failure) }
|
||||
|
||||
private func play(_ type: WKHapticType) {
|
||||
if prefs.haptics { WKInterfaceDevice.current().play(type) }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user