Sources/Orgstar/OrgstarApp.swift

512650677f4f383db027d187f15a091f62cb3cab
orgstar/Sources/Orgstar/OrgstarApp.swift

1176 lines · 56432 bytes

   1import AppKit
   2import OrgApp
   3import OrgCore
   4import OrgEditorAppKit
   5import OrgMathJax
   6import OrgPresentation
   7#if !APPSTORE
   8import OrgPrograms
   9#endif
  10import SwiftUI
  11import UserNotifications
  12
  13/// Window-level requests the menu bar makes.
  14@MainActor
  15@Observable
  16final class AppCommands {
  17    var showingQuickOpen = false
  18    var showingFolderPicker = false
  19    /// The first-launch sheet, while no folder has been added.
  20    var showingWelcome = false
  21    /// The notes the main window shows as a sheet.
  22    var whatsNew: ReleaseNotes?
  23    var focusSearch = false
  24    var showingConflict = false
  25    var showingPalette = false
  26    var showingMessages = false
  27    /// The main window's outline pane is shown, for View ▸ Show Outline.
  28    var outlineShown = false
  29    /// A location another window asked the main window to show.
  30    private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
  31    private var jumpID = 0
  32    /// Days the agenda window should show, from a followed timestamp.
  33    var agendaRequest: (start: Int, days: Int)?
  34    /// The editor with focus, for menus and the palette.
  35    var editor: OrgEditor?
  36    /// The editors and text views of every pane in every window.
  37    let store = EditorStore()
  38    /// The main window is on screen. App commands run there, so an editor window reopens it
  39    /// before asking for one.
  40    var mainWindowOpen = false
  41    /// What every editor is set up with, from the settings; the main window keeps it current.
  42    var editorSettings = EditorSettings()
  43    /// Runs work outside the text (a table recalculation in Emacs); the main window sets it.
  44    var externalHandler: ((ExternalRequest) -> Void)?
  45    /// Files and images pasted or dropped on an editor; the main window sets them.
  46    var filesHandler: (([URL]) -> Void)?
  47    var imageHandler: ((Data, String) -> Void)?
  48    #if APPSTORE
  49    /// Asks for the folders outside the sidebar's folders that paths need; the main window sets it.
  50    var reach: ([String]) -> Bool = { _ in true }
  51    #endif
  52    /// Tags used across the workspace, for tag completion; the main window sets it.
  53    var knownTags: () -> [String] = { [] }
  54    /// The pending key prefix, and what can follow it.
  55    var pendingKeys: String?
  56    /// The editor's evil state in the Doom preset.
  57    var editorState: String?
  58    /// The keymap in use, for showing keys in menus and the palette.
  59    var keymap = KeymapPreset.emacs.keymap
  60    var modal = false
  61    /// `org-stored-links`, most recent first; kept for the session, as in Emacs.
  62    var storedLinks: [StoredLink] = []
  63
  64    /// Puts `link` first in `storedLinks` and says what happened.
  65    func storeLink(_ link: StoredLink) {
  66        show(StoredLink.add(link, to: &storedLinks))
  67    }
  68
  69    /// The keys that run `command`, as menus and the palette show them.
  70    func keyLabel(for command: String) -> String? {
  71        let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
  72        return labels.isEmpty ? nil : labels.joined(separator: ", ")
  73    }
  74
  75    /// The editor's selection, for the modeline.
  76    var selection = NSRange(location: 0, length: 0)
  77    var keyHints: [KeyHint] = []
  78    /// A question a command asked, answered in the echo area.
  79    private(set) var prompt: PromptRequest?
  80    /// The last message from a command or the keymap, kept until the next key or click, as
  81    /// Emacs keeps it.
  82    private(set) var message: String?
  83    /// Recent messages, oldest first, for Messages.
  84    private(set) var messages: [String] = []
  85    @ObservationIgnored private var inputMonitor: Any?
  86
  87    func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
  88        self.prompt = PromptRequest(prompt: prompt, reply: reply)
  89    }
  90
  91    /// Clock questions in the echo area.
  92    var askClock: ClockModel.Ask {
  93        { [self] prompt in
  94            await withCheckedContinuation { continuation in
  95                ask(prompt) { continuation.resume(returning: $0) }
  96            }
  97        }
  98    }
  99
 100    /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
 101    func answer(_ text: String?) {
 102        guard let request = prompt else { return }
 103        prompt = nil
 104        if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
 105        request.reply(text)
 106    }
 107
 108    /// An export or table recalculation running in Emacs, for Cancel Running Task.
 109    private(set) var emacsTask: Task<Void, Never>?
 110    private var emacsSerial = 0
 111
 112    /// Runs `work` as the Emacs task, cancelling the one before.
 113    func runInEmacs(_ work: @escaping @MainActor () async -> Void) {
 114        emacsTask?.cancel()
 115        emacsSerial += 1
 116        let serial = emacsSerial
 117        emacsTask = Task {
 118            await work()
 119            if emacsSerial == serial { emacsTask = nil }
 120        }
 121    }
 122
 123    /// An app command from a menu, run by the main window.
 124    private(set) var runRequest: (id: String, serial: Int)?
 125    private var runSerial = 0
 126
 127    func run(_ id: String) {
 128        runSerial += 1
 129        runRequest = (id, runSerial)
 130    }
 131
 132    /// A capture waiting for the capture window: the template key and the link properties for
 133    /// its escapes (org-protocol), or the agenda day to schedule the entry on.
 134    var captureRequest: (template: String?, properties: [String: String], day: Int?, serial: Int)?
 135    private var captureSerial = 0
 136
 137    /// Capture from an agenda day, as `org-agenda-capture`: that day is the capture's date, and
 138    /// the entry is scheduled on it. The caller opens the capture window.
 139    func capture(on day: Int) {
 140        captureSerial += 1
 141        captureRequest = (nil, [:], day, captureSerial)
 142    }
 143
 144    /// `org-protocol://capture` and `store-link`, and the widgets' `orgstar://` links.
 145    func handle(protocolURL url: String) {
 146        if let link = URL(string: url).flatMap(AppLink.init(url:)) {
 147            switch link {
 148            case .agenda: run("app.agenda")
 149            case .clock: run("app.clock.goto")
 150            case .entry(let path, let offset): jump(path: path, offset: offset)
 151            case .capture(let template):
 152                captureSerial += 1
 153                captureRequest = (template, [:], nil, captureSerial)
 154                run("app.capture")
 155            }
 156            return
 157        }
 158        switch OrgProtocol.parse(url) {
 159        case .capture(let template, let properties):
 160            captureSerial += 1
 161            captureRequest = (template, properties, nil, captureSerial)
 162            run("app.capture")
 163        case .storeLink(let link, let title):
 164            storeLink(StoredLink(link: link, description: title))
 165            NSPasteboard.general.clearContents()
 166            NSPasteboard.general.setString(link, forType: .string)
 167        case nil:
 168            show("orgstar handles org-protocol capture and store-link")
 169        }
 170    }
 171
 172    func jump(path: String, offset: Int) {
 173        jumpID += 1
 174        jumpRequest = (path, offset, jumpID)
 175    }
 176
 177    func show(_ text: String) {
 178        message = text
 179        messages.append(text)
 180        if messages.count > 100 { messages.removeFirst(messages.count - 100) }
 181        AccessibilityNotification.Announcement(text).post()
 182        // A local monitor sees an event before it is handled, so a message the key or click
 183        // itself shows is set after this clears the last one.
 184        if inputMonitor == nil {
 185            inputMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .leftMouseDown, .rightMouseDown]) { [weak self] event in
 186                MainActor.assumeIsolated {
 187                    if self?.message != nil { self?.message = nil }
 188                }
 189                return event
 190            }
 191        }
 192    }
 193}
 194
 195struct PromptRequest: Identifiable {
 196    let id = UUID()
 197    let prompt: Prompt
 198    let reply: (String?) -> Void
 199}
 200
 201@MainActor
 202final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
 203    var session: DocumentSession?
 204    var commands: AppCommands?
 205    #if APPSTORE
 206    var workspace: WorkspaceModel?
 207    #else
 208    let updates = Updates()
 209    #endif
 210
 211    func applicationDidFinishLaunching(_ notification: Notification) {
 212        DockIcon.start()
 213        if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
 214        #if !APPSTORE
 215        updates.start()
 216        #endif
 217    }
 218
 219    #if APPSTORE
 220    /// A subscription may have lapsed or renewed while the app was in the background.
 221    func applicationDidBecomeActive(_ notification: Notification) {
 222        Task { await ProStore.shared.refresh() }
 223    }
 224    #endif
 225
 226    /// `:session` interpreters end with the app.
 227    func applicationWillTerminate(_ notification: Notification) {
 228        #if !APPSTORE
 229        BabelSessions.shared.stopAll()
 230        #endif
 231    }
 232
 233    /// Reminders show while Orgstar is in front too.
 234    nonisolated func userNotificationCenter(
 235        _ center: UNUserNotificationCenter, willPresent notification: UNNotification
 236    ) async -> UNNotificationPresentationOptions {
 237        [.banner, .sound, .list]
 238    }
 239
 240    /// Clicking a reminder shows its entry.
 241    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
 242        let info = response.notification.request.content.userInfo
 243        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
 244        await MainActor.run {
 245            NSApp.activate()
 246            commands?.jump(path: path, offset: offset)
 247        }
 248    }
 249
 250    /// Files opened from Finder, `open`, or a drop on the Dock icon: each opens as a buffer.
 251    /// Ones that arrive before the window is ready wait for it (`pendingOpens`).
 252    static var pendingOpens: [String] = []
 253
 254    func application(_ application: NSApplication, open urls: [URL]) {
 255        let paths = urls.filter(\.isFileURL).map(\.path)
 256        let links = urls.filter { $0.scheme == "org-protocol" || $0.scheme == AppLink.scheme }.map(\.absoluteString)
 257        guard let commands, let session else {
 258            Self.pendingOpens += paths
 259            Self.pendingLinks += links
 260            return
 261        }
 262        NSApp.activate()
 263        for path in paths { session.open(path) }
 264        for link in links { commands.handle(protocolURL: link) }
 265    }
 266
 267    /// org-protocol and orgstar:// links that arrive before the window is ready.
 268    static var pendingLinks: [String] = []
 269
 270    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
 271
 272    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
 273        guard let session else { return .terminateNow }
 274        #if APPSTORE
 275        BufferRestore.save(session, workspace: workspace)
 276        #else
 277        BufferRestore.save(session)
 278        #endif
 279        return UnsavedChanges.resolve(session, paths: session.openPaths) ? .terminateNow : .terminateCancel
 280    }
 281}
 282
 283/// Unsaved edits when leaving a file or quitting.
 284@MainActor
 285enum UnsavedChanges {
 286    /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
 287    /// explicit mode. A save that fails or conflicts keeps the file open.
 288    static func resolve(_ session: DocumentSession) -> Bool {
 289        guard session.isDirty else { return true }
 290        if session.saveMode == .automatic { return session.save() }
 291        let alert = NSAlert()
 292        alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
 293        alert.informativeText = "Your changes will be lost if you don't save them."
 294        alert.addButton(withTitle: "Save")
 295        alert.addButton(withTitle: "Don't Save")
 296        alert.addButton(withTitle: "Cancel")
 297        switch alert.runModal() {
 298        case .alertFirstButtonReturn: return session.save()
 299        case .alertSecondButtonReturn: return true
 300        default: return false
 301        }
 302    }
 303
 304    /// Whether the buffers of `paths` can be closed: saved in automatic mode, or as the user
 305    /// chooses for all of them in explicit mode.
 306    static func resolve(_ session: DocumentSession, paths: [String]) -> Bool {
 307        let dirty = paths.filter(session.dirtyPaths.contains)
 308        guard !dirty.isEmpty else { return true }
 309        if session.saveMode == .automatic { return dirty.map(session.save).allSatisfy { $0 } }
 310        if dirty == [session.path] { return resolve(session) }
 311        let alert = NSAlert()
 312        alert.messageText = "Save changes to \(dirty.count) files?"
 313        alert.informativeText = dirty.map { ($0 as NSString).lastPathComponent }.joined(separator: ", ")
 314        alert.addButton(withTitle: "Save All")
 315        alert.addButton(withTitle: "Don't Save")
 316        alert.addButton(withTitle: "Cancel")
 317        switch alert.runModal() {
 318        case .alertFirstButtonReturn: return dirty.map(session.save).allSatisfy { $0 }
 319        case .alertSecondButtonReturn: return true
 320        default: return false
 321        }
 322    }
 323}
 324
 325/// The open buffers, their order and carets, kept for the next launch.
 326@MainActor
 327enum BufferRestore {
 328    private static let key = "openBuffers"
 329
 330    struct State: Codable {
 331        var paths: [String]
 332        var current: String?
 333        var carets: [String: Int]
 334        /// In the Mac App Store build, bookmarks of the files outside every folder, which the
 335        /// sandbox would otherwise keep orgstar out of after relaunch.
 336        var bookmarks: [String: Data]?
 337    }
 338
 339    /// `bookmarking` says which paths get a bookmark. A path still open keeps the bookmark it
 340    /// has when no new one is made.
 341    static func save(_ session: DocumentSession, bookmarking: (String) -> Bool = { _ in false }, defaults: UserDefaults = .standard) {
 342        var carets: [String: Int] = [:]
 343        for path in session.openPaths { carets[path] = session.caret(of: path) }
 344        let previous = defaults.data(forKey: key).flatMap { try? JSONDecoder().decode(State.self, from: $0) }?.bookmarks ?? [:]
 345        var bookmarks: [String: Data] = [:]
 346        for path in session.openPaths {
 347            bookmarks[path] = (bookmarking(path) ? SecurityBookmark.make(URL(fileURLWithPath: path)) : nil) ?? previous[path]
 348        }
 349        let state = State(paths: session.openPaths, current: session.path, carets: carets, bookmarks: bookmarks.isEmpty ? nil : bookmarks)
 350        if let data = try? JSONEncoder().encode(state) { defaults.set(data, forKey: key) }
 351    }
 352
 353    #if APPSTORE
 354    /// Saves with bookmarks for the files outside `workspace`'s folders and grants.
 355    static func save(_ session: DocumentSession, workspace: WorkspaceModel?) {
 356        save(session, bookmarking: { workspace?.contains(URL(fileURLWithPath: $0)) != true })
 357    }
 358    #endif
 359
 360    /// Opens the buffers that were open, in order, and returns the carets to show them at.
 361    static func restore(_ session: DocumentSession, defaults: UserDefaults = .standard) -> [String: Int] {
 362        guard let data = defaults.data(forKey: key), var state = try? JSONDecoder().decode(State.self, from: data) else { return [:] }
 363        // A bookmarked file comes back with access, at the path it has now.
 364        for (path, bookmark) in state.bookmarks ?? [:] {
 365            guard let moved = SecurityBookmark.resolve(bookmark)?.url.path, moved != path else { continue }
 366            state.paths = state.paths.map { $0 == path ? moved : $0 }
 367            if state.current == path { state.current = moved }
 368            state.carets[moved] = state.carets.removeValue(forKey: path)
 369        }
 370        let existing = state.paths.filter { FileManager.default.fileExists(atPath: $0) }
 371        for path in existing { session.open(path) }
 372        if let current = state.current, existing.contains(current) { session.open(current) }
 373        return state.carets
 374    }
 375}
 376
 377@main
 378struct OrgstarApp: App {
 379    @NSApplicationDelegateAdaptor private var delegate: AppDelegate
 380    @State private var workspace = Result {
 381        try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
 382    }
 383    @State private var commands = AppCommands()
 384    @State private var clock = ClockModel()
 385    @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
 386    @State private var session: DocumentSession = {
 387        let session = DocumentSession()
 388        session.defaults = Preferences.orgSettings
 389        return session
 390    }()
 391
 392    init() {
 393        PDFExport.mathJaxURL = OrgMathJax.script
 394        DiagramBlocks.vizURL = OrgMathJax.viz
 395        DiagramBlocks.mermaidURL = OrgMathJax.mermaid
 396        #if APPSTORE
 397        AgendaSnapshot.useGroupContainer = true
 398        EmacsFallback.offered = false
 399        _ = FolderGrants.shared
 400        ProStore.shared.start()
 401        #else
 402        DocumentSession.programs = Programs()
 403        MacPro.resolve()
 404        MacPro.renewInBackground()
 405        #endif
 406        // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
 407        TableBlocks.allowed = { ProAccess.isUnlockedNow }
 408        // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
 409        #if DEBUG
 410        Perf.watchMainThread()
 411        #else
 412        if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
 413        #endif
 414    }
 415
 416    var body: some Scene {
 417        Window("orgstar", id: "main") {
 418            switch workspace {
 419            case .success(let model):
 420                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 421                    .environment(\.orgTheme, ConfigSync.shared.theme)
 422                    .tint(ConfigSync.shared.theme.color("accent"))
 423                    .onAppear {
 424                        delegate.session = session
 425                        delegate.commands = commands
 426                        #if APPSTORE
 427                        delegate.workspace = model
 428                        #endif
 429                        CaptureIntent.environment = (model, session, clock, commands)
 430                    }
 431            case .failure(let error):
 432                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
 433            }
 434        }
 435        .defaultSize(width: 1280, height: 860)
 436        WindowGroup("Editor", id: "editor") {
 437            if case .success = workspace {
 438                EditorWindowView(session: session, commands: commands, clock: clock)
 439                    .environment(\.orgTheme, ConfigSync.shared.theme)
 440                    .tint(ConfigSync.shared.theme.color("accent"))
 441            }
 442        }
 443        .defaultSize(width: 900, height: 700)
 444        .commandsRemoved()
 445        Window("Agenda", id: "agenda") {
 446            if case .success(let model) = workspace {
 447                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 448                    .environment(\.orgTheme, ConfigSync.shared.theme)
 449                    .tint(ConfigSync.shared.theme.color("accent"))
 450            }
 451        }
 452        .defaultSize(width: 760, height: 720)
 453        Window("Board", id: "board") {
 454            if case .success(let model) = workspace {
 455                BoardView(workspace: model, session: session, commands: commands)
 456                    .environment(\.orgTheme, ConfigSync.shared.theme)
 457                    .tint(ConfigSync.shared.theme.color("accent"))
 458            }
 459        }
 460        .defaultSize(width: 1100, height: 700)
 461        Window("Graph", id: "graph") {
 462            if case .success(let model) = workspace {
 463                RoamGraphWindow(workspace: model, session: session, commands: commands)
 464                    .tint(ConfigSync.shared.theme.color("accent"))
 465            }
 466        }
 467        .defaultSize(width: 900, height: 700)
 468        Window("Clock Report", id: "clock-report") {
 469            if case .success(let model) = workspace {
 470                ClockReportView(workspace: model, session: session)
 471            }
 472        }
 473        .defaultSize(width: 860, height: 560)
 474        Window("Capture", id: "capture") {
 475            if case .success(let model) = workspace {
 476                CaptureView(workspace: model, session: session, commands: commands, clock: clock)
 477            }
 478        }
 479        .windowResizability(.contentSize)
 480        .windowLevel(.floating)
 481        .commands {
 482            CommandGroup(after: .newItem) {
 483                Button("Add Folder…") { commands.showingFolderPicker = true }
 484                    .keyboardShortcut("o", modifiers: [.command, .shift])
 485                Button("Quick Open…") { commands.showingQuickOpen = true }
 486                    .keyboardShortcut("p")
 487                Button("Command Palette…") { commands.showingPalette = true }
 488                    .keyboardShortcut("p", modifiers: [.command, .shift])
 489            }
 490            CommandGroup(after: .saveItem) {
 491                Menu("Export") {
 492                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
 493                        Button(command.localizedTitle) { commands.run(command.id) }
 494                    }
 495                }
 496                .disabled(session.path == nil)
 497                Menu("Publish") {
 498                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
 499                        Button(command.localizedTitle) { commands.run(command.id) }
 500                    }
 501                }
 502                Divider()
 503                Button("Revert to File on Disk") { commands.run("app.revert") }
 504                    .disabled(session.path == nil)
 505                Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
 506                    .disabled(session.path == nil)
 507                Button("Recovery Versions…") { commands.run("app.recovery") }
 508                    .disabled(session.path == nil)
 509            }
 510            CommandGroup(replacing: .saveItem) {
 511                Button("Close Buffer") {
 512                    // ⌘W closes the buffer in the main window, and other windows themselves.
 513                    if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
 514                        key.performClose(nil)
 515                    } else {
 516                        commands.run("app.buffer.kill")
 517                    }
 518                }
 519                .keyboardShortcut("w")
 520                Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
 521                    .keyboardShortcut("w", modifiers: [.command, .shift])
 522                Divider()
 523                Button("Save") {
 524                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
 525                }
 526                .keyboardShortcut("s")
 527                .disabled(session.path == nil || session.isReadOnly)
 528                Button("Save All") { commands.run("app.save-all") }
 529                    .keyboardShortcut("s", modifiers: [.command, .option])
 530                    .disabled(session.dirtyPaths.isEmpty)
 531            }
 532            CommandGroup(after: .sidebar) {
 533                Button("Split Pane Below") { commands.run("app.split-below") }
 534                    .keyboardShortcut("2", modifiers: [.command, .control])
 535                Button("Split Pane Right") { commands.run("app.split-right") }
 536                    .keyboardShortcut("3", modifiers: [.command, .control])
 537                Button("Close Pane") { commands.run("app.pane-close") }
 538                    .keyboardShortcut("0", modifiers: [.command, .control])
 539                Button("Close Other Panes") { commands.run("app.pane-only") }
 540                    .keyboardShortcut("1", modifiers: [.command, .control])
 541                Button("Next Pane") { commands.run("app.pane-next") }
 542                    .keyboardShortcut("`", modifiers: [.command, .option])
 543                Divider()
 544                ViewMenuToggles(commands: commands)
 545                Divider()
 546                Button("Messages") { commands.run("app.messages") }
 547            }
 548            CommandGroup(after: .pasteboard) {
 549                Divider()
 550                FindMenu(commands: commands)
 551            }
 552            CommandGroup(after: .textEditing) {
 553                Button("Cancel Running Task") { commands.run("app.babel.cancel") }
 554                    .keyboardShortcut(".")
 555                    .disabled(!session.isRunningBabel && commands.emacsTask == nil)
 556                Button("Search Notes") { commands.focusSearch = true }
 557                    .keyboardShortcut("f", modifiers: [.command, .shift])
 558            }
 559            CommandGroup(before: .windowList) {
 560                AgendaMenuItem()
 561                Divider()
 562                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
 563                Button("Next Buffer") { commands.run("app.buffer.next") }
 564                    .keyboardShortcut("]", modifiers: [.command, .shift])
 565                Button("Previous Buffer") { commands.run("app.buffer.previous") }
 566                    .keyboardShortcut("[", modifiers: [.command, .shift])
 567                Divider()
 568            }
 569            CommandGroup(after: .newItem) {
 570                Button("Capture…") { commands.run("app.capture") }
 571                    .keyboardShortcut("n", modifiers: [.command, .shift])
 572                Button("New Window") { commands.run("app.window-new") }
 573                    .keyboardShortcut("n", modifiers: [.command, .option])
 574            }
 575        }
 576        .commands {
 577            CommandMenu("Org") {
 578                ClockMenu(commands: commands, clock: clock)
 579                Divider()
 580                OrgMenuItems(commands: commands)
 581            }
 582        }
 583        .commands {
 584            CommandGroup(after: .appSettings) {
 585                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
 586                    .keyboardShortcut(",", modifiers: [.command, .option])
 587            }
 588            #if !APPSTORE
 589            CommandGroup(after: .appInfo) {
 590                CheckForUpdatesItem(updates: delegate.updates)
 591            }
 592            #endif
 593            CommandGroup(replacing: .help) {
 594                Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
 595                Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
 596                Divider()
 597                Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
 598                    .disabled(!commands.mainWindowOpen)
 599            }
 600        }
 601        Settings {
 602            #if APPSTORE
 603            SettingsView(commands: commands, workspace: try? workspace.get())
 604            #else
 605            SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
 606            #endif
 607        }
 608    }
 609}
 610
 611/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
 612/// subject, with the keys that run them in the current keymap.
 613struct OrgMenuItems: View {
 614    let commands: AppCommands
 615
 616    /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
 617    /// first submenu with a prefix it starts with.
 618    static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
 619        ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
 620        ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
 621        ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort."]),
 622        ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
 623        ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
 624        ("Lists", ["org.item.", "org.checkbox."]),
 625        ("Tables", ["org.table", "app.table-", "app.plot"]),
 626        ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote."]),
 627        ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
 628        ("Text", ["org.emphasize", "org.fill-"]),
 629        ("Attachments", ["app.attach."]),
 630        ("Notes", ["app.dailies.", "app.node."]),
 631        ("Encryption", ["app.crypt."]),
 632    ]
 633
 634    private static func group(of id: String) -> Int? {
 635        groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
 636    }
 637
 638    private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
 639
 640    var body: some View {
 641        // Commands that fit no subject, such as Act at Point, come first.
 642        ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
 643        Divider()
 644        ForEach(Self.groups.indices, id: \.self) { index in
 645            Menu(Self.groups[index].title) {
 646                ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
 647            }
 648        }
 649    }
 650
 651    private func item(_ command: EditorCommand) -> some View {
 652        Button {
 653            if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
 654        } label: {
 655            Text(command.localizedTitle)
 656            if let keys = commands.keyLabel(for: command.id) { Text(keys) }
 657        }
 658        .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
 659    }
 660}
 661
 662/// The user manual, as `scripts/publish-docs.sh` publishes it.
 663enum Manual {
 664    static let home = URL(string: "https://files.krz.sh/orgstar/")!
 665    /// The key reference, with every preset's keys.
 666    static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
 667}
 668
 669/// View ▸ the panes and the focused editor's modes, checked while on.
 670struct ViewMenuToggles: View {
 671    let commands: AppCommands
 672    @AppStorage("backlinksShown") private var backlinksShown = true
 673    @AppStorage("inspectorShown") private var inspectorShown = false
 674
 675    var body: some View {
 676        let outline = commands.outlineShown
 677        let editor = commands.editor
 678        // A key that switches an editor mode shows a message, so the checks follow it.
 679        let _ = commands.message
 680        Toggle("Show Outline", isOn: Binding(get: { outline }, set: { _ in commands.run("app.toggle-outline") }))
 681            .keyboardShortcut("o", modifiers: [.command, .option])
 682        Toggle("Show Backlinks", isOn: $backlinksShown)
 683        Toggle("Show Columns and Clock", isOn: $inspectorShown)
 684            .keyboardShortcut("i", modifiers: [.command, .option])
 685        MarkupToggle()
 686        editorToggle("Truncate Long Lines", "editor.toggle-truncate-lines", editor?.truncatesLines)
 687        editorToggle("Auto Fill", "editor.toggle-auto-fill", editor?.autoFills)
 688        editorToggle("Check Spelling While Typing", "editor.toggle-spell-check", editor?.spellChecking)
 689    }
 690
 691    private func editorToggle(_ title: LocalizedStringKey, _ id: String, _ on: Bool?) -> some View {
 692        Toggle(title, isOn: Binding(get: { on ?? false }, set: { _ in commands.editor?.run(id) }))
 693            .disabled(on == nil)
 694    }
 695}
 696
 697/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
 698struct MarkupToggle: View {
 699    @AppStorage("showTabBar") private var showTabBar = false
 700    @AppStorage("showMarkup") private var showMarkup = false
 701    @AppStorage("showLineNumbers") private var showLineNumbers = false
 702    @AppStorage("lineNumbersType") private var lineNumbersType = "t"
 703
 704    var body: some View {
 705        Toggle("Show Markup", isOn: $showMarkup)
 706            .keyboardShortcut("m", modifiers: [.command, .shift])
 707        Toggle("Show Line Numbers", isOn: $showLineNumbers)
 708            .keyboardShortcut("l", modifiers: [.command, .shift])
 709        Picker("Line Numbers", selection: $lineNumbersType) {
 710            Text("Absolute").tag("t")
 711            Text("Relative").tag("relative")
 712            Text("Visual").tag("visual")
 713        }
 714        Toggle("Show Tab Bar", isOn: $showTabBar)
 715    }
 716}
 717
 718/// Edit ▸ Find: the editor's find bar.
 719struct FindMenu: View {
 720    let commands: AppCommands
 721
 722    var body: some View {
 723        Menu("Find") {
 724            item("Find…", "edit.find", "f")
 725            item("Find and Replace…", "edit.replace", "f", [.command, .option])
 726            item("Find Next", "edit.find-next", "g")
 727            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
 728            item("Use Selection for Find", "edit.use-selection-for-find", "e")
 729        }
 730    }
 731
 732    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
 733        Button(title) { commands.editor?.run(id) }
 734            .keyboardShortcut(key, modifiers: modifiers)
 735            .disabled(commands.editor == nil)
 736    }
 737}
 738
 739/// Window ▸ Agenda.
 740struct AgendaMenuItem: View {
 741    @Environment(\.openWindow) private var openWindow
 742
 743    var body: some View {
 744        Button("Agenda") { openWindow(id: "agenda") }
 745            .keyboardShortcut("a", modifiers: [.command, .shift])
 746        Button("Board") { openWindow(id: "board") }
 747            .keyboardShortcut("b", modifiers: [.command, .shift])
 748        Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
 749    }
 750}
 751
 752struct SettingsView: View {
 753    let commands: AppCommands
 754    let workspace: WorkspaceModel?
 755    #if !APPSTORE
 756    let updates: Updates
 757    #endif
 758    @State private var importing = false
 759    #if APPSTORE
 760    @State private var configFolder = UserConfig.directoryOverride
 761    #endif
 762    @Environment(\.openWindow) private var openWindow
 763    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 764    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 765    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 766    @AppStorage("tagsColumn") private var tagsColumn = -77
 767    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
 768    @AppStorage("splitLine") private var splitLine = false
 769    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 770    @AppStorage("fillColumn") private var fillColumn = 80
 771    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 772    @AppStorage("prettyEntities") private var prettyEntities = true
 773    @AppStorage("startupTruncated") private var startupTruncated = false
 774    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
 775    @AppStorage("logDone") private var logDone = "nil"
 776    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
 777    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
 778    @AppStorage("spellCheck") private var spellCheck = false
 779    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
 780    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
 781    @AppStorage("agendaSpan") private var agendaSpan = 10
 782    @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
 783    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
 784    @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
 785    @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
 786    @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
 787    @AppStorage("calendarEvents") private var calendarEvents = false
 788    @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
 789    @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
 790    @AppStorage("agendaReminders") private var agendaReminders = false
 791    @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
 792    @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
 793    @AppStorage("reminders") private var reminders = true
 794    @AppStorage("reminderLead") private var reminderLead = 12
 795    @AppStorage("clockIdleTime") private var clockIdleTime = 0
 796    @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
 797    @AppStorage("globalCapture") private var globalCapture = true
 798    @AppStorage("menuBarItem") private var menuBarItem = false
 799    @AppStorage("settingsTab") private var tab = "general"
 800    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
 801    @AppStorage("themeFont") private var themeFont = ""
 802    @AppStorage("themeBodyFont") private var themeBodyFont = ""
 803    @AppStorage("themeFontSize") private var themeFontSize = 13
 804    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
 805    @AppStorage("themeTextWidth") private var themeTextWidth = 0
 806    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
 807
 808    /// Installed font families that aren't monospaced, for body text.
 809    private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
 810        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
 811    }
 812
 813    /// Installed monospaced font families.
 814    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
 815        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
 816    }
 817
 818    var body: some View {
 819        TabView(selection: $tab) {
 820            Tab("General", systemImage: "gearshape", value: "general") { general }
 821            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
 822            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
 823            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
 824            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
 825            #if APPSTORE
 826            Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
 827            #else
 828            Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
 829            #endif
 830        }
 831        .frame(width: 600)
 832    }
 833
 834    private func editConfig() {
 835        ConfigSync.shared.start()
 836        openWindow(id: "main")
 837        commands.jump(path: UserConfig.configFile.path, offset: 0)
 838    }
 839
 840    #if APPSTORE
 841    /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
 842    private func chooseConfigFolder() {
 843        let panel = NSOpenPanel()
 844        panel.canChooseFiles = false
 845        panel.canChooseDirectories = true
 846        panel.canCreateDirectories = true
 847        panel.directoryURL = configFolder ?? ConfigFolder.suggested
 848        panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
 849        guard panel.runModal() == .OK, let url = panel.url else { return }
 850        if !ConfigFolder.set(url) {
 851            GrantAccess.tell(String(localized: "orgstar can't keep \(OrgPaths.abbreviatingWithTilde(url.path)) as the configuration folder.", comment: "Alert when the chosen configuration folder can't be saved"),
 852                             String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
 853        }
 854        useConfigFolder(url)
 855    }
 856
 857    /// Reads and writes the configuration in `url`, or with nil in the default folder.
 858    private func useConfigFolder(_ url: URL?) {
 859        if url == nil { ConfigFolder.clear() }
 860        UserConfig.directoryOverride = url
 861        configFolder = url
 862        ConfigSync.shared.move(to: UserConfig.configFile)
 863    }
 864    #endif
 865
 866    private var general: some View {
 867        Form {
 868            Section {
 869                LabeledContent("config.toml") {
 870                    HStack {
 871                        Button("Edit in orgstar") { editConfig() }
 872                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
 873                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
 874                    }
 875                }
 876                #if APPSTORE
 877                LabeledContent("Folder") {
 878                    HStack {
 879                        Button("Choose Configuration Folder…") { chooseConfigFolder() }
 880                        if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
 881                    }
 882                }
 883                #endif
 884                LabeledContent("Emacs") {
 885                    Button("Import from Emacs…") { importing = true }
 886                }
 887            } footer: {
 888                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.")
 889                    .settingsFooter()
 890            }
 891            #if !APPSTORE
 892            if updates.canCheck {
 893                Section {
 894                    Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
 895                } footer: {
 896                    Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
 897                        .settingsFooter()
 898                }
 899            }
 900            #endif
 901            Section {
 902                Picker("Save files", selection: $saveMode) {
 903                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
 904                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
 905                }
 906                .pickerStyle(.radioGroup)
 907            }
 908            Section {
 909                Picker("Keys", selection: $preset) {
 910                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
 911                }
 912                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
 913                Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
 914                    .help("Capture, the agenda, today's entries and the clock, from any app. When off, the menu bar shows orgstar only while a clock runs.")
 915                Picker("Option as Meta", selection: $optionAsMeta) {
 916                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
 917                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
 918                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
 919                    Text("Neither").tag(0)
 920                }
 921            } footer: {
 922                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
 923                    .settingsFooter()
 924            }
 925        }
 926        .formStyle(.grouped)
 927        .frame(height: 330)
 928        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
 929    }
 930
 931    private var editing: some View {
 932        Form {
 933            Section {
 934                Picker("Tags", selection: $tagsColumn) {
 935                    Text("Aligned to end at column 77").tag(-77)
 936                    Text("One space after the title").tag(0)
 937                }
 938                Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
 939                Toggle("M-RET splits the line at the caret", isOn: $splitLine)
 940                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
 941                Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
 942            }
 943            Section {
 944                Toggle("Long lines run off the edge instead of wrapping (org-startup-truncated)", isOn: $startupTruncated)
 945            } footer: {
 946                Text("Applies to files as they open. View ▸ Truncate or Wrap Long Lines switches the current file.")
 947                    .settingsFooter()
 948            }
 949            Section {
 950                Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
 951                Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
 952            } footer: {
 953                Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
 954                    .settingsFooter()
 955            }
 956            Section {
 957                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
 958            } footer: {
 959                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
 960                    .settingsFooter()
 961            }
 962            Section {
 963                Toggle("Entries can't be done before their TODO children (org-enforce-todo-dependencies)", isOn: $enforceTodoDependencies)
 964                Toggle("Entries can't be done with unchecked boxes (org-enforce-todo-checkbox-dependencies)", isOn: $enforceTodoCheckboxDependencies)
 965            } footer: {
 966                Text("Under a parent with the ORDERED property (Toggle ORDERED Property, C-c C-x o), TODO children are also done in order.")
 967                    .settingsFooter()
 968            }
 969            Section {
 970                Picker("When an entry is done (org-log-done)", selection: $logDone) {
 971                    Text("Record nothing").tag("nil")
 972                    Text("Record the time, as CLOSED").tag("time")
 973                    Text("Record the time and ask for a note").tag("note")
 974                }
 975                Toggle("State notes go in a LOGBOOK drawer (org-log-into-drawer)", isOn: logIntoDrawerOn)
 976            } footer: {
 977                Text("Keyword flags such as DONE(d!) and #+STARTUP words in a file override these. org-log-reschedule and org-log-redeadline are in config.toml.")
 978                    .settingsFooter()
 979            }
 980            Section {
 981                Toggle("Speed keys: single letters at the start of a heading line run commands (org-use-speed-commands)", isOn: $useSpeedCommands)
 982                Toggle("Check spelling while typing (spell-check)", isOn: $spellCheck)
 983            } footer: {
 984                Text("Spell checking applies to files as they open; Check Spelling While Typing switches the current file. Code, links, dates, tags and keywords aren't checked.")
 985                    .settingsFooter()
 986            }
 987        }
 988        .formStyle(.grouped)
 989        .frame(height: 860)
 990    }
 991
 992    /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
 993    private var logIntoDrawerOn: Binding<Bool> {
 994        Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
 995    }
 996
 997    private var appearance: some View {
 998        Form {
 999            ThemePickerSection()
1000            AppIconSection()
1001            Section {
1002                Picker("Font", selection: $themeFont) {
1003                    Text("System monospaced").tag("")
1004                    Divider()
1005                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
1006                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
1007                }
1008                Picker("Body text", selection: $themeBodyFont) {
1009                    Text("Same as Font").tag("")
1010                    Text("System").tag("system")
1011                    Divider()
1012                    ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
1013                    if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
1014                }
1015                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
1016                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
1017                Picker("Text width", selection: $themeTextWidth) {
1018                    Text("Whole editor").tag(0)
1019                    ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
1020                    if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
1021                }
1022                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
1023            } footer: {
1024                Text("Tags and tables line up in columns, so Font should be monospaced. With a Body text font, prose uses it while tables, code, dates, tags and drawers keep Font.")
1025                    .settingsFooter()
1026            }
1027            Section {
1028                LabeledContent("Colors") {
1029                    HStack {
1030                        Button("Edit in config.toml") { editConfig() }
1031                        Button("Show Default Theme") {
1032                            openWindow(id: "main")
1033                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1034                        }
1035                    }
1036                }
1037            } footer: {
1038                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.")
1039                    .settingsFooter()
1040            }
1041        }
1042        .formStyle(.grouped)
1043        .frame(height: 620)
1044    }
1045
1046    private var agenda: some View {
1047        Form {
1048            Section {
1049                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1050                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1051                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1052                Toggle("Show days without entries", isOn: $agendaShowAllDates)
1053                Toggle("Habits only today", isOn: $habitsOnlyForToday)
1054                Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1055                    Text("Dimmed").tag("t")
1056                    Text("Hidden").tag("invisible")
1057                    Text("Shown as usual").tag("nil")
1058                }
1059            }
1060            Section {
1061                Toggle("Show events from Calendar", isOn: $calendarEvents)
1062                    .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1063                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1064                if calendarEvents {
1065                    choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1066                }
1067            } footer: {
1068                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.")
1069                    .settingsFooter()
1070            }
1071            .task(id: calendarEvents) {
1072                let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1073                calendars = allowed ? CalendarAccess.events.calendars() : []
1074            }
1075            Section {
1076                Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1077                    .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1078                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1079                if agendaReminders {
1080                    choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1081                }
1082            } footer: {
1083                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.")
1084                    .settingsFooter()
1085            }
1086            .task(id: agendaReminders) {
1087                let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1088                reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1089            }
1090            Section {
1091                Toggle("Notify before timed agenda entries", isOn: $reminders)
1092                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1093                    .disabled(!reminders)
1094            } footer: {
1095                Text("An entry's APPT_WARNTIME property overrides the lead time.")
1096                    .settingsFooter()
1097            }
1098            Section {
1099                Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1100                    clockIdleTime > 0
1101                } set: { on in
1102                    clockIdleTime = on ? 15 : 0
1103                })
1104                Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1105                    .disabled(clockIdleTime == 0)
1106                Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1107            } footer: {
1108                Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1109                    .settingsFooter()
1110            }
1111        }
1112        .formStyle(.grouped)
1113        .frame(height: 560)
1114    }
1115
1116    /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1117    @ViewBuilder
1118    private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1119        if calendars.isEmpty {
1120            Text(empty)
1121                .foregroundStyle(.secondary)
1122        }
1123        ForEach(calendars, id: \.id) { calendar in
1124            Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1125                HStack(spacing: 6) {
1126                    Circle()
1127                        .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1128                        .frame(width: 8, height: 8)
1129                    Text(calendar.title)
1130                }
1131            }
1132        }
1133    }
1134
1135    /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1136    /// list, else the titles checked.
1137    private func chosen(
1138        _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1139    ) -> Binding<Bool> {
1140        let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1141        return Binding {
1142            CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1143        } set: { on in
1144            var titles = calendars.map(\.title).filter { title in
1145                chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1146            }
1147            titles.removeAll { $0 == calendar.title }
1148            if on { titles.append(calendar.title) }
1149            // An empty list means every calendar; turning events off hides them all.
1150            guard !titles.isEmpty else { return }
1151            setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1152        }
1153    }
1154
1155    private var capture: some View {
1156        Form {
1157            Section {
1158                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1159            } footer: {
1160                Text("Templates go in \(CaptureTemplates.userFile.path).")
1161                    .settingsFooter()
1162            }
1163        }
1164        .formStyle(.grouped)
1165        .frame(height: 160)
1166    }
1167}
1168
1169extension Text {
1170    func settingsFooter() -> some View {
1171        font(.caption)
1172            .foregroundStyle(.secondary)
1173            .textSelection(.enabled)
1174            .frame(maxWidth: .infinity, alignment: .leading)
1175    }
1176}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form