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