import Foundation
import OrgCore
#if os(macOS)
import AppKit
typealias DocxFont = NSFont
typealias DocxColor = NSColor
#else
import UIKit
typealias DocxFont = UIFont
typealias DocxColor = UIColor
#endif
/// Word's `.docx` from styled text: paragraphs with their runs' fonts, colors and links, and
/// tables from the text's table blocks, which the system's own writer leaves out. iOS's HTML
/// import keeps no tables, so there `tables` holds them, each standing for a paragraph that is
/// its `marker` alone.
enum DocxWriter {
static func marker(_ index: Int) -> String { "\u{E000}\(index)\u{E001}" }
/// Put at the start of a heading's text: 0 for the title, 1 to 6 for Word's heading levels.
static func headingMarker(_ level: Int) -> String { "\u{E002}\(level)\u{E003}" }
/// Stands for `images[index]` in the text.
static func imageMarker(_ index: Int) -> String { "\u{E004}\(index)\u{E005}" }
/// A picture for the document: PNG, JPEG or GIF bytes and its size in pixels.
struct Image: Equatable {
let data: Data
let ext: String
let width: Int
let height: Int
}
/// EMUs to a pixel at 96 to the inch, and to a twip.
static let emuPerPixel = 9525, emuPerTwip = 635
static func data(from text: NSAttributedString, tables: [String] = [], images: [Image] = []) -> Data {
var links: [String] = []
let letter = PDFExport.usesLetter()
let body = paragraphs(text, tables: tables, images: images, maxWidth: (letter ? 12240 : 11906) - 2 * 1134, links: &links)
let document = """
\(body)\
\(section(letter: letter))\
"""
let relationships = ""
+ links.enumerated().map { index, url in
""
}.joined()
+ images.enumerated().map { index, image in
""
}.joined()
let mediaTypes = Set(images.map(\.ext)).sorted().map { "" }.joined()
var zip = ZipWriter()
zip.add("[Content_Types].xml", """
\
\
\(mediaTypes)\
\
\
""")
zip.add("_rels/.rels", """
\
\
""")
zip.add("word/_rels/document.xml.rels", """
\(relationships)
""")
zip.add("word/document.xml", document)
zip.add("word/styles.xml", styles)
for (index, image) in images.enumerated() { zip.add("word/media/image\(index + 1).\(image.ext)", data: image.data) }
return zip.data()
}
/// Normal, Title and Word's built-in heading 1 to 6, so the navigation pane, outline view
/// and contents fields see the headings. The runs keep their own fonts and colors.
static let styles: String = {
let headings = (1...6).map { level in
""
+ ""
+ ""
}.joined()
return """
\
\
\
\
\
\(headings)\
"""
}()
/// An inline picture, as wide as its pixels at 96 to the inch, or `maxWidth` twips if less.
static func drawing(_ image: Image, index: Int, maxWidth: Int) -> String {
var cx = image.width * emuPerPixel, cy = image.height * emuPerPixel
let limit = maxWidth * emuPerTwip
if cx > limit, cx > 0 {
cy = cy * limit / cx
cx = limit
}
let id = index + 1
return ""
+ ""
+ ""
+ ""
+ ""
+ ""
}
/// The page: Letter or A4, as PDF export has it. Without a size, readers pick their own, and
/// Quick Look and Pages pick a narrow one.
static func section(letter: Bool) -> String {
let size = letter ? "" : ""
return "\(size)"
}
/// Paragraphs in order, consecutive ones in the same table gathered into ``.
/// A `` of rows of cells, each cell its paragraphs.
static func table(_ rows: [[String]], columns: Int) -> String {
var out = "" + ["top", "left", "bottom", "right", "insideH", "insideV"].map {
""
}.joined() + ""
out += "" + String(repeating: "", count: columns) + ""
for row in rows {
out += ""
for column in 0.." + (column < row.count && !row[column].isEmpty ? row[column] : "") + ""
}
out += ""
}
return out + ""
}
private static func paragraphs(_ text: NSAttributedString, tables: [String], images: [Image], maxWidth: Int, links: inout [String]) -> String {
let string = text.string as NSString
var out = ""
#if os(macOS)
var table: (block: NSTextTable, cells: [[Int: [String]]])?
func flushTable() {
guard let current = table else { return }
let columns = max(current.block.numberOfColumns, current.cells.map { ($0.keys.max() ?? 0) + 1 }.max() ?? 1)
out += Self.table(current.cells.map { row in (0.. String {
// In the order the schema has them: style, tabs, spacing, indentation, justification.
var properties = ""
let content = (text.string as NSString).substring(with: range)
if let match = content.firstMatch(of: /^\s*\u{E002}(\d)\u{E003}/), let level = Int(match.1) {
properties += ""
}
if let style {
if !style.tabStops.isEmpty {
properties += "" + style.tabStops.map { "" }.joined() + ""
}
properties += ""
let left = Int(style.headIndent * 20), first = Int((style.firstLineHeadIndent - style.headIndent) * 20)
if left != 0 || first != 0 { properties += "" }
switch style.alignment {
case .center: properties += ""
case .right: properties += ""
default: break
}
}
var runs = ""
text.enumerateAttributes(in: range, options: []) { attributes, runRange, _ in
var piece = (text.string as NSString).substring(with: runRange)
piece = piece.trimmingCharacters(in: CharacterSet(charactersIn: "\n\r"))
piece = piece.replacing(/\u{E002}\d\u{E003}/, with: "")
guard !piece.isEmpty else { return }
var run = run(piece, attributes, images: images, maxWidth: maxWidth)
let link = (attributes[.link] as? URL)?.absoluteString ?? (attributes[.link] as? String)
if let link {
links.append(link)
run = "\(run)"
}
runs += run
}
return "\(properties)\(runs)"
}
private static func run(_ piece: String, _ attributes: [NSAttributedString.Key: Any], images: [Image], maxWidth: Int) -> String {
var properties = ""
if let font = attributes[.font] as? DocxFont {
let traits = self.traits(font)
let name = traits.mono ? "Menlo" : traits.family
properties += ""
if traits.bold { properties += "" }
if traits.italic { properties += "" }
properties += ""
}
if let color = (attributes[.foregroundColor] as? DocxColor).flatMap(rgba) { properties += "" }
if (attributes[.underlineStyle] as? Int ?? 0) != 0 { properties += "" }
if (attributes[.strikethroughStyle] as? Int ?? 0) != 0 { properties += "" }
if let background = (attributes[.backgroundColor] as? DocxColor).flatMap(rgba), background.a > 0.05 {
properties += ""
}
if let offset = attributes[.baselineOffset] as? Double, offset != 0 { properties += " 0 ? "superscript" : "subscript")\"/>" }
// Tabs and line breaks are elements of their own.
var content = ""
var textRun = ""
func flush() {
if !textRun.isEmpty { content += "\(escape(textRun))" }
textRun = ""
}
// A picture's marker: its index between the two marker characters.
var picture: String?
for character in piece {
if picture != nil {
if character == "\u{E005}" {
if let index = Int(picture!), images.indices.contains(index) { content += drawing(images[index], index: index, maxWidth: maxWidth) }
picture = nil
} else {
picture!.append(character)
}
continue
}
switch character {
case "\u{E004}": flush(); picture = ""
case "\t": flush(); content += ""
case "\u{2028}", "\n": flush(); content += ""
default: textRun.append(character)
}
}
flush()
return "\(properties)\(content)"
}
private static func traits(_ font: DocxFont) -> (bold: Bool, italic: Bool, mono: Bool, family: String) {
let traits = font.fontDescriptor.symbolicTraits
#if os(macOS)
return (traits.contains(.bold), traits.contains(.italic), traits.contains(.monoSpace), font.familyName ?? "Helvetica Neue")
#else
return (traits.contains(.traitBold), traits.contains(.traitItalic), traits.contains(.traitMonoSpace), font.familyName)
#endif
}
/// The color's sRGB components and alpha.
private static func rgba(_ color: DocxColor) -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? {
#if os(macOS)
guard let c = color.usingColorSpace(.sRGB) else { return nil }
return (c.redComponent, c.greenComponent, c.blueComponent, c.alphaComponent)
#else
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
guard color.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil }
return (r, g, b, a)
#endif
}
/// `#rrggbb` of the color laid on white paper: Word has no transparency.
private static func hex(_ color: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)) -> String {
func on(_ c: CGFloat) -> Int { Int(((c * color.a + (1 - color.a)) * 255).rounded()) }
return String(format: "%02X%02X%02X", on(color.r), on(color.g), on(color.b))
}
static func escape(_ s: String) -> String {
s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<")
.replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)
}
}