Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: SPChat/Features/Chat/RichText.swift3// Description: Markdown → NSAttributedString (rich copy, PDF export) and native PDF generation of a conversation with paginated text layout.4import AppKit5import SPChatCore67enum RichText {8 /// Attributed rendering of Markdown for the pasteboard and for PDF pages (fixed colours: it is read outside the app).9 static func attributed(markdown: String, baseSize: CGFloat, textColor: NSColor = .black) -> NSAttributedString {10 let out = NSMutableAttributedString()11 append(MarkdownParser.shared.parse(markdown), to: out, size: baseSize, color: textColor, indent: 0)12 return out13 }1415 private static func paragraph(indent: CGFloat, spacing: CGFloat = 7, firstLine: CGFloat? = nil) -> NSParagraphStyle {16 let p = NSMutableParagraphStyle(); p.paragraphSpacing = spacing; p.lineSpacing = 2; p.headIndent = indent; p.firstLineHeadIndent = firstLine ?? indent17 return p18 }1920 private static func append(_ blocks: [MDBlock], to out: NSMutableAttributedString, size: CGFloat, color: NSColor, indent: CGFloat) {21 for block in blocks {22 switch block {23 case .paragraph(let i): out.append(inline(i, size: size, color: color, style: paragraph(indent: indent))); out.append(NSAttributedString(string: "\n"))24 case .heading(let level, let i):25 let s = size * [1.5, 1.3, 1.15, 1.05, 1, 1][min(max(level, 1), 6) - 1]26 out.append(inline(i, size: s, color: color, style: paragraph(indent: indent, spacing: 8), bold: true)); out.append(NSAttributedString(string: "\n"))27 case .code(_, let text):28 let p = NSMutableParagraphStyle(); p.paragraphSpacing = 8; p.headIndent = indent + 8; p.firstLineHeadIndent = indent + 829 out.append(NSAttributedString(string: text + "\n", attributes: [.font: NSFont.monospacedSystemFont(ofSize: size * 0.88, weight: .regular), .foregroundColor: color, .backgroundColor: NSColor(white: 0.95, alpha: 1), .paragraphStyle: p]))30 case .quote(let b):31 let start = out.length32 append(b, to: out, size: size, color: NSColor(white: 0.35, alpha: 1), indent: indent + 14)33 out.addAttribute(.obliqueness, value: 0.08, range: NSRange(location: start, length: out.length - start))34 case .list(let ordered, let startIndex, let items):35 for (n, item) in items.enumerated() {36 let marker = item.checkbox.map { $0 ? "☑ " : "☐ " } ?? (ordered ? "\(startIndex + n). " : "• ")37 let start = out.length38 append(item.blocks, to: out, size: size, color: color, indent: indent + 18)39 out.insert(NSAttributedString(string: marker, attributes: [.font: NSFont.systemFont(ofSize: size), .foregroundColor: color, .paragraphStyle: paragraph(indent: indent + 18, spacing: 3, firstLine: indent + 4)]), at: start)40 if start + marker.count < out.length { out.addAttribute(.paragraphStyle, value: paragraph(indent: indent + 18, spacing: 3, firstLine: indent + 4), range: (out.string as NSString).paragraphRange(for: NSRange(location: start, length: 0))) }41 }42 case .table(let t):43 let p = NSMutableParagraphStyle(); p.paragraphSpacing = 2; p.headIndent = indent; p.firstLineHeadIndent = indent44 p.tabStops = (1...max(t.columnCount, 1)).map { NSTextTab(textAlignment: .left, location: indent + CGFloat($0) * 130) }45 for (r, row) in ([t.header] + t.rows).enumerated() {46 let line = NSMutableAttributedString()47 for (c, cell) in row.enumerated() { if c > 0 { line.append(NSAttributedString(string: "\t")) }; line.append(inline(cell, size: size * 0.92, color: color, style: p, bold: r == 0)) }48 line.append(NSAttributedString(string: "\n")); line.addAttribute(.paragraphStyle, value: p, range: NSRange(location: 0, length: line.length)); out.append(line)49 }50 out.append(NSAttributedString(string: "\n", attributes: [.font: NSFont.systemFont(ofSize: 4)]))51 case .rule: out.append(NSAttributedString(string: "⸻\n", attributes: [.font: NSFont.systemFont(ofSize: size), .foregroundColor: NSColor.gray, .paragraphStyle: paragraph(indent: indent)]))52 case .math(let tex):53 if let m = MathRenderer.render(tex, fontSize: size * 1.15, display: true) { out.append(mathAttachment(m, color: color)); out.append(NSAttributedString(string: "\n", attributes: [.paragraphStyle: paragraph(indent: indent + 12)])) }54 else { out.append(NSAttributedString(string: tex + "\n", attributes: [.font: NSFont.monospacedSystemFont(ofSize: size * 0.9, weight: .regular), .foregroundColor: color])) }55 case .html(let raw): out.append(NSAttributedString(string: raw + "\n", attributes: [.font: NSFont.monospacedSystemFont(ofSize: size * 0.88, weight: .regular), .foregroundColor: NSColor.darkGray]))56 }57 }58 }5960 private static func mathAttachment(_ m: RenderedMath, color: NSColor) -> NSAttributedString {61 let tinted = NSImage(size: m.size, flipped: false) { rect in m.image.draw(in: rect); color.set(); rect.fill(using: .sourceIn); return true }62 let att = NSTextAttachment(); att.image = tinted; att.bounds = CGRect(x: 0, y: -m.descent, width: m.size.width, height: m.size.height)63 return NSAttributedString(attachment: att)64 }6566 private static func inline(_ inlines: [MDInline], size: CGFloat, color: NSColor, style: NSParagraphStyle, bold: Bool = false, italic: Bool = false, strike: Bool = false, link: URL? = nil) -> NSAttributedString {67 let out = NSMutableAttributedString()68 func font(_ b: Bool, _ i: Bool) -> NSFont {69 var f = NSFont.systemFont(ofSize: size, weight: b ? .semibold : .regular)70 if i { f = NSFontManager.shared.convert(f, toHaveTrait: .italicFontMask) }71 return f72 }73 func attrs(_ b: Bool, _ i: Bool, _ s: Bool, _ l: URL?) -> [NSAttributedString.Key: Any] {74 var a: [NSAttributedString.Key: Any] = [.font: font(b, i), .foregroundColor: color, .paragraphStyle: style]75 if s { a[.strikethroughStyle] = NSUnderlineStyle.single.rawValue }76 if let l { a[.link] = l }77 return a78 }79 func walk(_ nodes: [MDInline], _ b: Bool, _ i: Bool, _ s: Bool, _ l: URL?) {80 for n in nodes {81 switch n {82 case .text(let t): out.append(NSAttributedString(string: t, attributes: attrs(b, i, s, l)))83 case .softBreak: out.append(NSAttributedString(string: " ", attributes: attrs(b, i, s, l)))84 case .lineBreak: out.append(NSAttributedString(string: "\u{2028}", attributes: attrs(b, i, s, l)))85 case .emphasis(let c): walk(c, b, true, s, l)86 case .strong(let c): walk(c, true, i, s, l)87 case .strikethrough(let c): walk(c, b, i, true, l)88 case .code(let c): var a = attrs(b, i, s, l); a[.font] = NSFont.monospacedSystemFont(ofSize: size * 0.9, weight: .regular); a[.backgroundColor] = NSColor(white: 0.93, alpha: 1); out.append(NSAttributedString(string: c, attributes: a))89 case .link(let d, let c): walk(c.isEmpty ? [.text(d)] : c, b, i, s, LinkPolicy.safeURL(d))90 case .image(let src, let alt): out.append(NSAttributedString(string: alt.isEmpty ? src : alt, attributes: attrs(b, i, s, LinkPolicy.safeURL(src))))91 case .math(let tex, _):92 if let m = MathRenderer.render(tex, fontSize: size, display: false) { out.append(mathAttachment(m, color: color)) }93 else { out.append(NSAttributedString(string: tex, attributes: attrs(b, i, s, l))) }94 }95 }96 }97 walk(inlines, bold, italic, strike, link)98 return out99 }100101 // MARK: PDF102103 /// The conversation as an attributed document (title, speakers, answers with their formatting).104 static func document(for detail: ConversationDetail, modelName: (String?) -> String) -> NSAttributedString {105 let out = NSMutableAttributedString()106 let title = NSMutableParagraphStyle(); title.paragraphSpacing = 4107 out.append(NSAttributedString(string: detail.conversation.title + "\n", attributes: [.font: NSFont.systemFont(ofSize: 20, weight: .bold), .foregroundColor: NSColor.black, .paragraphStyle: title]))108 let meta = NSMutableParagraphStyle(); meta.paragraphSpacing = 16109 let date = Date().formatted(.dateTime.day().month(.wide).year().hour().minute().locale(Locale(identifier: "fr_CA")))110 out.append(NSAttributedString(string: "Exporté de SP Chat le \(date) — \(detail.activeMessages.count) messages\n", attributes: [.font: NSFont.systemFont(ofSize: 9.5), .foregroundColor: NSColor.gray, .paragraphStyle: meta]))111 for m in detail.activeMessages {112 let head = NSMutableParagraphStyle(); head.paragraphSpacingBefore = 10; head.paragraphSpacing = 4113 let who = m.role == .user ? "Vous" : "Assistant · \(modelName(m.modelId))"114 out.append(NSAttributedString(string: who + "\n", attributes: [.font: NSFont.systemFont(ofSize: 9.5, weight: .semibold), .foregroundColor: m.role == .user ? NSColor(red: 0.36, green: 0.30, blue: 0.86, alpha: 1) : NSColor.darkGray, .paragraphStyle: head]))115 for part in m.parts {116 switch part {117 case .text(let t): out.append(attributed(markdown: t, baseSize: 11))118 case .file(_, _, let name, _, _): out.append(note("Pièce jointe : \(name)"))119 case .image(_, _, let name): out.append(note("Image jointe : \(name ?? "image")"))120 case .toolCall(let c): out.append(note("Outil \(c.name) → \(c.status.rawValue)"))121 case .citation(let url, let t, _): out.append(note("Source : \(t ?? url) — \(url)"))122 case .generatedImage(_, let prompt, _): out.append(note("Image générée : \(prompt)"))123 default: break124 }125 }126 if m.role == .assistant, m.status != .complete { out.append(note("État : \(m.status.rawValue)" + (m.error.map { " — \($0)" } ?? ""))) }127 }128 return out129 }130 private static func note(_ s: String) -> NSAttributedString {131 NSAttributedString(string: s + "\n", attributes: [.font: NSFont.systemFont(ofSize: 9.5), .foregroundColor: NSColor.gray, .obliqueness: 0.1])132 }133134 /// Paginates the document on US Letter pages with CoreText and returns PDF data (no print panel, no web view).135 static func pdf(_ text: NSAttributedString, pageSize: CGSize = CGSize(width: 612, height: 792), margin: CGFloat = 54) -> Data {136 let data = NSMutableData()137 var box = CGRect(origin: .zero, size: pageSize)138 guard let consumer = CGDataConsumer(data: data as CFMutableData), let ctx = CGContext(consumer: consumer, mediaBox: &box, [kCGPDFContextCreator: "SP Chat"] as CFDictionary) else { return Data() }139 let setter = CTFramesetterCreateWithAttributedString(text as CFAttributedString)140 let frameRect = box.insetBy(dx: margin, dy: margin)141 var location = 0; var page = 1142 repeat {143 ctx.beginPDFPage(nil)144 let path = CGPath(rect: frameRect, transform: nil)145 let frame = CTFramesetterCreateFrame(setter, CFRange(location: location, length: 0), path, nil)146 CTFrameDraw(frame, ctx)147 let footer = NSAttributedString(string: "\(page)", attributes: [.font: NSFont.systemFont(ofSize: 8), .foregroundColor: NSColor.gray])148 let line = CTLineCreateWithAttributedString(footer); ctx.textPosition = CGPoint(x: pageSize.width / 2 - 3, y: margin / 2); CTLineDraw(line, ctx)149 ctx.endPDFPage()150 let visible = CTFrameGetVisibleStringRange(frame)151 if visible.length == 0 { break }152 location += visible.length; page += 1153 } while location < text.length && page < 5000154 ctx.closePDF()155 return data as Data156 }157}158