Sources/Orgstar/OrgstarApp.swift

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

319 lines · 13791 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    var keyHints: [KeyHint] = []
 25    /// A question a command asked, answered in the echo area.
 26    private(set) var prompt: PromptRequest?
 27    /// The last message from a command or the keymap, cleared after a few seconds.
 28    private(set) var message: String?
 29    private var messageID = 0
 30
 31    func ask(_ prompt: Prompt, reply: @escaping (String?) -> Void) {
 32        self.prompt = PromptRequest(prompt: prompt, reply: reply)
 33    }
 34
 35    /// Ends the prompt with an answer, or nil to cancel, and gives the editor the keys back.
 36    func answer(_ text: String?) {
 37        guard let request = prompt else { return }
 38        prompt = nil
 39        if let textView = editor?.textView { textView.window?.makeFirstResponder(textView) }
 40        request.reply(text)
 41    }
 42
 43    /// An app command from a menu, run by the main window.
 44    private(set) var runRequest: (id: String, serial: Int)?
 45    private var runSerial = 0
 46
 47    func run(_ id: String) {
 48        runSerial += 1
 49        runRequest = (id, runSerial)
 50    }
 51
 52    func jump(path: String, offset: Int) {
 53        jumpID += 1
 54        jumpRequest = (path, offset, jumpID)
 55    }
 56
 57    func show(_ text: String) {
 58        messageID += 1
 59        let id = messageID
 60        message = text
 61        Task {
 62            try? await Task.sleep(for: .seconds(4))
 63            if messageID == id { message = nil }
 64        }
 65    }
 66}
 67
 68struct PromptRequest: Identifiable {
 69    let id = UUID()
 70    let prompt: Prompt
 71    let reply: (String?) -> Void
 72}
 73
 74@MainActor
 75final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate {
 76    var session: DocumentSession?
 77    var commands: AppCommands?
 78
 79    func applicationDidFinishLaunching(_ notification: Notification) {
 80        if SystemReminderCenter.isAvailable { UNUserNotificationCenter.current().delegate = self }
 81    }
 82
 83    /// Reminders show while Orgstar is in front too.
 84    nonisolated func userNotificationCenter(
 85        _ center: UNUserNotificationCenter, willPresent notification: UNNotification
 86    ) async -> UNNotificationPresentationOptions {
 87        [.banner, .sound, .list]
 88    }
 89
 90    /// Clicking a reminder shows its entry.
 91    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
 92        let info = response.notification.request.content.userInfo
 93        guard let path = info["path"] as? String, let offset = info["offset"] as? Int else { return }
 94        await MainActor.run {
 95            NSApp.activate()
 96            commands?.jump(path: path, offset: offset)
 97        }
 98    }
 99
