SPB Git

Repository Public

RTFPictures.swift 9.4 KB 197 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocFormats/RTFPictures.swift3// Description: \pict support around AppKit's RTF codec, which neither reads nor writes embedded pictures in plain RTF:4//              pictures are lifted out of the RTF bytes before reading and spliced back in after writing.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910enum RTFPictures {11    struct Picture { var data: Data; var width: Double?; var height: Double? }1213    /// Private-use character that brackets a picture index in the text handed to / received from AppKit.14    static let sentinel: Character = "\u{E0F0}"15    private static let sentinelRTF = "{\\uc1\\u-7952?}"1617    static func placeholder(_ index: Int) -> String { "\(sentinel)\(index)\(sentinel)" }1819    /// Replaces every PNG / JPEG `\pict` group by a text placeholder. Pictures in other formats (WMF, EMF, PICT) are dropped (nil entry).20    static func extract(_ rtf: Data) -> (rtf: Data, pictures: [Picture?]) {21        let b = [UInt8](rtf)22        var out = [UInt8]()23        out.reserveCapacity(b.count)24        var pictures: [Picture?] = []25        var ignorable: [Bool] = []26        var i = 02728        func isLetter(_ c: UInt8) -> Bool { (c >= 65 && c <= 90) || (c >= 97 && c <= 122) }29        func keyword(at p: Int, _ word: String) -> Int? {30            let w = Array(word.utf8)31            guard p + w.count <= b.count, Array(b[p..<(p + w.count)]) == w else { return nil }32            if p + w.count < b.count, isLetter(b[p + w.count]) { return nil }33            return p + w.count34        }35        func skipSpace(_ p: Int) -> Int {36            var q = p37            while q < b.count, b[q] == 0x20 || b[q] == 0x0A || b[q] == 0x0D || b[q] == 0x09 { q += 1 }38            return q39        }40        /// Reads a control word at `p` (which holds a backslash). Returns its name, numeric argument and the index after it.41        func control(at p: Int) -> (name: String, value: Int?, next: Int) {42            var q = p + 143            guard q < b.count else { return ("", nil, q) }44            if !isLetter(b[q]) {45                if b[q] == 0x27 { return ("'", nil, min(b.count, q + 3)) }      // \'hh46                return (String(UnicodeScalar(b[q])), nil, q + 1)47            }48            let start = q49            while q < b.count, isLetter(b[q]), q - start < 40 { q += 1 }50            let name = String(decoding: b[start..<q], as: UTF8.self)51            var value: Int?52            let numberStart = q53            if q < b.count, b[q] == 0x2D { q += 1 }54            while q < b.count, b[q] >= 48, b[q] <= 57, q - numberStart < 11 { q += 1 }55            if q > numberStart, let v = Int(String(decoding: b[numberStart..<q], as: UTF8.self)) { value = v } else { q = numberStart }56            if q < b.count, b[q] == 0x20 { q += 1 }57            return (name, value, q)58        }59        /// Index just after the `}` that closes the group opened at `p`.60        func groupEnd(_ p: Int) -> Int {61            var depth = 062            var q = p63            while q < b.count {64                let c = b[q]65                if c == 0x5C {66                    let ctl = control(at: q)67                    q = ctl.next68                    if ctl.name == "bin", let n = ctl.value, n > 0 { q = min(b.count, q + n) }69                } else if c == 0x7B { depth += 1; q += 1 }70                else if c == 0x7D { depth -= 1; q += 1; if depth == 0 { return q } }71                else { q += 1 }72            }73            return b.count74        }75        /// Decodes the `\pict` group spanning `range` (braces included).76        func picture(_ range: Range<Int>) -> Picture? {77            var q = range.lowerBound + 178            let end = range.upperBound - 179            var supported = false80            var bytes = [UInt8]()81            var goalW: Int?, goalH: Int?, scaleX = 100, scaleY = 10082            var high: UInt8?83            while q < end {84                let c = b[q]85                if c == 0x5C {86                    let ctl = control(at: q)87                    q = ctl.next88                    switch ctl.name {89                    case "pngblip", "jpegblip": supported = true90                    case "picwgoal": goalW = ctl.value91                    case "pichgoal": goalH = ctl.value92                    case "picscalex": scaleX = ctl.value ?? 10093                    case "picscaley": scaleY = ctl.value ?? 10094                    case "bin":95                        if let n = ctl.value, n > 0, q + n <= end { bytes.append(contentsOf: b[q..<(q + n)]); q += n }96                    default: break97                    }98                } else if c == 0x7B {99                    q = min(end, groupEnd(q))100                } else {101                    var nibble: UInt8?102                    if c >= 48, c <= 57 { nibble = c - 48 } else if c >= 97, c <= 102 { nibble = c - 87 } else if c >= 65, c <= 70 { nibble = c - 55 }103                    if let n = nibble {104                        if let h = high { bytes.append(h << 4 | n); high = nil } else { high = n }105                        if bytes.count > FormatLimits.maxImageBytes { return nil }106                    }107                    q += 1108                }109            }110            guard supported, !bytes.isEmpty else { return nil }111            func points(_ goal: Int?, _ scale: Int) -> Double? {112                guard let g = goal, g > 0, g < 1_000_000 else { return nil }113                return Double(g) / 20 * Double(max(1, min(10_000, scale))) / 100114            }115            return Picture(data: Data(bytes), width: points(goalW, scaleX), height: points(goalH, scaleY))116        }117        func emitPlaceholder(_ p: Picture?) {118            pictures.append(p)119            out.append(contentsOf: Array((sentinelRTF + String(pictures.count - 1) + sentinelRTF).utf8))120        }121122        while i < b.count {123            let c = b[i]124            if c == 0x5C {125                let ctl = control(at: i)126                var next = ctl.next127                if ctl.name == "bin", let n = ctl.value, n > 0 { next = min(b.count, next + n) }128                out.append(contentsOf: b[i..<next])129                i = next130            } else if c == 0x7B {131                let inside = skipSpace(i + 1)132                let hidden = ignorable.last ?? false133                if !hidden, keyword(at: inside, "\\pict") != nil {134                    let end = groupEnd(i)135                    emitPlaceholder(picture(i..<end))136                    i = end137                } else if !hidden, let afterStar = keyword(at: inside, "\\*"), keyword(at: skipSpace(afterStar), "\\shppict") != nil {138                    // Word writes {\*\shppict{\pict …}}{\nonshppict{\pict …}}: keep the first, drop the fallback copy.139                    let end = groupEnd(i)140                    var q = inside141                    var found: Picture?142                    var any = false143                    while q < end {144                        if b[q] == 0x7B, keyword(at: skipSpace(q + 1), "\\pict") != nil {145                            let pictEnd = min(end, groupEnd(q))146                            any = true147                            found = picture(q..<pictEnd)148                            break149                        }150                        q += 1151                    }152                    if any { emitPlaceholder(found) }153                    i = end154                } else if !hidden, keyword(at: inside, "\\nonshppict") != nil {155                    i = groupEnd(i)156                } else {157                    ignorable.append(hidden || keyword(at: inside, "\\*") != nil)158                    out.append(c)159                    i += 1160                }161            } else if c == 0x7D {162                if !ignorable.isEmpty { ignorable.removeLast() }163                out.append(c)164                i += 1165            } else {166                out.append(c)167                i += 1168            }169        }170        return (Data(out), pictures)171    }172173    /// Replaces the placeholders AppKit wrote (as \uN escapes) by `\pict` groups. `pictures[i]` is nil when picture i cannot be written.174    static func splice(_ rtf: Data, pictures: [(data: Data, jpeg: Bool, pixels: (Int, Int), points: (Double, Double))?]) -> Data {175        guard !pictures.isEmpty, let text = String(data: rtf, encoding: .isoLatin1),176              let regex = try? NSRegularExpression(pattern: #"\\u(?:57584|-7952) ?(\d{1,9})(?:\\uc\d ?)?\\u(?:57584|-7952) ?"#) else { return rtf }177        let ns = text as NSString178        var out = ""179        var cursor = 0180        for match in regex.matches(in: text, range: NSRange(location: 0, length: ns.length)) {181            out += ns.substring(with: NSRange(location: cursor, length: match.range.location - cursor))182            cursor = match.range.location + match.range.length183            guard let index = Int(ns.substring(with: match.range(at: 1))), index < pictures.count, let p = pictures[index] else { continue }184            var group = "{\\pict\\\(p.jpeg ? "jpegblip" : "pngblip")\\picw\(p.pixels.0)\\pich\(p.pixels.1)\\picwgoal\(Int((p.points.0 * 20).rounded()))\\pichgoal\(Int((p.points.1 * 20).rounded())) "185            group.reserveCapacity(p.data.count * 2 + 80)186            let digits = Array("0123456789abcdef".utf8)187            var hex = [UInt8]()188            hex.reserveCapacity(p.data.count * 2)189            for byte in p.data { hex.append(digits[Int(byte >> 4)]); hex.append(digits[Int(byte & 15)]) }190            group += String(decoding: hex, as: UTF8.self) + "}"191            out += group192        }193        out += ns.substring(from: cursor)194        return out.data(using: .isoLatin1) ?? rtf195    }196}197
Files main
Menu

Theme