package dev.darkpyonix.composerust.foundation
import androidx.compose.foundation.text.InlineTextContent
import androidx.compose.foundation.text.appendInlineContent
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.MultiParagraph
import androidx.compose.ui.text.MultiParagraphIntrinsics
import androidx.compose.ui.text.Placeholder
import androidx.compose.ui.text.PlaceholderVerticalAlign
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.LineHeightStyle
import androidx.compose.ui.text.style.TextAlign as ComposeTextAlign
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow as ComposeOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.isUnspecified
import androidx.compose.ui.unit.sp
import dev.darkpyonix.composerust.design.ResolvedTheme
import kotlin.math.ceil
import dev.darkpyonix.composerust.design.platformDefaultChain
import dev.darkpyonix.composerust.design.platformSansSerifFamily
import dev.darkpyonix.composerust.design.platformUiFamily
import dev.darkpyonix.composerust.protocol.ColorRole
import dev.darkpyonix.composerust.protocol.FontRef
import dev.darkpyonix.composerust.protocol.FontRefRecords
import dev.darkpyonix.composerust.protocol.GenericFamily
import dev.darkpyonix.composerust.protocol.OverflowWrap
import dev.darkpyonix.composerust.protocol.Paint
import dev.darkpyonix.composerust.protocol.PropertyKind
import dev.darkpyonix.composerust.protocol.PropertyValue
import dev.darkpyonix.composerust.protocol.SpanFontFeatureRecords
import dev.darkpyonix.composerust.protocol.SpanFontRecords
import dev.darkpyonix.composerust.protocol.TYPE_ROLE_NONE
import dev.darkpyonix.composerust.protocol.TextAlign
import dev.darkpyonix.composerust.protocol.TypeRole
import dev.darkpyonix.composerust.protocol.WordBreak
import dev.darkpyonix.composerust.ui.floatProp
import dev.darkpyonix.composerust.ui.letterSpacingProp
import dev.darkpyonix.composerust.ui.lineHeightProp
import dev.darkpyonix.composerust.ui.intProp
import dev.darkpyonix.composerust.ui.maxLines
import dev.darkpyonix.composerust.ui.node.Asset
import dev.darkpyonix.composerust.ui.node.AssetCache
import dev.darkpyonix.composerust.ui.node.FontChain
import dev.darkpyonix.composerust.ui.node.FontTracking
import dev.darkpyonix.composerust.ui.node.fontTracking
import dev.darkpyonix.composerust.ui.node.Node
import dev.darkpyonix.composerust.ui.node.systemFontFamily
import dev.darkpyonix.composerust.ui.overflow
import dev.darkpyonix.composerust.ui.paintProp
import dev.darkpyonix.composerust.ui.role
import dev.darkpyonix.composerust.ui.typeRole
/**
* Everything that decides how a piece of text is set, wherever it came from.
*
* A `Text` node being drawn and a measure request being answered both become one of
* these, and [resolveText] turns it into what Compose lays out. Measuring and drawing go
* through that one function on purpose: a measured size is only worth having if it is the
* size the same text turns out to be on screen, and two functions that each meant to do
* the same thing would sooner or later disagree about a font, a scale or a break.
*/
internal class TextInput(
val text: String,
/** The runs, or empty for none. */
val runs: List<TextRun>,
/** The fonts runs name for themselves, by run index. */
val runFonts: Map<Int, List<FontRef>>,
/**
* The OpenType features runs name for themselves, as Compose's `fontFeatureSettings`
* strings by run index. Taken by a run with or without a role, after the text's own.
*/
val runFontFeatures: Map<Int, String> = emptyMap(),
/**
* True for text with no rung of the ladder at all, which takes its size, weight,
* line height, letter spacing and font from its own values and nothing from the
* design system.
*/
val noRole: Boolean,
/** The rung, where the text named one. */
val role: TypeRole?,
/** The rung where the text named none and is not [noRole]. */
val defaultRole: TypeRole = TypeRole.Body,
val fontSize: Float? = null,
val fontWeight: Int? = null,
val italic: Boolean = false,
val letterSpacing: Float? = null,
val lineHeight: Float? = null,
val maxLines: Int = Int.MAX_VALUE,
val softWrap: Boolean = true,
val tabSize: Int = DEFAULT_TAB_SIZE,
val wordBreak: WordBreak? = null,
val overflowWrap: OverflowWrap? = null,
/** Sizes are CSS pixels, which the system's font scale does not enlarge. */
val absoluteSize: Boolean = false,
/** The fonts to try, for [noRole] text. Ignored, and reported, where there is a role. */
val fonts: List<FontRef> = emptyList(),
/** Drawing only: neither changes a size. */
val color: Paint? = null,
val textAlign: TextAlign? = null,
val overflow: ComposeOverflow = ComposeOverflow.Clip,
/**
* The node's OpenType features as Compose's `fontFeatureSettings` string, or null for
* none. Taken with or without a role: a feature picks a form of the font, not a font.
*/
val fontFeatures: String? = null,
) {
companion object {
const val DEFAULT_TAB_SIZE = 8
/** What text with no role is set at when it says nothing, as CSS's `medium`. */
const val NO_ROLE_FONT_SIZE = 14f
const val NO_ROLE_FONT_WEIGHT = 400
}
}
/** What Compose is handed to lay the text out, drawn or measured. */
internal class ResolvedText(
val text: AnnotatedString,
val style: TextStyle,
val softWrap: Boolean,
val maxLines: Int,
val overflow: ComposeOverflow,
/** Where each tab sits and how far it advances. Empty where there are no tabs. */
val placeholders: List<AnnotatedString.Range<Placeholder>>,
/** The same placeholders, in the form `BasicText` takes them. */
val inlineContent: Map<String, InlineTextContent>,
/**
* The text broken anywhere, for working out the narrowest it can be when a word too
* long for its line may be broken inside. Null where that is the text itself.
*/
val minContentText: AnnotatedString?,
val minContentPlaceholders: List<AnnotatedString.Range<Placeholder>>,
/** What was wrong with the runs, which were left out, or null where nothing was. */
val runsProblem: String?,
/** What was wrong with the fonts, one sentence each, for the caller to report. */
val problems: List<String>,
/**
* What was wrong with the features the runs name, none of which were used, or null
* where nothing was. The runs themselves are still drawn.
*/
val runFeaturesProblem: String? = null,
/** Which fonts the text named and is not set in, or null where it is set in all it named. */
val ignoredFonts: String? = null,
)
/**
* Turns a [TextInput] into what Compose lays out.
*
* [link] makes the annotation a run that is a link carries, for text that is drawn and
* can be pressed. Measuring passes null: a link changes nothing about a size.
*/
internal fun resolveText(
input: TextInput,
theme: ResolvedTheme,
assets: AssetCache,
density: Density,
fontFamilyResolver: FontFamily.Resolver,
link: ((TextRun) -> LinkAnnotation.Clickable)? = null,
/**
* Leaves out what only paints: the colour. Nothing about a size depends on it, and
* resolving a colour through the design system is the dearest thing done here.
*/
forMeasure: Boolean = false,
intrinsicWordBreak: WordBreak? = null,
): ResolvedText {
val problems = mutableListOf<String>()
// Sizes are sp. Text in CSS pixels is not given smaller sp to undo the font scale:
// it is set in a density whose font scale is one (see [textDensity]), which is the only
// way that stays right where the font scale is not linear.
fun sized(value: Float): TextUnit = value.sp
// The families this text's letters are drawn from. For text with no role, its own font
// list; for text with a role, the theme's, where the theme set the role in a stack.
// Text with no role that names no font is set in the application's own font where the
// theme gave one, the way a page with no font-family is set in the browser's default.
val chain = if (input.noRole) {
val appFont = theme.fonts[TypeRole.Body]?.takeIf { input.fonts.isEmpty() }
if (appFont != null) {
theme.chainFor(appFont) ?: FontChain(listOf(FontChain.Member(appFont, null)))
} else {
resolveFontChain(input.fonts, assets, problems)
}
} else {
theme.chainFor(theme.family(input.role ?: input.defaultRole))
}
val tracking = if (input.noRole) noRoleTracking(input, chain) else null
val base = if (input.noRole) {
TextStyle(
fontSize = sized(input.fontSize ?: TextInput.NO_ROLE_FONT_SIZE),
fontWeight = FontWeight(input.fontWeight ?: TextInput.NO_ROLE_FONT_WEIGHT),
lineHeight = input.lineHeight?.let(::sized) ?: TextUnit.Unspecified,
letterSpacing = tracking?.let { sized(it.spacing(input.fontSize ?: TextInput.NO_ROLE_FONT_SIZE)) }
?: input.letterSpacing?.let(::sized)
?: TextUnit.Unspecified,
fontFamily = chain?.primary,
// As CSS sets a line box: every line is exactly its line height, the first and
// the last included, with the room the glyphs leave split evenly above and
// below them. Compose's default trims the first line's top and the last line's
// bottom back to the font's own, so a single line came out at the font's
// height whatever line height the page asked for.
lineHeightStyle = LineHeightStyle(LineHeightStyle.Alignment.Center, LineHeightStyle.Trim.None),
)
} else {
val role = input.role ?: input.defaultRole
val token = theme.type(role)
TextStyle(
fontSize = sized(input.fontSize ?: token.size),
fontWeight = input.fontWeight?.let { FontWeight(it) } ?: FontWeight(token.weight),
lineHeight = sized(input.lineHeight ?: token.lineHeight),
letterSpacing = sized(input.letterSpacing ?: token.letterSpacing),
// A font named for text that has a role is ignored: the theme decides what a
// rung is written in, and one node cannot say otherwise.
fontFamily = theme.family(role),
)
}
val style = base.merge(
TextStyle(
color = when {
forMeasure -> androidx.compose.ui.graphics.Color.Unspecified
else -> input.color?.let(theme::color) ?: theme.color(ColorRole.OnSurface)
},
fontStyle = if (input.italic) FontStyle.Italic else null,
textAlign = when (input.textAlign) {
TextAlign.Start -> ComposeTextAlign.Start
TextAlign.Center -> ComposeTextAlign.Center
TextAlign.End -> ComposeTextAlign.End
TextAlign.Justify -> ComposeTextAlign.Justify
TextAlign.Left -> ComposeTextAlign.Left
TextAlign.Right -> ComposeTextAlign.Right
null -> ComposeTextAlign.Unspecified
},
// After what the style already asks for, so a tag both name takes the node's
// value. Null where the node has none, which leaves the style's own.
fontFeatureSettings = appendFontFeatures(base.fontFeatureSettings, input.fontFeatures),
),
)
val badRuns = if (input.runs.isEmpty()) null else runsProblem(input.runs, input.text.encodeToByteArray().size)
val runs = if (badRuns == null) input.runs else emptyList()
// A table that names a run the text does not have was counted against some other list
// of runs, so none of it is trusted. Runs that were left out have said so already.
val badRunFeatures = if (badRuns == null) runFeaturesProblem(input.runFontFeatures, runs.size) else null
val runFeatures = if (badRuns == null && badRunFeatures == null) input.runFontFeatures else emptyMap()
val mode = when (intrinsicWordBreak ?: input.wordBreak) {
WordBreak.KeepAll -> BreakMode.KeepAll
WordBreak.BreakAll -> BreakMode.BreakAll
WordBreak.Normal, null -> BreakMode.Normal
}
val text = annotate(input, runs, runFeatures, mode, chain, tracking, theme, assets, density, ::sized, link, problems)
val (placeholders, inline) = tabStops(text, style, input.tabSize, density, fontFamilyResolver)
// Breaking anywhere only matters to the narrowest width: laid out at any width, a word
// too long for its line is broken inside it already. So the text broken anywhere is
// made only for that question, and only where the answer differs.
val anywhere = input.overflowWrap == OverflowWrap.Anywhere && mode != BreakMode.BreakAll
val minContent = if (anywhere) {
annotate(input, runs, runFeatures, BreakMode.BreakAll, chain, tracking, theme, assets, density, ::sized, null, mutableListOf())
} else {
null
}
val minContentPlaceholders = minContent
?.let { tabStops(it, style, input.tabSize, density, fontFamilyResolver).first }
?: emptyList()
return ResolvedText(
text = text,
style = style,
softWrap = input.softWrap,
maxLines = input.maxLines,
overflow = input.overflow,
placeholders = placeholders,
inlineContent = inline,
minContentText = minContent,
minContentPlaceholders = minContentPlaceholders,
runsProblem = badRuns,
problems = problems,
ignoredFonts = ignoredFontsProblem(input),
runFeaturesProblem = badRunFeatures,
)
}
/**
* The density a text is set in: the one it is drawn or measured under, with the font scale
* taken out for text in CSS pixels, which the system's text size does not enlarge.
*/
internal fun textDensity(input: TextInput, density: Density): Density =
if (input.absoluteSize && density.fontScale != 1f) Density(density.density, 1f) else density
/**
* How text with no role is tracked: its own letter spacing, with the tracking of the face
* it is set in added on top. Null where that face has no tracking, which leaves the letter
* spacing exactly what the text asked for.
*
* Apple's text system tracks its faces by their `trak` table at every size, and a browser
* on a Mac sets text the same way, with CSS `letter-spacing` added to the tracked advances
* rather than in place of them. So the tracking is added whatever the text's own letter
* spacing is, including an explicit zero, which is what `letter-spacing: normal` arrives as.
*
* Text with a role is not tracked here: its letter spacing is the design system's token
* for the role, and the Cupertino design system already writes SF's tracking into those
* tokens by hand (-0.4sp at its 34sp title, for example), so adding the table as well
* would track that text twice.
*
* The size the table is read at is the text's own size, before the font scale or any zoom,
* which is the CSS pixel size a browser reads it at with no zoom. Measuring and drawing a
* text see different densities, so reading the table at a scaled size would set the same
* text at two widths.
*/
internal class TextTracking(
/** The face the text is set in. */
val face: FontTracking,
/** The text's own letter spacing, in sp. */
val letterSpacing: Float,
) {
/** The letter spacing, in sp, of letters in [face] at [size] sp. */
fun spacing(size: Float): Float = letterSpacing + face.table.em(size) * size
}
/**
* [style]'s letter spacing with the tracking of [family]'s face added, for a field with no
* role, or null where the face has no tracking or the style is not sized in sp.
*/
internal fun trackedLetterSpacing(style: TextStyle, family: FontFamily?): TextUnit? {
val size = style.fontSize.takeIf { it.isSp }?.value ?: return null
val spacing = style.letterSpacing
if (!spacing.isSp && !spacing.isUnspecified) return null
val italic = style.fontStyle == FontStyle.Italic
val face = fontTracking(family, style.fontWeight?.weight ?: TextInput.NO_ROLE_FONT_WEIGHT, italic) ?: return null
val base = if (spacing.isSp) spacing.value else 0f
return (base + face.table.em(size) * size).sp
}
private fun noRoleTracking(input: TextInput, chain: FontChain?): TextTracking? {
val face = fontTracking(chain?.primary, input.fontWeight ?: TextInput.NO_ROLE_FONT_WEIGHT, input.italic) ?: return null
return TextTracking(face, input.letterSpacing ?: 0f)
}
/**
* The text's family, as a CSS font list is read: the first candidate that resolves.
*/
internal fun resolveFontFamily(
refs: List<FontRef>,
assets: AssetCache,
problems: MutableList<String>,
): FontFamily = resolveFontChain(refs, assets, problems).primary
/**
* The candidates that resolve, in order, as a CSS font list is read: the text is set in
* the first, and a letter it has no glyph for comes from the next one that has it.
*
* A registered font asset that is not there is reported and passed over, and a registered
* stack contributes all of its families. An installed family is asked for by name, and a
* name the machine does not have is passed over without a report, because a list that
* names fonts it may not find is what a font list is for. An installed or a generic family
* takes every letter left, so the list stops there. Nothing resolving is a sans serif.
* A letter none of them has is looked for in the fallback faces the renderer carries, where
* it carries any.
*/
internal fun resolveFontChain(
refs: List<FontRef>,
assets: AssetCache,
problems: MutableList<String>,
): FontChain {
val members = ArrayList<FontChain.Member>()
for (ref in refs) {
when (ref) {
is FontRef.Asset -> {
val font = assets.asset(ref.assetId) as? Asset.Font
if (font == null) {
problems += "font asset ${ref.assetId} is not a registered font; the next font in the list is used"
continue
}
val chain = font.chain
if (chain != null) {
members += chain.members
} else {
members += FontChain.Member(font.family, font.face?.hasGlyph)
if (font.face == null) break
}
}
is FontRef.System -> {
val family = cssUiFontFamily(ref.name) ?: systemFontFamily(ref.name) ?: continue
members += platformMember(family)
break
}
is FontRef.Generic -> {
members += platformMember(genericFontFamily(ref.family))
break
}
}
}
if (members.isEmpty()) members += platformMember(platformSansSerifFamily)
return FontChain(members)
}
/**
* The chain member for an installed or a generic [family]: one whose letters are not known,
* which takes every letter that reaches it.
*
* The exception is the default family where the renderer carries it itself. Its letters
* are known, so the member is the one of [platformDefaultChain], and a letter it lacks goes
* on to the fallback faces the renderer carries.
*/
private fun platformMember(family: FontFamily): FontChain.Member =
platformDefaultChain?.members?.first()?.takeIf { it.family === family } ?: FontChain.Member(family, null)
/**
* CSS's `ui-serif`, `ui-sans-serif`, `ui-monospace` and `ui-rounded`: the faces this
* platform writes its own interface in, in each of those styles. Null for any other name,
* and for a `ui-` name this platform has no face for, which a font list passes over as a
* browser does.
*
* They arrive as installed family names, because that is what a CSS list leaves them as,
* but no machine has a family called `ui-monospace`. Apple's platforms have one under a
* private name (SF Mono, New York, SF Rounded), and asking for that name by the same route
* as any installed family answers only where it really exists, so elsewhere the name falls
* to the platform's own generic face of the same kind. There is no rounded interface face
* outside Apple's platforms, so `ui-rounded` is not found there and the list moves on.
*/
internal fun cssUiFontFamily(name: String): FontFamily? = when (name.lowercase()) {
"ui-sans-serif" -> platformUiFamily
"ui-serif" -> systemFontFamily(".AppleSystemUIFontSerif") ?: FontFamily.Serif
"ui-monospace" -> systemFontFamily(".AppleSystemUIFontMonospaced") ?: FontFamily.Monospace
"ui-rounded" -> systemFontFamily(".AppleSystemUIFontRounded")
else -> null
}
/**
* What is ignored about the fonts [input] names, or null where nothing is.
*
* Text with a type role is set in the theme's font for that role, and so is a run with a
* role of its own. A font list sent for either is thrown away, which a Host has no way to
* see on screen beyond letters in the wrong face, so it is said. Text that sends no type
* role at all has the role [TextInput.defaultRole], not no role: naming fonts is not
* enough, the text has to say it has no role as well.
*/
internal fun ignoredFontsProblem(input: TextInput): String? {
if (input.noRole) {
val runs = input.runs.withIndex()
.filter { (index, run) -> run.role != null && input.runFonts.containsKey(index) }
.map { it.index }
if (runs.isEmpty()) return null
return "run ${runs.joinToString()} names fonts and a type role; a run with a role is set in the theme's font for it, so its fonts are ignored"
}
val nodeFonts = input.fonts.isNotEmpty()
val runFonts = input.runFonts.isNotEmpty()
if (!nodeFonts && !runFonts) return null
val named = when {
nodeFonts && runFonts -> "a font list and run fonts"
nodeFonts -> "a font list"
else -> "run fonts"
}
val role = input.role?.let { "the type role $it" }
?: "no type role, which is the role ${input.defaultRole}"
return "$named for text with $role: ignored, because text with a role is set in the theme's font for it. " +
"Send the type role None for text set in its own fonts"
}
/** Which installed family each generic name is, which is the platform's answer. */
internal fun genericFontFamily(family: GenericFamily): FontFamily = when (family) {
GenericFamily.SystemUi -> platformUiFamily
GenericFamily.SansSerif -> platformSansSerifFamily
GenericFamily.Serif -> FontFamily.Serif
GenericFamily.Monospace -> FontFamily.Monospace
}
/** Where lines may break, beyond where the language itself allows. */
internal enum class BreakMode { Normal, KeepAll, BreakAll }
/** Keeps two letters on one line: CSS `keep-all` between letters of a CJK word. */
private const val WORD_JOINER = ''
/** Lets a line break between two letters: CSS `break-all`. */
private const val ZERO_WIDTH_SPACE = ''
/**
* The text with invisible characters put where a break is forbidden or allowed, and where
* each of the original characters ended up. Both characters are default ignorable, so
* they take no width and are never drawn: they only change where a line can end.
*
* The platform's own line breaking is what decides everything else. It breaks Korean
* between syllables, which is CSS `normal`, so `keep-all` is the one that has to be asked
* for, and it differs from platform to platform in ways that this does not.
*/
internal class BrokenText(val text: String, private val map: IntArray?) {
/** Where character [index] of the original string is in [text]. */
fun position(index: Int): Int = map?.get(index) ?: index
/**
* The offset in the original string that offset [index] of [text] stands for. The two
* offsets on either side of an inserted character stand for the same one: the character
* takes no width, so both are the same place on screen.
*/
fun original(index: Int): Int {
val map = map ?: return index
// The first original offset at or after [index]; the map only grows.
var low = 0
var high = map.size - 1
while (low < high) {
val middle = (low + high) ushr 1
if (map[middle] < index) low = middle + 1 else high = middle
}
return low
}
}
internal fun breakText(text: String, mode: BreakMode): BrokenText {
if (mode == BreakMode.Normal || text.length < 2) return BrokenText(text, null)
val out = StringBuilder(text.length + text.length / 2)
val map = IntArray(text.length + 1)
for (index in text.indices) {
map[index] = out.length
val current = text[index]
out.append(current)
val next = text.getOrNull(index + 1) ?: continue
val insert = when (mode) {
BreakMode.KeepAll -> letter(current) && letter(next) && (cjk(current) || cjk(next))
BreakMode.BreakAll -> letter(current) && letter(next) && !joinedJamo(current, next)
BreakMode.Normal -> false
}
if (insert) out.append(if (mode == BreakMode.KeepAll) WORD_JOINER else ZERO_WIDTH_SPACE)
}
map[text.length] = out.length
return BrokenText(out.toString(), map)
}
/** A letter or digit, whole: half of a surrogate pair is never split from the other. */
private fun letter(char: Char): Boolean = !char.isSurrogate() && char.isLetterOrDigit()
/** Hangul, the CJK ideographs, and the two kana. */
private fun cjk(char: Char): Boolean {
val code = char.code
return code in 0xAC00..0xD7A3 || code in 0x1100..0x11FF || code in 0x3130..0x318F ||
code in 0x4E00..0x9FFF || code in 0x3400..0x4DBF || code in 0x3040..0x30FF
}
/** Conjoining jamo that make one syllable together, which a break would tear apart. */
private fun joinedJamo(first: Char, second: Char): Boolean =
first.code in 0x1100..0x11FF && second.code in 0x1100..0x11FF
/** The text and its runs, with the breaks [mode] asks for, as one annotated string. */
private fun annotate(
input: TextInput,
runs: List<TextRun>,
/** The features of the runs that name any, by index into [runs]. */
runFeatures: Map<Int, String>,
mode: BreakMode,
chain: FontChain?,
tracking: TextTracking?,
theme: ResolvedTheme,
assets: AssetCache,
density: Density,
sized: (Float) -> TextUnit,
link: ((TextRun) -> LinkAnnotation.Clickable)?,
problems: MutableList<String>,
): AnnotatedString {
val broken = breakText(input.text, mode)
val hasTabs = broken.text.indexOf('\t') >= 0
// Letters the text's first family lacks, set in the family of its chain that has them.
// Added before the runs, so a run that names its own font sets its letters in that.
val fallback = chain?.spans(broken.text).orEmpty()
// Letters the tracked face has no glyph for come from a face its tracking is not for.
val untracked = tracking?.face?.untracked(broken.text)
val hasUntracked = untracked != null && untracked.isNotEmpty()
if (runs.isEmpty() && !hasTabs && fallback.isEmpty() && !hasUntracked) return AnnotatedString(broken.text)
val utf8 = if (runs.isEmpty()) null else input.text.encodeToByteArray()
return buildAnnotatedString {
// Tabs become placeholders, each standing in place of its own character, so the
// string keeps its length and every run still covers what it covered.
var tab = 0
for (char in broken.text) {
if (char == '\t') {
appendInlineContent(tabId(tab++), "\t")
} else {
append(char)
}
}
for (span in fallback) addStyle(span.item, span.start, span.end)
if (utf8 != null) runs.forEachIndexed { index, run ->
val from = broken.position(utf8.decodeToString(0, run.start).length)
val to = broken.position(utf8.decodeToString(0, run.start + run.length).length)
// A run of text with no role may name its own font. Where the text has a
// role, or the run does, the font is the theme's.
val runChain = input.runFonts[index]
?.takeIf { input.noRole && run.role == null }
?.let { resolveFontChain(it, assets, problems) }
val spacing = if (input.noRole) runSpacing(input, run, runChain, tracking, theme) else null
// A span's features replace the paragraph's for its letters, they are not added
// to them. So a run that names features is given the text's as well, with its
// own after them, where a tag both name takes the run's value. A run that names
// none sets nothing and is drawn with the text's.
val features = runFeatures[index]?.let { appendFontFeatures(input.fontFeatures, it) }
val style = spanStyle(
run,
runChain?.primary,
theme,
sized,
spacing?.let(sized) ?: TextUnit.Unspecified,
features,
)
addStyle(style, from, to)
runChain?.spans(broken.text.substring(from, to))?.forEach { span ->
addStyle(span.item, from + span.start, from + span.end)
}
if (link != null && run.handlerId != 0L) addLink(link(run), from, to)
}
// After the runs, so a letter drawn from a fallback face inside a run is untracked too.
if (hasUntracked) {
val spacing = SpanStyle(letterSpacing = sized(tracking!!.letterSpacing))
for (at in untracked!!.indices step 2) addStyle(spacing, untracked[at], untracked[at + 1])
}
}
}
/**
* The letter spacing, in sp, of a run of text with no role whose tracking differs from the
* text's, or null where the run is tracked as the text is.
*
* A run set in fonts of its own is tracked by its own first face, or not at all where that
* face has no table. A run with a role is set at the role's size, and the table gives a
* different value at a different size.
*/
private fun runSpacing(
input: TextInput,
run: TextRun,
runChain: FontChain?,
tracking: TextTracking?,
theme: ResolvedTheme,
): Float? {
val size = run.role?.let { theme.type(it).size } ?: input.fontSize ?: TextInput.NO_ROLE_FONT_SIZE
if (runChain != null) {
val weight = if (run.bold) FontWeight.Bold.weight else input.fontWeight ?: TextInput.NO_ROLE_FONT_WEIGHT
val face = fontTracking(runChain.primary, weight, input.italic || run.italic)
if (face == null && tracking == null) return null
val letterSpacing = input.letterSpacing ?: 0f
return letterSpacing + (face?.table?.em(size)?.times(size) ?: 0f)
}
if (tracking == null || run.role == null) return null
return tracking.spacing(size)
}
/**
* The Compose style of one span record. Measuring and drawing both build their spans here,
* so what a span changes about its letters is decided in one place and the two cannot
* drift apart.
*/
private fun spanStyle(
run: TextRun,
family: FontFamily?,
theme: ResolvedTheme,
sized: (Float) -> TextUnit,
letterSpacing: TextUnit = TextUnit.Unspecified,
fontFeatures: String? = null,
): SpanStyle {
return SpanStyle(
color = run.color?.let(theme::color) ?: androidx.compose.ui.graphics.Color.Unspecified,
// Behind this run's letters only, line by line where it wraps. The line's
// own background is the node's, and this is the part of it that changed.
background = runBackground(run, theme),
fontWeight = if (run.bold) FontWeight.Bold else null,
fontStyle = if (run.italic) FontStyle.Italic else null,
fontSize = run.role?.let { sized(theme.type(it).size) } ?: TextUnit.Unspecified,
fontFamily = family,
letterSpacing = letterSpacing,
fontFeatureSettings = fontFeatures,
textDecoration = when {
run.underline && run.strikethrough ->
TextDecoration.combine(listOf(TextDecoration.Underline, TextDecoration.LineThrough))
run.underline -> TextDecoration.Underline
run.strikethrough -> TextDecoration.LineThrough
else -> null
},
)
}
private fun tabId(index: Int): String = "compose-rust-tab-$index"
/**
* One placeholder per tab, as wide as it takes to reach the next tab stop.
*
* The stops are [tabSize] spaces of the text's own font apart, as CSS `tab-size` puts
* them, and a tab advances to the next one after whatever comes before it on its line. A
* tab that would advance less than half a space goes on to the stop after, as CSS has it.
* Only the side that measures the letters can work this out, which is why a Host cannot
* expand tabs into spaces in a proportional font.
*
* "Its line" is the line the text starts it on, counted from the last newline. Text that
* wraps before a tab puts the tab's stops where the unwrapped line would have them, which
* is right for `pre` and as close as a layout that has not happened yet can get otherwise.
*/
private fun tabStops(
text: AnnotatedString,
style: TextStyle,
tabSize: Int,
density: Density,
fontFamilyResolver: FontFamily.Resolver,
): Pair<List<AnnotatedString.Range<Placeholder>>, Map<String, InlineTextContent>> {
if (text.text.indexOf('\t') < 0) return emptyList<AnnotatedString.Range<Placeholder>>() to emptyMap()
// Positions inside a laid out line rather than intrinsic widths: an intrinsic width is
// rounded up to a whole pixel and leaves out trailing spaces, and either would move every
// stop after it.
val space = startOf(AnnotatedString(" "), 1, emptyList(), style, density, fontFamilyResolver)
val stop = space * (if (tabSize > 0) tabSize else TextInput.DEFAULT_TAB_SIZE)
val placeholders = mutableListOf<AnnotatedString.Range<Placeholder>>()
val inline = mutableMapOf<String, InlineTextContent>()
var tab = 0
for (index in text.text.indices) {
if (text.text[index] != '\t') continue
val lineStart = text.text.lastIndexOf('\n', index - 1) + 1
val before = placeholders
.filter { it.start >= lineStart }
.map { AnnotatedString.Range(it.item, it.start - lineStart, it.end - lineStart) }
val prefix = startOf(
text.subSequence(lineStart, index + 1),
index - lineStart,
before,
style,
density,
fontFamilyResolver,
)
var advance = if (stop > 0f) stop - (prefix % stop) else space
if (advance < space / 2f) advance += stop
val placeholder = Placeholder(
width = with(density) { advance.toSp() },
height = 0.sp,
placeholderVerticalAlign = PlaceholderVerticalAlign.AboveBaseline,
)
placeholders += AnnotatedString.Range(placeholder, index, index + 1)
inline[tabId(tab++)] = InlineTextContent(placeholder) {}
}
return placeholders to inline
}
/** Where character [offset] of [text] starts, laid out on one line. */
private fun startOf(
text: AnnotatedString,
offset: Int,
placeholders: List<AnnotatedString.Range<Placeholder>>,
style: TextStyle,
density: Density,
fontFamilyResolver: FontFamily.Resolver,
): Float {
if (offset <= 0) return 0f
val intrinsics = MultiParagraphIntrinsics(text, style, placeholders, density, fontFamilyResolver)
val paragraph = MultiParagraph(
intrinsics,
Constraints.fitPrioritizingWidth(0, ceil(intrinsics.maxIntrinsicWidth).toInt() + 1, 0, Constraints.Infinity),
)
return paragraph.getHorizontalPosition(offset, usePrimaryDirection = true)
}
/** What a `Text` node says about how it is set, read off its properties. */
internal fun Node.textInput(): TextInput {
val blob = (property(PropertyKind.Spans) as? PropertyValue.Bytes)?.value
val decoded = blob?.let(::decodeRuns)
return TextInput(
text = text(PropertyKind.Text),
runs = decoded ?: emptyList(),
runFonts = bytes(PropertyKind.SpanFonts)?.let(SpanFontRecords::decodeBlob) ?: emptyMap(),
// Made when the table arrived and kept on the node. Never read from the bytes here:
// this runs on every composition, and a table that was refused stays refused.
runFontFeatures = spanFontFeatures ?: emptyMap(),
noRole = (property(PropertyKind.TypeRole) as? PropertyValue.Integer)?.value == TYPE_ROLE_NONE.toLong(),
role = typeRole(),
fontSize = floatProp(PropertyKind.FontSize),
fontWeight = intProp(PropertyKind.FontWeight)?.toInt(),
letterSpacing = letterSpacingProp(),
lineHeight = lineHeightProp(),
maxLines = maxLines(),
softWrap = (property(PropertyKind.SoftWrap) as? PropertyValue.Bool)?.value != false,
tabSize = intProp(PropertyKind.TabSize)?.toInt() ?: TextInput.DEFAULT_TAB_SIZE,
wordBreak = role(PropertyKind.WordBreak, WordBreak.entries.toTypedArray()),
overflowWrap = role(PropertyKind.OverflowWrap, OverflowWrap.entries.toTypedArray()),
absoluteSize = when (val value = property(PropertyKind.AbsoluteSize)) {
is PropertyValue.Bool -> value.value
is PropertyValue.Integer -> value.value != 0L
else -> false
},
fonts = bytes(PropertyKind.Font)?.let(FontRefRecords::decodeBlob) ?: emptyList(),
color = paintProp(PropertyKind.Color),
textAlign = role(PropertyKind.TextAlign, TextAlign.entries.toTypedArray()),
overflow = overflow(),
fontFeatures = fontFeatures,
)
}
/** What is malformed about a `Text` node's run list, or null where nothing is. */
internal fun Node.runsDecodeProblem(): String? {
val spans = (property(PropertyKind.Spans) as? PropertyValue.Bytes)?.value
if (spans != null && decodeRuns(spans) == null) {
return "the run list is not a whole number of records"
}
bytes(PropertyKind.SpanFonts)?.let {
if (SpanFontRecords.decodeBlob(it) == null) return "the run font table does not decode"
}
return null
}
/** What is malformed about a `Text` node's font list, or null where nothing is. */
internal fun Node.fontListProblem(): String? {
bytes(PropertyKind.Font)?.let {
if (FontRefRecords.decodeBlob(it) == null) return "the font list does not decode"
}
return null
}
/** Bytes of one font feature record: four tag bytes, then the value as a little-endian u32. */
internal const val FONT_FEATURE_RECORD_LENGTH = 8
/** The most font features one node may carry. */
internal const val MAX_FONT_FEATURES = 16
/**
* A `FontFeatureSettings` blob as Compose's `fontFeatureSettings` string, such as
* `tnum 1, liga 0`, or null where the list is empty or cannot be read.
*
* The tags are not quoted. Skia's reader on the desktop, iOS and the web
* (`FontFeature.parseW3`) takes the first word of each entry as the tag and drops any that
* is not four characters long, so `"tnum" 1` would be read as no feature at all. HarfBuzz,
* which Minikin uses on Android, reads a tag with or without quotes.
*
* The records keep their order, and a tag that comes twice is written twice: the shapers
* under Compose (HarfBuzz under Skia, Minikin on Android) let the later value win, as CSS
* does. A list whose length is not a whole number of records, that holds more than
* [MAX_FONT_FEATURES] records, or whose tag bytes are not printable ASCII is reported
* through [onError] and none of it is used, so the text is drawn without features.
*
* Called when the property changes, never per frame: the string is kept on the node.
*/
internal fun fontFeatureSettings(bytes: ByteArray, onError: (String) -> Unit): String? {
if (bytes.size % FONT_FEATURE_RECORD_LENGTH != 0) {
onError("${bytes.size} bytes is not a whole number of $FONT_FEATURE_RECORD_LENGTH-byte records")
return null
}
val count = bytes.size / FONT_FEATURE_RECORD_LENGTH
if (count > MAX_FONT_FEATURES) {
onError("$count features where at most $MAX_FONT_FEATURES are taken")
return null
}
if (count == 0) return null
val out = StringBuilder(count * 12)
for (index in 0 until count) {
val at = index * FONT_FEATURE_RECORD_LENGTH
for (offset in 0 until 4) {
val byte = bytes[at + offset].toInt() and 0xFF
if (byte !in 0x20..0x7E) {
onError("feature $index has the tag byte 0x${byte.toString(16)}, which is not printable ASCII")
return null
}
}
val value = (bytes[at + 4].toLong() and 0xFF) or
((bytes[at + 5].toLong() and 0xFF) shl 8) or
((bytes[at + 6].toLong() and 0xFF) shl 16) or
((bytes[at + 7].toLong() and 0xFF) shl 24)
if (index > 0) out.append(", ")
for (offset in 0 until 4) out.append((bytes[at + offset].toInt() and 0xFF).toChar())
out.append(' ').append(value)
}
return out.toString()
}
/**
* A `SpanFontFeatures` table as Compose's `fontFeatureSettings` strings by run index, or
* null where no run names a feature or the table cannot be read.
*
* The table is held to its layout by [SpanFontFeatureRecords.decodeBlob] and each run's
* records to the rules of [fontFeatureSettings]. The first thing wrong is reported through
* [onError], once, and none of the table is used: features taken from half a table would
* set some runs and not others with nothing on screen to say which.
*
* Called when the property changes, never per frame: the map is kept on the node.
*/
internal fun spanFontFeatureSettings(bytes: ByteArray, onError: (String) -> Unit): Map<Int, String>? {
val lists = SpanFontFeatureRecords.decodeBlob(bytes, onError) ?: return null
val settings = HashMap<Int, String>(lists.size)
for ((run, records) in lists) {
var refused = false
val made = fontFeatureSettings(records) { why ->
refused = true
onError("run $run: $why")
}
if (refused) return null
if (made != null) settings[run] = made
}
return settings.takeIf { it.isNotEmpty() }
}
/**
* What is wrong with the runs a feature table names, for a text of [runs] runs, or null
* where every one of them is a run the text has.
*/
private fun runFeaturesProblem(features: Map<Int, String>, runs: Int): String? {
if (features.isEmpty()) return null
for (run in features.keys) {
if (run < 0 || run >= runs) {
return "features are named for run $run where the text has $runs runs"
}
}
return null
}
/**
* [own] after [base], so a tag both name takes [own]'s value. Either alone is returned as
* it is, so a style with no features of its own costs nothing to give the node's.
*/
internal fun appendFontFeatures(base: String?, own: String?): String? = when {
own.isNullOrEmpty() -> base
base.isNullOrEmpty() -> own
else -> "$base, $own"
}