Sources/Orgstar/OrgstarApp.swift

6c2b0142aedbcc4495fceadee8750ecb9a790e34
orgstar/Sources/Orgstar/OrgstarApp.swift history · blame · raw

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