100    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true }
101
102    func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply {
103        guard let session else { return .terminateNow }
104        return UnsavedChanges.resolve(session) ? .terminateNow : .terminateCancel
105    }
106}
107
108/// Unsaved edits when leaving a file or quitting.
109@MainActor
110enum UnsavedChanges {
111    /// Whether the open file can be left: saved in automatic mode, or as the user chooses in
112    /// explicit mode. A save that fails or conflicts keeps the file open.
113    static func resolve(_ session: DocumentSession) -> Bool {
114        guard session.isDirty else { return true }
115        if session.saveMode == .automatic { return session.save() }
116        let alert = NSAlert()
117        alert.messageText = "Save changes to \(session.path.map { ($0 as NSString).lastPathComponent } ?? "this file")?"
118        alert.informativeText = "Your changes will be lost if you don't save them."
119        alert.addButton(withTitle: "Save")
120        alert.addButton(withTitle: "Don't Save")
121        alert.addButton(withTitle: "Cancel")
122        switch alert.runModal() {
123        case .alertFirstButtonReturn: return session.save()
124        case .alertSecondButtonReturn: return true
125        default: return false
126        }
127    }
128}
129
130@main
131struct OrgstarApp: App {
132    @NSApplicationDelegateAdaptor private var delegate: AppDelegate
133    @State private var workspace = Result {
134        try WorkspaceModel(directory: WorkspaceModel.defaultDirectory, settings: .with(todoKeywords: Preferences.orgSettings))
135    }
136    @State private var commands = AppCommands()
137    @State private var clock = ClockModel()
138    @State private var scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
139    @State private var session: DocumentSession = {
140        let session = DocumentSession()
141        session.defaults = Preferences.orgSettings
142        return session
143    }()
144
145    var body: some Scene {
146        Window("Orgstar", id: "main") {
147            switch workspace {
148            case .success(let model):
149                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler, clock: clock)
150                    .onAppear {
151                        delegate.session = session
152                        delegate.commands = commands
153                    }
154            case .failure(let error):
155                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
156            }
157        }
158        .defaultSize(width: 1280, height: 860)
159        Window("Agenda", id: "agenda") {
160            if case .success(let model) = workspace {
161                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler)
162            }
163        }
164        .defaultSize(width: 760, height: 720)
165        Window("Board", id: "board") {
166            if case .success(let model) = workspace {
167                BoardView(workspace: model, session: session, commands: commands)
168            }
169        }
170        .defaultSize(width: 1100, height: 700)
171        Window("Clock Report", id: "clock-report") {
172            if case .success(let model) = workspace {
173                ClockReportView(workspace: model)
174            }
175        }
176        .defaultSize(width: 860, height: 560)
177        Window("Capture", id: "capture") {
178            if case .success(let model) = workspace {
179                CaptureView(workspace: model, session: session, commands: commands)
180            }
181        }
182        .windowResizability(.contentSize)
183        .windowLevel(.floating)
184        .commands {
185            CommandGroup(after: .newItem) {
186                Button("Add Folder…") { commands.showingFolderPicker = true }
187                    .keyboardShortcut("o", modifiers: [.command, .shift])
188                Button("Quick Open…") { commands.showingQuickOpen = true }
189                    .keyboardShortcut("p")
190                Button("Command Palette…") { commands.showingPalette = true }
191                    .keyboardShortcut("p", modifiers: [.command, .shift])
192            }
193            CommandGroup(after: .saveItem) {
194                Menu("Export") {
195                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
196                        Button(command.title) { commands.run(command.id) }
197                    }
198                }
199                .disabled(session.path == nil)
200            }
201            CommandGroup(replacing: .saveItem) {
202                Button("Save") {
203                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
204                }
205                .keyboardShortcut("s")
206                .disabled(session.path == nil || session.isReadOnly)
207            }
208            CommandGroup(after: .textEditing) {
209                Button("Search Notes") { commands.focusSearch = true }
210                    .keyboardShortcut("f", modifiers: [.command, .shift])
211            }
212            CommandGroup(before: .windowList) {
213                AgendaMenuItem()
214            }
215            CommandGroup(after: .newItem) {
216                Button("Capture…") { commands.run("app.capture") }
217                    .keyboardShortcut("n", modifiers: [.command, .shift])
218            }
219        }
220        .commands {
221            CommandMenu("Org") {
222                ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
223                    Button(command.title) { commands.editor?.run(command.id) }
224                        .disabled(commands.editor == nil)
225                }
226            }
227        }
228        Settings {
229            SettingsView()
230        }
231    }
232}
233
234/// Window ▸ Agenda.
235struct AgendaMenuItem: View {
236    @Environment(\.openWindow) private var openWindow
237
238    var body: some View {
239        Button("Agenda") { openWindow(id: "agenda") }
240            .keyboardShortcut("a", modifiers: [.command, .shift])
241        Button("Board") { openWindow(id: "board") }
242            .keyboardShortcut("b", modifiers: [.command, .shift])
243    }
244}
245
246struct SettingsView: View {
247    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
248    @AppStorage("keymap") private var preset = KeymapPreset.emacs
249    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
250    @AppStorage("tagsColumn") private var tagsColumn = -77
251    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
252    @AppStorage("splitLine") private var splitLine = false
253    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
254    @AppStorage("fillColumn") private var fillColumn = 80
255    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
256    @AppStorage("prettyEntities") private var prettyEntities = true
257    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
258    @AppStorage("agendaSpan") private var agendaSpan = 10
259    @AppStorage("agendaStartOffset") private var agendaStartOffset = -3
260    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
261    @AppStorage("reminders") private var reminders = true
262    @AppStorage("reminderLead") private var reminderLead = 12
263    @AppStorage("globalCapture") private var globalCapture = true
264
265    var body: some View {
266        Form {
267            Picker("Save files:", selection: $saveMode) {
268                Text("Automatically, when typing stops").tag(SaveMode.automatic)
269                Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
270            }
271            .pickerStyle(.radioGroup)
272            Picker("Keys:", selection: $preset) {
273                ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
274            }
275            Picker("Option as Meta:", selection: $optionAsMeta) {
276                Text("Left Option").tag(OptionAsMeta.left.rawValue)
277                Text("Right Option").tag(OptionAsMeta.right.rawValue)
278                Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
279                Text("Neither").tag(0)
280            }
281            Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
282                .font(.caption)
283                .foregroundStyle(.secondary)
284                .textSelection(.enabled)
285            Divider()
286            Picker("Tags:", selection: $tagsColumn) {
287                Text("Aligned to end at column 77").tag(-77)
288                Text("One space after the title").tag(0)
289            }
290            Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
291            Toggle("M-RET splits the line at the caret", isOn: $splitLine)
292            Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
293            Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
294            Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
295            Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
296            Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
297                .font(.caption)
298                .foregroundStyle(.secondary)
299            TextField("Default TODO keywords:", text: $todoKeywords)
300            Text("For files without #+TODO, in #+TODO syntax. Takes effect when Orgstar restarts.")
301                .font(.caption)
302                .foregroundStyle(.secondary)
303            Divider()
304            Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...31)
305            Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
306            Toggle("Agenda includes files in subfolders", isOn: $agendaSubfolders)
307            Toggle("Notify before timed agenda entries", isOn: $reminders)
308            Stepper("\(reminderLead) minutes before (APPT_WARNTIME overrides)", value: $reminderLead, in: 0...120)
309                .disabled(!reminders)
310            Toggle("⌃⌥Space opens Capture from any app", isOn: $globalCapture)
311            Text("Templates go in \(CaptureTemplates.userFile.path).")
312                .font(.caption)
313                .foregroundStyle(.secondary)
314                .textSelection(.enabled)
315        }
316        .padding(20)
317        .frame(width: 480)
318    }
319}