Sources/OrgApp/DocxWriter.swift

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