Sources/OrgstarMobile/ExportMenu.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Sources/OrgstarMobile/ExportMenu.swift history · blame · raw

304 lines · 15925 bytes

12 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    @Environment(MobileModel.self) private var model
169    /// Shows what happened, as the screen's message line does.
170    var report: (String) -> Void = { _ in }
171    /// Offers the subtree at the caret alone, where there is a caret.
172    var exportSubtree: (() -> Void)?
173    /// Every file's export settings as kept, so the menu follows a change to this file's.
174    @AppStorage(ExportSettings.key) private var kept = Data()
175
176    var body: some View {
177        let bodyOnly = kept.isEmpty ? false : ExportSettings.saved(for: path).bodyOnly
178        let text = tree.text
179        // From the open tree: SwiftUI evaluates the menu on every edit.
180        let name = ExportScope.fileName(tree, settings: OrgPreferences.orgSettings())
181        Menu("Export", systemImage: "square.and.arrow.up") {
182            ForEach(OrgExport.Format.allCases, id: \.self) { format in
183                if format.locked {
184                    Button("\(format.name) (orgstar+)") { ProAccess.shared.allows(.export) }
185                } else if bodyOnly, !format.allowsBodyOnly {
186                    Button(format.name) { report(ExportSettings.noBodyOnly) }
187                } else {
188                    let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
189                                           codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), name: name, bodyOnly: bodyOnly)
190                    ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
191                }
192            }
193            Toggle("Body Only", isOn: Binding(get: { bodyOnly }, set: { ExportMenu.setBodyOnly($0, path: path) }))
194            if let exportSubtree {
195                Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
196            }
197            if let calendars = AgendaCalendars(model: model) {
198                Divider()
199                if OrgExport.Format.icalendar.locked {
200                    Button("Agenda Files to iCalendar (orgstar+)") { ProAccess.shared.allows(.export) }
201                } else {
202                    Button("Export Agenda Files to iCalendar", systemImage: "calendar") { report(calendars.exportEach()) }
203                    ShareLink(item: calendars, preview: SharePreview(calendars.fileName)) {
204                        Label("Combine Agenda Files into iCalendar", systemImage: "calendar.badge.plus")
205                    }
206                }
207            }
208            Divider()
209            Button("Copy as Rich Text", systemImage: "doc.on.doc") { if ProAccess.shared.allows(.export) { report(Self.copy(path: path, text: text, theme: model.theme)) } }
210        }
211    }
212
213    /// Keeps the body-only choice for the file at `path`.
214    static func setBodyOnly(_ on: Bool, path: String) {
215        var settings = ExportSettings.saved(for: path)
216        settings.bodyOnly = on
217        settings.save(for: path)
218    }
219
220    /// The file on the clipboard as HTML, RTF and plain text, to paste formatted. Returns a message.
221    @MainActor
222    static func copy(path: String, text: String, theme: ThemeSpec) -> String {
223        let html = OrgExport.html(text, path: path, theme: theme)
224        do {
225            try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
226            return "Copied as rich text"
227        } catch {
228            return "\(error)"
229        }
230    }
231}
232
233/// The agenda files as iCalendar: each to a calendar beside it
234/// (`org-icalendar-export-agenda-files`), or all in one calendar to share
235/// (`org-icalendar-combine-agenda-files`), named as `org-icalendar-combined-agenda-file` is.
236struct AgendaCalendars: Transferable {
237    let paths: [String]
238    /// The open files' text, which may not be saved yet.
239    let open: [String: String]
240
241    /// Nil without agenda files.
242    @MainActor init?(model: MobileModel) {
243        guard let paths = model.workspace?.agendaFilePaths(), !paths.isEmpty else { return nil }
244        self.paths = paths
245        open = Dictionary(model.session.openDocuments.map { ($0.path, $0.document.text) }, uniquingKeysWith: { first, _ in first })
246    }
247
248    var fileName: String { (OrgPreferences.icalendarCombinedFile() as NSString).lastPathComponent }
249
250    private func read(_ path: String) -> (text: String, settings: OrgSettings)? {
251        guard let text = open[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
252        return (text, OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
253    }
254
255    /// Writes each agenda file's calendar beside it. Returns a message.
256    func exportEach() -> String {
257        do {
258            let written = try ICalendarFiles.exportEach(paths, options: OrgPreferences.icalendarOptions(), read: read)
259            return "Exported \(written.count) agenda files to iCalendar"
260        } catch {
261            return "Can't export: \(error.localizedDescription)"
262        }
263    }
264
265    /// The combined calendar, in a new temporary folder.
266    func combined() throws -> URL {
267        let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
268        return try ICalendarFiles.combine(paths, to: folder.appendingPathComponent(fileName).path, options: OrgPreferences.icalendarOptions(), read: read)
269    }
270
271    static var transferRepresentation: some TransferRepresentation {
272        FileRepresentation(exportedContentType: .calendarEvent) { SentTransferredFile(try $0.combined()) }
273    }
274}
275
276/// The subtree at `caret` shared alone, in each of the export formats.
277struct SubtreeExportScreen: View {
278    let path: String
279    let tree: OrgTree
280    let caret: Int
281    @Environment(MobileModel.self) private var model
282    @Environment(\.dismiss) private var dismiss
283
284    var body: some View {
285        NavigationStack {
286            let bodyOnly = ExportSettings.saved(for: path).bodyOnly
287            let name = ExportScope.fileName(tree, subtreeAt: caret, settings: OrgPreferences.orgSettings())
288            List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
289                if bodyOnly, !format.allowsBodyOnly {
290                    LabeledContent(format.name) { Text("No body-only export") }.foregroundStyle(.secondary)
291                } else {
292                    let export = OrgExport(text: tree.text, path: path, format: format, settings: OrgPreferences.orgSettings(),
293                                           codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), name: name,
294                                           subtree: caret, bodyOnly: bodyOnly)
295                    ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
296                }
297            }
298            .navigationTitle("Export Subtree")
299            .navigationBarTitleDisplayMode(.inline)
300            .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
301        }
302    }
303}
304#endif