SPB Git

Repository Public

RTFExporter.swift 14.2 KB 263 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocFormats/RTFExporter.swift3// Description: RTF export through AppKit's RTF writer: resolved fonts and paragraph formatting, lists, tables, links and4//              PNG/JPEG pictures. Notes are appended, equations written as LaTeX, and everything RTF cannot carry is reported.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import AppKit10import DocModel11import DocContainer1213public enum RTFExporter {14    public static func export(_ doc: DocumentModel) -> ExportResult { export(doc, options: ExportOptions()) }1516    public static func export(_ doc: DocumentModel, options: ExportOptions) -> ExportResult {17        var writer = RTFWriter(doc, options: options)18        let data = writer.write()19        return ExportResult(data: data, warnings: writer.ctx.finalWarnings(source: doc, format: .rtf))20    }21}2223private struct RTFWriter {24    var ctx: ExportContext25    private var doc: DocumentModel { ctx.doc }26    private let out = NSMutableAttributedString()27    private var pictures: [(data: Data, jpeg: Bool, pixels: (Int, Int), points: (Double, Double))?] = []28    private var textLists: [String: NSTextList] = [:]29    private var fontCache: [String: NSFont] = [:]3031    init(_ source: DocumentModel, options: ExportOptions) { ctx = ExportContext(source, options: options) }3233    private static func colour(_ c: RGBA) -> NSColor { NSColor(srgbRed: c.r, green: c.g, blue: c.b, alpha: c.a) }3435    private mutating func font(_ c: ResolvedChar) -> NSFont {36        let key = "\(c.fontFamily)|\(c.fontSize)|\(c.isBold)|\(c.italic)"37        if let f = fontCache[key] { return f }38        let size = CGFloat(max(1, min(1638, c.fontSize)))39        var traits: NSFontDescriptor.SymbolicTraits = []40        if c.isBold { traits.insert(.bold) }41        if c.italic { traits.insert(.italic) }42        func make(_ family: String) -> NSFont? {43            let descriptor = NSFontDescriptor(fontAttributes: [.family: family]).withSymbolicTraits(traits)44            guard let f = NSFont(descriptor: descriptor, size: size), f.familyName == family else { return nil }45            return f46        }47        var result = make(c.fontFamily)48        if result == nil {49            // The family has no installed named face (system UI fonts, missing fonts): substitute a face RTF readers know.50            ctx.warnings.add(.approximated, "Fonts", "Fonts that are not installed as named families (\(c.fontFamily)) are replaced by Times New Roman or Helvetica in RTF.")51            let serif = ["New York", "Charter", "Georgia", "Palatino"].contains(c.fontFamily)52            result = make(serif ? "Times New Roman" : "Helvetica") ?? NSFont.userFont(ofSize: size)53        }54        let f = result ?? NSFont.systemFont(ofSize: size)55        fontCache[key] = f56        return f57    }5859    private mutating func attributes(_ run: Run, in p: Paragraph, style: NSParagraphStyle) -> [NSAttributedString.Key: Any] {60        let c = doc.styles.charProps(paraStyle: p.style, charStyle: run.charStyle, direct: run.props)61        var a: [NSAttributedString.Key: Any] = [.font: font(c), .foregroundColor: RTFWriter.colour(c.color), .paragraphStyle: style]62        if c.underline { a[.underlineStyle] = NSUnderlineStyle.single.rawValue }63        if c.strikethrough { a[.strikethroughStyle] = NSUnderlineStyle.single.rawValue }64        if let h = c.highlight { a[.backgroundColor] = RTFWriter.colour(h) }65        switch c.vertical {66        case .superscript: a[.superscript] = 167        case .subscript: a[.superscript] = -168        case .baseline: if c.baselineShift != 0 { a[.baselineOffset] = c.baselineShift }69        }70        if c.tracking != 0 { a[.kern] = c.tracking }71        if let link = c.link, !link.isEmpty, LinkPolicy.sanitize(link) != nil { a[.link] = URL(string: link) ?? link as Any }72        return a73    }7475    private func paragraphStyle(_ p: Paragraph, blocks: [NSTextBlock] = []) -> NSMutableParagraphStyle {76        let r = doc.styles.paraProps(style: p.style, direct: p.props)77        let s = NSMutableParagraphStyle()78        switch r.alignment {79        case .left: s.alignment = .left80        case .center: s.alignment = .center81        case .right: s.alignment = .right82        case .justified: s.alignment = .justified83        }84        s.headIndent = r.indentLeft85        s.firstLineHeadIndent = r.indentLeft + r.firstLineIndent86        s.tailIndent = r.indentRight > 0 ? -r.indentRight : 087        s.paragraphSpacing = r.spaceAfter88        s.paragraphSpacingBefore = r.spaceBefore89        switch r.lineSpacing {90        case .multiple(let m): s.lineHeightMultiple = m91        case .exact(let pt): s.minimumLineHeight = pt; s.maximumLineHeight = pt92        case .atLeast(let pt): s.minimumLineHeight = pt93        }94        if !r.tabs.isEmpty {95            s.tabStops = r.tabs.map { NSTextTab(textAlignment: $0.kind == .center ? .center : $0.kind == .right || $0.kind == .decimal ? .right : .left, location: $0.position) }96        }97        if r.rightToLeft { s.baseWritingDirection = .rightToLeft }98        s.textBlocks = blocks99        return s100    }101102    private mutating func textList(_ item: ListItem, _ def: ListDefinition) -> [NSTextList] {103        var chain: [NSTextList] = []104        let level = max(0, min(def.levels.count - 1, item.level))105        for l in 0...level {106            let key = "\(item.listID)|\(l)"107            if let known = textLists[key] { chain.append(known); continue }108            let format: NSTextList.MarkerFormat109            switch def.levels[l].format {110            case .decimal: format = .decimal111            case .lowerAlpha: format = .lowercaseAlpha112            case .upperAlpha: format = .uppercaseAlpha113            case .lowerRoman: format = .lowercaseRoman114            case .upperRoman: format = .uppercaseRoman115            case .bullet, .none: format = [.disc, .circle, .square][l % 3]116            }117            let list = NSTextList(markerFormat: format, options: 0)118            list.startingItemNumber = def.levels[l].start119            textLists[key] = list120            chain.append(list)121        }122        return chain123    }124125    /// Appends one paragraph (with its terminator).126    private mutating func append(_ p: Paragraph, blocks: [NSTextBlock] = [], prefix: String = "") {127        let style = paragraphStyle(p, blocks: blocks)128        var listPrefix = ""129        if let item = p.list, let def = doc.list(item.listID), !def.levels.isEmpty {130            let level = max(0, min(def.levels.count - 1, item.level))131            style.textLists = textList(item, def)132            let indent = def.levels[level].indent, hanging = def.levels[level].hanging133            style.headIndent = indent134            style.firstLineHeadIndent = max(0, indent - hanging)135            style.tabStops = [NSTextTab(textAlignment: .left, location: max(0, indent - hanging)), NSTextTab(textAlignment: .left, location: indent)]136            listPrefix = "\t" + (ctx.numbering.listLabels[p.id] ?? "•") + "\t"137        }138        let start = out.length139        var sequenceIndex = 0140        let base = Run("")141        func text(_ s: String, like run: Run, _ writer: inout RTFWriter) {142            guard !s.isEmpty else { return }143            writer.out.append(NSAttributedString(string: s, attributes: writer.attributes(run, in: p, style: style)))144        }145        text(listPrefix + prefix + ctx.headingNumberPrefix(p), like: base, &self)146        for run in p.runs {147            guard let inline = run.inline else { text(run.text, like: run, &self); continue }148            var plain = run149            plain.inline = nil150            switch inline {151            case .image(let image):152                guard let asset = doc.assets[image.asset] else {153                    ctx.warnings.add(.dropped, "Missing images", "An image has no data in the document; its alternative text was written instead.")154                    text(image.altText, like: plain, &self)155                    break156                }157                var data = asset.data158                let jpeg = asset.mimeType == "image/jpeg"159                if !jpeg, asset.mimeType != "image/png" {160                    guard let png = ImageSupport.pngData(from: asset.data) else {161                        ctx.warnings.add(.dropped, "Images", "An image that cannot be converted to PNG was replaced by its alternative text.")162                        text(image.altText, like: plain, &self)163                        break164                    }165                    data = png166                    ctx.warnings.add(.approximated, "Images", "Images other than PNG and JPEG are converted to PNG in RTF.")167                }168                let pixels = ImageSupport.pixelSize(data) ?? (Int(image.width.rounded()), Int(image.height.rounded()))169                pictures.append((data, jpeg, (max(1, pixels.0), max(1, pixels.1)), (max(1, image.width), max(1, image.height))))170                text(RTFPictures.placeholder(pictures.count - 1), like: plain, &self)171            case .shape(let shape): text(shape.text.isEmpty ? shape.altText : shape.text, like: plain, &self)172            case .equation(let e): text(e.latex, like: plain, &self)173            case .note(let ref):174                var mark = plain175                mark.props.vertical = .superscript176                text(ctx.noteMark(ref), like: mark, &self)177            case .citation(let c): text(ctx.citationText(c), like: plain, &self)178            case .crossRef(let ref): text(ctx.crossRefText(ref), like: plain, &self)179            case .field(let f): text(ctx.fieldText(f, in: p, sequenceIndex: &sequenceIndex), like: plain, &self)180            case .bookmark: break181            }182        }183        // The paragraph terminator carries the paragraph style (also for empty paragraphs).184        var terminator = attributes(p.runs.last.map { r in var t = r; t.inline = nil; t.props.link = nil; return t } ?? base, in: p, style: style)185        terminator[.link] = nil186        out.append(NSAttributedString(string: "\n", attributes: terminator))187        out.addAttribute(.paragraphStyle, value: style, range: NSRange(location: start, length: out.length - start))188    }189190    private mutating func append(_ t: Table) {191        let table = NSTextTable()192        table.numberOfColumns = max(1, t.columnCount)193        table.collapsesBorders = true194        func column(of cellIndex: Int, in row: TableRow) -> Int { row.cells[..<cellIndex].reduce(0) { $0 + $1.colSpan } }195        for (r, row) in t.rows.enumerated() {196            for (c, cell) in row.cells.enumerated() where cell.vMerge != .continue {197                let col = column(of: c, in: row)198                guard col < table.numberOfColumns else { continue }199                var span = 1200                if cell.vMerge == .restart {201                    var below = r + 1202                    while below < t.rows.count, let k = t.rows[below].cells.indices.first(where: { column(of: $0, in: t.rows[below]) == col }), t.rows[below].cells[k].vMerge == .continue { span += 1; below += 1 }203                }204                let width = min(cell.colSpan, table.numberOfColumns - col)205                let block = NSTextTableBlock(table: table, startingRow: r, rowSpan: span, startingColumn: col, columnSpan: width)206                block.setWidth(0.5, type: .absoluteValueType, for: .border)207                block.setWidth(4, type: .absoluteValueType, for: .padding)208                block.setBorderColor(.gray)209                let points = t.columnWidths[col..<min(t.columnWidths.count, col + width)].reduce(0, +)210                if points > 0 { block.setValue(points, type: .absoluteValueType, for: .width) }211                if let shading = cell.shading ?? (row.isHeader ? t.style.headerShading : nil) { block.backgroundColor = RTFWriter.colour(shading) }212                switch cell.vAlign {213                case .top: block.verticalAlignment = .topAlignment214                case .center: block.verticalAlignment = .middleAlignment215                case .bottom: block.verticalAlignment = .bottomAlignment216                }217                for p in cell.paragraphs { append(p, blocks: [block]) }218            }219        }220    }221222    mutating func write() -> Data {223        for block in doc.body {224            switch block {225            case .paragraph(let p): append(p)226            case .table(let t): append(t)227            case .pageBreak(let b): if b.kind == .page { out.append(NSAttributedString(string: "\u{0C}")) }228            case .sectionBreak(let s): if s.kind != .continuous { out.append(NSAttributedString(string: "\u{0C}")) }229            case .toc(let toc):230                if let title = toc.title, !title.isEmpty { append(Paragraph(title, style: StyleID.tocHeading)) }231                for e in ctx.entries(of: toc) { append(Paragraph(e.text, style: StyleID.toc(e.level))) }232            case .bibliography(let b):233                if let title = b.title, !title.isEmpty { append(Paragraph(title, style: StyleID.heading(1))) }234                if let entries = ctx.bibliographyParagraphs() { for e in entries { append(e) } }235            }236        }237        let notes = ctx.orderedNotes238        if !notes.isEmpty {239            append(ModelIdiom.rule())240            for (ref, note) in notes {241                for (k, p) in note.paragraphs.enumerated() { append(p, prefix: k == 0 ? ctx.noteMark(ref) + ". " : "") }242            }243        }244        var attributes: [NSAttributedString.DocumentAttributeKey: Any] = [.documentType: NSAttributedString.DocumentType.rtf]245        let meta = doc.meta246        if !meta.title.isEmpty { attributes[.title] = meta.title }247        if !meta.author.isEmpty { attributes[.author] = meta.author }248        if !meta.subject.isEmpty { attributes[.subject] = meta.subject }249        if !meta.keywords.isEmpty { attributes[.keywords] = meta.keywords }250        let setup = doc.pageSetup251        attributes[.paperSize] = NSSize(width: setup.pageWidth, height: setup.pageHeight)252        attributes[.leftMargin] = setup.margins.left253        attributes[.rightMargin] = setup.margins.right254        attributes[.topMargin] = setup.margins.top255        attributes[.bottomMargin] = setup.margins.bottom256        guard let data = out.rtf(from: NSRange(location: 0, length: out.length), documentAttributes: attributes) else {257            ctx.warnings.add(.dropped, "RTF", "The system RTF writer failed; an empty document was produced.")258            return Data("{\\rtf1\\ansi }".utf8)259        }260        return RTFPictures.splice(data, pictures: pictures)261    }262}263
Files main
Menu

Theme