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