Sources/Orgstar/OrgstarApp.swift

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