Sources/OrgApp/DocxWriter.swift

211 lines · 11499 bytes

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