Tests/OrgCoreTests/ODTExportTests.swift
502 lines · 20391 bytes
1import Foundation
2import AppKit
3import ImageIO
4import Testing
5@testable import OrgCore
6
7/// `content.xml` reduced to what ox-odt and the native export must agree on: headings with
8/// their outline level, paragraphs, lists, sections, tables and their rows and cells, links
9/// and images with their targets, notes and frames, and the text runs. Spaces written as
10/// elements count as spaces; references are numbered in order of appearance, since ox-odt's
11/// are random.
12enum ODTSkeleton {
13 static let kept: Set<String> = [
14 "text:h", "text:p", "text:list", "text:list-item", "text:list-header", "text:section", "text:note",
15 "table:table", "table:table-header-rows", "table:table-rows", "table:table-row", "table:table-cell", "table:covered-table-cell",
16 "text:a", "draw:a", "draw:frame", "draw:image", "draw:text-box", "text:table-of-content", "text:index-body",
17 ]
18
19 static func reduce(_ xml: String) -> String {
20 guard let start = xml.range(of: "<office:text>"), let end = xml.range(of: "</office:text>") else { return xml }
21 let body = xml[start.upperBound..<end.lowerBound]
22 var lines: [String] = []
23 var text = ""
24 var references: [String: Int] = [:]
25 func flush() {
26 let collapsed = Skeleton.decode(text).split(whereSeparator: \.isWhitespace).joined(separator: " ")
27 if !collapsed.isEmpty { lines.append("\"" + collapsed + "\"") }
28 text = ""
29 }
30 var i = body.startIndex
31 while i < body.endIndex {
32 guard body[i] == "<", let close = body[i...].firstIndex(of: ">") else {
33 text.append(body[i])
34 i = body.index(after: i)
35 continue
36 }
37 let tag = String(body[body.index(after: i)..<close])
38 i = body.index(after: close)
39 if tag.hasPrefix("!") || tag.hasPrefix("?") { continue }
40 let closing = tag.hasPrefix("/")
41 let name = String(tag.dropFirst(closing ? 1 : 0).prefix { !$0.isWhitespace && $0 != "/" })
42 switch name {
43 case "text:s":
44 let count = tag.firstMatch(of: /text:c="([0-9]+)"/).flatMap { Int($0.1) } ?? 1
45 text += String(repeating: " ", count: count)
46 continue
47 case "text:tab", "text:line-break":
48 text += " "
49 continue
50 default:
51 break
52 }
53 guard kept.contains(name) else { continue }
54 flush()
55 if closing {
56 lines.append("</\(name)>")
57 continue
58 }
59 var attributes = ""
60 if let level = tag.firstMatch(of: /text:outline-level="([0-9]+)"/) { attributes += " level=\(level.1)" }
61 if let href = tag.firstMatch(of: /xlink:href="([^"]*)"/) {
62 var value = String(href.1)
63 if value.hasPrefix("#") {
64 let n = references[value] ?? references.count + 1
65 references[value] = n
66 value = "#ref\(n)"
67 }
68 attributes += " href=\"\(value)\""
69 }
70 if let span = tag.firstMatch(of: /table:number-columns-spanned="([0-9]+)"/) { attributes += " span=\(span.1)" }
71 lines.append("<\(name)\(attributes)>")
72 if tag.hasSuffix("/") { lines.append("</\(name)>") }
73 }
74 flush()
75 return lines.joined(separator: "\n") + "\n"
76 }
77}
78
79/// Reads a zip's entries, stored or deflated, through `unzip` for the latter.
80enum ZipReader {
81 struct Entry {
82 var name: String
83 var method: UInt16
84 var extraLength: UInt16
85 var data: Data
86 }
87
88 /// The local entries in order.
89 static func entries(_ data: Data) -> [Entry] {
90 var out: [Entry] = []
91 var at = 0
92 let bytes = [UInt8](data)
93 func u16(_ i: Int) -> UInt16 { UInt16(bytes[i]) | UInt16(bytes[i + 1]) << 8 }
94 func u32(_ i: Int) -> UInt32 { UInt32(u16(i)) | UInt32(u16(i + 2)) << 16 }
95 while at + 30 <= bytes.count, u32(at) == 0x04034b50 {
96 let method = u16(at + 8)
97 let size = Int(u32(at + 18))
98 let nameLength = Int(u16(at + 26))
99 let extra = u16(at + 28)
100 let name = String(decoding: bytes[(at + 30)..<(at + 30 + nameLength)], as: UTF8.self)
101 let start = at + 30 + nameLength + Int(extra)
102 out.append(Entry(name: name, method: method, extraLength: extra, data: Data(bytes[start..<(start + size)])))
103 at = start + size
104 }
105 return out
106 }
107
108 /// The names the central directory lists.
109 static func directory(_ data: Data) -> [String] {
110 let bytes = [UInt8](data)
111 var names: [String] = []
112 var i = 0
113 while i + 46 <= bytes.count {
114 if bytes[i] == 0x50, bytes[i + 1] == 0x4b, bytes[i + 2] == 0x01, bytes[i + 3] == 0x02 {
115 let length = Int(bytes[i + 28]) | Int(bytes[i + 29]) << 8
116 names.append(String(decoding: bytes[(i + 46)..<(i + 46 + length)], as: UTF8.self))
117 i += 46 + length
118 } else {
119 i += 1
120 }
121 }
122 return names
123 }
124}
125
126struct ODTExportTests {
127 static let oracle = ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil && EmacsOracle.isAvailable
128
129 /// A PNG of `width` by `height` pixels.
130 static func png(width: Int, height: Int) -> Data {
131 let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0,
132 space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
133 context.setFillColor(red: 1, green: 0, blue: 0, alpha: 1)
134 context.fill(CGRect(x: 0, y: 0, width: width, height: height))
135 let data = NSMutableData()
136 let destination = CGImageDestinationCreateWithData(data, "public.png" as CFString, 1, nil)!
137 CGImageDestinationAddImage(destination, context.makeImage()!, nil)
138 CGImageDestinationFinalize(destination)
139 return data as Data
140 }
141
142 static let corpus = ["minimal", "core", "headings", "listblocks", "lists", "table", "blocks", "timestamps", "footnote", "tblfm"]
143
144 /// Documents for what the corpus doesn't cover. `PIC` is replaced by an image's path.
145 static let snippets: [String: String] = [
146 "images": """
147 #+TITLE: Images
148
149 [[file:PIC]]
150
151 #+CAPTION: A captioned picture
152 #+NAME: fig:one
153 [[file:PIC]]
154
155 Inline [[file:PIC]] in text and a [[file:PIC][described]] link.
156
157 #+ATTR_ODT: :width 3
158 [[file:PIC]]
159
160 See [[fig:one]] and [[fig:one][the figure]].
161
162 [[https://example.com][file:PIC]]
163 """,
164 "tables": """
165 #+TITLE: Tables
166 #+OPTIONS: toc:nil
167
168 * One
169 #+CAPTION: Scores
170 #+NAME: tbl:scores
171 | Name | <r> |
172 | Name | Score |
173 |-------+-------|
174 | alpha | 10 |
175 |-------+-------|
176 | beta | x |
177 | gamma | |
178
179 Refer to [[tbl:scores]].
180
181 | / | <> | |
182 | # | a | b |
183 | ! | x | y |
184 | # | 1 | 2 |
185
186 | <5> | b |
187 | 1 | 2 |
188
189 #+ATTR_ODT: :rel-width 50
190 | c | d |
191 """,
192 "list-tables": """
193 #+OPTIONS: toc:nil
194
195 1. first
196 - nested
197 | a | b |
198 | 1 | 2 |
199 after the table
200 - next nested
201 2. second
202 | x |
203 | y |
204 then text
205 | z |
206
207 - term :: definition
208 | t |
209 """,
210 "footnotes": """
211 #+OPTIONS: toc:nil
212
213 One[fn:a][fn:b] and again[fn:a], anonymous[fn:: inline /note/].
214
215 [fn:a] First note.
216
217 With a second paragraph.
218 [fn:b] Second note.
219 """,
220 "low-levels": """
221 #+OPTIONS: H:2
222
223 * Top
224 ** Second
225 *** Third
226 Text under third.
227 **** Fourth
228 | cell |
229 *** Third again
230 * Other
231 """,
232 "links": """
233 #+TITLE: Links
234
235 * Alpha
236 :PROPERTIES:
237 :CUSTOM_ID: alpha-id
238 :ID: 1234-abcd
239 :END:
240 Go to [[*Beta]], [[Beta][the beta]], [[#alpha-id][custom]], [[#alpha-id]], [[id:1234-abcd]] and <<here>>.
241 * Beta
242 A <<<radio word>>> and later the radio word again. [[here][back]].
243 Mail [[mailto:a@b.c][me]], a file [[file:notes.txt]], ./rel.txt and [[./dir/x.org][rel]].
244 #+begin_src emacs-lisp -n -r
245 (setq x 1) (ref:one)
246 (setq y 2)
247 #+end_src
248 Line [[(one)]] and [[(one)][line %s]].
249 * Gamma :noexport:
250 Excluded.
251 * COMMENT Delta
252 Commented.
253 """,
254 "inline": """
255 #+TITLE: Inline /markup/
256 #+SUBTITLE: The subtitle
257 #+AUTHOR: Someone
258 #+DATE: <2024-03-01 Fri>
259 #+OPTIONS: num:nil pri:t
260
261 * TODO [#B] Heading with =code= :tag:
262 Text with *bold*, /italic/, _under_, +strike+, ~code spaced~, =verb=.
263 Math \\(a+b\\) and $x$ and \\alpha and H_2O and x^{2} and e^x.
264 Dashes -- and --- and ... and a\\-b.
265 Line one\\\\
266 line two.
267 @@odt:<text:span>raw</text:span>@@ and @@html:<b>no</b>@@ and [2/3] cookie.
268 #+ODT: <text:p>raw paragraph</text:p>
269
270 -----
271
272 \\begin{equation}
273 E = mc^2
274 \\end{equation}
275
276 :NOTES:
277 Drawer contents.
278 :END:
279
280 #+begin_verse
281 Indented first
282 second line
283 #+end_verse
284
285 #+begin_example -n
286 one
287 two
288 #+end_example
289
290 #+CAPTION: A listing
291 #+begin_src python
292 print("x")
293 #+end_src
294
295 : fixed width
296 : lines
297
298 #+begin_center
299 Centered *text*.
300 #+end_center
301
302 #+TOC: headlines 1
303 """,
304 "more": """
305 #+OPTIONS: toc:nil
306
307 * Heading
308 #+begin_src python
309
310 x = 1
311
312 y = 2
313
314 #+end_src
315
316 #+begin_example
317 ex
318
319
320 #+end_example
321
322 3. [@3] third
323 4. fourth
324 - [X] term :: def
325 - [ ] other :: more
326
327 #+begin_quote
328 - a quoted item
329 #+end_quote
330
331 [2024-01-01 Mon]--[2024-01-02 Tue] and <2024-01-01 Mon 10:00>
332
333 #+TOC: headlines local
334
335 ** Sub
336 Text \\alpha{} \\beta and \\nbsp{}.
337
338 #+begin_textbox
339 Boxed.
340 #+end_textbox
341
342 #+begin_annotation
343 Noted.
344 #+end_annotation
345 """,
346 "options": """
347 #+OPTIONS: toc:1 num:1 todo:nil tags:nil author:nil date:nil title:nil -:nil ^:{} tex:nil
348
349 * DONE First :x:
350 ** Sub
351 Text -- here a_b and a_{b} and \\(x\\).
352 * Second
353 """,
354 ]
355
356 /// Exports each document with ox-odt in one Emacs: its `content.xml`, or `ERROR: ` and the
357 /// message.
358 static func emacs(_ files: [URL]) throws -> [String] {
359 let folder = files[0].deletingLastPathComponent()
360 let output = folder.appendingPathComponent("out.json")
361 let script = folder.appendingPathComponent("odt.el")
362 try """
363 ;;; -*- lexical-binding: t -*-
364 (require 'ox-odt)
365 (require 'json)
366 (setq user-full-name "Tester")
367 (let (results)
368 (dolist (file (split-string (getenv "ODT_FILES") "\\n" t))
369 (push (condition-case err
370 (with-current-buffer (find-file-noselect file)
371 (let ((odt (org-odt-export-to-odt)))
372 (with-temp-buffer
373 (let ((coding-system-for-read 'utf-8))
374 (call-process "unzip" nil t nil "-p" odt "content.xml"))
375 (buffer-string))))
376 (error (concat "ERROR: " (error-message-string err))))
377 results))
378 (let ((coding-system-for-write 'utf-8))
379 (with-temp-file (getenv "ODT_OUTPUT")
380 (insert (json-encode (vconcat (nreverse results)))))))
381 """.write(to: script, atomically: true, encoding: .utf8)
382 try EmacsOracle.run(["-Q", "--batch", "-l", script.path], environment: [
383 "ODT_FILES": files.map(\.path).joined(separator: "\n"), "ODT_OUTPUT": output.path, "TZ": "UTC",
384 ])
385 return try JSONDecoder().decode([String].self, from: Data(contentsOf: output))
386 }
387
388 static func content(_ text: String, path: String) throws -> String {
389 let parts = try ODTExport.parts(text, path: path, author: "Tester")
390 return String(decoding: parts.first { $0.name == "content.xml" }!.data, as: UTF8.self)
391 }
392
393 @Test(.enabled(if: oracle))
394 func matchesOxODT() throws {
395 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
396 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
397 defer { try? FileManager.default.removeItem(at: folder) }
398 let picture = folder.appendingPathComponent("pic.png")
399 try Self.png(width: 64, height: 48).write(to: picture)
400 var documents: [(name: String, text: String)] = []
401 for name in Self.corpus {
402 documents.append((name, try String(contentsOf: ExportTests.folder.appendingPathComponent("\(name).org"), encoding: .utf8)))
403 }
404 for (name, text) in Self.snippets.sorted(by: { $0.key < $1.key }) {
405 documents.append((name, text.replacingOccurrences(of: "PIC", with: picture.path) + "\n"))
406 }
407 let files = documents.map { folder.appendingPathComponent($0.name + ".org") }
408 for (document, file) in zip(documents, files) { try document.text.write(to: file, atomically: true, encoding: .utf8) }
409 let expected = try Self.emacs(files)
410 for (index, document) in documents.enumerated() {
411 let theirs = ODTSkeleton.reduce(expected[index])
412 let ours = ODTSkeleton.reduce(try Self.content(document.text, path: files[index].path))
413 #expect(ours == theirs, "\(document.name)\n--- ours\n\(ours)\n--- ox-odt\n\(theirs)")
414 }
415 }
416
417 /// Where ox-odt stops, the export stops with its message.
418 @Test(.enabled(if: oracle))
419 func failsLikeOxODT() throws {
420 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
421 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
422 defer { try? FileManager.default.removeItem(at: folder) }
423 let documents = [
424 "broken": "See [[nowhere]].\n",
425 "missing": "[[file:missing.png]]\n",
426 "elements": try String(contentsOf: ExportTests.folder.appendingPathComponent("elements.org"), encoding: .utf8),
427 ].sorted { $0.key < $1.key }
428 let files = documents.map { folder.appendingPathComponent($0.key + ".org") }
429 for (document, file) in zip(documents, files) { try document.value.write(to: file, atomically: true, encoding: .utf8) }
430 let expected = try Self.emacs(files)
431 for (index, document) in documents.enumerated() {
432 #expect(expected[index].hasPrefix("ERROR: "), "\(document.key)")
433 #expect(throws: ODTExport.Failure.self) { try Self.content(document.value, path: files[index].path) }
434 do {
435 _ = try Self.content(document.value, path: files[index].path)
436 } catch let failure as ODTExport.Failure {
437 #expect(expected[index].contains(failure.message), "\(document.key): \(failure.message) / \(expected[index])")
438 }
439 }
440 }
441
442 /// `mimetype` first and stored, with no extra field; the manifest lists every part; each
443 /// XML part parses.
444 @Test func package() throws {
445 let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-odt-\(UUID().uuidString)")
446 try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
447 defer { try? FileManager.default.removeItem(at: folder) }
448 try Self.png(width: 10, height: 10).write(to: folder.appendingPathComponent("a.png"))
449 let path = folder.appendingPathComponent("doc.org").path
450 let data = try ODTExport.document("#+TITLE: T & U\n\n* Heading\n[[./a.png]]\n\n| x | y |\n", path: path)
451 let entries = ZipReader.entries(data)
452 #expect(entries.first?.name == "mimetype")
453 #expect(entries.first?.method == 0)
454 #expect(entries.first?.extraLength == 0)
455 #expect(entries.first.map { String(decoding: $0.data, as: UTF8.self) } == "application/vnd.oasis.opendocument.text")
456 #expect(ZipReader.directory(data) == entries.map(\.name))
457 #expect(entries.map(\.name) == ["mimetype", "content.xml", "styles.xml", "meta.xml", "Images/0001.png", "META-INF/manifest.xml"])
458 let manifest = try XMLDocument(data: entries.last!.data)
459 let listed = try manifest.nodes(forXPath: "//*[local-name()='file-entry']/@*[local-name()='full-path']").compactMap(\.stringValue)
460 for entry in entries where !["mimetype", "META-INF/manifest.xml"].contains(entry.name) {
461 #expect(listed.contains(entry.name), "\(entry.name)")
462 }
463 #expect(listed.contains("/"))
464 for entry in entries where entry.name.hasSuffix(".xml") {
465 #expect(throws: Never.self) { try XMLDocument(data: entry.data) }
466 }
467 let content = try XMLDocument(data: entries[1].data)
468 #expect(try content.nodes(forXPath: "//*[local-name()='h']").count == 1)
469 #expect(try content.nodes(forXPath: "//*[local-name()='image']/@*[local-name()='href']").compactMap(\.stringValue) == ["Images/0001.png"])
470 #expect(try content.nodes(forXPath: "//*[local-name()='table-cell']").count == 2)
471 let meta = try XMLDocument(data: entries[3].data)
472 #expect(try meta.nodes(forXPath: "//*[local-name()='title']").first?.stringValue == "T & U")
473 }
474
475 /// The text system reads the file: headings, list items, table cells and notes.
476 @Test func opensInTextKit() throws {
477 let text = "#+TITLE: Opened\n\n* Heading\n- item one\n- item two\n\n| a | b |\n|---+---|\n| 1 | 2 |\n\nA note.[fn:1]\n\n[fn:1] Noted.\n"
478 let data = try ODTExport.document(text, path: "/tmp/doc.org")
479 let string = try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.openDocument], documentAttributes: nil).string
480 for word in ["Opened", "Heading", "item one", "item two", "a", "2", "A note."] {
481 #expect(string.contains(word), "\(word) in \(string)")
482 }
483 }
484
485 /// What the native export can't write the way ox-odt does stops the export instead.
486 @Test(arguments: [
487 "*************** Task\nBody.\n*************** END\n",
488 "Here <<there>> and [[there]].\n",
489 "#+begin_src emacs-lisp\n(x) (ref:a)\n#+end_src\n[[(a)]]\n",
490 "#+ATTR_ODT: :style TableWithHeaderRowAndColumn\n| a |\n",
491 "Code src_python[:exports code]{1 + 1} here.\n",
492 "#+DATE: 2024\n#+begin_annotation\nNote.\n#+end_annotation\n",
493 ])
494 func refuses(_ text: String) {
495 #expect(throws: ODTExport.Failure.self) { try ODTExport.document(text, path: "/tmp/doc.org") }
496 }
497
498 @Test func imageFiles() {
499 let files = ODTExport.imageFiles("[[file:a.png]] [[./b.jpg][desc]] [[https://x/c.png]] [[/abs/d.svg]]\n", path: "/doc/notes.org")
500 #expect(files == ["/doc/a.png", "/abs/d.svg"])
501 }
502}