Sources/Orgstar/OrgstarApp.swift

956 lines · 45690 bytes

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