Sources/OrgstarMobile/EditorScreen.swift
1022 lines · 50611 bytes
1#if os(iOS)
2import OrgApp
3import OrgCore
4import OrgDocument
5import PhotosUI
6import QuickLook
7import SwiftUI
8import UIKit
9import UniformTypeIdentifiers
10
11/// Editing a file: the text with Org's folding and styling, a bar of Org keys over the keyboard,
12/// and every command in a palette. The editor is the open file's live state, so autosave and
13/// merging go through the session as on the Mac.
14struct EditorScreen: View {
15 let path: String
16 let offset: Int?
17 let workspace: WorkspaceModel
18 let session: DocumentSession
19 /// The pane this screen shows its file in, from a split; nil makes one for the screen.
20 var givenPane: EditorPane? = nil
21 /// In a split, the focused pane shows the toolbar and the split the title.
22 var inSplit = false
23 var isFocused = true
24 /// Focus came to this screen's pane.
25 var onFocus: () -> Void = {}
26 /// The pane commands (`app.split-right` …), which the split runs.
27 var onPaneCommand: ((String) -> Void)? = nil
28 @State private var editor: MobileEditor?
29 /// This screen's view of the editor.
30 @State private var textView: UITextView?
31 @State private var holder = PaneHolder()
32 @Environment(\.horizontalSizeClass) private var sizeClass
33 @State private var prompt: PromptRequest?
34 @State private var message: String?
35 @State private var sheet: Sheet?
36 @State private var trust = TrustStore()
37 /// The command chosen in the palette, run once the palette is gone.
38 @State private var chosen: String?
39 @Environment(ClockModel.self) private var clock
40 @Environment(MobileModel.self) private var model
41 @Environment(\.openURL) private var openURL
42
43 /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
44 private var editorOptions: EditingOptions {
45 var options = session.options
46 options.filePath = path
47 options.agendaFiles = workspace.agendaFilePaths()
48 options.timer = TimerModel.shared.timer
49 return options
50 }
51
52 struct PromptRequest: Identifiable {
53 let id = UUID()
54 let prompt: Prompt
55 let reply: (String?) -> Void
56 }
57
58 /// One sheet at a time: two presenters on this screen interfere.
59 /// `org-table-import`'s file picker is up.
60 @State private var importingTable = false
61 /// The table at the caret, for `org-table-export`'s save dialog.
62 @State private var exportedTable: TableFile?
63 /// org-attach's file picker is up, for this method.
64 @State private var attaching: Attachments.Method?
65 @State private var attachingPhotos = false
66 @State private var photos: [PhotosPickerItem] = []
67 /// A file shown in Quick Look.
68 @State private var previewed: URL?
69
70 enum Sheet: Identifiable {
71 case palette, conflict, syncCopies, recovery
72 /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
73 case refile(String)
74 case block(BlockEdit)
75 case columns(ColumnView.View)
76 case plot(TablePlot.Plot)
77 case crypt(CryptRequest)
78 case backlinks
79
80 var id: String {
81 switch self {
82 case .palette: "palette"
83 case .refile(let command): command
84 case .conflict: "conflict"
85 case .syncCopies: "syncCopies"
86 case .recovery: "recovery"
87 case .block(let edit): "block \(edit.range)"
88 case .columns: "columns"
89 case .plot: "plot"
90 case .crypt(let request): request.id.uuidString
91 case .backlinks: "backlinks"
92 }
93 }
94 }
95
96 private var pane: EditorPane? { givenPane ?? holder.pane }
97
98 /// The pane commands, as the Mac's View menu has them.
99 static let paneCommands = ["app.split-right", "app.split-below", "app.pane-next", "app.pane-close", "app.pane-only"]
100
101 var body: some View {
102 Group {
103 if let editor, let textView {
104 EditorTextView(editor: editor, view: textView, palette: { sheet = .palette })
105 .ignoresSafeArea(.container, edges: .bottom)
106 } else {
107 ProgressView()
108 }
109 }
110 .modifier(EditorTitle(title: session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""), shown: !inSplit))
111 .toolbar(.hidden, for: .tabBar)
112 .toolbar {
113 if !inSplit || isFocused {
114 ToolbarItemGroup(placement: .primaryAction) {
115 if pane?.conflict != nil {
116 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
117 }
118 Button("Undo", systemImage: "arrow.uturn.backward") { editor?.run("edit.undo") }
119 Menu("More", systemImage: "ellipsis.circle") {
120 Button("Commands", systemImage: "command") { sheet = .palette }
121 Button("Clock In", systemImage: "stopwatch") { editor?.run("app.clock.in") }
122 Button("Column View", systemImage: "tablecells") { editor?.run("org.columns") }
123 Button("Column View of File", systemImage: "tablecells.badge.ellipsis") { editor?.run("org.columns.global") }
124 Menu("Table", systemImage: "tablecells") {
125 Button("Import Table from File…", systemImage: "square.and.arrow.down") { importingTable = true }
126 Button("Export Table as CSV…", systemImage: "square.and.arrow.up") { exportTable(csv: true) }
127 Button("Export Table as TSV…", systemImage: "square.and.arrow.up") { exportTable(csv: false) }
128 Button("Plot Table", systemImage: "chart.xyaxis.line") { plotTable() }
129 }
130 Toggle(isOn: Binding(get: { model.showMarkup }, set: { model.showMarkup = $0 })) {
131 Label("Show Markup", systemImage: "chevron.left.forwardslash.chevron.right")
132 }
133 RecentClockMenu(clock: clock) { editor?.run($0) }
134 Button("Backlinks", systemImage: "arrow.uturn.backward.circle") { sheet = .backlinks }
135 Menu("Daily Notes", systemImage: "calendar") {
136 Button("Today", systemImage: "calendar") { roamActions.run("app.dailies.today") }
137 Button("Yesterday", systemImage: "chevron.backward") { roamActions.run("app.dailies.yesterday") }
138 Button("Tomorrow", systemImage: "chevron.forward") { roamActions.run("app.dailies.tomorrow") }
139 Button("Date…", systemImage: "calendar.badge.clock") { roamActions.run("app.dailies.date") }
140 Button("Capture to Today", systemImage: "square.and.pencil") { roamActions.run("app.dailies.capture-today") }
141 Button("Previous Daily Note", systemImage: "arrow.left") { roamActions.run("app.dailies.previous") }
142 Button("Next Daily Note", systemImage: "arrow.right") { roamActions.run("app.dailies.next") }
143 }
144 Button("Find Node…", systemImage: "point.3.connected.trianglepath.dotted") { roamActions.run("app.node.find") }
145 Button("Insert Node Link…", systemImage: "link") { roamActions.run("app.node.insert") }
146 Menu("Attachments", systemImage: "paperclip") {
147 Button("Attach File…", systemImage: "doc.badge.plus") { attaching = .cp }
148 Button("Attach Photo or Video…", systemImage: "photo.badge.plus") { attachingPhotos = true }
149 Button("Attach File from URL…", systemImage: "link.badge.plus") { attachActions.run("app.attach.url") }
150 Button("New Attachment…", systemImage: "square.and.pencil") { attachActions.run("app.attach.new") }
151 Button("Open Attachment…", systemImage: "paperclip") { attachActions.run("app.attach.open") }
152 Button("Show Attachment Folder", systemImage: "folder") { attachActions.run("app.attach.reveal") }
153 Button("Delete Attachment…", systemImage: "trash") { attachActions.run("app.attach.delete") }
154 Button("Delete All Attachments…", systemImage: "trash.slash") { attachActions.run("app.attach.delete-all") }
155 Button("Sync Attachments", systemImage: "arrow.triangle.2.circlepath") { attachActions.run("app.attach.sync") }
156 Button("Set Attachment Folder…", systemImage: "folder.badge.gearshape") { attachActions.run("app.attach.set-directory") }
157 Button("Unset Attachment Folder", systemImage: "folder.badge.minus") { attachActions.run("app.attach.unset-directory") }
158 }
159 Menu("Encryption", systemImage: "lock") {
160 Button("Encrypt Entry…", systemImage: "lock") { crypt("app.crypt.encrypt-entry") }
161 Button("Decrypt Entry…", systemImage: "lock.open") { crypt("app.crypt.open-entry") }
162 Button("Decrypt Entry in File…", systemImage: "lock.open.trianglebadge.exclamationmark") { crypt("app.crypt.decrypt-entry") }
163 Button("Encrypt Tagged Entries…", systemImage: "lock.rectangle.stack") { crypt("app.crypt.encrypt-entries") }
164 Button("Forget Encryption Passphrase", systemImage: "key.slash") { crypt("app.crypt.forget-passphrase") }
165 }
166 if let text = session.document(of: path)?.text { ExportMenu(path: path, text: text) { message = $0 } }
167 Button("Sync Conflict Copies", systemImage: "doc.on.doc") { sheet = .syncCopies }
168 Button("Recovered Versions", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
169 if onPaneCommand != nil, sizeClass == .regular {
170 Menu("Panes", systemImage: "rectangle.split.2x1") {
171 Button("Split Pane Right", systemImage: "rectangle.split.2x1") { onPaneCommand?("app.split-right") }
172 Button("Split Pane Below", systemImage: "rectangle.split.1x2") { onPaneCommand?("app.split-below") }
173 if inSplit {
174 Button("Next Pane", systemImage: "arrow.right.square") { onPaneCommand?("app.pane-next") }
175 Button("Close Pane", systemImage: "xmark.square") { onPaneCommand?("app.pane-close") }
176 Button("Close Other Panes", systemImage: "square") { onPaneCommand?("app.pane-only") }
177 }
178 }
179 }
180 }
181 }
182 }
183 }
184 .safeAreaInset(edge: .top) {
185 VStack(spacing: 0) {
186 if let timer = TimerModel.shared.timer {
187 TimelineView(.periodic(from: .now, by: 1)) { context in
188 Text(timer.modeLine(now: context.date)).font(.callout.monospacedDigit())
189 }
190 .frame(maxWidth: .infinity).padding(4).background(.bar)
191 }
192 if let message {
193 Text(message).font(.callout).padding(8).frame(maxWidth: .infinity).background(.bar)
194 .onTapGesture { self.message = nil }
195 .task(id: message) {
196 try? await Task.sleep(for: .seconds(4))
197 if self.message == message { self.message = nil }
198 }
199 }
200 }
201 }
202 .sheet(item: $prompt) { request in
203 PromptSheet(prompt: request.prompt) { answer in
204 prompt = nil
205 request.reply(answer)
206 }
207 }
208 .sheet(item: $sheet, onDismiss: {
209 // After the sheet has gone, so a command's own prompt can show.
210 if let id = chosen {
211 chosen = nil
212 editor?.run(id)
213 }
214 }) { sheet in
215 switch sheet {
216 case .palette: if let editor { CommandPalette(editor: editor, panes: onPaneCommand != nil && sizeClass == .regular, split: inSplit) { chosen = $0 } }
217 case .conflict: ConflictSheet(session: session)
218 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
219 case .recovery: RecoverySheet(session: session) { message = $0 }
220 case .refile(let command):
221 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
222 create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
223 self.sheet = nil
224 switch session.createRefileChild(under: parent, title: child) {
225 case .success(let target):
226 guard let path = session.path, let editor else { return }
227 message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
228 case .failure(.message(let text)): message = text
229 }
230 }) { target in
231 self.sheet = nil
232 guard let target else { return }
233 if command == "app.refile.goto" {
234 model.openRequest = .offset(target.path, target.start ?? Int.max)
235 } else {
236 refile(to: target, keep: command == "app.refile.copy")
237 }
238 }
239 case .block(let edit):
240 BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
241 self.sheet = nil
242 if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
243 }
244 case .columns(let view):
245 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
246 case .plot(let plot):
247 PlotScreen(plot: plot)
248 case .crypt(let request):
249 CryptScreen(request: request, session: session, editor: editor) { message = $0 }
250 case .backlinks:
251 BacklinksScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in
252 if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) }
253 }
254 }
255 }
256 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
257 importTable(result)
258 }
259 .background {
260 // A second importer on the same view would replace the first.
261 Color.clear.fileImporter(isPresented: Binding(get: { attaching != nil }, set: { if !$0 { attaching = nil } }),
262 allowedContentTypes: [.item, .folder], allowsMultipleSelection: true) { result in
263 let method = attaching ?? .cp
264 switch result {
265 case .success(let urls): attachActions.attach(urls, method: method)
266 case .failure(let error): message = error.localizedDescription
267 }
268 }
269 }
270 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
271 .onChange(of: photos) { _, items in
272 guard !items.isEmpty else { return }
273 photos = []
274 attachPhotos(items)
275 }
276 .quickLookPreview($previewed)
277 .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
278 document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
279 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
280 if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
281 }
282 .onChange(of: pane?.conflict) { _, conflict in
283 if conflict != nil, isFocused { sheet = .conflict }
284 }
285 .onChange(of: session.lastError) { _, error in
286 if let error { message = error; session.lastError = nil }
287 }
288 .onAppear(perform: start)
289 // A pane command moved focus here.
290 .onChange(of: isFocused) {
291 guard isFocused, let textView, !textView.isFirstResponder else { return }
292 editor?.focus(textView)
293 textView.becomeFirstResponder()
294 }
295 .onChange(of: pane?.revealRequest?.id) {
296 if let offset = pane?.revealRequest?.offset, pane?.path == path { editor?.reveal(offset) }
297 }
298 .onChange(of: model.settingsVersion) {
299 editor?.options = editorOptions
300 editor?.themeSpec = model.theme
301 editor?.keymap = model.keymap
302 editor?.modal = model.modalKeys
303 }
304 .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
305 .onChange(of: TimerModel.shared.timer) { editor?.options = editorOptions }
306 .onDisappear {
307 // Typing the reader shows next, and a save, don't wait for the autosave delay.
308 if session.dirtyPaths.contains(path) { _ = session.save(path) }
309 }
310 }
311
312 /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
313 private func link(_ id: String) {
314 guard let editor else { return }
315 switch id {
316 case "org.link.store":
317 message = StoredLink.add(Links.store(in: editor.editContext(), path: Links.abbreviate(path, home: NSHomeDirectory())), to: &model.storedLinks)
318 case "org.id.store-link":
319 if case .commit = editor.perform(CreateID()),
320 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
321 message = StoredLink.add(link, to: &model.storedLinks)
322 }
323 default:
324 _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
325 }
326 }
327
328 /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
329 private func run(_ job: BabelJob) {
330 let go = {
331 message = "Running \(job.language) block…"
332 session.startBabel(job) { message = $0 }
333 }
334 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
335 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
336 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
337 switch answer {
338 case "always":
339 trust.trust(path: path, content: job.blockText)
340 go()
341 case "yes": go()
342 default: message = "Not run"
343 }
344 }
345 }
346
347 private func start() {
348 let pane: EditorPane
349 if let existing = self.pane {
350 pane = existing
351 } else {
352 pane = session.makePane()
353 holder.pane = pane
354 let store = model.editors, path = path
355 holder.release = { [weak session] in
356 store.release(pane.id, path: path)
357 session?.closePane(pane)
358 }
359 }
360 if pane.path != path { session.open(path, in: pane) }
361 model.editors.prune(session)
362 guard let editor = model.editors.editor(for: path, session: session, make: makeEditor) else { return }
363 let view = model.editors.view(for: pane.id, of: editor)
364 editor.onFocus[ObjectIdentifier(view)] = { [weak session] in
365 session?.focused = pane
366 bind(editor)
367 onFocus()
368 }
369 // A pane a split adds leaves focus where it was, as `split-window` does.
370 if isFocused {
371 session.focused = pane
372 bind(editor)
373 editor.focus(view)
374 }
375 self.editor = editor
376 textView = view
377 if let offset { editor.reveal(offset) }
378 if pane.conflict != nil {
379 sheet = .conflict
380 } else if case let copies = session.syncConflictCopies().count, copies > 0 {
381 message = "\(copies) sync conflict \(copies == 1 ? "copy" : "copies") of this file; More › Sync Conflict Copies compares them."
382 }
383 }
384
385 private func makeEditor() -> MobileEditor? {
386 guard let document = session.document(of: path) else { return nil }
387 return MobileEditor(
388 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
389 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
390 )
391 }
392
393 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
394 private func bind(_ editor: MobileEditor) {
395 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
396 editor.onChange = { [weak session] in session?.bufferChanged(path) }
397 editor.onMessage = { message = $0 }
398 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
399 editor.onLink = { link in follow(link) }
400 editor.onEditBlock = { edit in sheet = .block(edit) }
401 editor.onColumnView = { view in sheet = .columns(view) }
402 editor.onTangle = { scope in message = session.tangle(scope) }
403 editor.onBabel = { job in run(job) }
404 editor.onRefreshSetup = { session.refreshSetup() }
405 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
406 editor.keymap = model.keymap
407 editor.modal = model.modalKeys
408 editor.onAppCommand = { id in
409 if Self.paneCommands.contains(id) {
410 if let onPaneCommand { onPaneCommand(id) } else { message = "Not available here" }
411 } else if id == "app.save" {
412 _ = session.save(path)
413 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
414 sheet = .refile(id)
415 } else if id == "app.table-import" {
416 importingTable = true
417 } else if id == "app.table-export" {
418 exportTable(csv: true)
419 } else if id == "app.plot" {
420 plotTable()
421 } else if id.hasPrefix("app.crypt.") {
422 crypt(id)
423 } else if id.hasPrefix("app.attach.") {
424 attachActions.run(id)
425 } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
426 roamActions.run(id)
427 } else if id == "app.backlinks" {
428 sheet = .backlinks
429 } else if id == "app.toggle-markup" {
430 model.showMarkup.toggle()
431 } else if MobileEditor.linkCommands.contains(id) {
432 link(id)
433 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
434 message = "Not available on iOS yet"
435 }
436 }
437 }
438}
439
440extension EditorScreen {
441 /// Follows a link; files the editor doesn't open show in Quick Look.
442 private func follow(_ link: OrgLink) {
443 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
444 case .shown:
445 // A link to another file shows it on its own screen; this pane keeps its file.
446 guard let pane, let target = pane.path, target != path else { message = nil; return }
447 let caret = session.caret(of: target) ?? 0
448 session.open(path, in: pane)
449 model.openRequest = .offset(target, caret)
450 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
451 case .message(let text): message = text
452 }
453 }
454
455 /// org-roam's daily notes and nodes.
456 private var roamActions: RoamActions {
457 RoamActions(
458 session: session, roots: { workspace.rootPaths },
459 nodes: { workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
460 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
461 open: { file, offset in
462 if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
463 },
464 insertLink: { link, title in
465 guard let editor else { return }
466 let context = editor.editContext()
467 let range = context.selection.first ?? context.caret..<context.caret
468 let selected = (context.text as NSString).substring(with: NSRange(range))
469 let text = Links.makeString(link, selected.isEmpty ? title : selected)
470 let end = range.lowerBound + (text as NSString).length
471 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
472 },
473 refresh: { Task { await workspace.refresh() } })
474 }
475
476 /// org-attach's commands for the entry at the caret.
477 private var attachActions: AttachActions {
478 AttachActions(
479 entry: {
480 guard let editor else { return nil }
481 let context = editor.editContext()
482 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
483 },
484 apply: { new in
485 guard let editor else { return }
486 let context = editor.editContext()
487 let caret = min(context.caret, (new as NSString).length)
488 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
489 },
490 show: { message = $0 },
491 ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
492 storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
493 open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
494 reveal: { dir in
495 if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
496 },
497 pick: { attaching = $0 })
498 }
499
500 /// Photos and videos attached under the names Photos gives them.
501 private func attachPhotos(_ items: [PhotosPickerItem]) {
502 Task { @MainActor in
503 var urls: [URL] = []
504 for item in items {
505 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
506 }
507 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
508 if !urls.isEmpty { attachActions.attach(urls, method: .mv) }
509 }
510 }
511
512 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
513 private func importTable(_ result: Result<URL, Error>) {
514 guard case .success(let url) = result, let editor else { return }
515 let scoped = url.startAccessingSecurityScopedResource()
516 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
517 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
518 _ = editor.perform(ImportTable(contents: contents))
519 }
520
521 /// org-crypt's commands at the caret, through the passphrase sheet.
522 private func crypt(_ id: String) {
523 guard let editor else { return }
524 let context = editor.editContext()
525 switch id {
526 case "app.crypt.forget-passphrase":
527 CryptPassphrases.forget(path)
528 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
529 case "app.crypt.encrypt-entries":
530 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
531 default:
532 guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
533 let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
534 if id == "app.crypt.encrypt-entry" {
535 guard !encrypted else { return message = "The entry is encrypted already" }
536 sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
537 } else {
538 guard encrypted else { return message = "Not an encrypted entry" }
539 sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
540 }
541 }
542 }
543
544 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
545 /// one, else shown.
546 private func plotTable() {
547 guard let editor else { return }
548 let context = editor.editContext()
549 do {
550 let plot = try TablePlot.plot(context.text, at: context.caret)
551 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
552 try PlotOutput.write(plot, to: url)
553 message = "Plot written to \(url.lastPathComponent)"
554 if editor.showsImages { editor.restyleAll() }
555 } else {
556 sheet = .plot(plot)
557 }
558 } catch {
559 message = "\(error)"
560 }
561 }
562
563 /// `org-table-export` of the table at the caret, as CSV or TSV.
564 private func exportTable(csv: Bool) {
565 guard let editor else { return }
566 let context = editor.editContext()
567 guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
568 return message = "No table at point"
569 }
570 exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
571 }
572
573 /// `org-refile` of the entry at the caret, to a target worked out again from the files
574 /// now, as the agenda's Refile… does.
575 func refile(to target: RefileTarget, keep: Bool = false) {
576 guard let editor, let path = session.path else { return }
577 let caret = editor.editContext().caret
578 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
579 message = "Can't find \(target.label) any more."
580 return
581 }
582 message = session.refile(to: current, from: (path, caret), keep: keep)
583 }
584}
585
586/// The editor's text view, with the Org key bar over the keyboard.
587struct EditorTextView: UIViewRepresentable {
588 let editor: MobileEditor
589 /// This pane's view of the editor.
590 let view: UITextView
591 let palette: () -> Void
592
593 func makeUIView(context: Context) -> UITextView {
594 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette))
595 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 48)
596 bar.view.backgroundColor = .clear
597 bar.sizingOptions = []
598 view.inputAccessoryView = bar.view
599 context.coordinator.bar = bar
600 return view
601 }
602
603 func updateUIView(_ view: UITextView, context: Context) {}
604
605 func makeCoordinator() -> Coordinator { Coordinator() }
606
607 final class Coordinator {
608 var bar: UIViewController?
609 }
610}
611
612/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
613/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column).
614struct KeyBar: View {
615 let editor: MobileEditor
616 let palette: () -> Void
617
618 private static let keys: [(label: String, symbol: String?, keys: String)] = [
619 ("Fold", "arrow.right.to.line", "TAB"),
620 ("Overview", "arrow.left.to.line", "S-TAB"),
621 ("Promote", "arrow.left", "M-<left>"),
622 ("Demote", "arrow.right", "M-<right>"),
623 ("Move up", "arrow.up", "M-<up>"),
624 ("Move down", "arrow.down", "M-<down>"),
625 ("New heading or item", "plus", "M-RET"),
626 ("TODO", nil, "C-c C-t"),
627 ("Act at point", "checkmark.square", "C-c C-c"),
628 ("Schedule", "calendar", "C-c C-s"),
629 ("Deadline", "calendar.badge.exclamationmark", "C-c C-d"),
630 ("Tags", "tag", "C-c C-q"),
631 ("Open link", "link", "C-c C-o"),
632 ]
633
634 var body: some View {
635 ScrollView(.horizontal, showsIndicators: false) {
636 HStack(spacing: 4) {
637 Button("Commands", systemImage: "command", action: palette)
638 ForEach(Self.keys, id: \.keys) { key in
639 Button {
640 editor.run(keys: key.keys)
641 } label: {
642 if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
643 }
644 .accessibilityLabel(key.label)
645 }
646 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
647 }
648 .labelStyle(.iconOnly)
649 .buttonStyle(.bordered)
650 .padding(.horizontal, 8)
651 .padding(.vertical, 6)
652 }
653 .background(.bar)
654 }
655}
656
657/// A command's question: text with choices, a date, or fast selection by keys.
658struct PromptSheet: View {
659 let prompt: Prompt
660 let answer: (String?) -> Void
661 @State private var text = ""
662 @State private var date = Date()
663 @State private var keys: [FastSelection.Input] = []
664
665 var body: some View {
666 NavigationStack {
667 Form {
668 if let fast = prompt.fast {
669 fastSection(fast)
670 } else {
671 Section {
672 TextField(prompt.message, text: $text)
673 .autocorrectionDisabled()
674 .textInputAutocapitalization(.never)
675 .onSubmit { answer(text) }
676 } footer: {
677 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
678 }
679 if prompt.date != nil {
680 DatePicker("Date", selection: $date, displayedComponents: [.date])
681 .datePickerStyle(.graphical)
682 .onChange(of: date) { text = Self.stamp(date) }
683 }
684 if !prompt.choices.isEmpty {
685 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
686 Section("Choices") {
687 ForEach(matching.prefix(50), id: \.self) { choice in
688 Button(choice) { choose(choice) }
689 }
690 }
691 }
692 }
693 }
694 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
695 .navigationBarTitleDisplayMode(.inline)
696 .toolbar {
697 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
698 if prompt.fast == nil || prompt.fast?.multiple == true {
699 ToolbarItem(placement: .confirmationAction) {
700 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
701 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
702 }
703 }
704 }
705 }
706 .onAppear {
707 text = prompt.initial
708 if let day = prompt.date?.defaultDate { date = day }
709 }
710 }
711
712 /// With a separator (tags), what's typed after the last one.
713 private var lastPart: String {
714 guard let separator = prompt.completionSeparator else { return text }
715 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
716 }
717
718 private func choose(_ choice: String) {
719 guard let separator = prompt.completionSeparator else {
720 text = choice
721 if prompt.date == nil { answer(choice) }
722 return
723 }
724 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
725 if parts.isEmpty { parts = [""] }
726 parts[parts.count - 1] = choice
727 text = parts.joined(separator: String(separator)) + String(separator)
728 }
729
730 @ViewBuilder
731 private func fastSection(_ fast: FastSelection) -> some View {
732 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
733 Section {
734 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
735 Button {
736 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
737 } label: {
738 HStack {
739 Text(option.name).foregroundStyle(.primary)
740 Spacer()
741 if current.contains(option.name) { Image(systemName: "checkmark") }
742 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
743 }
744 }
745 }
746 if !fast.multiple {
747 Button("No keyword") { answer(" ") }
748 }
749 } footer: {
750 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
751 }
752 }
753
754 static func stamp(_ date: Date) -> String {
755 let formatter = DateFormatter()
756 formatter.locale = Locale(identifier: "en_US_POSIX")
757 formatter.dateFormat = "yyyy-MM-dd"
758 return formatter.string(from: date)
759 }
760}
761
762/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
763/// A src block's code is highlighted as its language.
764struct BlockEditSheet: View {
765 let edit: BlockEdit
766 let theme: MobileTheme
767 let finish: (String?) -> Void
768 @State private var text: String?
769
770 var body: some View {
771 NavigationStack {
772 Group {
773 if let text {
774 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
775 }
776 }
777 .padding(.horizontal, 8)
778 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
779 .navigationBarTitleDisplayMode(.inline)
780 .toolbar {
781 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
782 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
783 }
784 }
785 .onAppear { text = edit.content }
786 }
787}
788
789/// A text view for code, restyled with the editor's highlighter after each change.
790struct CodeTextView: UIViewRepresentable {
791 let text: String
792 let language: String?
793 let theme: MobileTheme
794 let changed: (String) -> Void
795
796 func makeUIView(context: Context) -> UITextView {
797 let view = UITextView()
798 view.autocorrectionType = .no
799 view.autocapitalizationType = .none
800 view.smartQuotesType = .no
801 view.smartDashesType = .no
802 view.spellCheckingType = .no
803 view.keyboardDismissMode = .interactive
804 view.backgroundColor = .clear
805 view.text = text
806 view.delegate = context.coordinator
807 context.coordinator.style(view)
808 DispatchQueue.main.async { view.becomeFirstResponder() }
809 return view
810 }
811
812 func updateUIView(_ view: UITextView, context: Context) {
813 context.coordinator.parent = self
814 }
815
816 func makeCoordinator() -> Coordinator { Coordinator(self) }
817
818 @MainActor
819 final class Coordinator: NSObject, UITextViewDelegate {
820 var parent: CodeTextView
821 init(_ parent: CodeTextView) { self.parent = parent }
822
823 func textViewDidChange(_ view: UITextView) {
824 parent.changed(view.text)
825 style(view)
826 }
827
828 /// The theme's font and color, then the language's token colors.
829 func style(_ view: UITextView) {
830 let storage = view.textStorage
831 let whole = NSRange(location: 0, length: storage.length)
832 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
833 storage.beginEditing()
834 storage.setAttributes(base, range: whole)
835 if let language = parent.language {
836 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
837 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
838 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
839 }
840 }
841 storage.endEditing()
842 view.typingAttributes = base
843 }
844 }
845}
846
847/// Every command that applies at the caret, by name.
848struct CommandPalette: View {
849 let editor: MobileEditor
850 /// The pane commands are offered (on iPad), and those for more than one pane.
851 var panes = false
852 var split = false
853 /// Called with the chosen command before the palette closes.
854 let choose: (String) -> Void
855 @State private var query = ""
856 @Environment(\.dismiss) private var dismiss
857
858 private static let viewCommands: [(id: String, title: String)] = [
859 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
860 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
861 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
862 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
863 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
864 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
865 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
866 ("app.toggle-markup", "Show or Hide Markup"),
867 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.latex-preview", "Show or Hide LaTeX Previews"), ("editor.toggle-truncate-lines", "Truncate or Wrap Long Lines"), ("editor.toggle-auto-fill", "Turn Auto Fill On or Off"),
868 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
869 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
870 ("org.table.expand", "Expand Table Columns"),
871 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
872 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
873 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
874 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"),
875 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
876 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
877 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
878 ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
879 ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
880 ("app.attach.attach", "Attach File…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
881 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
882 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
883 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
884 ]
885
886 /// The commands that apply at the caret and their keys, worked out once when the palette
887 /// opens rather than on every keystroke in the search field.
888 @State private var applicable: [(id: String, title: String, keys: String?)]?
889
890 var body: some View {
891 let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
892 NavigationStack {
893 List(shown, id: \.id) { command in
894 Button {
895 choose(command.id)
896 dismiss()
897 } label: {
898 HStack {
899 Text(command.title).foregroundStyle(.primary)
900 Spacer()
901 if let keys = command.keys {
902 Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
903 }
904 }
905 }
906 }
907 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
908 .navigationTitle("Commands")
909 .navigationBarTitleDisplayMode(.inline)
910 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
911 }
912 .onAppear {
913 guard applicable == nil else { return }
914 let context = editor.editContext()
915 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
916 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
917 applicable = paneCommands.map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) } + (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
918 .filter { editor.applies($0.id, in: context) }
919 .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
920 }
921 }
922}
923/// A table as CSV or TSV, for the save dialog.
924struct TableFile: FileDocument {
925 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
926 let text: String
927 let type: UTType
928
929 init(text: String, type: UTType) {
930 self.text = text
931 self.type = type
932 }
933
934 init(configuration: ReadConfiguration) throws {
935 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
936 type = configuration.contentType
937 }
938
939 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
940 FileWrapper(regularFileWithContents: Data(text.utf8))
941 }
942}
943/// A plotted table, as the Mac's plot sheet shows it.
944struct PlotScreen: View {
945 let plot: TablePlot.Plot
946 @Environment(\.dismiss) private var dismiss
947
948 var body: some View {
949 NavigationStack {
950 PlotChart(plot)
951 .navigationTitle("Plot")
952 .navigationBarTitleDisplayMode(.inline)
953 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
954 }
955 }
956}
957/// A file from the photo picker, copied out of the picker's temporary place with its name.
958struct PickedFile: Transferable {
959 let url: URL
960
961 static var transferRepresentation: some TransferRepresentation {
962 FileRepresentation(importedContentType: .item) { received in
963 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
964 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
965 let url = folder.appendingPathComponent(received.file.lastPathComponent)
966 try FileManager.default.copyItem(at: received.file, to: url)
967 return PickedFile(url: url)
968 }
969 }
970}
971
972/// The passphrase sheet for org-crypt, its new text applied in the editor.
973struct CryptScreen: View {
974 let request: CryptRequest
975 let session: DocumentSession
976 let editor: MobileEditor?
977 let report: (String) -> Void
978 @Environment(\.dismiss) private var dismiss
979
980 var body: some View {
981 NavigationStack {
982 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
983 dismiss()
984 if let message { report(message) }
985 }
986 .navigationBarTitleDisplayMode(.inline)
987 }
988 }
989
990 private func apply(_ new: String) {
991 guard let editor else { return }
992 let context = editor.editContext()
993 let caret = min(context.caret, (new as NSString).length)
994 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
995 }
996}
997/// The pane an editor screen made for itself, closed with the screen.
998@MainActor
999final class PaneHolder {
1000 var pane: EditorPane?
1001 nonisolated(unsafe) var release: (() -> Void)?
1002
1003 deinit {
1004 guard let release else { return }
1005 Task { @MainActor in release() }
1006 }
1007}
1008
1009/// The screen's title, unless a split shows the focused pane's.
1010private struct EditorTitle: ViewModifier {
1011 let title: String
1012 let shown: Bool
1013
1014 func body(content: Content) -> some View {
1015 if shown {
1016 content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1017 } else {
1018 content
1019 }
1020 }
1021}
1022#endif