Sources/Orgstar/OrgstarApp.swift

427abbbee0d20a70754de8e0e0846dae001f9c92
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

526 lines · 22133 bytes

  1import AppKit
  2import OrgApp
  3import OrgCore
  4import OrgEditorAppKit
  5import SwiftUI
  6import UserNotifications
  7
  8/// Window-level requests the menu bar makes.
  9@MainActor
 10@Observable
 11final class AppCommands {
 12    var showingQuickOpen = false
 13    var showingFolderPicker = false
 14    var focusSearch = false
 15    var showingConflict = false
 16    var showingPalette = false
 17    /// A location another window asked the main window to show.
 18    private(set) var jumpRequest: (path: String, offset: Int, id: Int)?
 19    private var jumpID = 0
 20    /// The editor showing the open file, for menus and the palette.
 21    var editor: OrgEditor?
 22    /// The pending key prefix, and what can follow it.
 23    var pendingKeys: String?
 24    /// The editor's evil state in the Doom preset.
 25    var editorState: String?
 26    /// The keymap in use, for showing keys in menus and the palette.
 27    var keymap = KeymapPreset.emacs.keymap
 28    var modal = false
 29
 30    /// The keys that run `command`, as menus and the palette show them.
 31    func keyLabel(for command: String) -> String? {
 32        let labels = keymap.keyLabels(for: command, modes: modal ? ["normal", "insert"] : [nil])
 33        return labels.isEmpty ? nil : labels.joined(separator: ", ")
 34    }
 35
 36    /// The editor's selection, for the modeline.
 37    var selection = NSRange(location: 0, length: 0)
 38    var keyHints: [KeyHint] = []
 39    /// A question a command asked, answered in the echo area.
 40    private(set) var prompt: PromptRequest?
 41    /// The last message from a command or the keymap, cleared after a few seconds.
 42    private(set) var message: String?
 43    private var messageID = 0
 44
 45    func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
 46        self.prompt = PromptRequest(prompt: prompt, reply: reply)
 47    }
 48
 49    /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
 50    func answer(_ text: String?) {
 51        guard let request = prompt else { return }
 52        prompt = nil
 53        if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
 54        request.reply(text)
 55    }
 56
 57    /// An app command from a menu, run by the main window.
 58    private(set) var runRequest: (id: String, serial: Int)?
 59    private var runSerial = 0
 60
 61    func run(_ id: String) {
 62        runSerial += 1
 63        runRequest = (id, runSerial)
 64    }
 65
 66    func jump(path: String, offset: Int) {
 67        jumpID += 1
 68        jumpRequest = (path, offset, jumpID)
 69    }
 70
 71    func show(_ text: String) {
 72        messageID += 1
 73        let id = messageID
 74        message = text
 75        Task {
 76            try? await Task.sleep(for: .seconds(4))
 77            if messageID == id { message = nil }
 78        }
 79    }
 80}
 81
 82struct PromptRequest: Identifiable {
 83    let id = UUID()
 84    let prompt: Prompt
 85    let reply: (String?) -> Void
 86}
 87
 88@MainActor
 89final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
 90    var session: DocumentSession?
 91    var commands: AppCommands?
 92
 93    func applicationDidFinishLaunching(_ notification: Notification) {
 94        if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
 95    }
 96
 97    /// Reminders show while Orgstar is in front too.
 98    nonisolated func userNotificationCenter(
 99        _ center: UNUserNotificationCenter, willPresent notification: UNNotification
100    ) async -> UNNotificationPresentationOptions {
101        [.banner, .sound, .list]
102    }
103
104    /// Clicking a reminder shows its entry.
105    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
106        let info = response.notification.request.content.userInfo
107        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
108        await MainActor.run {
109            NSApp.activate()
110            commands?.jump(path: path, offset: offset)
111        }
112    }
113
114    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
115
116    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
117        guard let session else { return .terminateNow }
118        return UnsavedChanges.resolve(session) ? .terminateNow : .terminateCancel
119    }
120}
121
122/// Unsaved edits when leaving a file or quitting.
123@MainActor
124enum UnsavedChanges {
125    /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
126    /// explicit mode. A save that fails or conflicts keeps the file open.
127    static func resolve(_ session: DocumentSession) -> Bool {
128        guard session.isDirty else { return true }
129        if session.saveMode == .automatic { return session.save() }
130        let alert = NSAlert()
131        alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
132        alert.informativeText = "Your changes will be lost if you don't save them."
133        alert.addButton(withTitle: "Save")
134        alert.addButton(withTitle: "Don't Save")
135        alert.addButton(withTitle: "Cancel")
136        switch alert.runModal() {
137        case .alertFirstButtonReturn: return session.save()
138        case .alertSecondButtonReturn: return true
139        default: return false
140        }
141    }
142}
143
144@main
145struct OrgstarApp: App {
146    @NSApplicationDelegateAdaptor private var delegate: AppDelegate
147    @State private var workspace = Result {
148        try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
149    }
150    @State private var commands = AppCommands()
151    @State private var clock = ClockModel()
152    @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
153    @State private var session: DocumentSession = {
154        let session = DocumentSession()
155        session.defaults = Preferences.orgSettings
156        return session
157    }()
158
159    var body: some Scene {
160        Window("Orgstar", id: "main") {
161            switch workspace {
162            case .success(let model):
163                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
164                    .environment(\.orgTheme, ConfigSync.shared.theme)
165                    .onAppear {
166                        delegate.session = session
167                        delegate.commands = commands
168                    }
169            case .failure(let error):
170                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
171            }
172        }
173        .defaultSize(width: 1280, height: 860)
174        Window("Agenda", id: "agenda") {
175            if case .success(let model) = workspace {
176                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler)
177                    .environment(\.orgTheme, ConfigSync.shared.theme)
178            }
179        }
180        .defaultSize(width: 760, height: 720)
181        Window("Board", id: "board") {
182            if case .success(let model) = workspace {
183                BoardView(workspace: model, session: session, commands: commands)
184                    .environment(\.orgTheme, ConfigSync.shared.theme)
185            }
186        }
187        .defaultSize(width: 1100, height: 700)
188        Window("Clock Report", id: "clock-report") {
189            if case .success(let model) = workspace {
190                ClockReportView(workspace: model)
191            }
192        }
193        .defaultSize(width: 860, height: 560)
194        Window("Capture", id: "capture") {
195            if case .success(let model) = workspace {
196                CaptureView(workspace: model, session: session, commands: commands)
197            }
198        }
199        .windowResizability(.contentSize)
200        .windowLevel(.floating)
201        .commands {
202            CommandGroup(after: .newItem) {
203                Button("Add Folder…") { commands.showingFolderPicker = true }
204                    .keyboardShortcut("o", modifiers: [.command, .shift])
205                Button("Quick Open…") { commands.showingQuickOpen = true }
206                    .keyboardShortcut("p")
207                Button("Command Palette…") { commands.showingPalette = true }
208                    .keyboardShortcut("p", modifiers: [.command, .shift])
209            }
210            CommandGroup(after: .saveItem) {
211                Menu("Export") {
212                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
213                        Button(command.title) { commands.run(command.id) }
214                    }
215                }
216                .disabled(session.path == nil)
217            }
218            CommandGroup(replacing: .saveItem) {
219                Button("Save") {
220                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
221                }
222                .keyboardShortcut("s")
223                .disabled(session.path == nil || session.isReadOnly)
224            }
225            CommandGroup(after: .sidebar) {
226                Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
227                    .keyboardShortcut("o", modifiers: [.command, .option])
228                MarkupToggle()
229            }
230            CommandGroup(after: .pasteboard) {
231                Divider()
232                FindMenu(commands: commands)
233            }
234            CommandGroup(after: .textEditing) {
235                Button("Search Notes") { commands.focusSearch = true }
236                    .keyboardShortcut("f", modifiers: [.command, .shift])
237            }
238            CommandGroup(before: .windowList) {
239                AgendaMenuItem()
240            }
241            CommandGroup(after: .newItem) {
242                Button("Capture…") { commands.run("app.capture") }
243                    .keyboardShortcut("n", modifiers: [.command, .shift])
244            }
245        }
246        .commands {
247            CommandMenu("Org") {
248                OrgMenuItems(commands: commands)
249            }
250        }
251        .commands {
252            CommandGroup(after: .appSettings) {
253                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
254                    .keyboardShortcut(",", modifiers: [.command, .option])
255            }
256        }
257        Settings {
258            SettingsView(commands: commands, workspace: try? workspace.get())
259        }
260    }
261}
262
263/// The Org menu: every org command, with the keys that run it in the current keymap.
264struct OrgMenuItems: View {
265    let commands: AppCommands
266
267    var body: some View {
268        ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
269            Button {
270                commands.editor?.run(command.id)
271            } label: {
272                Text(command.title)
273                if let keys = commands.keyLabel(for: command.id) { Text(keys) }
274            }
275            .disabled(commands.editor == nil)
276        }
277    }
278}
279
280/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
281struct MarkupToggle: View {
282    @AppStorage("showMarkup") private var showMarkup = false
283    @AppStorage("showLineNumbers") private var showLineNumbers = true
284
285    var body: some View {
286        Toggle("Show Markup", isOn: $showMarkup)
287            .keyboardShortcut("m", modifiers: [.command, .shift])
288        Toggle("Show Line Numbers", isOn: $showLineNumbers)
289            .keyboardShortcut("l", modifiers: [.command, .shift])
290    }
291}
292
293/// Edit ▸ Find: the editor's find bar.
294struct FindMenu: View {
295    let commands: AppCommands
296
297    var body: some View {
298        Menu("Find") {
299            item("Find…", "edit.find", "f")
300            item("Find and Replace…", "edit.replace", "f", [.command, .option])
301            item("Find Next", "edit.find-next", "g")
302            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
303            item("Use Selection for Find", "edit.use-selection-for-find", "e")
304        }
305    }
306
307    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
308        Button(title) { commands.editor?.run(id) }
309            .keyboardShortcut(key, modifiers: modifiers)
310            .disabled(commands.editor == nil)
311    }
312}
313
314/// Window ▸ Agenda.
315struct AgendaMenuItem: View {
316    @Environment(\.openWindow) private var openWindow
317
318    var body: some View {
319        Button("Agenda") { openWindow(id: "agenda") }
320            .keyboardShortcut("a", modifiers: [.command, .shift])
321        Button("Board") { openWindow(id: "board") }
322            .keyboardShortcut("b", modifiers: [.command, .shift])
323    }
324}
325
326struct SettingsView: View {
327    let commands: AppCommands
328    let workspace: WorkspaceModel?
329    @State private var importing = false
330    @Environment(\.openWindow) private var openWindow
331    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
332    @AppStorage("keymap") private var preset = KeymapPreset.emacs
333    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
334    @AppStorage("tagsColumn") private var tagsColumn = -77
335    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
336    @AppStorage("splitLine") private var splitLine = false
337    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
338    @AppStorage("fillColumn") private var fillColumn = 80
339    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
340    @AppStorage("prettyEntities") private var prettyEntities = true
341    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
342    @AppStorage("agendaSpan") private var agendaSpan = 10
343    @AppStorage("agendaStartOffset") private var agendaStartOffset = -3
344    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
345    @AppStorage("reminders") private var reminders = true
346    @AppStorage("reminderLead") private var reminderLead = 12
347    @AppStorage("globalCapture") private var globalCapture = true
348    @AppStorage("settingsTab") private var tab = "general"
349    @AppStorage("themeFont") private var themeFont = ""
350    @AppStorage("themeFontSize") private var themeFontSize = 13
351    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
352    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
353
354    /// Installed monospaced font families.
355    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
356        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
357    }
358
359    var body: some View {
360        TabView(selection: $tab) {
361            Tab("General", systemImage: "gearshape", value: "general") { general }
362            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
363            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
364            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
365            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
366        }
367        .frame(width: 600)
368    }
369
370    private func editConfig() {
371        ConfigSync.shared.start()
372        openWindow(id: "main")
373        commands.jump(path: UserConfig.configFile.path, offset: 0)
374    }
375
376    private var general: some View {
377        Form {
378            Section {
379                LabeledContent("config.toml") {
380                    HStack {
381                        Button("Edit in Orgstar") { editConfig() }
382                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
383                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
384                    }
385                }
386                LabeledContent("Emacs") {
387                    Button("Import from Emacs…") { importing = true }
388                }
389            } footer: {
390                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.")
391                    .settingsFooter()
392            }
393            Section {
394                Picker("Save files", selection: $saveMode) {
395                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
396                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
397                }
398                .pickerStyle(.radioGroup)
399            }
400            Section {
401                Picker("Keys", selection: $preset) {
402                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
403                }
404                Picker("Option as Meta", selection: $optionAsMeta) {
405                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
406                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
407                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
408                    Text("Neither").tag(0)
409                }
410            } footer: {
411                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
412                    .settingsFooter()
413            }
414        }
415        .formStyle(.grouped)
416        .frame(height: 330)
417        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
418    }
419
420    private var editing: some View {
421        Form {
422            Section {
423                Picker("Tags", selection: $tagsColumn) {
424                    Text("Aligned to end at column 77").tag(-77)
425                    Text("One space after the title").tag(0)
426                }
427                Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
428                Toggle("M-RET splits the line at the caret", isOn: $splitLine)
429                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
430                Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
431            }
432            Section {
433                Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
434                Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
435            } footer: {
436                Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
437                    .settingsFooter()
438            }
439            Section {
440                TextField("Default TODO keywords", text: $todoKeywords)
441            } footer: {
442                Text("For files without #+TODO, in #+TODO syntax. Takes effect when Orgstar restarts.")
443                    .settingsFooter()
444            }
445        }
446        .formStyle(.grouped)
447        .frame(height: 450)
448    }
449
450    private var appearance: some View {
451        Form {
452            Section {
453                Picker("Font", selection: $themeFont) {
454                    Text("System monospaced").tag("")
455                    Divider()
456                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
457                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
458                }
459                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
460                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
461                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
462            } footer: {
463                Text("Tags and tables line up in columns, so a monospaced font keeps them straight.")
464                    .settingsFooter()
465            }
466            Section {
467                LabeledContent("Colors") {
468                    HStack {
469                        Button("Edit in config.toml") { editConfig() }
470                        Button("Show Default Theme") {
471                            openWindow(id: "main")
472                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
473                        }
474                    }
475                }
476            } footer: {
477                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.")
478                    .settingsFooter()
479            }
480        }
481        .formStyle(.grouped)
482        .frame(height: 380)
483    }
484
485    private var agenda: some View {
486        Form {
487            Section {
488                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...31)
489                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
490                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
491            }
492            Section {
493                Toggle("Notify before timed agenda entries", isOn: $reminders)
494                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
495                    .disabled(!reminders)
496            } footer: {
497                Text("An entry's APPT_WARNTIME property overrides the lead time.")
498                    .settingsFooter()
499            }
500        }
501        .formStyle(.grouped)
502        .frame(height: 290)
503    }
504
505    private var capture: some View {
506        Form {
507            Section {
508                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
509            } footer: {
510                Text("Templates go in \(CaptureTemplates.userFile.path).")
511                    .settingsFooter()
512            }
513        }
514        .formStyle(.grouped)
515        .frame(height: 160)
516    }
517}
518
519private extension Text {
520    func settingsFooter() -> some View {
521        font(.caption)
522            .foregroundStyle(.secondary)
523            .textSelection(.enabled)
524            .frame(maxWidth: .infinity, alignment: .leading)
525    }
526}