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