Sources/Orgstar/OrgstarApp.swift

d85099bc95bf1766aee990d94671dacda0c0686e
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

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