Sources/OrgstarMobile/ExportMenu.swift

277 lines · 14144 bytes

  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        var fileExtension: String {
 35            switch self {
 36            case .html: "html"
 37            case .markdown: "md"
 38            case .pdf: "pdf"
 39            case .docx: "docx"
 40            case .rtf: "rtf"
 41            case .plainText: "txt"
 42            case .odt: "odt"
 43            case .icalendar: "ics"
 44            case .latex: "tex"
 45            case .ascii: "txt"
 46            }
 47        }
 48    }
 49
 50    let text: String
 51    let path: String
 52    let format: Format
 53    let settings: OrgSettings
 54    /// Made on the main actor, where the editor's highlighter is.
 55    let codeStyle: HTMLCodeStyle
 56    /// The subtree at this offset exported alone.
 57    var subtree: Int?
 58
 59    /// The subtree's `EXPORT_FILE_NAME`, `#+EXPORT_FILE_NAME`'s name, or the file's, with the
 60    /// format's extension.
 61    var fileName: String {
 62        ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: subtree, settings: settings),
 63                           extension: format.fileExtension)
 64            .lastPathComponent
 65    }
 66
 67    /// Posted with the message, for the screen's message line, when the LaTeX or ASCII export
 68    /// refuses the file: the share sheet shows no reason.
 69    static let refused = Notification.Name("OrgExportRefused")
 70
 71    static var transferRepresentation: some TransferRepresentation {
 72        FileRepresentation(exportedContentType: .html) { try await $0.write() }
 73            .exportingCondition { $0.format == .html }
 74        FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { try await $0.write() }
 75            .exportingCondition { $0.format == .markdown }
 76        FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
 77            .exportingCondition { $0.format == .pdf }
 78        FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() }
 79            .exportingCondition { $0.format == .docx }
 80        FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
 81            .exportingCondition { $0.format == .rtf }
 82        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 83            .exportingCondition { $0.format == .plainText }
 84        FileRepresentation(exportedContentType: UTType(filenameExtension: "odt") ?? .data) { try await $0.write() }
 85            .exportingCondition { $0.format == .odt }
 86        FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
 87            .exportingCondition { $0.format == .icalendar }
 88        FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
 89            .exportingCondition { $0.format == .latex }
 90        FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
 91            .exportingCondition { $0.format == .ascii }
 92    }
 93
 94    /// The page HTML export makes of `text`, the file at `path`, with its setup files.
 95    @MainActor
 96    static func html(_ text: String, path: String, theme: ThemeSpec) -> String {
 97        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
 98        let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
 99        return HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
100                               codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: theme), language: OrgPreferences.exportLanguage())
101    }
102
103    private func write() async throws -> SentTransferredFile {
104        let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
105        let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
106        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
107        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
108        let url = folder.appendingPathComponent(fileName)
109        let text = subtree.flatMap { ExportScope.subtree(self.text, at: $0, settings: settings) } ?? self.text
110        switch format {
111        case .html:
112            try HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
113                .write(to: url, atomically: true, encoding: .utf8)
114        case .markdown:
115            try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
116        case .latex:
117            let content: String
118            do {
119                content = try LaTeXExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage(), file: true)
120            } catch let error as LaTeXExport.Unsupported {
121                let message = "Can't export to LaTeX: \(error.reason)"
122                await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
123                throw error
124            }
125            try content.write(to: url, atomically: true, encoding: .utf8)
126        case .ascii:
127            let content: String
128            do {
129                content = try ASCIIExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage(), file: true)
130            } catch let error as ASCIIExport.Unsupported {
131                let message = "Can't export to plain text: \(error.reason)"
132                await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
133                throw error
134            }
135            try content.write(to: url, atomically: true, encoding: .utf8)
136        case .odt:
137            try ODTExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage())
138                .write(to: url, options: .atomic)
139        case .icalendar:
140            try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
141                                      subtree: subtree, destination: url)
142        case .docx:
143            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
144            try await RichTextExport.docx(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).write(to: url, options: .atomic)
145        case .pdf, .rtf, .plainText:
146            let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
147            let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
148            let data: Data = switch format {
149            case .pdf: try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
150            case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
151            default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
152            }
153            try data.write(to: url, options: .atomic)
154        }
155        return SentTransferredFile(url)
156    }
157}
158
159/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar, LaTeX or ASCII: to another app, or saved with
160/// Save to Files; or copying it as rich text.
161struct ExportMenu: View {
162    let path: String
163    let text: String
164    @Environment(MobileModel.self) private var model
165    /// Shows what happened, as the screen's message line does.
166    var report: (String) -> Void = { _ in }
167    /// Offers the subtree at the caret alone, where there is a caret.
168    var exportSubtree: (() -> Void)?
169
170    var body: some View {
171        Menu("Export", systemImage: "square.and.arrow.up") {
172            ForEach(OrgExport.Format.allCases, id: \.self) { format in
173                if format.locked {
174                    Button("\(format.name) (orgstar+)") { ProAccess.shared.allows(.export) }
175                } else {
176                    let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
177                                           codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
178                    ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
179                }
180            }
181            if let exportSubtree {
182                Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
183            }
184            if let calendars = AgendaCalendars(model: model) {
185                Divider()
186                if OrgExport.Format.icalendar.locked {
187                    Button("Agenda Files to iCalendar (orgstar+)") { ProAccess.shared.allows(.export) }
188                } else {
189                    Button("Export Agenda Files to iCalendar", systemImage: "calendar") { report(calendars.exportEach()) }
190                    ShareLink(item: calendars, preview: SharePreview(calendars.fileName)) {
191                        Label("Combine Agenda Files into iCalendar", systemImage: "calendar.badge.plus")
192                    }
193                }
194            }
195            Divider()
196            Button("Copy as Rich Text", systemImage: "doc.on.doc") { if ProAccess.shared.allows(.export) { report(Self.copy(path: path, text: text, theme: model.theme)) } }
197        }
198    }
199
200    /// The file on the clipboard as HTML, RTF and plain text, to paste formatted. Returns a message.
201    @MainActor
202    static func copy(path: String, text: String, theme: ThemeSpec) -> String {
203        let html = OrgExport.html(text, path: path, theme: theme)
204        do {
205            try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
206            return "Copied as rich text"
207        } catch {
208            return "\(error)"
209        }
210    }
211}
212
213/// The agenda files as iCalendar: each to a calendar beside it
214/// (`org-icalendar-export-agenda-files`), or all in one calendar to share
215/// (`org-icalendar-combine-agenda-files`), named as `org-icalendar-combined-agenda-file` is.
216struct AgendaCalendars: Transferable {
217    let paths: [String]
218    /// The open files' text, which may not be saved yet.
219    let open: [String: String]
220
221    /// Nil without agenda files.
222    @MainActor init?(model: MobileModel) {
223        guard let paths = model.workspace?.agendaFilePaths(), !paths.isEmpty else { return nil }
224        self.paths = paths
225        open = Dictionary(model.session.openDocuments.map { ($0.path, $0.document.text) }, uniquingKeysWith: { first, _ in first })
226    }
227
228    var fileName: String { (OrgPreferences.icalendarCombinedFile() as NSString).lastPathComponent }
229
230    private func read(_ path: String) -> (text: String, settings: OrgSettings)? {
231        guard let text = open[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
232        return (text, OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
233    }
234
235    /// Writes each agenda file's calendar beside it. Returns a message.
236    func exportEach() -> String {
237        do {
238            let written = try ICalendarFiles.exportEach(paths, options: OrgPreferences.icalendarOptions(), read: read)
239            return "Exported \(written.count) agenda files to iCalendar"
240        } catch {
241            return "Can't export: \(error.localizedDescription)"
242        }
243    }
244
245    /// The combined calendar, in a new temporary folder.
246    func combined() throws -> URL {
247        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
248        return try ICalendarFiles.combine(paths, to: folder.appendingPathComponent(fileName).path, options: OrgPreferences.icalendarOptions(), read: read)
249    }
250
251    static var transferRepresentation: some TransferRepresentation {
252        FileRepresentation(exportedContentType: .calendarEvent) { SentTransferredFile(try $0.combined()) }
253    }
254}
255
256/// The subtree at `caret` shared alone, in each of the export formats.
257struct SubtreeExportScreen: View {
258    let path: String
259    let text: String
260    let caret: Int
261    @Environment(MobileModel.self) private var model
262    @Environment(\.dismiss) private var dismiss
263
264    var body: some View {
265        NavigationStack {
266            List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
267                let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
268                                       codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), subtree: caret)
269                ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
270            }
271            .navigationTitle("Export Subtree")
272            .navigationBarTitleDisplayMode(.inline)
273            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
274        }
275    }
276}
277#endif