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