Cotton code
214 lines · 11.3 KB · SwiftRaw
// The layout under the text: tag chips, checkboxes, dividers and quote bars// drawn behind the words, and blocks — a picture, a table — drawn in place of// their text. A block's text stays in the storage, so every offset the core// answers still lands where it meant; its glyphs are hidden and its first// line is made as tall as the block, the rest of its lines nothing.#if canImport(UIKit)import UIKitfinal class WritingLayoutManager: NSLayoutManager, NSLayoutManagerDelegate {    /// Each block's height at the column's width, by its key; a block not    /// yet measured stands at `pending`.    var blockHeights: [String: CGFloat] = [:]    static let pending: CGFloat = 160    static let blockGap: CGFloat = 10    /// The accent a ticked box is filled with, and what draws an open box's ring.    var accent: UIColor = .clear    var onAccent: UIColor = .clear    var ring: UIColor = .clear    /// A ticked box.    var check: UIColor = .clear    /// A divider's hairline.    var mark: UIColor = .clear    override init() {        super.init()        delegate = self        allowsNonContiguousLayout = true    }    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }    // MARK: Blocks    func layoutManager(_ layoutManager: NSLayoutManager, shouldGenerateGlyphs glyphs: UnsafePointer<CGGlyph>,                                   properties props: UnsafePointer<NSLayoutManager.GlyphProperty>,                                   characterIndexes charIndexes: UnsafePointer<Int>, font aFont: UIFont,                                   forGlyphRange glyphRange: NSRange) -> Int {        do {            guard let storage = layoutManager.textStorage, glyphRange.length > 0 else { return 0 }            let first = charIndexes[0]            let last = charIndexes[glyphRange.length - 1]            var hidden = false            let span = NSRange(location: first, length: last - first + 1)            for key in [NSAttributedString.Key.writingBlock, .writingFolded] {                storage.enumerateAttribute(key, in: span) { value, _, stop in                    if value != nil { hidden = true; stop.pointee = true }                }            }            guard hidden else { return 0 }            var changed = [NSLayoutManager.GlyphProperty](repeating: [], count: glyphRange.length)            for i in 0..<glyphRange.length {                let at = charIndexes[i]                let gone = at < storage.length && (storage.attribute(.writingBlock, at: at, effectiveRange: nil) != nil                    || storage.attribute(.writingFolded, at: at, effectiveRange: nil) != nil)                changed[i] = gone ? .null : props[i]            }            changed.withUnsafeBufferPointer { buffer in                layoutManager.setGlyphs(glyphs, properties: buffer.baseAddress!, characterIndexes: charIndexes, font: aFont, forGlyphRange: glyphRange)            }            return glyphRange.length        }    }    func layoutManager(_ layoutManager: NSLayoutManager, shouldSetLineFragmentRect lineFragmentRect: UnsafeMutablePointer<CGRect>,                                   lineFragmentUsedRect: UnsafeMutablePointer<CGRect>, baselineOffset: UnsafeMutablePointer<CGFloat>,                                   in textContainer: NSTextContainer, forGlyphRange glyphRange: NSRange) -> Bool {        do {            guard let storage = layoutManager.textStorage, glyphRange.length > 0 else { return false }            let at = layoutManager.characterIndexForGlyph(at: glyphRange.location)            guard at < storage.length else { return false }            // A folded line takes no height.            if storage.attribute(.writingFolded, at: at, effectiveRange: nil) != nil {                lineFragmentRect.pointee.size.height = 0                lineFragmentUsedRect.pointee.size.height = 0                baselineOffset.pointee = 0                return true            }            var whole = NSRange()            guard let key = storage.attribute(.writingBlock, at: at, longestEffectiveRange: &whole,                                              in: NSRange(location: 0, length: storage.length)) as? String else { return false }            let height = at == whole.location ? (blockHeights[key] ?? Self.pending) + Self.blockGap * 2 : 0            lineFragmentRect.pointee.size.height = height            lineFragmentUsedRect.pointee.size.height = height            baselineOffset.pointee = 0            return true        }    }    /// Where each block of `range` stands in the container: its key, its    /// characters and the rect its view takes.    func blocks(in container: NSTextContainer) -> [(key: String, range: NSRange, rect: CGRect)] {        guard let storage = textStorage else { return [] }        var found: [(String, NSRange, CGRect)] = []        storage.enumerateAttribute(.writingBlock, in: NSRange(location: 0, length: storage.length)) { value, range, _ in            guard let key = value as? String else { return }            let glyph = glyphIndexForCharacter(at: range.location)            let line = lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)            let width = container.size.width - container.lineFragmentPadding * 2            found.append((key, range, CGRect(x: container.lineFragmentPadding, y: line.minY + Self.blockGap,                                             width: width, height: max(0, line.height - Self.blockGap * 2))))        }        return found    }    // MARK: Drawn behind the words    override func drawBackground(forGlyphRange glyphsToShow: NSRange, at origin: CGPoint) {        super.drawBackground(forGlyphRange: glyphsToShow, at: origin)        guard let storage = textStorage, let container = textContainers.first,              let context = UIGraphicsGetCurrentContext() else { return }        let chars = characterRange(forGlyphRange: glyphsToShow, actualGlyphRange: nil)        storage.enumerateAttributes(in: chars) { attributes, range, _ in            if let chip = attributes[.writingChip] as? UIColor {                each(range, in: container) { rect in                    let r = rect.offsetBy(dx: origin.x, dy: origin.y).insetBy(dx: -3, dy: 1)                    chip.setFill()                    UIBezierPath(roundedRect: r, cornerRadius: r.height / 2.4).fill()                }            }            if let glyph = attributes[.writingGlyph] as? String {                // A mark's run may be split by its other attributes (the kern                // that sets a list item's hang): it is drawn once, from the run                // its glyph starts in.                var whole = NSRange()                _ = storage.attribute(.writingGlyph, at: range.location, longestEffectiveRange: &whole, in: NSRange(location: 0, length: storage.length))                let drawnAlready = whole.location < range.location && whole.location >= chars.location                var first = !drawnAlready || glyph == "rule"                each(glyph == "rule" ? range : whole, in: container) { rect in                    let r = rect.offsetBy(dx: origin.x, dy: origin.y)                    switch glyph {                    case "box", "ticked":                        guard first else { return }                        let side = min(r.height - 4, max(15, (attributes[.font] as? UIFont)?.pointSize ?? 17))                        let box = CGRect(x: r.minX + 1, y: r.midY - side / 2, width: side, height: side)                        drawBox(box, done: glyph == "ticked", in: context)                    case "rule":                        mark.setFill()                        UIRectFill(CGRect(x: origin.x + container.lineFragmentPadding, y: r.midY,                                          width: container.size.width - container.lineFragmentPadding * 2, height: 1))                    default:                        guard first else { return }                        let side: CGFloat = 6                        accent.setFill()                        UIBezierPath(ovalIn: CGRect(x: r.minX + 3, y: r.midY - side / 2, width: side, height: side)).fill()                    }                    first = false                }            }            if let fold = attributes[.writingFold] as? String {                // The chevron in the margin beside a line that folds: down while open, right while folded.                var first = true                each(range, in: container) { rect in                    guard first, let paths = WritingMarks.paths(fold == "closed" ? "chevron_right" : "chevron_down") else { return }                    first = false                    let side: CGFloat = 14                    let r = rect.offsetBy(dx: origin.x, dy: origin.y)                    let lineHeight = min(r.height, ((attributes[.font] as? UIFont)?.lineHeight ?? 20) + 2)                    let box = CGRect(x: origin.x + container.lineFragmentPadding - side - 6, y: r.minY + (lineHeight - side) / 2, width: side, height: side)                    context.saveGState()                    context.translateBy(x: box.minX, y: box.minY)                    context.scaleBy(x: side / 24, y: side / 24)                    context.setLineWidth(CGFloat(WritingMarks.stroke) * 1.2)                    context.setLineCap(.round)                    context.setLineJoin(.round)                    context.setStrokeColor(ring.withAlphaComponent(fold == "closed" ? 0.95 : 0.55).cgColor)                    for part in paths {                        context.addPath(part.path)                        context.strokePath()                    }                    context.restoreGState()                }            }            if let bar = attributes[.writingQuote] as? UIColor {                each(range, in: container) { rect in                    bar.setFill()                    UIBezierPath(roundedRect: CGRect(x: origin.x + container.lineFragmentPadding, y: rect.minY + origin.y,                                                     width: 3, height: rect.height), cornerRadius: 1.5).fill()                }            }        }    }    /// The used rect of each line `range` lies on.    private func each(_ range: NSRange, in container: NSTextContainer, _ draw: (CGRect) -> Void) {        let glyphs = glyphRange(forCharacterRange: range, actualCharacterRange: nil)        var rects: [CGRect] = []        enumerateEnclosingRects(forGlyphRange: glyphs, withinSelectedGlyphRange: NSRange(location: NSNotFound, length: 0),                                in: container) { rect, _ in rects.append(rect) }        rects.forEach(draw)    }    private func drawBox(_ box: CGRect, done: Bool, in context: CGContext) {        let path = UIBezierPath(roundedRect: box, cornerRadius: box.width * 0.28)        if done {            check.setFill()            path.fill()            let tick = UIBezierPath()            tick.move(to: CGPoint(x: box.minX + box.width * 0.26, y: box.midY + box.height * 0.02))            tick.addLine(to: CGPoint(x: box.minX + box.width * 0.44, y: box.maxY - box.height * 0.28))            tick.addLine(to: CGPoint(x: box.maxX - box.width * 0.24, y: box.minY + box.height * 0.3))            tick.lineWidth = max(1.6, box.width * 0.12)            tick.lineCapStyle = .round            tick.lineJoinStyle = .round            onAccent.setStroke()            tick.stroke()        } else {            path.lineWidth = 1.6            ring.setStroke()            path.stroke()        }    }}#endif