Sources/OrgstarMobile/LiveClock.swift

71 lines · 3415 bytes

 1#if os(iOS)
 2import ActivityKit
 3import AppIntents
 4import OrgApp
 5import WidgetKit
 6
 7/// The running clock's Live Activity: one while a clock runs, started when it starts and
 8/// ended when it stops, however that happens.
 9@MainActor
10enum LiveClock {
11    nonisolated private static func isLive(_ activity: Activity<ClockActivityAttributes>) -> Bool {
12        activity.activityState == .active || activity.activityState == .stale
13    }
14
15    nonisolated private static func shows(_ activity: Activity<ClockActivityAttributes>, _ running: ClockModel.Running) -> Bool {
16        activity.attributes.path == running.path && activity.attributes.start == running.start
17    }
18
19    /// Ends activities of other clocks; starts one for `running` unless it has one.
20    nonisolated static func sync(_ running: ClockModel.Running?) async {
21        let activities = Activity<ClockActivityAttributes>.activities.filter(isLive)
22        for activity in activities where running.map({ !shows(activity, $0) }) ?? true {
23            await activity.end(nil, dismissalPolicy: .immediate)
24        }
25        guard let running, !activities.contains(where: { shows($0, running) }), ActivityAuthorizationInfo().areActivitiesEnabled else { return }
26        let state = ClockActivityAttributes.ContentState(heading: running.heading, startedAt: running.startedAt)
27        _ = try? Activity.request(
28            attributes: ClockActivityAttributes(path: running.path, start: running.start), content: ActivityContent(state: state, staleDate: nil)
29        )
30    }
31
32    /// The clock control's state: the running clock, and the entry Clock In Last would take.
33    static func publish(_ clock: ClockModel) {
34        let snapshot = ClockSnapshot(running: clock.running?.heading, startedAt: clock.running?.startedAt, last: clock.history.first?.title)
35        if (try? snapshot.write()) == true { ControlCenter.shared.reloadControls(ofKind: "sh.krz.orgstar.clock-control") }
36    }
37
38    /// The Clock Out button's work, in the app's process, and the capture and clock controls'.
39    static func install() {
40        ClockOutIntent.handler = clockOut
41        ClockToggleIntent.handler = { on in
42            guard on else { return await clockOut() }
43            // Asks in the app if a dangling clock needs resolving.
44            let model = MobileModel.shared
45            guard let workspace = model.workspace else { return }
46            let paths = workspace.files.filter { $0.kind == .org }.map(\.path)
47            _ = await model.clock.clockIn(model.session, target: .last, paths: paths, ask: model.clockPrompts.ask)
48            for path in model.session.dirtyPaths { _ = model.session.save(path) }
49            await sync(model.clock.running)
50            publish(model.clock)
51        }
52        OpenCaptureIntent.handler = { template in
53            MobileModel.shared.captureRequest = CaptureRequest(template: template)
54        }
55    }
56
57    private static func clockOut() async {
58        let model = MobileModel.shared
59        let path = model.clock.running?.path
60        _ = model.clock.clockOut(model.session)
61        if let path, model.session.dirtyPaths.contains(path) { _ = model.session.save(path) }
62        await sync(model.clock.running)
63        publish(model.clock)
64    }
65}
66
67/// The App Intents OrgApp declares.
68struct OrgstarIntents: AppIntentsPackage {
69    static var includedPackages: [any AppIntentsPackage.Type] { [OrgAppIntents.self] }
70}
71#endif