Sources/Orgstar/OrgstarApp.swift

a15753a827b5ab7a0ccf3a0873890771c2979ee7
orgstar/Sources/Orgstar/OrgstarApp.swift

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