Commit e0794b27d2

e0794b27d2449358f323e3af8ad1f3e09f1b39df

parent: 0e0e407283

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-11 16:40 UTC

macOS widgets

Today, Up Next (small) and Habits widgets on the Mac desktop and in Notification Center: OrgstarWidgets is a SwiftPM executable target bundled by build-app.sh as a sandboxed widgetkit-extension; iOS-only widgets, controls and the Live Activity are guarded. The Mac app writes the agenda and habit snapshots to ~/Library/Application Support/Orgstar/Widgets (read by a sandbox exception, as a group container needs a provisioning profile on the Mac) and opens orgstar:// links.

Closes #63

Layout: unified · split

Package.swift +5 −1
@@ -21,7 +21,8 @@ let package = Package(
2121 .executable(name: "OrgstarMobile", targets: ["OrgstarMobile"]),
2222 .executable(name: "OrgstarQuickLook", targets: ["OrgstarQuickLook"]),
2323 .executable(name: "OrgstarSpotlight", targets: ["OrgstarSpotlight"]),
24 .executable(name: "OrgstarShare", targets: ["OrgstarShare"])
24 .executable(name: "OrgstarShare", targets: ["OrgstarShare"]),
25 .executable(name: "OrgstarWidgets", targets: ["OrgstarWidgets"])
2526 ],
2627 dependencies: [
2728 .package(url: "https://github.com/groue/GRDB.swift", from: "7.11.1"),
@@ -92,6 +93,9 @@ let package = Package(
9293 .executableTarget(name: "OrgstarSpotlight", dependencies: ["OrgCore"], linkerSettings: extensionEntry),
9394 // The iOS share extension, bundled into the iOS app by scripts/build-ios-app.sh.
9495 .executableTarget(name: "OrgstarShare", dependencies: ["OrgApp"], linkerSettings: extensionEntry),
96 // The Mac's widget extension, bundled into the app by scripts/build-app.sh; the iOS one
97 // is built from the same sources by ios/Orgstar.xcodeproj.
98 .executableTarget(name: "OrgstarWidgets", dependencies: ["OrgApp"]),
9599 .testTarget(name: "OrgCoreTests", dependencies: ["OrgCore"], exclude: ["Conformance"]),
96100 .testTarget(name: "OrgDocumentTests", dependencies: ["OrgDocument"]),
97101 .testTarget(name: "OrgIndexTests", dependencies: ["OrgIndex"]),
Sources/OrgApp/AgendaSnapshot.swift +15 −1
@@ -198,12 +198,26 @@ public struct AgendaSnapshot: Codable, Equatable, Sendable {
198198
199199 // MARK: - The file
200200
201 /// `Widgets/agenda.json` in the app group's container; nil without the group.
201 /// `Widgets/agenda.json` in the app group's container; nil without the group. On the Mac,
202 /// in `~/Library/Application Support/Orgstar/Widgets`, which the sandboxed widget extension
203 /// reads by a sandbox exception, as an app group there needs a provisioning profile.
202204 public static func file(group: String = CaptureInbox.group) -> URL? {
205 #if os(macOS)
206 return macWidgetsFolder.appendingPathComponent("agenda.json")
207 #else
203208 FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: group)?
204209 .appendingPathComponent("Widgets").appendingPathComponent("agenda.json")
210 #endif
205211 }
206212
213 #if os(macOS)
214 /// From the account's home folder, not a sandbox container's.
215 static var macWidgetsFolder: URL {
216 let home = getpwuid(getuid())?.pointee.pw_dir.map { String(cString: $0) } ?? NSHomeDirectory()
217 return URL(fileURLWithPath: home).appendingPathComponent("Library/Application Support/Orgstar/Widgets")
218 }
219 #endif
220
207221 public static func read(from file: URL) -> AgendaSnapshot? {
208222 guard let data = try? Data(contentsOf: file) else { return nil }
209223 return try? decoder.decode(AgendaSnapshot.self, from: data)
Sources/Orgstar/ContentView.swift +29
@@ -7,6 +7,7 @@ import OrgWorkspace
77import OrgIndex
88import SwiftUI
99import UniformTypeIdentifiers
10import WidgetKit
1011
1112struct ContentView: View {
1213 let workspace: WorkspaceModel
@@ -19,6 +20,7 @@ struct ContentView: View {
1920 @AppStorage("clockIdleTime") private var clockIdleTime = 0
2021 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
2122 @State private var reminderAgenda: AgendaModel?
23 @State private var widgetAgenda: AgendaModel?
2224 @State private var trust = TrustStore()
2325 @State private var hotKey: GlobalHotKey?
2426 @State private var statusItem: ClockStatusItem?
@@ -448,6 +450,7 @@ struct ContentView: View {
448450 changed: workspace.changedFile?.version, edits: session.editVersion, hour: hour
449451 )) {
450452 await updateReminders()
453 await updateWidgets()
451454 }
452455 .task {
453456 while !Task.isCancelled {
@@ -917,6 +920,32 @@ struct ContentView: View {
917920 await scheduler.reconcile(reminders)
918921 }
919922
923 /// The desktop widgets' agenda and habits, written where the widget extension reads them,
924 /// with the widgets reloaded when they changed.
925 private func updateWidgets() async {
926 guard !Task.isCancelled, !workspace.files.isEmpty, let file = AgendaSnapshot.file() else { return }
927 let days = widgetAgenda ?? AgendaModel(workspace: workspace)
928 widgetAgenda = days
929 days.mode = .agenda(span: AgendaSnapshot.dayCount, startOffset: 0)
930 days.startOnWeekday = nil
931 days.includeSubfolders = agendaSubfolders
932 days.agendaFiles = OrgPreferences.agendaFiles()
933 days.options = OrgPreferences.agendaOptions(days.options)
934 days.options.logMode = false
935 days.calendarEvents = OrgPreferences.calendarEvents() && CalendarEvents.isAuthorized ? CalendarAccess.events : nil
936 days.calendarNames = OrgPreferences.calendarEventCalendars()
937 days.reminderLists = OrgPreferences.agendaReminders() && ReminderLists.isAuthorized ? CalendarAccess.reminders : nil
938 days.reminderListNames = OrgPreferences.agendaReminderLists()
939 let open = session.openTexts
940 await days.refresh(open: open)
941 guard !Task.isCancelled else { return }
942 if (try? HabitSnapshot(habits: await days.habits(open: open), theme: theme).write()) == true {
943 WidgetCenter.shared.reloadTimelines(ofKind: "sh.krz.orgstar.habits")
944 }
945 let snapshot = AgendaSnapshot(groups: days.groups(), today: days.today, theme: theme, generated: Date())
946 if (try? snapshot.write(to: file)) == true { WidgetCenter.shared.reloadAllTimelines() }
947 }
948
920949 private func loadKeymap() {
921950 let loaded = KeymapLoader.load(preset, commands: Set(EditorCommands.all.map(\.id)))
922951 keymap = loaded.keymap
Sources/Orgstar/OrgstarApp.swift +15 −3
@@ -120,8 +120,20 @@ final class AppCommands {
120120 captureRequest = (nil, [:], day, captureSerial)
121121 }
122122
123 /// `org-protocol://capture` and `store-link`.
123 /// `org-protocol://capture` and `store-link`, and the widgets' `orgstar://` links.
124124 func handle(protocolURL url: String) {
125 if let link = URL(string: url).flatMap(AppLink.init(url:)) {
126 switch link {
127 case .agenda: run("app.agenda")
128 case .clock: run("app.clock.goto")
129 case .entry(let path, let offset): jump(path: path, offset: offset)
130 case .capture(let template):
131 captureSerial += 1
132 captureRequest = (template, [:], nil, captureSerial)
133 run("app.capture")
134 }
135 return
136 }
125137 switch OrgProtocol.parse(url) {
126138 case .capture(let template, let properties):
127139 captureSerial += 1
@@ -197,7 +209,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
197209
198210 func application(_ application: NSApplication, open urls: [URL]) {
199211 let paths = urls.filter(\.isFileURL).map(\.path)
200 let links = urls.filter { $0.scheme == "org-protocol" }.map(\.absoluteString)
212 let links = urls.filter { $0.scheme == "org-protocol" || $0.scheme == AppLink.scheme }.map(\.absoluteString)
201213 guard let commands, let session else {
202214 Self.pendingOpens += paths
203215 Self.pendingLinks += links
@@ -208,7 +220,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
208220 for link in links { commands.handle(protocolURL: link) }
209221 }
210222
211 /// org-protocol links that arrive before the window is ready.
223 /// org-protocol and orgstar:// links that arrive before the window is ready.
212224 static var pendingLinks: [String] = []
213225
214226 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
Sources/OrgstarWidgets/ClockActivityWidget.swift +2
@@ -1,3 +1,4 @@
1#if os(iOS)
12import ActivityKit
23import AppIntents
34import OrgApp
@@ -82,3 +83,4 @@ struct ClockOutButton: View {
8283} contentStates: {
8384 ClockActivityAttributes.ContentState(heading: "Review the draft", startedAt: .now.addingTimeInterval(-3725))
8485}
86#endif
Sources/OrgstarWidgets/Controls.swift +2
@@ -1,3 +1,4 @@
1#if os(iOS)
12import AppIntents
23import OrgApp
34import SwiftUI
@@ -98,3 +99,4 @@ struct CaptureView: View {
9899 .accessibilityLabel("Capture" + (entry.template.map { " with \($0.name)" } ?? ""))
99100 }
100101}
102#endif
Sources/OrgstarWidgets/HabitsWidget.swift +4
@@ -60,7 +60,11 @@ struct HabitsView: View {
6060 }
6161 }
6262 .widgetURL(AppLink.agenda.url)
63 #if os(macOS)
64 .containerBackground(for: .widget) { Color(nsColor: .windowBackgroundColor) }
65 #else
6366 .containerBackground(for: .widget) { Color(uiColor: .systemBackground) }
67 #endif
6468 }
6569
6670 private func content(_ snapshot: HabitSnapshot) -> some View {
Sources/OrgstarWidgets/OrgstarWidgets.swift +6 −1
@@ -4,21 +4,26 @@ import SwiftUI
44import WidgetKit
55
66/// The agenda and habits on the Home Screen and the Lock Screen, capture and the clock in
7/// Control Center, and the running clock's Live Activity.
7/// Control Center, and the running clock's Live Activity; on the Mac, the agenda and habits on
8/// the desktop and in Notification Center.
89@main
910struct OrgstarWidgets: WidgetBundle {
1011 var body: some Widget {
1112 TodayWidget()
1213 HabitsWidget()
1314 UpNextWidget()
15 #if os(iOS)
1416 CaptureWidget()
1517 ClockActivityWidget()
1618 CaptureControl()
1719 ClockControl()
20 #endif
1821 }
1922}
2023
24#if os(iOS)
2125/// The App Intents OrgApp declares: the Live Activity's Clock Out button.
2226struct OrgstarWidgetIntents: AppIntentsPackage {
2327 static var includedPackages: [any AppIntentsPackage.Type] { [OrgAppIntents.self] }
2428}
29#endif
Sources/OrgstarWidgets/TodayWidget.swift +4
@@ -33,7 +33,11 @@ struct TodayView: View {
3333 }
3434 .widgetURL(AppLink.agenda.url)
3535 .containerBackground(for: .widget) {
36 #if os(macOS)
37 entry.snapshot?.color("agenda-background", scheme) ?? Color(nsColor: .windowBackgroundColor)
38 #else
3639 entry.snapshot?.color("agenda-background", scheme) ?? Color(uiColor: .systemBackground)
40 #endif
3741 }
3842 }
3943
Sources/OrgstarWidgets/UpNextWidget.swift +11 −1
@@ -3,7 +3,7 @@ import SwiftUI
33import WidgetKit
44
55/// The agenda on the Lock Screen: the next entry (rectangular), the next entry or the count
6/// (inline), today's open entries (circular).
6/// (inline), today's open entries (circular). On the Mac, the next entry in a small widget.
77struct UpNextWidget: Widget {
88 var body: some WidgetConfiguration {
99 StaticConfiguration(kind: "sh.krz.orgstar.up-next", provider: AgendaProvider()) { entry in
@@ -11,7 +11,11 @@ struct UpNextWidget: Widget {
1111 }
1212 .configurationDisplayName("Up Next")
1313 .description("The next agenda entry, or how many are open today.")
14 #if os(macOS)
15 .supportedFamilies([.systemSmall])
16 #else
1417 .supportedFamilies([.accessoryRectangular, .accessoryInline, .accessoryCircular])
18 #endif
1519 }
1620}
1721
@@ -25,7 +29,11 @@ struct UpNextView: View {
2529 var body: some View {
2630 content
2731 .widgetURL((next?.link ?? .agenda).url)
32 #if os(macOS)
33 .containerBackground(for: .widget) { Color(nsColor: .windowBackgroundColor) }
34 #else
2835 .containerBackground(for: .widget) { Color.clear }
36 #endif
2937 }
3038
3139 @ViewBuilder
@@ -64,6 +72,7 @@ struct UpNextView: View {
6472 }
6573}
6674
75#if os(iOS)
6776#Preview("Rectangular", as: .accessoryRectangular) {
6877 UpNextWidget()
6978} timeline: {
@@ -81,3 +90,4 @@ struct UpNextView: View {
8190} timeline: {
8291 AgendaEntry(date: .now, snapshot: .sample(.now))
8392}
93#endif
Tests/OrgAppTests/WidgetDataTests.swift +13
@@ -90,3 +90,16 @@ struct PropertyInheritanceTests {
9090 #expect(SemanticSettings.PropertyInheritance("style Team") == .only(["STYLE", "TEAM"]))
9191 }
9292}
93
94#if os(macOS)
95struct MacWidgetFolderTests {
96 /// The account's home, not a sandbox container's, so that the widget extension's sandbox
97 /// exception names the same folder.
98 @Test func widgetDataIsInApplicationSupport() throws {
99 let agenda = try #require(AgendaSnapshot.file())
100 #expect(agenda.path.hasSuffix("/Library/Application Support/Orgstar/Widgets/agenda.json"))
101 #expect(!agenda.path.contains("/Containers/"))
102 #expect(HabitSnapshot.file()?.deletingLastPathComponent() == agenda.deletingLastPathComponent())
103 }
104}
105#endif
docs/manual/guide/07-agenda.org +13 −1
@@ -224,7 +224,7 @@ On the Mac, double-click an event, or select it and press =RET=, to open it in C
224224
225225Both use the access granted for showing events. Read-only calendars, such as subscriptions and holidays, can't be chosen.
226226
227* Reminders
227* Reminders from the Reminders app
228228
229229The agenda can also show reminders from the Reminders app (EventKit), read-only. It is off by default. To turn it on:
230230
@@ -689,6 +689,18 @@ Choose Board from the Views menu in the Agenda tab. The board opens over the age
689689
690690The board is not available on iOS.
691691
692* Desktop widgets
693
694On the Mac, orgstar's widgets go on the desktop and in Notification Center: right-click the desktop, choose Edit Widgets…, and pick orgstar in the gallery. They appear there once orgstar has run.
695
696| Widget | Sizes | Shows |
697|--------+-------------------------+-----------------------------------------------------------------------------------------|
698| Today | Small, medium and large | The date, the open count, and what's left of today, as on iOS. |
699| Up Next | Small | The next entry's time or status and title, or the agenda when nothing is left today. |
700| Habits | Small, medium and large | Each habit's consistency graph, as on iOS. |
701
702Click a row in Today, the Up Next widget or a habit to show that entry in orgstar; click elsewhere to open the agenda. The widgets read the next seven days of the agenda and the habits, which the app writes to =~/Library/Application Support/Orgstar/Widgets= when files, edits or settings change and every hour while it runs; see [[file:14-ios.org][iOS]] for what they show and leave out.
703
692704* The agenda on iOS
693705
694706The Agenda tab shows the same views from the same files, using the settings in the synced =config.toml= and the views in =views.toml= (see [[file:14-ios.org][iOS]]). Differences from the Mac:
scripts/build-app.sh +12 −5
@@ -27,6 +27,8 @@ swift build -c release $arch_flags --product OrgstarQuickLook
2727# shellcheck disable=SC2086
2828swift build -c release $arch_flags --product OrgstarSpotlight
2929# shellcheck disable=SC2086
30swift build -c release $arch_flags --product OrgstarWidgets
31# shellcheck disable=SC2086
3032binary="$(swift build -c release $arch_flags --show-bin-path)/Orgstar"
3133
3234rm -rf "$app"
@@ -119,7 +121,7 @@ cat > "$app/Contents/Info.plist" <<EOF
119121 <key>CFBundleURLName</key>
120122 <string>org-protocol</string>
121123 <key>CFBundleURLSchemes</key>
122 <array><string>org-protocol</string></array>
124 <array><string>org-protocol</string><string>orgstar</string></array>
123125 </dict>
124126 </array>
125127 <key>CFBundleShortVersionString</key>
@@ -156,8 +158,9 @@ echo "$PWD/$objects/Orgstar-primary.swiftconstvalues" > "$work/constvalues.txt"
156158 --swift-const-vals-list "$work/constvalues.txt" --output "$app/Contents/Resources" --force > /dev/null 2>&1
157159rm -rf "$work"
158160
159# App extensions: Quick Look previews and the Spotlight importer. They run sandboxed.
160appex() { # name, extension point, principal class, attributes
161# App extensions: Quick Look previews, the Spotlight importer and the widgets. They run
162# sandboxed.
163appex() { # name, extension point, principal class (or ""), attributes, extra entitlements
161164 dir="$app/Contents/PlugIns/$1.appex/Contents"
162165 mkdir -p "$dir/MacOS"
163166 cp "$(dirname "$binary")/$1" "$dir/MacOS/$1"
@@ -184,8 +187,7 @@ appex() { # name, extension point, principal class, attributes
184187 <dict>
185188 <key>NSExtensionPointIdentifier</key>
186189 <string>$2</string>
187 <key>NSExtensionPrincipalClass</key>
188 <string>$3</string>
190$([ -n "$3" ] && printf ' <key>NSExtensionPrincipalClass</key>\n <string>%s</string>\n' "$3")
189191 <key>NSExtensionAttributes</key>
190192 <dict>$4</dict>
191193 </dict>
@@ -199,6 +201,7 @@ PLIST
199201<dict>
200202 <key>com.apple.security.app-sandbox</key>
201203 <true/>
204${5:-}
202205</dict>
203206</plist>
204207PLIST
@@ -210,6 +213,10 @@ appex OrgstarQuickLook com.apple.quicklook.preview PreviewProvider \
210213 "<key>QLSupportedContentTypes</key><array><string>org.orgmode.org</string></array><key>QLIsDataBasedPreview</key><true/>"
211214appex OrgstarSpotlight com.apple.spotlight.import ImportExtension \
212215 "<key>CSSupportedContentTypes</key><array><string>org.orgmode.org</string></array>"
216# The widgets read what the app writes in ~/Library/Application Support/Orgstar/Widgets.
217appex OrgstarWidgets com.apple.widgetkit-extension "" "" \
218 " <key>com.apple.security.temporary-exception.files.home-relative-path.read-only</key>
219 <array><string>/Library/Application Support/Orgstar/Widgets/</string></array>"
213220
214221# Sparkle's inner pieces are signed first, as its documentation has it, then the framework.
215222fw="$app/Contents/Frameworks/Sparkle.framework/Versions/B"