Sources/OrgstarMobile/EditorScreen.swift
1393 lines · 69216 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; returns why one did nothing.
27 var onPaneCommand: ((String) -> String?)? = 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 /// The file's sync conflict copies and recovery versions, for their toolbar buttons.
40 @State private var syncCopies = 0
41 @State private var recoveries = 0
42 @Environment(MobileModel.self) private var model
43 @Environment(\.openURL) private var openURL
44
45 /// The session's options with `buffer-file-name` and the agenda files, for clock tables.
46 private var editorOptions: EditingOptions {
47 var options = session.options
48 options.filePath = path
49 options.agendaFiles = workspace.agendaFilePaths()
50 options.denoteDirectories = DenoteNote.directories(roots: workspace.rootPaths)
51 options.denoteSequenceScheme = OrgPreferences.denoteSequenceScheme()
52 options.timer = TimerModel.shared.timer
53 return options
54 }
55
56 struct PromptRequest: Identifiable {
57 let id = UUID()
58 let prompt: Prompt
59 let reply: (String?) -> Void
60 }
61
62 /// One sheet at a time: two presenters on this screen interfere.
63 /// `org-table-import`'s file picker is up.
64 @State private var importingTable = false
65 /// The table at the caret, for `org-table-export`'s save dialog.
66 @State private var exportedTable: TableFile?
67 /// org-attach's file picker is up, for this method.
68 @State private var attaching: Attachments.Method?
69 @State private var attachingPhotos = false
70 @State private var takingPhoto = false
71 @State private var scanning = false
72 @State private var photos: [PhotosPickerItem] = []
73 /// A file shown in Quick Look.
74 @State private var previewed: URL?
75 /// The project whose publishing folder the folder picker is choosing.
76 @State private var publishFolder: PublishFolderRequest?
77 @State private var choosingPublishFolder = false
78
79 struct PublishFolderRequest {
80 let project: String
81 /// Publishes again, with the folder.
82 let then: () -> Void
83 }
84
85 enum Sheet: Identifiable {
86 case palette, conflict, syncCopies, recovery
87 /// `app.refile`, `app.refile.copy` or `app.refile.goto`.
88 case refile(String)
89 case block(BlockEdit)
90 case columns(ColumnView.View)
91 case plot(TablePlot.Plot)
92 case crypt(CryptRequest)
93 case backlinks
94 case graph
95 /// The subtree at this offset, to export.
96 case exportSubtree(Int)
97
98 var id: String {
99 switch self {
100 case .palette: "palette"
101 case .refile(let command): command
102 case .conflict: "conflict"
103 case .syncCopies: "syncCopies"
104 case .recovery: "recovery"
105 case .block(let edit): "block \(edit.range)"
106 case .columns: "columns"
107 case .plot: "plot"
108 case .crypt(let request): request.id.uuidString
109 case .backlinks: "backlinks"
110 case .graph: "graph"
111 case .exportSubtree: "exportSubtree"
112 }
113 }
114 }
115
116 private var pane: EditorPane? { givenPane ?? holder.pane }
117
118 /// The pane commands, as the Mac's View menu has them.
119 static let paneCommands = ["app.split-right", "app.split-below", "app.pane-next", "app.pane-close", "app.pane-only"]
120
121 var body: some View {
122 Group {
123 if let editor, let textView {
124 EditorTextView(editor: editor, view: textView, palette: { sheet = .palette })
125 .ignoresSafeArea(.container, edges: .bottom)
126 } else {
127 ProgressView()
128 }
129 }
130 .modifier(EditorTitle(title: session.bufferName(path) + (session.dirtyPaths.contains(path) ? " •" : ""), shown: !inSplit))
131 .toolbar(.hidden, for: .tabBar)
132 .toolbar {
133 if !inSplit || isFocused {
134 ToolbarItemGroup(placement: .primaryAction) {
135 if pane?.conflict != nil {
136 Button("Conflict", systemImage: "exclamationmark.triangle") { sheet = .conflict }
137 }
138 if syncCopies > 0 {
139 Button("Resolve Sync Conflicts…", systemImage: "doc.on.doc") { sheet = .syncCopies }
140 }
141 if recoveries > 0 {
142 Button("Recovery Versions…", systemImage: "clock.arrow.circlepath") { sheet = .recovery }
143 }
144 Button("Find", systemImage: "magnifyingglass") {
145 textView?.interactions.lazy.compactMap { $0 as? UIFindInteraction }.first?.presentFindNavigator(showingReplace: false)
146 }
147 // Redo on a long press, as the system's back buttons offer history.
148 Menu {
149 Button("Redo", systemImage: "arrow.uturn.forward") { editor?.run("edit.redo") }
150 } label: {
151 Label("Undo", systemImage: "arrow.uturn.backward")
152 } primaryAction: {
153 editor?.run("edit.undo")
154 }
155 if let tree = session.document(of: path)?.tree {
156 ExportMenu(path: path, tree: tree, report: { message = $0 }, exportSubtree: exportSubtree)
157 }
158 Button("Commands", systemImage: "command") { sheet = .palette }
159 }
160 }
161 }
162 .safeAreaInset(edge: .top) {
163 VStack(spacing: 0) {
164 if let timer = TimerModel.shared.timer {
165 TimelineView(.periodic(from: .now, by: 1)) { context in
166 Text(timer.modeLine(now: context.date)).font(.callout.monospacedDigit())
167 }
168 .frame(maxWidth: .infinity).padding(4).background(.bar)
169 }
170 }
171 }
172 .message($message, edge: .top)
173 .sheet(item: $prompt) { request in
174 PromptSheet(prompt: request.prompt) { answer in
175 prompt = nil
176 request.reply(answer)
177 }
178 }
179 .sheet(item: $sheet, onDismiss: {
180 countVersions()
181 // After the sheet has gone, so a command's own prompt can show.
182 if let id = chosen {
183 chosen = nil
184 editor?.run(id)
185 }
186 }) { sheet in
187 switch sheet {
188 case .palette: if let editor { CommandPalette(editor: editor, panes: onPaneCommand != nil && sizeClass == .regular, split: inSplit,
189 recoveries: recoveries, syncCopies: syncCopies) { chosen = $0 } }
190 case .conflict: ConflictSheet(session: session)
191 case .syncCopies: SyncConflictSheet(session: session) { message = $0 }
192 case .recovery: RecoverySheet(session: session) { message = $0 }
193 case .refile(let command):
194 RefileSheet(targets: workspace.refileTargets(openPath: session.path, document: session.document),
195 create: command == "app.refile.goto" || OrgPreferences.refileSettings().creating == .no ? nil : { parent, child in
196 self.sheet = nil
197 switch session.createRefileChild(under: parent, title: child) {
198 case .success(let target):
199 guard let path = session.path, let editor else { return }
200 message = session.refile(to: target, from: (path, editor.editContext().caret), keep: command == "app.refile.copy")
201 case .failure(.message(let text)): message = text
202 }
203 }) { target in
204 self.sheet = nil
205 guard let target else { return }
206 if command == "app.refile.goto" {
207 model.openRequest = .offset(target.path, target.start ?? Int.max)
208 } else {
209 refile(to: target, keep: command == "app.refile.copy")
210 }
211 }
212 case .block(let edit):
213 BlockEditSheet(edit: edit, theme: MobileTheme(model.theme)) { content in
214 self.sheet = nil
215 if let content, let editor { _ = editor.perform(ReplaceBlockLines(edit: edit, content: content)) }
216 }
217 case .columns(let view):
218 ColumnViewScreen(view: view, session: session, path: path) { offset in editor?.reveal(offset) }
219 case .plot(let plot):
220 PlotScreen(plot: plot)
221 case .crypt(let request):
222 CryptScreen(request: request, session: session, editor: editor) { message = $0 }
223 case .exportSubtree(let caret):
224 if let tree = session.document(of: path)?.tree { SubtreeExportScreen(path: path, tree: tree, caret: caret) }
225 case .backlinks:
226 BacklinksScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in
227 if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) }
228 }
229 case .graph:
230 RoamGraphScreen(workspace: workspace, session: session, path: path, caret: editor?.editContext().caret ?? 0) { location in
231 if location.path == path { editor?.reveal(location.start) } else { model.openRequest = .heading(location) }
232 }
233 }
234 }
235 .fileImporter(isPresented: $importingTable, allowedContentTypes: [.commaSeparatedText, .tabSeparatedText, .plainText]) { result in
236 importTable(result)
237 }
238 .background {
239 // A second importer on the same view would replace the first.
240 Color.clear.fileImporter(isPresented: Binding(get: { attaching != nil }, set: { if !$0 { attaching = nil } }),
241 allowedContentTypes: [.item, .folder], allowsMultipleSelection: true) { result in
242 let method = attaching ?? .cp
243 switch result {
244 case .success(let urls): attachActions.attach(urls, method: method)
245 case .failure(let error): message = error.localizedDescription
246 }
247 }
248 }
249 .background {
250 Color.clear.fileImporter(isPresented: $choosingPublishFolder, allowedContentTypes: [.folder]) { result in
251 guard let request = publishFolder else { return }
252 publishFolder = nil
253 switch result {
254 case .success(let url):
255 if !PublishFolders.shared.set(url, for: request.project) { message = "orgstar can use \(url.lastPathComponent) only until it quits" }
256 request.then()
257 case .failure(let error): message = error.localizedDescription
258 }
259 }
260 }
261 .photosPicker(isPresented: $attachingPhotos, selection: $photos, matching: .any(of: [.images, .videos]))
262 .fullScreenCover(isPresented: $takingPhoto) {
263 CameraPicker { data in
264 takingPhoto = false
265 if let data { attachActions.yankImage(data, ext: "jpg", prefix: "photo") }
266 }
267 .ignoresSafeArea()
268 }
269 .fullScreenCover(isPresented: $scanning) {
270 DocumentScanner { data in
271 scanning = false
272 if let data { attachActions.yankImage(data, ext: "pdf", prefix: "scan") }
273 }
274 .ignoresSafeArea()
275 }
276 .onChange(of: photos) { _, items in
277 guard !items.isEmpty else { return }
278 photos = []
279 attachPhotos(items)
280 }
281 .quickLookPreview($previewed)
282 .fileExporter(isPresented: Binding(get: { exportedTable != nil }, set: { if !$0 { exportedTable = nil } }),
283 document: exportedTable, contentType: exportedTable?.type ?? .commaSeparatedText,
284 defaultFilename: exportedTable?.type == .tabSeparatedText ? "table.tsv" : "table.csv") { result in
285 if case .failure(let error) = result { message = error.localizedDescription } else { message = "Export done." }
286 }
287 .onChange(of: pane?.conflict) { _, conflict in
288 countVersions()
289 if conflict != nil, isFocused { sheet = .conflict }
290 }
291 .onChange(of: session.lastError) { _, error in
292 guard let error else { return }
293 // The title says what failed.
294 message = session.lastErrorTitle.map { "\($0)\n\(error)" } ?? error
295 session.lastError = nil
296 }
297 .onReceive(NotificationCenter.default.publisher(for: OrgExport.refused)) { message = $0.object as? String }
298 .onAppear(perform: start)
299 // A pane command moved focus here.
300 .onChange(of: isFocused) {
301 countVersions()
302 guard isFocused, let textView, !textView.isFirstResponder else { return }
303 editor?.focus(textView)
304 textView.becomeFirstResponder()
305 }
306 .onChange(of: pane?.revealRequest?.id) {
307 if let offset = pane?.revealRequest?.offset, pane?.path == path { editor?.reveal(offset) }
308 }
309 .onChange(of: model.settingsVersion) {
310 editor?.options = editorOptions
311 editor?.themeSpec = model.theme
312 editor?.keymap = model.keymap
313 editor?.modal = model.modalKeys
314 }
315 .onChange(of: model.showMarkup) { editor?.showMarkup = model.showMarkup }
316 .onChange(of: TimerModel.shared.timer) { editor?.options = editorOptions }
317 .onDisappear {
318 // Typing the reader shows next, and a save, don't wait for the autosave delay.
319 if session.dirtyPaths.contains(path) { _ = session.save(path) }
320 }
321 }
322
323 /// Store Link, Store ID Link and Insert Link, with the links stored while the app runs.
324 private func link(_ id: String) {
325 guard let editor else { return }
326 switch id {
327 case "org.link.store":
328 let context = editor.editContext()
329 let denote = OrgPreferences.usesDenote() ? Links.storeDenote(in: context, path: path) : nil
330 message = StoredLink.add(denote ?? Links.store(in: context, path: Links.abbreviate(path, home: OrgPaths.home)), to: &model.storedLinks)
331 case "org.id.store-link":
332 if case .commit = editor.perform(CreateID()),
333 let link = Links.storeID(in: editor.editContext(), fileName: (path as NSString).lastPathComponent) {
334 message = StoredLink.add(link, to: &model.storedLinks)
335 }
336 default:
337 _ = editor.perform(InsertLink(stored: model.storedLinks, file: path))
338 }
339 }
340
341 /// Runs a block once it's trusted, asking as `org-confirm-babel-evaluate` does.
342 private func run(_ job: BabelJob) {
343 let go = {
344 message = "Running \(job.language) block…"
345 session.startBabel(job) { message = $0 }
346 }
347 if !job.alwaysAsk, trust.isTrusted(path: path, content: job.blockText) { return go() }
348 let choices = job.alwaysAsk ? ["yes", "no"] : ["yes", "no", "always"]
349 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Run this \(job.language) block?", choices: choices)) { answer in
350 switch answer {
351 case "always":
352 trust.trust(path: path, content: job.blockText)
353 go()
354 case "yes": go()
355 default: message = "Not run"
356 }
357 }
358 }
359
360 private func start() {
361 let pane: EditorPane
362 if let existing = self.pane {
363 pane = existing
364 } else {
365 pane = session.makePane()
366 holder.pane = pane
367 let store = model.editors, path = path
368 holder.release = { [weak session] in
369 store.release(pane.id, path: path)
370 session?.closePane(pane)
371 }
372 }
373 if pane.path != path { session.open(path, in: pane) }
374 model.editors.prune(session)
375 guard let editor = model.editors.editor(for: path, session: session, make: makeEditor) else { return }
376 let view = model.editors.view(for: pane.id, of: editor)
377 editor.onFocus[ObjectIdentifier(view)] = { [weak session] in
378 session?.focused = pane
379 bind(editor)
380 onFocus()
381 }
382 // A pane a split adds leaves focus where it was, as `split-window` does.
383 if isFocused {
384 session.focused = pane
385 bind(editor)
386 editor.focus(view)
387 }
388 self.editor = editor
389 textView = view
390 if let offset { editor.reveal(offset) }
391 if let template = SnippetLibrary.shared.takeTemplate(for: path) { DispatchQueue.main.async { _ = editor.perform(ExpandNamedSnippet(snippet: template)) } }
392 countVersions()
393 if pane.conflict != nil {
394 sheet = .conflict
395 } else if syncCopies > 0 {
396 message = String(localized: "\(syncCopies) sync conflict copies of this file; Resolve Sync Conflicts… in the toolbar compares them.")
397 }
398 }
399
400 /// Counts the focused file's sync conflict copies and recovery versions.
401 private func countVersions() {
402 guard isFocused else { return }
403 syncCopies = session.syncConflictCopies().count
404 recoveries = session.recoveryVersions().count
405 }
406
407 private func makeEditor() -> MobileEditor? {
408 guard let document = session.document(of: path) else { return nil }
409 let editor = MobileEditor(
410 document: document, editable: document.isEditable, options: editorOptions, theme: model.theme,
411 showMarkup: model.showMarkup, baseDirectory: URL(fileURLWithPath: path).deletingLastPathComponent()
412 )
413 let path = path
414 editor.fileName = path
415 editor.attachmentPath = { DocumentSession.attachmentPath($0, at: $1, tree: $2, path: path) }
416 return editor
417 }
418
419 /// The editor's callbacks go to this screen: it's shown here, or its view here took focus.
420 private func bind(_ editor: MobileEditor) {
421 editor.knownTags = { [index = workspace.index] in (try? index.tags()) ?? [] }
422 editor.onChange = { [weak session] in session?.bufferChanged(path) }
423 editor.onMessage = { message = $0 }
424 editor.onPrompt = { prompt, reply in self.prompt = PromptRequest(prompt: prompt, reply: reply) }
425 editor.onLink = { link in follow(link) }
426 editor.onEditBlock = { edit in sheet = .block(edit) }
427 editor.onColumnView = { view in sheet = .columns(view) }
428 editor.onTangle = { scope in if ProAccess.shared.allows(.babel) { message = session.tangle(scope) } }
429 editor.onBabel = { job in if ProAccess.shared.allows(.babel) { run(job) } }
430 editor.onRefreshSetup = { session.refreshSetup() }
431 editor.onAgenda = { start, count in model.agendaRequest = .init(start: start, count: count) }
432 editor.keymap = model.keymap
433 editor.modal = model.modalKeys
434 // Dropped files are copies the drop made, so they are attached, not linked or opened.
435 editor.onFiles = { attachActions.drop($0, method: .attach, attachMethod: .mv) }
436 editor.onImage = { attachActions.yankImage($0, ext: $1) }
437 editor.onAppCommand = { id in
438 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
439 if Self.paneCommands.contains(id) {
440 if let onPaneCommand { if let text = onPaneCommand(id) { message = text } } else { message = MobileEditor.unavailable(command: id) }
441 } else if id == "app.save" {
442 _ = session.save(path)
443 } else if id == "app.archive" {
444 if let caret = self.editor?.editContext().caret { message = session.archive(from: (path, caret)) }
445 } else if id == "app.copy-rich-text" {
446 if let text = session.document(of: path)?.text { message = ExportMenu.copy(path: path, text: text, theme: model.theme) }
447 } else if id == "app.export.html-open" {
448 exportHTMLAndOpen()
449 } else if id == "app.export-body-only" {
450 let on = !ExportSettings.saved(for: path).bodyOnly
451 ExportMenu.setBodyOnly(on, path: path)
452 message = on ? "Export: body only" : "Export: whole document"
453 } else if id == "app.export.icalendar-agenda" || id == "app.export.icalendar-combined" {
454 agendaCalendars(combined: id == "app.export.icalendar-combined")
455 } else if id.hasPrefix("app.publish") {
456 publish(id)
457 } else if AppStoreCommands.unavailable(id) {
458 message = "Attachments can't be linked on iPhone and iPad; Attach File… copies the file."
459 } else if ["app.refile", "app.refile.copy", "app.refile.goto"].contains(id) {
460 sheet = .refile(id)
461 } else if id == "app.table-import" {
462 importingTable = true
463 } else if id == "app.table-export" || id == "app.table-export.tsv" {
464 exportTable(csv: id == "app.table-export")
465 } else if id == "app.word-count" {
466 message = wordCount()
467 } else if id == "app.recovery" {
468 sheet = .recovery
469 } else if id == "app.sync-conflicts" {
470 sheet = .syncCopies
471 } else if id == "app.attach.photo" {
472 attachingPhotos = true
473 } else if id == "app.attach.camera" {
474 takingPhoto = true
475 } else if id == "app.attach.scan" {
476 scanning = true
477 } else if id == "app.plot" {
478 plotTable()
479 } else if id.hasPrefix("app.crypt.") {
480 crypt(id)
481 } else if id.hasPrefix("app.attach.") {
482 attachActions.run(id)
483 } else if id == "app.node.graph" {
484 sheet = .graph
485 } else if id.hasPrefix("app.dailies.") || id.hasPrefix("app.node.") {
486 roamActions.run(id)
487 } else if id == "app.backlinks" {
488 sheet = .backlinks
489 } else if id == "app.toggle-markup" {
490 model.showMarkup.toggle()
491 } else if MobileEditor.linkCommands.contains(id) {
492 link(id)
493 } else if !MobileClock.run(id, model: model, workspace: workspace, show: { message = $0 }) {
494 message = MobileEditor.unavailable(command: id)
495 }
496 }
497 }
498}
499
500extension EditorScreen {
501 /// Follows a link; files the editor doesn't open show in Quick Look.
502 private func follow(_ link: OrgLink) {
503 switch session.follow(link, workspace: workspace, isText: { _ in false }) {
504 case .shown:
505 // A link to another file shows it on its own screen; this pane keeps its file.
506 guard let pane, let target = pane.path, target != path else { message = nil; return }
507 let caret = session.caret(of: target) ?? 0
508 session.open(path, in: pane)
509 model.openRequest = .offset(target, caret)
510 case .openExternally(let url): if url.isFileURL { previewed = url } else { openURL(url) }
511 case .message(let text): message = text
512 case .choose(let question, let paths):
513 let labels = paths.map { ($0 as NSString).lastPathComponent }
514 prompt = PromptRequest(prompt: Prompt(key: "file", message: question, choices: labels)) { answer in
515 guard let answer, let index = labels.firstIndex(of: answer) else { return }
516 follow(OrgLink(type: "file", path: paths[index], raw: "file:" + paths[index]))
517 }
518 case .elisp(let form):
519 // Once trusted, as `org-link-elisp-confirm-function` asks.
520 let go = { _ = Task { message = await session.evaluateLink(form) } }
521 let content = "elisp:" + form
522 if trust.isTrusted(path: path, content: content) { return go() }
523 prompt = PromptRequest(prompt: Prompt(key: "confirm", message: "Execute \(form) as Elisp?", choices: ["yes", "no", "always"])) { answer in
524 switch answer {
525 case "always":
526 trust.trust(path: path, content: content)
527 go()
528 case "yes": go()
529 default: message = "Not run"
530 }
531 }
532 }
533 }
534
535 /// org-roam's daily notes and nodes.
536 private var roamActions: RoamActions {
537 RoamActions(
538 session: session, roots: { workspace.rootPaths },
539 nodes: { try workspace.nodes(overlay: workspace.overlay(session.openDocuments)) },
540 show: { message = $0 }, ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
541 open: { file, offset in
542 if file == path { editor?.reveal(offset) } else { model.openRequest = .offset(file, offset) }
543 },
544 insertLink: { link, title in
545 guard let editor else { return }
546 let context = editor.editContext()
547 let range = context.selection.first ?? context.caret..<context.caret
548 let selected = (context.text as NSString).substring(with: NSRange(range))
549 let text = Links.makeString(link, selected.isEmpty ? title : selected)
550 let end = range.lowerBound + (text as NSString).length
551 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: range, replacement: text)], selection: [end..<end])))
552 },
553 refresh: { Task { await workspace.refresh() } })
554 }
555
556 /// org-attach's commands for the entry at the caret.
557 private var attachActions: AttachActions {
558 AttachActions(
559 entry: {
560 guard let editor else { return nil }
561 let context = editor.editContext()
562 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
563 },
564 apply: { new, caret in
565 guard let editor else { return }
566 let context = editor.editContext()
567 let caret = min(caret ?? context.caret, (new as NSString).length)
568 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
569 },
570 show: { message = $0 },
571 ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
572 storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
573 open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
574 reveal: { dir in
575 if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
576 },
577 pick: { attaching = $0 })
578 }
579
580 /// Photos and videos attached under the names Photos gives them, linked at the caret.
581 private func attachPhotos(_ items: [PhotosPickerItem]) {
582 Task { @MainActor in
583 var urls: [URL] = []
584 for item in items {
585 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
586 }
587 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
588 if !urls.isEmpty { attachActions.drop(urls, method: .attach, attachMethod: .mv) }
589 }
590 }
591
592 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
593 private func importTable(_ result: Result<URL, Error>) {
594 guard case .success(let url) = result, let editor else { return }
595 let scoped = url.startAccessingSecurityScopedResource()
596 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
597 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
598 _ = editor.perform(ImportTable(contents: contents))
599 }
600
601 /// The export formats for the subtree at the caret, as the Mac's export sheet's scope.
602 private func exportSubtree() {
603 guard let context = editor?.editContext() else { return }
604 guard ExportScope.subtree(context.text, at: context.caret) != nil else { return message = "Not in a subtree" }
605 sheet = .exportSubtree(context.caret)
606 }
607
608 /// `org-html-export-to-html` and open: the page in Quick Look, from a temporary file.
609 private func exportHTMLAndOpen() {
610 guard let text = session.document(of: path)?.text else { return }
611 let html = OrgExport.html(text, path: path, theme: model.theme, bodyOnly: ExportSettings.saved(for: path).bodyOnly)
612 let name = ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: OrgPreferences.orgSettings()), extension: "html")
613 .lastPathComponent
614 do {
615 previewed = try HTMLPreview.write(html, directory: URL(fileURLWithPath: path).deletingLastPathComponent(), name: name)
616 } catch {
617 message = "Can't export \(name): \(error.localizedDescription)"
618 }
619 }
620
621 /// The agenda files' calendars written beside them, or combined in one shown in Quick Look,
622 /// whose share button saves or sends it.
623 private func agendaCalendars(combined: Bool) {
624 guard let calendars = AgendaCalendars(model: model) else { return message = "No agenda files" }
625 guard combined else { return message = calendars.exportEach() }
626 do {
627 previewed = try calendars.combined()
628 } catch {
629 message = "Can't export: \(error.localizedDescription)"
630 }
631 }
632
633 /// `org-publish` and its variants, for the `[[publish]]` projects in config.toml.
634 private func publish(_ id: String) {
635 guard let all = publishProjects() else { return }
636 let current = Publish.projects(containing: path, in: all)
637 switch id {
638 case "app.publish.all":
639 publish(all.map(\.name))
640 case "app.publish.current-file":
641 guard let project = current.first else { return message = "File is not part of any known project" }
642 publish([project.name], only: path)
643 case "app.publish.current-project":
644 guard let project = current.first else { return message = "File is not part of any known project" }
645 publish([project.name])
646 default:
647 prompt = PromptRequest(prompt: Prompt(key: "project", message: "Publish project:", choices: all.map(\.name))) { answer in
648 if let answer, all.contains(where: { $0.name == answer }) { publish([answer]) }
649 }
650 }
651 }
652
653 /// The projects in config.toml, each publishing to the folder chosen for it; nil, with a
654 /// message, when there are none.
655 private func publishProjects() -> [PublishProject]? {
656 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
657 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
658 if let problem = loaded.problems.first { message = problem }
659 guard !loaded.projects.isEmpty else {
660 message = "No [[publish]] projects in config.toml"
661 return nil
662 }
663 return PublishFolders.shared.applied(to: loaded.projects)
664 }
665
666 /// Publishes the projects named, `only` that file when given. A project that publishes
667 /// outside the folders added to orgstar asks for its folder first, once.
668 private func publish(_ names: [String], only: String? = nil) {
669 guard let all = publishProjects() else { return }
670 let chosen = all.filter { names.contains($0.name) }
671 do {
672 if let project = try PublishFolders.shared.needed(chosen, all: all, roots: workspace.rootPaths).first {
673 message = "Choose the folder \(project.name) publishes to"
674 publishFolder = PublishFolderRequest(project: project.name) { publish(names, only: only) }
675 choosingPublishFolder = true
676 return
677 }
678 if let project = try Publish.expand(chosen, all: all).first(where: { !FileManager.default.fileExists(atPath: $0.baseDirectory) }) {
679 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
680 }
681 let read = { (file: String) -> String? in
682 session.openDocuments.first { $0.path == file }?.document.text ?? (try? String(contentsOfFile: file, encoding: .utf8))
683 }
684 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
685 // As the Export menu: no author unless the file has #+AUTHOR:.
686 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in
687 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "")
688 }
689 message = report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
690 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")
691 } catch {
692 message = "\(error)"
693 }
694 }
695
696 /// org-crypt's commands at the caret, through the passphrase sheet.
697 private func crypt(_ id: String) {
698 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
699 guard let editor else { return }
700 let context = editor.editContext()
701 switch id {
702 case "app.crypt.forget-passphrase":
703 CryptPassphrases.forget(path)
704 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
705 case "app.crypt.encrypt-entries":
706 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
707 default:
708 guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
709 let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
710 if id == "app.crypt.encrypt-entry" {
711 guard !encrypted else { return message = "The entry is encrypted already" }
712 sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
713 } else {
714 guard encrypted else { return message = "Not an encrypted entry" }
715 sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
716 }
717 }
718 }
719
720 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
721 /// one, else shown.
722 private func plotTable() {
723 guard let editor else { return }
724 let context = editor.editContext()
725 do {
726 let plot = try TablePlot.plot(context.text, at: context.caret)
727 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
728 try PlotOutput.write(plot, to: url)
729 message = "Plot written to \(url.lastPathComponent)" + (PlotOutput.note(plot).map { ". " + $0 } ?? "")
730 if editor.showsImages { editor.restyleAll() }
731 } else {
732 try PlotOutput.check(plot)
733 sheet = .plot(plot)
734 if let note = PlotOutput.note(plot) { message = note }
735 }
736 } catch {
737 message = "\(error)"
738 }
739 }
740
741 /// `org-table-export` of the table at the caret, as CSV or TSV.
742 /// Words, characters and reading time of the selection, or of the file.
743 private func wordCount() -> String {
744 guard let editor else { return "No file is open" }
745 let text = editor.document.text as NSString
746 let selection = editor.textView.selectedRange
747 let selected = selection.length > 0 && NSMaxRange(selection) <= text.length
748 let counts = TextStats.region(selected ? text.substring(with: selection) : text as String)
749 return (selected ? "Selection: " : "") + TextStats.summary(words: counts.words, characters: counts.characters)
750 }
751
752 private func exportTable(csv: Bool) {
753 guard let editor else { return }
754 let context = editor.editContext()
755 guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
756 return message = "No table at point"
757 }
758 exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
759 }
760
761 /// `org-refile` of the entry at the caret, to a target worked out again from the files
762 /// now, as the agenda's Refile… does.
763 func refile(to target: RefileTarget, keep: Bool = false) {
764 guard let editor, let path = session.path else { return }
765 let caret = editor.editContext().caret
766 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
767 message = "Can't find \(target.label) any more."
768 return
769 }
770 message = session.refile(to: current, from: (path, caret), keep: keep)
771 }
772}
773
774/// The editor's text view, with the Org key bar over the keyboard.
775struct EditorTextView: UIViewRepresentable {
776 let editor: MobileEditor
777 /// This pane's view of the editor.
778 let view: UITextView
779 let palette: () -> Void
780
781 func makeUIView(context: Context) -> UITextView {
782 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette).dynamicTypeSize(...KeyBar.largestSize))
783 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 2 * KeyBar.padding + KeyBar.target)
784 bar.view.backgroundColor = .clear
785 // As tall as its buttons: the input accessory takes the intrinsic height.
786 bar.sizingOptions = .intrinsicContentSize
787 bar.safeAreaRegions = []
788 bar.view.autoresizingMask = .flexibleHeight
789 view.inputAccessoryView = bar.view
790 context.coordinator.bar = bar
791 // The bar's height follows the text size.
792 view.registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) { (view: UITextView, _) in
793 view.inputAccessoryView?.invalidateIntrinsicContentSize()
794 view.reloadInputViews()
795 }
796 return view
797 }
798
799 func updateUIView(_ view: UITextView, context: Context) {}
800
801 func makeCoordinator() -> Coordinator { Coordinator() }
802
803 final class Coordinator {
804 var bar: UIViewController?
805 }
806}
807
808/// Org's keys for a touch keyboard: each button does what its key does at the caret, as the
809/// Emacs keymap binds it (M-→ demotes a heading, indents an item, moves a table column). It holds
810/// what is repeated at the caret while typing; the rest is in Commands. Its buttons share the
811/// width, without scrolling.
812struct KeyBar: View {
813 let editor: MobileEditor
814 let palette: () -> Void
815 @Environment(\.horizontalSizeClass) private var sizeClass
816
817 /// A button the bar can hold.
818 struct Item {
819 enum Action {
820 /// What the keys are bound to at the caret.
821 case keys(String)
822 case command(String)
823 case palette
824 /// Schedule, Deadline and Tags in a menu.
825 case plan
826 case hideKeyboard
827 }
828
829 let label: String
830 /// Nil shows the label as text.
831 let symbol: String?
832 let action: Action
833 }
834
835 /// Every button the bar can hold, by id.
836 static let items: [String: Item] = [
837 "commands": Item(label: String(localized: "Commands"), symbol: "command", action: .palette),
838 "fold": Item(label: String(localized: "Fold", comment: "Key bar button"), symbol: "arrow.right.to.line", action: .keys("TAB")),
839 "overview": Item(label: String(localized: "Overview", comment: "Key bar button"), symbol: "arrow.left.to.line", action: .keys("S-TAB")),
840 "promote": Item(label: String(localized: "Promote", comment: "Key bar button"), symbol: "decrease.indent", action: .keys("M-<left>")),
841 "demote": Item(label: String(localized: "Demote", comment: "Key bar button"), symbol: "increase.indent", action: .keys("M-<right>")),
842 "move-up": Item(label: String(localized: "Move Up", comment: "Key bar button"), symbol: "arrow.up.square", action: .keys("M-<up>")),
843 "move-down": Item(label: String(localized: "Move Down", comment: "Key bar button"), symbol: "arrow.down.square", action: .keys("M-<down>")),
844 "new-heading": Item(label: String(localized: "New Heading or Item", comment: "Key bar button"), symbol: "plus", action: .keys("M-RET")),
845 "todo": Item(label: "TODO", symbol: nil, action: .keys("C-c C-t")),
846 "act": Item(label: String(localized: "Act at Point", comment: "Key bar button"), symbol: "checkmark.square", action: .keys("C-c C-c")),
847 "plan": Item(label: String(localized: "Plan", comment: "Key bar button: a menu of Schedule, Deadline and Tags"), symbol: "calendar.badge.clock", action: .plan),
848 "schedule": Item(label: String(localized: "Schedule", comment: "Key bar button"), symbol: "calendar", action: .keys("C-c C-s")),
849 "deadline": Item(label: String(localized: "Deadline", comment: "Key bar button"), symbol: "calendar.badge.exclamationmark", action: .keys("C-c C-d")),
850 "tags": Item(label: String(localized: "Tags", comment: "Key bar button"), symbol: "tag", action: .keys("C-c C-q")),
851 "open-link": Item(label: String(localized: "Open Link", comment: "Key bar button"), symbol: "link", action: .keys("C-c C-o")),
852 "bold": Item(label: String(localized: "Bold", comment: "Key bar button"), symbol: "bold", action: .command("org.emphasize.bold")),
853 "italic": Item(label: String(localized: "Italic", comment: "Key bar button"), symbol: "italic", action: .command("org.emphasize.italic")),
854 "code": Item(label: String(localized: "Code", comment: "Key bar button"), symbol: "chevron.left.forwardslash.chevron.right", action: .command("org.emphasize.code")),
855 "hide-keyboard": Item(label: String(localized: "Hide Keyboard"), symbol: "keyboard.chevron.compact.down", action: .hideKeyboard),
856 ]
857
858 /// The bar's buttons in order. On iPad, where it is wider, Plan's three are buttons.
859 static func layout(regular: Bool) -> [String] {
860 ["commands", "fold", "promote", "demote", "move-up", "move-down", "new-heading", "todo", "act"]
861 + (regular ? ["schedule", "deadline", "tags"] : ["plan"]) + ["hide-keyboard"]
862 }
863
864 /// The bar's buttons are at least 44 points tall, scaled with the text size up to here.
865 static let largestSize = DynamicTypeSize.accessibility2
866 static let target: CGFloat = 44
867 static let padding: CGFloat = 4
868 /// The widest a button gets where the bar has room.
869 static let widest: CGFloat = 64
870 @ScaledMetric(relativeTo: .body) private var size = KeyBar.target
871
872 var body: some View {
873 HStack(spacing: 0) {
874 ForEach(Self.layout(regular: sizeClass == .regular), id: \.self) { id in
875 if let item = Self.items[id] { button(item) }
876 }
877 }
878 .labelStyle(.iconOnly)
879 .padding(.horizontal, 6)
880 .padding(.vertical, Self.padding)
881 .frame(maxWidth: .infinity)
882 .background(.bar)
883 }
884
885 @ViewBuilder
886 private func button(_ item: Item) -> some View {
887 switch item.action {
888 case .plan:
889 Menu {
890 ForEach(["schedule", "deadline", "tags"], id: \.self) { id in
891 if let entry = Self.items[id], case .keys(let keys) = entry.action {
892 Button(entry.label, systemImage: entry.symbol ?? "") { editor.run(keys: keys) }
893 }
894 }
895 } label: {
896 label(item).modifier(KeyShape(size: size))
897 }
898 .accessibilityLabel(item.label)
899 default:
900 Button {
901 switch item.action {
902 case .keys(let keys): editor.run(keys: keys)
903 case .command(let id): editor.run(id)
904 case .palette: palette()
905 case .hideKeyboard: editor.textView.resignFirstResponder()
906 case .plan: break
907 }
908 } label: {
909 label(item)
910 }
911 .buttonStyle(KeyStyle(size: size))
912 .accessibilityLabel(item.label)
913 }
914 }
915
916 /// The buttons grow taller with the text size, but their symbols stop growing here, so
917 /// that they fit the button's share of the width.
918 static let largestSymbolSize = DynamicTypeSize.xxxLarge
919
920 @ViewBuilder
921 private func label(_ item: Item) -> some View {
922 Group {
923 if let symbol = item.symbol {
924 Label(item.label, systemImage: symbol)
925 } else {
926 // A word is wider than a symbol, so it stays at the default size.
927 Text(item.label).font(.callout.weight(.semibold)).lineLimit(1).minimumScaleFactor(0.5)
928 .dynamicTypeSize(...DynamicTypeSize.large)
929 }
930 }
931 .dynamicTypeSize(...Self.largestSymbolSize)
932 }
933}
934
935/// A key bar button's look: a tinted label on a rounded tile, `size` tall, sharing the bar's
936/// width with the others. The whole share is the touch target.
937private struct KeyShape: ViewModifier {
938 let size: CGFloat
939 var pressed = false
940
941 func body(content: Content) -> some View {
942 content
943 .foregroundStyle(.tint)
944 .frame(maxWidth: KeyBar.widest, minHeight: size)
945 .background(.fill.tertiary, in: .rect(cornerRadius: 10))
946 .opacity(pressed ? 0.5 : 1)
947 .padding(.horizontal, 2)
948 .frame(maxWidth: .infinity)
949 .contentShape(.rect)
950 }
951}
952
953private struct KeyStyle: ButtonStyle {
954 let size: CGFloat
955
956 func makeBody(configuration: Configuration) -> some View {
957 configuration.label.modifier(KeyShape(size: size, pressed: configuration.isPressed))
958 }
959}
960
961/// A command's question: text with choices, a date, or fast selection by keys.
962struct PromptSheet: View {
963 let prompt: Prompt
964 let answer: (String?) -> Void
965 @State private var text = ""
966 @State private var date = Date()
967 @State private var withTime = false
968 @State private var keys: [FastSelection.Input] = []
969
970 var body: some View {
971 NavigationStack {
972 Form {
973 if let fast = prompt.fast {
974 fastSection(fast)
975 } else {
976 Section {
977 TextField(prompt.message, text: $text)
978 .autocorrectionDisabled()
979 .textInputAutocapitalization(.never)
980 .onSubmit { answer(text) }
981 } footer: {
982 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
983 }
984 if prompt.date != nil {
985 DatePicker("Date", selection: $date, displayedComponents: [.date])
986 .datePickerStyle(.graphical)
987 .onChange(of: date) { text = QuestionField.stamp(date, withTime: withTime) }
988 Toggle("Time", isOn: $withTime)
989 .onChange(of: withTime) {
990 if withTime { date = QuestionField.timed(date) }
991 text = QuestionField.stamp(date, withTime: withTime)
992 }
993 if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
994 }
995 if !prompt.choices.isEmpty {
996 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
997 Section("Choices") {
998 ForEach(matching.prefix(50), id: \.self) { choice in
999 Button(choice) { choose(choice) }
1000 }
1001 }
1002 }
1003 }
1004 }
1005 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
1006 .navigationBarTitleDisplayMode(.inline)
1007 .toolbar {
1008 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
1009 if prompt.fast == nil || prompt.fast?.multiple == true {
1010 ToolbarItem(placement: .confirmationAction) {
1011 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
1012 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
1013 }
1014 }
1015 }
1016 }
1017 .onAppear {
1018 text = prompt.initial
1019 date = prompt.date?.defaultDate ?? Calendar.current.startOfDay(for: Date())
1020 }
1021 }
1022
1023 /// With a separator (tags), what's typed after the last one.
1024 private var lastPart: String {
1025 guard let separator = prompt.completionSeparator else { return text }
1026 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
1027 }
1028
1029 private func choose(_ choice: String) {
1030 guard let separator = prompt.completionSeparator else {
1031 text = choice
1032 if prompt.date == nil { answer(choice) }
1033 return
1034 }
1035 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
1036 if parts.isEmpty { parts = [""] }
1037 parts[parts.count - 1] = choice
1038 text = parts.joined(separator: String(separator)) + String(separator)
1039 }
1040
1041 @ViewBuilder
1042 private func fastSection(_ fast: FastSelection) -> some View {
1043 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
1044 Section {
1045 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
1046 Button {
1047 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
1048 } label: {
1049 HStack {
1050 Text(option.name).foregroundStyle(.primary)
1051 Spacer()
1052 if current.contains(option.name) { Image(systemName: "checkmark") }
1053 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
1054 }
1055 }
1056 }
1057 if !fast.multiple {
1058 Button("No Keyword") { answer(" ") }
1059 }
1060 } footer: {
1061 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
1062 }
1063 }
1064}
1065
1066/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
1067/// A src block's code is highlighted as its language.
1068struct BlockEditSheet: View {
1069 let edit: BlockEdit
1070 let theme: MobileTheme
1071 let finish: (String?) -> Void
1072 @State private var text: String?
1073
1074 var body: some View {
1075 NavigationStack {
1076 Group {
1077 if let text {
1078 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
1079 }
1080 }
1081 .padding(.horizontal, 8)
1082 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
1083 .navigationBarTitleDisplayMode(.inline)
1084 .toolbar {
1085 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
1086 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
1087 }
1088 }
1089 .onAppear { text = edit.content }
1090 }
1091}
1092
1093/// A text view for code, restyled with the editor's highlighter after each change.
1094struct CodeTextView: UIViewRepresentable {
1095 let text: String
1096 let language: String?
1097 let theme: MobileTheme
1098 let changed: (String) -> Void
1099
1100 func makeUIView(context: Context) -> UITextView {
1101 let view = UITextView()
1102 view.autocorrectionType = .no
1103 view.autocapitalizationType = .none
1104 view.smartQuotesType = .no
1105 view.smartDashesType = .no
1106 view.spellCheckingType = .no
1107 view.keyboardDismissMode = .interactive
1108 view.backgroundColor = .clear
1109 view.text = text
1110 view.delegate = context.coordinator
1111 context.coordinator.style(view)
1112 DispatchQueue.main.async { view.becomeFirstResponder() }
1113 return view
1114 }
1115
1116 func updateUIView(_ view: UITextView, context: Context) {
1117 context.coordinator.parent = self
1118 }
1119
1120 func makeCoordinator() -> Coordinator { Coordinator(self) }
1121
1122 @MainActor
1123 final class Coordinator: NSObject, UITextViewDelegate {
1124 var parent: CodeTextView
1125 init(_ parent: CodeTextView) { self.parent = parent }
1126
1127 func textViewDidChange(_ view: UITextView) {
1128 parent.changed(view.text)
1129 style(view)
1130 }
1131
1132 /// The theme's font and color, then the language's token colors.
1133 func style(_ view: UITextView) {
1134 let storage = view.textStorage
1135 let whole = NSRange(location: 0, length: storage.length)
1136 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
1137 storage.beginEditing()
1138 storage.setAttributes(base, range: whole)
1139 if let language = parent.language {
1140 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
1141 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
1142 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
1143 }
1144 }
1145 storage.endEditing()
1146 view.typingAttributes = base
1147 }
1148 }
1149}
1150
1151/// The editor's commands, those that don't apply at the caret greyed with the reason.
1152struct CommandPalette: View {
1153 let editor: MobileEditor
1154 /// The pane commands are offered (on iPad), and those for more than one pane.
1155 var panes = false
1156 var split = false
1157 /// Recovery versions and sync conflict copies of the file, which their commands show.
1158 var recoveries = 0
1159 var syncCopies = 0
1160 /// Called with the chosen command before the palette closes.
1161 let choose: (String) -> Void
1162
1163 static let viewCommands: [(id: String, title: String)] = [
1164 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
1165 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
1166 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
1167 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
1168 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
1169 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
1170 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
1171 ("app.archive", "Archive Subtree"), ("app.copy-rich-text", "Copy as Rich Text"), ("app.export.html-open", "Export to HTML and Open"),
1172 ("app.export-body-only", "Turn Body-Only Export On or Off"),
1173 ("app.export.icalendar-agenda", "Export Agenda Files to iCalendar"), ("app.export.icalendar-combined", "Combine Agenda Files into iCalendar"),
1174 ("app.publish", "Publish Project…"), ("app.publish.all", "Publish All Projects"), ("app.publish.current-file", "Publish Current File"),
1175 ("app.publish.current-project", "Publish Current Project"),
1176 ("app.toggle-markup", "Show or Hide Markup"), ("app.word-count", "Word Count"),
1177 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"),
1178 ("org.toggle-inline-images", "Show or Hide Inline Images"), ("org.toggle-inline-images-linked", "Show or Hide Inline Images, Including Described Links"), ("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"),
1179 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
1180 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
1181 ("org.table.expand", "Expand Table Columns"),
1182 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"),
1183 ("app.table-export.tsv", "Export Table as TSV…"), ("app.plot", "Plot Table"),
1184 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
1185 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
1186 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"), ("app.node.graph", "Show Node Graph"),
1187 ("app.node.rename-from-front-matter", "Rename Note from Front Matter"),
1188 ("app.node.rename", "Rename Note…"),
1189 ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"),
1190 ("app.node.silo-find", "Find Note in Silo…"),
1191 ("app.node.silo-create", "New Note in Silo…"),
1192 ("app.node.sequence-new-parent", "New Sequence Note…"),
1193 ("app.node.sequence-new-child", "New Child Sequence Note…"),
1194 ("app.node.sequence-new-sibling", "New Sibling Sequence Note…"),
1195 ("app.node.sequence-new-child-of-current", "New Child of This Note…"),
1196 ("app.node.sequence-new-sibling-of-current", "New Sibling of This Note…"),
1197 ("app.node.sequence-find", "Find Sequence Relatives…"),
1198 ("app.node.sequence-next-sibling", "Next Sibling Note"),
1199 ("app.node.sequence-previous-sibling", "Previous Sibling Note"),
1200 ("app.node.sequence-reparent", "Reparent Note…"),
1201 ("app.node.sequence-reparent-recursive", "Reparent Note with Descendants…"),
1202 ("app.node.sequence-rename-as-parent", "Rename Note as Sequence Parent"),
1203 ("app.node.sequence-convert", "Convert Note Sequence Scheme"),
1204 ("app.node.sequence-link", "Insert Sequence Link…"),
1205 ("app.node.sequence-hierarchy", "Sequence Hierarchy…"),
1206 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
1207 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
1208 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
1209 ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
1210 ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
1211 ("app.attach.attach", "Attach File…"), ("app.attach.photo", "Attach Photo or Video…"), ("app.attach.camera", "Take Photo…"),
1212 ("app.attach.scan", "Scan Document…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
1213 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
1214 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
1215 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
1216 ]
1217
1218 /// The commands and their keys, and why those that don't apply at the caret don't, worked
1219 /// out once when the palette opens rather than on every keystroke in the search field.
1220 @State private var rows: [CommandRow]?
1221
1222 var body: some View {
1223 CommandList(rows: rows ?? [], choose: choose)
1224 .onAppear {
1225 guard rows == nil else { return }
1226 rows = commandRows()
1227 }
1228 }
1229
1230 private func commandRows() -> [CommandRow] {
1231 let context = editor.editContext()
1232 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
1233 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
1234 var seen = Set<String>()
1235 let macros = editor.namedMacros.names.map { (id: NamedMacros.commandPrefix + $0, title: $0) }
1236 return (paneCommands + Self.viewCommands + Commands.everything.map { ($0.id, $0.title) } + macros)
1237 .filter { !AppStoreCommands.hidden.contains($0.id) && Self.offered($0.id) && seen.insert($0.id).inserted }
1238 .map { command in
1239 CommandRow(id: command.id, title: CommandTitle.localized(command.title), keys: editor.keymap.keyLabels(for: command.id).first,
1240 reason: reason(command.id, context))
1241 }
1242 }
1243
1244 /// Commands for a camera or scanner this device lacks aren't listed.
1245 private static func offered(_ id: String) -> Bool {
1246 switch id {
1247 case "app.attach.camera": CameraPicker.isAvailable
1248 case "app.attach.scan": DocumentScanner.isAvailable
1249 default: true
1250 }
1251 }
1252
1253 private func reason(_ id: String, _ context: EditContext) -> String? {
1254 switch id {
1255 case "app.recovery": return recoveries > 0 ? nil : String(localized: "No Recovery Versions")
1256 case "app.sync-conflicts": return syncCopies > 0 ? nil : String(localized: "No sync conflict copies", comment: "Why Resolve Sync Conflicts… is greyed in the Commands list")
1257 default: return editor.applies(id, in: context) ? nil : CommandReason.reason(for: id, in: context)
1258 }
1259 }
1260}
1261/// A table as CSV or TSV, for the save dialog.
1262struct TableFile: FileDocument {
1263 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
1264 let text: String
1265 let type: UTType
1266
1267 init(text: String, type: UTType) {
1268 self.text = text
1269 self.type = type
1270 }
1271
1272 init(configuration: ReadConfiguration) throws {
1273 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
1274 type = configuration.contentType
1275 }
1276
1277 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
1278 FileWrapper(regularFileWithContents: Data(text.utf8))
1279 }
1280}
1281/// A plotted table, as the Mac's plot sheet shows it.
1282struct PlotScreen: View {
1283 let plot: TablePlot.Plot
1284 @Environment(\.dismiss) private var dismiss
1285
1286 var body: some View {
1287 NavigationStack {
1288 PlotChart(plot)
1289 .navigationTitle("Plot")
1290 .navigationBarTitleDisplayMode(.inline)
1291 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
1292 }
1293 }
1294}
1295/// A file from the photo picker, copied out of the picker's temporary place with its name.
1296struct PickedFile: Transferable {
1297 let url: URL
1298
1299 static var transferRepresentation: some TransferRepresentation {
1300 FileRepresentation(importedContentType: .item) { received in
1301 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1302 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1303 let url = folder.appendingPathComponent(received.file.lastPathComponent)
1304 try FileManager.default.copyItem(at: received.file, to: url)
1305 return PickedFile(url: url)
1306 }
1307 }
1308}
1309
1310/// The passphrase sheet for org-crypt, its new text applied in the editor.
1311struct CryptScreen: View {
1312 let request: CryptRequest
1313 let session: DocumentSession
1314 let editor: MobileEditor?
1315 let report: (String) -> Void
1316 @Environment(\.dismiss) private var dismiss
1317
1318 var body: some View {
1319 NavigationStack {
1320 CryptSheet(request: request, text: { session.document?.text ?? "" }, apply: apply) { message in
1321 dismiss()
1322 if let message { report(message) }
1323 }
1324 .navigationBarTitleDisplayMode(.inline)
1325 }
1326 }
1327
1328 private func apply(_ new: String) {
1329 guard let editor else { return }
1330 let context = editor.editContext()
1331 let caret = min(context.caret, (new as NSString).length)
1332 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1333 }
1334}
1335/// The pane an editor screen made for itself, closed with the screen.
1336@MainActor
1337final class PaneHolder {
1338 var pane: EditorPane?
1339 nonisolated(unsafe) var release: (() -> Void)?
1340
1341 deinit {
1342 guard let release else { return }
1343 Task { @MainActor in release() }
1344 }
1345}
1346
1347/// A command's result or refusal, over the screen until it is tapped or for four seconds, and
1348/// read out by VoiceOver.
1349private struct MessageView: ViewModifier {
1350 @Binding var message: String?
1351 let edge: VerticalEdge
1352
1353 func body(content: Content) -> some View {
1354 content.overlay(alignment: edge == .top ? .top : .bottom) {
1355 if let message {
1356 Text(message).font(.callout).multilineTextAlignment(.center)
1357 .padding(.horizontal, 14).padding(.vertical, 8)
1358 .glassEffect(.regular, in: .rect(cornerRadius: 18))
1359 .padding(8)
1360 .onTapGesture { self.message = nil }
1361 .task(id: message) {
1362 try? await Task.sleep(for: .seconds(4))
1363 if self.message == message { self.message = nil }
1364 }
1365 }
1366 }
1367 .onChange(of: message) { _, message in
1368 if let message { AccessibilityNotification.Announcement(message).post() }
1369 }
1370 }
1371}
1372
1373extension View {
1374 /// Shows `message` in the one message view, at the top or bottom of the screen.
1375 func message(_ message: Binding<String?>, edge: VerticalEdge = .bottom) -> some View {
1376 modifier(MessageView(message: message, edge: edge))
1377 }
1378}
1379
1380/// The screen's title, unless a split shows the focused pane's.
1381private struct EditorTitle: ViewModifier {
1382 let title: String
1383 let shown: Bool
1384
1385 func body(content: Content) -> some View {
1386 if shown {
1387 content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1388 } else {
1389 content
1390 }
1391 }
1392}
1393#endif