Commit 23d8b5c164

23d8b5c1642d9050ce6eb21bcb485c139d66b333

parent: 92e4b38d50

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 23:29 UTC

watchOS app

A watch app with today's agenda from the phone, marking entries done, the running clock with
Clock Out and Clock In Last, and dictated capture into the phone's capture inbox; Up Next and
Clock complications. OrgWatchData holds the payload and actions, sent over WatchConnectivity:
the phone updates the application context with every widget update and clock change, the
watch sends messages when the phone is reachable and transferUserInfo otherwise.
scripts/build-watch-app.sh bundles the SwiftPM products and build-ios-app.sh embeds the app.

Closes #62

Layout: unified · split

Package.swift +11 −3
@@ -6,7 +6,7 @@ let extensionEntry: [LinkerSetting] = [.unsafeFlags(["-Xlinker", "-e", "-Xlinker
66
77let package = Package(
88 name: "Orgstar",
9 platforms: [.macOS(.v26), .iOS(.v26)],
9 platforms: [.macOS(.v26), .iOS(.v26), .watchOS(.v26)],
1010 products: [
1111 .library(name: "OrgCore", targets: ["OrgCore"]),
1212 .library(name: "OrgDocument", targets: ["OrgDocument"]),
@@ -22,7 +22,9 @@ let package = Package(
2222 .executable(name: "OrgstarQuickLook", targets: ["OrgstarQuickLook"]),
2323 .executable(name: "OrgstarSpotlight", targets: ["OrgstarSpotlight"]),
2424 .executable(name: "OrgstarShare", targets: ["OrgstarShare"]),
25 .executable(name: "OrgstarWidgets", targets: ["OrgstarWidgets"])
25 .executable(name: "OrgstarWidgets", targets: ["OrgstarWidgets"]),
26 .executable(name: "OrgstarWatch", targets: ["OrgstarWatch"]),
27 .executable(name: "OrgstarWatchWidgets", targets: ["OrgstarWatchWidgets"])
2628 ],
2729 dependencies: [
2830 .package(url: "https://github.com/groue/GRDB.swift", from: "7.11.1"),
@@ -84,7 +86,12 @@ let package = Package(
8486 ]
8587 ),
8688 .executableTarget(name: "OrgstarSpike", dependencies: ["OrgEditorAppKit"]),
87 .target(name: "OrgApp", dependencies: ["OrgWorkspace", "OrgDocument", "OrgPresentation"]),
89 .target(name: "OrgApp", dependencies: ["OrgWorkspace", "OrgDocument", "OrgPresentation", "OrgWatchData"]),
90 // What the phone and the watch send each other; Foundation only, so the watch builds it.
91 .target(name: "OrgWatchData"),
92 // The watch app and its complications, bundled by scripts/build-watch-app.sh.
93 .executableTarget(name: "OrgstarWatch", dependencies: ["OrgWatchData"]),
94 .executableTarget(name: "OrgstarWatchWidgets", dependencies: ["OrgWatchData"]),
8895 .executableTarget(name: "Orgstar", dependencies: ["OrgApp", "OrgEditorAppKit", "OrgHighlight", .product(name: "Sparkle", package: "Sparkle")]),
8996 // The iOS app, bundled by scripts/build-ios-app.sh.
9097 .executableTarget(name: "OrgstarMobile", dependencies: ["OrgApp", "OrgHighlight"]),
@@ -98,6 +105,7 @@ let package = Package(
98105 .executableTarget(name: "OrgstarWidgets", dependencies: ["OrgApp"]),
99106 .testTarget(name: "OrgCoreTests", dependencies: ["OrgCore"], exclude: ["Conformance"]),
100107 .testTarget(name: "OrgDocumentTests", dependencies: ["OrgDocument"]),
108 .testTarget(name: "OrgWatchDataTests", dependencies: ["OrgWatchData"]),
101109 .testTarget(name: "OrgIndexTests", dependencies: ["OrgIndex"]),
102110 .testTarget(name: "OrgWorkspaceTests", dependencies: ["OrgWorkspace"]),
103111 .testTarget(name: "OrgPresentationTests", dependencies: ["OrgPresentation"]),
Sources/OrgApp/WatchPayload.swift added +27
@@ -0,0 +1,27 @@
1import Foundation
2import OrgPresentation
3import OrgWatchData
4
5extension WatchAgenda {
6 /// Today's group of the agenda, for the watch, with the running clock and the entry
7 /// Clock In Last would take.
8 public init(groups: [AgendaDayGroup], today: Int, clock: ClockModel.Running?, lastClocked: String?, generated: Date, calendar: Calendar = .current) {
9 let group = groups.first { $0.day == today }
10 let midnight = group?.date(calendar: calendar) ?? calendar.startOfDay(for: generated)
11 func entry(_ row: AgendaRow) -> Entry {
12 func at(_ hhmm: Int?) -> Date? {
13 hhmm.flatMap { calendar.date(byAdding: .minute, value: ($0 / 100) * 60 + $0 % 100, to: midnight) }
14 }
15 let item = row.item
16 return Entry(
17 id: row.id, title: row.title, gutter: row.gutter, category: row.category, todo: row.todo, status: row.status.rawValue,
18 isDone: row.isDone, isEvent: row.isEvent, start: at(row.start), end: at(row.end), path: item?.path,
19 offset: item?.headingOffset, headingLine: item?.headingLine, doneKeyword: item?.doneKeyword
20 )
21 }
22 self.init(
23 generated: generated, day: midnight, overdue: group?.overdue.map(entry) ?? [], rows: group?.rows.map(entry) ?? [],
24 clock: clock.map { Clock(heading: $0.heading, startedAt: $0.startedAt) }, lastClocked: lastClocked
25 )
26 }
27}
Sources/OrgWatchData/WatchAgenda.swift added +188
@@ -0,0 +1,188 @@
1import Foundation
2
3/// What the watch shows, sent by the phone over WatchConnectivity: today's agenda, the running
4/// clock and the entry Clock In Last would take. The watch keeps the last one it got.
5public struct WatchAgenda: Codable, Equatable, Sendable {
6 public struct Entry: Codable, Equatable, Sendable, Identifiable {
7 public var id: String
8 public var title: String
9 /// The agenda's gutter: the time or a short status.
10 public var gutter: String
11 public var category: String
12 public var todo: String?
13 /// `AgendaRow.Status`'s raw value: `overdue`, `due-soon`, `normal`, `done`.
14 public var status: String
15 public var isDone: Bool
16 public var isEvent: Bool
17 public var start: Date?
18 public var end: Date?
19 /// Where the entry is, and its heading line, for the phone to find it again.
20 public var path: String?
21 public var offset: Int?
22 public var headingLine: String?
23 /// The keyword marking it done takes: the first done keyword of its sequence.
24 public var doneKeyword: String?
25
26 public init(
27 id: String, title: String, gutter: String, category: String, todo: String?, status: String, isDone: Bool, isEvent: Bool,
28 start: Date?, end: Date?, path: String?, offset: Int?, headingLine: String?, doneKeyword: String?
29 ) {
30 self.id = id
31 self.title = title
32 self.gutter = gutter
33 self.category = category
34 self.todo = todo
35 self.status = status
36 self.isDone = isDone
37 self.isEvent = isEvent
38 self.start = start
39 self.end = end
40 self.path = path
41 self.offset = offset
42 self.headingLine = headingLine
43 self.doneKeyword = doneKeyword
44 }
45
46 /// An open TODO entry the phone can find.
47 public var canBeDone: Bool {
48 !isDone && !isEvent && todo != nil && doneKeyword != nil && path != nil && offset != nil && headingLine != nil
49 }
50
51 /// The action marking it done.
52 public var done: WatchAction? {
53 guard canBeDone, let path, let offset, let headingLine, let doneKeyword else { return nil }
54 return .done(path: path, offset: offset, headingLine: headingLine, keyword: doneKeyword)
55 }
56 }
57
58 public struct Clock: Codable, Equatable, Sendable {
59 public var heading: String
60 public var startedAt: Date
61
62 public init(heading: String, startedAt: Date) {
63 self.heading = heading
64 self.startedAt = startedAt
65 }
66 }
67
68 public var generated: Date
69 /// Midnight starting today.
70 public var day: Date
71 /// Deadlines and scheduled entries from before today.
72 public var overdue: [Entry]
73 public var rows: [Entry]
74 public var clock: Clock?
75 /// The most recently clocked entry, `org-clock-in-last`'s.
76 public var lastClocked: String?
77
78 public init(generated: Date, day: Date, overdue: [Entry], rows: [Entry], clock: Clock?, lastClocked: String?) {
79 self.generated = generated
80 self.day = day
81 self.overdue = overdue
82 self.rows = rows
83 self.clock = clock
84 self.lastClocked = lastClocked
85 }
86
87 /// What's left of today at `now`, as the Up Next widget counts it: entries that aren't
88 /// done, without timed ones that have ended (or started, with no end), then the overdue.
89 public func upcoming(at now: Date, calendar: Calendar = .current) -> [Entry] {
90 guard calendar.isDate(day, inSameDayAs: now) else { return [] }
91 let left = rows.filter { row in
92 guard !row.isDone else { return false }
93 if let end = row.end ?? row.start { return end > now }
94 return true
95 }
96 return left + overdue.filter { !$0.isDone }
97 }
98
99 /// The first of `upcoming`.
100 public func next(at now: Date, calendar: Calendar = .current) -> Entry? { upcoming(at: now, calendar: calendar).first }
101
102 /// Open TODO entries today and overdue, as the complication counts them.
103 public func openCount(at now: Date, calendar: Calendar = .current) -> Int {
104 guard calendar.isDate(day, inSameDayAs: now) else { return 0 }
105 return (rows + overdue).filter { !$0.isDone && !$0.isEvent && $0.todo != nil }.count
106 }
107
108 /// `entry` marked done here before the phone sends the agenda again.
109 public func markingDone(_ id: String) -> WatchAgenda {
110 var copy = self
111 func mark(_ rows: inout [Entry]) {
112 for i in rows.indices where rows[i].id == id {
113 rows[i].isDone = true
114 rows[i].todo = rows[i].doneKeyword
115 rows[i].status = "done"
116 }
117 }
118 mark(&copy.rows)
119 mark(&copy.overdue)
120 return copy
121 }
122
123 // MARK: - Transfer
124
125 static var encoder: JSONEncoder {
126 let encoder = JSONEncoder()
127 encoder.dateEncodingStrategy = .iso8601
128 encoder.outputFormatting = [.sortedKeys]
129 return encoder
130 }
131
132 static var decoder: JSONDecoder {
133 let decoder = JSONDecoder()
134 decoder.dateDecodingStrategy = .iso8601
135 return decoder
136 }
137
138 /// The application context key the agenda travels under.
139 public static let contextKey = "agenda"
140
141 public func data() throws -> Data { try Self.encoder.encode(self) }
142
143 public static func decode(_ data: Data) -> WatchAgenda? { try? decoder.decode(WatchAgenda.self, from: data) }
144
145 /// `Widgets/watch.json` in the app group's container, which the complications read; nil
146 /// without the group.
147 public static func file(group: String = "group.sh.krz.orgstar") -> URL? {
148 FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
149 .appendingPathComponent("Widgets").appendingPathComponent("watch.json")
150 }
151
152 public static func read(from file: URL? = file()) -> WatchAgenda? {
153 file.flatMap { try? Data(contentsOf: $0) }.flatMap(decode)
154 }
155
156 /// Writes unless the file holds the same; true when it wrote.
157 @discardableResult
158 public func write(to file: URL? = WatchAgenda.file()) throws -> Bool {
159 guard let file, Self.read(from: file) != self else { return false }
160 try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
161 try data().write(to: file, options: .atomic)
162 return true
163 }
164}
165
166/// What the watch asks the phone to do.
167public enum WatchAction: Codable, Equatable, Sendable {
168 /// Sets the entry's keyword to `keyword`, if its heading line is still `headingLine`.
169 case done(path: String, offset: Int, headingLine: String, keyword: String)
170 case clockOut
171 /// `org-clock-in-last`.
172 case clockInLast
173 /// Dictated text for the capture inbox.
174 case capture(text: String)
175
176 /// The user info key an action travels under.
177 public static let key = "action"
178
179 public var userInfo: [String: Any] {
180 guard let data = try? WatchAgenda.encoder.encode(self) else { return [:] }
181 return [Self.key: data]
182 }
183
184 public init?(userInfo: [String: Any]) {
185 guard let data = userInfo[Self.key] as? Data, let action = try? WatchAgenda.decoder.decode(WatchAction.self, from: data) else { return nil }
186 self = action
187 }
188}
Sources/OrgstarMobile/MobileModel.swift +4
@@ -5,6 +5,7 @@ import OrgApp
55import OrgCore
66import OrgIndex
77import OrgPresentation
8import OrgWatchData
89import OrgWorkspace
910import UIKit
1011import UserNotifications
@@ -40,6 +41,8 @@ final class MobileModel {
4041 var captureRequest: CaptureRequest?
4142 /// Calendar's events for the agenda, with `calendar-events`.
4243 let calendarEvents = CalendarEvents()
44 /// Captures the watch sent, for the root view to pick up from the inbox.
45 var watchCaptures = 0
4346 /// Reminders for the agenda, with `agenda-reminders`.
4447 let reminderLists = ReminderLists()
4548
@@ -295,6 +298,7 @@ final class MobileModel {
295298 }
296299 await days.refresh(open: session.openTexts)
297300 let groups = days.groups()
301 WatchLink.shared.send(WatchAgenda(groups: groups, today: days.today, clock: clock.running, lastClocked: clock.history.first?.title, generated: Date()))
298302 await updateBadge(OverdueBadge.counts(groups, today: days.today, days: AgendaSnapshot.dayCount))
299303 if (try? HabitSnapshot(habits: await days.habits(open: session.openTexts), theme: theme).write()) == true { WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits") }
300304 _ = try? TemplateList(templates: CaptureTemplates.load().templates.map { .init(key: $0.key, name: $0.name) }).write()
Sources/OrgstarMobile/OrgstarMobileApp.swift +5
@@ -19,6 +19,8 @@ struct OrgstarMobileApp: App {
1919 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
2020 #endif
2121 LiveClock.install()
22 // Early, so that the watch's actions are taken when iOS wakes the app for them.
23 WatchLink.shared.activate(MobileModel.shared)
2224 }
2325
2426 var body: some Scene {
@@ -302,7 +304,10 @@ struct RootView: View {
302304 .onChange(of: model.clock.running) {
303305 LiveClock.publish(model.clock)
304306 Task { await LiveClock.sync(model.clock.running) }
307 Task { await model.updateWidgets() }
305308 }
309 // A capture dictated on the watch, while the app is open.
310 .onChange(of: model.watchCaptures) { takeShared() }
306311 }
307312
308313 /// What the share extension left, one capture sheet at a time.
Sources/OrgstarMobile/WatchLink.swift added +90
@@ -0,0 +1,90 @@
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 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
Sources/OrgstarWatch/WatchApp.swift added +180
@@ -0,0 +1,180 @@
1#if os(watchOS)
2import OrgWatchData
3import SwiftUI
4import WatchConnectivity
5import WidgetKit
6
7/// orgstar on the watch: today's agenda from the phone, marking entries done, the running
8/// clock, and dictated capture into the phone's capture inbox.
9@main
10struct OrgstarWatchApp: App {
11 @State private var link = PhoneLink.shared
12
13 var body: some Scene {
14 WindowGroup {
15 NavigationStack { AgendaList(link: link) }
16 .onAppear { link.activate() }
17 }
18 }
19}
20
21/// The phone, over WatchConnectivity: the agenda it last sent, and the actions sent to it.
22/// Actions go as a message when the phone is reachable, which wakes the app there, else with
23/// `transferUserInfo`, which waits for it.
24@MainActor
25@Observable
26final class PhoneLink: NSObject, WCSessionDelegate {
27 static let shared = PhoneLink()
28
29 private(set) var agenda: WatchAgenda? = WatchAgenda.read()
30 /// Captures sent and not yet acknowledged by the next agenda.
31 private(set) var sentCaptures = 0
32
33 func activate() {
34 guard WCSession.isSupported(), WCSession.default.delegate == nil else { return }
35 WCSession.default.delegate = self
36 WCSession.default.activate()
37 }
38
39 func send(_ action: WatchAction) {
40 switch action {
41 case .done:
42 if case .done(_, let offset, _, _) = action, let agenda,
43 let entry = (agenda.rows + agenda.overdue).first(where: { $0.offset == offset && $0.done == action }) {
44 store(agenda.markingDone(entry.id))
45 }
46 case .clockOut:
47 if var agenda {
48 agenda.lastClocked = agenda.clock?.heading ?? agenda.lastClocked
49 agenda.clock = nil
50 store(agenda)
51 }
52 case .capture:
53 sentCaptures += 1
54 case .clockInLast:
55 break
56 }
57 let session = WCSession.default
58 guard session.activationState == .activated else { return }
59 let info = action.userInfo
60 if session.isReachable {
61 session.sendMessage(info, replyHandler: nil) { _ in session.transferUserInfo(info) }
62 } else {
63 session.transferUserInfo(info)
64 }
65 }
66
67 private func store(_ new: WatchAgenda) {
68 agenda = new
69 if (try? new.write()) == true { WidgetCenter.shared.reloadAllTimelines() }
70 }
71
72 private func received(_ new: WatchAgenda?) {
73 guard let new else { return }
74 store(new)
75 sentCaptures = 0
76 }
77
78 nonisolated private static func agenda(in context: [String: Any]) -> WatchAgenda? {
79 (context[WatchAgenda.contextKey] as? Data).flatMap(WatchAgenda.decode)
80 }
81
82 nonisolated func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
83 let new = Self.agenda(in: session.receivedApplicationContext)
84 Task { @MainActor in self.received(new) }
85 }
86
87 nonisolated func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) {
88 let new = Self.agenda(in: applicationContext)
89 Task { @MainActor in self.received(new) }
90 }
91}
92
93/// Today: the running clock, capture, and the entries, each of which a tap marks done.
94struct AgendaList: View {
95 let link: PhoneLink
96 @State private var capturing = false
97 @State private var dictated = ""
98
99 var body: some View {
100 List {
101 if let clock = link.agenda?.clock {
102 Section("Clocked In") {
103 VStack(alignment: .leading, spacing: 2) {
104 Text(clock.heading).font(.headline).lineLimit(2)
105 Text(clock.startedAt, style: .timer).font(.title3.monospacedDigit()).foregroundStyle(.green)
106 }
107 Button("Clock Out", systemImage: "stop.circle") { link.send(.clockOut) }.tint(.red)
108 }
109 } else if let last = link.agenda?.lastClocked {
110 Section("Clock") {
111 Button { link.send(.clockInLast) } label: {
112 Label { Text("Clock In to \(last)").lineLimit(2) } icon: { Image(systemName: "play.circle") }
113 }
114 }
115 }
116 Section {
117 TextField("Capture", text: $dictated)
118 .onSubmit {
119 let text = dictated.trimmingCharacters(in: .whitespacesAndNewlines)
120 dictated = ""
121 if !text.isEmpty { link.send(.capture(text: text)) }
122 }
123 if link.sentCaptures > 0 {
124 Text(link.sentCaptures == 1 ? "Sent to orgstar on iPhone." : "\(link.sentCaptures) sent to orgstar on iPhone.")
125 .font(.footnote).foregroundStyle(.secondary)
126 }
127 } footer: {
128 Text("orgstar files it with a template when you next open it on iPhone.")
129 }
130 if let agenda = link.agenda {
131 if !agenda.overdue.isEmpty {
132 Section("Overdue") { ForEach(agenda.overdue) { EntryRow(entry: $0, link: link) } }
133 }
134 Section(agenda.day.formatted(.dateTime.weekday(.wide).day().month())) {
135 if agenda.rows.isEmpty { Text("Nothing scheduled").foregroundStyle(.secondary) }
136 ForEach(agenda.rows) { EntryRow(entry: $0, link: link) }
137 }
138 } else {
139 Text("Open orgstar on your iPhone to show your agenda here.").foregroundStyle(.secondary)
140 }
141 }
142 .navigationTitle("Today")
143 }
144}
145
146struct EntryRow: View {
147 let entry: WatchAgenda.Entry
148 let link: PhoneLink
149
150 var body: some View {
151 if let done = entry.done {
152 Button { link.send(done) } label: { content(symbol: "circle") }
153 .accessibilityHint("Marks it \(entry.doneKeyword ?? "done")")
154 } else {
155 content(symbol: entry.isDone ? "checkmark.circle.fill" : entry.isEvent ? "calendar" : nil)
156 }
157 }
158
159 private func content(symbol: String?) -> some View {
160 HStack(alignment: .top, spacing: 6) {
161 if let symbol {
162 Image(systemName: symbol).foregroundStyle(entry.isDone ? .green : .secondary)
163 }
164 VStack(alignment: .leading, spacing: 1) {
165 if !entry.gutter.isEmpty {
166 Text(entry.gutter).font(.caption2).foregroundStyle(entry.status == "overdue" ? .red : .secondary)
167 }
168 Text(entry.title).strikethrough(entry.isDone).lineLimit(3)
169 if let todo = entry.todo { Text(todo).font(.caption2.weight(.semibold)).foregroundStyle(entry.isDone ? .green : .orange) }
170 }
171 }
172 }
173}
174#else
175/// The watch app builds for watchOS only; elsewhere the product does nothing.
176@main
177enum OrgstarWatchApp {
178 static func main() {}
179}
180#endif
Sources/OrgstarWatchWidgets/WatchWidgets.swift added +132
@@ -0,0 +1,132 @@
1#if os(watchOS)
2import OrgWatchData
3import SwiftUI
4import WidgetKit
5
6/// Complications: the next agenda entry, and the running clock.
7@main
8struct OrgstarWatchWidgets: WidgetBundle {
9 var body: some Widget {
10 NextEntryComplication()
11 ClockComplication()
12 }
13}
14
15struct WatchEntry: TimelineEntry {
16 let date: Date
17 let agenda: WatchAgenda?
18}
19
20/// The agenda the watch app last got, with an entry at each change of what's next.
21struct WatchProvider: TimelineProvider {
22 func placeholder(in context: Context) -> WatchEntry { WatchEntry(date: .now, agenda: nil) }
23
24 func getSnapshot(in context: Context, completion: @escaping (WatchEntry) -> Void) {
25 completion(WatchEntry(date: .now, agenda: WatchAgenda.read()))
26 }
27
28 func getTimeline(in context: Context, completion: @escaping (Timeline<WatchEntry>) -> Void) {
29 let agenda = WatchAgenda.read()
30 let now = Date()
31 var dates = [now]
32 for row in agenda?.rows ?? [] {
33 if let end = row.end ?? row.start, end > now { dates.append(end.addingTimeInterval(60)) }
34 }
35 if let midnight = Calendar.current.date(byAdding: .day, value: 1, to: Calendar.current.startOfDay(for: now)) { dates.append(midnight) }
36 let entries = Set(dates).sorted().map { WatchEntry(date: $0, agenda: agenda) }
37 completion(Timeline(entries: entries, policy: .never))
38 }
39}
40
41struct NextEntryComplication: Widget {
42 var body: some WidgetConfiguration {
43 StaticConfiguration(kind: "sh.krz.orgstar.watch.next", provider: WatchProvider()) { entry in
44 NextEntryView(entry: entry).containerBackground(for: .widget) { Color.clear }
45 }
46 .configurationDisplayName("Up Next")
47 .description("The next agenda entry, or how many are open today.")
48 .supportedFamilies([.accessoryRectangular, .accessoryInline, .accessoryCircular, .accessoryCorner])
49 }
50}
51
52struct NextEntryView: View {
53 let entry: WatchEntry
54 @Environment(\.widgetFamily) private var family
55
56 private var next: WatchAgenda.Entry? { entry.agenda?.next(at: entry.date) }
57 private var open: Int { entry.agenda?.openCount(at: entry.date) ?? 0 }
58
59 var body: some View {
60 switch family {
61 case .accessoryInline:
62 Text(next.map { "\($0.gutter) \($0.title)" } ?? (open == 0 ? "Agenda clear" : "\(open) open today"))
63 case .accessoryCircular:
64 ZStack {
65 AccessoryWidgetBackground()
66 VStack(spacing: -2) {
67 Text("\(open)").font(.title3.weight(.semibold)).widgetAccentable()
68 Text("open").font(.caption2)
69 }
70 }
71 case .accessoryCorner:
72 Text("\(open)").font(.title3.weight(.semibold)).widgetLabel { Text(next?.title ?? "Agenda clear") }
73 default:
74 VStack(alignment: .leading, spacing: 0) {
75 Text(next?.gutter ?? "Agenda").font(.headline).widgetAccentable().lineLimit(1)
76 Text(next?.title ?? (entry.agenda == nil ? "Open orgstar" : "Nothing left today")).lineLimit(2)
77 }
78 .frame(maxWidth: .infinity, alignment: .leading)
79 }
80 }
81}
82
83struct ClockComplication: Widget {
84 var body: some WidgetConfiguration {
85 StaticConfiguration(kind: "sh.krz.orgstar.watch.clock", provider: WatchProvider()) { entry in
86 ClockView(entry: entry).containerBackground(for: .widget) { Color.clear }
87 }
88 .configurationDisplayName("Clock")
89 .description("The running clock and its time so far.")
90 .supportedFamilies([.accessoryRectangular, .accessoryInline, .accessoryCircular])
91 }
92}
93
94struct ClockView: View {
95 let entry: WatchEntry
96 @Environment(\.widgetFamily) private var family
97
98 var body: some View {
99 let clock = entry.agenda?.clock
100 switch family {
101 case .accessoryInline:
102 if let clock { Text("\(clock.heading) ") + Text(clock.startedAt, style: .timer) } else { Text("Not clocked in") }
103 case .accessoryCircular:
104 ZStack {
105 AccessoryWidgetBackground()
106 if let clock {
107 Text(clock.startedAt, style: .timer).font(.caption.monospacedDigit()).multilineTextAlignment(.center).widgetAccentable()
108 } else {
109 Image(systemName: "stopwatch").font(.title3)
110 }
111 }
112 default:
113 VStack(alignment: .leading, spacing: 0) {
114 if let clock {
115 Text(clock.startedAt, style: .timer).font(.headline.monospacedDigit()).widgetAccentable()
116 Text(clock.heading).lineLimit(2)
117 } else {
118 Text("Clock").font(.headline).widgetAccentable()
119 Text("Not clocked in").foregroundStyle(.secondary)
120 }
121 }
122 .frame(maxWidth: .infinity, alignment: .leading)
123 }
124 }
125}
126#else
127/// The complications build for watchOS only; elsewhere the product does nothing.
128@main
129enum OrgstarWatchWidgets {
130 static func main() {}
131}
132#endif
Tests/OrgWatchDataTests/WatchAgendaTests.swift added +57
@@ -0,0 +1,57 @@
1import Foundation
2import Testing
3@testable import OrgWatchData
4
5struct WatchAgendaTests {
6 static var utc: Calendar {
7 var c = Calendar(identifier: .gregorian)
8 c.timeZone = TimeZone(identifier: "UTC")!
9 return c
10 }
11
12 static func entry(_ id: String, start: Int? = nil, end: Int? = nil, todo: String? = "TODO", done: Bool = false, event: Bool = false) -> WatchAgenda.Entry {
13 let midnight = utc.date(from: DateComponents(year: 2026, month: 10, day: 12))!
14 func at(_ hhmm: Int?) -> Date? { hhmm.map { midnight.addingTimeInterval(Double(($0 / 100) * 3600 + ($0 % 100) * 60)) } }
15 return WatchAgenda.Entry(
16 id: id, title: id, gutter: start == nil ? "Scheduled" : "", category: "work", todo: todo, status: done ? "done" : "normal", isDone: done,
17 isEvent: event, start: at(start), end: at(end), path: "/n/work.org", offset: 10, headingLine: "* \(todo ?? "") \(id)", doneKeyword: "DONE"
18 )
19 }
20
21 static let agenda = WatchAgenda(
22 generated: Date(timeIntervalSince1970: 0), day: utc.date(from: DateComponents(year: 2026, month: 10, day: 12))!,
23 overdue: [entry("late")],
24 rows: [entry("standup", start: 900, end: 915), entry("lunch", start: 1200, todo: nil, event: true), entry("review", start: 1530),
25 entry("done", done: true), entry("plants")],
26 clock: .init(heading: "Review", startedAt: Date(timeIntervalSince1970: 100)), lastClocked: "Review"
27 )
28
29 @Test func upcomingLeavesOutWhatsOver() {
30 let ten = Self.utc.date(from: DateComponents(year: 2026, month: 10, day: 12, hour: 10))!
31 #expect(Self.agenda.upcoming(at: ten, calendar: Self.utc).map(\.id) == ["lunch", "review", "plants", "late"])
32 #expect(Self.agenda.next(at: ten, calendar: Self.utc)?.id == "lunch")
33 #expect(Self.agenda.openCount(at: ten, calendar: Self.utc) == 4)
34 let tomorrow = ten.addingTimeInterval(86400)
35 #expect(Self.agenda.upcoming(at: tomorrow, calendar: Self.utc).isEmpty && Self.agenda.openCount(at: tomorrow, calendar: Self.utc) == 0)
36 }
37
38 @Test func markingDoneHere() {
39 let marked = Self.agenda.markingDone("late")
40 #expect(marked.overdue[0].isDone && marked.overdue[0].todo == "DONE" && !marked.overdue[0].canBeDone)
41 #expect(Self.agenda.overdue[0].done == .done(path: "/n/work.org", offset: 10, headingLine: "* TODO late", keyword: "DONE"))
42 #expect(Self.agenda.rows[1].done == nil)
43 }
44
45 @Test func roundTrips() throws {
46 #expect(WatchAgenda.decode(try Self.agenda.data()) == Self.agenda)
47 for action in [WatchAction.done(path: "/a.org", offset: 3, headingLine: "* TODO x", keyword: "DONE"), .clockOut, .clockInLast, .capture(text: "Buy milk")] {
48 #expect(WatchAction(userInfo: action.userInfo) == action)
49 }
50 #expect(WatchAction(userInfo: [:]) == nil)
51 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-watch-\(UUID().uuidString)")
52 defer { try? FileManager.default.removeItem(at: folder) }
53 let file = folder.appendingPathComponent("watch.json")
54 #expect(try Self.agenda.write(to: file) && !(try Self.agenda.write(to: file)))
55 #expect(WatchAgenda.read(from: file) == Self.agenda)
56 }
57}
docs/manual/guide/14-ios.org +19
@@ -241,6 +241,25 @@ The widgets and the Live Activity open the app with these links, which also work
241241| =orgstar://clock= | The entry of the running clock |
242242| ~orgstar://entry?path=/path/file.org&offset=N~ | The file in the reader, at offset N |
243243
244* Apple Watch
245
246The watch app shows today's agenda from your iPhone, marks entries done, shows and stops the running clock, and takes dictated captures. It comes with orgstar on iPhone and installs on a paired watch as other watch apps do. It reads nothing itself: your iPhone sends it today's agenda and the clock whenever its widgets update (when files, edits or settings change while orgstar is open, and when you return to it) and whenever the clock starts or stops, and the watch keeps the last one it got. Until it has one, it says =Open orgstar on your iPhone to show your agenda here.=
247
248- Clocked In :: the running clock's heading and its time so far, with Clock Out. Without a running clock, Clock In to /heading/ clocks in to the entry clocked last (=org-clock-in-last=).
249- Capture :: dictate or scribble text, then Done. It goes to orgstar on iPhone, which opens the capture sheet with it as =%i=, with the first template, as text from the share sheet does; see Capture below.
250- Overdue, then today :: as the agenda lists them, with the time or status, the title and the keyword. Tap an open TODO entry to mark it done: it takes its sequence's first done keyword, as the agenda's Done does. The entry shows done at once; the iPhone changes the file, unless the heading changed since the agenda was sent.
251
252What the watch asks for runs on your iPhone, which iOS wakes for it when orgstar isn't open; while the iPhone is out of reach, the requests wait and run when it is back.
253
254** Complications
255
256| Complication | Families | Shows |
257|--------------+-------------------------------------------+------------------------------------------------------------------------------------|
258| Up Next | Rectangular, inline, circular and corner | The next entry's time or status and title (rectangular, inline, corner), or the count of open TODO entries today (circular, and corner) |
259| Clock | Rectangular, inline and circular | The running clock's time so far and heading, or =Not clocked in= |
260
261They read the agenda the watch app last got, and move on by themselves as timed entries end and at midnight.
262
244263* Capture
245264
246265Tap Capture (the pencil icon) in the Agenda or Folders tab.
l10n/Localizable.xcstrings +84 −1
@@ -17,6 +17,9 @@
1717 }
1818 }
1919 },
20 "%@ ": {
21 "shouldTranslate": false
22 },
2023 "%@ %@": {
2124 "localizations": {
2225 "en": {
@@ -159,6 +162,16 @@
159162 }
160163 }
161164 },
165 "%lld sent to orgstar on iPhone.": {
166 "localizations": {
167 "de": {
168 "stringUnit": {
169 "state": "translated",
170 "value": "%lld an orgstar auf dem iPhone gesendet."
171 }
172 }
173 }
174 },
162175 "%lld/%lld today": {
163176 "localizations": {
164177 "de": {
@@ -1038,6 +1051,16 @@
10381051 }
10391052 }
10401053 },
1054 "Clock In to %@": {
1055 "localizations": {
1056 "de": {
1057 "stringUnit": {
1058 "state": "translated",
1059 "value": "Zeit für %@ erfassen"
1060 }
1061 }
1062 }
1063 },
10411064 "Clock In to Recent Entry…": {
10421065 "localizations": {
10431066 "de": {
@@ -2735,6 +2758,16 @@
27352758 }
27362759 }
27372760 },
2761 "Marks it %@": {
2762 "localizations": {
2763 "de": {
2764 "stringUnit": {
2765 "state": "translated",
2766 "value": "Setzt es auf %@"
2767 }
2768 }
2769 }
2770 },
27382771 "Match: +work/!TODO": {
27392772 "localizations": {
27402773 "de": {
@@ -3191,6 +3224,16 @@
31913224 }
31923225 }
31933226 },
3227 "Not clocked in": {
3228 "localizations": {
3229 "de": {
3230 "stringUnit": {
3231 "state": "translated",
3232 "value": "Keine Zeiterfassung"
3233 }
3234 }
3235 }
3236 },
31943237 "Not done before TODO children": {
31953238 "localizations": {
31963239 "de": {
@@ -3361,6 +3404,16 @@
33613404 }
33623405 }
33633406 },
3407 "Open orgstar on your iPhone to show your agenda here.": {
3408 "localizations": {
3409 "de": {
3410 "stringUnit": {
3411 "state": "translated",
3412 "value": "Öffne orgstar auf deinem iPhone, um hier deine Agenda zu sehen."
3413 }
3414 }
3415 }
3416 },
33643417 "Open orgstar to show your agenda here.": {
33653418 "localizations": {
33663419 "de": {
@@ -4107,6 +4160,16 @@
41074160 }
41084161 }
41094162 },
4163 "Sent to orgstar on iPhone.": {
4164 "localizations": {
4165 "de": {
4166 "stringUnit": {
4167 "state": "translated",
4168 "value": "An orgstar auf dem iPhone gesendet."
4169 }
4170 }
4171 }
4172 },
41104173 "Series": {
41114174 "localizations": {
41124175 "de": {
@@ -4820,6 +4883,16 @@
48204883 }
48214884 }
48224885 },
4886 "The running clock and its time so far.": {
4887 "localizations": {
4888 "de": {
4889 "stringUnit": {
4890 "state": "translated",
4891 "value": "Die laufende Zeiterfassung und die bisherige Zeit."
4892 }
4893 }
4894 }
4895 },
48234896 "The template to capture with.": {
48244897 "localizations": {
48254898 "de": {
@@ -5249,6 +5322,16 @@
52495322 }
52505323 }
52515324 },
5325 "orgstar files it with a template when you next open it on iPhone.": {
5326 "localizations": {
5327 "de": {
5328 "stringUnit": {
5329 "state": "translated",
5330 "value": "orgstar legt es beim nächsten Öffnen auf dem iPhone mit einer Vorlage ab."
5331 }
5332 }
5333 }
5334 },
52525335 "orgstar files it with the template when you next open it.": {
52535336 "localizations": {
52545337 "de": {
@@ -5313,5 +5396,5 @@
53135396 "shouldTranslate": false
53145397 }
53155398 },
5316 "version": "1.0"
5399 "version": "1.1"
53175400}
scripts/build-ios-app.sh +6 −1
@@ -5,7 +5,7 @@
55set -eu
66
77cd "$(dirname "$0")/.."
8version="${1:-0.1.0}"
8version="${1:-0.3.0}"
99app=".build/ios-app/orgstar.app"
1010products=".build/ios/Build/Products/Debug-iphonesimulator"
1111
@@ -177,6 +177,11 @@ appex OrgstarShare share com.apple.share-services ShareViewController \
177177 "<key>NSExtensionActivationRule</key><dict><key>NSExtensionActivationSupportsWebURLWithMaxCount</key><integer>1</integer><key>NSExtensionActivationSupportsText</key><true/><key>NSExtensionActivationSupportsImageWithMaxCount</key><integer>10</integer><key>NSExtensionActivationSupportsMovieWithMaxCount</key><integer>10</integer><key>NSExtensionActivationSupportsFileWithMaxCount</key><integer>10</integer></dict>" \
178178 "$entitlements"
179179
180# The watch app, which a paired watch installs from here.
181scripts/build-watch-app.sh "$version" > /dev/null
182mkdir -p "$app/Watch"
183cp -R .build/watch-app/OrgstarWatch.app "$app/Watch/"
184
180185codesign --force --sign - --entitlements "$entitlements" "$app"
181186rm -rf "$work"
182187echo "$app"
scripts/build-watch-app.sh added +98
@@ -0,0 +1,98 @@
1#!/bin/sh
2# Builds OrgstarWatch.app, with its complications, for the watchOS Simulator in
3# .build/watch-app from the OrgstarWatch and OrgstarWatchWidgets products, signed ad hoc.
4# scripts/build-ios-app.sh embeds it in the iOS app; install it on a paired watch simulator
5# with `xcrun simctl install <watch> .build/watch-app/OrgstarWatch.app`.
6# Usage: scripts/build-watch-app.sh [version]
7set -eu
8
9cd "$(dirname "$0")/.."
10version="${1:-0.3.0}"
11app=".build/watch-app/OrgstarWatch.app"
12products=".build/watch/Build/Products/Debug-watchsimulator"
13# The app group the complications read the agenda from, on the watch.
14entitlements=scripts/OrgstarMobile.entitlements
15
16for scheme in OrgstarWatch OrgstarWatchWidgets; do
17 xcodebuild -scheme "$scheme" -destination 'generic/platform=watchOS Simulator' -derivedDataPath .build/watch build -quiet \
18 CODE_SIGN_ENTITLEMENTS="$PWD/$entitlements"
19done
20
21rm -rf "$app"
22mkdir -p "$app/PlugIns/OrgstarWatchWidgets.appex"
23cp "$products/OrgstarWatch" "$app/OrgstarWatch"
24scripts/localize.sh "$app"
25cat > "$app/Info.plist" <<PLIST
26<?xml version="1.0" encoding="UTF-8"?>
27<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28<plist version="1.0">
29<dict>
30 <key>CFBundleIdentifier</key>
31 <string>sh.krz.orgstar.watchkitapp</string>
32 <key>CFBundleDevelopmentRegion</key>
33 <string>en</string>
34 <key>CFBundleLocalizations</key>
35 <array><string>en</string><string>de</string></array>
36 <key>CFBundleName</key>
37 <string>orgstar</string>
38 <key>CFBundleDisplayName</key>
39 <string>orgstar</string>
40 <key>CFBundleExecutable</key>
41 <string>OrgstarWatch</string>
42 <key>CFBundlePackageType</key>
43 <string>APPL</string>
44 <key>CFBundleShortVersionString</key>
45 <string>${version}</string>
46 <key>CFBundleVersion</key>
47 <string>${version}</string>
48 <key>CFBundleSupportedPlatforms</key>
49 <array><string>WatchSimulator</string></array>
50 <key>MinimumOSVersion</key>
51 <string>26.0</string>
52 <key>UIDeviceFamily</key>
53 <array><integer>4</integer></array>
54 <key>WKApplication</key>
55 <true/>
56 <key>WKCompanionAppBundleIdentifier</key>
57 <string>sh.krz.orgstar</string>
58</dict>
59</plist>
60PLIST
61
62dir="$app/PlugIns/OrgstarWatchWidgets.appex"
63cp "$products/OrgstarWatchWidgets" "$dir/OrgstarWatchWidgets"
64scripts/localize.sh "$dir"
65cat > "$dir/Info.plist" <<PLIST
66<?xml version="1.0" encoding="UTF-8"?>
67<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
68<plist version="1.0">
69<dict>
70 <key>CFBundleIdentifier</key>
71 <string>sh.krz.orgstar.watchkitapp.widgets</string>
72 <key>CFBundleName</key>
73 <string>OrgstarWatchWidgets</string>
74 <key>CFBundleDisplayName</key>
75 <string>orgstar</string>
76 <key>CFBundleExecutable</key>
77 <string>OrgstarWatchWidgets</string>
78 <key>CFBundlePackageType</key>
79 <string>XPC!</string>
80 <key>CFBundleShortVersionString</key>
81 <string>${version}</string>
82 <key>CFBundleVersion</key>
83 <string>${version}</string>
84 <key>CFBundleSupportedPlatforms</key>
85 <array><string>WatchSimulator</string></array>
86 <key>MinimumOSVersion</key>
87 <string>26.0</string>
88 <key>NSExtension</key>
89 <dict>
90 <key>NSExtensionPointIdentifier</key>
91 <string>com.apple.widgetkit-extension</string>
92 </dict>
93</dict>
94</plist>
95PLIST
96codesign --force --sign - --entitlements "$entitlements" "$dir"
97codesign --force --sign - --entitlements "$entitlements" "$app"
98echo "$app"
scripts/sync-strings.sh +4 −1
@@ -15,10 +15,13 @@ done
1515for scheme in OrgstarMobile OrgstarShare OrgstarWidgets; do
1616 xcodebuild -scheme "$scheme" -destination 'generic/platform=iOS Simulator' -derivedDataPath "$ios" build -quiet SWIFT_EMIT_LOC_STRINGS=YES
1717done
18for scheme in OrgstarWatch OrgstarWatchWidgets; do
19 xcodebuild -scheme "$scheme" -destination 'generic/platform=watchOS Simulator' -derivedDataPath "$ios" build -quiet SWIFT_EMIT_LOC_STRINGS=YES
20done
1821
1922[ -f "$catalog" ] || printf '{\n "sourceLanguage" : "en",\n "strings" : {\n\n },\n "version" : "1.0"\n}\n' > "$catalog"
2023find "$mac" "$ios" -path '*/arm64/*' -name '*.stringsdata' \
21 | grep -E '/(Orgstar|OrgstarMobile|OrgstarWidgets|OrgstarShare)-p\.build/|/(OrgApp|OrgPresentation|OrgEditorAppKit)-t?\.build/' \
24 | grep -E '/(Orgstar|OrgstarMobile|OrgstarWidgets|OrgstarShare|OrgstarWatch|OrgstarWatchWidgets)-p\.build/|/(OrgApp|OrgPresentation|OrgEditorAppKit)-t?\.build/' \
2225 > "$mac/stringsdata.txt"
2326# shellcheck disable=SC2046
2427xcrun xcstringstool sync "$catalog" --stringsdata $(tr '\n' ' ' < "$mac/stringsdata.txt")