Sources/OrgApp/DocxWriter.swift
258 lines · 13465 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
19 static func data(from text: NSAttributedString, tables: [String] = []) -> Data {
20 var links: [String] = []
21 let body = paragraphs(text, tables: tables, links: &links)
22 let document = """
23 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
24 <w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" \
25 xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:body>\(body)\
26 <w:sectPr><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>\
27 </w:body></w:document>
28 """
29 let relationships = links.enumerated().map { index, url in
30 "<Relationship Id=\"link\(index + 1)\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink\" Target=\"\(escape(url))\" TargetMode=\"External\"/>"
31 }.joined()
32 var zip = ZipWriter()
33 zip.add("[Content_Types].xml", """
34 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
35 <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">\
36 <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>\
37 <Default Extension="xml" ContentType="application/xml"/>\
38 <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>\
39 </Types>
40 """)
41 zip.add("_rels/.rels", """
42 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
43 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\
44 <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>\
45 </Relationships>
46 """)
47 zip.add("word/_rels/document.xml.rels", """
48 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
49 <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">\(relationships)</Relationships>
50 """)
51 zip.add("word/document.xml", document)
52 return zip.data()
53 }
54
55 /// Paragraphs in order, consecutive ones in the same table gathered into `<w:tbl>`.
56 /// A `<w:tbl>` of rows of cells, each cell its paragraphs.
57 static func table(_ rows: [[String]], columns: Int) -> String {
58 var out = "<w:tbl><w:tblPr><w:tblBorders>" + ["top", "left", "bottom", "right", "insideH", "insideV"].map {
59 "<w:\($0) w:val=\"single\" w:sz=\"4\" w:space=\"0\" w:color=\"A0A0A0\"/>"
60 }.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>"
61 out += "<w:tblGrid>" + String(repeating: "<w:gridCol/>", count: columns) + "</w:tblGrid>"
62 for row in rows {
63 out += "<w:tr>"
64 for column in 0..<columns {
65 out += "<w:tc><w:tcPr/>" + (column < row.count && !row[column].isEmpty ? row[column] : "<w:p/>") + "</w:tc>"
66 }
67 out += "</w:tr>"
68 }
69 return out + "</w:tbl>"
70 }
71
72 private static func paragraphs(_ text: NSAttributedString, tables: [String], links: inout [String]) -> String {
73 let string = text.string as NSString
74 var out = ""
75 #if os(macOS)
76 var table: (block: NSTextTable, cells: [[Int: [String]]])?
77 func flushTable() {
78 guard let current = table else { return }
79 let columns = max(current.block.numberOfColumns, current.cells.map { ($0.keys.max() ?? 0) + 1 }.max() ?? 1)
80 out += Self.table(current.cells.map { row in (0..<columns).map { row[$0]?.joined() ?? "" } }, columns: columns)
81 table = nil
82 }
83 #else
84 func flushTable() {}
85 #endif
86 var location = 0
87 while location < string.length {
88 let range = string.paragraphRange(for: NSRange(location: location, length: 0))
89 location = NSMaxRange(range)
90 let line = string.substring(with: range).trimmingCharacters(in: .whitespacesAndNewlines)
91 if let index = tables.indices.first(where: { line == marker($0) }) {
92 flushTable()
93 out += tables[index]
94 continue
95 }
96 let style = text.attribute(.paragraphStyle, at: range.location, effectiveRange: nil) as? NSParagraphStyle
97 let paragraph = self.paragraph(text, range, style, links: &links)
98 #if os(macOS)
99 if let cell = style?.textBlocks.compactMap({ $0 as? NSTextTableBlock }).last {
100 if table?.block !== cell.table {
101 flushTable()
102 table = (cell.table, [])
103 }
104 while table!.cells.count <= cell.startingRow { table!.cells.append([:]) }
105 table!.cells[cell.startingRow][cell.startingColumn, default: []].append(paragraph)
106 continue
107 }
108 #endif
109 flushTable()
110 out += paragraph
111 }
112 flushTable()
113 return out
114 }
115
116 private static func paragraph(_ text: NSAttributedString, _ range: NSRange, _ style: NSParagraphStyle?, links: inout [String]) -> String {
117 var properties = ""
118 if let style {
119 switch style.alignment {
120 case .center: properties += "<w:jc w:val=\"center\"/>"
121 case .right: properties += "<w:jc w:val=\"right\"/>"
122 default: break
123 }
124 let left = Int(style.headIndent * 20), first = Int((style.firstLineHeadIndent - style.headIndent) * 20)
125 if left != 0 || first != 0 { properties += "<w:ind w:left=\"\(left)\" \(first < 0 ? "w:hanging=\"\(-first)\"" : "w:firstLine=\"\(first)\"")/>" }
126 properties += "<w:spacing w:before=\"\(Int(style.paragraphSpacingBefore * 20))\" w:after=\"\(Int(style.paragraphSpacing * 20))\"/>"
127 if !style.tabStops.isEmpty {
128 properties += "<w:tabs>" + style.tabStops.map { "<w:tab w:val=\"left\" w:pos=\"\(Int($0.location * 20))\"/>" }.joined() + "</w:tabs>"
129 }
130 }
131 var runs = ""
132 text.enumerateAttributes(in: range, options: []) { attributes, runRange, _ in
133 var piece = (text.string as NSString).substring(with: runRange)
134 piece = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\n\r"))
135 guard !piece.isEmpty else { return }
136 var run = run(piece, attributes)
137 let link = (attributes[.link] as? URL)?.absoluteString ?? (attributes[.link] as? String)
138 if let link {
139 links.append(link)
140 run = "<w:hyperlink r:id=\"link\(links.count)\">\(run)</w:hyperlink>"
141 }
142 runs += run
143 }
144 return "<w:p><w:pPr>\(properties)</w:pPr>\(runs)</w:p>"
145 }
146
147 private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any]) -> String {
148 var properties = ""
149 if let font = attributes[.font] as? DocxFont {
150 let traits = self.traits(font)
151 let name = traits.mono ? "Menlo" : traits.family
152 properties += "<w:rFonts w:ascii=\"\(escape(name))\" w:hAnsi=\"\(escape(name))\" w:cs=\"\(escape(name))\"/>"
153 if traits.bold { properties += "<w:b/>" }
154 if traits.italic { properties += "<w:i/>" }
155 properties += "<w:sz w:val=\"\(Int((font.pointSize * 2).rounded()))\"/>"
156 }
157 if let color = (attributes[.foregroundColor] as? DocxColor).flatMap(rgba) { properties += "<w:color w:val=\"\(hex(color))\"/>" }
158 if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "<w:u w:val=\"single\"/>" }
159 if (attributes[.strikethroughStyle] as? Int ?? 0) != 0 { properties += "<w:strike/>" }
160 if let background = (attributes[.backgroundColor] as? DocxColor).flatMap(rgba), background.a > 0.05 {
161 properties += "<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"\(hex(background))\"/>"
162 }
163 if let offset = attributes[.baselineOffset] as? Double, offset != 0 { properties += "<w:vertAlign w:val=\"\(offset > 0 ? "superscript" : "subscript")\"/>" }
164 // Tabs and line breaks are elements of their own.
165 var content = ""
166 var textRun = ""
167 func flush() {
168 if !textRun.isEmpty { content += "<w:t xml:space=\"preserve\">\(escape(textRun))</w:t>" }
169 textRun = ""
170 }
171 for character in piece {
172 switch character {
173 case "\t": flush(); content += "<w:tab/>"
174 case "\u{2028}", "\n": flush(); content += "<w:br/>"
175 default: textRun.append(character)
176 }
177 }
178 flush()
179 return "<w:r><w:rPr>\(properties)</w:rPr>\(content)</w:r>"
180 }
181
182 private static func traits(_ font: DocxFont) -> (bold: Bool, italic: Bool, mono: Bool, family: String) {
183 let traits = font.fontDescriptor.symbolicTraits
184 #if os(macOS)
185 return (traits.contains(.bold), traits.contains(.italic), traits.contains(.monoSpace), font.familyName ?? "Helvetica Neue")
186 #else
187 return (traits.contains(.traitBold), traits.contains(.traitItalic), traits.contains(.traitMonoSpace), font.familyName)
188 #endif
189 }
190
191 /// The color's sRGB components and alpha.
192 private static func rgba(_ color: DocxColor) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? {
193 #if os(macOS)
194 guard let c = color.usingColorSpace(.sRGB) else { return nil }
195 return (c.redComponent, c.greenComponent, c.blueComponent, c.alphaComponent)
196 #else
197 var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
198 guard color.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil }
199 return (r, g, b, a)
200 #endif
201 }
202
203 /// `#rrggbb` of the color laid on white paper: Word has no transparency.
204 private static func hex(_ color: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)) -> String {
205 func on(_ c: CGFloat) -> Int { Int(((c * color.a + (1 - color.a)) * 255).rounded()) }
206 return String(format: "%02X%02X%02X", on(color.r), on(color.g), on(color.b))
207 }
208
209 static func escape(_ s: String) -> String {
210 s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")
211 .replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)
212 }
213}
214
215/// A zip archive with stored (uncompressed) entries, as `.docx` files are read.
216struct ZipWriter {
217 private var entries: [(name: Data, data: Data, crc: UInt32, offset: UInt32)] = []
218 private var archive = Data()
219
220 mutating func add(_ name: String, _ text: String) {
221 let data = Data(text.utf8)
222 let nameData = Data(name.utf8)
223 let crc = Self.crc32(data)
224 let offset = UInt32(archive.count)
225 archive += Self.le32(0x04034b50) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
226 archive += Self.le32(crc) + Self.le32(UInt32(data.count)) + Self.le32(UInt32(data.count))
227 archive += Self.le16(UInt16(nameData.count)) + Self.le16(0) + nameData + data
228 entries.append((nameData, data, crc, offset))
229 }
230
231 func data() -> Data {
232 var central = Data()
233 for entry in entries {
234 central += Self.le32(0x02014b50) + Self.le16(20) + Self.le16(20) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0x21)
235 central += Self.le32(entry.crc) + Self.le32(UInt32(entry.data.count)) + Self.le32(UInt32(entry.data.count))
236 central += Self.le16(UInt16(entry.name.count)) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le16(0) + Self.le32(0)
237 central += Self.le32(entry.offset) + entry.name
238 }
239 var end = Self.le32(0x06054b50) + Self.le16(0) + Self.le16(0) + Self.le16(UInt16(entries.count)) + Self.le16(UInt16(entries.count))
240 end += Self.le32(UInt32(central.count)) + Self.le32(UInt32(archive.count)) + Self.le16(0)
241 return archive + central + end
242 }
243
244 private static func le16(_ v: UInt16) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
245 private static func le32(_ v: UInt32) -> Data { withUnsafeBytes(of: v.littleEndian) { Data($0) } }
246
247 private static let table: [UInt32] = (0..<256).map { n in
248 var c = UInt32(n)
249 for _ in 0..<8 { c = c & 1 != 0 ? 0xEDB88320 ^ (c >> 1) : c >> 1 }
250 return c
251 }
252
253 static func crc32(_ data: Data) -> UInt32 {
254 var c: UInt32 = 0xFFFFFFFF
255 for byte in data { c = table[Int((c ^ UInt32(byte)) & 0xFF)] ^ (c >> 8) }
256 return c ^ 0xFFFFFFFF
257 }
258}