Sources/Orgstar/OrgstarApp.swift

6e84c5315a776376ffe643f78b5b48551895d250
orgstar/Sources/Orgstar/OrgstarApp.swift

1027 lines · 48268 bytes

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