Sources/Orgstar/OrgstarApp.swift
1143 lines · 54943 bytes
1import AppKit
2import OrgApp
3import OrgCore
4import OrgEditorAppKit
5import OrgMathJax
6import OrgPresentation
7#if !APPSTORE
8import OrgPrograms
9#endif
10import SwiftUI
11import UserNotifications
12
13/// Window-level requests the menu bar makes.
14@MainActor
15@Observable
16final class AppCommands {
17 var showingQuickOpen = false
18 var showingFolderPicker = false
19 /// The first-launch sheet, while no folder has been added.
20 var showingWelcome = false
21 /// The notes the main window shows as a sheet.
22 var whatsNew: ReleaseNotes?
23 var focusSearch = false
24 var showingConflict = false
25 var showingPalette = false
26 /// A location another window asked the main window to show.
27 private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
28 private var jumpID = 0
29 /// Days the agenda window should show, from a followed timestamp.
30 var agendaRequest: (start: Int, days: Int)?
31 /// The editor with focus, for menus and the palette.
32 var editor: OrgEditor?
33 /// The editors and text views of every pane in every window.
34 let store = EditorStore()
35 /// The main window is on screen. App commands run there, so an editor window reopens it
36 /// before asking for one.
37 var mainWindowOpen = false
38 /// What every editor is set up with, from the settings; the main window keeps it current.
39 var editorSettings = EditorSettings()
40 /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
41 var externalHandler: ((ExternalRequest) -> Void)?
42 /// Files and images pasted or dropped on an editor; the main window sets them.
43 var filesHandler: (([URL]) -> Void)?
44 var imageHandler: ((Data, String) -> Void)?
45 #if APPSTORE
46 /// Asks for the folders outside the sidebar's folders that paths need; the main window sets it.
47 var reach: ([String]) -> Bool = { _ in true }
48 #endif
49 /// Tags used across the workspace, for tag completion; the main window sets it.
50 var knownTags: () -> [String] = { [] }
51 /// The pending key prefix, and what can follow it.
52 var pendingKeys: String?
53 /// The editor's evil state in the Doom preset.
54 var editorState: String?
55 /// The keymap in use, for showing keys in menus and the palette.
56 var keymap = KeymapPreset.emacs.keymap
57 var modal = false
58 /// `org-stored-links`, most recent first; kept for the session, as in Emacs.
59 var storedLinks: [StoredLink] = []
60
61 /// Puts `link` first in `storedLinks` and says what happened.
62 func storeLink(_ link: StoredLink) {
63 show(StoredLink.add(link, to: &storedLinks))
64 }
65
66 /// The keys that run `command`, as menus and the palette show them.
67 func keyLabel(for command: String) -> String? {
68 let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
69 return labels.isEmpty ? nil : labels.joined(separator: ", ")
70 }
71
72 /// The editor's selection, for the modeline.
73 var selection = NSRange(location: 0, length: 0)
74 var keyHints: [KeyHint] = []
75 /// A question a command asked, answered in the echo area.
76 private(set) var prompt: PromptRequest?
77 /// The last message from a command or the keymap, cleared after a few seconds.
78 private(set) var message: String?
79 private var messageID = 0
80
81 func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
82 self.prompt = PromptRequest(prompt: prompt, reply: reply)
83 }
84
85 /// Clock questions in the echo area.
86 var askClock: ClockModel.Ask {
87 { [self] prompt in
88 await withCheckedContinuation { continuation in
89 ask(prompt) { continuation.resume(returning: $0) }
90 }
91 }
92 }
93
94 /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
95 func answer(_ text: String?) {
96 guard let request = prompt else { return }
97 prompt = nil
98 if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
99 request.reply(text)
100 }
101
102 /// An export or table recalculation running in Emacs, for Cancel Running Task.
103 private(set) var emacsTask: Task<Void, Never>?
104 private var emacsSerial = 0
105
106 /// Runs `work` as the Emacs task, cancelling the one before.
107 func runInEmacs(_ work: @escaping @MainActor () async -> Void) {
108 emacsTask?.cancel()
109 emacsSerial += 1
110 let serial = emacsSerial
111 emacsTask = Task {
112 await work()
113 if emacsSerial == serial { emacsTask = nil }
114 }
115 }
116
117 /// An app command from a menu, run by the main window.
118 private(set) var runRequest: (id: String, serial: Int)?
119 private var runSerial = 0
120
121 func run(_ id: String) {
122 runSerial += 1
123 runRequest = (id, runSerial)
124 }
125
126 /// A capture waiting for the capture window: the template key and the link properties for
127 /// its escapes (org-protocol), or the agenda day to schedule the entry on.
128 var captureRequest: (template: String?, properties: [String: String], day: Int?, serial: Int)?
129 private var captureSerial = 0
130
131 /// Capture from an agenda day, as `org-agenda-capture`: that day is the capture's date, and
132 /// the entry is scheduled on it. The caller opens the capture window.
133 func capture(on day: Int) {
134 captureSerial += 1
135 captureRequest = (nil, [:], day, captureSerial)
136 }
137
138 /// `org-protocol://capture` and `store-link`, and the widgets' `orgstar://` links.
139 func handle(protocolURL url: String) {
140 if let link = URL(string: url).flatMap(AppLink.init(url:)) {
141 switch link {
142 case .agenda: run("app.agenda")
143 case .clock: run("app.clock.goto")
144 case .entry(let path, let offset): jump(path: path, offset: offset)
145 case .capture(let template):
146 captureSerial += 1
147 captureRequest = (template, [:], nil, captureSerial)
148 run("app.capture")
149 }
150 return
151 }
152 switch OrgProtocol.parse(url) {
153 case .capture(let template, let properties):
154 captureSerial += 1
155 captureRequest = (template, properties, nil, captureSerial)
156 run("app.capture")
157 case .storeLink(let link, let title):
158 storeLink(StoredLink(link: link, description: title))
159 NSPasteboard.general.clearContents()
160 NSPasteboard.general.setString(link, forType: .string)
161 case nil:
162 show("orgstar handles org-protocol capture and store-link")
163 }
164 }
165
166 func jump(path: String, offset: Int) {
167 jumpID += 1
168 jumpRequest = (path, offset, jumpID)
169 }
170
171 func show(_ text: String) {
172 messageID += 1
173 let id = messageID
174 message = text
175 AccessibilityNotification.Announcement(text).post()
176 Task {
177 try? await Task.sleep(for: .seconds(4))
178 if messageID == id { message = nil }
179 }
180 }
181}
182
183struct PromptRequest: Identifiable {
184 let id = UUID()
185 let prompt: Prompt
186 let reply: (String?) -> Void
187}
188
189@MainActor
190final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
191 var session: DocumentSession?
192 var commands: AppCommands?
193 #if APPSTORE
194 var workspace: WorkspaceModel?
195 #else
196 let updates = Updates()
197 #endif
198
199 func applicationDidFinishLaunching(_ notification: Notification) {
200 DockIcon.start()
201 if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
202 #if !APPSTORE
203 updates.start()
204 #endif
205 }
206
207 #if APPSTORE
208 /// A subscription may have lapsed or renewed while the app was in the background.
209 func applicationDidBecomeActive(_ notification: Notification) {
210 Task { await ProStore.shared.refresh() }
211 }
212 #endif
213
214 /// `:session` interpreters end with the app.
215 func applicationWillTerminate(_ notification: Notification) {
216 #if !APPSTORE
217 BabelSessions.shared.stopAll()
218 #endif
219 }
220
221 /// Reminders show while Orgstar is in front too.
222 nonisolated func userNotificationCenter(
223 _ center: UNUserNotificationCenter, willPresent notification: UNNotification
224 ) async -> UNNotificationPresentationOptions {
225 [.banner, .sound, .list]
226 }
227
228 /// Clicking a reminder shows its entry.
229 nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
230 let info = response.notification.request.content.userInfo
231 guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
232 await MainActor.run {
233 NSApp.activate()
234 commands?.jump(path: path, offset: offset)
235 }
236 }
237
238 /// Files opened from Finder, `open`, or a drop on the Dock icon: each opens as a buffer.
239 /// Ones that arrive before the window is ready wait for it (`pendingOpens`).
240 static var pendingOpens: [String] = []
241
242 func application(_ application: NSApplication, open urls: [URL]) {
243 let paths = urls.filter(\.isFileURL).map(\.path)
244 let links = urls.filter { $0.scheme == "org-protocol" || $0.scheme == AppLink.scheme }.map(\.absoluteString)
245 guard let commands, let session else {
246 Self.pendingOpens += paths
247 Self.pendingLinks += links
248 return
249 }
250 NSApp.activate()
251 for path in paths { session.open(path) }
252 for link in links { commands.handle(protocolURL: link) }
253 }
254
255 /// org-protocol and orgstar:// links that arrive before the window is ready.
256 static var pendingLinks: [String] = []
257
258 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
259
260 func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
261 guard let session else { return .terminateNow }
262 #if APPSTORE
263 BufferRestore.save(session, workspace: workspace)
264 #else
265 BufferRestore.save(session)
266 #endif
267 return UnsavedChanges.resolve(session, paths: session.openPaths) ? .terminateNow : .terminateCancel
268 }
269}
270
271/// Unsaved edits when leaving a file or quitting.
272@MainActor
273enum UnsavedChanges {
274 /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
275 /// explicit mode. A save that fails or conflicts keeps the file open.
276 static func resolve(_ session: DocumentSession) -> Bool {
277 guard session.isDirty else { return true }
278 if session.saveMode == .automatic { return session.save() }
279 let alert = NSAlert()
280 alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
281 alert.informativeText = "Your changes will be lost if you don't save them."
282 alert.addButton(withTitle: "Save")
283 alert.addButton(withTitle: "Don't Save")
284 alert.addButton(withTitle: "Cancel")
285 switch alert.runModal() {
286 case .alertFirstButtonReturn: return session.save()
287 case .alertSecondButtonReturn: return true
288 default: return false
289 }
290 }
291
292 /// Whether the buffers of `paths` can be closed: saved in automatic mode, or as the user
293 /// chooses for all of them in explicit mode.
294 static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
295 let dirty = paths.filter(session.dirtyPaths.contains)
296 guard !dirty.isEmpty else { return true }
297 if session.saveMode == .automatic { return dirty.map(session.save).allSatisfy { $0 } }
298 if dirty == [session.path] { return resolve(session) }
299 let alert = NSAlert()
300 alert.messageText = "Save changes to \(dirty.count) files?"
301 alert.informativeText = dirty.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
302 alert.addButton(withTitle: "Save All")
303 alert.addButton(withTitle: "Don't Save")
304 alert.addButton(withTitle: "Cancel")
305 switch alert.runModal() {
306 case .alertFirstButtonReturn: return dirty.map(session.save).allSatisfy { $0 }
307 case .alertSecondButtonReturn: return true
308 default: return false
309 }
310 }
311}
312
313/// The open buffers, their order and carets, kept for the next launch.
314@MainActor
315enum BufferRestore {
316 private static let key = "openBuffers"
317
318 struct State: Codable {
319 var paths: [String]
320 var current: String?
321 var carets: [String: Int]
322 /// In the Mac App Store build, bookmarks of the files outside every folder, which the
323 /// sandbox would otherwise keep orgstar out of after relaunch.
324 var bookmarks: [String: Data]?
325 }
326
327 /// `bookmarking` says which paths get a bookmark. A path still open keeps the bookmark it
328 /// has when no new one is made.
329 static func save(_ session: DocumentSession, bookmarking: (String) -> Bool = { _ in false }, defaults: UserDefaults = .standard) {
330 var carets: [String: Int] = [:]
331 for path in session.openPaths { carets[path] = session.caret(of: path) }
332 let previous = defaults.data(forKey: key).flatMap { try? JSONDecoder().decode(State.self, from: $0) }?.bookmarks ?? [:]
333 var bookmarks: [String: Data] = [:]
334 for path in session.openPaths {
335 bookmarks[path] = (bookmarking(path) ? SecurityBookmark.make(URL(fileURLWithPath: path)) : nil) ?? previous[path]
336 }
337 let state = State(paths: session.openPaths, current: session.path, carets: carets, bookmarks: bookmarks.isEmpty ? nil : bookmarks)
338 if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
339 }
340
341 #if APPSTORE
342 /// Saves with bookmarks for the files outside `workspace`'s folders and grants.
343 static func save(_ session: DocumentSession, workspace: WorkspaceModel?) {
344 save(session, bookmarking: { workspace?.contains(URL(fileURLWithPath: $0)) != true })
345 }
346 #endif
347
348 /// Opens the buffers that were open, in order, and returns the carets to show them at.
349 static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
350 guard let data = defaults.data(forKey: key), var state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
351 // A bookmarked file comes back with access, at the path it has now.
352 for (path, bookmark) in state.bookmarks ?? [:] {
353 guard let moved = SecurityBookmark.resolve(bookmark)?.url.path, moved != path else { continue }
354 state.paths = state.paths.map { $0 == path ? moved : $0 }
355 if state.current == path { state.current = moved }
356 state.carets[moved] = state.carets.removeValue(forKey: path)
357 }
358 let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
359 for path in existing { session.open(path) }
360 if let current = state.current, existing.contains(current) { session.open(current) }
361 return state.carets
362 }
363}
364
365@main
366struct OrgstarApp: App {
367 @NSApplicationDelegateAdaptor private var delegate: AppDelegate
368 @State private var workspace = Result {
369 try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
370 }
371 @State private var commands = AppCommands()
372 @State private var clock = ClockModel()
373 @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
374 @State private var session: DocumentSession = {
375 let session = DocumentSession()
376 session.defaults = Preferences.orgSettings
377 return session
378 }()
379
380 init() {
381 PDFExport.mathJaxURL = OrgMathJax.script
382 DiagramBlocks.vizURL = OrgMathJax.viz
383 DiagramBlocks.mermaidURL = OrgMathJax.mermaid
384 #if APPSTORE
385 AgendaSnapshot.useGroupContainer = true
386 EmacsFallback.offered = false
387 _ = FolderGrants.shared
388 ProStore.shared.start()
389 #else
390 DocumentSession.programs = Programs()
391 MacPro.resolve()
392 MacPro.renewInBackground()
393 #endif
394 // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
395 TableBlocks.allowed = { ProAccess.isUnlockedNow }
396 // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
397 #if DEBUG
398 Perf.watchMainThread()
399 #else
400 if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
401 #endif
402 }
403
404 var body: some Scene {
405 Window("orgstar", id: "main") {
406 switch workspace {
407 case .success(let model):
408 ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
409 .environment(\.orgTheme, ConfigSync.shared.theme)
410 .tint(ConfigSync.shared.theme.color("accent"))
411 .onAppear {
412 delegate.session = session
413 delegate.commands = commands
414 #if APPSTORE
415 delegate.workspace = model
416 #endif
417 CaptureIntent.environment = (model, session, clock, commands)
418 }
419 case .failure(let error):
420 ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
421 }
422 }
423 .defaultSize(width: 1280, height: 860)
424 WindowGroup("Editor", id: "editor") {
425 if case .success = workspace {
426 EditorWindowView(session: session, commands: commands, clock: clock)
427 .environment(\.orgTheme, ConfigSync.shared.theme)
428 .tint(ConfigSync.shared.theme.color("accent"))
429 }
430 }
431 .defaultSize(width: 900, height: 700)
432 .commandsRemoved()
433 Window("Agenda", id: "agenda") {
434 if case .success(let model) = workspace {
435 AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
436 .environment(\.orgTheme, ConfigSync.shared.theme)
437 .tint(ConfigSync.shared.theme.color("accent"))
438 }
439 }
440 .defaultSize(width: 760, height: 720)
441 Window("Board", id: "board") {
442 if case .success(let model) = workspace {
443 BoardView(workspace: model, session: session, commands: commands)
444 .environment(\.orgTheme, ConfigSync.shared.theme)
445 .tint(ConfigSync.shared.theme.color("accent"))
446 }
447 }
448 .defaultSize(width: 1100, height: 700)
449 Window("Graph", id: "graph") {
450 if case .success(let model) = workspace {
451 RoamGraphWindow(workspace: model, session: session, commands: commands)
452 .tint(ConfigSync.shared.theme.color("accent"))
453 }
454 }
455 .defaultSize(width: 900, height: 700)
456 Window("Clock Report", id: "clock-report") {
457 if case .success(let model) = workspace {
458 ClockReportView(workspace: model, session: session)
459 }
460 }
461 .defaultSize(width: 860, height: 560)
462 Window("Capture", id: "capture") {
463 if case .success(let model) = workspace {
464 CaptureView(workspace: model, session: session, commands: commands, clock: clock)
465 }
466 }
467 .windowResizability(.contentSize)
468 .windowLevel(.floating)
469 .commands {
470 CommandGroup(after: .newItem) {
471 Button("Add Folder…") { commands.showingFolderPicker = true }
472 .keyboardShortcut("o", modifiers: [.command, .shift])
473 Button("Quick Open…") { commands.showingQuickOpen = true }
474 .keyboardShortcut("p")
475 Button("Command Palette…") { commands.showingPalette = true }
476 .keyboardShortcut("p", modifiers: [.command, .shift])
477 }
478 CommandGroup(after: .saveItem) {
479 Menu("Export") {
480 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
481 Button(command.localizedTitle) { commands.run(command.id) }
482 }
483 }
484 .disabled(session.path == nil)
485 Menu("Publish") {
486 ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
487 Button(command.localizedTitle) { commands.run(command.id) }
488 }
489 }
490 Divider()
491 Button("Revert to File on Disk") { commands.run("app.revert") }
492 .disabled(session.path == nil)
493 Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
494 .disabled(session.path == nil)
495 Button("Recovery Versions…") { commands.run("app.recovery") }
496 .disabled(session.path == nil)
497 }
498 CommandGroup(replacing: .saveItem) {
499 Button("Close Buffer") {
500 // ⌘W closes the buffer in the main window, and other windows themselves.
501 if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
502 key.performClose(nil)
503 } else {
504 commands.run("app.buffer.kill")
505 }
506 }
507 .keyboardShortcut("w")
508 Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
509 .keyboardShortcut("w", modifiers: [.command, .shift])
510 Divider()
511 Button("Save") {
512 if !session.save(), session.conflict != nil { commands.showingConflict = true }
513 }
514 .keyboardShortcut("s")
515 .disabled(session.path == nil || session.isReadOnly)
516 Button("Save All") { commands.run("app.save-all") }
517 .keyboardShortcut("s", modifiers: [.command, .option])
518 .disabled(session.dirtyPaths.isEmpty)
519 }
520 CommandGroup(after: .sidebar) {
521 Button("Split Pane Below") { commands.run("app.split-below") }
522 .keyboardShortcut("2", modifiers: [.command, .control])
523 Button("Split Pane Right") { commands.run("app.split-right") }
524 .keyboardShortcut("3", modifiers: [.command, .control])
525 Button("Close Pane") { commands.run("app.pane-close") }
526 .keyboardShortcut("0", modifiers: [.command, .control])
527 Button("Close Other Panes") { commands.run("app.pane-only") }
528 .keyboardShortcut("1", modifiers: [.command, .control])
529 Button("Next Pane") { commands.run("app.pane-next") }
530 .keyboardShortcut("`", modifiers: [.command, .option])
531 Divider()
532 Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
533 .keyboardShortcut("o", modifiers: [.command, .option])
534 Button("Show or Hide Backlinks") { commands.run("app.toggle-backlinks") }
535 Button("Show or Hide Columns and Clock") { commands.run("app.toggle-inspector") }
536 .keyboardShortcut("i", modifiers: [.command, .option])
537 MarkupToggle()
538 Button("Truncate or Wrap Long Lines") { commands.run("editor.toggle-truncate-lines") }
539 Button("Turn Auto Fill On or Off") { commands.run("editor.toggle-auto-fill") }
540 Button("Check Spelling While Typing") { commands.editor?.run("editor.toggle-spell-check") }
541 .disabled(commands.editor == nil)
542 }
543 CommandGroup(after: .pasteboard) {
544 Divider()
545 FindMenu(commands: commands)
546 }
547 CommandGroup(after: .textEditing) {
548 Button("Cancel Running Task") { commands.run("app.babel.cancel") }
549 .keyboardShortcut(".")
550 .disabled(!session.isRunningBabel && commands.emacsTask == nil)
551 Button("Search Notes") { commands.focusSearch = true }
552 .keyboardShortcut("f", modifiers: [.command, .shift])
553 }
554 CommandGroup(before: .windowList) {
555 AgendaMenuItem()
556 Divider()
557 Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
558 Button("Next Buffer") { commands.run("app.buffer.next") }
559 .keyboardShortcut("]", modifiers: [.command, .shift])
560 Button("Previous Buffer") { commands.run("app.buffer.previous") }
561 .keyboardShortcut("[", modifiers: [.command, .shift])
562 Divider()
563 }
564 CommandGroup(after: .newItem) {
565 Button("Capture…") { commands.run("app.capture") }
566 .keyboardShortcut("n", modifiers: [.command, .shift])
567 Button("New Window") { commands.run("app.window-new") }
568 .keyboardShortcut("n", modifiers: [.command, .option])
569 }
570 }
571 .commands {
572 CommandMenu("Org") {
573 ClockMenu(commands: commands, clock: clock)
574 Divider()
575 OrgMenuItems(commands: commands)
576 }
577 }
578 .commands {
579 CommandGroup(after: .appSettings) {
580 Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
581 .keyboardShortcut(",", modifiers: [.command, .option])
582 }
583 #if !APPSTORE
584 CommandGroup(after: .appInfo) {
585 CheckForUpdatesItem(updates: delegate.updates)
586 }
587 #endif
588 CommandGroup(replacing: .help) {
589 Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
590 Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
591 Divider()
592 Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
593 .disabled(!commands.mainWindowOpen)
594 }
595 }
596 Settings {
597 #if APPSTORE
598 SettingsView(commands: commands, workspace: try? workspace.get())
599 #else
600 SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
601 #endif
602 }
603 }
604}
605
606/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
607/// subject, with the keys that run them in the current keymap.
608struct OrgMenuItems: View {
609 let commands: AppCommands
610
611 /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
612 /// first submenu with a prefix it starts with.
613 static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
614 ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
615 ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
616 ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort."]),
617 ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
618 ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
619 ("Lists", ["org.item.", "org.checkbox."]),
620 ("Tables", ["org.table", "app.table-", "app.plot"]),
621 ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote."]),
622 ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
623 ("Text", ["org.emphasize", "org.fill-"]),
624 ("Attachments", ["app.attach."]),
625 ("Notes", ["app.dailies.", "app.node."]),
626 ("Encryption", ["app.crypt."]),
627 ]
628
629 private static func group(of id: String) -> Int? {
630 groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
631 }
632
633 private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
634
635 var body: some View {
636 // Commands that fit no subject, such as Act at Point, come first.
637 ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
638 Divider()
639 ForEach(Self.groups.indices, id: \.self) { index in
640 Menu(Self.groups[index].title) {
641 ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
642 }
643 }
644 }
645
646 private func item(_ command: EditorCommand) -> some View {
647 Button {
648 if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
649 } label: {
650 Text(command.localizedTitle)
651 if let keys = commands.keyLabel(for: command.id) { Text(keys) }
652 }
653 .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
654 }
655}
656
657/// The user manual, as `scripts/publish-docs.sh` publishes it.
658enum Manual {
659 static let home = URL(string: "https://files.krz.sh/orgstar/")!
660 /// The key reference, with every preset's keys.
661 static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
662}
663
664/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
665struct MarkupToggle: View {
666 @AppStorage("showTabBar") private var showTabBar = false
667 @AppStorage("showMarkup") private var showMarkup = false
668 @AppStorage("showLineNumbers") private var showLineNumbers = false
669 @AppStorage("lineNumbersType") private var lineNumbersType = "t"
670
671 var body: some View {
672 Toggle("Show Markup", isOn: $showMarkup)
673 .keyboardShortcut("m", modifiers: [.command, .shift])
674 Toggle("Show Line Numbers", isOn: $showLineNumbers)
675 .keyboardShortcut("l", modifiers: [.command, .shift])
676 Picker("Line Numbers", selection: $lineNumbersType) {
677 Text("Absolute").tag("t")
678 Text("Relative").tag("relative")
679 Text("Visual").tag("visual")
680 }
681 Toggle("Show Tab Bar", isOn: $showTabBar)
682 }
683}
684
685/// Edit ▸ Find: the editor's find bar.
686struct FindMenu: View {
687 let commands: AppCommands
688
689 var body: some View {
690 Menu("Find") {
691 item("Find…", "edit.find", "f")
692 item("Find and Replace…", "edit.replace", "f", [.command, .option])
693 item("Find Next", "edit.find-next", "g")
694 item("Find Previous", "edit.find-previous", "g", [.command, .shift])
695 item("Use Selection for Find", "edit.use-selection-for-find", "e")
696 }
697 }
698
699 private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
700 Button(title) { commands.editor?.run(id) }
701 .keyboardShortcut(key, modifiers: modifiers)
702 .disabled(commands.editor == nil)
703 }
704}
705
706/// Window ▸ Agenda.
707struct AgendaMenuItem: View {
708 @Environment(\.openWindow) private var openWindow
709
710 var body: some View {
711 Button("Agenda") { openWindow(id: "agenda") }
712 .keyboardShortcut("a", modifiers: [.command, .shift])
713 Button("Board") { openWindow(id: "board") }
714 .keyboardShortcut("b", modifiers: [.command, .shift])
715 Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
716 }
717}
718
719struct SettingsView: View {
720 let commands: AppCommands
721 let workspace: WorkspaceModel?
722 #if !APPSTORE
723 let updates: Updates
724 #endif
725 @State private var importing = false
726 #if APPSTORE
727 @State private var configFolder = UserConfig.directoryOverride
728 #endif
729 @Environment(\.openWindow) private var openWindow
730 @AppStorage("saveMode") private var saveMode = SaveMode.automatic
731 @AppStorage("keymap") private var preset = KeymapPreset.emacs
732 @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
733 @AppStorage("tagsColumn") private var tagsColumn = -77
734 @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
735 @AppStorage("splitLine") private var splitLine = false
736 @AppStorage("alphabeticalLists") private var alphabeticalLists = true
737 @AppStorage("fillColumn") private var fillColumn = 80
738 @AppStorage("hiddenMarkers") private var hiddenMarkers = true
739 @AppStorage("prettyEntities") private var prettyEntities = true
740 @AppStorage("startupTruncated") private var startupTruncated = false
741 @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
742 @AppStorage("logDone") private var logDone = "nil"
743 @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
744 @AppStorage("useSpeedCommands") private var useSpeedCommands = false
745 @AppStorage("spellCheck") private var spellCheck = false
746 @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
747 @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
748 @AppStorage("agendaSpan") private var agendaSpan = 10
749 @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
750 @AppStorage("agendaSubfolders") private var agendaSubfolders = false
751 @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
752 @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
753 @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
754 @AppStorage("calendarEvents") private var calendarEvents = false
755 @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
756 @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
757 @AppStorage("agendaReminders") private var agendaReminders = false
758 @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
759 @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
760 @AppStorage("reminders") private var reminders = true
761 @AppStorage("reminderLead") private var reminderLead = 12
762 @AppStorage("clockIdleTime") private var clockIdleTime = 0
763 @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
764 @AppStorage("globalCapture") private var globalCapture = true
765 @AppStorage("menuBarItem") private var menuBarItem = false
766 @AppStorage("settingsTab") private var tab = "general"
767 @AppStorage("showHiddenFiles") private var showHiddenFiles = true
768 @AppStorage("themeFont") private var themeFont = ""
769 @AppStorage("themeBodyFont") private var themeBodyFont = ""
770 @AppStorage("themeFontSize") private var themeFontSize = 13
771 @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
772 @AppStorage("themeTextWidth") private var themeTextWidth = 0
773 @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
774
775 /// Installed font families that aren't monospaced, for body text.
776 private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
777 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
778 }
779
780 /// Installed monospaced font families.
781 private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
782 NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
783 }
784
785 var body: some View {
786 TabView(selection: $tab) {
787 Tab("General", systemImage: "gearshape", value: "general") { general }
788 Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
789 Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
790 Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
791 Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
792 #if APPSTORE
793 Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
794 #else
795 Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
796 #endif
797 }
798 .frame(width: 600)
799 }
800
801 private func editConfig() {
802 ConfigSync.shared.start()
803 openWindow(id: "main")
804 commands.jump(path: UserConfig.configFile.path, offset: 0)
805 }
806
807 #if APPSTORE
808 /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
809 private func chooseConfigFolder() {
810 let panel = NSOpenPanel()
811 panel.canChooseFiles = false
812 panel.canChooseDirectories = true
813 panel.canCreateDirectories = true
814 panel.directoryURL = configFolder ?? ConfigFolder.suggested
815 panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
816 guard panel.runModal() == .OK, let url = panel.url else { return }
817 if !ConfigFolder.set(url) {
818 GrantAccess.tell(String(localized: "orgstar can't keep \(OrgPaths.abbreviatingWithTilde(url.path)) as the configuration folder.", comment: "Alert when the chosen configuration folder can't be saved"),
819 String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
820 }
821 useConfigFolder(url)
822 }
823
824 /// Reads and writes the configuration in `url`, or with nil in the default folder.
825 private func useConfigFolder(_ url: URL?) {
826 if url == nil { ConfigFolder.clear() }
827 UserConfig.directoryOverride = url
828 configFolder = url
829 ConfigSync.shared.move(to: UserConfig.configFile)
830 }
831 #endif
832
833 private var general: some View {
834 Form {
835 Section {
836 LabeledContent("config.toml") {
837 HStack {
838 Button("Edit in orgstar") { editConfig() }
839 Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
840 Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
841 }
842 }
843 #if APPSTORE
844 LabeledContent("Folder") {
845 HStack {
846 Button("Choose Configuration Folder…") { chooseConfigFolder() }
847 if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
848 }
849 }
850 #endif
851 LabeledContent("Emacs") {
852 Button("Import from Emacs…") { importing = true }
853 }
854 } footer: {
855 Text("Every setting here is also in \(UserConfig.configFile.path), which you can edit, share or keep with your dotfiles. Changes in either place show up in the other.")
856 .settingsFooter()
857 }
858 #if !APPSTORE
859 if updates.canCheck {
860 Section {
861 Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
862 } footer: {
863 Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
864 .settingsFooter()
865 }
866 }
867 #endif
868 Section {
869 Picker("Save files", selection: $saveMode) {
870 Text("Automatically, when typing stops").tag(SaveMode.automatic)
871 Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
872 }
873 .pickerStyle(.radioGroup)
874 }
875 Section {
876 Picker("Keys", selection: $preset) {
877 ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
878 }
879 Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
880 Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
881 .help("Capture, the agenda, today's entries and the clock, from any app. When off, the menu bar shows orgstar only while a clock runs.")
882 Picker("Option as Meta", selection: $optionAsMeta) {
883 Text("Left Option").tag(OptionAsMeta.left.rawValue)
884 Text("Right Option").tag(OptionAsMeta.right.rawValue)
885 Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
886 Text("Neither").tag(0)
887 }
888 } footer: {
889 Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
890 .settingsFooter()
891 }
892 }
893 .formStyle(.grouped)
894 .frame(height: 330)
895 .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
896 }
897
898 private var editing: some View {
899 Form {
900 Section {
901 Picker("Tags", selection: $tagsColumn) {
902 Text("Aligned to end at column 77").tag(-77)
903 Text("One space after the title").tag(0)
904 }
905 Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
906 Toggle("M-RET splits the line at the caret", isOn: $splitLine)
907 Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
908 Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
909 }
910 Section {
911 Toggle("Long lines run off the edge instead of wrapping (org-startup-truncated)", isOn: $startupTruncated)
912 } footer: {
913 Text("Applies to files as they open. View ▸ Truncate or Wrap Long Lines switches the current file.")
914 .settingsFooter()
915 }
916 Section {
917 Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
918 Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
919 } footer: {
920 Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
921 .settingsFooter()
922 }
923 Section {
924 TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
925 } footer: {
926 Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
927 .settingsFooter()
928 }
929 Section {
930 Toggle("Entries can't be done before their TODO children (org-enforce-todo-dependencies)", isOn: $enforceTodoDependencies)
931 Toggle("Entries can't be done with unchecked boxes (org-enforce-todo-checkbox-dependencies)", isOn: $enforceTodoCheckboxDependencies)
932 } footer: {
933 Text("Under a parent with the ORDERED property (Toggle ORDERED Property, C-c C-x o), TODO children are also done in order.")
934 .settingsFooter()
935 }
936 Section {
937 Picker("When an entry is done (org-log-done)", selection: $logDone) {
938 Text("Record nothing").tag("nil")
939 Text("Record the time, as CLOSED").tag("time")
940 Text("Record the time and ask for a note").tag("note")
941 }
942 Toggle("State notes go in a LOGBOOK drawer (org-log-into-drawer)", isOn: logIntoDrawerOn)
943 } footer: {
944 Text("Keyword flags such as DONE(d!) and #+STARTUP words in a file override these. org-log-reschedule and org-log-redeadline are in config.toml.")
945 .settingsFooter()
946 }
947 Section {
948 Toggle("Speed keys: single letters at the start of a heading line run commands (org-use-speed-commands)", isOn: $useSpeedCommands)
949 Toggle("Check spelling while typing (spell-check)", isOn: $spellCheck)
950 } footer: {
951 Text("Spell checking applies to files as they open; Check Spelling While Typing switches the current file. Code, links, dates, tags and keywords aren't checked.")
952 .settingsFooter()
953 }
954 }
955 .formStyle(.grouped)
956 .frame(height: 860)
957 }
958
959 /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
960 private var logIntoDrawerOn: Binding<Bool> {
961 Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
962 }
963
964 private var appearance: some View {
965 Form {
966 ThemePickerSection()
967 AppIconSection()
968 Section {
969 Picker("Font", selection: $themeFont) {
970 Text("System monospaced").tag("")
971 Divider()
972 ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
973 if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
974 }
975 Picker("Body text", selection: $themeBodyFont) {
976 Text("Same as Font").tag("")
977 Text("System").tag("system")
978 Divider()
979 ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
980 if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
981 }
982 Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
983 Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
984 Picker("Text width", selection: $themeTextWidth) {
985 Text("Whole editor").tag(0)
986 ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
987 if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
988 }
989 Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
990 } footer: {
991 Text("Tags and tables line up in columns, so Font should be monospaced. With a Body text font, prose uses it while tables, code, dates, tags and drawers keep Font.")
992 .settingsFooter()
993 }
994 Section {
995 LabeledContent("Colors") {
996 HStack {
997 Button("Edit in config.toml") { editConfig() }
998 Button("Show Default Theme") {
999 openWindow(id: "main")
1000 commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1001 }
1002 }
1003 }
1004 } footer: {
1005 Text("Set colors under [theme] (both appearances), [theme.light] or [theme.dark] in config.toml, and TODO keyword colors under [theme.todo]. default-theme.toml lists every color with the default theme's values.")
1006 .settingsFooter()
1007 }
1008 }
1009 .formStyle(.grouped)
1010 .frame(height: 620)
1011 }
1012
1013 private var agenda: some View {
1014 Form {
1015 Section {
1016 Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1017 Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1018 Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1019 Toggle("Show days without entries", isOn: $agendaShowAllDates)
1020 Toggle("Habits only today", isOn: $habitsOnlyForToday)
1021 Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1022 Text("Dimmed").tag("t")
1023 Text("Hidden").tag("invisible")
1024 Text("Shown as usual").tag("nil")
1025 }
1026 }
1027 Section {
1028 Toggle("Show events from Calendar", isOn: $calendarEvents)
1029 .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1030 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1031 if calendarEvents {
1032 choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1033 }
1034 } footer: {
1035 Text("Events show in the agenda; double-click one to open it in Calendar, or choose Edit Event… in its context menu. New calendars show while every calendar is checked.")
1036 .settingsFooter()
1037 }
1038 .task(id: calendarEvents) {
1039 let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1040 calendars = allowed ? CalendarAccess.events.calendars() : []
1041 }
1042 Section {
1043 Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1044 .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1045 .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1046 if agendaReminders {
1047 choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1048 }
1049 } footer: {
1050 Text("Incomplete reminders with a due date show in the agenda read-only, overdue ones under today; double-click one to open it in Reminders.")
1051 .settingsFooter()
1052 }
1053 .task(id: agendaReminders) {
1054 let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1055 reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1056 }
1057 Section {
1058 Toggle("Notify before timed agenda entries", isOn: $reminders)
1059 Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1060 .disabled(!reminders)
1061 } footer: {
1062 Text("An entry's APPT_WARNTIME property overrides the lead time.")
1063 .settingsFooter()
1064 }
1065 Section {
1066 Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1067 clockIdleTime > 0
1068 } set: { on in
1069 clockIdleTime = on ? 15 : 0
1070 })
1071 Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1072 .disabled(clockIdleTime == 0)
1073 Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1074 } footer: {
1075 Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1076 .settingsFooter()
1077 }
1078 }
1079 .formStyle(.grouped)
1080 .frame(height: 560)
1081 }
1082
1083 /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1084 @ViewBuilder
1085 private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1086 if calendars.isEmpty {
1087 Text(empty)
1088 .foregroundStyle(.secondary)
1089 }
1090 ForEach(calendars, id: \.id) { calendar in
1091 Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1092 HStack(spacing: 6) {
1093 Circle()
1094 .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1095 .frame(width: 8, height: 8)
1096 Text(calendar.title)
1097 }
1098 }
1099 }
1100 }
1101
1102 /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1103 /// list, else the titles checked.
1104 private func chosen(
1105 _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1106 ) -> Binding<Bool> {
1107 let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1108 return Binding {
1109 CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1110 } set: { on in
1111 var titles = calendars.map(\.title).filter { title in
1112 chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1113 }
1114 titles.removeAll { $0 == calendar.title }
1115 if on { titles.append(calendar.title) }
1116 // An empty list means every calendar; turning events off hides them all.
1117 guard !titles.isEmpty else { return }
1118 setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1119 }
1120 }
1121
1122 private var capture: some View {
1123 Form {
1124 Section {
1125 Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1126 } footer: {
1127 Text("Templates go in \(CaptureTemplates.userFile.path).")
1128 .settingsFooter()
1129 }
1130 }
1131 .formStyle(.grouped)
1132 .frame(height: 160)
1133 }
1134}
1135
1136extension Text {
1137 func settingsFooter() -> some View {
1138 font(.caption)
1139 .foregroundStyle(.secondary)
1140 .textSelection(.enabled)
1141 .frame(maxWidth: .infinity, alignment: .leading)
1142 }
1143}