Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose/RichTextPlatform.swift3// Description: The platform side of the composer's rich text — display attributes (fonts, colours, paragraph styles) derived from the core's4// semantic attributes, the TextKit layout manager that draws list markers and quote bars, import of foreign attributed text (RTF paste),5// inline image decoding / downscaling (ImageIO) and pasteboard reading. Shared by the AppKit and UIKit text views.6import ImageIO7import SPMailCore8import SwiftUI9import UniformTypeIdentifiers10#if os(macOS)11import AppKit12typealias PlatformFont = NSFont13typealias PlatformColor = NSColor14#else15import UIKit16typealias PlatformFont = UIFont17typealias PlatformColor = UIColor18#endif1920/// A value crossing an isolation boundary that the type system cannot prove safe (undo handlers, item providers): used on the main actor only.21struct Unchecked<T>: @unchecked Sendable { let value: T }2223// MARK: - theme2425/// The colours and base size the editor draws with, resolved from the design tokens for the current theme.26struct RichTheme: Equatable {27 var text: PlatformColor, secondary: PlatformColor, accent: PlatformColor, codeBackground: PlatformColor, bar: PlatformColor28 var baseSize: CGFloat2930 @MainActor31 init(variant: SPVariant, increasedContrast: Bool = false) {32 func c(_ t: SPToken) -> PlatformColor { PlatformColor(t.color(variant, increasedContrast: increasedContrast)) }33 text = c(SPColor.text); secondary = c(SPColor.text2); accent = c(SPColor.accent); codeBackground = c(SPColor.surface3); bar = c(SPColor.borderStrong)34 baseSize = RichTheme.bodySize35 }3637 /// The body size: Dynamic Type on iOS, the system size (one point up, as in the reader) on macOS.38 @MainActor static var bodySize: CGFloat {39 #if os(macOS)40 NSFont.systemFontSize + 141 #else42 UIFont.preferredFont(forTextStyle: .body).pointSize43 #endif44 }45}4647// MARK: - display attributes4849enum RichStyler {50 static let listIndent: CGFloat = 24, quoteIndent: CGFloat = 1451 /// Attributes the styler owns: everything else on a run is semantic (or foreign and removed).52 static let displayKeys: [NSAttributedString.Key] = [.font, .foregroundColor, .backgroundColor, .underlineStyle, .strikethroughStyle, .paragraphStyle, .baselineOffset, .kern, .ligature, .link, .underlineColor, .strikethroughColor, .shadow, .obliqueness, .expansion, .strokeWidth, .strokeColor]5354 static func font(size: CGFloat, bold: Bool, italic: Bool, mono: Bool) -> PlatformFont {55 #if os(macOS)56 var font = mono ? NSFont.monospacedSystemFont(ofSize: size * 0.94, weight: bold ? .semibold : .regular) : NSFont.systemFont(ofSize: size, weight: bold ? .semibold : .regular)57 if italic { font = NSFont(descriptor: font.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits.union(.italic)), size: font.pointSize) ?? font }58 return font59 #else60 var font = mono ? UIFont.monospacedSystemFont(ofSize: size * 0.94, weight: bold ? .semibold : .regular) : UIFont.systemFont(ofSize: size, weight: bold ? .semibold : .regular)61 if italic, let d = font.fontDescriptor.withSymbolicTraits(font.fontDescriptor.symbolicTraits.union(.traitItalic)) { font = UIFont(descriptor: d, size: font.pointSize) }62 return font63 #endif64 }6566 static func paragraphStyle(_ block: RichBlock) -> NSParagraphStyle {67 let p = NSMutableParagraphStyle()68 let indent = CGFloat(block.quote) * quoteIndent + CGFloat(block.level) * listIndent69 p.firstLineHeadIndent = indent70 p.headIndent = indent71 p.lineSpacing = 272 if case .heading = block.kind { p.paragraphSpacingBefore = 4; p.paragraphSpacing = 4 }73 return p74 }7576 /// The display attributes of a run with these semantic attributes.77 static func display(for attrs: [NSAttributedString.Key: Any], theme: RichTheme) -> [NSAttributedString.Key: Any] {78 let block = RichBlock(rawValue: attrs[RichKey.block] as? String ?? "p")79 var size = theme.baseSize, heading = false80 if case .heading(let n) = block.kind { size *= n == 1 ? 1.55 : n == 2 ? 1.3 : 1.12; heading = true }81 let code = attrs[RichKey.code] != nil, link = attrs[RichKey.link] != nil82 var out: [NSAttributedString.Key: Any] = [83 .font: font(size: size, bold: heading || attrs[RichKey.bold] != nil, italic: attrs[RichKey.italic] != nil, mono: code),84 .foregroundColor: link ? theme.accent : block.quote > 0 ? theme.secondary : theme.text,85 .paragraphStyle: paragraphStyle(block),86 ]87 if attrs[RichKey.underline] != nil || link { out[.underlineStyle] = NSUnderlineStyle.single.rawValue }88 if attrs[RichKey.strike] != nil { out[.strikethroughStyle] = NSUnderlineStyle.single.rawValue }89 if code { out[.backgroundColor] = theme.codeBackground }90 return out91 }9293 /// Only the semantic attributes of a dictionary.94 static func semantic(_ attrs: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] {95 var out: [NSAttributedString.Key: Any] = [:]96 for key in RichKey.all { if let v = attrs[key] { out[key] = v } }97 return out98 }99100 /// Re-derives the display attributes of `range` (grown to whole paragraphs) and gives every inline image its attachment.101 @MainActor102 static func restyle(_ storage: NSMutableAttributedString, in range: NSRange, theme: RichTheme, maxImageWidth: CGFloat, image: (String) -> PlatformImage?) {103 guard storage.length > 0 else { return }104 let span = RichText.paragraphSpan(of: range, in: storage.string as NSString)105 guard span.length > 0 else { return }106 RichText.normalizeBlocks(storage, in: span)107 var runs: [(NSRange, [NSAttributedString.Key: Any])] = []108 storage.enumerateAttributes(in: span) { attrs, r, _ in runs.append((r, attrs)) }109 for (r, attrs) in runs {110 let sem = semantic(attrs)111 var wanted = display(for: sem, theme: theme)112 if let raw = sem[RichKey.image] as? String, let info = RichImage(rawValue: raw) {113 let existing = attrs[.attachment] as? RichImageAttachment114 if let existing, existing.info == info, existing.maxWidth == maxImageWidth, existing.isLoaded || image(info.cid) == nil { wanted[.attachment] = existing }115 else { wanted[.attachment] = RichImageAttachment(info: info, image: image(info.cid), maxWidth: maxImageWidth) }116 }117 for (k, v) in sem { wanted[k] = v }118 // replace only when something differs: untouched runs keep their layout119 let same = wanted.count == attrs.count && wanted.allSatisfy { k, v in (attrs[k] as AnyObject?)?.isEqual(v) ?? false }120 if !same { storage.setAttributes(wanted, range: r) }121 }122 }123}124125/// The attachment of an inline image: the decoded picture scaled to its display width, or a placeholder while its part is being fetched.126final class RichImageAttachment: NSTextAttachment {127 let info: RichImage128 let maxWidth: CGFloat129 let isLoaded: Bool130131 @MainActor132 init(info: RichImage, image: PlatformImage?, maxWidth: CGFloat) {133 self.info = info; self.maxWidth = maxWidth; isLoaded = image != nil134 super.init(data: nil, ofType: nil)135 let natural = image?.size ?? CGSize(width: 120, height: 80)136 let width = max(24, min(info.width.map { CGFloat($0) } ?? natural.width, maxWidth))137 let height = natural.width > 0 ? (width * natural.height / natural.width).rounded() : 80138 bounds = CGRect(x: 0, y: 0, width: width, height: height)139 self.image = image ?? RichImageAttachment.placeholder(size: bounds.size)140 }141 required init?(coder: NSCoder) { nil }142143 @MainActor144 static func placeholder(size: CGSize) -> PlatformImage {145 #if os(macOS)146 let image = NSImage(size: size, flipped: false) { rect in147 NSColor.tertiaryLabelColor.withAlphaComponent(0.18).setFill()148 NSBezierPath(roundedRect: rect, xRadius: 6, yRadius: 6).fill()149 return true150 }151 return image152 #else153 return UIGraphicsImageRenderer(size: size).image { ctx in154 UIColor.tertiaryLabel.withAlphaComponent(0.18).setFill()155 UIBezierPath(roundedRect: CGRect(origin: .zero, size: size), cornerRadius: 6).fill()156 }157 #endif158 }159}160161// MARK: - layout manager (list markers, quote bars)162163/// TextKit 1 layout manager of the editor: draws what is not text — the bullet or number of a list item in its indent, and the bar of a164/// quoted paragraph. Markers are never characters, so they cannot be selected, copied or left behind.165final class RichLayoutManager: NSLayoutManager {166 var theme: RichTheme?167 /// The block of the empty last paragraph (it has no character to carry one): what the insertion point is about to type.168 var trailingBlock: RichBlock = .body169170 override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) {171 super.drawBackground(forGlyphRange: glyphsToShow, at: origin)172 guard let storage = textStorage, let container = textContainers.first, let theme else { return }173 let s = storage.string as NSString174 let padding = container.lineFragmentPadding175 let font = RichStyler.font(size: theme.baseSize, bold: false, italic: false, mono: false)176177 func draw(block: RichBlock, firstLine: CGRect, baseline: CGFloat, whole: CGRect, paragraphStart: Int) {178 for k in 0..<block.quote {179 let bar = CGRect(x: origin.x + padding + CGFloat(k) * RichStyler.quoteIndent + 3, y: origin.y + whole.minY, width: 2, height: whole.height)180 theme.bar.setFill()181 #if os(macOS)182 NSBezierPath(roundedRect: bar, xRadius: 1, yRadius: 1).fill()183 #else184 UIBezierPath(roundedRect: bar, cornerRadius: 1).fill()185 #endif186 }187 guard block.isList else { return }188 let marker: String189 if block.kind == .ordered { marker = "\(ordinal(ofParagraphAt: paragraphStart, block: block, in: storage))." } else { marker = block.level == 1 ? "•" : block.level == 2 ? "◦" : "▪" }190 let attrs: [NSAttributedString.Key: Any] = [.font: font, .foregroundColor: block.quote > 0 ? theme.secondary : theme.text]191 let size = (marker as NSString).size(withAttributes: attrs)192 let indent = padding + CGFloat(block.quote) * RichStyler.quoteIndent + CGFloat(block.level) * RichStyler.listIndent193 let point = CGPoint(x: origin.x + indent - 7 - size.width, y: origin.y + firstLine.minY + baseline - font.ascender)194 (marker as NSString).draw(at: point, withAttributes: attrs)195 }196197 let chars = characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil)198 var at = s.length == 0 ? 0 : s.paragraphRange(for: NSRange(location: min(chars.location, s.length - 1), length: 0)).location199 while at < s.length, at <= NSMaxRange(chars) {200 let p = s.paragraphRange(for: NSRange(location: at, length: 0))201 guard p.length > 0 else { break }202 if let raw = storage.attribute(RichKey.block, at: p.location, effectiveRange: nil) as? String, raw != "p" {203 let block = RichBlock(rawValue: raw)204 let glyphs = glyphRange(forCharacterRange: p, actualCharacterRange: nil)205 if glyphs.length > 0 {206 var first = NSRange()207 let firstLine = lineFragmentRect(forGlyphAt: glyphs.location, effectiveRange: &first)208 let whole = boundingRect(forGlyphRange: glyphs, in: container)209 draw(block: block, firstLine: firstLine, baseline: location(forGlyphAt: glyphs.location).y, whole: CGRect(x: whole.minX, y: firstLine.minY, width: whole.width, height: max(firstLine.height, whole.maxY - firstLine.minY)), paragraphStart: p.location)210 }211 }212 at = NSMaxRange(p)213 }214 // the empty paragraph after the last line break215 let extra = extraLineFragmentRect216 if extra.height > 0, trailingBlock != .body, NSMaxRange(chars) >= s.length {217 draw(block: trailingBlock, firstLine: extra, baseline: font.ascender + (extra.height - font.ascender + font.descender) / 2 - 1, whole: extra, paragraphStart: s.length)218 }219 }220221 /// The number of an ordered item: its position among the items of the same list (same level and quote depth, not interrupted by a222 /// shallower paragraph).223 func ordinal(ofParagraphAt location: Int, block: RichBlock, in storage: NSAttributedString) -> Int {224 let s = storage.string as NSString225 var n = 1, at = location226 while at > 0 {227 let previous = s.paragraphRange(for: NSRange(location: at - 1, length: 0))228 let b = RichBlock(rawValue: storage.attribute(RichKey.block, at: previous.location, effectiveRange: nil) as? String ?? "p")229 if b.quote != block.quote || !b.isList || b.level < block.level { break }230 if b.level == block.level { if b.kind == .ordered { n += 1 } else { break } }231 at = previous.location232 }233 return n234 }235}236237// MARK: - foreign attributed text (RTF)238239enum RichImport {240 /// Attributed text from another app (RTF on the pasteboard) reduced to the composer's vocabulary: bold, italic, underline,241 /// strikethrough, fixed pitch, links and list paragraphs. Fonts, sizes, colours and attachments are not kept.242 static func semantic(from foreign: NSAttributedString) -> NSAttributedString {243 let out = NSMutableAttributedString(string: foreign.string)244 foreign.enumerateAttributes(in: NSRange(location: 0, length: foreign.length)) { attrs, r, _ in245 var a: [NSAttributedString.Key: Any] = [:]246 if let font = attrs[.font] as? PlatformFont {247 let traits = font.fontDescriptor.symbolicTraits248 #if os(macOS)249 if traits.contains(.bold) { a[RichKey.bold] = true }250 if traits.contains(.italic) { a[RichKey.italic] = true }251 if traits.contains(.monoSpace) { a[RichKey.code] = true }252 #else253 if traits.contains(.traitBold) { a[RichKey.bold] = true }254 if traits.contains(.traitItalic) { a[RichKey.italic] = true }255 if traits.contains(.traitMonoSpace) { a[RichKey.code] = true }256 #endif257 }258 if let u = attrs[.underlineStyle] as? Int, u != 0, attrs[.link] == nil { a[RichKey.underline] = true }259 if let st = attrs[.strikethroughStyle] as? Int, st != 0 { a[RichKey.strike] = true }260 if let link = (attrs[.link] as? URL)?.absoluteString ?? (attrs[.link] as? String), let safe = RichImport.safeLink(link) { a[RichKey.link] = safe }261 var block = RichBlock.body262 if let style = attrs[.paragraphStyle] as? NSParagraphStyle, let list = style.textLists.last {263 let ordered = list.markerFormat == .decimal || list.markerFormat.rawValue.contains("decimal") || list.markerFormat.rawValue.contains("alpha") || list.markerFormat.rawValue.contains("roman")264 block = RichBlock(kind: ordered ? .ordered : .bullet, level: style.textLists.count)265 }266 a[RichKey.block] = block.rawValue267 out.setAttributes(a, range: r)268 }269 // AppKit writes the marker of a list item as text (`\t•\t`): it is drawn, never typed, here270 let s = out.string as NSString271 var edits: [NSRange] = []272 for p in RichText.paragraphRanges(in: s) where p.length > 0 {273 guard RichText.block(ofParagraph: p, in: out).isList else { continue }274 let line = s.substring(with: p)275 if let m = line.range(of: "^\\t[^\\t]{0,8}\\t", options: .regularExpression) { edits.append(NSRange(location: p.location, length: line.distance(from: m.lowerBound, to: m.upperBound))) }276 }277 for r in edits.reversed() { out.deleteCharacters(in: r) }278 out.mutableString.replaceOccurrences(of: RichText.attachmentCharacter, with: "", options: [], range: NSRange(location: 0, length: out.length))279 for (from, to) in [("\r\n", "\n"), ("\r", "\n"), ("\u{2028}", "\n"), ("\u{2029}", "\n")] { out.mutableString.replaceOccurrences(of: from, with: to, options: [], range: NSRange(location: 0, length: out.length)) }280 RichText.normalizeBlocks(out, in: NSRange(location: 0, length: out.length))281 return out282 }283284 static func safeLink(_ raw: String) -> String? {285 let cleaned = String(raw.unicodeScalars.filter { $0.value > 0x20 && $0.value != 0x7F })286 let lower = cleaned.lowercased()287 return lower.hasPrefix("http://") || lower.hasPrefix("https://") || lower.hasPrefix("mailto:") ? cleaned : nil288 }289290 /// What a link field means: a bare address gets `https://`, an e-mail address `mailto:`; anything else unsafe is refused.291 static func normalizedLink(_ typed: String) -> String? {292 let t = typed.trimmingCharacters(in: .whitespacesAndNewlines)293 guard !t.isEmpty else { return nil }294 if let safe = safeLink(t) { return safe }295 if t.contains("://") || t.lowercased().hasPrefix("javascript:") || t.lowercased().hasPrefix("data:") || t.lowercased().hasPrefix("file:") { return nil }296 if AddressParser.isValid(t) { return "mailto:" + t }297 return t.contains(".") && !t.contains(" ") ? "https://" + t : nil298 }299}300301// MARK: - images302303/// One picture ready to be inserted inline: bytes in a type every mail client shows, and their pixel size.304struct InlineImageData: Sendable {305 var data: Data306 var type: String307 var name: String308 var pixelWidth: Int309 var pixelHeight: Int310}311312enum InlineImageCodec {313 /// Photos larger than this on their long side are reduced before they are attached.314 static let maxPixel = 2048315316 /// Makes a picture mail-safe: PNG, JPEG, GIF and WebP pass as they are when small enough; anything else (HEIC, TIFF, a huge photo)317 /// is redrawn as JPEG — or PNG when it has transparency — no larger than `maxPixel`. Nil when the bytes are not an image.318 nonisolated static func prepare(_ data: Data, name: String, maxPixel: Int = maxPixel) -> InlineImageData? {319 guard let source = CGImageSourceCreateWithData(data as CFData, nil), CGImageSourceGetCount(source) > 0,320 let props = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] else { return nil }321 var width = (props[kCGImagePropertyPixelWidth] as? Int) ?? 0, height = (props[kCGImagePropertyPixelHeight] as? Int) ?? 0322 if let orientation = props[kCGImagePropertyOrientation] as? Int, orientation >= 5 { swap(&width, &height) }323 guard width > 0, height > 0 else { return nil }324 let uti = (CGImageSourceGetType(source) as String?).flatMap { UTType($0) }325 let mime = uti?.preferredMIMEType ?? ""326 let base = (name as NSString).deletingPathExtension.isEmpty ? "image" : (name as NSString).deletingPathExtension327 if InlineParts.isInlineImageType(mime), max(width, height) <= maxPixel, data.count <= 1_500_000 {328 let ext = (name as NSString).pathExtension.isEmpty ? (uti?.preferredFilenameExtension ?? "png") : (name as NSString).pathExtension329 return InlineImageData(data: data, type: mime, name: "\(base).\(ext)", pixelWidth: width, pixelHeight: height)330 }331 let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceThumbnailMaxPixelSize: min(maxPixel, max(width, height))]332 guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }333 let alpha = ![CGImageAlphaInfo.none, .noneSkipFirst, .noneSkipLast].contains(image.alphaInfo)334 let out = NSMutableData()335 let type = alpha ? UTType.png : UTType.jpeg336 guard let dest = CGImageDestinationCreateWithData(out, type.identifier as CFString, 1, nil) else { return nil }337 CGImageDestinationAddImage(dest, image, [kCGImageDestinationLossyCompressionQuality: 0.82] as CFDictionary)338 guard CGImageDestinationFinalize(dest) else { return nil }339 return InlineImageData(data: out as Data, type: alpha ? "image/png" : "image/jpeg", name: "\(base).\(alpha ? "png" : "jpg")", pixelWidth: image.width, pixelHeight: image.height)340 }341342 @MainActor343 static func image(from data: Data) -> PlatformImage? {344 #if os(macOS)345 NSImage(data: data)346 #else347 UIImage(data: data)348 #endif349 }350}351352// MARK: - pasteboard353354/// What a paste or a drop brings, in the order the composer prefers it.355enum PasteContent {356 case files([URL])357 case images([Data])358 case rich(NSAttributedString)359 case plain(String)360361 #if os(macOS)362 @MainActor363 static func read(_ pb: NSPasteboard, plainOnly: Bool, allowedCIDs: Set<String>) -> PasteContent? {364 if !plainOnly {365 if let urls = pb.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty { return .files(urls) }366 let hasText = pb.availableType(from: [.string, .html, .rtf]) != nil367 if !hasText, let data = pb.data(forType: .png) ?? pb.data(forType: .tiff) { return .images([data]) }368 if let html = pb.string(forType: .html) ?? pb.data(forType: .html).flatMap({ String(data: $0, encoding: .utf8) }), !html.isEmpty {369 let parsed = RichHTML.parse(html, mode: .paste, allowedCIDs: allowedCIDs).text370 if parsed.length > 0 { return .rich(parsed) }371 }372 if let rtf = pb.data(forType: .rtf), let text = NSAttributedString(rtf: rtf, documentAttributes: nil), text.length > 0 { return .rich(RichImport.semantic(from: text)) }373 }374 if let s = pb.string(forType: .string), !s.isEmpty { return .plain(s) }375 return nil376 }377 #else378 @MainActor379 static func read(_ pb: UIPasteboard, plainOnly: Bool, allowedCIDs: Set<String>) -> PasteContent? {380 if !plainOnly {381 if pb.hasImages, !pb.hasStrings, let images = pb.images, !images.isEmpty { return .images(images.compactMap { $0.pngData() }) }382 if let data = pb.data(forPasteboardType: UTType.html.identifier), let html = String(data: data, encoding: .utf8), !html.isEmpty {383 let parsed = RichHTML.parse(html, mode: .paste, allowedCIDs: allowedCIDs).text384 if parsed.length > 0 { return .rich(parsed) }385 }386 if let rtf = pb.data(forPasteboardType: UTType.rtf.identifier), let text = try? NSAttributedString(data: rtf, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil), text.length > 0 {387 return .rich(RichImport.semantic(from: text))388 }389 }390 if let s = pb.string, !s.isEmpty { return .plain(s) }391 return nil392 }393 #endif394}395