Sources/OrgstarMobile/EditorScreen.swift

1025 lines · 50764 bytes

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