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