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