Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocDOCX/DocxCommon.swift3// Description: Shared pieces of the DOCX importer and exporter: units, colours, OPC package model (content types, relationships,4// part-name resolution), the ORIX extras payload and the conventions both directions agree on.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer1112// MARK: - Units1314enum DocxUnit {15 /// Twentieths of a point → points.16 static func twips(_ s: String?) -> Double? {17 guard let s, let v = number(s) else { return nil }18 return v / 2019 }20 /// Accepts plain numbers and the universal measures ("12pt", "1in", "2.5cm") that strict documents use.21 static func number(_ s: String) -> Double? {22 if let v = Double(s) { return v.isFinite && abs(v) <= 1e12 ? v : nil }23 let units: [(String, Double)] = [("pt", 20), ("in", 1440), ("cm", 1440 / 2.54), ("mm", 1440 / 25.4), ("pc", 240), ("pi", 240)]24 for (suffix, factor) in units where s.hasSuffix(suffix) {25 if let v = Double(s.dropLast(suffix.count)), v.isFinite, abs(v) <= 1e9 { return v * factor }26 }27 return nil28 }29 static func int(_ s: String?) -> Int? {30 guard let s, let v = number(s), abs(v) < 1e9 else { return nil }31 return Int(v.rounded())32 }33 /// Rounds to an integer without trapping on NaN, infinities or absurd magnitudes (the model may hold anything).34 static func safeInt(_ v: Double) -> Int {35 guard v.isFinite else { return 0 }36 return Int(max(-2_000_000_000, min(2_000_000_000, v.rounded())))37 }38 static func toTwips(_ pt: Double) -> String { String(safeInt(pt * 20)) }39 static func emu(_ s: String?) -> Double? {40 guard let s, let v = Double(s), v.isFinite, abs(v) <= 1e13 else { return nil }41 return v / 1270042 }43 static func toEMU(_ pt: Double) -> String { String(safeInt(pt * 12700)) }44 static func halfPoints(_ s: String?) -> Double? {45 guard let s, let v = number(s) else { return nil }46 return v / 247 }48 static func toHalfPoints(_ pt: Double) -> String { String(safeInt(pt * 2)) }49 /// The value a length takes after a trip through twentieths of a point.50 static func quantizedTwips(_ pt: Double) -> Double { (pt * 20).rounded() / 20 }51}5253/// ST_OnOff: an element without w:val means "on".54func docxOnOff(_ node: XMLNode?) -> Bool? {55 guard let node else { return nil }56 guard let v = node.attr("w:val") else { return true }57 switch v.lowercased() {58 case "0", "false", "off": return false59 default: return true60 }61}62func docxBool(_ s: String?) -> Bool {63 guard let s else { return false }64 return !["0", "false", "off"].contains(s.lowercased())65}6667enum DocxColor {68 static let highlights: [(String, UInt32)] = [69 ("yellow", 0xFFFF00), ("green", 0x00FF00), ("cyan", 0x00FFFF), ("magenta", 0xFF00FF), ("blue", 0x0000FF), ("red", 0xFF0000),70 ("darkBlue", 0x000080), ("darkCyan", 0x008080), ("darkGreen", 0x008000), ("darkMagenta", 0x800080), ("darkRed", 0x800000),71 ("darkYellow", 0x808000), ("darkGray", 0x808080), ("lightGray", 0xC0C0C0), ("black", 0x000000), ("white", 0xFFFFFF),72 ]73 static func hex(_ s: String?) -> RGBA? {74 guard let s, s != "auto" else { return nil }75 return RGBA(hexString: s)76 }77 static func highlight(named n: String) -> RGBA? { highlights.first { $0.0 == n }.map { RGBA(hex: $0.1) } }78 static func highlightName(_ c: RGBA) -> String? {79 let h = c.hexString80 return highlights.first { String(format: "%06X", $0.1) == h }?.081 }82}8384enum DocxDate {85 static func parse(_ s: String?) -> Date? {86 guard let s, !s.isEmpty else { return nil }87 let f = ISO8601DateFormatter()88 f.formatOptions = [.withInternetDateTime]89 if let d = f.date(from: s) { return d }90 f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]91 if let d = f.date(from: s) { return d }92 // Word sometimes writes local times without a zone designator.93 f.formatOptions = [.withInternetDateTime]94 if let d = f.date(from: s + "Z") { return d }95 f.formatOptions = [.withFullDate]96 return f.date(from: s)97 }98 static func string(_ d: Date) -> String {99 let f = ISO8601DateFormatter()100 f.formatOptions = [.withInternetDateTime]101 return f.string(from: d)102 }103 /// Dates that are absent from the file.104 static let unknown = Date(timeIntervalSince1970: 0)105}106107// MARK: - OPC108109enum RelType {110 static let base = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"111 static let officeDocument = base + "officeDocument"112 static let styles = base + "styles"113 static let numbering = base + "numbering"114 static let settings = base + "settings"115 static let footnotes = base + "footnotes"116 static let endnotes = base + "endnotes"117 static let comments = base + "comments"118 static let commentsExtended = "http://schemas.microsoft.com/office/2011/relationships/commentsExtended"119 static let header = base + "header"120 static let footer = base + "footer"121 static let image = base + "image"122 static let hyperlink = base + "hyperlink"123 static let theme = base + "theme"124 static let fontTable = base + "fontTable"125 static let webSettings = base + "webSettings"126 static let customXml = base + "customXml"127 static let customXmlProps = base + "customXmlProps"128 static let extendedProperties = base + "extended-properties"129 static let customProperties = base + "custom-properties"130 static let coreProperties = "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties"131 /// Suffix after the last "/": strict documents use another base URI for the same relationship kinds.132 static func kind(_ type: String) -> String { String(type.split(separator: "/").last ?? "") }133}134135enum ContentType {136 static let main = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"137 static let styles = "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"138 static let numbering = "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"139 static let settings = "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"140 static let footnotes = "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml"141 static let endnotes = "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml"142 static let comments = "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml"143 static let commentsExtended = "application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml"144 static let header = "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"145 static let footer = "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml"146 static let core = "application/vnd.openxmlformats-package.core-properties+xml"147 static let theme = "application/vnd.openxmlformats-officedocument.theme+xml"148 static let fontTable = "application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"149 static let webSettings = "application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"150 static let app = "application/vnd.openxmlformats-officedocument.extended-properties+xml"151 static let custom = "application/vnd.openxmlformats-officedocument.custom-properties+xml"152 static let customXmlProps = "application/vnd.openxmlformats-officedocument.customXmlProperties+xml"153 static let rels = "application/vnd.openxmlformats-package.relationships+xml"154}155156struct Relationship {157 var id: String158 var type: String159 var target: String160 var external: Bool161 var kind: String { RelType.kind(type) }162}163164enum OPC {165 /// Path of the relationships part that belongs to `part` ("word/document.xml" → "word/_rels/document.xml.rels").166 static func relsPath(for part: String) -> String {167 let comps = part.split(separator: "/").map(String.init)168 guard let last = comps.last else { return "_rels/.rels" }169 return (comps.dropLast() + ["_rels", last + ".rels"]).joined(separator: "/")170 }171172 /// Resolves an internal relationship target against the part that owns the relationship.173 /// Returns nil for anything that leaves the package ("..", absolute URLs, backslashes, percent-encoded traversal).174 static func resolve(target: String, from part: String) -> String? {175 var t = target176 if let q = t.firstIndex(where: { $0 == "?" || $0 == "#" }) { t = String(t[..<q]) }177 guard !t.isEmpty, !t.contains("\\"), !t.contains(":"), !t.contains("\0") else { return nil }178 let decoded = t.removingPercentEncoding ?? t179 guard !decoded.contains("\\"), !decoded.contains(":") else { return nil }180 var comps: [String]181 if decoded.hasPrefix("/") {182 comps = []183 } else {184 comps = part.split(separator: "/").map(String.init)185 if !comps.isEmpty { comps.removeLast() }186 }187 for c in decoded.split(separator: "/", omittingEmptySubsequences: true) {188 if c == "." { continue }189 if c == ".." {190 // Going up inside the package is legal OPC ("../customXml/item1.xml"); leaving the package root is not.191 if comps.isEmpty { return nil }192 comps.removeLast()193 } else {194 comps.append(String(c))195 }196 }197 return comps.isEmpty ? nil : comps.joined(separator: "/")198 }199200 static func parseRelationships(_ data: Data?, part: String) throws -> [Relationship] {201 guard let data else { return [] }202 let root = try XMLTree.parse(data, part: relsPath(for: part))203 return root.children.compactMap { n in204 guard n.name.hasSuffix("Relationship"), let id = n.attr("Id"), let type = n.attr("Type"), let target = n.attr("Target") else { return nil }205 return Relationship(id: id, type: type, target: target, external: (n.attr("TargetMode") ?? "").lowercased() == "external")206 }207 }208}209210struct ContentTypes {211 var defaults: [String: String] = [:]212 var overrides: [String: String] = [:]213214 init() {}215 init(_ data: Data?) throws {216 guard let data else { return }217 let root = try XMLTree.parse(data, part: "[Content_Types].xml")218 for n in root.children {219 if n.name.hasSuffix("Default"), let e = n.attr("Extension"), let t = n.attr("ContentType") { defaults[e.lowercased()] = t }220 if n.name.hasSuffix("Override"), let p = n.attr("PartName"), let t = n.attr("ContentType") {221 overrides[p.hasPrefix("/") ? String(p.dropFirst()) : p] = t222 }223 }224 }225 func type(of part: String) -> String? {226 if let t = overrides[part] { return t }227 // "_rels/.rels" has no extension as far as path APIs are concerned.228 let ext = part.split(separator: ".", omittingEmptySubsequences: false).last.map { $0.lowercased() } ?? ""229 return defaults[ext]230 }231}232233// MARK: - Media234235enum DocxMedia {236 static let mimeByExtension: [String: String] = [237 "png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg", "gif": "image/gif", "tif": "image/tiff", "tiff": "image/tiff",238 "bmp": "image/bmp", "emf": "image/x-emf", "wmf": "image/x-wmf", "svg": "image/svg+xml", "pdf": "application/pdf", "heic": "image/heic",239 "webp": "image/webp",240 ]241 static func fileExtension(forMime m: String) -> String {242 switch m {243 case "image/png": return "png"244 case "image/jpeg": return "jpeg"245 case "image/gif": return "gif"246 case "image/tiff": return "tiff"247 case "image/bmp": return "bmp"248 case "image/x-emf": return "emf"249 case "image/x-wmf": return "wmf"250 case "image/svg+xml": return "svg"251 case "application/pdf": return "pdf"252 case "image/heic": return "heic"253 case "image/webp": return "webp"254 default: return "bin"255 }256 }257 /// Identifies an image by its signature; nil when the bytes are not a known image format.258 static func sniff(_ d: Data) -> String? {259 let b = [UInt8](d.prefix(12))260 if b.count >= 8, b[0] == 0x89, b[1] == 0x50, b[2] == 0x4E, b[3] == 0x47 { return "image/png" }261 if b.count >= 3, b[0] == 0xFF, b[1] == 0xD8, b[2] == 0xFF { return "image/jpeg" }262 if b.count >= 4, b[0] == 0x47, b[1] == 0x49, b[2] == 0x46, b[3] == 0x38 { return "image/gif" }263 if b.count >= 4, (b[0] == 0x49 && b[1] == 0x49 && b[2] == 0x2A) || (b[0] == 0x4D && b[1] == 0x4D && b[3] == 0x2A) { return "image/tiff" }264 if b.count >= 2, b[0] == 0x42, b[1] == 0x4D { return "image/bmp" }265 if b.count >= 4, b[0] == 0x25, b[1] == 0x50, b[2] == 0x44, b[3] == 0x46 { return "application/pdf" }266 if b.count >= 12, b[0] == 0x52, b[1] == 0x49, b[2] == 0x46, b[3] == 0x46, b[8] == 0x57, b[9] == 0x45 { return "image/webp" }267 return nil268 }269 /// A stable identifier derived from the content, so the same picture imported twice (or into two documents) keeps one id.270 static func assetID(for data: Data) -> String {271 "img" + String(CRC32.checksum(data), radix: 36) + String(data.count, radix: 36)272 }273}274275// MARK: - Conventions shared by both directions276277enum DocxConvention {278 /// Hidden bookmarks that carry a cross-reference target: `_ORIX_T_<paragraph id>` covers the whole paragraph,279 /// `_ORIX_L_<id>` the label and number of a caption, `_ORIX_N_<id>` the number alone.280 static let refPrefix = "_ORIX_"281 static func refBookmark(kind: Character, id: String) -> String { "\(refPrefix)\(kind)_\(id)" }282 static func parseRefBookmark(_ name: String) -> (kind: Character, id: String)? {283 guard name.hasPrefix(refPrefix) else { return nil }284 let rest = name.dropFirst(refPrefix.count)285 guard rest.count > 2, let k = rest.first, "TLN".contains(k), rest.dropFirst().first == "_" else { return nil }286 return (k, String(rest.dropFirst(2)))287 }288 static func isBookmarkSafe(_ id: String) -> Bool {289 !id.isEmpty && id.count <= 30 && id.unicodeScalars.allSatisfy { ($0.value < 128) && (CharacterSet.alphanumerics.contains($0) || $0 == "_") }290 }291 static let citationInstruction = "ADDIN ORIX_CITATION"292 static let bibliographyTag = "ORIX_BIBLIOGRAPHY"293 static let tableStylePrefix = "ORIXTable"294 static let headingNumberingName = "ORIXHeadingNumbering"295 static let watermarkShapeID = "PowerPlusWaterMarkObject"296}297298/// Document data that WordprocessingML has no place for. Stored as a custom XML data part (which Word preserves) so that299/// ORIX Docs → DOCX → ORIX Docs keeps the bibliography database and the document-level settings.300struct OrixExtras: Codable, Equatable {301 var version = 1302 var citationStyle: String?303 var smartQuotes: Bool?304 var smartDashes: Bool?305 var themeName: String?306 var bibliography: [BibEntry] = []307308 static let rootName = "orix:document"309310 func xml() -> String {311 let enc = JSONEncoder()312 enc.outputFormatting = [.sortedKeys]313 enc.dateEncodingStrategy = .iso8601314 let json = (try? enc.encode(self)).map { String(decoding: $0, as: UTF8.self) } ?? "{}"315 return xmlDeclaration + xmlTag(OrixExtras.rootName, [("xmlns:orix", XMLNS.orix)], xmlTag("orix:data", [("format", "json")], XMLEscape.text(json)))316 }317 static func parse(_ root: XMLNode) -> OrixExtras? {318 guard root.name == rootName, let payload = root.first("orix:data")?.text, payload.utf8.count < 32 * 1024 * 1024 else { return nil }319 let dec = JSONDecoder()320 dec.dateDecodingStrategy = .iso8601321 return try? dec.decode(OrixExtras.self, from: Data(payload.utf8))322 }323}324325/// Paper sizes are matched by dimensions (within a point) so A4 comes back as A4 and not as "Custom".326func docxPaper(width: Double, height: Double) -> (paper: PaperSize, landscape: Bool) {327 let landscape = width > height328 let w = min(width, height), h = max(width, height)329 if let known = PaperSize.all.first(where: { abs($0.width - w) < 1 && abs($0.height - h) < 1 }) { return (known, landscape) }330 return (PaperSize(name: "Custom", width: w, height: h), landscape)331}332333extension WarningCollector {334 mutating func merge(_ other: [FormatWarning]) {335 for w in other { for _ in 0..<max(1, w.count) { add(w.severity, w.feature, w.detail) } }336 }337}338339/// The importer and the exporter walk trees recursively (XML nesting is capped at `XMLLimits.maxDepth`). Callers are often on340/// Swift concurrency or GCD threads, whose stacks are 512 KB, so the work runs on a thread with a stack sized for the worst case.341enum DocxStack {342 private final class Job<T>: @unchecked Sendable {343 var body: (() -> Result<T, Error>)?344 var result: Result<T, Error>?345 }346347 static func run<T>(_ body: () throws -> T) throws -> T {348 if MathStack.remaining() >= (24 << 20) { return try body() }349 return try withoutActuallyEscaping(body) { escaping in350 let job = Job<T>()351 job.body = { Result { try escaping() } }352 let done = DispatchSemaphore(value: 0)353 let thread = Thread {354 job.result = job.body?()355 job.body = nil356 done.signal()357 }358 thread.stackSize = 32 << 20359 thread.start()360 done.wait()361 return try job.result!.get()362 }363 }364}365