Sources/OrgApp/DocxWriter.swift
352 lines · 19618 bytes
1import Foundation
2#if os(macOS)
3import AppKit
4typealias DocxFont = NSFont
5typealias DocxColor = NSColor
6#else
7import UIKit
8typealias DocxFont = UIFont
9typealias DocxColor = UIColor
10#endif
11
12/// Word's `.docx` from styled text: paragraphs with their runs' fonts, colors and links, and
13/// tables from the text's table blocks, which the system's own writer leaves out. iOS's HTML
14/// import keeps no tables, so there `tables` holds them, each standing for a paragraph that is
15/// its `marker` alone.
16enum DocxWriter {
17 static func marker(_ index: Int) -> String { "\u{E000}\(index)\u{E001}" }
18 /// Put at the start of a heading's text: 0 for the title, 1 to 6 for Word's heading levels.
19 static func headingMarker(_ level: Int) -> String { "\u{E002}\(level)\u{E003}" }
20 /// Stands for `images[index]` in the text.
21 static func imageMarker(_ index: Int) -> String { "\u{E004}\(index)\u{E005}" }
22
23 /// A picture for the document: PNG, JPEG or GIF bytes and its size in pixels.
24 struct Image: Equatable {
25 let data: Data
26 let ext: String
27 let width: Int
28 let height: Int
29 }
30
31 /// EMUs to a pixel at 96 to the inch, and to a twip.
32 static let emuPerPixel = 9525, emuPerTwip = 635
33
34 static func data(from text: NSAttributedString, tables: [String] = [], images: [Image] = []) -> Data {
35 var links: [String] = []
36 let letter = PDFExport.usesLetter()
37 let body = paragraphs(text, tables: tables, images: images, maxWidth: (letter ? 12240 : 11906) - 2 * 1134, links: &links)
38 let document = """
39 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
40 <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \
41 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" \
42 xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" \
43 xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" \
44 xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><w:body>\(body)\
45 \(section(letter: letter))\
46 </w:body></w:document>
47 """
48 let relationships = "<Relationship Id=\"styles\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles\" Target=\"styles.xml\"/>"
49 + links.enumerated().map { index, url in
50 "<Relationship Id=\"link\(index + 1)\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\" Target=\"\(escape(url))\" TargetMode=\"External\"/>"
51 }.joined()
52 + images.enumerated().map { index, image in
53 "<Relationship Id=\"img\(index + 1)\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\" Target=\"media/image\(index + 1).\(image.ext)\"/>"
54 }.joined()
55 let mediaTypes = Set(images.map(\.ext)).sorted().map { "<Default Extension=\"\($0)\" ContentType=\"image/\($0)\"/>" }.joined()
56 var zip = ZipWriter()
57 zip.add("[Content_Types].xml", """
58 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
59 <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\
60 <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\
61 <Default Extension="xml" ContentType="application/xml"/>\(mediaTypes)\
62 <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>\
63 <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>\
64 </Types>
65 """)
66 zip.add("_rels/.rels", """
67 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
68 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\
69 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>\
70 </Relationships>
71 """)
72 zip.add("word/_rels/document.xml.rels", """
73 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
74 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\(relationships)</Relationships>
75 """)
76 zip.add("word/document.xml", document)
77 zip.add("word/styles.xml", styles)
78 for (index, image) in images.enumerated() { zip.add("word/media/image\(index + 1).\(image.ext)", data: image.data) }
79 return zip.data()
80 }
81
82 /// Normal, Title and Word's built-in heading 1 to 6, so the navigation pane, outline view
83 /// and contents fields see the headings. The runs keep their own fonts and colors.
84 static let styles: String = {
85 let headings = (1...6).map { level in
86 "<w:style w:type=\"paragraph\" w:styleId=\"Heading\(level)\"><w:name w:val=\"heading \(level)\"/><w:basedOn w:val=\"Normal\"/>"
87 + "<w:next w:val=\"Normal\"/><w:uiPriority w:val=\"9\"/><w:qFormat/><w:pPr><w:keepNext/><w:outlineLvl w:val=\"\(level - 1)\"/></w:pPr>"
88 + "<w:rPr><w:b/></w:rPr></w:style>"
89 }.joined()
90 return """
91 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
92 <w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">\
93 <w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Helvetica Neue" w:hAnsi="Helvetica Neue" w:cs="Helvetica Neue"/>\
94 <w:sz w:val="22"/></w:rPr></w:rPrDefault><w:pPrDefault/></w:docDefaults>\
95 <w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>\
96 <w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/>\
97 <w:qFormat/><w:pPr><w:keepNext/></w:pPr><w:rPr><w:b/><w:sz w:val="40"/></w:rPr></w:style>\(headings)\
98 </w:styles>
99 """
100 }()
101
102 /// An inline picture, as wide as its pixels at 96 to the inch, or `maxWidth` twips if less.
103 static func drawing(_ image: Image, index: Int, maxWidth: Int) -> String {
104 var cx = image.width * emuPerPixel, cy = image.height * emuPerPixel
105 let limit = maxWidth * emuPerTwip
106 if cx > limit, cx > 0 {
107 cy = cy * limit / cx
108 cx = limit
109 }
110 let id = index + 1
111 return "<w:drawing><wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\"><wp:extent cx=\"\(cx)\" cy=\"\(cy)\"/>"
112 + "<wp:docPr id=\"\(id)\" name=\"Picture \(id)\"/><a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
113 + "<pic:pic><pic:nvPicPr><pic:cNvPr id=\"\(id)\" name=\"image\(id).\(image.ext)\"/><pic:cNvPicPr/></pic:nvPicPr>"
114 + "<pic:blipFill><a:blip r:embed=\"img\(id)\"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill>"
115 + "<pic:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"\(cx)\" cy=\"\(cy)\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr>"
116 + "</pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing>"
117 }
118
119 /// The page: Letter or A4, as PDF export has it. Without a size, readers pick their own, and
120 /// Quick Look and Pages pick a narrow one.
121 static func section(letter: Bool) -> String {
122 let size = letter ? "<w:pgSz w:w=\"12240\" w:h=\"15840\"/>" : "<w:pgSz w:w=\"11906\" w:h=\"16838\"/>"
123 return "<w:sectPr>\(size)<w:pgMar w:top=\"1134\" w:right=\"1134\" w:bottom=\"1134\" w:left=\"1134\" w:header=\"0\" w:footer=\"0\" w:gutter=\"0\"/></w:sectPr>"
124 }
125
126 /// Paragraphs in order, consecutive ones in the same table gathered into `<w:tbl>`.
127 /// A `<w:tbl>` of rows of cells, each cell its paragraphs.
128 static func table(_ rows: [[String]], columns: Int) -> String {
129 var out = "<w:tbl><w:tblPr><w:tblBorders>" + ["top", "left", "bottom", "right", "insideH", "insideV"].map {
130 "<w:\($0) w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"A0A0A0\"/>"
131 }.joined() + "</w:tblBorders><w:tblCellMar><w:left w:w=\"100\" w:type=\"dxa\"/><w:right w:w=\"100\" w:type=\"dxa\"/></w:tblCellMar></w:tblPr>"
132 out += "<w:tblGrid>" + String(repeating: "<w:gridCol/>", count: columns) + "</w:tblGrid>"
133 for row in rows {
134 out += "<w:tr>"
135 for column in 0..<columns {
136 out += "<w:tc><w:tcPr/>" + (column < row.count && !row[column].isEmpty ? row[column] : "<w:p/>") + "</w:tc>"
137 }
138 out += "</w:tr>"
139 }
140 return out + "</w:tbl>"
141 }
142
143 private static func paragraphs(_ text: NSAttributedString, tables: [String], images: [Image], maxWidth: Int, links: inout [String]) -> String {
144 let string = text.string as NSString
145 var out = ""
146 #if os(macOS)
147 var table: (block: NSTextTable, cells: [[Int: [String]]])?
148 func flushTable() {
149 guard let current = table else { return }
150 let columns = max(current.block.numberOfColumns, current.cells.map { ($0.keys.max() ?? 0) + 1 }.max() ?? 1)
151 out += Self.table(current.cells.map { row in (0..<columns).map { row[$0]?.joined() ?? "" } }, columns: columns)
152 table = nil
153 }
154 #else
155 func flushTable() {}
156 #endif
157 var location = 0
158 while location < string.length {
159 let range = string.paragraphRange(for: NSRange(location: location, length: 0))
160 location = NSMaxRange(range)
161 let line = string.substring(with: range).trimmingCharacters(in: .whitespacesAndNewlines)
162 if let index = tables.indices.first(where: { line == marker($0) }) {
163 flushTable()
164 out += tables[index]
165 continue
166 }
167 let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle
168 let paragraph = self.paragraph(text, range, style, images: images, maxWidth: maxWidth, links: &links)
169 #if os(macOS)
170 if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last {
171 if table?.block !== cell.table {
172 flushTable()
173 table = (cell.table, [])
174 }
175 while table!.cells.count <= cell.startingRow { table!.cells.append([:]) }
176 table!.cells[cell.startingRow][cell.startingColumn, default: []].append(paragraph)
177 continue
178 }
179 #endif
180 flushTable()
181 out += paragraph
182 }
183 flushTable()
184 return out
185 }
186
187 private static func paragraph(
188 _ text: NSAttributedString, _ range: NSRange, _ style: NSParagraphStyle?, images: [Image], maxWidth: Int, links: inout [String]
189 ) -> String {
190 // In the order the schema has them: style, tabs, spacing, indentation, justification.
191 var properties = ""
192 let content = (text.string as NSString).substring(with: range)
193 if let match = content.firstMatch(of: /^\s*\u{E002}(\d)\u{E003}/), let level = Int(match.1) {
194 properties += "<w:pStyle w:val=\"\(level == 0 ? "Title" : "Heading\(level)")\"/>"
195 }
196 if let style {
197 if !style.tabStops.isEmpty {
198 properties += "<w:tabs>" + style.tabStops.map { "<w:tab w:val=\"left\" w:pos=\"\(Int($0.location * 20))\"/>" }.joined() + "</w:tabs>"
199 }
200 properties += "<w:spacing w:before=\"\(Int(style.paragraphSpacingBefore * 20))\" w:after=\"\(Int(style.paragraphSpacing * 20))\"/>"
201 let left = Int(style.headIndent * 20), first = Int((style.firstLineHeadIndent - style.headIndent) * 20)
202 if left != 0 || first != 0 { properties += "<w:ind w:left=\"\(left)\" \(first < 0 ? "w:hanging=\"\(-first)\"" : "w:firstLine=\"\(first)\"")/>" }
203 switch style.alignment {
204 case .center: properties += "<w:jc w:val=\"center\"/>"
205 case .right: properties += "<w:jc w:val=\"right\"/>"
206 default: break
207 }
208 }
209 var runs = ""
210 text.enumerateAttributes(in: range, options: []) { attributes, runRange, _ in
211 var piece = (text.string as NSString).substring(with: runRange)
212 piece = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\n\r"))
213 piece = piece.replacing(/\u{E002}\d\u{E003}/, with: "")
214 guard !piece.isEmpty else { return }
215 var run = run(piece, attributes, images: images, maxWidth: maxWidth)
216 let link = (attributes[.link] as? URL)?.absoluteString ?? (attributes[.link] as? String)
217 if let link {
218 links.append(link)
219 run = "<w:hyperlink r:id=\"link\(links.count)\">\(run)</w:hyperlink>"
220 }
221 runs += run
222 }
223 return "<w:p><w:pPr>\(properties)</w:pPr>\(runs)</w:p>"
224 }
225
226 private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any], images: [Image], maxWidth: Int) -> String {
227 var properties = ""
228 if let font = attributes[.font] as? DocxFont {
229 let traits = self.traits(font)
230 let name = traits.mono ? "Menlo" : traits.family
231 properties += "<w:rFonts w:ascii=\"\(escape(name))\" w:hAnsi=\"\(escape(name))\" w:cs=\"\(escape(name))\"/>"
232 if traits.bold { properties += "<w:b/>" }
233 if traits.italic { properties += "<w:i/>" }
234 properties += "<w:sz w:val=\"\(Int((font.pointSize * 2).rounded()))\"/>"
235 }
236 if let color = (attributes[.foregroundColor] as? DocxColor).flatMap(rgba) { properties += "<w:color w:val=\"\(hex(color))\"/>" }
237 if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "<w:u w:val=\"single\"/>" }
238 if (attributes[.strikethroughStyle] as? Int ?? 0) != 0 { properties += "<w:strike/>" }
239 if let background = (attributes[.backgroundColor] as? DocxColor).flatMap(rgba), background.a > 0.05 {
240 properties += "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"\(hex(background))\"/>"
241 }
242 if let offset = attributes[.baselineOffset] as? Double, offset != 0 { properties += "<w:vertAlign w:val=\"\(offset > 0 ? "superscript" : "subscript")\"/>" }
243 // Tabs and line breaks are elements of their own.
244 var content = ""
245 var textRun = ""
246 func flush() {
247 if !textRun.isEmpty { content += "<w:t xml:space=\"preserve\">\(escape(textRun))</w:t>" }
248 textRun = ""
249 }
250 // A picture's marker: its index between the two marker characters.
251 var picture: String?
252 for character in piece {
253 if picture != nil {
254 if character == "\u{E005}" {
255 if let index = Int(picture!), images.indices.contains(index) { content += drawing(images[index], index: index, maxWidth: maxWidth) }
256 picture = nil
257 } else {
258 picture!.append(character)
259 }
260 continue
261 }
262 switch character {
263 case "\u{E004}": flush(); picture = ""
264 case "\t": flush(); content += "<w:tab/>"
265 case "\u{2028}", "\n": flush(); content += "<w:br/>"
266 default: textRun.append(character)
267 }
268 }
269 flush()
270 return "<w:r><w:rPr>\(properties)</w:rPr>\(content)</w:r>"
271 }
272
273 private static func traits(_ font: DocxFont) -> (bold: Bool, italic: Bool, mono: Bool, family: String) {
274 let traits = font.fontDescriptor.symbolicTraits
275 #if os(macOS)
276 return (traits.contains(.bold), traits.contains(.italic), traits.contains(.monoSpace), font.familyName ?? "Helvetica Neue")
277 #else
278 return (traits.contains(.traitBold), traits.contains(.traitItalic), traits.contains(.traitMonoSpace), font.familyName)
279 #endif
280 }
281
282 /// The color's sRGB components and alpha.
283 private static func rgba(_ color: DocxColor) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? {
284 #if os(macOS)
285 guard let c = color.usingColorSpace(.sRGB) else { return nil }
286 return (c.redComponent, c.greenComponent, c.blueComponent, c.alphaComponent)
287 #else
288 var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
289 guard color.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil }
290 return (r, g, b, a)
291 #endif
292 }
293
294 /// `#rrggbb` of the color laid on white paper: Word has no transparency.
295 private static func hex(_ color: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)) -> String {
296 func on(_ c: CGFloat) -> Int { Int(((c * color.a + (1 - color.a)) * 255).rounded()) }
297 return String(format: "%02X%02X%02X", on(color.r), on(color.g), on(color.b))
298 }
299
300 static func escape(_ s: String) -> String {
301 s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")
302 .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)
303 }
304}
305
306/// A zip archive with stored (uncompressed) entries, as `.docx` files are read.
307struct ZipWriter {
308 private var entries: [(name: Data, data: Data, crc: UInt32, offset: UInt32)] = []
309 private var archive = Data()
310
311 mutating func add(_ name: String, _ text: String) {
312 add(name, data: Data(text.utf8))
313 }
314
315 mutating func add(_ name: String, data: Data) {
316 let nameData = Data(name.utf8)
317 let crc = Self.crc32(data)
318 let offset = UInt32(archive.count)
319 archive += Self.le32(0x04034b50) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
320 archive += Self.le32(crc) + Self.le32(UInt32(data.count)) + Self.le32(UInt32(data.count))
321 archive += Self.le16(UInt16(nameData.count)) + Self.le16(0) + nameData + data
322 entries.append((nameData, data, crc, offset))
323 }
324
325 func data() -> Data {
326 var central = Data()
327 for entry in entries {
328 central += Self.le32(0x02014b50) + Self.le16(20) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
329 central += Self.le32(entry.crc) + Self.le32(UInt32(entry.data.count)) + Self.le32(UInt32(entry.data.count))
330 central += Self.le16(UInt16(entry.name.count)) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le32(0)
331 central += Self.le32(entry.offset) + entry.name
332 }
333 var end = Self.le32(0x06054b50) + Self.le16(0) + Self.le16(0) + Self.le16(UInt16(entries.count)) + Self.le16(UInt16(entries.count))
334 end += Self.le32(UInt32(central.count)) + Self.le32(UInt32(archive.count)) + Self.le16(0)
335 return archive + central + end
336 }
337
338 private static func le16(_ v: UInt16) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
339 private static func le32(_ v: UInt32) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
340
341 private static let table: [UInt32] = (0..<256).map { n in
342 var c = UInt32(n)
343 for _ in 0..<8 { c = c & 1 != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1 }
344 return c
345 }
346
347 static func crc32(_ data: Data) -> UInt32 {
348 var c: UInt32 = 0xFFFFFFFF
349 for byte in data { c = table[Int((c ^ UInt32(byte)) & 0xFF)] ^ (c >> 8) }
350 return c ^ 0xFFFFFFFF
351 }
352}