Sources/Orgstar/OrgstarApp.swift

bd76bdbef02dcaa96435b05ce2586c024c56b478
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

523 lines · 21923 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                    .onAppear {
165                        delegate.session = session
166                        delegate.commands = commands
167                    }
168            case .failure(let error):
169                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
170            }
171        }
172        .defaultSize(width: 1280, height: 860)
173        Window("Agenda", id: "agenda") {
174            if case .success(let model) = workspace {
175                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler)
176            }
177        }
178        .defaultSize(width: 760, height: 720)
179        Window("Board", id: "board") {
180            if case .success(let model) = workspace {
181                BoardView(workspace: model, session: session, commands: commands)
182            }
183        }
184        .defaultSize(width: 1100, height: 700)
185        Window("Clock Report", id: "clock-report") {
186            if case .success(let model) = workspace {
187                ClockReportView(workspace: model)
188            }
189        }
190        .defaultSize(width: 860, height: 560)
191        Window("Capture", id: "capture") {
192            if case .success(let model) = workspace {
193                CaptureView(workspace: model, session: session, commands: commands)
194            }
195        }
196        .windowResizability(.contentSize)
197        .windowLevel(.floating)
198        .commands {
199            CommandGroup(after: .newItem) {
200                Button("Add Folder…") { commands.showingFolderPicker = true }
201                    .keyboardShortcut("o", modifiers: [.command, .shift])
202                Button("Quick Open…") { commands.showingQuickOpen = true }
203                    .keyboardShortcut("p")
204                Button("Command Palette…") { commands.showingPalette = true }
205                    .keyboardShortcut("p", modifiers: [.command, .shift])
206            }
207            CommandGroup(after: .saveItem) {
208                Menu("Export") {
209                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
210                        Button(command.title) { commands.run(command.id) }
211                    }
212                }
213                .disabled(session.path == nil)
214            }
215            CommandGroup(replacing: .saveItem) {
216                Button("Save") {
217                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
218                }
219                .keyboardShortcut("s")
220                .disabled(session.path == nil || session.isReadOnly)
221            }
222            CommandGroup(after: .sidebar) {
223                Button("Show or Hide Outline") { commands.run("app.toggle-outline") }
224                    .keyboardShortcut("o", modifiers: [.command, .option])
225                MarkupToggle()
226            }
227            CommandGroup(after: .pasteboard) {
228                Divider()
229                FindMenu(commands: commands)
230            }
231            CommandGroup(after: .textEditing) {
232                Button("Search Notes") { commands.focusSearch = true }
233                    .keyboardShortcut("f", modifiers: [.command, .shift])
234            }
235            CommandGroup(before: .windowList) {
236                AgendaMenuItem()
237            }
238            CommandGroup(after: .newItem) {
239                Button("Capture…") { commands.run("app.capture") }
240                    .keyboardShortcut("n", modifiers: [.command, .shift])
241            }
242        }
243        .commands {
244            CommandMenu("Org") {
245                OrgMenuItems(commands: commands)
246            }
247        }
248        .commands {
249            CommandGroup(after: .appSettings) {
250                Button("Edit Config File") { commands.jump(path: UserConfig.configFile.path, offset: 0) }
251                    .keyboardShortcut(",", modifiers: [.command, .option])
252            }
253        }
254        Settings {
255            SettingsView(commands: commands, workspace: try? workspace.get())
256        }
257    }
258}
259
260/// The Org menu: every org command, with the keys that run it in the current keymap.
261struct OrgMenuItems: View {
262    let commands: AppCommands
263
264    var body: some View {
265        ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
266            Button {
267                commands.editor?.run(command.id)
268            } label: {
269                Text(command.title)
270                if let keys = commands.keyLabel(for: command.id) { Text(keys) }
271            }
272            .disabled(commands.editor == nil)
273        }
274    }
275}
276
277/// View ▸ Show Markup (link brackets and targets, emphasis markers) and Show Line Numbers.
278struct MarkupToggle: View {
279    @AppStorage("showMarkup") private var showMarkup = false
280    @AppStorage("showLineNumbers") private var showLineNumbers = true
281
282    var body: some View {
283        Toggle("Show Markup", isOn: $showMarkup)
284            .keyboardShortcut("m", modifiers: [.command, .shift])
285        Toggle("Show Line Numbers", isOn: $showLineNumbers)
286            .keyboardShortcut("l", modifiers: [.command, .shift])
287    }
288}
289
290/// Edit ▸ Find: the editor's find bar.
291struct FindMenu: View {
292    let commands: AppCommands
293
294    var body: some View {
295        Menu("Find") {
296            item("Find…", "edit.find", "f")
297            item("Find and Replace…", "edit.replace", "f", [.command, .option])
298            item("Find Next", "edit.find-next", "g")
299            item("Find Previous", "edit.find-previous", "g", [.command, .shift])
300            item("Use Selection for Find", "edit.use-selection-for-find", "e")
301        }
302    }
303
304    private func item(_ title: String, _ id: String, _ key: KeyEquivalent, _ modifiers: EventModifiers = .command) -> some View {
305        Button(title) { commands.editor?.run(id) }
306            .keyboardShortcut(key, modifiers: modifiers)
307            .disabled(commands.editor == nil)
308    }
309}
310
311/// Window ▸ Agenda.
312struct AgendaMenuItem: View {
313    @Environment(\.openWindow) private var openWindow
314
315    var body: some View {
316        Button("Agenda") { openWindow(id: "agenda") }
317            .keyboardShortcut("a", modifiers: [.command, .shift])
318        Button("Board") { openWindow(id: "board") }
319            .keyboardShortcut("b", modifiers: [.command, .shift])
320    }
321}
322
323struct SettingsView: View {
324    let commands: AppCommands
325    let workspace: WorkspaceModel?
326    @State private var importing = false
327    @Environment(\.openWindow) private var openWindow
328    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
329    @AppStorage("keymap") private var preset = KeymapPreset.emacs
330    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
331    @AppStorage("tagsColumn") private var tagsColumn = -77
332    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
333    @AppStorage("splitLine") private var splitLine = false
334    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
335    @AppStorage("fillColumn") private var fillColumn = 80
336    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
337    @AppStorage("prettyEntities") private var prettyEntities = true
338    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
339    @AppStorage("agendaSpan") private var agendaSpan = 10
340    @AppStorage("agendaStartOffset") private var agendaStartOffset = -3
341    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
342    @AppStorage("reminders") private var reminders = true
343    @AppStorage("reminderLead") private var reminderLead = 12
344    @AppStorage("globalCapture") private var globalCapture = true
345    @AppStorage("settingsTab") private var tab = "general"
346    @AppStorage("themeFont") private var themeFont = ""
347    @AppStorage("themeFontSize") private var themeFontSize = 13
348    @AppStorage("themeLineSpacing") private var themeLineSpacing = 2
349    @AppStorage("themeHeadingStep") private var themeHeadingStep = 1
350
351    /// Installed monospaced font families.
352    private static let monospacedFamilies: [String] = NSFontManager.shared.availableFontFamilies.filter { family in
353        NSFontManager.shared.font(withFamily: family, traits: [], weight: 5, size: 13)?.isFixedPitch == true
354    }
355
356    var body: some View {
357        TabView(selection: $tab) {
358            Tab("General", systemImage: "gearshape", value: "general") { general }
359            Tab("Editing", systemImage: "text.alignleft", value: "editing") { editing }
360            Tab("Appearance", systemImage: "paintpalette", value: "appearance") { appearance }
361            Tab("Agenda", systemImage: "calendar", value: "agenda") { agenda }
362            Tab("Capture", systemImage: "tray.and.arrow.down", value: "capture") { capture }
363        }
364        .frame(width: 600)
365    }
366
367    private func editConfig() {
368        ConfigSync.shared.start()
369        openWindow(id: "main")
370        commands.jump(path: UserConfig.configFile.path, offset: 0)
371    }
372
373    private var general: some View {
374        Form {
375            Section {
376                LabeledContent("config.toml") {
377                    HStack {
378                        Button("Edit in Orgstar") { editConfig() }
379                        Button("Open with Default App") { NSWorkspace.shared.open(UserConfig.configFile) }
380                        Button("Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([UserConfig.configFile]) }
381                    }
382                }
383                LabeledContent("Emacs") {
384                    Button("Import from Emacs…") { importing = true }
385                }
386            } footer: {
387                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.")
388                    .settingsFooter()
389            }
390            Section {
391                Picker("Save files", selection: $saveMode) {
392                    Text("Automatically, when typing stops").tag(SaveMode.automatic)
393                    Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
394                }
395                .pickerStyle(.radioGroup)
396            }
397            Section {
398                Picker("Keys", selection: $preset) {
399                    ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
400                }
401                Picker("Option as Meta", selection: $optionAsMeta) {
402                    Text("Left Option").tag(OptionAsMeta.left.rawValue)
403                    Text("Right Option").tag(OptionAsMeta.right.rawValue)
404                    Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
405                    Text("Neither").tag(0)
406                }
407            } footer: {
408                Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
409                    .settingsFooter()
410            }
411        }
412        .formStyle(.grouped)
413        .frame(height: 330)
414        .sheet(isPresented: $importing) { EmacsImportView(workspace: workspace) }
415    }
416
417    private var editing: some View {
418        Form {
419            Section {
420                Picker("Tags", selection: $tagsColumn) {
421                    Text("Aligned to end at column 77").tag(-77)
422                    Text("One space after the title").tag(0)
423                }
424                Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
425                Toggle("M-RET splits the line at the caret", isOn: $splitLine)
426                Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
427                Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
428            }
429            Section {
430                Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
431                Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
432            } footer: {
433                Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
434                    .settingsFooter()
435            }
436            Section {
437                TextField("Default TODO keywords", text: $todoKeywords)
438            } footer: {
439                Text("For files without #+TODO, in #+TODO syntax. Takes effect when Orgstar restarts.")
440                    .settingsFooter()
441            }
442        }
443        .formStyle(.grouped)
444        .frame(height: 450)
445    }
446
447    private var appearance: some View {
448        Form {
449            Section {
450                Picker("Font", selection: $themeFont) {
451                    Text("System monospaced").tag("")
452                    Divider()
453                    ForEach(Self.monospacedFamilies, id: \.self) { Text($0).tag($0) }
454                    if !themeFont.isEmpty, !Self.monospacedFamilies.contains(themeFont) { Text(themeFont).tag(themeFont) }
455                }
456                Stepper("Size: \(themeFontSize) pt", value: $themeFontSize, in: 8...36)
457                Stepper("Line spacing: \(themeLineSpacing) pt", value: $themeLineSpacing, in: 0...16)
458                Stepper("Headings grow by \(themeHeadingStep) pt a level", value: $themeHeadingStep, in: 0...8)
459            } footer: {
460                Text("Tags and tables line up in columns, so a monospaced font keeps them straight.")
461                    .settingsFooter()
462            }
463            Section {
464                LabeledContent("Colors") {
465                    HStack {
466                        Button("Edit in config.toml") { editConfig() }
467                        Button("Show Default Theme") {
468                            openWindow(id: "main")
469                            commands.jump(path: UserConfig.directory.appendingPathComponent("default-theme.toml").path, offset: 0)
470                        }
471                    }
472                }
473            } footer: {
474                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.")
475                    .settingsFooter()
476            }
477        }
478        .formStyle(.grouped)
479        .frame(height: 380)
480    }
481
482    private var agenda: some View {
483        Form {
484            Section {
485                Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...31)
486                Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
487                Toggle("Include files in subfolders", isOn: $agendaSubfolders)
488            }
489            Section {
490                Toggle("Notify before timed agenda entries", isOn: $reminders)
491                Stepper("\(reminderLead) minutes before", value: $reminderLead, in: 0...120)
492                    .disabled(!reminders)
493            } footer: {
494                Text("An entry's APPT_WARNTIME property overrides the lead time.")
495                    .settingsFooter()
496            }
497        }
498        .formStyle(.grouped)
499        .frame(height: 290)
500    }
501
502    private var capture: some View {
503        Form {
504            Section {
505                Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
506            } footer: {
507                Text("Templates go in \(CaptureTemplates.userFile.path).")
508                    .settingsFooter()
509            }
510        }
511        .formStyle(.grouped)
512        .frame(height: 160)
513    }
514}
515
516private extension Text {
517    func settingsFooter() -> some View {
518        font(.caption)
519            .foregroundStyle(.secondary)
520            .textSelection(.enabled)
521            .frame(maxWidth: .infinity, alignment: .leading)
522    }
523}