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