Skip to content

Commit

Permalink
fix rendering a surrogate pair (e.g. emoji) in BigMonospaceText/TextF…
Browse files Browse the repository at this point in the history
…ield would throw an exception
  • Loading branch information
sunny-chung committed Sep 4, 2024
1 parent e7fc87e commit 63db38c
Showing 1 changed file with 26 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,20 @@ class ComposeUnicodeCharMeasurer(private val measurer: TextMeasurer, private val
*/
override fun measureFullText(text: String) {
val charToMeasure = mutableSetOf<String>()
var surrogatePairFirst: Char? = null
text.forEach {
val s = it.toString()
var s = it.toString()
if (surrogatePairFirst == null && s[0].isSurrogatePairFirst()) {
surrogatePairFirst = s[0]
return@forEach
} else if (surrogatePairFirst != null) {
if (s[0].isSurrogatePairSecond()) {
s = "$surrogatePairFirst${s[0]}"
} else {
s = s.substring(0, 1)
}
surrogatePairFirst = null
}
if (!charWidth.containsKey(s) && shouldIndexChar(s)) {
charToMeasure += s
}
Expand All @@ -27,8 +39,13 @@ class ComposeUnicodeCharMeasurer(private val measurer: TextMeasurer, private val

/**
* Time complexity = O(lg C)
*
* TODO: handle surrogate pair correctly
*/
override fun findCharWidth(char: String): Float {
if (char[0].isSurrogatePairFirst()) {
return 0f
}
when (char.codePoints().findFirst().asInt) {
in 0x4E00..0x9FFF,
in 0x3400..0x4DBF,
Expand Down Expand Up @@ -72,6 +89,14 @@ class ComposeUnicodeCharMeasurer(private val measurer: TextMeasurer, private val
}
}

fun Char.isSurrogatePairFirst(): Boolean {
return code in (0xD800 .. 0xDBFF)
}

fun Char.isSurrogatePairSecond(): Boolean {
return code in (0xDC00 .. 0xDFFF)
}

init {
measureAndIndex(COMPULSORY_MEASURES)
// hardcode, because calling TextMeasurer#measure() against below characters returns zero width
Expand Down

0 comments on commit 63db38c

Please sign in to comment.