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