Sources/Orgstar/OrgstarApp.swift

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