Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocLayout/PageRenderer.swift3// Description: Draws a laid-out page into a Core Graphics context. The same code paints the editor canvas, page thumbnails, print and PDF,4// so what is on screen is what is published.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreGraphics10import CoreText11import ImageIO12import DocModel13import DocMath1415/// Decodes and caches the document's images.16public final class ImageStore: @unchecked Sendable {17 private let cache = NSCache<NSString, CGImage>()18 private var pdfs: [String: CGPDFDocument] = [:]19 private let lock = NSLock()20 public init() { cache.totalCostLimit = 512 * 1024 * 1024 }2122 public func image(for asset: Asset) -> CGImage? {23 if let hit = cache.object(forKey: asset.id as NSString) { return hit }24 guard asset.mimeType != "application/pdf", let src = CGImageSourceCreateWithData(asset.data as CFData, nil),25 let img = CGImageSourceCreateImageAtIndex(src, 0, [kCGImageSourceShouldCache: true] as CFDictionary) else { return nil }26 cache.setObject(img, forKey: asset.id as NSString, cost: img.bytesPerRow * img.height)27 return img28 }2930 public func pdfPage(for asset: Asset) -> CGPDFPage? {31 guard asset.mimeType == "application/pdf" else { return nil }32 lock.lock(); defer { lock.unlock() }33 if pdfs[asset.id] == nil, let provider = CGDataProvider(data: asset.data as CFData) { pdfs[asset.id] = CGPDFDocument(provider) }34 return pdfs[asset.id]?.page(at: 1)35 }3637 /// Pixel size and point size (at the image's own resolution) of image data, without decoding it fully.38 public static func naturalSize(of data: Data) -> CGSize? {39 guard let src = CGImageSourceCreateWithData(data as CFData, nil),40 let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as? [CFString: Any],41 let w = props[kCGImagePropertyPixelWidth] as? CGFloat, let h = props[kCGImagePropertyPixelHeight] as? CGFloat else { return nil }42 let dpi = (props[kCGImagePropertyDPIWidth] as? CGFloat) ?? 7243 let scale = dpi > 72 ? 72 / dpi : 144 return CGSize(width: w * scale, height: h * scale)45 }46}4748/// Semantic role of a piece of content, used to tag PDF output.49public enum ContentRole: Sendable {50 case paragraph, heading(Int), figure(alt: String), table, tableRow, tableHeaderCell, tableDataCell, listItem, note, caption, artifact51}5253public struct RenderHooks {54 /// Called with the page rectangle of every hyperlink run and its target.55 public var link: ((CGRect, String) -> Void)?56 public var begin: ((ContentRole) -> Void)?57 public var end: (() -> Void)?58 public init() {}59}6061public struct MarkerLabels: Sendable {62 public var pageBreak = "Page Break"63 public var columnBreak = "Column Break"64 public var sectionNextPage = "Section Break (Next Page)"65 public var sectionContinuous = "Section Break (Continuous)"66 public var sectionOdd = "Section Break (Odd Page)"67 public var sectionEven = "Section Break (Even Page)"68 public init() {}69}7071public final class PageRenderer {72 public let doc: DocumentModel73 public let layout: DocumentLayout74 public let images: ImageStore75 public var labels = MarkerLabels()76 /// Paints the paper. Off for PDF output, where an unset background stays transparent.77 public var drawsPaper = true78 /// Focus mode: paragraphs other than this one are dimmed.79 public var focusParagraphID: String?80 public var hooks = RenderHooks()8182 public init(doc: DocumentModel, layout: DocumentLayout, images: ImageStore = ImageStore()) {83 self.doc = doc; self.layout = layout; self.images = images84 }8586 var forPrint: Bool { layout.options.forPrint }8788 /// Draws page `index` in a context whose origin is the page's top-left corner with y pointing down.89 public func draw(page index: Int, in ctx: CGContext) {90 guard layout.pages.indices.contains(index) else { return }91 let page = layout.pages[index]92 let bounds = CGRect(origin: .zero, size: page.size)93 ctx.saveGState()94 if let bg = page.setup.background { ctx.setFillColor(bg.cgColor); ctx.fill(bounds) }95 else if drawsPaper { ctx.setFillColor(CGColor(gray: 1, alpha: 1)); ctx.fill(bounds) }96 if let wm = page.setup.watermark, !wm.isEmpty, !page.isBlank { drawWatermark(wm, in: bounds, ctx) }97 if let border = page.setup.border {98 stroke(border.line, ctx) { ctx.stroke(bounds.insetBy(dx: border.inset, dy: border.inset)) }99 }100 for f in page.floats where f.box.wrap == .behindText { drawFloat(f, ctx) }101 for t in page.tables { drawTable(t, ctx) }102 for f in page.texts { drawText(f, page: page, ctx) }103 for f in page.floats where f.box.wrap != .behindText { drawFloat(f, ctx) }104 ctx.setFillColor(CGColor(gray: 0.45, alpha: 1))105 for r in page.footnoteRules { ctx.fill(r) }106 ctx.setFillColor(CGColor(gray: 0.7, alpha: 1))107 for r in page.columnRules { ctx.fill(r) }108 if !forPrint { for m in page.markers { drawMarker(m, ctx) } }109 ctx.restoreGState()110 }111112 // MARK: Text113114 func role(for f: TextFragment) -> ContentRole {115 if case .note = f.story { return .note }116 if case .header = f.story { return .artifact }117 if case .footer = f.story { return .artifact }118 if f.path.cell != nil { return .paragraph }119 if f.layout.para.outlineLevel >= 1 { return .heading(min(6, f.layout.para.outlineLevel)) }120 if f.layout.label != nil, f.layout.para.outlineLevel == 0 { return .listItem }121 return .paragraph122 }123124 func drawText(_ f: TextFragment, page: PageLayout, _ ctx: CGContext) {125 let l = f.layout126 let para = l.para127 let dim = focusParagraphID != nil && f.story == .body && focusParagraphID != l.paragraphID128 ctx.saveGState()129 if dim { ctx.setAlpha(0.28) }130 let r = role(for: f)131 if case .artifact = r {} else { hooks.begin?(r) }132 // Paragraph shading and borders span the fragment.133 let box = CGRect(x: f.origin.x + para.indentLeft, y: f.origin.y, width: f.width - para.indentLeft - para.indentRight, height: f.height)134 if let shade = para.shading {135 ctx.setFillColor(shade.cgColor)136 ctx.fill(box.insetBy(dx: -4, dy: 0))137 }138 if let b = para.borderLeft { ctx.setFillColor(b.color.cgColor); ctx.fill(CGRect(x: box.minX - 12, y: box.minY, width: b.width, height: box.height)) }139 if let b = para.borderTop, f.lines.lowerBound == 0 { ctx.setFillColor(b.color.cgColor); ctx.fill(CGRect(x: box.minX, y: box.minY - 3, width: box.width, height: b.width)) }140 if let b = para.borderBottom, f.lines.upperBound == l.lines.count { ctx.setFillColor(b.color.cgColor); ctx.fill(CGRect(x: box.minX, y: box.maxY + 2, width: box.width, height: b.width)) }141142 var changed = false143 for i in f.lines {144 let line = l.lines[i]145 let baseline = f.baseline(ofLine: i)146 let top = f.top(ofLine: i)147 if i == 0, let label = l.label, !label.text.isEmpty {148 ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1)149 ctx.textPosition = CGPoint(x: f.origin.x + label.x, y: baseline)150 CTLineDraw(label.line, ctx)151 }152 changed = drawLine(line, layout: l, x: f.origin.x, baseline: baseline, top: top, ctx) || changed153 if !forPrint, changed {154 // Change bar in the margin next to lines that carry tracked changes.155 ctx.setFillColor(CGColor(srgbRed: 0.76, green: 0.25, blue: 0.05, alpha: 0.9))156 ctx.fill(CGRect(x: max(6, f.origin.x - 14), y: top + 1, width: 1.5, height: line.height - 2))157 changed = false158 }159 }160 if !forPrint, l.para.pageBreakBefore, f.lines.lowerBound == 0, f.story == .body {161 // nothing drawn: the break is visible as the page change itself162 }163 if case .artifact = r {} else { hooks.end?() }164 ctx.restoreGState()165 }166167 /// Draws one line. Returns true when the line carries a tracked change.168 func drawLine(_ line: LayoutLine, layout l: ParagraphLayout, x: CGFloat, baseline: CGFloat, top: CGFloat, _ ctx: CGContext) -> Bool {169 var changed = false170 let runs = CTLineGetGlyphRuns(line.line) as? [CTRun] ?? []171 for run in runs {172 let attrs = CTRunGetAttributes(run) as NSDictionary173 let info = attrs[runInfoKey] as? RunInfo174 let glyphs = CTRunGetGlyphCount(run)175 guard glyphs > 0 else { continue }176 var pos = CGPoint.zero177 CTRunGetPositions(run, CFRange(location: 0, length: 1), &pos)178 var ascent: CGFloat = 0, descent: CGFloat = 0179 let width = CGFloat(CTRunGetTypographicBounds(run, CFRange(location: 0, length: 0), &ascent, &descent, nil))180 let rx = x + line.x + pos.x181 if let info {182 if info.revision != nil || info.formatChanged { changed = true }183 if info.hidden { continue }184 if let hl = info.char.highlight {185 ctx.setFillColor(hl.cgColor)186 ctx.fill(CGRect(x: rx, y: top, width: width, height: line.height))187 } else if info.commented, !forPrint, self.layout.options.showComments {188 ctx.setFillColor(CGColor(srgbRed: 1.0, green: 0.84, blue: 0.2, alpha: 0.32))189 ctx.fill(CGRect(x: rx, y: top, width: width, height: line.height))190 }191 if let link = info.char.link, width > 0 { hooks.link?(CGRect(x: rx, y: top, width: width, height: line.height), link) }192 if let box = info.box {193 draw(box, x: rx, baseline: baseline, ctx)194 if case .text = box.content {} else { continue }195 decorate(info, x: rx, width: width, baseline: baseline, font: attrs[kCTFontAttributeName as String] as! CTFont?, ctx)196 continue197 }198 }199 ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1)200 ctx.textPosition = CGPoint(x: x + line.x, y: baseline)201 CTRunDraw(run, ctx, CFRange(location: 0, length: 0))202 if let info { decorate(info, x: rx, width: width - trailingSpace(run, line: line), baseline: baseline, font: attrs[kCTFontAttributeName as String] as! CTFont?, ctx) }203 }204 if line.hyphenated == false { drawLeaders(line, layout: l, x: x, baseline: baseline, ctx) }205 return changed206 }207208 func trailingSpace(_ run: CTRun, line: LayoutLine) -> CGFloat {209 let r = CTRunGetStringRange(run)210 let lineRange = CTLineGetStringRange(line.line)211 return r.location + r.length >= lineRange.location + lineRange.length ? CGFloat(CTLineGetTrailingWhitespaceWidth(line.line)) : 0212 }213214 func decorate(_ info: RunInfo, x: CGFloat, width: CGFloat, baseline: CGFloat, font: CTFont?, _ ctx: CGContext) {215 guard info.underline || info.strikethrough, width > 0, let font else { return }216 ctx.setFillColor(info.color.cgColor)217 let thickness = max(0.5, CTFontGetUnderlineThickness(font))218 if info.underline {219 let offset = max(1.2, -CTFontGetUnderlinePosition(font))220 ctx.fill(CGRect(x: x, y: baseline + offset - thickness / 2, width: width, height: thickness))221 }222 if info.strikethrough {223 ctx.fill(CGRect(x: x, y: baseline - CTFontGetXHeight(font) * 0.5 - thickness / 2, width: width, height: thickness))224 }225 }226227 /// Fills the gap of tab characters with the leader of the paragraph's tab stops.228 func drawLeaders(_ line: LayoutLine, layout l: ParagraphLayout, x: CGFloat, baseline: CGFloat, _ ctx: CGContext) {229 guard let leader = l.para.tabs.first(where: { $0.leader != .none })?.leader else { return }230 let text = l.attributed.string as NSString231 guard line.range.upperBound <= text.length else { return }232 var search = NSRange(location: line.range.lowerBound, length: line.range.count)233 while search.length > 0 {234 let r = text.range(of: "\t", options: [], range: search)235 guard r.location != NSNotFound else { break }236 let x0 = x + line.xPosition(for: r.location) + 3, x1 = x + line.xPosition(for: r.location + 1) - 3237 if x1 > x0 + 4 {238 let attrs = l.attributed.attributes(at: r.location, effectiveRange: nil)239 let color = (attrs[runInfoKey] as? RunInfo)?.color ?? .black240 ctx.setFillColor(color.cgColor)241 ctx.setStrokeColor(color.cgColor)242 switch leader {243 case .dots:244 let step: CGFloat = 4.2245 var px = (x0 / step).rounded(.up) * step246 while px < x1 { ctx.fillEllipse(in: CGRect(x: px - 0.45, y: baseline - 1.1, width: 0.9, height: 0.9)); px += step }247 case .dashes:248 ctx.setLineWidth(0.5); ctx.setLineDash(phase: 0, lengths: [3, 2])249 ctx.move(to: CGPoint(x: x0, y: baseline - 0.5)); ctx.addLine(to: CGPoint(x: x1, y: baseline - 0.5)); ctx.strokePath()250 ctx.setLineDash(phase: 0, lengths: [])251 case .line:252 ctx.fill(CGRect(x: x0, y: baseline + 0.5, width: x1 - x0, height: 0.5))253 case .none: break254 }255 }256 let next = r.location + 1257 search = NSRange(location: next, length: max(0, line.range.upperBound - next))258 }259 }260261 // MARK: Inline objects262263 func draw(_ box: InlineBox, x: CGFloat, baseline: CGFloat, _ ctx: CGContext) {264 switch box.content {265 case .anchor: break266 case .text(let line, let rise):267 ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1)268 ctx.textPosition = CGPoint(x: x, y: baseline - rise)269 CTLineDraw(line, ctx)270 case .dropCap(let line, let drop):271 ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1)272 ctx.textPosition = CGPoint(x: x, y: baseline + drop)273 CTLineDraw(line, ctx)274 case .equation(let m):275 hooks.begin?(.figure(alt: m.latex))276 m.draw(in: ctx, at: CGPoint(x: x, y: baseline))277 hooks.end?()278 case .image(let img):279 drawImage(img, in: CGRect(x: x, y: baseline - box.ascent, width: box.width, height: box.ascent), ctx)280 case .shape(let s):281 drawShape(s, in: CGRect(x: x, y: baseline - box.ascent, width: box.width, height: box.ascent), ctx)282 }283 }284285 func drawFloat(_ f: FloatFragment, _ ctx: CGContext) {286 switch f.box.inline {287 case .image(let img): drawImage(img, in: f.rect, ctx)288 case .shape(let s): drawShape(s, in: f.rect, ctx)289 default: break290 }291 }292293 public func drawImage(_ img: ImageObject, in bounds: CGRect, _ ctx: CGContext) {294 hooks.begin?(.figure(alt: img.altText))295 defer { hooks.end?() }296 ctx.saveGState()297 defer { ctx.restoreGState() }298 // The object keeps its own size; `bounds` is its (possibly rotated) bounding box.299 let rect = CGRect(x: bounds.midX - img.width / 2, y: bounds.midY - img.height / 2, width: img.width, height: img.height)300 if img.rotation != 0 {301 ctx.translateBy(x: bounds.midX, y: bounds.midY)302 ctx.rotate(by: img.rotation * .pi / 180)303 ctx.translateBy(x: -bounds.midX, y: -bounds.midY)304 }305 guard let asset = doc.assets[img.asset] else { placeholder(rect, text: img.altText.isEmpty ? "Missing image" : img.altText, ctx); return }306 ctx.clip(to: rect)307 // Flip locally: Core Graphics images are drawn with y pointing up.308 ctx.translateBy(x: rect.minX, y: rect.maxY)309 ctx.scaleBy(x: 1, y: -1)310 let c = img.crop311 let fw = max(0.05, 1 - c.left - c.right), fh = max(0.05, 1 - c.top - c.bottom)312 let full = CGRect(x: -c.left / fw * rect.width, y: -c.bottom / fh * rect.height, width: rect.width / fw, height: rect.height / fh)313 if let page = images.pdfPage(for: asset) {314 let media = page.getBoxRect(.cropBox)315 ctx.translateBy(x: full.minX, y: full.minY)316 ctx.scaleBy(x: full.width / max(1, media.width), y: full.height / max(1, media.height))317 ctx.translateBy(x: -media.minX, y: -media.minY)318 ctx.drawPDFPage(page)319 } else if let cg = images.image(for: asset) {320 ctx.interpolationQuality = .high321 ctx.draw(cg, in: full)322 } else {323 ctx.scaleBy(x: 1, y: -1)324 ctx.translateBy(x: -rect.minX, y: -rect.maxY)325 placeholder(rect, text: "Unreadable image", ctx)326 }327 }328329 func placeholder(_ rect: CGRect, text: String, _ ctx: CGContext) {330 ctx.setFillColor(CGColor(gray: 0.94, alpha: 1)); ctx.fill(rect)331 ctx.setStrokeColor(CGColor(gray: 0.7, alpha: 1)); ctx.setLineWidth(0.5); ctx.stroke(rect.insetBy(dx: 0.25, dy: 0.25))332 drawCentered(text, in: rect, size: 9, color: RGBA(hex: 0x6B7180), ctx)333 }334335 func drawCentered(_ text: String, in rect: CGRect, size: CGFloat, color: RGBA, _ ctx: CGContext) {336 guard !text.isEmpty else { return }337 let font = FontCache.shared.font(family: "SF Pro", size: size)338 let lines = text.components(separatedBy: "\n").map { s in339 CTLineCreateWithAttributedString(NSAttributedString(string: s, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font,340 NSAttributedString.Key(kCTForegroundColorAttributeName as String): color.cgColor]))341 }342 let lh = size * 1.3343 var y = rect.midY - CGFloat(lines.count) * lh / 2 + size344 ctx.saveGState()345 ctx.clip(to: rect)346 for line in lines {347 let w = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))348 ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1)349 ctx.textPosition = CGPoint(x: rect.midX - w / 2, y: y)350 CTLineDraw(line, ctx)351 y += lh352 }353 ctx.restoreGState()354 }355356 public func drawShape(_ s: ShapeObject, in rect: CGRect, _ ctx: CGContext) {357 hooks.begin?(.figure(alt: s.altText.isEmpty ? s.text : s.altText))358 defer { hooks.end?() }359 ctx.saveGState()360 let r = rect.insetBy(dx: s.strokeWidth / 2, dy: s.strokeWidth / 2)361 let path = CGMutablePath()362 switch s.kind {363 case .rectangle: path.addRect(r)364 case .roundedRectangle: path.addRoundedRect(in: r, cornerWidth: min(10, r.width / 4), cornerHeight: min(10, r.height / 4))365 case .ellipse: path.addEllipse(in: r)366 case .callout:367 let body = CGRect(x: r.minX, y: r.minY, width: r.width, height: r.height * 0.8)368 path.addRoundedRect(in: body, cornerWidth: min(8, body.width / 4), cornerHeight: min(8, body.height / 4))369 path.move(to: CGPoint(x: body.minX + body.width * 0.2, y: body.maxY))370 path.addLine(to: CGPoint(x: body.minX + body.width * 0.15, y: r.maxY))371 path.addLine(to: CGPoint(x: body.minX + body.width * 0.35, y: body.maxY))372 case .line, .arrow:373 path.move(to: CGPoint(x: r.minX, y: r.midY)); path.addLine(to: CGPoint(x: r.maxX, y: r.midY))374 if s.kind == .arrow {375 let a = min(10, r.width / 3)376 path.move(to: CGPoint(x: r.maxX - a, y: r.midY - a * 0.6)); path.addLine(to: CGPoint(x: r.maxX, y: r.midY)); path.addLine(to: CGPoint(x: r.maxX - a, y: r.midY + a * 0.6))377 }378 }379 if let fill = s.fill, s.kind != .line, s.kind != .arrow { ctx.addPath(path); ctx.setFillColor(fill.cgColor); ctx.fillPath() }380 ctx.addPath(path)381 ctx.setStrokeColor(s.stroke.cgColor); ctx.setLineWidth(s.strokeWidth); ctx.setLineJoin(.round); ctx.setLineCap(.round)382 ctx.strokePath()383 ctx.restoreGState()384 if !s.text.isEmpty, s.kind != .line, s.kind != .arrow {385 let area = s.kind == .callout ? CGRect(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height * 0.8) : rect386 drawCentered(s.text, in: area.insetBy(dx: 4, dy: 2), size: 10, color: RGBA(hex: 0x2B2F3A), ctx)387 }388 }389390 // MARK: Tables391392 func stroke(_ line: BorderLine, _ ctx: CGContext, _ draw: () -> Void) {393 ctx.saveGState()394 ctx.setStrokeColor(line.color.cgColor)395 ctx.setLineWidth(line.width)396 switch line.style {397 case .dashed: ctx.setLineDash(phase: 0, lengths: [4, 2.5])398 case .dotted: ctx.setLineDash(phase: 0, lengths: [0.8, 1.8]); ctx.setLineCap(.round)399 default: break400 }401 draw()402 ctx.restoreGState()403 }404405 func hline(_ b: BorderLine, _ x0: CGFloat, _ x1: CGFloat, _ y: CGFloat, _ ctx: CGContext) {406 stroke(b, ctx) { ctx.move(to: CGPoint(x: x0, y: y)); ctx.addLine(to: CGPoint(x: x1, y: y)); ctx.strokePath() }407 if b.style == .double { stroke(b, ctx) { ctx.move(to: CGPoint(x: x0, y: y + b.width * 2)); ctx.addLine(to: CGPoint(x: x1, y: y + b.width * 2)); ctx.strokePath() } }408 }409410 func vline(_ b: BorderLine, _ x: CGFloat, _ y0: CGFloat, _ y1: CGFloat, _ ctx: CGContext) {411 stroke(b, ctx) { ctx.move(to: CGPoint(x: x, y: y0)); ctx.addLine(to: CGPoint(x: x, y: y1)); ctx.strokePath() }412 }413414 func drawTable(_ f: TableFragment, _ ctx: CGContext) {415 let tl = f.layout, t = tl.table, style = t.style416 hooks.begin?(.table)417 defer { hooks.end?() }418 var rows: [(row: Int, y: CGFloat)] = []419 var y = f.origin.y420 for r in 0..<f.repeatedHeaderRows { rows.append((r, y)); y += tl.rowHeights[r] }421 for r in f.rows { rows.append((r, y)); y += tl.rowHeights[r] }422 let bottom = y423 let x0 = f.origin.x, x1 = f.origin.x + tl.width424 let lastGrid = t.columnCount425 var bodyIndex = 0426 for (r, ry) in rows {427 let row = t.rows[r]428 if !row.isHeader { bodyIndex = r - tl.headerRows }429 for cell in tl.cells[r] {430 let model = row.cells[cell.cellIndex]431 if model.vMerge == .continue { continue }432 let span = min(cell.rowSpan, (f.rows.upperBound - r > 0 ? f.rows.upperBound - r : 1))433 let h = tl.height(rows: r..<min(tl.rowHeights.count, r + max(1, span)))434 let rect = CGRect(x: x0 + cell.x, y: ry, width: cell.width, height: h)435 let shade = model.shading ?? (row.isHeader ? style.headerShading : (bodyIndex % 2 == 1 ? style.bandedRowShading : nil))436 if let shade { ctx.setFillColor(shade.cgColor); ctx.fill(rect) }437 let firstRow = r == rows.first?.row && ry == f.origin.y, lastRow = abs(rect.maxY - bottom) < 0.01438 let top = model.borderTop ?? (firstRow ? style.outerBorder : style.innerHorizontal)439 let bot = model.borderBottom ?? (lastRow ? style.outerBorder : nil)440 let left = model.borderLeft ?? (cell.gridStart == 0 ? style.outerBorder : style.innerVertical)441 let right = model.borderRight ?? (cell.gridStart + cell.span >= lastGrid ? style.outerBorder : nil)442 if let top { hline(top, rect.minX, rect.maxX, rect.minY, ctx) }443 if let bot { hline(bot, rect.minX, rect.maxX, rect.maxY, ctx) }444 if let left { vline(left, rect.minX, rect.minY, rect.maxY, ctx) }445 if let right { vline(right, rect.maxX, rect.minY, rect.maxY, ctx) }446 }447 }448 if style.name == TableStyle.academic.name {449 // Three-rule table: heavy rules above and below, a light rule under the header.450 let heavy = BorderLine(width: 1, color: .black), light = BorderLine(width: 0.5, color: .black)451 hline(heavy, x0, x1, f.origin.y, ctx)452 hline(heavy, x0, x1, bottom, ctx)453 let headerCount = f.repeatedHeaderRows > 0 ? f.repeatedHeaderRows : (f.rows.lowerBound == 0 ? tl.headerRows : 0)454 if headerCount > 0 { hline(light, x0, x1, f.origin.y + tl.height(rows: 0..<headerCount), ctx) }455 }456 }457458 // MARK: Page furniture459460 func drawWatermark(_ text: String, in bounds: CGRect, _ ctx: CGContext) {461 let size = min(bounds.width, bounds.height) / max(4, CGFloat(text.count)) * 1.55462 let font = FontCache.shared.font(family: "SF Pro", size: size, weight: 700)463 let line = CTLineCreateWithAttributedString(NSAttributedString(string: text, attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font,464 NSAttributedString.Key(kCTForegroundColorAttributeName as String): CGColor(gray: 0.5, alpha: 0.13)]))465 let w = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))466 ctx.saveGState()467 ctx.translateBy(x: bounds.midX, y: bounds.midY)468 ctx.rotate(by: -.pi / 5)469 ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1)470 ctx.textPosition = CGPoint(x: -w / 2, y: size * 0.35)471 CTLineDraw(line, ctx)472 ctx.restoreGState()473 }474475 func drawMarker(_ m: MarkerFragment, _ ctx: CGContext) {476 guard m.rect.height > 3 else { return }477 let text: String478 switch m.kind {479 case .pageBreak: text = labels.pageBreak480 case .columnBreak: text = labels.columnBreak481 case .sectionBreak(.nextPage): text = labels.sectionNextPage482 case .sectionBreak(.continuous): text = labels.sectionContinuous483 case .sectionBreak(.oddPage): text = labels.sectionOdd484 case .sectionBreak(.evenPage): text = labels.sectionEven485 }486 let color = RGBA(hex: 0x8A8FA3)487 let font = FontCache.shared.font(family: "SF Pro", size: 8, weight: 500)488 let line = CTLineCreateWithAttributedString(NSAttributedString(string: text.uppercased(), attributes: [NSAttributedString.Key(kCTFontAttributeName as String): font,489 NSAttributedString.Key(kCTForegroundColorAttributeName as String): color.cgColor, NSAttributedString.Key(kCTTrackingAttributeName as String): 0.6]))490 let w = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))491 let compact = m.rect.height < 12492 let midY = m.rect.minY + (compact ? 3 : 7)493 ctx.saveGState()494 if compact {495 // Not enough room for the label (continuous section breaks): a dashed rule only.496 ctx.setStrokeColor(color.cgColor); ctx.setLineWidth(0.5); ctx.setLineDash(phase: 0, lengths: [2, 2])497 ctx.move(to: CGPoint(x: m.rect.minX, y: midY)); ctx.addLine(to: CGPoint(x: m.rect.maxX, y: midY)); ctx.strokePath()498 ctx.restoreGState()499 return500 }501 ctx.setStrokeColor(color.cgColor); ctx.setLineWidth(0.5); ctx.setLineDash(phase: 0, lengths: [2, 2])502 ctx.move(to: CGPoint(x: m.rect.minX, y: midY)); ctx.addLine(to: CGPoint(x: m.rect.midX - w / 2 - 6, y: midY))503 ctx.move(to: CGPoint(x: m.rect.midX + w / 2 + 6, y: midY)); ctx.addLine(to: CGPoint(x: m.rect.maxX, y: midY))504 ctx.strokePath()505 ctx.textMatrix = CGAffineTransform(scaleX: 1, y: -1)506 ctx.textPosition = CGPoint(x: m.rect.midX - w / 2, y: midY + 2.8)507 CTLineDraw(line, ctx)508 ctx.restoreGState()509 }510}511