Sources/OrgstarMobile/WatchLink.swift
90 lines · 3798 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgWatchData
5import UIKit
6import WatchConnectivity
7
8/// The watch, over WatchConnectivity: today's agenda and the clock go to it as the application
9/// context, whenever the widgets update or the clock changes; what it asks for (done, clock out
10/// or in, a dictated capture) runs here. iOS wakes the app for those when it isn't running.
11@MainActor
12final class WatchLink: NSObject, WCSessionDelegate {
13 static let shared = WatchLink()
14
15 weak var model: MobileModel?
16 /// The last agenda sent, so an unchanged one isn't sent again.
17 private var sent: Data?
18
19 func activate(_ model: MobileModel) {
20 self.model = model
21 guard WCSession.isSupported(), WCSession.default.delegate == nil else { return }
22 WCSession.default.delegate = self
23 WCSession.default.activate()
24 }
25
26 /// Sends `agenda` when a watch is paired and it changed. Without the watch app installed,
27 /// updating the context fails, and nothing is kept as sent.
28 func send(_ agenda: WatchAgenda) {
29 let session = WCSession.default
30 guard WCSession.isSupported(), session.activationState == .activated, session.isPaired,
31 let data = try? agenda.data(), data != sent else { return }
32 do {
33 try session.updateApplicationContext([WatchAgenda.contextKey: data])
34 sent = data
35 } catch {}
36 }
37
38 func perform(_ action: WatchAction) async {
39 guard ProAccess.shared.isUnlocked, let model, let workspace = model.workspace else { return }
40 switch action {
41 case .done(let path, let offset, let headingLine, let keyword):
42 _ = model.session.perform(SetTodo(keyword: keyword), path: path, at: offset, expect: (offset, headingLine))
43 case .clockOut:
44 _ = MobileClock.run("app.clock.out", model: model, workspace: workspace) { _ in }
45 case .clockInLast:
46 _ = MobileClock.run("app.clock.in-last", model: model, workspace: workspace) { _ in }
47 // Clocking in finishes after a moment.
48 try? await Task.sleep(for: .seconds(1))
49 case .capture(let text):
50 // As the share extension leaves text: filed with a template when the app is next open.
51 var components = URLComponents(string: "org-protocol://capture")!
52 components.queryItems = [URLQueryItem(name: "body", value: text)]
53 if let link = components.url?.absoluteString { try? model.inbox?.add(link) }
54 model.watchCaptures += 1
55 }
56 await model.updateWidgets()
57 }
58
59 nonisolated func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
60 Task { @MainActor in
61 guard activationState == .activated else { return }
62 await self.model?.updateWidgets()
63 }
64 }
65
66 nonisolated func session(_ session: WCSession, didReceiveUserInfo userInfo: [String: Any] = [:]) {
67 guard let action = WatchAction(userInfo: userInfo) else { return }
68 Task { @MainActor in await self.perform(action) }
69 }
70
71 nonisolated func session(_ session: WCSession, didReceiveMessage message: [String: Any]) {
72 guard let action = WatchAction(userInfo: message) else { return }
73 Task { @MainActor in await self.perform(action) }
74 }
75
76 nonisolated func sessionWatchStateDidChange(_ session: WCSession) {
77 Task { @MainActor in
78 self.sent = nil
79 await self.model?.updateWidgets()
80 }
81 }
82
83 nonisolated func sessionDidBecomeInactive(_ session: WCSession) {}
84
85 nonisolated func sessionDidDeactivate(_ session: WCSession) {
86 // A different watch was chosen: start again for it.
87 session.activate()
88 }
89}
90#endif