Sources/OrgstarMobile/EditorScreen.swift
1344 lines · 68683 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 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 }
646
647 /// org-attach's commands for the entry at the caret.
648 private var attachActions: AttachActions {
649 AttachActions(
650 entry: {
651 guard let editor else { return nil }
652 let context = editor.editContext()
653 return Attachments.Entry(text: context.text, offset: context.caret, path: path, options: context.options)
654 },
655 apply: { new, caret in
656 guard let editor else { return }
657 let context = editor.editContext()
658 let caret = min(caret ?? context.caret, (new as NSString).length)
659 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
660 },
661 show: { message = $0 },
662 ask: { prompt = PromptRequest(prompt: $0, reply: $1) },
663 storeLink: { _ = StoredLink.add($0, to: &model.storedLinks) },
664 open: { follow(OrgLink(type: "file", path: $0, raw: "file:" + $0)) },
665 reveal: { dir in
666 if let url = URL(string: "shareddocuments://" + (dir.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? dir)) { openURL(url) }
667 },
668 pick: { attaching = $0 })
669 }
670
671 /// Photos and videos attached under the names Photos gives them, linked at the caret.
672 private func attachPhotos(_ items: [PhotosPickerItem]) {
673 Task { @MainActor in
674 var urls: [URL] = []
675 for item in items {
676 if let picked = try? await item.loadTransferable(type: PickedFile.self) { urls.append(picked.url) }
677 }
678 if urls.count < items.count { message = "Can't read \(items.count - urls.count) of the items" }
679 if !urls.isEmpty { attachActions.drop(urls, method: .attach, attachMethod: .mv) }
680 }
681 }
682
683 /// `org-table-import`: a TSV, CSV or space-separated file becomes a table at the caret.
684 private func importTable(_ result: Result<URL, Error>) {
685 guard case .success(let url) = result, let editor else { return }
686 let scoped = url.startAccessingSecurityScopedResource()
687 defer { if scoped { url.stopAccessingSecurityScopedResource() } }
688 guard let contents = try? String(contentsOf: url, encoding: .utf8) else { return message = "Can't read \(url.lastPathComponent)" }
689 _ = editor.perform(ImportTable(contents: contents))
690 }
691
692 /// The export formats for the subtree at the caret, as the Mac's export sheet's scope.
693 private func exportSubtree() {
694 guard let context = editor?.editContext() else { return }
695 guard ExportScope.subtree(context.text, at: context.caret) != nil else { return message = "Not in a subtree" }
696 sheet = .exportSubtree(context.caret)
697 }
698
699 /// `org-html-export-to-html` and open: the page in Quick Look, from a temporary file.
700 private func exportHTMLAndOpen() {
701 guard let text = session.document(of: path)?.text else { return }
702 let html = OrgExport.html(text, path: path, theme: model.theme, bodyOnly: ExportSettings.saved(for: path).bodyOnly)
703 let name = ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, settings: OrgPreferences.orgSettings()), extension: "html")
704 .lastPathComponent
705 do {
706 previewed = try HTMLPreview.write(html, directory: URL(fileURLWithPath: path).deletingLastPathComponent(), name: name)
707 } catch {
708 message = "Can't export \(name): \(error.localizedDescription)"
709 }
710 }
711
712 /// The agenda files' calendars written beside them, or combined in one shown in Quick Look,
713 /// whose share button saves or sends it.
714 private func agendaCalendars(combined: Bool) {
715 guard let calendars = AgendaCalendars(model: model) else { return message = "No agenda files" }
716 guard combined else { return message = calendars.exportEach() }
717 do {
718 previewed = try calendars.combined()
719 } catch {
720 message = "Can't export: \(error.localizedDescription)"
721 }
722 }
723
724 /// `org-publish` and its variants, for the `[[publish]]` projects in config.toml.
725 private func publish(_ id: String) {
726 guard let all = publishProjects() else { return }
727 let current = Publish.projects(containing: path, in: all)
728 switch id {
729 case "app.publish.all":
730 publish(all.map(\.name))
731 case "app.publish.current-file":
732 guard let project = current.first else { return message = "File is not part of any known project" }
733 publish([project.name], only: path)
734 case "app.publish.current-project":
735 guard let project = current.first else { return message = "File is not part of any known project" }
736 publish([project.name])
737 default:
738 prompt = PromptRequest(prompt: Prompt(key: "project", message: "Publish project:", choices: all.map(\.name))) { answer in
739 if let answer, all.contains(where: { $0.name == answer }) { publish([answer]) }
740 }
741 }
742 }
743
744 /// The projects in config.toml, each publishing to the folder chosen for it; nil, with a
745 /// message, when there are none.
746 private func publishProjects() -> [PublishProject]? {
747 let config = (try? String(contentsOf: UserConfig.file("config.toml"), encoding: .utf8)) ?? ""
748 let loaded = Publish.projects(fromConfig: config, root: workspace.rootPaths.first)
749 if let problem = loaded.problems.first { message = problem }
750 guard !loaded.projects.isEmpty else {
751 message = "No [[publish]] projects in config.toml"
752 return nil
753 }
754 return PublishFolders.shared.applied(to: loaded.projects)
755 }
756
757 /// Publishes the projects named, `only` that file when given. A project that publishes
758 /// outside the folders added to orgstar asks for its folder first, once.
759 private func publish(_ names: [String], only: String? = nil) {
760 guard let all = publishProjects() else { return }
761 let chosen = all.filter { names.contains($0.name) }
762 do {
763 if let project = try PublishFolders.shared.needed(chosen, all: all, roots: workspace.rootPaths).first {
764 message = "Choose the folder \(project.name) publishes to"
765 publishFolder = PublishFolderRequest(project: project.name) { publish(names, only: only) }
766 choosingPublishFolder = true
767 return
768 }
769 if let project = try Publish.expand(chosen, all: all).first(where: { !FileManager.default.fileExists(atPath: $0.baseDirectory) }) {
770 return message = "Can't read \(project.name)'s base-directory, \(OrgPaths.abbreviatingWithTilde(project.baseDirectory))"
771 }
772 let read = { (file: String) -> String? in
773 session.exportText(of: file)
774 }
775 let codeStyle = HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme)
776 // As the Export menu: no author unless the file has #+AUTHOR:.
777 let report = try Publish.publish(chosen, all: all, only: only, author: "", read: read) { function, text, file, bodyOnly in
778 try Publish.export(function, text: text, path: file, bodyOnly: bodyOnly, settings: OrgPreferences.orgSettings(), codeStyle: codeStyle, author: "")
779 }
780 let note = session.openPaths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
781 message = (report.skipped.isEmpty ? String(localized: "Published \(report.published.count) files")
782 : String(localized: "Published \(report.published.count) files, \(report.skipped.count) up to date")) + note
783 } catch {
784 message = "\(error)"
785 }
786 }
787
788 /// org-crypt's commands at the caret, through the passphrase sheet.
789 private func crypt(_ id: String) {
790 if let feature = ProFeature.required(byCommand: id), !ProAccess.shared.allows(feature) { return }
791 guard let editor else { return }
792 let context = editor.editContext()
793 switch id {
794 case "app.crypt.forget-passphrase":
795 session.forgetPassphrase(for: path)
796 message = "Passphrase forgotten for \((path as NSString).lastPathComponent)"
797 case "app.crypt.encrypt-entries":
798 sheet = .crypt(CryptRequest(mode: .encryptAll(tag: OrgPreferences.cryptTag()), path: path, offset: context.caret))
799 default:
800 guard OrgCrypt.heading(context.text, at: context.caret) != nil else { return message = "Before first headline" }
801 let encrypted = OrgCrypt.encryptedRange(context.text, at: context.caret) != nil
802 if id == "app.crypt.encrypt-entry" {
803 guard !encrypted else { return message = "The entry is encrypted already" }
804 sheet = .crypt(CryptRequest(mode: .encrypt, path: path, offset: context.caret))
805 } else {
806 guard encrypted else { return message = "Not an encrypted entry" }
807 sheet = .crypt(CryptRequest(mode: id == "app.crypt.open-entry" ? .open : .decryptInPlace, path: path, offset: context.caret))
808 }
809 }
810 }
811
812 /// `org-plot/gnuplot`, drawn by Swift Charts: written to `file:` when the options name
813 /// one, else shown.
814 private func plotTable() {
815 guard let editor else { return }
816 let context = editor.editContext()
817 do {
818 let plot = try TablePlot.plot(context.text, at: context.caret)
819 if let url = PlotOutput.file(plot, directory: URL(fileURLWithPath: path).deletingLastPathComponent()) {
820 try PlotOutput.write(plot, to: url)
821 message = "Plot written to \(url.lastPathComponent)" + (PlotOutput.note(plot).map { ". " + $0 } ?? "")
822 if editor.showsImages { editor.restyleAll() }
823 } else {
824 try PlotOutput.check(plot)
825 sheet = .plot(plot)
826 if let note = PlotOutput.note(plot) { message = note }
827 }
828 } catch {
829 message = "\(error)"
830 }
831 }
832
833 /// `org-table-export` of the table at the caret, as CSV or TSV.
834 /// Words, characters and reading time of the selection, or of the file.
835 private func wordCount() -> String {
836 guard let editor else { return "No file is open" }
837 let text = editor.document.text as NSString
838 let selection = editor.textView.selectedRange
839 let selected = selection.length > 0 && NSMaxRange(selection) <= text.length
840 let counts = TextStats.region(selected ? text.substring(with: selection) : text as String)
841 return (selected ? "Selection: " : "") + TextStats.summary(words: counts.words, characters: counts.characters)
842 }
843
844 private func exportTable(csv: Bool) {
845 guard let editor else { return }
846 let context = editor.editContext()
847 guard let text = ImportTable.exportText(context.text, at: context.caret, path: csv ? "table.csv" : "table.tsv") else {
848 return message = "No table at point"
849 }
850 exportedTable = TableFile(text: text, type: csv ? .commaSeparatedText : .tabSeparatedText)
851 }
852
853 /// `org-refile` of the entry at the caret, to a target worked out again from the files
854 /// now, as the agenda's Refile… does.
855 func refile(to target: RefileTarget, keep: Bool = false) {
856 guard let editor, let path = session.path else { return }
857 let caret = editor.editContext().caret
858 guard let current = workspace.refileTargets(openPath: path, document: session.document).first(where: { $0.label == target.label }) else {
859 message = "Can't find \(target.label) any more."
860 return
861 }
862 message = session.refile(to: current, from: (path, caret), keep: keep)
863 }
864}
865
866/// The editor's text view, with the Org key bar over the keyboard.
867struct EditorTextView: UIViewRepresentable {
868 let editor: MobileEditor
869 /// This pane's view of the editor.
870 let view: UITextView
871 let palette: () -> Void
872
873 func makeUIView(context: Context) -> UITextView {
874 let bar = UIHostingController(rootView: KeyBar(editor: editor, palette: palette).dynamicTypeSize(...KeyBar.largestSize))
875 bar.view.frame = CGRect(x: 0, y: 0, width: 400, height: 2 * KeyBar.padding + KeyBar.target)
876 bar.view.backgroundColor = .clear
877 // As tall as its buttons: the input accessory takes the intrinsic height.
878 bar.sizingOptions = .intrinsicContentSize
879 bar.safeAreaRegions = []
880 bar.view.autoresizingMask = .flexibleHeight
881 view.inputAccessoryView = bar.view
882 context.coordinator.bar = bar
883 // The bar's height follows the text size.
884 view.registerForTraitChanges([UITraitPreferredContentSizeCategory.self]) { (view: UITextView, _) in
885 view.inputAccessoryView?.invalidateIntrinsicContentSize()
886 view.reloadInputViews()
887 }
888 return view
889 }
890
891 func updateUIView(_ view: UITextView, context: Context) {}
892
893 func makeCoordinator() -> Coordinator { Coordinator() }
894
895 final class Coordinator {
896 var bar: UIViewController?
897 }
898}
899
900/// A command's question: text with choices, a date, or fast selection by keys.
901struct PromptSheet: View {
902 let prompt: Prompt
903 let answer: (String?) -> Void
904 @State private var text = ""
905 @State private var date = Date()
906 @State private var withTime = false
907 @State private var keys: [FastSelection.Input] = []
908
909 var body: some View {
910 NavigationStack {
911 Form {
912 if let fast = prompt.fast {
913 fastSection(fast)
914 } else {
915 Section {
916 TextField(prompt.message, text: $text)
917 .autocorrectionDisabled()
918 .textInputAutocapitalization(.never)
919 .onSubmit { answer(text) }
920 } footer: {
921 if prompt.date != nil { Text("Org's date syntax works too: +2d, fri, 14:00") }
922 }
923 if prompt.date != nil {
924 DatePicker("Date", selection: $date, displayedComponents: [.date])
925 .datePickerStyle(.graphical)
926 .onChange(of: date) { text = QuestionField.stamp(date, withTime: withTime) }
927 Toggle("Time", isOn: $withTime)
928 .onChange(of: withTime) {
929 if withTime { date = QuestionField.timed(date) }
930 text = QuestionField.stamp(date, withTime: withTime)
931 }
932 if withTime { DatePicker("Time", selection: $date, displayedComponents: .hourAndMinute) }
933 }
934 if !prompt.choices.isEmpty {
935 let matching = prompt.choices.filter { lastPart.isEmpty || $0.localizedCaseInsensitiveContains(lastPart) }
936 Section("Choices") {
937 ForEach(matching.prefix(50), id: \.self) { choice in
938 Button(choice) { choose(choice) }
939 }
940 }
941 }
942 }
943 }
944 .navigationTitle(prompt.message.trimmingCharacters(in: CharacterSet(charactersIn: ": ")))
945 .navigationBarTitleDisplayMode(.inline)
946 .toolbar {
947 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { answer(nil) } }
948 if prompt.fast == nil || prompt.fast?.multiple == true {
949 ToolbarItem(placement: .confirmationAction) {
950 Button("Done") { answer(prompt.fast == nil ? text : FastSelection.encode(keys)) }
951 .disabled(prompt.requireMatch && prompt.fast == nil && !prompt.choices.isEmpty && !prompt.choices.contains(text))
952 }
953 }
954 }
955 }
956 .onAppear {
957 text = prompt.initial
958 date = prompt.date?.defaultDate ?? Calendar.current.startOfDay(for: Date())
959 }
960 }
961
962 /// With a separator (tags), what's typed after the last one.
963 private var lastPart: String {
964 guard let separator = prompt.completionSeparator else { return text }
965 return String(text.split(separator: separator, omittingEmptySubsequences: false).last ?? "")
966 }
967
968 private func choose(_ choice: String) {
969 guard let separator = prompt.completionSeparator else {
970 text = choice
971 if prompt.date == nil { answer(choice) }
972 return
973 }
974 var parts = text.split(separator: separator, omittingEmptySubsequences: false).map(String.init)
975 if parts.isEmpty { parts = [""] }
976 parts[parts.count - 1] = choice
977 text = parts.joined(separator: String(separator)) + String(separator)
978 }
979
980 @ViewBuilder
981 private func fastSection(_ fast: FastSelection) -> some View {
982 let current = fast.multiple ? fast.tags(after: keys) ?? [] : []
983 Section {
984 ForEach(Array(fast.options.enumerated()), id: \.offset) { _, option in
985 Button {
986 if fast.multiple { keys.append(.key(option.key)) } else { answer(String(option.key)) }
987 } label: {
988 HStack {
989 Text(option.name).foregroundStyle(.primary)
990 Spacer()
991 if current.contains(option.name) { Image(systemName: "checkmark") }
992 Text(String(option.key)).font(.caption.monospaced()).foregroundStyle(.secondary)
993 }
994 }
995 }
996 if !fast.multiple {
997 Button("No Keyword") { answer(" ") }
998 }
999 } footer: {
1000 if fast.multiple, !fast.inherited.isEmpty { Text("Inherited: :" + fast.inherited.joined(separator: ":") + ":") }
1001 }
1002 }
1003}
1004
1005/// `org-edit-special` and `org-table-edit-field`: the text edited apart, put back with Save.
1006/// A src block's code is highlighted as its language.
1007struct BlockEditSheet: View {
1008 let edit: BlockEdit
1009 let theme: MobileTheme
1010 let finish: (String?) -> Void
1011 @State private var text: String?
1012
1013 var body: some View {
1014 NavigationStack {
1015 Group {
1016 if let text {
1017 CodeTextView(text: text, language: edit.language, theme: theme) { self.text = $0 }
1018 }
1019 }
1020 .padding(.horizontal, 8)
1021 .navigationTitle(edit.title.replacingOccurrences(of: "Editing ", with: "").capitalized(with: nil))
1022 .navigationBarTitleDisplayMode(.inline)
1023 .toolbar {
1024 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { finish(nil) } }
1025 ToolbarItem(placement: .confirmationAction) { Button("Save") { finish(text ?? edit.content) } }
1026 }
1027 }
1028 .onAppear { text = edit.content }
1029 }
1030}
1031
1032/// A text view for code, restyled with the editor's highlighter after each change.
1033struct CodeTextView: UIViewRepresentable {
1034 let text: String
1035 let language: String?
1036 let theme: MobileTheme
1037 let changed: (String) -> Void
1038
1039 func makeUIView(context: Context) -> UITextView {
1040 let view = UITextView()
1041 view.autocorrectionType = .no
1042 view.autocapitalizationType = .none
1043 view.smartQuotesType = .no
1044 view.smartDashesType = .no
1045 view.spellCheckingType = .no
1046 view.keyboardDismissMode = .interactive
1047 view.backgroundColor = .clear
1048 view.text = text
1049 view.delegate = context.coordinator
1050 context.coordinator.style(view)
1051 DispatchQueue.main.async { view.becomeFirstResponder() }
1052 return view
1053 }
1054
1055 func updateUIView(_ view: UITextView, context: Context) {
1056 context.coordinator.parent = self
1057 }
1058
1059 func makeCoordinator() -> Coordinator { Coordinator(self) }
1060
1061 @MainActor
1062 final class Coordinator: NSObject, UITextViewDelegate {
1063 var parent: CodeTextView
1064 init(_ parent: CodeTextView) { self.parent = parent }
1065
1066 func textViewDidChange(_ view: UITextView) {
1067 parent.changed(view.text)
1068 style(view)
1069 }
1070
1071 /// The theme's font and color, then the language's token colors.
1072 func style(_ view: UITextView) {
1073 let storage = view.textStorage
1074 let whole = NSRange(location: 0, length: storage.length)
1075 let base: [NSAttributedString.Key: Any] = [.font: parent.theme.font, .foregroundColor: parent.theme.foreground]
1076 storage.beginEditing()
1077 storage.setAttributes(base, range: whole)
1078 if let language = parent.language {
1079 for run in MobileEditor.highlighter.highlights(language: language, code: storage.string) {
1080 guard let key = run.category.themeKey, let color = parent.theme.color(key), run.range.upperBound <= storage.length else { continue }
1081 storage.addAttribute(.foregroundColor, value: color, range: NSRange(location: run.range.lowerBound, length: run.range.count))
1082 }
1083 }
1084 storage.endEditing()
1085 view.typingAttributes = base
1086 }
1087 }
1088}
1089
1090/// The editor's commands, those that don't apply at the caret greyed with the reason.
1091struct CommandPalette: View {
1092 let editor: MobileEditor
1093 /// The pane commands are offered (on iPad), and those for more than one pane.
1094 var panes = false
1095 var split = false
1096 /// Recovery versions and sync conflict copies of the file, which their commands show.
1097 var recoveries = 0
1098 var syncCopies = 0
1099 /// Called with the chosen command before the palette closes.
1100 let choose: (String) -> Void
1101
1102 static let viewCommands: [(id: String, title: String)] = [
1103 ("org.cycle", "Cycle Visibility"), ("org.cycle-global", "Cycle Global Visibility"),
1104 ("edit.undo", "Undo"), ("edit.redo", "Redo"),
1105 ("app.clock.in", "Clock In"), ("app.clock.out", "Clock Out"), ("app.clock.cancel", "Cancel Clock"),
1106 ("app.clock.goto", "Go to Clocked Entry"), ("app.clock.in-recent", "Clock In to Recent Entry…"),
1107 ("app.clock.in-last", "Clock In to Last Entry"), ("app.clock.goto-recent", "Go to Recent Clocked Entry…"),
1108 ("app.clock.default", "Mark as Default Clock Task"), ("app.clock.resolve", "Resolve Open Clocks…"),
1109 ("app.refile", "Refile…"), ("app.refile.copy", "Copy to Refile Target…"), ("app.refile.goto", "Go to Refile Target…"),
1110 ("app.archive", "Archive Subtree"), ("app.export-dialog", "Export…"), ("app.export-subtree-dialog", "Export Subtree…"),
1111 ("app.share-subtree", "Share Subtree…"),
1112 ("app.copy-rich-text", "Copy as Rich Text"), ("app.export.html-open", "Export to HTML and Open"),
1113 ("app.export-body-only", "Turn Body-Only Export On or Off"),
1114 ("app.export.icalendar-agenda", "Export Agenda Files to iCalendar"), ("app.export.icalendar-combined", "Combine Agenda Files into iCalendar"),
1115 ("app.publish", "Publish Project…"), ("app.publish.all", "Publish All Projects"), ("app.publish.current-file", "Publish Current File"),
1116 ("app.publish.current-project", "Publish Current Project"),
1117 ("app.toggle-markup", "Show or Hide Markup"), ("app.word-count", "Word Count"),
1118 ("org.snippet.next-field", "Next Snippet Field"), ("org.snippet.previous-field", "Previous Snippet Field"),
1119 ("app.recovery", "Recovery Versions…"), ("app.sync-conflicts", "Resolve Sync Conflicts…"), ("app.lint", "Lint File"), ("app.lint-folders", "Lint All Folders"),
1120 ("app.working-copy.sync", "Sync with Working Copy"),
1121 ("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"),
1122 ("editor.complete", "Complete at Point"), ("editor.dabbrev-expand", "Expand Word"), ("editor.dabbrev-completion", "Complete Word"),
1123 ("edit.isearch-forward", "Incremental Search"), ("edit.isearch-backward", "Incremental Search Backward"),
1124 ("org.table.toggle-column-width", "Shrink or Expand Table Column"), ("org.table.shrink", "Shrink Table Columns with Widths"),
1125 ("org.table.expand", "Expand Table Columns"),
1126 ("app.table-import", "Import Table from File…"), ("app.table-export", "Export Table to File…"),
1127 ("app.table-export.tsv", "Export Table as TSV…"), ("app.plot", "Plot Table"),
1128 ("app.crypt.encrypt-entry", "Encrypt Entry…"), ("app.crypt.open-entry", "Decrypt Entry…"), ("app.crypt.decrypt-entry", "Decrypt Entry in File…"),
1129 ("app.crypt.encrypt-entries", "Encrypt Tagged Entries…"), ("app.crypt.forget-passphrase", "Forget Encryption Passphrase"),
1130 ("app.rename-tag", "Rename Tag…"), ("app.rename-todo-keyword", "Rename TODO Keyword…"),
1131 ("app.backlinks", "Show Backlinks"), ("app.node.find", "Find Node…"), ("app.node.insert", "Insert Node Link…"), ("app.node.graph", "Show Node Graph"),
1132 ("app.node.rename-from-front-matter", "Rename Note from Front Matter"),
1133 ("app.node.rename", "Rename Note…"),
1134 ("app.node.rename-folder-from-front-matter", "Rename Notes in Folder from Front Matter…"),
1135 ("app.node.silo-find", "Find Note in Silo…"),
1136 ("app.node.silo-create", "New Note in Silo…"),
1137 ("app.node.sequence-new-parent", "New Sequence Note…"),
1138 ("app.node.sequence-new-child", "New Child Sequence Note…"),
1139 ("app.node.sequence-new-sibling", "New Sibling Sequence Note…"),
1140 ("app.node.sequence-new-child-of-current", "New Child of This Note…"),
1141 ("app.node.sequence-new-sibling-of-current", "New Sibling of This Note…"),
1142 ("app.node.sequence-find", "Find Sequence Relatives…"),
1143 ("app.node.sequence-next-sibling", "Next Sibling Note"),
1144 ("app.node.sequence-previous-sibling", "Previous Sibling Note"),
1145 ("app.node.sequence-reparent", "Reparent Note…"),
1146 ("app.node.sequence-reparent-recursive", "Reparent Note with Descendants…"),
1147 ("app.node.sequence-rename-as-parent", "Rename Note as Sequence Parent"),
1148 ("app.node.sequence-convert", "Convert Note Sequence Scheme"),
1149 ("app.node.sequence-link", "Insert Sequence Link…"),
1150 ("app.node.sequence-hierarchy", "Sequence Hierarchy…"),
1151 ("app.dailies.today", "Go to Today's Daily Note"), ("app.dailies.yesterday", "Go to Yesterday's Daily Note"),
1152 ("app.dailies.tomorrow", "Go to Tomorrow's Daily Note"), ("app.dailies.date", "Go to Daily Note for Date…"),
1153 ("app.dailies.capture-today", "Capture to Today's Daily Note"), ("app.dailies.capture-yesterday", "Capture to Yesterday's Daily Note"),
1154 ("app.dailies.capture-tomorrow", "Capture to Tomorrow's Daily Note"), ("app.dailies.capture-date", "Capture to Daily Note for Date…"),
1155 ("app.dailies.next", "Next Daily Note"), ("app.dailies.previous", "Previous Daily Note"),
1156 ("app.attach.attach", "Attach File…"), ("app.attach.photo", "Attach Photo or Video…"), ("app.attach.camera", "Take Photo…"),
1157 ("app.attach.scan", "Scan Document…"), ("app.attach.url", "Attach File from URL…"), ("app.attach.new", "New Attachment…"),
1158 ("app.attach.open", "Open Attachment…"), ("app.attach.reveal", "Show Attachment Folder"), ("app.attach.delete", "Delete Attachment…"),
1159 ("app.attach.delete-all", "Delete All Attachments…"), ("app.attach.sync", "Sync Attachments"),
1160 ("app.attach.set-directory", "Set Attachment Folder…"), ("app.attach.unset-directory", "Unset Attachment Folder"),
1161 ]
1162
1163 /// The commands and their keys, and why those that don't apply at the caret don't, worked
1164 /// out once when the palette opens rather than on every keystroke in the search field.
1165 @State private var rows: [CommandRow]?
1166
1167 var body: some View {
1168 CommandList(rows: rows ?? [], choose: choose)
1169 .onAppear {
1170 guard rows == nil else { return }
1171 rows = commandRows()
1172 }
1173 }
1174
1175 private func commandRows() -> [CommandRow] {
1176 let context = editor.editContext()
1177 let paneCommands: [(id: String, title: String)] = !panes ? [] : [("app.split-right", "Split Pane Right"), ("app.split-below", "Split Pane Below")]
1178 + (split ? [("app.pane-next", "Next Pane"), ("app.pane-close", "Close Pane"), ("app.pane-only", "Close Other Panes")] : [])
1179 return Self.commands(macros: editor.namedMacros, panes: paneCommands)
1180 .map { command in
1181 CommandRow(id: command.id, title: CommandTitle.localized(command.title), keys: editor.keymap.keyLabels(for: command.id).first,
1182 reason: reason(command.id, context))
1183 }
1184 }
1185
1186 /// The commands listed, with English titles: `panes`, the editor's, and the named macros.
1187 static func commands(macros: NamedMacros, panes: [(id: String, title: String)] = []) -> [(id: String, title: String)] {
1188 var seen = Set<String>()
1189 return (panes + viewCommands + Commands.everything.map { ($0.id, $0.title) } + macros.names.map { (NamedMacros.commandPrefix + $0, $0) })
1190 .filter { !AppStoreCommands.hidden.contains($0.id) && offered($0.id) && seen.insert($0.id).inserted }
1191 }
1192
1193 /// Commands for a camera or scanner this device lacks aren't listed.
1194 private static func offered(_ id: String) -> Bool {
1195 switch id {
1196 case "app.attach.camera": CameraPicker.isAvailable
1197 case "app.attach.scan": DocumentScanner.isAvailable
1198 default: true
1199 }
1200 }
1201
1202 private func reason(_ id: String, _ context: EditContext) -> String? {
1203 switch id {
1204 case "app.recovery": return recoveries > 0 ? nil : String(localized: "No Recovery Versions")
1205 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")
1206 case EditorScreen.exportSubtreeCommand, "app.share-subtree":
1207 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")
1208 default: return editor.applies(id, in: context) ? nil : CommandReason.reason(for: id, in: context)
1209 }
1210 }
1211}
1212/// A table as CSV or TSV, for the save dialog.
1213struct TableFile: FileDocument {
1214 static var readableContentTypes: [UTType] { [.commaSeparatedText, .tabSeparatedText] }
1215 let text: String
1216 let type: UTType
1217
1218 init(text: String, type: UTType) {
1219 self.text = text
1220 self.type = type
1221 }
1222
1223 init(configuration: ReadConfiguration) throws {
1224 text = configuration.file.regularFileContents.map { String(decoding: $0, as: UTF8.self) } ?? ""
1225 type = configuration.contentType
1226 }
1227
1228 func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
1229 FileWrapper(regularFileWithContents: Data(text.utf8))
1230 }
1231}
1232/// A plotted table, as the Mac's plot sheet shows it.
1233struct PlotScreen: View {
1234 let plot: TablePlot.Plot
1235 @Environment(\.dismiss) private var dismiss
1236
1237 var body: some View {
1238 NavigationStack {
1239 PlotChart(plot)
1240 .navigationTitle("Plot")
1241 .navigationBarTitleDisplayMode(.inline)
1242 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
1243 }
1244 }
1245}
1246/// A file from the photo picker, copied out of the picker's temporary place with its name.
1247struct PickedFile: Transferable {
1248 let url: URL
1249
1250 static var transferRepresentation: some TransferRepresentation {
1251 FileRepresentation(importedContentType: .item) { received in
1252 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
1253 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
1254 let url = folder.appendingPathComponent(received.file.lastPathComponent)
1255 try FileManager.default.copyItem(at: received.file, to: url)
1256 return PickedFile(url: url)
1257 }
1258 }
1259}
1260
1261/// The passphrase sheet for org-crypt, its new text applied in the editor.
1262struct CryptScreen: View {
1263 let request: CryptRequest
1264 let session: DocumentSession
1265 let editor: MobileEditor?
1266 let report: (String) -> Void
1267 @Environment(\.dismiss) private var dismiss
1268
1269 var body: some View {
1270 NavigationStack {
1271 CryptSheet(request: request, session: session, text: { session.document(of: request.path)?.text ?? "" }, apply: apply) { message in
1272 dismiss()
1273 if let message { report(message) }
1274 }
1275 .navigationBarTitleDisplayMode(.inline)
1276 }
1277 }
1278
1279 private func apply(_ new: String) {
1280 guard let editor else { return }
1281 let context = editor.editContext()
1282 let caret = min(context.caret, (new as NSString).length)
1283 _ = editor.perform(PrecomputedEdit(EditResult(baseRevision: context.revision, edits: TextEdit.between(context.text, new), selection: [caret..<caret])))
1284 }
1285}
1286/// The pane an editor screen made for itself, closed with the screen.
1287@MainActor
1288final class PaneHolder {
1289 var pane: EditorPane?
1290 nonisolated(unsafe) var release: (() -> Void)?
1291
1292 deinit {
1293 guard let release else { return }
1294 Task { @MainActor in release() }
1295 }
1296}
1297
1298/// A command's result or refusal, over the screen until it is tapped or for four seconds, and
1299/// read out by VoiceOver.
1300private struct MessageView: ViewModifier {
1301 @Binding var message: String?
1302 let edge: VerticalEdge
1303
1304 func body(content: Content) -> some View {
1305 content.overlay(alignment: edge == .top ? .top : .bottom) {
1306 if let message {
1307 Text(message).font(.callout).multilineTextAlignment(.center)
1308 .padding(.horizontal, 14).padding(.vertical, 8)
1309 .glassEffect(.regular, in: .rect(cornerRadius: 18))
1310 .padding(8)
1311 .onTapGesture { self.message = nil }
1312 .task(id: message) {
1313 try? await Task.sleep(for: .seconds(4))
1314 if self.message == message { self.message = nil }
1315 }
1316 }
1317 }
1318 .onChange(of: message) { _, message in
1319 if let message { AccessibilityNotification.Announcement(message).post() }
1320 }
1321 }
1322}
1323
1324extension View {
1325 /// Shows `message` in the one message view, at the top or bottom of the screen.
1326 func message(_ message: Binding<String?>, edge: VerticalEdge = .bottom) -> some View {
1327 modifier(MessageView(message: message, edge: edge))
1328 }
1329}
1330
1331/// The screen's title, unless a split shows the focused pane's.
1332private struct EditorTitle: ViewModifier {
1333 let title: String
1334 let shown: Bool
1335
1336 func body(content: Content) -> some View {
1337 if shown {
1338 content.navigationTitle(title).navigationBarTitleDisplayMode(.inline)
1339 } else {
1340 content
1341 }
1342 }
1343}
1344#endif