Sources/Orgstar/OrgstarApp.swift

213799f3f0792831bdbd707d1f85cb19b614f39f
orgstar/Sources/Orgstar/OrgstarApp.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form