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