SPB Git

Repository Public

ParagraphLayout.swift 34.5 KB 610 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocLayout/ParagraphLayout.swift3// Description: Paragraph typesetting with Core Text: attributed text from the model, inline object boxes, line breaking against variable widths4//              (indents, floats, drop caps), hyphenation, justification and line metrics. One character of the model is one character of the line.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CoreText10import CoreGraphics11import DocModel12import DocMath1314public struct LayoutOptions: Hashable, Sendable {15    public enum Markup: Sendable { case all, none }16    /// `.all` shows tracked insertions and deletions; `.none` shows the text as if every change were accepted.17    public var markup: Markup = .all18    /// Tint text that carries comments (screen only).19    public var showComments = true20    /// Printing and PDF: no editor decorations (break markers, comment tint, change bars).21    public var forPrint = false22    public init(markup: Markup = .all, showComments: Bool = true, forPrint: Bool = false) { self.markup = markup; self.showComments = showComments; self.forPrint = forPrint }23}2425public enum ReviewColors {26    static let palette: [RGBA] = [RGBA(hex: 0xC2410C), RGBA(hex: 0x1D4ED8), RGBA(hex: 0x15803D), RGBA(hex: 0x9333EA), RGBA(hex: 0xBE123C), RGBA(hex: 0x0F766E)]27    /// A stable colour per reviewer name.28    public static func color(for author: String) -> RGBA {29        var h: UInt32 = 216613626130        for b in author.utf8 { h = (h ^ UInt32(b)) &* 16777619 }31        return palette[Int(h % UInt32(palette.count))]32    }33}3435/// A region of a paragraph's vertical extent where the line is narrowed (a floating object or a drop cap). Widths are measured from the column edges.36public struct Exclusion: Hashable, Sendable {37    public var y0: CGFloat38    public var y1: CGFloat39    public var left: CGFloat40    public var right: CGFloat41    public init(y0: CGFloat, y1: CGFloat, left: CGFloat = 0, right: CGFloat = 0) { self.y0 = y0; self.y1 = y1; self.left = left; self.right = right }42}4344/// An inline object as it sits in a line: a box with metrics and a way to draw itself.45public final class InlineBox: @unchecked Sendable {46    public enum Content {47        case image(ImageObject)48        case shape(ShapeObject)49        case equation(MathLayout)50        /// Field, cross-reference, citation or note mark: typeset text, drawn `rise` above the baseline.51        case text(CTLine, rise: CGFloat)52        case dropCap(CTLine, drop: CGFloat)53        /// Zero-size anchor (bookmark, floating object anchor, hidden deleted text).54        case anchor55    }56    public let content: Content57    public let inline: Inline?58    public let width: CGFloat59    public let ascent: CGFloat60    public let descent: CGFloat61    init(_ content: Content, inline: Inline?, width: CGFloat, ascent: CGFloat, descent: CGFloat) {62        self.content = content; self.inline = inline; self.width = width; self.ascent = ascent; self.descent = descent63    }6465    func makeDelegate() -> CTRunDelegate {66        var callbacks = CTRunDelegateCallbacks(67            version: kCTRunDelegateVersion1,68            dealloc: { Unmanaged<InlineBox>.fromOpaque($0).release() },69            getAscent: { Unmanaged<InlineBox>.fromOpaque($0).takeUnretainedValue().ascent },70            getDescent: { Unmanaged<InlineBox>.fromOpaque($0).takeUnretainedValue().descent },71            getWidth: { Unmanaged<InlineBox>.fromOpaque($0).takeUnretainedValue().width })72        return CTRunDelegateCreate(&callbacks, Unmanaged.passRetained(self).toOpaque())!73    }74}7576/// Per-run information attached to the attributed string and read back when drawing.77final class RunInfo: NSObject, @unchecked Sendable {78    let char: ResolvedChar79    let color: RGBA80    let revision: Revision?81    let formatChanged: Bool82    let commented: Bool83    let hidden: Bool84    let box: InlineBox?85    let underline: Bool86    let strikethrough: Bool87    init(char: ResolvedChar, color: RGBA, revision: Revision?, formatChanged: Bool, commented: Bool, hidden: Bool, box: InlineBox?, underline: Bool, strikethrough: Bool) {88        self.char = char; self.color = color; self.revision = revision; self.formatChanged = formatChanged; self.commented = commented89        self.hidden = hidden; self.box = box; self.underline = underline; self.strikethrough = strikethrough90    }91}9293let runInfoKey = NSAttributedString.Key("orix.run")9495public struct FloatBox: @unchecked Sendable {96    /// Model offset of the anchor character.97    public var offset: Int98    public var inline: Inline99    /// Rectangle relative to the paragraph's top-left corner (x measured from the column's left edge).100    public var rect: CGRect101    public var wrap: WrapMode102}103104public struct LayoutLine: @unchecked Sendable {105    public let line: CTLine106    /// Model range (UTF-16) covered by the line.107    public let range: Range<Int>108    /// Offset to add to the CTLine's own string indexes to obtain model offsets (non-zero for hyphenated lines, which are typeset on their own).109    let indexBase: Int110    /// Left edge of the text, from the column's left edge.111    public let x: CGFloat112    /// Top of the line box, from the paragraph top.113    public let top: CGFloat114    public let height: CGFloat115    /// Baseline, from the paragraph top.116    public let baseline: CGFloat117    public let ascent: CGFloat118    public let descent: CGFloat119    public let width: CGFloat120    public let hyphenated: Bool121122    public var bottom: CGFloat { top + height }123124    /// x position (from the column's left edge) of the caret at model `offset`.125    public func xPosition(for offset: Int) -> CGFloat {126        let local = max(0, min(range.upperBound, offset)) - indexBase127        return x + CTLineGetOffsetForStringIndex(line, local, nil)128    }129130    /// Model offset nearest to an x position (from the column's left edge).131    public func offset(atX px: CGFloat) -> Int {132        let idx = CTLineGetStringIndexForPosition(line, CGPoint(x: px - x, y: 0))133        if idx == kCFNotFound { return range.lowerBound }134        return max(range.lowerBound, min(range.upperBound, idx + indexBase))135    }136}137138public struct LabelBox: @unchecked Sendable {139    public let line: CTLine140    public let x: CGFloat141    public let width: CGFloat142    public let text: String143}144145/// Everything the paragraph builder needs that does not come from the paragraph itself.146public struct ParagraphEnvironment {147    public var styles: StyleSheet148    public var options: LayoutOptions149    public var width: CGFloat150    /// List label ("1.", "•") shown hanging in the indent.151    public var listLabel: String?152    public var listLevel: ListLevel?153    /// Heading number ("2.1") shown inline before the text.154    public var headingNumber: String?155    /// Displayed text of each text-like inline object (fields, cross-references, citations, note marks), in order of appearance.156    public var boxTexts: [String]157    /// Narrowed regions caused by floating objects of earlier paragraphs.158    public var exclusions: [Exclusion]159    /// Header and footer paragraphs centre and right-align their tab stops on the actual width.160    public var isHeaderFooter: Bool161    public var mathTypeface: MathTypeface162    /// Overrides the text colour (table header rows of banded styles).163    public var colorOverride: RGBA?164    public var language: String165    public var assetSize: (String) -> CGSize?166167    public init(styles: StyleSheet, options: LayoutOptions, width: CGFloat, language: String = "en") {168        self.styles = styles; self.options = options; self.width = width; self.boxTexts = []; self.exclusions = []169        self.isHeaderFooter = false; self.mathTypeface = .latinModern; self.language = language; self.assetSize = { _ in nil }170    }171}172173public final class ParagraphLayout: @unchecked Sendable {174    public let paragraphID: String175    public let width: CGFloat176    public let para: ResolvedPara177    /// Length of the paragraph in UTF-16 units.178    public let length: Int179    public let lines: [LayoutLine]180    /// Height of the lines (spacing before and after excluded).181    public let height: CGFloat182    public let label: LabelBox?183    public let floats: [FloatBox]184    /// Footnote references by model offset.185    public let footnoteRefs: [(offset: Int, id: String)]186    public let hasChanges: Bool187    public let commentIDs: [String]188    /// Bookmark names and their model offsets (PDF destinations).189    public let bookmarks: [(offset: Int, name: String)]190    let attributed: NSAttributedString191    let boxes: [Int: InlineBox]192193    public var spaceBefore: CGFloat { para.spaceBefore }194    public var spaceAfter: CGFloat { para.spaceAfter }195196    public func lineIndex(containing offset: Int, preferPrevious: Bool = false) -> Int {197        guard !lines.isEmpty else { return 0 }198        for (i, l) in lines.enumerated() {199            if offset < l.range.upperBound { return i }200            if offset == l.range.upperBound {201                // The boundary between two lines belongs to the next line, unless asked otherwise (End key, upstream affinity) or it is the last one.202                if i == lines.count - 1 || preferPrevious { return i }203                // After a hard break the caret is always on the next line.204            }205        }206        return lines.count - 1207    }208209    public func box(at offset: Int) -> InlineBox? { boxes[offset] }210211    /// The paragraph text as displayed (one character per model character).212    public var plainString: String { attributed.string }213214    // MARK: Building215216    public init(_ p: Paragraph, env: ParagraphEnvironment) {217        paragraphID = p.id218        width = env.width219        let para = env.styles.paraProps(style: p.style, direct: p.props)220        self.para = para221        let showMarkup = env.options.markup == .all222223        // 1. Attributed string, one model character per character.224        let text = NSMutableAttributedString()225        var boxes: [Int: InlineBox] = [:]226        var floats: [FloatBox] = []227        var notes: [(Int, String)] = []228        var marks: [(Int, String)] = []229        var commentIDs: [String] = []230        var changes = p.markRevision != nil231        var textIndex = 0232        var offset = 0233        let baseChar = env.styles.charProps(paraStyle: p.style, charStyle: nil, direct: .none)234        var lastChar = baseChar235236        func font(_ c: ResolvedChar) -> CTFont { FontCache.shared.font(for: c) }237238        for run in p.runs where !run.text.isEmpty {239            var c = env.styles.charProps(paraStyle: p.style, charStyle: run.charStyle, direct: run.props)240            lastChar = c241            var color = env.colorOverride ?? c.color242            var underline = c.underline, strike = c.strikethrough243            var hidden = false244            if let rev = run.revision {245                changes = true246                if showMarkup {247                    color = ReviewColors.color(for: rev.author)248                    if rev.kind == .insertion { underline = true } else { strike = true }249                } else if rev.kind == .deletion {250                    hidden = true251                }252            }253            if run.formatRevision != nil { changes = true }254            for id in run.comments where !commentIDs.contains(id) { commentIDs.append(id) }255            c.color = color256            var attrs: [NSAttributedString.Key: Any] = [:]257            let f = font(c)258            attrs[NSAttributedString.Key(kCTFontAttributeName as String)] = f259            attrs[NSAttributedString.Key(kCTForegroundColorAttributeName as String)] = color.cgColor260            if c.tracking != 0 { attrs[NSAttributedString.Key(kCTTrackingAttributeName as String)] = c.tracking }261            if !c.kerning { attrs[NSAttributedString.Key(kCTKernAttributeName as String)] = 0 }262            if !c.ligatures { attrs[NSAttributedString.Key(kCTLigatureAttributeName as String)] = 0 }263            let shift: CGFloat = c.baselineShift + (c.vertical == .superscript ? c.fontSize * 0.33 : c.vertical == .subscript ? -c.fontSize * 0.14 : 0)264            if shift != 0 { attrs[NSAttributedString.Key(kCTBaselineOffsetAttributeName as String)] = shift }265            if let lang = c.language { attrs[NSAttributedString.Key(kCTLanguageAttributeName as String)] = lang }266267            var box: InlineBox?268            var display = run.text269            if hidden {270                box = InlineBox(.anchor, inline: nil, width: 0, ascent: 0, descent: 0)271            } else if let inline = run.inline {272                let ascent = CTFontGetAscent(f), descent = CTFontGetDescent(f)273                func textBox(_ s: String, superscript: Bool = false) -> InlineBox {274                    var cc = c275                    if superscript { cc.vertical = .superscript }276                    var a: [NSAttributedString.Key: Any] = [NSAttributedString.Key(kCTFontAttributeName as String): font(cc),277                                                             NSAttributedString.Key(kCTForegroundColorAttributeName as String): color.cgColor]278                    if c.tracking != 0 { a[NSAttributedString.Key(kCTTrackingAttributeName as String)] = c.tracking }279                    let line = CTLineCreateWithAttributedString(NSAttributedString(string: s.isEmpty ? "\u{200B}" : s, attributes: a))280                    let w = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))281                    return InlineBox(.text(line, rise: superscript ? c.fontSize * 0.33 : 0), inline: inline, width: w, ascent: ascent, descent: descent)282                }283                func nextText() -> String { defer { textIndex += 1 }; return textIndex < env.boxTexts.count ? env.boxTexts[textIndex] : "?" }284                switch inline {285                case .image(let img):286                    let size = ParagraphLayout.boundingSize(width: img.width, height: img.height, rotation: img.rotation)287                    if case .floating(let wrap, let align, let xo, let yo) = img.placement {288                        floats.append(FloatBox(offset: offset, inline: inline, rect: ParagraphLayout.floatRect(size, align: align, x: xo, y: yo, columnWidth: env.width), wrap: wrap))289                        box = InlineBox(.anchor, inline: inline, width: 0, ascent: 0, descent: 0)290                    } else {291                        box = InlineBox(.image(img), inline: inline, width: size.width, ascent: size.height, descent: 0)292                    }293                case .shape(let shape):294                    let size = CGSize(width: shape.width, height: shape.height)295                    if case .floating(let wrap, let align, let xo, let yo) = shape.placement {296                        floats.append(FloatBox(offset: offset, inline: inline, rect: ParagraphLayout.floatRect(size, align: align, x: xo, y: yo, columnWidth: env.width), wrap: wrap))297                        box = InlineBox(.anchor, inline: inline, width: 0, ascent: 0, descent: 0)298                    } else {299                        box = InlineBox(.shape(shape), inline: inline, width: size.width, ascent: size.height, descent: 0)300                    }301                case .equation(let eq):302                    let m = MathRenderer.layout(latex: eq.latex, fontSize: c.fontSize * 1.1, display: eq.display, color: color, typeface: env.mathTypeface)303                    box = InlineBox(.equation(m), inline: inline, width: m.width, ascent: m.ascent, descent: m.descent)304                case .note(let ref):305                    if ref.kind == .footnote { notes.append((offset, ref.id)) }306                    box = textBox(nextText(), superscript: true)307                case .citation, .crossRef, .field:308                    box = textBox(nextText())309                case .bookmark(let name):310                    marks.append((offset, name))311                    box = InlineBox(.anchor, inline: inline, width: 0, ascent: 0, descent: 0)312                }313            } else if c.allCaps {314                let upper = run.text.uppercased(with: Locale(identifier: c.language ?? env.language))315                if upper.utf16.count == run.text.utf16.count { display = upper }316            }317            if let box { attrs[NSAttributedString.Key(kCTRunDelegateAttributeName as String)] = box.makeDelegate(); boxes[offset] = box }318            attrs[runInfoKey] = RunInfo(char: c, color: color, revision: showMarkup ? run.revision : nil, formatChanged: showMarkup && run.formatRevision != nil,319                                        commented: !run.comments.isEmpty, hidden: hidden, box: box, underline: underline, strikethrough: strike)320            let startIndex = text.length321            text.append(NSAttributedString(string: display, attributes: attrs))322            if box == nil, display.unicodeScalars.contains("\u{00A0}") {323                // Some fonts (Charter among them) give the no-break space a figure-wide advance: bring it back to the width of a space.324                let delta = FontCache.shared.noBreakSpaceCorrection(f)325                if abs(delta) > 0.01 {326                    let ns = display as NSString327                    var search = NSRange(location: 0, length: ns.length)328                    while search.length > 0 {329                        let r = ns.range(of: "\u{00A0}", options: [], range: search)330                        guard r.location != NSNotFound else { break }331                        // Tracking and kerning do not add up on one character: use whichever the run already uses.332                        let key = c.tracking != 0 ? kCTTrackingAttributeName : kCTKernAttributeName333                        text.addAttribute(NSAttributedString.Key(key as String), value: delta + c.tracking, range: NSRange(location: startIndex + r.location, length: 1))334                        search = NSRange(location: r.location + 1, length: ns.length - r.location - 1)335                    }336                }337            }338            offset += run.length339        }340        length = offset341        self.boxes = boxes342        self.footnoteRefs = notes.map { (offset: $0.0, id: $0.1) }343        self.bookmarks = marks.map { (offset: $0.0, name: $0.1) }344        self.commentIDs = commentIDs345        self.hasChanges = changes346347        // 2. Paragraph geometry.348        var indentLeft = para.indentLeft, firstIndent = para.indentLeft + para.firstLineIndent349        var label: LabelBox?350        let labelAttrs: [NSAttributedString.Key: Any] = {351            var c = p.runs.first.map { env.styles.charProps(paraStyle: p.style, charStyle: nil, direct: CharProps(fontSize: $0.props.fontSize, color: $0.props.color)) } ?? baseChar352            c.italic = baseChar.italic; c.underline = false353            if let o = env.colorOverride { c.color = o }354            return [NSAttributedString.Key(kCTFontAttributeName as String): FontCache.shared.font(for: c),355                    NSAttributedString.Key(kCTForegroundColorAttributeName as String): c.color.cgColor]356        }()357        if let lbl = env.listLabel, let level = env.listLevel {358            indentLeft = level.indent + para.indentLeft359            firstIndent = indentLeft360            let line = CTLineCreateWithAttributedString(NSAttributedString(string: lbl, attributes: labelAttrs))361            let w = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))362            let x = max(0, indentLeft - level.hanging)363            label = LabelBox(line: line, x: x, width: w, text: lbl)364            firstIndent = max(indentLeft, x + w + 3)365        } else if let number = env.headingNumber {366            let line = CTLineCreateWithAttributedString(NSAttributedString(string: number, attributes: labelAttrs))367            let w = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))368            label = LabelBox(line: line, x: max(0, firstIndent), width: w, text: number)369            firstIndent = max(0, firstIndent) + w + baseChar.fontSize * 0.55370        }371        firstIndent = max(0, firstIndent)372        indentLeft = max(0, indentLeft)373374        // Tab stops are measured from the column's left edge.375        var tabs = para.tabs376        if env.isHeaderFooter && p.props.tabs == nil {377            tabs = [TabStop(position: env.width / 2, kind: .center), TabStop(position: env.width, kind: .right)]378        }379        var ctTabs: [CTTextTab] = tabs.map { t in380            switch t.kind {381            case .left: return CTTextTabCreate(.left, t.position, nil)382            case .center: return CTTextTabCreate(.center, t.position, nil)383            case .right: return CTTextTabCreate(.right, t.position, nil)384            case .decimal:385                let opts = [kCTTabColumnTerminatorsAttributeName: CFCharacterSetCreateWithCharactersInString(nil, ".," as CFString)!] as CFDictionary386                return CTTextTabCreate(.right, t.position, opts)387            }388        }389        var interval: CGFloat = 36390        var direction: CTWritingDirection = para.rightToLeft ? .rightToLeft : .natural391        let style: CTParagraphStyle = withUnsafePointer(to: &interval) { ip in392            withUnsafePointer(to: &direction) { dp in393                let arr = ctTabs as CFArray394                return withUnsafePointer(to: arr) { tp in395                    let settings = [CTParagraphStyleSetting(spec: .defaultTabInterval, valueSize: MemoryLayout<CGFloat>.size, value: ip),396                                    CTParagraphStyleSetting(spec: .baseWritingDirection, valueSize: MemoryLayout<CTWritingDirection>.size, value: dp),397                                    CTParagraphStyleSetting(spec: .tabStops, valueSize: MemoryLayout<CFArray>.size, value: tp)]398                    return CTParagraphStyleCreate(settings, settings.count)399                }400            }401        }402        ctTabs.removeAll()403        if text.length > 0 { text.addAttribute(NSAttributedString.Key(kCTParagraphStyleAttributeName as String), value: style, range: NSRange(location: 0, length: text.length)) }404        precondition(text.length == length, "display text must map one to one onto the model text")405406        // 3. Floats belonging to this paragraph narrow its own lines.407        var exclusions = env.exclusions408        for f in floats {409            switch f.wrap {410            case .square:411                let mid = f.rect.midX412                if mid < env.width * 0.4 { exclusions.append(Exclusion(y0: f.rect.minY - 2, y1: f.rect.maxY + 4, left: f.rect.maxX + 9)) }413                else if mid > env.width * 0.6 { exclusions.append(Exclusion(y0: f.rect.minY - 2, y1: f.rect.maxY + 4, right: env.width - f.rect.minX + 9)) }414                else { exclusions.append(Exclusion(y0: f.rect.minY - 2, y1: f.rect.maxY + 6, left: env.width)) }415            case .topAndBottom: exclusions.append(Exclusion(y0: f.rect.minY - 2, y1: f.rect.maxY + 6, left: env.width))416            case .behindText, .inFrontOfText: break417            }418        }419        self.floats = floats420421        // 4. Line breaking.422        let markFont = FontCache.shared.font(for: lastChar)423        let fontLine = CTFontGetAscent(markFont) + CTFontGetDescent(markFont) + CTFontGetLeading(markFont)424        var lines: [LayoutLine] = []425        var y: CGFloat = 0426        let nsText = text.string as NSString427        let alignment: TextAlignment = para.rightToLeft && para.alignment == .left ? .right : para.alignment428        let hyphenLocale = Locale(identifier: lastChar.language ?? env.language)429        let canHyphenate = para.hyphenate && CFStringIsHyphenationAvailableForLocale(hyphenLocale as CFLocale)430431        func extent(at y: CGFloat, height: CGFloat, first: Bool) -> (x: CGFloat, width: CGFloat, skipTo: CGFloat?) {432            var left = first ? firstIndent : indentLeft433            var right = max(0, para.indentRight)434            var skip: CGFloat?435            for e in exclusions where y < e.y1 && y + height > e.y0 {436                left = max(left, e.left)437                right = max(right, e.right)438                if e.left >= env.width || env.width - max(left, e.left) - max(right, e.right) < 40 { skip = max(skip ?? 0, e.y1) }439            }440            return (left, max(20, env.width - left - right), skip)441        }442443        func metrics(_ line: CTLine) -> (a: CGFloat, d: CGFloat, l: CGFloat, w: CGFloat) {444            var a: CGFloat = 0, d: CGFloat = 0, l: CGFloat = 0445            let w = CGFloat(CTLineGetTypographicBounds(line, &a, &d, &l))446            return (a, d, l, w)447        }448449        func place(_ ctLine: CTLine, range: Range<Int>, base: Int, x0: CGFloat, avail: CGFloat, last: Bool, hardBreak: Bool, hyphenated: Bool) {450            var line = ctLine451            if alignment == .justified, !last, !hardBreak, let j = CTLineCreateJustifiedLine(line, 1.0, Double(avail)) { line = j }452            var m = metrics(line)453            if m.a + m.d < 1 { m.a = CTFontGetAscent(markFont); m.d = CTFontGetDescent(markFont); m.l = CTFontGetLeading(markFont) }454            let natural = m.a + m.d + m.l455            var h = natural456            switch para.lineSpacing {457            case .multiple(let k): h = natural + (CGFloat(k) - 1) * min(natural, fontLine)458            case .exact(let v): h = CGFloat(v)459            case .atLeast(let v): h = max(CGFloat(v), natural)460            }461            h = max(1, h)462            let trailing = CGFloat(CTLineGetTrailingWhitespaceWidth(line))463            var x = x0464            switch alignment {465            case .center: x += max(0, (avail - (m.w - trailing)) / 2)466            case .right: x += max(0, avail - (m.w - trailing))467            default: break468            }469            let baseline = y + (h - (m.a + m.d)) / 2 + m.a470            lines.append(LayoutLine(line: line, range: range, indexBase: base, x: x, top: y, height: h, baseline: baseline, ascent: m.a, descent: m.d, width: m.w, hyphenated: hyphenated))471            y += h472        }473474        if length == 0 {475            let attrs: [NSAttributedString.Key: Any] = [NSAttributedString.Key(kCTFontAttributeName as String): markFont]476            let empty = CTLineCreateWithAttributedString(NSAttributedString(string: "\u{200B}", attributes: attrs))477            // An empty paragraph still honours floats above it.478            var e = extent(at: y, height: fontLine, first: true)479            while let s = e.skipTo, s > y { y = s; e = extent(at: y, height: fontLine, first: true) }480            place(empty, range: 0..<0, base: 0, x0: e.x, avail: e.width, last: true, hardBreak: false, hyphenated: false)481        } else {482            let typesetter = CTTypesetterCreateWithAttributedString(text)483            var start = 0484            var guardCount = 0485            // Drop cap: the first character is replaced by a large glyph box and the following lines step aside.486            var dropCap: (lines: Int, width: CGFloat)?487            if para.dropCapLines >= 2, env.listLabel == nil, let first = p.runs.first, first.inline == nil, first.revision == nil,488               let scalar = first.text.unicodeScalars.first, CharacterSet.letters.contains(scalar) {489                let cluster = nsText.rangeOfComposedCharacterSequence(at: 0)490                let c0 = env.styles.charProps(paraStyle: p.style, charStyle: first.charStyle, direct: first.props)491                let f0 = FontCache.shared.font(for: c0)492                let n = CGFloat(min(6, para.dropCapLines))493                var lineH = fontLine494                if case .multiple(let k) = para.lineSpacing { lineH = fontLine * CGFloat(k) }495                let cap = max(1, CTFontGetCapHeight(f0))496                var big = c0497                big.fontSize = c0.fontSize * ((n - 1) * lineH + cap) / cap498                let bigLine = CTLineCreateWithAttributedString(NSAttributedString(string: nsText.substring(with: cluster), attributes: [499                    NSAttributedString.Key(kCTFontAttributeName as String): FontCache.shared.font(for: big),500                    NSAttributedString.Key(kCTForegroundColorAttributeName as String): (env.colorOverride ?? c0.color).cgColor]))501                let w = CGFloat(CTLineGetTypographicBounds(bigLine, nil, nil, nil)) + c0.fontSize * 0.25502                let box = InlineBox(.dropCap(bigLine, drop: (n - 1) * lineH), inline: nil, width: w, ascent: CTFontGetAscent(f0), descent: CTFontGetDescent(f0))503                text.addAttribute(NSAttributedString.Key(kCTRunDelegateAttributeName as String), value: box.makeDelegate(), range: cluster)504                if let info = text.attribute(runInfoKey, at: 0, effectiveRange: nil) as? RunInfo {505                    text.addAttribute(runInfoKey, value: RunInfo(char: info.char, color: info.color, revision: nil, formatChanged: false, commented: info.commented,506                                                                 hidden: false, box: box, underline: false, strikethrough: false), range: cluster)507                }508                dropCap = (Int(n), w)509            }510            let ts = dropCap == nil ? typesetter : CTTypesetterCreateWithAttributedString(text)511            while start < length && guardCount < 100_000 {512                guardCount += 1513                let first = lines.isEmpty514                var e = extent(at: y, height: fontLine, first: first)515                if let s = e.skipTo, s > y { y = s; e = extent(at: y, height: fontLine, first: first); if let s2 = e.skipTo, s2 > y { continue } }516                var count = CTTypesetterSuggestLineBreakWithOffset(ts, start, Double(e.width), Double(e.x))517                if count <= 0 { count = max(1, nsText.rangeOfComposedCharacterSequence(at: start).length) }518                var end = start + count519                let lastChar16 = nsText.character(at: end - 1)520                let hardBreak = lastChar16 == 0x2028 || lastChar16 == 0x000A521                var placed = false522                // Hyphenation: try to pull the beginning of the next word onto this line.523                if canHyphenate, end < length, !hardBreak, nsText.rangeOfCharacter(from: .init(charactersIn: "\t"), options: [], range: NSRange(location: start, length: count)).location == NSNotFound {524                    var wordEnd = end525                    while wordEnd < length, let s = UnicodeScalar(nsText.character(at: wordEnd)), CharacterSet.letters.contains(s) { wordEnd += 1 }526                    if wordEnd - end >= 5, end > start, nsText.character(at: end - 1) == 0x20 {527                        var limit = wordEnd - 2528                        while limit > end + 1 {529                            let h = CFStringGetHyphenationLocationBeforeIndex(nsText, limit, CFRange(location: end, length: wordEnd - end), 0, hyphenLocale as CFLocale, nil)530                            if h == kCFNotFound || h <= end + 1 { break }531                            let piece = NSMutableAttributedString(attributedString: text.attributedSubstring(from: NSRange(location: start, length: h - start)))532                            piece.append(NSAttributedString(string: "-", attributes: text.attributes(at: h - 1, effectiveRange: nil).filter { $0.key != NSAttributedString.Key(kCTRunDelegateAttributeName as String) }))533                            let candidate = CTLineCreateWithAttributedString(piece)534                            if CGFloat(CTLineGetTypographicBounds(candidate, nil, nil, nil)) <= e.width {535                                place(candidate, range: start..<h, base: start, x0: e.x, avail: e.width, last: false, hardBreak: false, hyphenated: true)536                                end = h537                                placed = true538                                break539                            }540                            limit = h541                        }542                    }543                }544                if !placed {545                    let line = CTTypesetterCreateLineWithOffset(ts, CFRange(location: start, length: end - start), Double(e.x))546                    place(line, range: start..<end, base: 0, x0: e.x, avail: e.width, last: end >= length, hardBreak: hardBreak, hyphenated: false)547                }548                if let dc = dropCap, lines.count == 1 {549                    exclusions.append(Exclusion(y0: lines[0].height * 0.5, y1: lines[0].height * CGFloat(dc.lines) - 1, left: firstIndent + dc.width))550                }551                start = end552            }553            // A paragraph that ends with a forced line break shows an empty last line for the caret.554            if let last = lines.last, nsText.length > 0, nsText.character(at: nsText.length - 1) == 0x2028, last.range.upperBound == length {555                let attrs: [NSAttributedString.Key: Any] = [NSAttributedString.Key(kCTFontAttributeName as String): markFont]556                let empty = CTLineCreateWithAttributedString(NSAttributedString(string: "\u{200B}", attributes: attrs))557                let e = extent(at: y, height: fontLine, first: false)558                place(empty, range: length..<length, base: length, x0: e.x, avail: e.width, last: true, hardBreak: false, hyphenated: false)559            }560        }561        self.lines = lines562        self.height = y563        self.label = label564        self.attributed = text565    }566567    static func boundingSize(width: CGFloat, height: CGFloat, rotation: Double) -> CGSize {568        let r = rotation.truncatingRemainder(dividingBy: 360) * .pi / 180569        guard abs(r) > 0.0001 else { return CGSize(width: width, height: height) }570        let c = abs(cos(r)), s = abs(sin(r))571        return CGSize(width: width * c + height * s, height: width * s + height * c)572    }573574    static func floatRect(_ size: CGSize, align: HorizontalAnchor, x: CGFloat, y: CGFloat, columnWidth: CGFloat) -> CGRect {575        let px: CGFloat576        switch align {577        case .left: px = x578        case .center: px = (columnWidth - size.width) / 2 + x579        case .right: px = columnWidth - size.width - x580        }581        return CGRect(x: px, y: y, width: size.width, height: size.height)582    }583584    /// Height of lines `range` (line boxes only).585    public func height(ofLines range: Range<Int>) -> CGFloat {586        guard !range.isEmpty, range.lowerBound < lines.count else { return 0 }587        return lines[min(lines.count, range.upperBound) - 1].bottom - lines[range.lowerBound].top588    }589590    /// The lowest point reached by the paragraph's floats, from the paragraph top.591    public var floatBottom: CGFloat { floats.map(\.rect.maxY).max() ?? 0 }592593    /// Rectangles (relative to the paragraph: x from the column's left edge, y from the paragraph top) covering a model range, per line.594    public func rects(for range: Range<Int>, lines lineRange: Range<Int>? = nil) -> [(line: Int, rect: CGRect)] {595        var out: [(Int, CGRect)] = []596        let lr = lineRange ?? 0..<lines.count597        for i in lr where i < lines.count {598            let l = lines[i]599            let lo = max(range.lowerBound, l.range.lowerBound), hi = min(range.upperBound, l.range.upperBound)600            guard lo < hi || (range.isEmpty && lo == hi) else { continue }601            let a = l.xPosition(for: lo)602            // A selection that runs past the line end extends to the end of the visible text.603            var b = hi == l.range.upperBound && !l.hyphenated ? l.x + l.width - CGFloat(CTLineGetTrailingWhitespaceWidth(l.line)) : l.xPosition(for: hi)604            if hi == l.range.upperBound { b = max(b, l.xPosition(for: hi)) }605            out.append((i, CGRect(x: min(a, b), y: l.top, width: abs(b - a), height: l.height)))606        }607        return out608    }609}610
Files main
Menu

Theme