Sources/OrgstarMobile/ExportMenu.swift

49c5da97098ed000be935c19462d4102812b0471
orgstar/Sources/OrgstarMobile/ExportMenu.swift

419 lines · 21163 bytes

16 symbols in this file
  1#if os(iOS)
  2import CoreTransferable
  3import OrgApp
  4import OrgCore
  5import OrgPresentation
  6import SwiftUI
  7import UniformTypeIdentifiers
  8
  9/// A file exported as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX or ASCII,
 10/// written when the share sheet takes it.
 11struct OrgExport: Transferable {
 12    enum Format: CaseIterable {
 13        case html, markdown, pdf, docx, rtf, plainText, odt, icalendar
 14        case latex, ascii
 15
 16        /// Whether it needs Pro now: every format but HTML and Markdown, until Pro is unlocked.
 17        @MainActor var locked: Bool { self != .html && self != .markdown && !ProAccess.shared.isUnlocked }
 18
 19        var name: String {
 20            switch self {
 21            case .html: "HTML"
 22            case .markdown: "Markdown"
 23            case .pdf: "PDF"
 24            case .docx: "Word"
 25            case .rtf: "Rich Text (RTF)"
 26            case .plainText: "Plain Text"
 27            case .odt: "ODT"
 28            case .icalendar: "iCalendar"
 29            case .latex: "LaTeX"
 30            case .ascii: "Plain Text (ASCII)"
 31            }
 32        }
 33
 34        /// Whether it can leave out the title and the page around the text.
 35        var allowsBodyOnly: Bool { [.html, .markdown, .latex, .ascii].contains(self) }
 36
 37        var fileExtension: String {
 38            switch self {
 39            case .html: "html"
 40            case .markdown: "md"
 41            case .pdf: "pdf"
 42            case .docx: "docx"
 43            case .rtf: "rtf"
 44            case .plainText: "txt"
 45            case .odt: "odt"
 46            case .icalendar: "ics"
 47            case .latex: "tex"
 48            case .ascii: "txt"
 49            }
 50        }
 51    }
 52
 53    let text: String
 54    let path: String
 55    let format: Format
 56    let settings: OrgSettings
 57    /// Made on the main actor, where the editor's highlighter is.
 58    let codeStyle: HTMLCodeStyle
 59    /// The subtree's `EXPORT_FILE_NAME`, `#+EXPORT_FILE_NAME`'s name, or nil for the file's.
 60    let name: String?
 61    /// The subtree at this offset exported alone.
 62    var subtree: Int?
 63    /// Without the title and the page around the text, in the formats that allow it.
 64    var bodyOnly = false
 65
 66    /// `name`, or the file's, with the format's extension.
 67    var fileName: String {
 68        ExportScope.output(for: URL(fileURLWithPath: path), name: name, extension: format.fileExtension).lastPathComponent
 69    }
 70
 71    /// Posted with the message, for the screen's message line, when the LaTeX or ASCII export
 72    /// refuses the file: the share sheet shows no reason.
 73    static let refused = Notification.Name("OrgExportRefused")
 74
 75    static var transferRepresentation: some TransferRepresentation {
 76        FileRepresentation(exportedContentType: .html) { try await $0.write() }
 77            .exportingCondition { $0.format == .html }
 78        FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { try await $0.write() }
 79            .exportingCondition { $0.format == .markdown }
 80        FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
 81            .exportingCondition { $0.format == .pdf }
 82        FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() }
 83            .exportingCondition { $0.format == .docx }
 84        FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
 85            .exportingCondition { $0.format == .rtf }
 86        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 87            .exportingCondition { $0.format == .plainText }
 88        FileRepresentation(exportedContentType: UTType(filenameExtension: "odt") ?? .data) { try await $0.write() }
 89            .exportingCondition { $0.format == .odt }
 90        FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
 91            .exportingCondition { $0.format == .icalendar }
 92        FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
 93            .exportingCondition { $0.format == .latex }
 94        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 95            .exportingCondition { $0.format == .ascii }
 96    }
 97
 98    /// The page HTML export makes of `text`, the file at `path`, with its setup files.
 99    @MainActor
