Sources/Orgstar/OrgstarApp.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/Orgstar/OrgstarApp.swift

1436 lines · 70265 bytes

54 symbols in this file
   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        #if !APPSTORE
 519        Printing.saveTo = DevelopmentHooks.printTo
 520        #endif
 521        DiagramBlocks.vizURL = OrgMathJax.viz
 522        DiagramBlocks.mermaidURL = OrgMathJax.mermaid
 523        #if APPSTORE
 524        AgendaSnapshot.useGroupContainer = true
 525        EmacsFallback.offered = false
 526        _ = FolderGrants.shared
 527        ProStore.shared.start()
 528        #else
 529        DocumentSession.programs = Programs()
 530        MacPro.resolve()
 531        MacPro.renewInBackground()
 532        #endif
 533        // `org-sbe` in table formulas runs blocks, so it needs Babel as source blocks do.
 534        TableBlocks.allowed = { ProAccess.isUnlockedNow }
 535        // Debug builds, and runs with ORGSTAR_PERF set: main-thread stalls in the console.
 536        #if DEBUG
 537        Perf.watchMainThread()
 538        #else
 539        if ProcessInfo.processInfo.environment["ORGSTAR_PERF"] != nil { Perf.watchMainThread() }
 540        #endif
 541    }
 542
 543    var body: some Scene {
 544        Window("orgstar", id: "main") {
 545            switch workspace {
 546            case .success(let model):
 547                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 548                    .environment(\.orgTheme, ConfigSync.shared.theme)
 549                    .tint(ConfigSync.shared.theme.color("accent"))
 550                    .onAppear {
 551                        delegate.session = session
 552                        delegate.commands = commands
 553                        #if APPSTORE
 554                        delegate.workspace = model
 555                        #else
 556                        GitAutoCommit.shared.roots = { model.rootPaths }
 557                        GitAutoCommit.shared.report = { commands.show($0) }
 558                        session.fileWritten = { GitAutoCommit.shared.fileWritten($0) }
 559                        #endif
 560                        CaptureIntent.environment = (model, session, clock, commands)
 561                    }
 562            case .failure(let error):
 563                ContentUnavailableView("Can't Open the Index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
 564            }
 565        }
 566        .defaultSize(width: 1280, height: 860)
 567        WindowGroup("Editor", id: "editor") {
 568            if case .success = workspace {
 569                EditorWindowView(session: session, commands: commands)
 570                    .environment(\.orgTheme, ConfigSync.shared.theme)
 571                    .tint(ConfigSync.shared.theme.color("accent"))
 572            }
 573        }
 574        .defaultSize(width: 900, height: 700)
 575        .commandsRemoved()
 576        Window("Agenda", id: "agenda") {
 577            if case .success(let model) = workspace {
 578                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
 579                    .environment(\.orgTheme, ConfigSync.shared.theme)
 580                    .tint(ConfigSync.shared.theme.color("accent"))
 581            }
 582        }
 583        .defaultSize(width: 760, height: 720)
 584        Window("Board", id: "board") {
 585            if case .success(let model) = workspace {
 586                BoardView(workspace: model, session: session, commands: commands)
 587                    .environment(\.orgTheme, ConfigSync.shared.theme)
 588                    .tint(ConfigSync.shared.theme.color("accent"))
 589            }
 590        }
 591        .defaultSize(width: 1100, height: 700)
 592        Window("Node Graph", id: "graph") {
 593            if case .success(let model) = workspace {
 594                RoamGraphWindow(workspace: model, session: session, commands: commands)
 595                    .tint(ConfigSync.shared.theme.color("accent"))
 596            }
 597        }
 598        .defaultSize(width: 900, height: 700)
 599        Window("Lint All Folders", id: "lint-folders") {
 600            if case .success(let model) = workspace {
 601                FolderLintWindow(workspace: model, session: session, commands: commands)
 602                    .tint(ConfigSync.shared.theme.color("accent"))
 603            }
 604        }
 605        .defaultSize(width: 760, height: 520)
 606        Window("Clock Report", id: "clock-report") {
 607            if case .success(let model) = workspace {
 608                ClockReportView(workspace: model, session: session)
 609                    .environment(\.orgTheme, ConfigSync.shared.theme)
 610                    .tint(ConfigSync.shared.theme.color("accent"))
 611            }
 612        }
 613        .defaultSize(width: 860, height: 560)
 614        Window("Capture", id: "capture") {
 615            if case .success(let model) = workspace {
 616                CaptureView(workspace: model, session: session, commands: commands, clock: clock)
 617                    .environment(\.orgTheme, ConfigSync.shared.theme)
 618                    .tint(ConfigSync.shared.theme.color("accent"))
 619            }
 620        }
 621        .windowResizability(.contentSize)
 622        .windowLevel(.floating)
 623        .commands {
 624            CommandGroup(after: .newItem) {
 625                Button("Add Folder…") { commands.showingFolderPicker = true }
 626                    .keyboardShortcut("o", modifiers: [.command, .shift])
 627                Button("Quick Open…") { commands.showingQuickOpen = true }
 628                    .keyboardShortcut("p")
 629                Button("Command Palette…") { commands.showingPalette = true }
 630                    .keyboardShortcut("p", modifiers: [.command, .shift])
 631            }
 632            CommandGroup(after: .saveItem) {
 633                Menu("Export") {
 634                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") && !hiddenCommandIDs.contains($0.id) }, id: \.id) { command in
 635                        Button(command.localizedTitle) { commands.run(command.id) }
 636                    }
 637                }
 638                .disabled(session.path == nil)
 639                Button("Share Subtree…") { commands.run("app.share-subtree") }
 640                    .disabled(!session.isOrg)
 641                Menu("Publish") {
 642                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.publish") }, id: \.id) { command in
 643                        Button(command.localizedTitle) { commands.run(command.id) }
 644                    }
 645                }
 646                Menu("Import") {
 647                    Button("Markdown Files…") { commands.run("app.import-markdown") }
 648                    Button("Obsidian Vault…") { commands.run("app.import-obsidian") }
 649                }
 650                Divider()
 651                Button("Revert to File on Disk") { commands.run("app.revert") }
 652                    .disabled(session.path == nil)
 653                Button("Resolve Sync Conflicts…") { commands.run("app.sync-conflicts") }
 654                    .disabled(session.path == nil)
 655                Button("History…") { commands.run("app.recovery") }
 656                    .disabled(session.path == nil)
 657                Button("Lint File") { commands.run("app.lint") }
 658                    .disabled(!FileLint.applies(to: session.path))
 659                Button("Lint All Folders") { commands.run("app.lint-folders") }
 660            }
 661            CommandGroup(replacing: .saveItem) {
 662                Button("Close Buffer") {
 663                    // ⌘W closes the buffer in the main window, and other windows themselves.
 664                    if let key = NSApp.keyWindow, key.identifier?.rawValue.contains("main") != true {
 665                        key.performClose(nil)
 666                    } else {
 667                        commands.run("app.buffer.kill")
 668                    }
 669                }
 670                .keyboardShortcut("w")
 671                Button("Close Window") { NSApp.keyWindow?.performClose(nil) }
 672                    .keyboardShortcut("w", modifiers: [.command, .shift])
 673                Divider()
 674                Button("Save") {
 675                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
 676                }
 677                .keyboardShortcut("s")
 678                .disabled(session.path == nil || session.isReadOnly)
 679                Button("Save All") { commands.run("app.save-all") }
 680                    .keyboardShortcut("s", modifiers: [.command, .option])
 681                    .disabled(session.dirtyPaths.isEmpty)
 682            }
 683            CommandGroup(replacing: .printItem) {
 684                Button("Page Setup…") { NSPageLayout().runModal() }
 685                // ⌘P is Quick Open.
 686                Button("Print…") {
 687                    if NSApp.keyWindow?.identifier?.rawValue.contains("agenda") == true {
 688                        commands.agendaPrintRequested = true
 689                    } else {
 690                        commands.run("app.print")
 691                    }
 692                }
 693                .keyboardShortcut("p", modifiers: [.command, .option])
 694                Button("Print Subtree…") { commands.run("app.print-subtree") }
 695                    .disabled(!session.isOrg)
 696                Button("Print Selection…") { commands.run("app.print-selection") }
 697                    .disabled(!session.isOrg)
 698            }
 699            CommandGroup(after: .sidebar) {
 700                Button("Split Pane Below") { commands.run("app.split-below") }
 701                    .keyboardShortcut("2", modifiers: [.command, .control])
 702                Button("Split Pane Right") { commands.run("app.split-right") }
 703                    .keyboardShortcut("3", modifiers: [.command, .control])
 704                Button("Close Pane") { commands.run("app.pane-close") }
 705                    .keyboardShortcut("0", modifiers: [.command, .control])
 706                Button("Close Other Panes") { commands.run("app.pane-only") }
 707                    .keyboardShortcut("1", modifiers: [.command, .control])
 708                Button("Next Pane") { commands.run("app.pane-next") }
 709                    .keyboardShortcut("`", modifiers: [.command, .option])
 710                Divider()
 711                ViewMenuToggles(commands: commands)
 712                Divider()
 713                Button("Messages") { commands.run("app.messages") }
 714            }
 715            CommandGroup(after: .pasteboard) {
 716                Divider()
 717                FindMenu(commands: commands)
 718                MacroMenu(commands: commands)
 719            }
 720            CommandGroup(after: .textEditing) {
 721                Button("Cancel Running Task") { commands.run("app.babel.cancel") }
 722                    .keyboardShortcut(".")
 723                    .disabled(!session.isRunningBabel && commands.emacsTask == nil)
 724                Button("Search Notes") { commands.focusSearch = true }
 725                    .keyboardShortcut("f", modifiers: [.command, .shift])
 726            }
 727            CommandGroup(before: .windowList) {
 728                AgendaMenuItem()
 729                Divider()
 730                Button("Switch to Buffer…") { commands.run("app.buffer.switch") }
 731                Button("Next Buffer") { commands.run("app.buffer.next") }
 732                    .keyboardShortcut("]", modifiers: [.command, .shift])
 733                Button("Previous Buffer") { commands.run("app.buffer.previous") }
 734                    .keyboardShortcut("[", modifiers: [.command, .shift])
 735                Divider()
 736            }
 737            CommandGroup(after: .newItem) {
 738                Button("Capture…") { commands.run("app.capture") }
 739                    .keyboardShortcut("n", modifiers: [.command, .shift])
 740                Button("New File from Template…") { commands.run("app.new-file-from-template") }
 741                Button("New Window") { commands.run("app.window-new") }
 742                    .keyboardShortcut("n", modifiers: [.command, .option])
 743            }
 744        }
 745        .commands {
 746            CommandMenu("Org") {
 747                ClockMenu(commands: commands, clock: clock)
 748                Divider()
 749                OrgMenuItems(commands: commands)
 750            }
 751        }
 752        .commands {
 753            CommandGroup(after: .appSettings) {
 754                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
 755                    .keyboardShortcut(",", modifiers: [.command, .option])
 756            }
 757            #if !APPSTORE
 758            CommandGroup(after: .appInfo) {
 759                CheckForUpdatesItem(updates: delegate.updates)
 760            }
 761            #endif
 762            CommandGroup(replacing: .help) {
 763                Button("orgstar Manual") { NSWorkspace.shared.open(Manual.home) }
 764                Button("Keys") { NSWorkspace.shared.open(Manual.keys) }
 765                Divider()
 766                Button("What's New in orgstar") { commands.whatsNew = WhatsNew.releases.first }
 767                    .disabled(!commands.mainWindowOpen)
 768            }
 769        }
 770        Settings {
 771            #if APPSTORE
 772            SettingsView(commands: commands, workspace: try? workspace.get())
 773            #else
 774            SettingsView(commands: commands, workspace: try? workspace.get(), updates: delegate.updates)
 775            #endif
 776        }
 777    }
 778}
 779
 780/// The Org menu: every org command and the app's commands for entries and notes, in submenus by
 781/// subject, with the keys that run them in the current keymap.
 782struct OrgMenuItems: View {
 783    let commands: AppCommands
 784
 785    /// Submenus and the command id prefixes they hold, in menu order. A command goes in the
 786    /// first submenu with a prefix it starts with.
 787    static let groups: [(title: LocalizedStringKey, prefixes: [String])] = [
 788        ("Visibility", ["org.cycle", "org.fold.", "org.narrow.", "org.widen", "org.sparse-tree", "org.toggle-inline-images", "org.latex-preview"]),
 789        ("Headings", ["org.heading.", "org.subtree.", "org.element.", "org.goto", "org.sort", "org.archive.", "app.refile", "app.archive"]),
 790        ("TODO and Tags", ["org.todo.", "org.priority.", "org.tags.", "org.effort.", "app.rename-"]),
 791        ("Properties and Columns", ["org.property.", "org.columns", "org.drawer."]),
 792        ("Dates and Timers", ["org.schedule", "org.deadline", "org.timestamp.", "org.timer."]),
 793        ("Lists", ["org.item.", "org.checkbox."]),
 794        ("Tables", ["org.table", "app.table-", "app.plot"]),
 795        ("Links and Footnotes", ["org.link.", "org.id.", "org.footnote.", "app.cite."]),
 796        ("Blocks", ["org.babel.", "org.structure-template", "org.edit-special", "org.dblock.", "org.clock.report", "org.denote."]),
 797        ("Text", ["org.emphasize", "org.fill-"]),
 798        ("Attachments", ["app.attach."]),
 799        ("Notes", ["app.dailies.", "app.node."]),
 800        ("Encryption", ["app.crypt."]),
 801    ]
 802
 803    private static func group(of id: String) -> Int? {
 804        groups.firstIndex { $0.prefixes.contains { id.hasPrefix($0) } }
 805    }
 806
 807    private static let shown = EditorCommands.all.filter { ($0.id.hasPrefix("org.") || group(of: $0.id) != nil) && !hiddenCommandIDs.contains($0.id) }
 808
 809    var body: some View {
 810        // Commands that fit no subject, such as Act at Point, come first.
 811        ForEach(Self.shown.filter { Self.group(of: $0.id) == nil }, id: \.id) { item($0) }
 812        Divider()
 813        ForEach(Self.groups.indices, id: \.self) { index in
 814            Menu(Self.groups[index].title) {
 815                ForEach(Self.shown.filter { Self.group(of: $0.id) == index }, id: \.id) { item($0) }
 816            }
 817        }
 818    }
 819
 820    private func item(_ command: EditorCommand) -> some View {
 821        Button {
 822            if command.id.hasPrefix("org.") { commands.editor?.run(command.id) } else { commands.run(command.id) }
 823        } label: {
 824            Text(command.localizedTitle)
 825            if let keys = commands.keyLabel(for: command.id) { Text(keys) }
 826        }
 827        .disabled(command.id.hasPrefix("org.") && commands.editor == nil)
 828    }
 829}
 830
 831/// The user manual, as `scripts/publish-docs.sh` publishes it.
 832enum Manual {
 833    static let home = URL(string: "https://files.krz.sh/orgstar/")!
 834    /// The key reference, with every preset's keys.
 835    static let keys = URL(string: "https://files.krz.sh/orgstar/guide/03-keys.html#key-reference")!
 836}
 837
 838/// View ▸ the panes and the focused editor's modes, checked while on.
 839struct ViewMenuToggles: View {
 840    let commands: AppCommands
 841    @AppStorage("backlinksShown") private var backlinksShown = true
 842    @AppStorage("inspectorShown") private var inspectorShown = false
 843
 844    var body: some View {
 845        let outline = commands.outlineShown
 846        let editor = commands.editor
 847        // A key that switches an editor mode shows a message, so the checks follow it.
 848        let _ = commands.message
 849        Toggle("Show Outline", isOn: Binding(get: { outline }, set: { _ in commands.run("app.toggle-outline") }))
 850            .keyboardShortcut("o", modifiers: [.command, .option])
 851        Toggle("Show Backlinks", isOn: $backlinksShown)
 852        Toggle("Show Inspector", isOn: $inspectorShown)
 853            .keyboardShortcut("i", modifiers: [.command, .option])
 854        MarkupToggle()
 855        editorToggle("Truncate Long Lines", "editor.toggle-truncate-lines", editor?.truncatesLines)
 856        editorToggle("Auto Fill", "editor.toggle-auto-fill", editor?.autoFills)
 857        editorToggle("Check Spelling While Typing", "editor.toggle-spell-check", editor?.spellChecking)
 858    }
 859
 860    private func editorToggle(_ title: LocalizedStringKey, _ id: String, _ on: Bool?) -> some View {
 861        Toggle(title, isOn: Binding(get: { on ?? false }, set: { _ in commands.editor?.run(id) }))
 862            .disabled(on == nil)
 863    }
 864}
 865
 866/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
 867struct MarkupToggle: View {
 868    @AppStorage("showTabBar") private var showTabBar = false
 869    @AppStorage("showMarkup") private var showMarkup = false
 870    @AppStorage("showLineNumbers") private var showLineNumbers = false
 871    @AppStorage("lineNumbersType") private var lineNumbersType = "t"
 872
 873    var body: some View {
 874        Toggle("Show Markup", isOn: $showMarkup)
 875            .keyboardShortcut("m", modifiers: [.command, .shift])
 876        Toggle("Show Line Numbers", isOn: $showLineNumbers)
 877            .keyboardShortcut("l", modifiers: [.command, .shift])
 878        Picker("Line Numbers", selection: $lineNumbersType) {
 879            Text("Absolute").tag("t")
 880            Text("Relative").tag("relative")
 881            Text("Visual").tag("visual")
 882        }
 883        Toggle("Show Tab Bar", isOn: $showTabBar)
 884    }
 885}
 886
 887/// Edit ▸ Find: the editor's find bar.
 888struct FindMenu: View {
 889    let commands: AppCommands
 890
 891    var body: some View {
 892        Menu("Find") {
 893            item("Find…", "edit.find", "f")
 894            item("Find and Replace…", "edit.replace", "f", [.command, .option])
 895            item("Find Next", "edit.find-next", "g")
 896            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
 897            item("Use Selection for Find", "edit.use-selection-for-find", "e")
 898            Divider()
 899            Button("Replace in Files…") { commands.run("app.replace-in-files") }
 900                .keyboardShortcut("f", modifiers: [.command, .option, .shift])
 901        }
 902    }
 903
 904    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
 905        Button(title) { commands.editor?.run(id) }
 906            .keyboardShortcut(key, modifiers: modifiers)
 907            .disabled(commands.editor == nil)
 908    }
 909}
 910
 911/// Edit ▸ Macros: keyboard macros, with the keys that run them in the current keymap.
 912struct MacroMenu: View {
 913    let commands: AppCommands
 914
 915    var body: some View {
 916        Menu("Macros") {
 917            item("Start Recording", "macro.start")
 918            item("Stop Recording", "macro.end")
 919            item("Run Last Macro", "macro.call")
 920            Divider()
 921            item("Name Last Macro…", "macro.name")
 922            item("Run Macro…", "macro.run")
 923        }
 924    }
 925
 926    private func item(_ title: LocalizedStringKey, _ id: String) -> some View {
 927        Button {
 928            commands.editor?.run(id)
 929        } label: {
 930            Text(title)
 931            if let keys = commands.keyLabel(for: id) { Text(keys) }
 932        }
 933        .disabled(commands.editor == nil)
 934    }
 935}
 936
 937/// Window ▸ Agenda.
 938struct AgendaMenuItem: View {
 939    @Environment(\.openWindow) private var openWindow
 940
 941    var body: some View {
 942        Button("Agenda") { openWindow(id: "agenda") }
 943            .keyboardShortcut("a", modifiers: [.command, .shift])
 944        Button("Board") { openWindow(id: "board") }
 945            .keyboardShortcut("b", modifiers: [.command, .shift])
 946        Button("Graph") { if ProAccess.shared.allows(.roam) { openWindow(id: "graph") } }
 947    }
 948}
 949
 950struct SettingsView: View {
 951    let commands: AppCommands
 952    let workspace: WorkspaceModel?
 953    #if !APPSTORE
 954    let updates: Updates
 955    #endif
 956    @State private var importing = false
 957    #if APPSTORE
 958    @State private var configFolder = UserConfig.directoryOverride
 959    #endif
 960    @Environment(\.openWindow) private var openWindow
 961    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
 962    @AppStorage("keymap") private var preset = KeymapPreset.emacs
 963    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
 964    @AppStorage("tagsColumn") private var tagsColumn = -77
 965    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = false
 966    @AppStorage("splitLine") private var splitLine = false
 967    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
 968    @AppStorage("fillColumn") private var fillColumn = 80
 969    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
 970    @AppStorage("prettyEntities") private var prettyEntities = true
 971    @AppStorage("startupTruncated") private var startupTruncated = false
 972    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
 973    @AppStorage("logDone") private var logDone = "nil"
 974    @AppStorage("logIntoDrawer") private var logIntoDrawer = ""
 975    @AppStorage("useSpeedCommands") private var useSpeedCommands = false
 976    @AppStorage("spellCheck") private var spellCheck = false
 977    @AppStorage("completionAuto") private var completionAuto = "preset"
 978    @AppStorage("completionAutoDelay") private var completionAutoDelay = 400
 979    @AppStorage("completionAutoPrefix") private var completionAutoPrefix = 2
 980    @AppStorage("completionStyle") private var completionStyle = "preset"
 981    @AppStorage("completionWords") private var completionWords = false
 982    @AppStorage("enforceTodoDependencies") private var enforceTodoDependencies = false
 983    @AppStorage("enforceTodoCheckboxDependencies") private var enforceTodoCheckboxDependencies = false
 984    @AppStorage("agendaSpan") private var agendaSpan = 10
 985    @AppStorage("agendaStartOffset") private var agendaStartOffset = 0
 986    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
 987    @AppStorage("agendaShowAllDates") private var agendaShowAllDates = false
 988    @AppStorage("habitsOnlyForToday") private var habitsOnlyForToday = true
 989    @AppStorage("agendaDimBlockedTasks") private var agendaDimBlockedTasks = "t"
 990    @AppStorage("calendarEvents") private var calendarEvents = false
 991    @AppStorage("calendarEventCalendars") private var calendarEventCalendars = ""
 992    @State private var calendars: [(id: String, title: String, color: RGBA?)] = []
 993    @AppStorage("agendaReminders") private var agendaReminders = false
 994    @AppStorage("agendaReminderLists") private var agendaReminderLists = ""
 995    @State private var reminderLists: [(id: String, title: String, color: RGBA?)] = []
 996    @AppStorage("reminders") private var reminders = true
 997    @AppStorage("reminderLead") private var reminderLead = 12
 998    @AppStorage("clockIdleTime") private var clockIdleTime = 0
 999    @AppStorage("clockHistoryLength") private var clockHistoryLength = 5
1000    @AppStorage("globalCapture") private var globalCapture = true
1001    @AppStorage("menuBarItem") private var menuBarItem = false
1002    @AppStorage("settingsTab") private var tab = "general"
1003    @AppStorage("showHiddenFiles") private var showHiddenFiles = true
1004    @AppStorage("themeFont") private var themeFont = ""
1005    @AppStorage("themeBodyFont") private var themeBodyFont = ""
1006    @AppStorage("themeFontSize") private var themeFontSize = 13
1007    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
1008    @AppStorage("themeTextWidth") private var themeTextWidth = 0
1009    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
1010
1011    /// Installed font families that aren't monospaced, for body text.
1012    private static let proportionalFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
1013        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == false
1014    }
1015
1016    /// Installed monospaced font families.
1017    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
1018        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
1019    }
1020
1021    var body: some View {
1022        TabView(selection: $tab) {
1023            Tab("General", systemImage: "gearshape", value: "general") { general }
1024            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
1025            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
1026            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
1027            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
1028            Tab("Encryption", systemImage: "lock", value: "encryption") {
1029                Form { DecryptSettings() }.formStyle(.grouped).frame(height: 330)
1030            }
1031            #if !APPSTORE
1032            Tab(value: "git") { GitSettingsForm(workspace: workspace) } label: {
1033                Label { Text("Git", tableName: "DeveloperID") } icon: { Image(systemName: "arrow.triangle.branch") }
1034            }
1035            #endif
1036            #if APPSTORE
1037            Tab("orgstar+", systemImage: "star", value: "pro") { StoreForm() }
1038            #else
1039            Tab("orgstar+", systemImage: "star", value: "pro") { LicenseForm() }
1040            #endif
1041        }
1042        .frame(width: 600)
1043    }
1044
1045    private func editConfig() {
1046        ConfigSync.shared.start()
1047        openWindow(id: "main")
1048        commands.jump(path: UserConfig.configFile.path, offset: 0)
1049    }
1050
1051    #if APPSTORE
1052    /// A folder outside the app's container, such as `~/.config/orgstar` kept with dotfiles.
1053    private func chooseConfigFolder() {
1054        let panel = NSOpenPanel()
1055        panel.canChooseFiles = false
1056        panel.canChooseDirectories = true
1057        panel.canCreateDirectories = true
1058        panel.directoryURL = configFolder ?? ConfigFolder.suggested
1059        panel.message = String(localized: "Choose the folder for config.toml and orgstar's other configuration files.", comment: "Choose Configuration Folder panel")
1060        guard panel.runModal() == .OK, let url = panel.url else { return }
1061        if !ConfigFolder.set(url) {
1062            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"),
1063                             String(localized: "Access lasts until orgstar quits.", comment: "Alert when a folder grant or the configuration folder can't be saved"))
1064        }
1065        useConfigFolder(url)
1066    }
1067
1068    /// Reads and writes the configuration in `url`, or with nil in the default folder.
1069    private func useConfigFolder(_ url: URL?) {
1070        if url == nil { ConfigFolder.clear() }
1071        UserConfig.directoryOverride = url
1072        configFolder = url
1073        ConfigSync.shared.move(to: UserConfig.configFile)
1074    }
1075    #endif
1076
1077    private var general: some View {
1078        Form {
1079            Section {
1080                LabeledContent("config.toml") {
1081                    HStack {
1082                        Button("Edit in orgstar") { editConfig() }
1083                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
1084                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
1085                    }
1086                }
1087                #if APPSTORE
1088                LabeledContent("Folder") {
1089                    HStack {
1090                        Button("Choose Configuration Folder…") { chooseConfigFolder() }
1091                        if configFolder != nil { Button("Use Default Folder") { useConfigFolder(nil) } }
1092                    }
1093                }
1094                #endif
1095                LabeledContent("Emacs") {
1096                    Button("Import from Emacs…") { importing = true }
1097                }
1098            } footer: {
1099                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.")
1100                    .settingsFooter()
1101            }
1102            #if !APPSTORE
1103            if updates.canCheck {
1104                Section {
1105                    Toggle(isOn: Binding(get: { updates.automatically }, set: { updates.automatically = $0 })) { Text("Check for updates automatically", tableName: "DeveloperID") }
1106                } footer: {
1107                    Text("Once a day, from the app's own feed. orgstar ▸ Check for Updates… checks now.", tableName: "DeveloperID")
1108                        .settingsFooter()
1109                }
1110            }
1111            #endif
1112            Section {
1113                Picker("Save files", selection: $saveMode) {
1114                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
1115                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
1116                }
1117                .pickerStyle(.radioGroup)
1118            }
1119            Section {
1120                Picker("Keys", selection: $preset) {
1121                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
1122                }
1123                Toggle("Show hidden files and folders", isOn: $showHiddenFiles)
1124                Toggle("Keep orgstar in the menu bar", isOn: $menuBarItem)
1125                    .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.")
1126                Picker("Option as Meta", selection: $optionAsMeta) {
1127                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
1128                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
1129                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
1130                    Text("Neither").tag(0)
1131                }
1132            } footer: {
1133                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
1134                    .settingsFooter()
1135            }
1136        }
1137        .formStyle(.grouped)
1138        .frame(height: 330)
1139        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
1140    }
1141
1142    private var editing: some View {
1143        Form {
1144            Section {
1145                Picker("Tags", selection: $tagsColumn) {
1146                    Text("Aligned to end at column 77").tag(-77)
1147                    Text("One space after the title").tag(0)
1148                }
1149                .help(Text(verbatim: "org-tags-column"))
1150                Toggle(isOn: $headingAfterSubtree) { keyed("New headings go after the subtree", "org.heading.insert") }
1151                    .help(Text(verbatim: "org-insert-heading-respect-content"))
1152                Toggle(isOn: $splitLine) { keyed("New headings and items split the line at the caret", "org.heading.insert") }
1153                    .help(Text(verbatim: "org-M-RET-may-split-line"))
1154                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
1155                    .help(Text(verbatim: "org-list-allow-alphabetical"))
1156                Stepper(value: $fillColumn, in: 40...200) { keyed("Fill Paragraph wraps lines at column \(fillColumn)", "org.fill-paragraph") }
1157                    .help(Text(verbatim: "fill-column"))
1158            }
1159            Section {
1160                Toggle("Long lines run off the edge instead of wrapping", isOn: $startupTruncated)
1161                    .help(Text(verbatim: "org-startup-truncated"))
1162            } footer: {
1163                Text("Applies to files as they open. View ▸ Truncate Long Lines switches the current file.")
1164                    .settingsFooter()
1165            }
1166            Section {
1167                Toggle("Emacs hides emphasis markers", isOn: $hiddenMarkers)
1168                    .help(Text(verbatim: "org-hide-emphasis-markers"))
1169                Toggle("Emacs shows entities as characters", isOn: $prettyEntities)
1170                    .help(Text(verbatim: "org-pretty-entities"))
1171            } footer: {
1172                Text("Tags, tables and Fill Paragraph measure text as your Emacs displays it, so both write the same file.")
1173                    .settingsFooter()
1174            }
1175            Section {
1176                TextField("Default TODO keywords", text: $todoKeywords, axis: .vertical)
1177            } footer: {
1178                Text("For files without #+TODO, in #+TODO syntax, one sequence per line. Takes effect when orgstar restarts.")
1179                    .settingsFooter()
1180            }
1181            Section {
1182                Toggle("Entries can't be done before their TODO children", isOn: $enforceTodoDependencies)
1183                    .help(Text(verbatim: "org-enforce-todo-dependencies"))
1184                Toggle("Entries can't be done with unchecked boxes", isOn: $enforceTodoCheckboxDependencies)
1185                    .help(Text(verbatim: "org-enforce-todo-checkbox-dependencies"))
1186            } footer: {
1187                Text("Under a parent with the ORDERED property (Org ▸ Properties and Columns ▸ Toggle ORDERED Property), TODO children are also done in order.")
1188                    .settingsFooter()
1189            }
1190            Section {
1191                Picker("When an entry is done", selection: $logDone) {
1192                    Text("Record nothing").tag("nil")
1193                    Text("Record the time, as CLOSED").tag("time")
1194                    Text("Record the time and ask for a note").tag("note")
1195                }
1196                .help(Text(verbatim: "org-log-done"))
1197                Toggle("State notes go in a LOGBOOK drawer", isOn: logIntoDrawerOn)
1198                    .help(Text(verbatim: "org-log-into-drawer"))
1199            } footer: {
1200                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.")
1201                    .settingsFooter()
1202            }
1203            Section {
1204                Toggle("Speed keys: single letters at the start of a heading line run commands", isOn: $useSpeedCommands)
1205                    .help(Text(verbatim: "org-use-speed-commands"))
1206                Toggle("Check spelling while typing", isOn: $spellCheck)
1207                    .help(Text(verbatim: "spell-check"))
1208            } footer: {
1209                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.")
1210                    .settingsFooter()
1211            }
1212            Section {
1213                Picker("Completion list opens", selection: $completionAuto) {
1214                    Text("As the keys do (by itself with Doom)").tag("preset")
1215                    Text("By itself as you type").tag("on")
1216                    Text("Only with a key").tag("off")
1217                }
1218                .help(Text(verbatim: "completion-auto"))
1219                Stepper("After a pause of \(completionAutoDelay) ms", value: $completionAutoDelay, in: 0...2000, step: 50)
1220                    .help(Text(verbatim: "completion-auto-delay"))
1221                Stepper("Once \(completionAutoPrefix) characters are typed", value: $completionAutoPrefix, in: 1...10)
1222                    .help(Text(verbatim: "completion-auto-prefix"))
1223                Picker("Candidates", selection: $completionStyle) {
1224                    Text("As the keys do (letters in order with Doom)").tag("preset")
1225                    Text("Start with what's typed").tag("prefix")
1226                    Text("Have its letters in order, best first").tag("fuzzy")
1227                }
1228                .help(Text(verbatim: "completion-style"))
1229                Toggle("The list offers words from open files and folders", isOn: $completionWords)
1230                    .help(Text(verbatim: "completion-words"))
1231            } header: {
1232                Text("Completion")
1233            } footer: {
1234                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.")
1235                    .settingsFooter()
1236            }
1237        }
1238        .formStyle(.grouped)
1239        .frame(height: 860)
1240    }
1241
1242    /// `label`, then the keys that run `command` in the current preset, if any.
1243    private func keyed(_ label: LocalizedStringKey, _ command: String) -> some View {
1244        HStack(spacing: 6) {
1245            Text(label)
1246            if let keys = commands.keyLabel(for: command) {
1247                Text(verbatim: keys).font(.system(.body, design: .monospaced)).foregroundStyle(.secondary)
1248            }
1249        }
1250    }
1251
1252    /// `org-log-into-drawer` as a switch: on is "LOGBOOK" (Emacs's t); a drawer name of its own counts as on.
1253    private var logIntoDrawerOn: Binding<Bool> {
1254        Binding(get: { !logIntoDrawer.isEmpty }, set: { logIntoDrawer = $0 ? "LOGBOOK" : "" })
1255    }
1256
1257    private var appearance: some View {
1258        Form {
1259            ThemePickerSection()
1260            AppIconSection()
1261            Section {
1262                Picker("Font", selection: $themeFont) {
1263                    Text("System monospaced").tag("")
1264                    Divider()
1265                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
1266                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
1267                }
1268                Picker("Body font", selection: $themeBodyFont) {
1269                    Text("Same as Font").tag("")
1270                    Text("System").tag("system")
1271                    Divider()
1272                    ForEach(Self.proportionalFamilies, id: \.self) { Text($0).tag($0) }
1273                    if !["", "system"].contains(themeBodyFont), !Self.proportionalFamilies.contains(themeBodyFont) { Text(themeBodyFont).tag(themeBodyFont) }
1274                }
1275                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
1276                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
1277                Picker("Text width", selection: $themeTextWidth) {
1278                    Text("Whole editor").tag(0)
1279                    ForEach([60, 70, 80, 90, 100, 120], id: \.self) { Text("\($0) columns").tag($0) }
1280                    if ![0, 60, 70, 80, 90, 100, 120].contains(themeTextWidth) { Text("\(themeTextWidth) columns").tag(themeTextWidth) }
1281                }
1282                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
1283            } footer: {
1284                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.")
1285                    .settingsFooter()
1286            }
1287            Section {
1288                LabeledContent("Colors") {
1289                    HStack {
1290                        Button("Edit in config.toml") { editConfig() }
1291                        Button("Show Default Theme") {
1292                            openWindow(id: "main")
1293                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
1294                        }
1295                    }
1296                }
1297            } footer: {
1298                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.")
1299                    .settingsFooter()
1300            }
1301        }
1302        .formStyle(.grouped)
1303        .frame(height: 620)
1304    }
1305
1306    private var agenda: some View {
1307        Form {
1308            Section {
1309                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...366)
1310                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
1311                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
1312                Toggle("Show days without entries", isOn: $agendaShowAllDates)
1313                Toggle("Habits only today", isOn: $habitsOnlyForToday)
1314                Picker("Blocked entries", selection: $agendaDimBlockedTasks) {
1315                    Text("Dimmed").tag("t")
1316                    Text("Hidden").tag("invisible")
1317                    Text("Shown as usual").tag("nil")
1318                }
1319            }
1320            Section {
1321                Toggle("Show events from Calendar", isOn: $calendarEvents)
1322                    .disabled(!ProAccess.shared.isUnlocked && !calendarEvents)
1323                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1324                if calendarEvents {
1325                    choices(calendars, empty: CalendarEvents.isAuthorized ? "No calendars." : "Allow orgstar to read your calendars in System Settings ▸ Privacy & Security ▸ Calendars.", setting: $calendarEventCalendars)
1326                }
1327            } footer: {
1328                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.")
1329                    .settingsFooter()
1330            }
1331            .task(id: calendarEvents) {
1332                let allowed = calendarEvents ? await CalendarAccess.events.requestAccess() : false
1333                calendars = allowed ? CalendarAccess.events.calendars() : []
1334            }
1335            Section {
1336                Toggle("Show reminders from Reminders", isOn: $agendaReminders)
1337                    .disabled(!ProAccess.shared.isUnlocked && !agendaReminders)
1338                    .help(ProAccess.shared.isUnlocked ? "" : "Needs orgstar+")
1339                if agendaReminders {
1340                    choices(reminderLists, empty: ReminderLists.isAuthorized ? "No lists." : "Allow orgstar to read your reminders in System Settings ▸ Privacy & Security ▸ Reminders.", setting: $agendaReminderLists)
1341                }
1342            } footer: {
1343                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.")
1344                    .settingsFooter()
1345            }
1346            .task(id: agendaReminders) {
1347                let allowed = agendaReminders ? await CalendarAccess.reminders.requestAccess() : false
1348                reminderLists = allowed ? CalendarAccess.reminders.lists() : []
1349            }
1350            Section {
1351                Toggle("Notify before timed agenda entries", isOn: $reminders)
1352                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
1353                    .disabled(!reminders)
1354            } footer: {
1355                Text("An entry's APPT_WARNTIME property overrides the lead time.")
1356                    .settingsFooter()
1357            }
1358            Section {
1359                Toggle("Ask what to do with idle time while clocked in", isOn: Binding {
1360                    clockIdleTime > 0
1361                } set: { on in
1362                    clockIdleTime = on ? 15 : 0
1363                })
1364                Stepper("After \(max(clockIdleTime, 1)) minutes without keyboard or mouse input", value: $clockIdleTime, in: 1...240)
1365                    .disabled(clockIdleTime == 0)
1366                Stepper("Remember \(clockHistoryLength) recently clocked entries", value: $clockHistoryLength, in: 1...35)
1367            } footer: {
1368                Text("org-clock-idle-time and org-clock-history-length. Org ▸ Clock lists the recent entries.")
1369                    .settingsFooter()
1370            }
1371        }
1372        .formStyle(.grouped)
1373        .frame(height: 560)
1374    }
1375
1376    /// A toggle per calendar or reminder list, with its color; `empty` when there are none.
1377    @ViewBuilder
1378    private func choices(_ calendars: [(id: String, title: String, color: RGBA?)], empty: LocalizedStringKey, setting: Binding<String>) -> some View {
1379        if calendars.isEmpty {
1380            Text(empty)
1381                .foregroundStyle(.secondary)
1382        }
1383        ForEach(calendars, id: \.id) { calendar in
1384            Toggle(isOn: chosen(calendar, among: calendars, setting: setting)) {
1385                HStack(spacing: 6) {
1386                    Circle()
1387                        .fill(calendar.color.map { Color(.sRGB, red: $0.red, green: $0.green, blue: $0.blue, opacity: $0.alpha) } ?? .secondary)
1388                        .frame(width: 8, height: 8)
1389                    Text(calendar.title)
1390                }
1391            }
1392        }
1393    }
1394
1395    /// `calendar-event-calendars` and `agenda-reminder-lists`: empty for every calendar or
1396    /// list, else the titles checked.
1397    private func chosen(
1398        _ calendar: (id: String, title: String, color: RGBA?), among calendars: [(id: String, title: String, color: RGBA?)], setting: Binding<String>
1399    ) -> Binding<Bool> {
1400        let chosen = setting.wrappedValue.split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }
1401        return Binding {
1402            CalendarEvents.chooses(id: calendar.id, title: calendar.title, chosen: chosen)
1403        } set: { on in
1404            var titles = calendars.map(\.title).filter { title in
1405                chosen.isEmpty || chosen.contains(title) || chosen.contains(calendars.first { $0.title == title }?.id ?? "")
1406            }
1407            titles.removeAll { $0 == calendar.title }
1408            if on { titles.append(calendar.title) }
1409            // An empty list means every calendar; turning events off hides them all.
1410            guard !titles.isEmpty else { return }
1411            setting.wrappedValue = Set(titles) == Set(calendars.map(\.title)) ? "" : titles.joined(separator: ", ")
1412        }
1413    }
1414
1415    private var capture: some View {
1416        Form {
1417            Section {
1418                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
1419            } footer: {
1420                Text("Templates go in \(CaptureTemplates.userFile.path).")
1421                    .settingsFooter()
1422            }
1423        }
1424        .formStyle(.grouped)
1425        .frame(height: 160)
1426    }
1427}
1428
1429extension Text {
1430    func settingsFooter() -> some View {
1431        font(.caption)
1432            .foregroundStyle(.secondary)
1433            .textSelection(.enabled)
1434            .frame(maxWidth: .infinity, alignment: .leading)
1435    }
1436}
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