Sources/Orgstar/OrgstarApp.swift

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