Cotton code
243 lines · 13.4 KB · SwiftRaw
// The size a card sets its words at so none is ever cut off.//// SwiftUI draws a Text it has shrunk (`minimumScaleFactor`) clipped to the// Text's own box, and a handwriting face's last letter swings past that box —// "Ferrowmill" lost its last "l", "Pune" its "e" (architect, r3, 13 Oct 2026).// So a card never asks SwiftUI to shrink its words: it measures them here with// CoreText — wrapped to the lines it allows, then smaller step by step — until// every line's ink, swash included, stands inside the width, and sets them at// that size.import CoreTextimport Foundationpublic enum InkFit {    public static func figureSize(_ words: String, face: ThemeFace, preferred: CGFloat, width: CGFloat,                           scale: ThemeScale) -> CGFloat {        size(words, face: face, preferred: preferred, width: width, lines: 1, floor: 0, scale: scale)    }    /// The largest size from `preferred` down to `preferred * floor` at which    /// `words` in `face` wrap to at most `lines` lines inside `width` without    /// breaking a word, every line's ink inside it once centred; the floor    /// when even it does not. The floor, when the caller names none, and the    /// step down are the theme's (`ink_fit_*`); no floor is ever under the    /// theme's caption size, the smallest a card's words may be set.    static func size(        _ words: String, face: ThemeFace, preferred: CGFloat, width: CGFloat, lines: Int, floor: CGFloat? = nil,        scale: ThemeScale    ) -> CGFloat {        set(words, face: face, preferred: preferred, width: width, lines: lines, floor: floor, scale: scale).size    }    /// The size `words` are set at and the words themselves: whole when    /// they fit at a size no smaller than the floor, otherwise cut at a word    /// with an ellipsis at the floor — a card never sets its words under the    /// caption size to make them fit, and the whole value is on the record's    /// page (architect's frame rule, 16 Oct 2026). Every candidate is    /// measured with `padded` at each end, as the caller draws it.    public static func set(        _ words: String, face: ThemeFace, preferred: CGFloat, width: CGFloat, lines: Int, floor: CGFloat? = nil,        padded: String = "", scale: ThemeScale    ) -> (size: CGFloat, words: String) {        let caption = scale[.typeCaptionSize]        let start = max(preferred, caption)        let least = max(caption, preferred * (floor ?? InkFitKnobs.inkFitFloor))        let step = max(InkFitKnobs.inkFitStepMin, start * InkFitKnobs.inkFitStepFraction)        var size = start        while size > least {            if fits(padded + words + padded, face: face, size: size, width: width, lines: lines) { return (size, words) }            size -= step        }        if fits(padded + words + padded, face: face, size: least, width: width, lines: lines) { return (least, words) }        return (least, cut(words, face: face, size: least, width: width, lines: lines, padded: padded))    }    /// The size at which `words`, on ONE line, stand inside `width`: `size`    /// when they already do, else smaller in proportion to their ink. For a    /// word longer than its line even at the caption size (a fan tile's    /// "Membership"): a label is never broken inside a word, so it sets    /// smaller on one line rather than wrap mid-word.    public static func oneLine(_ words: String, face: ThemeFace, size: CGFloat, width: CGFloat) -> CGFloat {        let line = CTLineCreateWithAttributedString(            NSAttributedString(string: words, attributes: [.init(kCTFontAttributeName as String): font(face, size)]))        let bounds = CTLineGetImageBounds(line, nil)        let ink = max(bounds.maxX, CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil))) - min(0, bounds.minX)        guard ink > width, ink > 0 else { return size }        return size * width / ink * InkFitKnobs.inkFitOneLineSlack    }    /// `words` whole when they stand inside `width` in at most `lines` lines    /// at `size`, otherwise cut at a word with an ellipsis.    public static func fitting(_ words: String, face: ThemeFace, size: CGFloat, width: CGFloat, lines: Int) -> String {        fits(words, face: face, size: size, width: width, lines: lines)            ? words : cut(words, face: face, size: size, width: width, lines: lines)    }    /// `words` cut after the most whole words that, with an ellipsis, stand    /// inside `width` in at most `lines` lines at `size`; the first word and    /// the ellipsis when not even that does.    static func cut(_ words: String, face: ThemeFace, size: CGFloat, width: CGFloat, lines: Int,                    padded: String = "") -> String {        let parts = Self.words(of: words)        guard parts.count > 1 else { return words }        for count in stride(from: parts.count - 1, through: 1, by: -1) {            let shorter = parts.prefix(count).joined().trimmingCharacters(in: .whitespacesAndNewlines) + InkFitKnobs.inkFitEllipsis            if fits(padded + shorter + padded, face: face, size: size, width: width, lines: lines) { return shorter }        }        return parts[0].trimmingCharacters(in: .whitespacesAndNewlines) + InkFitKnobs.inkFitEllipsis    }    /// Where `words` may be cut, each piece keeping what follows it: at its    /// spaces; one word with none — a web address — at its own parts, after    /// each "/", ".", "?", "&", "=", "#", "-" or "_"; a word with neither is    /// whole, the one case the line cannot cut.    static func words(of words: String) -> [String] {        func pieces(_ text: String, after breaks: (Character) -> Bool) -> [String] {            var found: [String] = []            var piece = ""            for character in text {                if !piece.isEmpty, breaks(character) == false, let last = piece.last, breaks(last) {                    found.append(piece)                    piece = ""                }                piece.append(character)            }            if !piece.isEmpty { found.append(piece) }            return found        }        let spaced = pieces(words.trimmingCharacters(in: .whitespacesAndNewlines), after: \.isWhitespace)        if spaced.count > 1 { return spaced }        return pieces(words, after: { "/.?&=#-_".contains($0) })    }    /// Whether `words` at `size` stand inside `width` in at most `lines` lines.    public static func fits(_ words: String, face: ThemeFace, size: CGFloat, width: CGFloat, lines: Int) -> Bool {        guard let laid = laid(words, face: face, size: size, width: width), laid.count <= lines else { return false }        return laid.allSatisfy { line in            let ink = ink(of: line, centredIn: width)            return ink.lowerBound >= 0 && ink.upperBound <= width        }    }    /// `words` as a Text should be given them at `size` in `width`, for two    /// lines. A Text's own line breaking may move a word down to spare the    /// last line a lone word, and does so even when that cuts it: "Add a /    /// file" was set "Add / a fi…" at the largest text size (books build 3    /// walk, 5 Nov 2026). Only then is the break given, where CoreText laid    /// it; otherwise the words go as they are ("On this / phone").    public static func broken(_ words: String, face: ThemeFace, size: CGFloat, width: CGFloat) -> String {        guard let laid = laid(words, face: face, size: size, width: width), laid.count == 2 else { return words }        let text = words as NSString        let lines = laid.map { line in            let range = CTLineGetStringRange(line)            return text.substring(with: NSRange(location: range.location, length: range.length))                .trimmingCharacters(in: .whitespaces)        }        guard !lines[1].contains(" "), let cut = lines[0].range(of: " ", options: .backwards) else { return words }        let movedDown = lines[0][cut.upperBound...] + " " + lines[1]        return fits(movedDown, face: face, size: size, width: width, lines: 1) ? words : lines.joined(separator: "\n")    }    /// The size `words` are set at in at most `lines` lines inside `width`,    /// never broken inside a word: the first of `sizes` (largest first) at    /// which they stand whole; past the last, smaller still, until their    /// longest word stands on a line of its own (a tile's "Downloads"). Lines    /// the words still overrun are the caller's to end at a word.    public static func wholeWords(_ words: String, face: ThemeFace, sizes: [CGFloat], width: CGFloat, lines: Int) -> CGFloat {        for size in sizes where fits(words, face: face, size: size, width: width, lines: lines) { return size }        guard let least = sizes.last else { return 0 }        guard laid(words, face: face, size: least, width: width) == nil else { return least }        return Self.words(of: words).map { oneLine($0.trimmingCharacters(in: .whitespacesAndNewlines), face: face, size: least, width: width) }            .min() ?? least    }    /// `words` laid in lines inside `width` at `size`, broken only between    /// words — at its spaces, and a word longer than the line (a file's name,    /// "mary-shelley_frankenstein.epub") at its own parts, after a "/", ".",    /// "?", "&", "=", "#", "-" or "_" — never inside a word: nil when one    /// part alone is wider than the line (362 walk: Downloads' card read    /// "frankenstei / n.epub"). Each line as the caller should give it, the    /// lines joined with "\n", so a Text never breaks a word of its own accord.    public static func wholeLines(_ words: String, face: ThemeFace, size: CGFloat, width: CGFloat) -> [String]? {        let measuring = font(face, size)        func wide(_ text: String) -> CGFloat {            let line = CTLineCreateWithAttributedString(                NSAttributedString(string: text, attributes: [.init(kCTFontAttributeName as String): measuring]))            let bounds = CTLineGetImageBounds(line, nil)            let typographic = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil) - CTLineGetTrailingWhitespaceWidth(line))            return max(typographic, bounds.maxX) - min(0, bounds.minX)        }        // Each piece keeps the space or mark after it.        var pieces: [String] = []        for token in Self.words(of: words) {            if wide(token.trimmingCharacters(in: .whitespaces)) <= width { pieces.append(token); continue }            var part = ""            for character in token {                part.append(character)                if "/.?&=#-_".contains(character) { pieces.append(part); part = "" }            }            if !part.isEmpty { pieces.append(part) }        }        var lines: [String] = []        var line = ""        for piece in pieces {            guard wide(piece.trimmingCharacters(in: .whitespaces)) <= width else { return nil }            let longer = line + piece            if line.isEmpty || wide(longer.trimmingCharacters(in: .whitespaces)) <= width {                line = longer            } else {                lines.append(line.trimmingCharacters(in: .whitespaces))                line = piece            }        }        if !line.isEmpty { lines.append(line.trimmingCharacters(in: .whitespaces)) }        return lines    }    /// The lines `words` wrap to in `width`, or nil when a word alone is    /// wider than it (CoreText would break inside the word).    public static func laid(_ words: String, face: ThemeFace, size: CGFloat, width: CGFloat) -> [CTLine]? {        let text = words as NSString        let typesetter = CTTypesetterCreateWithAttributedString(            NSAttributedString(string: words, attributes: [.init(kCTFontAttributeName as String): font(face, size)]))        var lines: [CTLine] = []        var start = 0        while start < text.length {            let count = CTTypesetterSuggestLineBreak(typesetter, start, Double(width))            guard count > 0 else { return nil }            let end = start + count            let breaksAWord = end < text.length                && !CharacterSet.whitespacesAndNewlines.contains(UnicodeScalar(text.character(at: end - 1)) ?? " ")                && !CharacterSet.whitespacesAndNewlines.contains(UnicodeScalar(text.character(at: end)) ?? " ")            if breaksAWord { return nil }            lines.append(CTTypesetterCreateLine(typesetter, CFRange(location: start, length: count)))            start = end        }        return lines    }    /// Where a line's ink falls when it is centred in `width` the way a    /// centred Text lays it: by its width less any trailing spaces.    static func ink(of line: CTLine, centredIn width: CGFloat) -> ClosedRange<CGFloat> {        let typographic = CGFloat(CTLineGetTypographicBounds(line, nil, nil, nil) - CTLineGetTrailingWhitespaceWidth(line))        let bounds = CTLineGetImageBounds(line, nil)        let origin = (width - typographic) * 0.5        return (origin + bounds.minX)...(origin + bounds.maxX)    }    static func font(_ face: ThemeFace, _ size: CGFloat) -> CTFont { face.measuring(size) }}/// The sizes, counts and timings InkFit draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum InkFitKnobs {    static let inkFitFloor: CGFloat = 0.3    static let inkFitStepFraction: CGFloat = 0.02    static let inkFitStepMin: CGFloat = 0.25    static let inkFitEllipsis = "\u{2026}"    /// What a one-line fit keeps in hand, so rounding never puts the last    /// letter's ink on the edge.    static let inkFitOneLineSlack: CGFloat = 0.96}