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