SPB Git

Repository Public

DocxImportObjects.swift 22.5 KB 397 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocDOCX/DocxImportObjects.swift3// Description: WordprocessingML import of tables and drawings: table grid, merges, borders and shading; DrawingML pictures4//              (inline and anchored), shapes and text boxes; legacy VML pictures, watermarks and embedded-object previews.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer1112extension DocxImportContext {1314    // MARK: Tables1516    func tableRows(_ tbl: XMLNode) -> [XMLNode] {17        var rows: [XMLNode] = []18        for c in tbl.children {19            switch c.name {20            case "w:tr": rows.append(c)21            case "w:sdt": rows.append(contentsOf: tableRows(c.first("w:sdtContent") ?? XMLNode(name: "x")))22            case "w:customXml", "w:ins", "w:del", "w:moveFrom", "w:moveTo": rows.append(contentsOf: tableRows(c))23            default: break24            }25        }26        return rows27    }2829    func rowCells(_ tr: XMLNode) -> [XMLNode] {30        var cells: [XMLNode] = []31        for c in tr.children {32            switch c.name {33            case "w:tc": cells.append(c)34            case "w:sdt": cells.append(contentsOf: rowCells(c.first("w:sdtContent") ?? XMLNode(name: "x")))35            case "w:customXml", "w:ins", "w:del": cells.append(contentsOf: rowCells(c))36            default: break37            }38        }39        return cells40    }4142    func cellParagraphs(_ tc: XMLNode, story: DocxStory) -> [Paragraph] {43        story.tableDepth += 144        defer { story.tableDepth -= 1 }45        let blocks = parseBlocks(tc.children, story: story, allowTables: false)46        if blocks.contains(where: { $0.paragraph == nil }) {47            warn(.dropped, "Breaks in table cells", "Page breaks, section breaks and generated lists inside table cells are not supported.")48        }49        return blocks.compactMap(\.paragraph)50    }5152    /// A table where the model has no table (nested tables, headers, notes): its cell paragraphs in reading order.53    func flattenTable(_ tbl: XMLNode, story: DocxStory) -> [Block] {54        var out: [Block] = []55        for tr in tableRows(tbl) { for tc in rowCells(tr) { out.append(contentsOf: cellParagraphs(tc, story: story).map { .paragraph($0) }) } }56        return out57    }5859    func parseTable(_ tbl: XMLNode, story: DocxStory) -> Table {60        let tblPr = tbl.first("w:tblPr")61        var imported = resolvedTableStyle(tblPr?.val("w:tblStyle") ?? defaultTableStyle)62        if tblPr?.val("w:tblStyle") == nil && defaultTableStyle == nil { imported.style.name = "Custom" }63        if imported.unsupportedConditions {64            warn(.approximated, "Table styles", "Only the header-row and banded-row formatting of a table style is applied; first/last column, last row and corner formatting is not.")65        }66        if let tblPr { applyTableProperties(tblPr, to: &imported) }67        var firstRowLook = true68        if let look = tblPr?.first("w:tblLook") {69            if let f = look.attr("w:firstRow") { firstRowLook = docxBool(f) }70            else if let v = look.attr("w:val"), let bits = UInt32(v, radix: 16) { firstRowLook = bits & 0x20 != 0 }71        }72        var alignment = HorizontalAnchor.left73        switch tblPr?.val("w:jc") ?? "left" {74        case "center": alignment = .center75        case "right", "end": alignment = .right76        default: break77        }78        if tblPr?.first("w:tblpPr") != nil { warn(.approximated, "Floating tables", "A table positioned outside the text flow is imported in the text flow.") }79        if tblPr?.first("w:tblPrChange") != nil || tbl.first("w:tblGrid")?.first("w:tblGridChange") != nil {80            warn(.dropped, "Tracked table changes", "Tracked changes of table structure and properties are not kept; the current table is.")81        }8283        var widths = (tbl.first("w:tblGrid")?.all("w:gridCol") ?? []).map { max(1, DocxUnit.twips($0.attr("w:w")) ?? 72) }84        var rows: [TableRow] = []85        var trackedRows = false86        for tr in tableRows(tbl) {87            let trPr = tr.first("w:trPr")88            var cells: [TableCell] = []89            if let before = DocxUnit.int(trPr?.val("w:gridBefore")), before > 0 {90                cells.append(TableCell(paragraphs: [Paragraph(style: defaultParaStyle)], colSpan: min(before, 63)))91                warn(.approximated, "Irregular table rows", "Rows that start after or end before the table edge are completed with empty cells.")92            }93            if trPr?.first("w:ins") != nil || trPr?.first("w:del") != nil { trackedRows = true }94            for tc in rowCells(tr) {95                let tcPr = tc.first("w:tcPr")96                // Legacy horizontal merge: a continued cell extends the one before it.97                if let h = tcPr?.first("w:hMerge"), (h.attr("w:val") ?? "continue") == "continue", !cells.isEmpty {98                    cells[cells.count - 1].colSpan += max(1, DocxUnit.int(tcPr?.val("w:gridSpan")) ?? 1)99                    continue100                }101                story.cellFormula = nil102                var paragraphs = cellParagraphs(tc, story: story)103                if paragraphs.isEmpty { paragraphs = [Paragraph(style: defaultParaStyle)] }104                var cell = TableCell(paragraphs: paragraphs, colSpan: max(1, min(63, DocxUnit.int(tcPr?.val("w:gridSpan")) ?? 1)))105                cell.formula = story.cellFormula106                story.cellFormula = nil107                if let vm = tcPr?.first("w:vMerge") { cell.vMerge = (vm.attr("w:val") ?? "continue") == "restart" ? .restart : .continue }108                cell.shading = DocxImportContext.shading(tcPr?.first("w:shd"))109                switch tcPr?.val("w:vAlign") ?? "top" {110                case "center", "both": cell.vAlign = .center111                case "bottom": cell.vAlign = .bottom112                default: cell.vAlign = .top113                }114                if let bd = tcPr?.first("w:tcBorders") {115                    cell.borderTop = DocxImportContext.border(bd.first("w:top"))116                    cell.borderBottom = DocxImportContext.border(bd.first("w:bottom"))117                    cell.borderLeft = DocxImportContext.border(bd.first("w:left") ?? bd.first("w:start"))118                    cell.borderRight = DocxImportContext.border(bd.first("w:right") ?? bd.first("w:end"))119                    if DocxImportContext.border(bd.first("w:tl2br")) != nil || DocxImportContext.border(bd.first("w:tr2bl")) != nil {120                        warn(.dropped, "Diagonal cell borders", "Diagonal borders in table cells are not supported.")121                    }122                }123                if tcPr?.first("w:cellIns") != nil || tcPr?.first("w:cellDel") != nil || tcPr?.first("w:cellMerge") != nil { trackedRows = true }124                if let dir = tcPr?.val("w:textDirection"), dir != "lrTb" { warn(.dropped, "Rotated cell text", "Vertical or rotated text in table cells is imported as horizontal text.") }125                cells.append(cell)126            }127            if let after = DocxUnit.int(trPr?.val("w:gridAfter")), after > 0 {128                cells.append(TableCell(paragraphs: [Paragraph(style: defaultParaStyle)], colSpan: min(after, 63)))129            }130            if cells.isEmpty { cells = [TableCell(paragraphs: [Paragraph(style: defaultParaStyle)])] }131            var row = TableRow(cells: cells, isHeader: docxOnOff(trPr?.first("w:tblHeader")) ?? false)132            if let h = DocxUnit.twips(trPr?.val("w:trHeight")), h > 0 { row.minHeight = h }133            rows.append(row)134        }135        if trackedRows { warn(.dropped, "Tracked table changes", "Tracked insertions and deletions of rows and cells are not kept; the current table is.") }136        if rows.isEmpty { rows = [TableRow(cells: [TableCell(paragraphs: [Paragraph(style: defaultParaStyle)])])] }137138        // Make the grid and the rows agree.139        let columns = max(widths.count, rows.map { $0.cells.reduce(0) { $0 + $1.colSpan } }.max() ?? 1, 1)140        if widths.count < columns {141            let known = widths.reduce(0, +)142            let fallback = widths.isEmpty ? max(36, doc.pageSetup.contentWidth / Double(columns)) : known / Double(widths.count)143            widths.append(contentsOf: Array(repeating: fallback, count: columns - widths.count))144        }145        var padded = false146        for i in rows.indices {147            let span = rows[i].cells.reduce(0) { $0 + $1.colSpan }148            if span < columns {149                rows[i].cells.append(TableCell(paragraphs: [Paragraph(style: defaultParaStyle)], colSpan: columns - span))150                padded = true151            }152        }153        if padded { warn(.approximated, "Irregular table rows", "Rows that start after or end before the table edge are completed with empty cells.") }154155        // Table-level frames that are not a full box, and the header rule of the table style, become cell borders.156        if imported.hasBorders, imported.style.outerBorder == nil {157            let lastRow = rows.count - 1158            for r in rows.indices {159                for c in rows[r].cells.indices {160                    if r == 0, let b = imported.top, rows[r].cells[c].borderTop == nil { rows[r].cells[c].borderTop = b }161                    if r == lastRow, let b = imported.bottom, rows[r].cells[c].borderBottom == nil { rows[r].cells[c].borderBottom = b }162                    if c == 0, let b = imported.left, rows[r].cells[c].borderLeft == nil { rows[r].cells[c].borderLeft = b }163                    if c == rows[r].cells.count - 1, let b = imported.right, rows[r].cells[c].borderRight == nil { rows[r].cells[c].borderRight = b }164                }165            }166        }167        if firstRowLook, let rule = imported.firstRowBottom, !rows.isEmpty {168            for c in rows[0].cells.indices where rows[0].cells[c].borderBottom == nil { rows[0].cells[c].borderBottom = rule }169        }170        return Table(columnWidths: widths, rows: rows, style: imported.style, alignment: alignment)171    }172173    // MARK: Media174175    /// Loads the image behind a relationship id into `doc.assets` and returns the asset id.176    func asset(relID: String?, story: DocxStory, feature: String) -> String? {177        guard let relID, let rel = story.rels[relID] else {178            warn(.dropped, feature, "A picture has no image data in the file and was dropped.")179            return nil180        }181        if rel.external {182            warn(.dropped, "Linked pictures", "A picture linked to an external file or address is not fetched and was dropped.")183            return nil184        }185        guard let part = OPC.resolve(target: rel.target, from: story.part) else {186            warn(.dropped, "Unsafe relationship", "A picture relationship points outside the package and was ignored.")187            return nil188        }189        if let id = assetByPart[part] { return id }190        guard let data = try? partData(part), !data.isEmpty else {191            warn(.dropped, feature, "The image file \(part) is missing from the package.")192            return nil193        }194        let ext = (part as NSString).pathExtension.lowercased()195        guard let mime = DocxMedia.sniff(data) ?? (["emf", "wmf", "svg"].contains(ext) ? DocxMedia.mimeByExtension[ext] : nil) else {196            warn(.dropped, feature, "The file \(part) is not a recognised image and was dropped.")197            consumed.insert(part)198            return nil199        }200        if mime == "image/x-emf" || mime == "image/x-wmf" { warn(.approximated, "Metafile pictures", "EMF/WMF pictures are kept but may not display on macOS.") }201        consumed.insert(part)202        let id = DocxMedia.assetID(for: data)203        if doc.assets[id] == nil { doc.assets[id] = Asset(id: id, mimeType: mime, data: data) }204        assetByPart[part] = id205        return id206    }207208    // MARK: DrawingML209210    func parseDrawing(_ drawing: XMLNode, _ rp: DocxRunProps, _ st: DocxInlineState, _ b: inout DocxParaBuilder, _ story: DocxStory) {211        guard let container = drawing.first("wp:inline") ?? drawing.first("wp:anchor") else {212            warn(.dropped, "Drawings", "A drawing without content was dropped.")213            return214        }215        let width = DocxUnit.emu(container.first("wp:extent")?.attr("cx")) ?? 72216        let height = DocxUnit.emu(container.first("wp:extent")?.attr("cy")) ?? 72217        let docPr = container.first("wp:docPr")218        let alt = docPr?.attr("descr") ?? docPr?.attr("title") ?? ""219        let placement = self.placement(container)220        guard let data = container.path("a:graphic", "a:graphicData") else { return }221        let uri = data.attr("uri") ?? ""222223        if let pic = data.first("pic:pic") {224            if let image = picture(pic, width: width, height: height, alt: alt, placement: placement, story: story) {225                appendInline(.image(image), rp, st, &b, story)226            }227            return228        }229        if let wsp = data.first("wps:wsp") {230            importShape(wsp, width: width, height: height, alt: alt, placement: placement, rp, st, &b, story)231            return232        }233        if uri.contains("chart") {234            warn(.dropped, "Charts", "A chart is not imported\(alt.isEmpty ? "" : " (alternative text: \(alt))").")235        } else if uri.contains("diagram") {236            warn(.dropped, "SmartArt", "A SmartArt diagram is not imported.")237        } else if data.first("wpg:wgp") != nil || data.first("wpc:wpc") != nil {238            warn(.approximated, "Grouped drawings", "A group of shapes is not kept as a group; its pictures and text are imported one after the other.")239            for pic in data.descendants("pic:pic") {240                let ext = pic.path("pic:spPr", "a:xfrm", "a:ext")241                if let image = picture(pic, width: DocxUnit.emu(ext?.attr("cx")) ?? width, height: DocxUnit.emu(ext?.attr("cy")) ?? height, alt: alt, placement: .inline, story: story) {242                    appendInline(.image(image), rp, st, &b, story)243                }244            }245            extractTextBoxes(data, &b, story, warnAs: nil)246        } else {247            warn(.dropped, "Drawings", "A drawing object of an unsupported kind was dropped.")248            extractTextBoxes(data, &b, story, warnAs: nil)249        }250    }251252    func placement(_ container: XMLNode) -> Placement {253        guard container.name == "wp:anchor" else { return .inline }254        var wrap = WrapMode.square255        if container.first("wp:wrapTopAndBottom") != nil { wrap = .topAndBottom }256        else if container.first("wp:wrapNone") != nil { wrap = docxBool(container.attr("behindDoc")) ? .behindText : .inFrontOfText }257        var align = HorizontalAnchor.left258        var x = 0.0, y = 0.0259        if let h = container.first("wp:positionH") {260            switch h.first("wp:align")?.text.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" {261            case "center": align = .center262            case "right", "outside": align = .right263            default: break264            }265            x = DocxUnit.emu(h.first("wp:posOffset")?.text.trimmingCharacters(in: .whitespacesAndNewlines)) ?? 0266            if let from = h.attr("relativeFrom"), from != "column", from != "margin" {267                warn(.approximated, "Floating object positions", "Objects positioned relative to the page or a character are placed relative to the text column.")268            }269        }270        if let v = container.first("wp:positionV") {271            y = DocxUnit.emu(v.first("wp:posOffset")?.text.trimmingCharacters(in: .whitespacesAndNewlines)) ?? 0272            if let from = v.attr("relativeFrom"), from != "paragraph", from != "line" {273                warn(.approximated, "Floating object positions", "Objects positioned vertically relative to the page or margin are placed relative to their paragraph.")274            }275        }276        return .floating(wrap: wrap, align: align, xOffset: x, yOffset: y)277    }278279    func picture(_ pic: XMLNode, width: Double, height: Double, alt: String, placement: Placement, story: DocxStory) -> ImageObject? {280        let blip = pic.path("pic:blipFill", "a:blip")281        var relID = blip?.attr("r:embed")282        if relID == nil, let link = blip?.attr("r:link") { relID = link }283        guard let asset = asset(relID: relID, story: story, feature: "Pictures") else { return nil }284        var image = ImageObject(asset: asset, width: max(1, width), height: max(1, height), altText: alt, placement: placement)285        if let src = pic.path("pic:blipFill", "a:srcRect") {286            func f(_ name: String) -> Double { max(0, min(1, (Double(src.attr(name) ?? "0") ?? 0) / 100_000)) }287            image.crop = Insets(top: f("t"), left: f("l"), bottom: f("b"), right: f("r"))288        }289        if let rot = pic.path("pic:spPr", "a:xfrm")?.attr("rot"), let v = Double(rot) { image.rotation = v / 60_000 }290        if blip?.children.contains(where: { ["a:duotone", "a:grayscl", "a:biLevel", "a:lum", "a:clrChange"].contains($0.name) }) == true {291            warn(.dropped, "Picture effects", "Recolouring and brightness adjustments of pictures are not applied.")292        }293        return image294    }295296    static func solidColor(_ n: XMLNode?) -> RGBA? {297        guard let fill = n?.first("a:solidFill") else { return nil }298        if let hex = fill.first("a:srgbClr")?.attr("val") { return RGBA(hexString: hex) }299        if fill.first("a:schemeClr") != nil { return RGBA(hex: 0x4472C4) }300        return nil301    }302303    func importShape(_ wsp: XMLNode, width: Double, height: Double, alt: String, placement: Placement,304                     _ rp: DocxRunProps, _ st: DocxInlineState, _ b: inout DocxParaBuilder, _ story: DocxStory) {305        let spPr = wsp.first("wps:spPr")306        let prst = spPr?.first("a:prstGeom")?.attr("prst") ?? "rect"307        let isTextBox = docxBool(wsp.first("wps:cNvSpPr")?.attr("txBox")) || prst == "textBox"308        let txbx = wsp.first("wps:txbx")?.first("w:txbxContent")309        let ln = spPr?.first("a:ln")310        var kind: ShapeObject.Kind?311        switch prst {312        case "rect": kind = .rectangle313        case "roundRect": kind = .roundedRectangle314        case "ellipse": kind = .ellipse315        case "line", "straightConnector1": kind = (ln?.first("a:tailEnd") != nil || ln?.first("a:headEnd") != nil) ? .arrow : .line316        case "rightArrow": kind = .arrow317        case "wedgeRectCallout", "wedgeRoundRectCallout", "wedgeEllipseCallout": kind = .callout318        default: kind = nil319        }320        let richText = txbx.map { $0.descendants("w:p").count > 1 || $0.firstDescendant("w:drawing") != nil || $0.firstDescendant("w:tbl") != nil } ?? false321        if isTextBox || kind == nil || richText {322            if txbx != nil {323                extractTextBoxes(wsp, &b, story, warnAs: "Text boxes")324            } else {325                warn(.dropped, "Shapes", "A \"\(prst)\" shape has no equivalent and was dropped.")326            }327            return328        }329        var shape = ShapeObject(kind: kind!, width: max(1, width), height: max(1, height), placement: placement)330        shape.altText = alt331        shape.text = txbx.map { $0.descendants("w:p").map { plainText(of: $0) }.joined(separator: "\n") } ?? ""332        if ln?.first("a:noFill") != nil { shape.strokeWidth = 0 } else {333            if let c = DocxImportContext.solidColor(ln) { shape.stroke = c }334            if let w = DocxUnit.emu(ln?.attr("w")) { shape.strokeWidth = w }335        }336        shape.fill = DocxImportContext.solidColor(spPr)337        appendInline(.shape(shape), rp, st, &b, story)338    }339340    /// Text boxes have no model equivalent: their paragraphs are placed after the paragraph that anchors them.341    func extractTextBoxes(_ node: XMLNode, _ b: inout DocxParaBuilder, _ story: DocxStory, warnAs feature: String?) {342        let boxes = node.name == "w:txbxContent" ? [node] : node.descendants("w:txbxContent")343        guard !boxes.isEmpty else { return }344        if let feature { warn(.approximated, feature, "A text box is not kept as a floating box; its text is placed after the paragraph it is attached to.") }345        for box in boxes {346            let inner = DocxStory(part: story.part, rels: Array(story.rels.values), kind: story.kind)347            inner.tableDepth = story.tableDepth348            let allow = story.kind == .body && story.tableDepth == 0349            b.trailing.append(contentsOf: parseBlocks(box.children, story: inner, allowTables: allow).filter {350                // Section breaks cannot live in a text box; everything else is content.351                if case .sectionBreak = $0 { return false } else { return true }352            })353            closeStory(inner)354        }355    }356357    // MARK: VML358359    static func cssLength(_ style: String, _ property: String) -> Double? {360        for decl in style.split(separator: ";") {361            let kv = decl.split(separator: ":", maxSplits: 1).map { $0.trimmingCharacters(in: .whitespaces) }362            guard kv.count == 2, kv[0].lowercased() == property else { continue }363            guard let twips = DocxUnit.number(kv[1].hasSuffix("px") ? String(Double(kv[1].dropLast(2)).map { $0 * 0.75 } ?? 0) + "pt" : kv[1]) else { return nil }364            return kv[1].contains(where: \.isLetter) ? twips / 20 : twips365        }366        return nil367    }368369    func parseVML(_ node: XMLNode, isObject: Bool, _ rp: DocxRunProps, _ st: DocxInlineState, _ b: inout DocxParaBuilder, _ story: DocxStory) {370        if isObject {371            warn(.dropped, "Embedded objects", "An embedded OLE object is not imported and never opened\(node.firstDescendant("v:imagedata") != nil ? "; its preview picture is kept" : "").")372        }373        if let text = node.descendants("v:textpath").compactMap({ $0.attr("string") }).first(where: { !$0.isEmpty }) {374            if story.kind == .header { story.watermark = text } else {375                warn(.approximated, "WordArt", "WordArt text is imported as plain text.")376                appendText(text, rp, st, &b, story)377            }378            return379        }380        var handled = isObject381        for shape in node.descendants("v:shape") + node.descendants("v:rect") {382            if let data = shape.first("v:imagedata") {383                handled = true384                guard let id = asset(relID: data.attr("r:id") ?? data.attr("r:pict") ?? data.attr("r:href"), story: story, feature: "Pictures") else { continue }385                let style = shape.attr("style") ?? ""386                let w = DocxImportContext.cssLength(style, "width") ?? 144, h = DocxImportContext.cssLength(style, "height") ?? 108387                appendInline(.image(ImageObject(asset: id, width: max(1, w), height: max(1, h), altText: shape.attr("alt") ?? data.attr("o:title") ?? "")), rp, st, &b, story)388            }389        }390        if node.firstDescendant("w:txbxContent") != nil {391            handled = true392            extractTextBoxes(node, &b, story, warnAs: "Text boxes")393        }394        if !handled { warn(.dropped, "Legacy drawings", "A legacy (VML) drawing was dropped.") }395    }396}397
Files main
Menu

Theme