Sources/OrgstarMobile/ExportMenu.swift
202 lines · 10187 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 or LaTeX, written
10/// 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
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 }
31 }
32
33 var fileExtension: String {
34 switch self {
35 case .html: "html"
36 case .markdown: "md"
37 case .pdf: "pdf"
38 case .docx: "docx"
39 case .rtf: "rtf"
40 case .plainText: "txt"
41 case .odt: "odt"
42 case .icalendar: "ics"
43 case .latex: "tex"
44 }
45 }
46 }
47
48 let text: String
49 let path: String
50 let format: Format
51 let settings: OrgSettings
52 /// Made on the main actor, where the editor's highlighter is.
53 let codeStyle: HTMLCodeStyle
54 /// The subtree at this offset exported alone.
55 var subtree: Int?
56
57 /// The subtree's `EXPORT_FILE_NAME`, `#+EXPORT_FILE_NAME`'s name, or the file's, with the
58 /// format's extension.
59 var fileName: String {
60 ExportScope.output(for: URL(fileURLWithPath: path), name: ExportScope.fileName(text, subtreeAt: subtree, settings: settings),
61 extension: format.fileExtension)
62 .lastPathComponent
63 }
64
65 /// Posted with the message, for the screen's message line, when the LaTeX export refuses
66 /// the file: the share sheet shows no reason.
67 static let refused = Notification.Name("OrgExportRefused")
68
69 static var transferRepresentation: some TransferRepresentation {
70 FileRepresentation(exportedContentType: .html) { try await $0.write() }
71 .exportingCondition { $0.format == .html }
72 FileRepresentation(exportedContentType: UTType(filenameExtension: "md") ?? .plainText) { try await $0.write() }
73 .exportingCondition { $0.format == .markdown }
74 FileRepresentation(exportedContentType: .pdf) { try await $0.write() }
75 .exportingCondition { $0.format == .pdf }
76 FileRepresentation(exportedContentType: UTType(filenameExtension: "docx") ?? .data) { try await $0.write() }
77 .exportingCondition { $0.format == .docx }
78 FileRepresentation(exportedContentType: .rtf) { try await $0.write() }
79 .exportingCondition { $0.format == .rtf }
80 FileRepresentation(exportedContentType: .plainText) { try await $0.write() }
81 .exportingCondition { $0.format == .plainText }
82 FileRepresentation(exportedContentType: UTType(filenameExtension: "odt") ?? .data) { try await $0.write() }
83 .exportingCondition { $0.format == .odt }
84 FileRepresentation(exportedContentType: .calendarEvent) { try await $0.write() }
85 .exportingCondition { $0.format == .icalendar }
86 FileRepresentation(exportedContentType: UTType(filenameExtension: "tex") ?? .plainText) { try await $0.write() }
87 .exportingCondition { $0.format == .latex }
88 }
89
90 private func write() async throws -> SentTransferredFile {
91 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
92 let settings = settings.resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
93 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
94 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
95 let url = folder.appendingPathComponent(fileName)
96 let text = subtree.flatMap { ExportScope.subtree(self.text, at: $0, settings: settings) } ?? self.text
97 switch format {
98 case .html:
99 try HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
100 .write(to: url, atomically: true, encoding: .utf8)
101 case .markdown:
102 try MarkdownExport.document(text, settings: settings, path: path).write(to: url, atomically: true, encoding: .utf8)
103 case .latex:
104 let content: String
105 do {
106 content = try LaTeXExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage(), file: true)
107 } catch let error as LaTeXExport.Unsupported {
108 let message = "Can't export to LaTeX: \(error.reason)"
109 await MainActor.run { NotificationCenter.default.post(name: Self.refused, object: message) }
110 throw error
111 }
112 try content.write(to: url, atomically: true, encoding: .utf8)
113 case .odt:
114 try ODTExport.document(text, settings: settings, path: path, language: OrgPreferences.exportLanguage())
115 .write(to: url, options: .atomic)
116 case .icalendar:
117 try ICalendarFiles.export(self.text, path: path, settings: settings, options: OrgPreferences.icalendarOptions(),
118 subtree: subtree, destination: url)
119 case .docx:
120 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
121 try await RichTextExport.docx(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent()).write(to: url, options: .atomic)
122 case .pdf, .rtf, .plainText:
123 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path, codeStyle: codeStyle, language: OrgPreferences.exportLanguage())
124 let directory = URL(fileURLWithPath: path).deletingLastPathComponent()
125 let data: Data = switch format {
126 case .pdf: try await PDFExport.pdf(html: html, directory: directory, options: OrgPreferences.pdfOptions())
127 case .rtf: try await RichTextExport.rtf(html: html, directory: directory)
128 default: Data(try await RichTextExport.plain(html: html, directory: directory).utf8)
129 }
130 try data.write(to: url, options: .atomic)
131 }
132 return SentTransferredFile(url)
133 }
134}
135
136/// Sharing the file as HTML, Markdown, PDF, Word, RTF, plain text, ODT, iCalendar or LaTeX: to another app, or saved with
137/// Save to Files; or copying it as rich text.
138struct ExportMenu: View {
139 let path: String
140 let text: String
141 @Environment(MobileModel.self) private var model
142 /// Shows what happened, as the screen's message line does.
143 var report: (String) -> Void = { _ in }
144 /// Offers the subtree at the caret alone, where there is a caret.
145 var exportSubtree: (() -> Void)?
146
147 var body: some View {
148 Menu("Export", systemImage: "square.and.arrow.up") {
149 ForEach(OrgExport.Format.allCases, id: \.self) { format in
150 if format.locked {
151 Button("\(format.name) (orgstar+)") { ProAccess.shared.allows(.export) }
152 } else {
153 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
154 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme))
155 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
156 }
157 }
158 if let exportSubtree {
159 Button("Export Subtree…", systemImage: "list.bullet.indent") { exportSubtree() }
160 }
161 Divider()
162 Button("Copy as Rich Text", systemImage: "doc.on.doc") { if ProAccess.shared.allows(.export) { copy() } }
163 }
164 }
165
166 /// The file on the clipboard as HTML, RTF and plain text, to paste formatted.
167 private func copy() {
168 let base = ((path as NSString).lastPathComponent as NSString).deletingPathExtension
169 let settings = OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile)
170 let html = HTMLExport.page(text, fallbackTitle: base, settings: settings, path: path,
171 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), language: OrgPreferences.exportLanguage())
172 do {
173 try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
174 report("Copied as rich text")
175 } catch {
176 report("\(error)")
177 }
178 }
179}
180
181/// The subtree at `caret` shared alone, in each of the export formats.
182struct SubtreeExportScreen: View {
183 let path: String
184 let text: String
185 let caret: Int
186 @Environment(MobileModel.self) private var model
187 @Environment(\.dismiss) private var dismiss
188
189 var body: some View {
190 NavigationStack {
191 List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
192 let export = OrgExport(text: text, path: path, format: format, settings: OrgPreferences.orgSettings(),
193 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), subtree: caret)
194 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
195 }
196 .navigationTitle("Export Subtree")
197 .navigationBarTitleDisplayMode(.inline)
198 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Done") { dismiss() } } }
199 }
200 }
201}
202#endif