Sources/Orgstar/OrgstarApp.swift

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

287 lines · 12324 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 scheduler = SystemReminderCenter.isAvailable ? ReminderScheduler(center: SystemReminderCenter()) : nil
138    @State private var session: DocumentSession = {
139        let session = DocumentSession()
140        session.defaults = Preferences.orgSettings
141        return session
142    }()
143
144    var body: some Scene {
145        Window("Orgstar", id: "main") {
146            switch workspace {
147            case .success(let model):
148                ContentView(workspace: model, session: session, commands: commands, scheduler: scheduler)
149                    .onAppear {
150                        delegate.session = session
151                        delegate.commands = commands
152                    }
153            case .failure(let error):
154                ContentUnavailableView("Can't open the index", systemImage: "exclamationmark.triangle", description: Text(error.localizedDescription))
155            }
156        }
157        .defaultSize(width: 1280, height: 860)
158        Window("Agenda", id: "agenda") {
159            if case .success(let model) = workspace {
160                AgendaView(workspace: model, session: session, commands: commands, scheduler: scheduler)
161            }
162        }
163        .defaultSize(width: 760, height: 720)
164        .commands {
165            CommandGroup(after: .newItem) {
166                Button("Add Folder…") { commands.showingFolderPicker = true }
167                    .keyboardShortcut("o", modifiers: [.command, .shift])
168                Button("Quick Open…") { commands.showingQuickOpen = true }
169                    .keyboardShortcut("p")
170                Button("Command Palette…") { commands.showingPalette = true }
171                    .keyboardShortcut("p", modifiers: [.command, .shift])
172            }
173            CommandGroup(after: .saveItem) {
174                Menu("Export") {
175                    ForEach(EditorCommands.all.filter { $0.id.hasPrefix("app.export.") }, id: \.id) { command in
176                        Button(command.title) { commands.run(command.id) }
177                    }
178                }
179                .disabled(session.path == nil)
180            }
181            CommandGroup(replacing: .saveItem) {
182                Button("Save") {
183                    if !session.save(), session.conflict != nil { commands.showingConflict = true }
184                }
185                .keyboardShortcut("s")
186                .disabled(session.path == nil || session.isReadOnly)
187            }
188            CommandGroup(after: .textEditing) {
189                Button("Search Notes") { commands.focusSearch = true }
190                    .keyboardShortcut("f", modifiers: [.command, .shift])
191            }
192            CommandGroup(before: .windowList) {
193                AgendaMenuItem()
194            }
195        }
196        .commands {
197            CommandMenu("Org") {
198                ForEach(EditorCommands.all.filter { $0.id.hasPrefix("org.") }, id: \.id) { command in
199                    Button(command.title) { commands.editor?.run(command.id) }
200                        .disabled(commands.editor == nil)
201                }
202            }
203        }
204        Settings {
205            SettingsView()
206        }
207    }
208}
209
210/// Window ▸ Agenda.
211struct AgendaMenuItem: View {
212    @Environment(\.openWindow) private var openWindow
213
214    var body: some View {
215        Button("Agenda") { openWindow(id: "agenda") }
216            .keyboardShortcut("a", modifiers: [.command, .shift])
217    }
218}
219
220struct SettingsView: View {
221    @AppStorage("saveMode") private var saveMode = SaveMode.automatic
222    @AppStorage("keymap") private var preset = KeymapPreset.emacs
223    @AppStorage("optionAsMeta") private var optionAsMeta = OptionAsMeta.left.rawValue
224    @AppStorage("tagsColumn") private var tagsColumn = -77
225    @AppStorage("headingAfterSubtree") private var headingAfterSubtree = true
226    @AppStorage("splitLine") private var splitLine = false
227    @AppStorage("alphabeticalLists") private var alphabeticalLists = true
228    @AppStorage("fillColumn") private var fillColumn = 80
229    @AppStorage("hiddenMarkers") private var hiddenMarkers = true
230    @AppStorage("prettyEntities") private var prettyEntities = true
231    @AppStorage("todoKeywords") private var todoKeywords = Preferences.defaultTodoKeywords
232    @AppStorage("agendaSpan") private var agendaSpan = 10
233    @AppStorage("agendaStartOffset") private var agendaStartOffset = -3
234    @AppStorage("agendaSubfolders") private var agendaSubfolders = false
235    @AppStorage("reminders") private var reminders = true
236    @AppStorage("reminderLead") private var reminderLead = 12
237
238    var body: some View {
239        Form {
240            Picker("Save files:", selection: $saveMode) {
241                Text("Automatically, when typing stops").tag(SaveMode.automatic)
242                Text("Only with File ▸ Save (⌘S)").tag(SaveMode.explicit)
243            }
244            .pickerStyle(.radioGroup)
245            Picker("Keys:", selection: $preset) {
246                ForEach(KeymapPreset.allCases, id: \.self) { Text($0.title).tag($0) }
247            }
248            Picker("Option as Meta:", selection: $optionAsMeta) {
249                Text("Left Option").tag(OptionAsMeta.left.rawValue)
250                Text("Right Option").tag(OptionAsMeta.right.rawValue)
251                Text("Both").tag(OptionAsMeta([.left, .right]).rawValue)
252                Text("Neither").tag(0)
253            }
254            Text("Your own bindings go in \(KeymapLoader.userFile.path), on top of the preset.")
255                .font(.caption)
256                .foregroundStyle(.secondary)
257                .textSelection(.enabled)
258            Divider()
259            Picker("Tags:", selection: $tagsColumn) {
260                Text("Aligned to end at column 77").tag(-77)
261                Text("One space after the title").tag(0)
262            }
263            Toggle("M-RET adds the new heading after the subtree", isOn: $headingAfterSubtree)
264            Toggle("M-RET splits the line at the caret", isOn: $splitLine)
265            Toggle("Lists can use letters (a. b. c.)", isOn: $alphabeticalLists)
266            Stepper("M-q fills to column \(fillColumn)", value: $fillColumn, in: 40...200)
267            Toggle("Emacs hides emphasis markers (org-hide-emphasis-markers)", isOn: $hiddenMarkers)
268            Toggle("Emacs shows entities as characters (org-pretty-entities)", isOn: $prettyEntities)
269            Text("Tags, tables and M-q measure text as your Emacs displays it, so both write the same file.")
270                .font(.caption)
271                .foregroundStyle(.secondary)
272            TextField("Default TODO keywords:", text: $todoKeywords)
273            Text("For files without #+TODO, in #+TODO syntax. Takes effect when Orgstar restarts.")
274                .font(.caption)
275                .foregroundStyle(.secondary)
276            Divider()
277            Stepper("Agenda shows \(agendaSpan) days", value: $agendaSpan, in: 1...31)
278            Stepper(agendaStartOffset == 0 ? "Agenda starts today" : "Agenda starts \(-agendaStartOffset) days before today", value: $agendaStartOffset, in: -14...0)
279            Toggle("Agenda includes files in subfolders", isOn: $agendaSubfolders)
280            Toggle("Notify before timed agenda entries", isOn: $reminders)
281            Stepper("\(reminderLead) minutes before (APPT_WARNTIME overrides)", value: $reminderLead, in: 0...120)
282                .disabled(!reminders)
283        }
284        .padding(20)
285        .frame(width: 480)
286    }
287}