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