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