Repository Public
1// SP Notes iOS2// File: Features/Export/NoteExporter.swift3// Description: Exports a note to Markdown, plain text, standalone HTML, RTF or a paginated PDF with selectable text.4// RTF and PDF are produced from the editor's styled attributed string, always in light appearance.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import UIKit9import UniformTypeIdentifiers10import SPNotesCore1112enum ExportFormat: String, CaseIterable, Identifiable, Sendable {13 case markdown, plainText, html, rtf, pdf1415 var id: String { rawValue }16 var fileExtension: String {17 switch self { case .markdown: "md"; case .plainText: "txt"; case .html: "html"; case .rtf: "rtf"; case .pdf: "pdf" }18 }19 var contentType: UTType {20 switch self {21 case .markdown: UTType(filenameExtension: "md") ?? .plainText22 case .plainText: .plainText23 case .html: .html24 case .rtf: .rtf25 case .pdf: .pdf26 }27 }28 /// Name shown in menus.29 var label: String {30 switch self {31 case .markdown: String(localized: "Markdown")32 case .plainText: String(localized: "Texte brut")33 case .html: String(localized: "Page HTML")34 case .rtf: String(localized: "Texte enrichi (RTF)")35 case .pdf: String(localized: "PDF")36 }37 }38 var symbolName: String {39 switch self { case .markdown: "number"; case .plainText: "doc.plaintext"; case .html: "chevron.left.forwardslash.chevron.right"; case .rtf: "doc.richtext"; case .pdf: "doc.viewfinder" }40 }41}4243enum ExportError: LocalizedError {44 case encodingFailed45 var errorDescription: String? { String(localized: "L’export de la note a échoué.") }46}4748@MainActor49enum NoteExporter {50 /// Writes the note to a temporary file named after the sanitized title and returns its URL.51 /// `imageProvider` returns the local picture of an image `src` (nil when it is not on the device: a placeholder or the link is kept).52 static func export(document: NoteDocument, title: String, format: ExportFormat, imageProvider: (String) -> UIImage?) throws -> URL {53 let data = try data(document: document, title: title, format: format, imageProvider: imageProvider)54 let url = try temporaryURL(fileName: "\(sanitizedFileName(title)).\(format.fileExtension)")55 try data.write(to: url, options: .atomic)56 return url57 }5859 /// The bytes of the export (what `export` writes).60 static func data(document: NoteDocument, title: String, format: ExportFormat, imageProvider: (String) -> UIImage?) throws -> Data {61 switch format {62 case .markdown: return Data(document.markdown().utf8)63 case .plainText: return Data(document.plainText().utf8)64 case .html: return Data(html(document: document, title: title, imageProvider: imageProvider).utf8)65 case .rtf: return try rtf(document: document, imageProvider: imageProvider)66 case .pdf: return pdf(document: document, title: title, imageProvider: imageProvider)67 }68 }6970 // MARK: file names7172 /// A file name (without extension) safe on every platform: no path separators, reserved or control characters; never empty.73 nonisolated static func sanitizedFileName(_ title: String, fallback: String = "Note") -> String {74 let forbidden = CharacterSet(charactersIn: "/\\:*?\"<>|").union(.controlCharacters).union(.newlines)75 // Precomposed (NFC): names read back from the file system are decomposed, and archives travel to other platforms.76 var name = String(String.UnicodeScalarView(title.precomposedStringWithCanonicalMapping.unicodeScalars.map { forbidden.contains($0) ? " " : $0 }))77 name = name.split(whereSeparator: \.isWhitespace).joined(separator: " ")78 name = name.trimmingCharacters(in: CharacterSet(charactersIn: ". "))79 if name.count > 80 { name = String(name.prefix(80)).trimmingCharacters(in: CharacterSet(charactersIn: ". ")) }80 return name.isEmpty ? fallback : name81 }8283 /// A URL for `fileName` in a fresh temporary directory (so the name is exactly the one asked).84 nonisolated static func temporaryURL(fileName: String) throws -> URL {85 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("spn-export", isDirectory: true).appendingPathComponent(UUID().uuidString, isDirectory: true)86 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)87 return directory.appendingPathComponent(fileName)88 }8990 /// Removes the exports left in the temporary directory (call at launch).91 nonisolated static func purgeTemporaryFiles() {92 try? FileManager.default.removeItem(at: FileManager.default.temporaryDirectory.appendingPathComponent("spn-export", isDirectory: true))93 }9495 // MARK: HTML9697 /// The standalone HTML of the Document API, with the available pictures embedded as data URIs so the file is self-contained.98 static func html(document: NoteDocument, title: String, imageProvider: (String) -> UIImage?) -> String {99 var html = document.html(title: title)100 var done = Set<String>()101 for src in imageSources(of: document.pmNode()) where !done.contains(src) {102 done.insert(src)103 guard !src.lowercased().hasPrefix("data:"), let image = imageProvider(src), let encoded = encode(image, maxPixel: 2000) else { continue }104 let uri = "data:\(encoded.mime);base64,\(encoded.data.base64EncodedString())"105 html = html.replacingOccurrences(of: "<img src=\"\(escapeHTML(src))\"", with: "<img src=\"\(uri)\"")106 }107 return html108 }109110 nonisolated static func imageSources(of node: PMNode) -> [String] {111 var out: [String] = []112 if node.type == "image", let src = node.stringAttr("src"), !src.isEmpty { out.append(src) }113 // 2.0: the renders of `mermaid` and `drawing` blocks are `<img>` too in the Core's HTML114 switch node.typed {115 case .mermaid(let block)?: if let id = block.preview { out.append(AttachmentFiles.source(forAttachmentID: id)) }116 case .drawing(let block)?: if let id = block.preview { out.append(AttachmentFiles.source(forAttachmentID: id)) }117 default: break118 }119 for child in node.content ?? [] { out.append(contentsOf: imageSources(of: child)) }120 return out121 }122123 nonisolated static func escapeHTML(_ s: String) -> String {124 s.replacingOccurrences(of: "&", with: "&").replacingOccurrences(of: "<", with: "<").replacingOccurrences(of: ">", with: ">").replacingOccurrences(of: "\"", with: """)125 }126127 /// JPEG for opaque pictures, PNG when there is transparency; downscaled to `maxPixel` on the long side.128 static func encode(_ image: UIImage, maxPixel: CGFloat) -> (data: Data, mime: String, pixelSize: CGSize)? {129 let pixels = CGSize(width: image.size.width * image.scale, height: image.size.height * image.scale)130 guard pixels.width >= 1, pixels.height >= 1 else { return nil }131 let ratio = min(1, maxPixel / max(pixels.width, pixels.height))132 let target = CGSize(width: max(1, (pixels.width * ratio).rounded()), height: max(1, (pixels.height * ratio).rounded()))133 let alpha = image.cgImage?.alphaInfo134 let opaque = alpha == nil || alpha == CGImageAlphaInfo.none || alpha == .noneSkipFirst || alpha == .noneSkipLast135 let format = UIGraphicsImageRendererFormat()136 format.scale = 1137 format.opaque = opaque138 let renderer = UIGraphicsImageRenderer(size: target, format: format)139 if opaque {140 let data = renderer.jpegData(withCompressionQuality: 0.85) { _ in image.draw(in: CGRect(origin: .zero, size: target)) }141 return (data, "image/jpeg", target)142 }143 let data = renderer.pngData { _ in image.draw(in: CGRect(origin: .zero, size: target)) }144 return (data, "image/png", target)145 }146147 // MARK: styled string (RTF and PDF)148149 static let light = UITraitCollection(userInterfaceStyle: .light)150 /// 2.0: resolved card data of the note being exported (set around an export by `NoteExportMenu`), so the cards of a PDF151 /// show the referenced block, the query rows, the PDF thumbnail… exactly as the screen does.152 static var cardSource: BlockCardStore?153 /// Body size on paper; the editor's metrics are scaled to it.154 static let paperBodySize: CGFloat = 11.5155156 /// The document as the editor shows it, in light appearance, with list markers as text (the editor draws them outside the text).157 /// Block atoms are rendered for `contentWidth`. The string does not end with a paragraph terminator.158 static func styledString(document: NoteDocument, contentWidth: CGFloat, imageProvider: (String) -> UIImage?) -> NSMutableAttributedString {159 var out = NSMutableAttributedString()160 withoutActuallyEscaping(imageProvider) { provider in161 light.performAsCurrent {162 let renderer = AtomRenderer()163 renderer.imageProvider = provider164 // 2.0: block cards are drawn once, with what the open note already resolved (nothing is fetched for an export)165 if let source = cardSource { renderer.cards.adopt(source) }166 renderer.cards.isFinal = true167 let styler = EditorStyler(atoms: renderer)168 styler.contentWidth = contentWidth169 let string = AttributedCodec.attributedString(from: document)170 styler.restyleAll(string)171 renderer.imageProvider = { _ in nil }172 out = string173 }174 }175 if out.length > 0, (out.string as NSString).character(at: out.length - 1) == EditorCharacter.newlineScalar {176 out.deleteCharacters(in: NSRange(location: out.length - 1, length: 1))177 }178 insertListMarkers(in: out)179 resolveColors(in: out)180 return out181 }182183 /// Dynamic colours are frozen to their light value: the output never depends on the device's appearance.184 private static func resolveColors(in string: NSMutableAttributedString) {185 let all = NSRange(location: 0, length: string.length)186 for key in [NSAttributedString.Key.foregroundColor, .backgroundColor, .underlineColor, .strikethroughColor] {187 string.enumerateAttribute(key, in: all, options: []) { value, range, _ in188 guard let color = value as? UIColor else { return }189 string.addAttribute(key, value: color.resolvedColor(with: light), range: range)190 }191 }192 }193194 private static func insertListMarkers(in string: NSMutableAttributedString) {195 let theme = EditorTheme.shared196 var paragraphs: [NSRange] = []197 let ns = string.string as NSString198 var location = 0199 while location < ns.length {200 let range = ns.paragraphRange(for: NSRange(location: location, length: 0))201 paragraphs.append(range)202 location = NSMaxRange(range)203 }204 for paragraph in paragraphs.reversed() where paragraph.length > 0 {205 guard string.attribute(.spnItemHead, at: paragraph.location, effectiveRange: nil) != nil,206 let box = string.attribute(.spnLine, at: paragraph.location, effectiveRange: nil) as? LineBox,207 let item = box.style.innermostItem else { continue }208 let marker: String209 if item.type == "taskItem" { marker = box.style.isTaskChecked ? "☑" : "☐" }210 else if let ordinal = (string.attribute(.spnOrdinal, at: paragraph.location, effectiveRange: nil) as? NSNumber)?.intValue { marker = "\(ordinal)." }211 else { marker = box.style.listDepth % 2 == 1 ? "•" : "◦" }212 let geometry = LineGeometry(style: box.style, theme: theme)213 let base = (string.attribute(.paragraphStyle, at: paragraph.location, effectiveRange: nil) as? NSParagraphStyle) ?? NSParagraphStyle.default214 let style = base.mutableCopy() as! NSMutableParagraphStyle215 style.firstLineHeadIndent = max(0, geometry.textIndent - theme.listIndent + 4)216 style.headIndent = geometry.textIndent217 style.tabStops = [NSTextTab(textAlignment: .left, location: geometry.textIndent)]218 style.defaultTabInterval = theme.listIndent219 string.addAttribute(.paragraphStyle, value: style, range: paragraph)220 let font = (string.attribute(.font, at: paragraph.location, effectiveRange: nil) as? UIFont) ?? theme.body221 let markerFont = UIFont.systemFont(ofSize: font.pointSize)222 string.insert(NSAttributedString(string: marker + "\t", attributes: [.font: markerFont, .foregroundColor: theme.secondary, .paragraphStyle: style, .spnLine: box]), at: paragraph.location)223 }224 }225226 // MARK: RTF227228 /// RTF of the note. Pictures and block equations are embedded as standard `\pict` groups (read by Word, Pages, LibreOffice;229 /// ignored by readers without picture support); tables, files and other atoms become text. Valid RTF with or without pictures.230 static func rtf(document: NoteDocument, imageProvider: (String) -> UIImage?) throws -> Data {231 let string = styledString(document: document, contentWidth: 468, imageProvider: imageProvider)232 let token = "SPNPICT" + UUID().uuidString.replacingOccurrences(of: "-", with: "")233 var pictures: [String] = []234 // Atoms → text or picture tokens, from the end so ranges stay valid.235 var atoms: [(NSRange, AtomAttachment)] = []236 string.enumerateAttribute(.attachment, in: NSRange(location: 0, length: string.length), options: []) { value, range, _ in237 guard let atom = value as? AtomAttachment else { return }238 for offset in 0..<range.length { atoms.append((NSRange(location: range.location + offset, length: 1), atom)) }239 }240 for (range, atom) in atoms.reversed() {241 var replacement = fallbackText(for: atom.node, isBlock: atom.isBlock)242 if atom.isBlock, let picture = rtfPicture(for: atom.node, imageProvider: imageProvider) {243 pictures.append(picture)244 let caption = atom.node.type == "image" ? (atom.node.stringAttr("title") ?? "") : ""245 replacement = "\(token)N\(pictures.count - 1)E" + (caption.isEmpty ? "" : EditorCharacter.softBreak + caption)246 }247 string.removeAttribute(.attachment, range: range)248 string.replaceCharacters(in: range, with: replacement)249 }250 // Paper metrics, hyperlinks, and only standard attributes.251 let all = NSRange(location: 0, length: string.length)252 let factor = paperBodySize / max(1, EditorTheme.shared.body.pointSize)253 string.enumerateAttribute(.font, in: all, options: []) { value, range, _ in254 guard let font = value as? UIFont else { return }255 string.addAttribute(.font, value: font.withSize(max(6, (font.pointSize * factor * 2).rounded() / 2)), range: range)256 }257 string.enumerateAttribute(.baselineOffset, in: all, options: []) { value, range, _ in258 guard let offset = value as? CGFloat else { return }259 string.addAttribute(.baselineOffset, value: offset * factor, range: range)260 }261 string.enumerateAttribute(.spnMarks, in: all, options: []) { value, range, _ in262 guard let href = (value as? MarksBox)?.link, let url = LinkAddress.openableURL(href) else { return }263 string.addAttribute(.link, value: url, range: range)264 }265 for key in [NSAttributedString.Key.spnLine, .spnMarks, .spnOrdinal, .spnItemHead] { string.removeAttribute(key, range: all) }266 let data = try string.data(from: NSRange(location: 0, length: string.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf])267 guard !pictures.isEmpty, var text = String(data: data, encoding: .isoLatin1) else { return data }268 for (index, picture) in pictures.enumerated() { text = text.replacingOccurrences(of: "\(token)N\(index)E", with: picture) }269 guard let out = text.data(using: .isoLatin1) else { throw ExportError.encodingFailed }270 return out271 }272273 /// The text that stands for an atom where it cannot be shown.274 static func fallbackText(for node: PMNode, isBlock: Bool) -> String {275 switch node.type {276 case "mention": return "@" + (node.stringAttr("label") ?? "")277 case "inlineMath", "math": return "$" + (node.stringAttr("latex") ?? "") + "$"278 case "footnoteRef": return "[" + (node.stringAttr("id") ?? "?") + "]"279 case "blockMath": return "$$ " + (node.stringAttr("latex") ?? "") + " $$"280 case "image":281 let name = node.stringAttr("alt") ?? node.stringAttr("title") ?? ""282 return name.isEmpty ? String(localized: "[Image]") : String(localized: "[Image : \(name)]")283 case "fileBlock": return "📎 " + (node.stringAttr("name") ?? String(localized: "Fichier"))284 case "youtube": return "▶ " + (node.stringAttr("src") ?? "")285 case "horizontalRule": return "────────────"286 case "table":287 return TableGrid(node: node).rows.map { row in288 row.map { $0.text.replacingOccurrences(of: "\n", with: " ") }.joined(separator: "\t")289 }.joined(separator: EditorCharacter.softBreak)290 default:291 // 2.0: the nodes of SPEC §2 are written as the Core writes them (plain text; Markdown when the plain text is empty)292 if let typed = node.typed {293 if case .citation(let citation) = typed { return "[" + citation.displayText + "]" }294 let single = NoteDocument(lines: [Line(blockAtom: node)])295 var text = single.plainText().trimmingCharacters(in: .whitespacesAndNewlines)296 if text.isEmpty { text = single.markdown().trimmingCharacters(in: .whitespacesAndNewlines) }297 if !text.isEmpty { return text.replacingOccurrences(of: "\n", with: EditorCharacter.softBreak) }298 }299 let text = node.plainText300 return text.isEmpty && isBlock ? "[\(node.type)]" : text301 }302 }303304 /// `{\pict …}` group for a picture or a block equation; nil when there is nothing to embed.305 private static func rtfPicture(for node: PMNode, imageProvider: (String) -> UIImage?) -> String? {306 var image: UIImage?307 var points = CGSize.zero308 switch node.type {309 case "image":310 guard let picture = imageProvider(node.stringAttr("src") ?? "") else { return nil }311 image = picture312 let natural = CGSize(width: picture.size.width, height: picture.size.height)313 let ratio = min(1, 440 / max(1, natural.width), 560 / max(1, natural.height))314 points = CGSize(width: natural.width * ratio, height: natural.height * ratio)315 case "blockMath":316 guard let typeset = MathPreview.image(latex: node.stringAttr("latex") ?? "", display: true, fontSize: 28, color: .black) else { return nil }317 image = typeset318 points = CGSize(width: typeset.size.width * 0.5, height: typeset.size.height * 0.5)319 if points.width > 440 { points = CGSize(width: 440, height: points.height * 440 / points.width) }320 // 2.0: a chart is embedded as its Swift Charts picture; a diagram or a drawing as its render when it is on the device321 case NodeType.chart, NodeType.mermaid, NodeType.drawing:322 var picture: UIImage?323 switch node.typed {324 case .chart(let chart)?: picture = ChartSnapshot.image(chart, width: 440, traits: light)325 case .mermaid(let block)?: if block.isPreviewCurrent, let id = block.preview { picture = imageProvider(AttachmentFiles.source(forAttachmentID: id)) }326 case .drawing(let block)?: if let id = block.preview { picture = imageProvider(AttachmentFiles.source(forAttachmentID: id)) }327 default: break328 }329 guard let picture else { return nil }330 image = picture331 let ratio = min(1, 440 / max(1, picture.size.width), 560 / max(1, picture.size.height))332 points = CGSize(width: picture.size.width * ratio, height: picture.size.height * ratio)333 default: return nil334 }335 guard let image, let encoded = encode(image, maxPixel: 1400) else { return nil }336 let blip = encoded.mime == "image/png" ? "\\pngblip" : "\\jpegblip"337 let hex = encoded.data.map { String(format: "%02x", $0) }.joined()338 return "{\\pict\(blip)\\picw\(Int(encoded.pixelSize.width))\\pich\(Int(encoded.pixelSize.height))\\picwgoal\(Int(points.width * 20))\\pichgoal\(Int(points.height * 20)) \(hex)}"339 }340341 // MARK: PDF342343 struct PageLayout {344 var pageSize: CGSize345 var margins = UIEdgeInsets(top: 64, left: 54, bottom: 60, right: 54)346 var contentRect: CGRect { CGRect(origin: .zero, size: pageSize).inset(by: margins) }347348 static let letter = PageLayout(pageSize: CGSize(width: 612, height: 792))349 static let a4 = PageLayout(pageSize: CGSize(width: 595.2, height: 841.8))350351 /// US Letter where it is the customary paper (North America and part of Latin America), A4 elsewhere.352 static func forLocale(_ locale: Locale = .current) -> PageLayout {353 let letterRegions: Set<String> = ["US", "CA", "MX", "PR", "PH", "CL", "CO", "VE", "CR", "PA", "GT", "DO", "SV", "HN", "NI", "BO"]354 return letterRegions.contains(locale.region?.identifier ?? "") ? .letter : .a4355 }356 }357358 /// A paginated PDF: text drawn by TextKit (selectable, searchable), pictures included, tables drawn as vector text,359 /// the title as running header and "page / pages" as footer.360 static func pdf(document: NoteDocument, title: String, imageProvider: (String) -> UIImage?, layout: PageLayout = .forLocale()) -> Data {361 let theme = EditorTheme.shared362 let content = layout.contentRect363 // The editor's metrics (Dynamic Type) are laid out in a wider virtual page then scaled, so the paper size is constant.364 let scale = paperBodySize / max(1, theme.body.pointSize)365 let virtual = CGSize(width: (content.width / scale).rounded(.down), height: (content.height / scale).rounded(.down))366 let string = styledString(document: document, contentWidth: virtual.width, imageProvider: imageProvider)367 prepareAttachmentsForPaper(in: string, page: virtual)368369 let storage = NSTextStorage(attributedString: string)370 let manager = NSLayoutManager()371 manager.usesFontLeading = true372 storage.addLayoutManager(manager)373 var containers: [NSTextContainer] = []374 repeat {375 let container = NSTextContainer(size: virtual)376 container.lineFragmentPadding = 0377 manager.addTextContainer(container)378 containers.append(container)379 let range = manager.glyphRange(for: container)380 if range.length == 0 || NSMaxRange(range) >= manager.numberOfGlyphs { break }381 } while containers.count < 5000382383 let format = UIGraphicsPDFRendererFormat()384 format.documentInfo = [kCGPDFContextTitle as String: title, kCGPDFContextCreator as String: "SP Notes"]385 let renderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, size: layout.pageSize), format: format)386 let chromeColor = UIColor(white: 0.42, alpha: 1)387 let chromeFont = UIFont.systemFont(ofSize: 8.5)388 return renderer.pdfData { context in389 light.performAsCurrent {390 for (index, container) in containers.enumerated() {391 context.beginPage()392 // running header and footer393 let headerStyle = NSMutableParagraphStyle(); headerStyle.lineBreakMode = .byTruncatingTail394 (title as NSString).draw(in: CGRect(x: content.minX, y: 30, width: content.width, height: 14), withAttributes: [.font: chromeFont, .foregroundColor: chromeColor, .paragraphStyle: headerStyle])395 UIColor(white: 0.82, alpha: 1).setFill()396 UIRectFill(CGRect(x: content.minX, y: 47, width: content.width, height: 0.5))397 let footerStyle = NSMutableParagraphStyle(); footerStyle.alignment = .center398 ("\(index + 1) / \(containers.count)" as NSString).draw(in: CGRect(x: content.minX, y: layout.pageSize.height - 40, width: content.width, height: 14), withAttributes: [.font: chromeFont, .foregroundColor: chromeColor, .paragraphStyle: footerStyle])399 // body400 let cg = context.cgContext401 cg.saveGState()402 cg.translateBy(x: content.minX, y: content.minY)403 cg.scaleBy(x: scale, y: scale)404 let glyphs = manager.glyphRange(for: container)405 if glyphs.length > 0 {406 drawDecorations(manager: manager, storage: storage, glyphs: glyphs, width: virtual.width, theme: theme)407 manager.drawBackground(forGlyphRange: glyphs, at: .zero)408 manager.drawGlyphs(forGlyphRange: glyphs, at: .zero)409 drawTables(manager: manager, storage: storage, glyphs: glyphs)410 }411 cg.restoreGState()412 }413 }414 }415 }416417 /// Tables become vector attachments; anything taller than a page is reduced to fit one.418 private static func prepareAttachmentsForPaper(in string: NSMutableAttributedString, page: CGSize) {419 let maxHeight = page.height * 0.92420 string.enumerateAttribute(.attachment, in: NSRange(location: 0, length: string.length), options: []) { value, range, _ in421 guard let atom = value as? AtomAttachment else { return }422 if atom.isBlock, atom.node.type == "table" {423 let box = string.attribute(.spnLine, at: range.location, effectiveRange: nil) as? LineBox424 let indent = box.map { LineGeometry(style: $0.style, theme: .shared).textIndent } ?? 0425 let table = PaperTable(node: atom.node, width: max(120, page.width - indent), maxHeight: maxHeight)426 guard !table.rows.isEmpty else { return }427 string.addAttribute(.attachment, value: PaperTableAttachment(table: table), range: range)428 } else if atom.bounds.height > maxHeight, atom.bounds.height > 0 {429 let ratio = maxHeight / atom.bounds.height430 atom.bounds = CGRect(x: 0, y: atom.bounds.minY * ratio, width: atom.bounds.width * ratio, height: maxHeight)431 }432 }433 }434435 /// Quote bars and callout / code boxes behind the lines of a page (the editor draws them in its layout fragments).436 private static func drawDecorations(manager: NSLayoutManager, storage: NSTextStorage, glyphs: NSRange, width: CGFloat, theme: EditorTheme) {437 manager.enumerateLineFragments(forGlyphRange: glyphs) { rect, _, _, lineGlyphs, _ in438 let index = manager.characterIndexForGlyph(at: lineGlyphs.location)439 guard index < storage.length, let style = (storage.attribute(.spnLine, at: index, effectiveRange: nil) as? LineBox)?.style else { return }440 let geometry = LineGeometry(style: style, theme: theme)441 if let boxLeft = geometry.boxLeft {442 (style.isCode ? theme.codeBackground : theme.surface).resolvedColor(with: light).setFill()443 UIRectFill(CGRect(x: boxLeft, y: rect.minY, width: width - boxLeft, height: rect.height))444 }445 for x in geometry.quoteBars {446 theme.quoteBar.resolvedColor(with: light).setFill()447 UIRectFill(CGRect(x: x, y: rect.minY, width: 3, height: rect.height))448 }449 }450 }451452 private static func drawTables(manager: NSLayoutManager, storage: NSTextStorage, glyphs: NSRange) {453 let characters = manager.characterRange(forGlyphRange: glyphs, actualGlyphRange: nil)454 storage.enumerateAttribute(.attachment, in: characters, options: []) { value, range, _ in455 guard let attachment = value as? PaperTableAttachment else { return }456 let glyph = manager.glyphIndexForCharacter(at: range.location)457 let line = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)458 let location = manager.location(forGlyphAt: glyph)459 let size = manager.attachmentSize(forGlyphAt: glyph)460 attachment.table.draw(at: CGPoint(x: line.minX + location.x, y: line.minY + location.y - size.height))461 }462 }463}464465/// A table laid out for paper: equal columns, rows as tall as their tallest cell, drawn as text (selectable in the PDF).466struct PaperTable {467 var rows: [[TableGrid.Cell]] = []468 var columnWidth: CGFloat = 0469 var heights: [CGFloat] = []470 var scale: CGFloat = 1471 var size: CGSize = .zero472 private let padding: CGFloat = 7473 private var font: UIFont { UIFont.systemFont(ofSize: max(10, EditorTheme.shared.body.pointSize * 0.88)) }474 private func font(header: Bool) -> UIFont { header ? font.withTraits(.traitBold) : font }475476 init(node: PMNode, width: CGFloat, maxHeight: CGFloat) {477 let grid = TableGrid(node: node)478 guard grid.columnCount > 0, !grid.rows.isEmpty else { return }479 rows = grid.rows480 columnWidth = width / CGFloat(grid.columnCount)481 for row in rows {482 var height = font.lineHeight483 for cell in row {484 let bounds = (cell.text as NSString).boundingRect(with: CGSize(width: max(10, columnWidth - 2 * padding), height: .greatestFiniteMagnitude), options: [.usesLineFragmentOrigin], attributes: [.font: font(header: cell.isHeader)], context: nil)485 height = max(height, ceil(bounds.height))486 }487 heights.append(height + 2 * padding)488 }489 let total = heights.reduce(0, +)490 scale = total > maxHeight ? maxHeight / total : 1491 size = CGSize(width: width * scale, height: total * scale + 8)492 }493494 /// Draws in the current context with its top-left corner at `origin`.495 func draw(at origin: CGPoint) {496 guard let context = UIGraphicsGetCurrentContext(), !rows.isEmpty else { return }497 let columns = rows.map(\.count).max() ?? 0498 let width = columnWidth * CGFloat(columns), total = heights.reduce(0, +)499 context.saveGState()500 context.translateBy(x: origin.x, y: origin.y + 4)501 context.scaleBy(x: scale, y: scale)502 var y: CGFloat = 0503 for (r, row) in rows.enumerated() {504 for (c, cell) in row.enumerated() {505 let rect = CGRect(x: CGFloat(c) * columnWidth, y: y, width: columnWidth, height: heights[r])506 if cell.isHeader { UIColor(white: 0.94, alpha: 1).setFill(); UIRectFill(rect) }507 (cell.text as NSString).draw(with: rect.insetBy(dx: padding, dy: padding), options: [.usesLineFragmentOrigin], attributes: [.font: font(header: cell.isHeader), .foregroundColor: UIColor.black], context: nil)508 }509 y += heights[r]510 }511 UIColor(white: 0.7, alpha: 1).setStroke()512 let lines = UIBezierPath(rect: CGRect(x: 0, y: 0, width: width, height: total))513 y = 0514 for height in heights.dropLast() { y += height; lines.move(to: CGPoint(x: 0, y: y)); lines.addLine(to: CGPoint(x: width, y: y)) }515 for c in 1..<max(1, columns) { let x = CGFloat(c) * columnWidth; lines.move(to: CGPoint(x: x, y: 0)); lines.addLine(to: CGPoint(x: x, y: total)) }516 lines.lineWidth = 0.6517 lines.stroke()518 context.restoreGState()519 }520}521522/// Reserves the room of a `PaperTable` in the text flow; the exporter draws the table over it.523final class PaperTableAttachment: NSTextAttachment {524 let table: PaperTable525 private static let blank = UIGraphicsImageRenderer(size: CGSize(width: 1, height: 1)).image { _ in }526527 init(table: PaperTable) {528 self.table = table529 super.init(data: nil, ofType: nil)530 image = Self.blank531 bounds = CGRect(origin: .zero, size: table.size)532 }533534 @available(*, unavailable)535 required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }536}537