Sources/Orgstar/OrgstarApp.swift

4752dd3a1e83428b7d3360dbd60184ea42644ead
orgstar/Sources/Orgstar/OrgstarApp.swift

1454 lines · 71153 bytes

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