Sources/OrgstarMobile/ExportMenu.swift
341 lines · 17337 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 /// 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 let calendars = AgendaCalendars(model: model) {
231 if dividers { Divider() }
232 if OrgExport.Format.icalendar.locked {
233 Button("\(String(localized: "Export Agenda Files to iCalendar")) (orgstar+)", systemImage: "calendar") { ProAccess.shared.allows(.export) }
234 } else {
235 Button("Export Agenda Files to iCalendar", systemImage: "calendar") { report(calendars.exportEach()) }
236 ShareLink(item: calendars, preview: SharePreview(calendars.fileName)) {
237 Label("Combine Agenda Files into iCalendar", systemImage: "calendar.badge.plus")
238 }
239 }
240 }
241 if dividers { Divider() }
242 if ProAccess.shared.isUnlocked {
243 Button("Copy as Rich Text", systemImage: "doc.on.doc") { report(Self.copy(path: path, text: text, theme: model.theme)) }
244 } else {
245 Button("\(String(localized: "Copy as Rich Text")) (orgstar+)", systemImage: "doc.on.doc") { ProAccess.shared.allows(.export) }
246 }
247 }
248 }
249
250 /// Keeps the body-only choice for the file at `path`.
251 static func setBodyOnly(_ on: Bool, path: String) {
252 var settings = ExportSettings.saved(for: path)
253 settings.bodyOnly = on
254 settings.save(for: path)
255 }
256
257 /// The file on the clipboard as HTML, RTF and plain text, to paste formatted. Returns a message.
258 @MainActor
259 static func copy(path: String, text: String, theme: ThemeSpec) -> String {
260 let html = OrgExport.html(text, path: path, theme: theme)
261 do {
262 try RichTextExport.copy(html: html, directory: URL(fileURLWithPath: path).deletingLastPathComponent())
263 return "Copied as rich text"
264 } catch {
265 return "\(error)"
266 }
267 }
268}
269
270/// The agenda files as iCalendar: each to a calendar beside it
271/// (`org-icalendar-export-agenda-files`), or all in one calendar to share
272/// (`org-icalendar-combine-agenda-files`), named as `org-icalendar-combined-agenda-file` is.
273struct AgendaCalendars: Transferable {
274 let paths: [String]
275 /// The open files' text, which may not be saved yet.
276 let open: [String: String]
277
278 /// Nil without agenda files.
279 @MainActor init?(model: MobileModel) {
280 guard let paths = model.workspace?.agendaFilePaths(), !paths.isEmpty else { return nil }
281 self.paths = paths
282 open = Dictionary(model.session.openDocuments.map { ($0.path, $0.document.text) }, uniquingKeysWith: { first, _ in first })
283 }
284
285 var fileName: String { (OrgPreferences.icalendarCombinedFile() as NSString).lastPathComponent }
286
287 private func read(_ path: String) -> (text: String, settings: OrgSettings)? {
288 guard let text = open[path] ?? (try? String(contentsOfFile: path, encoding: .utf8)) else { return nil }
289 return (text, OrgPreferences.orgSettings().resolvingSetupFiles(in: text, path: path, read: OrgSettings.readFile))
290 }
291
292 /// Writes each agenda file's calendar beside it. Returns a message.
293 func exportEach() -> String {
294 do {
295 let written = try ICalendarFiles.exportEach(paths, options: OrgPreferences.icalendarOptions(), read: read)
296 return String(localized: "Exported \(written.count) agenda files to iCalendar")
297 } catch {
298 return "Can't export: \(error.localizedDescription)"
299 }
300 }
301
302 /// The combined calendar, in a new temporary folder.
303 func combined() throws -> URL {
304 let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
305 return try ICalendarFiles.combine(paths, to: folder.appendingPathComponent(fileName).path, options: OrgPreferences.icalendarOptions(), read: read)
306 }
307
308 static var transferRepresentation: some TransferRepresentation {
309 FileRepresentation(exportedContentType: .calendarEvent) { SentTransferredFile(try $0.combined()) }
310 }
311}
312
313/// The subtree at `caret` shared alone, in each of the export formats.
314struct SubtreeExportScreen: View {
315 let path: String
316 let tree: OrgTree
317 let caret: Int
318 @Environment(MobileModel.self) private var model
319 @Environment(\.dismiss) private var dismiss
320
321 var body: some View {
322 NavigationStack {
323 let bodyOnly = ExportSettings.saved(for: path).bodyOnly
324 let name = ExportScope.fileName(tree, subtreeAt: caret, settings: OrgPreferences.orgSettings())
325 List(OrgExport.Format.allCases.filter { !$0.locked }, id: \.self) { format in
326 if bodyOnly, !format.allowsBodyOnly {
327 LabeledContent(format.name) { Text("No body-only export") }.foregroundStyle(.secondary)
328 } else {
329 let export = OrgExport(text: tree.text, path: path, format: format, settings: OrgPreferences.orgSettings(),
330 codeStyle: HTMLCodeStyle(highlighter: MobileEditor.highlighter, theme: model.theme), name: name,
331 subtree: caret, bodyOnly: bodyOnly)
332 ShareLink(item: export, preview: SharePreview(export.fileName)) { Text(format.name) }
333 }
334 }
335 .navigationTitle("Export Subtree")
336 .navigationBarTitleDisplayMode(.inline)
337 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
338 }
339 }
340}
341#endif