Sources/OrgApp/RichTextExport.swift

182 lines · 9236 bytes

  1import Foundation
  2import ImageIO
  3#if os(macOS)
  4import AppKit
  5#else
  6import UIKit
  7#endif
  8
  9/// Word, RTF and plain text from the HTML export, through the system's HTML import, and the
 10/// same for the clipboard.
 11@MainActor
 12public enum RichTextExport {
 13    public struct Failure: Error, CustomStringConvertible {
 14        public let description: String
 15    }
 16
 17    /// The HTML export as styled text: light colors, and fonts other apps have.
 18    public static func attributed(html: String, directory: URL?) throws -> NSAttributedString {
 19        // The dark rules would turn the text white wherever the system is dark.
 20        let light = html.components(separatedBy: "\n").filter { !$0.contains("prefers-color-scheme: dark") }.joined(separator: "\n")
 21        let page = light.replacingOccurrences(of: "</head>", with: """
 22            <style>
 23            body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #222; background: #fff; }
 24            code, pre { font-family: Menlo, Consolas, "Courier New", monospace; }
 25            </style>
 26            </head>
 27            """)
 28        var options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
 29            .documentType: NSAttributedString.DocumentType.html,
 30            .characterEncoding: String.Encoding.utf8.rawValue,
 31        ]
 32        #if os(macOS)
 33        if let directory { options[.baseURL] = directory }
 34        #endif
 35        do {
 36            return try NSAttributedString(data: Data(page.utf8), options: options, documentAttributes: nil)
 37        } catch {
 38            throw Failure(description: "The text couldn't be converted: \(error.localizedDescription)")
 39        }
 40    }
 41
 42    public static func rtf(_ text: NSAttributedString) throws -> Data {
 43        try text.data(from: NSRange(location: 0, length: text.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf])
 44    }
 45
 46    #if os(macOS)
 47    /// Word's `.docx`, tables included.
 48    public static func docx(_ text: NSAttributedString) throws -> Data {
 49        DocxWriter.data(from: text)
 50    }
 51    #endif
 52
 53    /// The HTML export as Word's `.docx`, with tables, heading styles and pictures.
 54    public static func docx(html: String, directory: URL?) throws -> Data {
 55        let (marked, images) = markingHeadingsAndImages(html, directory: directory)
 56        #if os(macOS)
 57        return DocxWriter.data(from: try attributed(html: marked, directory: directory), images: images)
 58        #else
 59        let (page, tables) = extractingTables(marked)
 60        return DocxWriter.data(from: try attributed(html: page, directory: directory), tables: tables, images: images)
 61        #endif
 62    }
 63
 64    /// `html` with each heading's text starting with `DocxWriter.headingMarker` (`<h1>` the
 65    /// title, `<h2>` to `<h7>` Word's levels 1 to 6), and each local image replaced by
 66    /// `DocxWriter.imageMarker` for the pictures returned: what the system's HTML import
 67    /// leaves out or, on iOS, can't say.
 68    static func markingHeadingsAndImages(_ html: String, directory: URL?) -> (html: String, images: [DocxWriter.Image]) {
 69        var out = html.replacing(#/(?i)<h([1-7])\b([^>]*)>/#) { match in
 70            let level = Int(match.1)! - 1
 71            return "<h\(match.1)\(match.2)>" + DocxWriter.headingMarker(min(level, 6))
 72        }
 73        var images: [DocxWriter.Image] = []
 74        out = out.replacing(#/(?i)<img\b[^>]*>/#) { match in
 75            let tag = String(match.0)
 76            guard let src = tag.firstMatch(of: #/(?i)\bsrc="([^"]*)"/#).map({ decode(String($0.1)) }),
 77                  let image = image(src, width: tag.firstMatch(of: #/(?i)\bwidth="(\d+)/#).flatMap { Int($0.1) }, directory: directory) else { return tag }
 78            images.append(image)
 79            return DocxWriter.imageMarker(images.count - 1)
 80        }
 81        return (out, images)
 82    }
 83
 84    /// A local image as Word takes it: PNG, JPEG or GIF as they are, other formats ImageIO
 85    /// reads as PNG. `width` in pixels scales it, as `#+ATTR_HTML: :width` does on the page.
 86    static func image(_ src: String, width: Int?, directory: URL?) -> DocxWriter.Image? {
 87        let url: URL
 88        if src.hasPrefix("file://") {
 89            guard let file = URL(string: src) else { return nil }
 90            url = file
 91        } else if src.contains("://") || src.hasPrefix("data:") {
 92            return nil
 93        } else {
 94            let path = src.removingPercentEncoding ?? src
 95            if path.hasPrefix("/") { url = URL(fileURLWithPath: path) } else if let directory { url = directory.appendingPathComponent(path) } else { return nil }
 96        }
 97        guard let data = try? Data(contentsOf: url), let source = CGImageSourceCreateWithData(data as CFData, nil),
 98              let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
 99              let pixelWidth = properties[kCGImagePropertyPixelWidth] as? Int, let pixelHeight = properties[kCGImagePropertyPixelHeight] as? Int,
100              pixelWidth > 0, pixelHeight > 0 else { return nil }
101        let (w, h) = width.map { ($0, pixelHeight * $0 / pixelWidth) } ?? (pixelWidth, pixelHeight)
102        switch CGImageSourceGetType(source) as String? {
103        case "public.png": return DocxWriter.Image(data: data, ext: "png", width: w, height: h)
104        case "public.jpeg": return DocxWriter.Image(data: data, ext: "jpeg", width: w, height: h)
105        case "com.compuserve.gif": return DocxWriter.Image(data: data, ext: "gif", width: w, height: h)
106        default:
107            let png = NSMutableData()
108            guard let image = CGImageSourceCreateImageAtIndex(source, 0, nil),
109                  let destination = CGImageDestinationCreateWithData(png, "public.png" as CFString, 1, nil) else { return nil }
110            CGImageDestinationAddImage(destination, image, nil)
111            guard CGImageDestinationFinalize(destination) else { return nil }
112            return DocxWriter.Image(data: png as Data, ext: "png", width: w, height: h)
113        }
114    }
115
116    /// `html` with each `<table>` replaced by a paragraph holding `DocxWriter.marker`, and the
117    /// tables as Word XML, header cells bold.
118    static func extractingTables(_ html: String) -> (html: String, tables: [String]) {
119        var tables: [String] = []
120        var out = ""
121        var rest = Substring(html)
122        while let match = rest.firstMatch(of: #/(?is)<table\b.*?</table>/#) {
123            out += rest[..<match.range.lowerBound]
124            var rows: [[String]] = []
125            for row in match.0.matches(of: #/(?is)<tr\b[^>]*>(.*?)</tr>/#) {
126                rows.append(row.1.matches(of: #/(?is)<t([hd])\b[^>]*>(.*?)</t[hd]>/#).map { cell in
127                    let text = decode(String(cell.2).replacing(#/(?s)<[^>]*>/#, with: "")).trimmingCharacters(in: .whitespacesAndNewlines)
128                    guard !text.isEmpty else { return "" }
129                    return "<w:p><w:pPr></w:pPr><w:r><w:rPr>\(cell.1.lowercased() == "h" ? "<w:b/>" : "")</w:rPr><w:t xml:space=\"preserve\">\(DocxWriter.escape(text))</w:t></w:r></w:p>"
130                })
131            }
132            out += "<p>\(DocxWriter.marker(tables.count))</p>"
133            tables.append(DocxWriter.table(rows, columns: rows.map(\.count).max() ?? 1))
134            rest = rest[match.range.upperBound...]
135        }
136        return (out + rest, tables)
137    }
138
139    /// HTML character references.
140    static func decode(_ s: String) -> String {
141        var out = s
142        for (entity, character) in [("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&#39;", "'"), ("&nbsp;", "\u{A0}")] {
143            out = out.replacingOccurrences(of: entity, with: character)
144        }
145        out = out.replacing(#/&#(x?)([0-9a-fA-F]+);/#) { m in
146            UInt32(m.2, radix: m.1.isEmpty ? 10 : 16).flatMap(Unicode.Scalar.init).map { String(Character($0)) } ?? String(m.0)
147        }
148        return out.replacingOccurrences(of: "&amp;", with: "&")
149    }
150
151    /// The HTML export as RTF.
152    public static func rtf(html: String, directory: URL?) throws -> Data {
153        try rtf(attributed(html: html, directory: directory))
154    }
155
156    /// The HTML export as plain text.
157    public static func plain(html: String, directory: URL?) throws -> String {
158        plain(try attributed(html: html, directory: directory))
159    }
160
161    /// The text without its styles, ending in one newline.
162    public static func plain(_ text: NSAttributedString) -> String {
163        text.string.replacingOccurrences(of: "\u{2028}", with: "\n").trimmingCharacters(in: .whitespacesAndNewlines) + "\n"
164    }
165
166    /// The export on the clipboard as HTML, RTF and plain text, for pasting formatted.
167    public static func copy(html: String, directory: URL?) throws {
168        let text = try attributed(html: html, directory: directory)
169        let rtf = try rtf(text)
170        #if os(macOS)
171        let pasteboard = NSPasteboard.general
172        pasteboard.clearContents()
173        pasteboard.setString(html, forType: .html)
174        pasteboard.setData(rtf, forType: .rtf)
175        pasteboard.setString(plain(text), forType: .string)
176        #else
177        UIPasteboard.general.setItems([[
178            "public.html": html, "public.rtf": rtf, "public.utf8-plain-text": plain(text),
179        ]])
180        #endif
181    }
182}