Sources/OrgApp/DocxWriter.swift

305 lines · 17343 bytes

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