Sources/OrgstarMobile/EditorScreen.swift
cmc org-emphasize, with ⌘B, ⌘I and ⌘U in the Mac preset and key bar buttons on iOS
1d52f06a76 1 month ago1063 lines · 53140 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", "decrease.indent", "M-<left>"),
653 ("Demote", "increase.indent", "M-<right>"),
654 ("Move up", "arrow.up.square", "M-<up>"),
655 ("Move down", "arrow.down.square", "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 /// Emphasis for the selection, or a pair of markers with the caret between.
666 private static let emphasis: [(label: String, symbol: String, command: String)] = [
667 ("Bold", "bold", "org.emphasize.bold"),
668 ("Italic", "italic", "org.emphasize.italic"),
669 ("Code", "chevron.left.forwardslash.chevron.right", "org.emphasize.code"),
670 ]
671
672 var body: some View {
673 ScrollView(.horizontal, showsIndicators: false) {
674 HStack(spacing: 4) {
675 Button("Commands", systemImage: "command", action: palette)
676 ForEach(Self.keys, id: \.keys) { key in
677 Button {
678 editor.run(keys: key.keys)
679 } label: {
680 if let symbol = key.symbol { Label(key.label, systemImage: symbol) } else { Text(key.label).font(.callout.weight(.semibold)) }
681 }
682 .accessibilityLabel(key.label)
683 }
684 ForEach(Self.emphasis, id: \.command) { item in
685 Button(item.label, systemImage: item.symbol) { editor.run(item.command) }
686 }
687 Button("Hide keyboard", systemImage: "keyboard.chevron.compact.down") { editor.textView.resignFirstResponder() }
688 }
689 .labelStyle(.iconOnly)
690 .buttonStyle(.bordered)
691 .padding(.horizontal, 8)
692 .padding(.vertical, 6)
693 }
694 .background(.bar)
695 }
696}
697
698/// A command's question: text with choices, a date, or fast selection by keys.
699struct PromptSheet: View {
700 let prompt: Prompt
701 let answer: (String?) -> Void
702 @State private var text = ""
703 @State private var date = Date()
704 @State private var withTime = false
705 @State private var keys: [FastSelection.Input] = []
706
707 var body: some View {
708 NavigationStack {
709 Form {
710 if let fast = prompt.fast {
711 fastSection(fast)
712 } else {
713 Section {
714 TextField(prompt.message, text: $text)
715 .autocorrectionDisabled()
716 .textInputAutocapitalization(.never)
717 .onSubmit { answer(text) }
718 } footer: {
719 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
720 }
721 if prompt.date != nil {
722 DatePicker("Date", selection: $date, displayedComponents: [.date])
723 .datePickerStyle(.graphical)
724 .onChange(of: date) { text = QuestionField.stamp(date, withTime: withTime) }
725 Toggle("Time", isOn: $withTime)
726 .onChange(of: withTime) {
727 if withTime { date = QuestionField.timed(date) }
728 text = QuestionField.stamp(date, withTime: withTime)
729 }
730 if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
731 }
732 if !prompt.choices.isEmpty {
733 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
734 Section("Choices") {
735 ForEach(matching.prefix(50), id: \.self) { choice in
736 Button(choice) { choose(choice) }
737 }
738 }
739 }
740 }
741 }
742 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
743 .navigationBarTitleDisplayMode(.inline)
744 .toolbar {
745 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
746 if prompt.fast == nil || prompt.fast?.multiple == true {
747 ToolbarItem(placement: .confirmationAction) {
748 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
749 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
750 }
751 }
752 }
753 }
754 .onAppear {
755 text = prompt.initial
756 date = prompt.date?.defaultDate ?? Calendar.current.startOfDay(for: Date())
757 }
758 }
759
760 /// With a separator (tags), what's typed after the last one.
761 private var lastPart: String {
762 guard let separator = prompt.completionSeparator else { return text }
763 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
764 }
765
766 private func choose(_ choice: String) {
767 guard let separator = prompt.completionSeparator else {
768 text = choice
769 if prompt.date == nil { answer(choice) }
770 return
771 }
772 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
773 if parts.isEmpty { parts = [""] }
774 parts[parts.count - 1] = choice
775 text = parts.joined(separator: String(separator)) + String(separator)
776 }
777
778 @ViewBuilder
779 private func fastSection(_ fast: FastSelection) -> some View {
780 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
781 Section {
782 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
783 Button {
784 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
785 } label: {
786 HStack {
787 Text(option.name).foregroundStyle(.primary)
788 Spacer()
789 if current.contains(option.name) { Image(systemName: "checkmark") }
790 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
791 }
792 }
793 }
794 if !fast.multiple {
795 Button("No keyword") { answer(" ") }
796 }
797 } footer: {
798 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
799 }
800 }
801}
802
803/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
804/// A src block's code is highlighted as its language.
805struct BlockEditSheet: View {
806 let edit: BlockEdit
807 let theme: MobileTheme
808 let finish: (String?) -> Void
809 @State private var text: String?
810
811 var body: some View {
812 NavigationStack {
813 Group {
814 if let text {
815 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
816 }
817 }
818 .padding(.horizontal, 8)
819 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
820 .navigationBarTitleDisplayMode(.inline)
821 .toolbar {
822 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
823 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
824 }
825 }
826 .onAppear { text = edit.content }
827 }
828}
829
830/// A text view for code, restyled with the editor's highlighter after each change.
831struct CodeTextView: UIViewRepresentable {
832 let text: String
833 let language: String?
834 let theme: MobileTheme
835 let changed: (String) -> Void
836
837 func makeUIView(context: Context) -> UITextView {
838 let view = UITextView()
839 view.autocorrectionType = .no
840 view.autocapitalizationType = .none
841 view.smartQuotesType = .no
842 view.smartDashesType = .no
843 view.spellCheckingType = .no
844 view.keyboardDismissMode = .interactive
845 view.backgroundColor = .clear
846 view.text = text
847 view.delegate = context.coordinator
848 context.coordinator.style(view)
849 DispatchQueue.main.async { view.becomeFirstResponder() }
850 return view
851 }
852
853 func updateUIView(_ view: UITextView, context: Context) {
854 context.coordinator.parent = self
855 }
856
857 func makeCoordinator() -> Coordinator { Coordinator(self) }
858
859 @MainActor
860 final class Coordinator: NSObject, UITextViewDelegate {
861 var parent: CodeTextView
862 init(_ parent: CodeTextView) { self.parent = parent }
863
864 func textViewDidChange(_ view: UITextView) {
865 parent.changed(view.text)
866 style(view)
867 }
868
869 /// The theme's font and color, then the language's token colors.
870 func style(_ view: UITextView) {
871 let storage = view.textStorage
872 let whole = NSRange(location: 0, length: storage.length)
873 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
874 storage.beginEditing()
875 storage.setAttributes(base, range: whole)
876 if let language = parent.language {
877 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
878 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
879 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
880 }
881 }
882 storage.endEditing()
883 view.typingAttributes = base
884 }
885 }
886}
887
888/// Every command that applies at the caret, by name.
889struct CommandPalette: View {
890 let editor: MobileEditor
891 /// The pane commands are offered (on iPad), and those for more than one pane.
892 var panes = false
893 var split = false
894 /// Called with the chosen command before the palette closes.
895 let choose: (String) -> Void
896 @State private var query = ""
897 @Environment(\.dismiss) private var dismiss
898
899 private static let viewCommands: [(id: String, title: String)] = [
900 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
901 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
902 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
903 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
904 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
905 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
906 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
907 ("app.toggle-markup", "Show or Hide Markup"),
908 ("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"),
909 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
910 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
911 ("org.table.expand", "Expand Table Columns"),
912 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"), ("app.plot", "Plot Table"),
913 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
914 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
915 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"),
916 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
917 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
918 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
919 ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
920 ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
921 ("app.attach.attach", "Attach File…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
922 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
923 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
924 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
925 ]
926
927 /// The commands that apply at the caret and their keys, worked out once when the palette
928 /// opens rather than on every keystroke in the search field.
929 @State private var applicable: [(id: String, title: String, keys: String?)]?
930
931 var body: some View {
932 let shown = (applicable ?? []).filter { query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) }
933 NavigationStack {
934 List(shown, id: \.id) { command in
935 Button {
936 choose(command.id)
937 dismiss()
938 } label: {
939 HStack {
940 Text(command.title).foregroundStyle(.primary)
941 Spacer()
942 if let keys = command.keys {
943 Text(keys).font(.caption.monospaced()).foregroundStyle(.secondary)
944 }
945 }
946 }
947 }
948 .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
949 .navigationTitle("Commands")
950 .navigationBarTitleDisplayMode(.inline)
951 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Close") { dismiss() } } }
952 }
953 .onAppear {
954 guard applicable == nil else { return }
955 let context = editor.editContext()
956 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
957 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
958 applicable = paneCommands.map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) } + (Self.viewCommands + Commands.everything.map { ($0.id, $0.title) })
959 .filter { editor.applies($0.id, in: context) }
960 .map { ($0.id, $0.title, editor.keymap.keyLabels(for: $0.id).first) }
961 }
962 }
963}
964/// A table as CSV or TSV, for the save dialog.
965struct TableFile: FileDocument {
966 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
967 let text: String
968 let type: UTType
969
970 init(text: String, type: UTType) {
971 self.text = text
972 self.type = type
973 }
974
975 init(configuration: ReadConfiguration) throws {
976 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
977 type = configuration.contentType
978 }
979
980 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
981 FileWrapper(regularFileWithContents: Data(text.utf8))
982 }
983}
984/// A plotted table, as the Mac's plot sheet shows it.
985struct PlotScreen: View {
986 let plot: TablePlot.Plot
987 @Environment(\.dismiss) private var dismiss
988
989 var body: some View {
990 NavigationStack {
991 PlotChart(plot)
992 .navigationTitle("Plot")
993 .navigationBarTitleDisplayMode(.inline)
994 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
995 }
996 }
997}
998/// A file from the photo picker, copied out of the picker's temporary place with its name.
999struct PickedFile: Transferable {
1000 let url: URL
1001
1002 static var transferRepresentation: some TransferRepresentation {
1003 FileRepresentation(importedContentType: .item) { received in
1004 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1005 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1006 let url = folder.appendingPathComponent(received.file.lastPathComponent)
1007 try FileManager.default.copyItem(at: received.file, to: url)
1008 return PickedFile(url: url)
1009 }
1010 }
1011}
1012
1013/// The passphrase sheet for org-crypt, its new text applied in the editor.
1014struct CryptScreen: View {
1015 let request: CryptRequest
1016 let session: DocumentSession
1017 let editor: MobileEditor?
1018 let report: (String) -> Void
1019 @Environment(\.dismiss) private var dismiss
1020
1021 var body: some View {
1022 NavigationStack {
1023 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
1024 dismiss()
1025 if let message { report(message) }
1026 }
1027 .navigationBarTitleDisplayMode(.inline)
1028 }
1029 }
1030
1031 private func apply(_ new: String) {
1032 guard let editor else { return }
1033 let context = editor.editContext()
1034 let caret = min(context.caret, (new as NSString).length)
1035 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1036 }
1037}
1038/// The pane an editor screen made for itself, closed with the screen.
1039@MainActor
1040final class PaneHolder {
1041 var pane: EditorPane?
1042 nonisolated(unsafe) var release: (() -> Void)?
1043
1044 deinit {
1045 guard let release else { return }
1046 Task { @MainActor in release() }
1047 }
1048}
1049
1050/// The screen's title, unless a split shows the focused pane's.
1051private struct EditorTitle: ViewModifier {
1052 let title: String
1053 let shown: Bool
1054
1055 func body(content: Content) -> some View {
1056 if shown {
1057 content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1058 } else {
1059 content
1060 }
1061 }
1062}
1063#endif