100    static func html(_ text: String, path: String, theme: ThemeSpec, bodyOnly: Bool = false) -> String {
101        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
102        let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
103        return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly,
104                               codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: theme), language: OrgPreferences.exportLanguage())
105    }
106
107    private func write() async throws -> SentTransferredFile {
108        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
109        let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
110        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
111        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
112        let url = folder.appendingPathComponent(fileName)
113        let text = subtree.flatMap { ExportScope.subtree(self.text, at: $0, settings: settings) } ?? self.text
114        switch format {
115        case .html:
116            try HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, bodyOnly: bodyOnly, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
117                .write(to: url, atomically: true, encoding: .utf8)
118        case .markdown:
119            try MarkdownExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly).write(to: url, atomically: true, encoding: .utf8)
120        case .latex:
121            let content: String
122            do {
123                content = try LaTeXExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, language: OrgPreferences.exportLanguage(), file: true)
124            } catch let error as LaTeXExport.Unsupported {
125                let message = "Can't export to LaTeX: \(error.reason)"
126                await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
127                throw error
128            }
129            try content.write(to: url, atomically: true, encoding: .utf8)
130        case .ascii:
131            let content: String
132            do {
133                content = try ASCIIExport.document(text, settings: settings, path: path, bodyOnly: bodyOnly, language: OrgPreferences.exportLanguage(), file: true)
134            } catch let error as ASCIIExport.Unsupported {
135                let message = "Can't export to plain text: \(error.reason)"
136                await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
137                throw error
138            }
139            try content.write(to: url, atomically: true, encoding: .utf8)
140        case .odt:
141            try ODTExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage())
142                .write(to: url, options: .atomic)
143        case .icalendar:
144            try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
145                                      subtree: subtree, destination: url)
146        case .docx:
147            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
148            try await RichTextExport.docx(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).write(to: url, options: .atomic)
149        case .pdf, .rtf, .plainText:
150            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
151            let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
152            let data: Data = switch format {
153            case .pdf: try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
154            case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
155            default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
156            }
157            try data.write(to: url, options: .atomic)
158        }
159        return SentTransferredFile(url)
160    }
161}
162
163/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX or ASCII: to another app, or saved with
164/// Save to Files; or copying it as rich text.
165struct ExportMenu: View {
166    let path: String
167    let tree: OrgTree
168    var report: (String) -> Void = { _ in }
169    var exportSubtree: (() -> Void)?
170
171    var body: some View {
172        Menu("Export", systemImage: "square.and.arrow.up") {
173            ExportItems(path: path, tree: tree, report: report, exportSubtree: exportSubtree)
174        }
175    }
176}
177
178/// The export menu's items as a list, for a screen without the menu in its toolbar.
179struct ExportScreen: View {
180    let path: String
181    let tree: OrgTree
182    var report: (String) -> Void = { _ in }
183    @Environment(\.dismiss) private var dismiss
184
185    var body: some View {
186        NavigationStack {
187            List { ExportItems(path: path, tree: tree, report: report, dividers: false) }
188                .navigationTitle("Export")
189                .navigationBarTitleDisplayMode(.inline)
190                .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
191        }
192    }
193}
194
195/// Export's formats, Body Only, the agenda calendars and Copy as Rich Text.
196struct ExportItems: View {
197    let path: String
198    let tree: OrgTree
199    @Environment(MobileModel.self) private var model
200    /// Shows what happened, as the screen's message line does.
201    var report: (String) -> Void = { _ in }
202    /// Offers the subtree at the caret alone, where there is a caret.
203    var exportSubtree: (() -> Void)?
204    /// Dividers between the groups, as a menu draws them; a list already separates its rows.
205    var dividers = true
206    /// Every file's export settings as kept, so the menu follows a change to this file's.
207    @AppStorage(ExportSettings.key) private var kept = Data()
208
209    var body: some View {
210        let bodyOnly = kept.isEmpty ? false : ExportSettings.saved(for: path).bodyOnly
211        let text = tree.text
212        // From the open tree: SwiftUI evaluates the menu on every edit.
213        let name = ExportScope.fileName(tree, settings: OrgPreferences.orgSettings())
214        Group {
215            ForEach(OrgExport.Format.allCases, id: \.self) { format in
216                if format.locked {
217                    Button("\(format.name) (orgstar+)") { ProAccess.shared.allows(.export) }
218                } else if bodyOnly, !format.allowsBodyOnly {
219                    Button(format.name) { report(ExportSettings.noBodyOnly) }
220                } else {
221                    let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
222                                           codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), name: name, bodyOnly: bodyOnly)
223                    ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
224                }
225            }
226            Toggle("Body Only", isOn: Binding(get: { bodyOnly }, set: { ExportItems.setBodyOnly($0, path: path) }))
227            if let exportSubtree {
228                Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
229            }
230            if OrgExport.Format.pdf.locked {
231                Button("\(String(localized: "Print…")) (orgstar+)", systemImage: "printer") { ProAccess.shared.allows(.export) }
232            } else {
233                Button("Print…", systemImage: "printer") { Self.startPrinting(path: path, text: text, scope: .file, theme: model.theme, report: report) }
234            }
235            if let calendars = AgendaCalendars(model: model) {
236                if dividers { Divider() }
237                if OrgExport.Format.icalendar.locked {
238                    Button("\(String(localized: "Export Agenda Files to iCalendar")) (orgstar+)", systemImage: "calendar") { ProAccess.shared.allows(.export) }
239                } else {
240                    Button("Export Agenda Files to iCalendar", systemImage: "calendar") { report(calendars.exportEach()) }
241                    ShareLink(item: calendars, preview: SharePreview(calendars.fileName)) {
242                        Label("Combine Agenda Files into iCalendar", systemImage: "calendar.badge.plus")
243                    }
244                }
245            }
246            if dividers { Divider() }
247            if ProAccess.shared.isUnlocked {
248                Button("Copy as Rich Text", systemImage: "doc.on.doc") { report(Self.copy(path: path, text: text, theme: model.theme)) }
249            } else {
250                Button("\(String(localized: "Copy as Rich Text")) (orgstar+)", systemImage: "doc.on.doc") { ProAccess.shared.allows(.export) }
251            }
252        }
253    }
254
255    /// Keeps the body-only choice for the file at `path`.
256    static func setBodyOnly(_ on: Bool, path: String) {
257        var settings = ExportSettings.saved(for: path)
258        settings.bodyOnly = on
259        settings.save(for: path)
260    }
261
262    /// Print…: the page PDF export makes of `scope` of `text`, the buffer of the file at `path`,
263    /// in the print sheet. `report` gets the reason it can't print.
264    @MainActor
265    static func startPrinting(path: String, text: String, scope: PrintScope, theme: ThemeSpec, report: @escaping (String) -> Void) {
266        let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
267        guard let html = Printing.page(text, path: path, scope: scope, settings: settings, codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: theme),
268                                       language: OrgPreferences.exportLanguage()) else { return report(String(localized: "Not in a subtree")) }
269        Task {
270            do {
271                try await Printing.show(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
272            } catch {
273                report(String(localized: "Can't print: \(String(describing: error))"))
274            }
275        }
276    }
277
278    /// The file on the clipboard as HTML, RTF and plain text, to paste formatted. Returns a message.
279    @MainActor
280    static func copy(path: String, text: String, theme: ThemeSpec) -> String {
281        let html = OrgExport.html(text, path: path, theme: theme)
282        do {
283            try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
284            return "Copied as rich text"
285        } catch {
286            return "\(error)"
287        }
288    }
289}
290
291/// The agenda files as iCalendar: each to a calendar beside it
292/// (`org-icalendar-export-agenda-files`), or all in one calendar to share
293/// (`org-icalendar-combine-agenda-files`), named as `org-icalendar-combined-agenda-file` is.
294struct AgendaCalendars: Transferable {
295    let paths: [String]
296    /// The files' text for the export: open buffers', or what's on disk for those holding
297    /// what's encrypted there; encrypted files are left out.
298    let texts: [String: String]
299    /// Said after the export when it left something out.
300    let note: String
301
302    /// Nil without agenda files.
303    @MainActor init?(model: MobileModel) {
304        guard let paths = model.workspace?.agendaFilePaths(), !paths.isEmpty else { return nil }
305        self.paths = paths
306        let session = model.session
307        texts = Dictionary(paths.compactMap { path in session.exportText(of: path).map { (path, $0) } }, uniquingKeysWith: { first, _ in first })
308        note = paths.contains(where: session.exportLeavesOut) ? " " + DocumentSession.exportNote : ""
309    }
310
311    var fileName: String { (OrgPreferences.icalendarCombinedFile() as NSString).lastPathComponent }
312
313    private func read(_ path: String) -> (text: String, settings: OrgSettings)? {
314        guard let text = texts[path] else { return nil }
315        return (text, OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
316    }
317
318    /// Writes each agenda file's calendar beside it. Returns a message.
319    func exportEach() -> String {
320        do {
321            let written = try ICalendarFiles.exportEach(paths, options: OrgPreferences.icalendarOptions(), read: read)
322            return String(localized: "Exported \(written.count) agenda files to iCalendar") + note
323        } catch {
324            return "Can't export: \(error.localizedDescription)"
325        }
326    }
327
328    /// The combined calendar, in a new temporary folder.
329    func combined() throws -> URL {
330        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
331        return try ICalendarFiles.combine(paths, to: folder.appendingPathComponent(fileName).path, options: OrgPreferences.icalendarOptions(), read: read)
332    }
333
334    static var transferRepresentation: some TransferRepresentation {
335        FileRepresentation(exportedContentType: .calendarEvent) { SentTransferredFile(try $0.combined()) }
336    }
337}
338
339/// The subtree at `caret` shared alone, in each of the export formats.
340struct SubtreeExportScreen: View {
341    let path: String
342    let tree: OrgTree
343    let caret: Int
344    @Environment(MobileModel.self) private var model
345    @Environment(\.dismiss) private var dismiss
346
347    var body: some View {
348        NavigationStack {
349            let bodyOnly = ExportSettings.saved(for: path).bodyOnly
350            let name = ExportScope.fileName(tree, subtreeAt: caret, settings: OrgPreferences.orgSettings())
351            List {
352                ForEach(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
353                    if bodyOnly, !format.allowsBodyOnly {
354                        LabeledContent(format.name) { Text("No body-only export") }.foregroundStyle(.secondary)
355                    } else {
356                        let export = OrgExport(text: tree.text, path: path, format: format, settings: OrgPreferences.orgSettings(),
357                                               codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), name: name,
358                                               subtree: caret, bodyOnly: bodyOnly)
359                        ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
360                    }
361                }
362                if !OrgExport.Format.pdf.locked {
363                    Button("Print…", systemImage: "printer") {
364                        ExportItems.startPrinting(path: path, text: tree.text, scope: .subtree(caret), theme: model.theme) { _ in }
365                    }
366                }
367            }
368            .navigationTitle("Export Subtree")
369            .navigationBarTitleDisplayMode(.inline)
370            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
371        }
372    }
373}
374
375/// Share Subtree…: the entry at the caret as an org file, with its attachments as separate items
376/// if chosen, or as text.
377struct SubtreeShareScreen: View {
378    let share: SubtreeShare
379    var report: (String) -> Void = { _ in }
380    @State private var file: URL?
381    @State private var withAttachments = false
382    @Environment(\.dismiss) private var dismiss
383
384    var body: some View {
385        NavigationStack {
386            List {
387                Section {
388                    if let file {
389                        ShareLink(items: share.files(file: file, withAttachments: withAttachments)) {
390                            Label("Share as Org File", systemImage: "doc")
391                        }
392                    }
393                    if !share.attachments.isEmpty {
394                        Toggle("Include \(share.attachments.count) attachments", isOn: $withAttachments)
395                    }
396                } footer: {
397                    Text(verbatim: share.fileName)
398                }
399                Section {
400                    ShareLink(item: share.text, preview: SharePreview(share.fileName)) {
401                        Label("Share as Text", systemImage: "text.alignleft")
402                    }
403                }
404            }
405            .navigationTitle("Share Subtree")
406            .navigationBarTitleDisplayMode(.inline)
407            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
408            .onAppear {
409                guard file == nil else { return }
410                do {
411                    file = try share.writeFile()
412                } catch {
413                    report(String(localized: "Can't share \(share.fileName): \(error.localizedDescription)"))
414                }
415            }
416        }
417    }
418}
419#endif
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form