react-native-nitro-input 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/CHANGELOG.md +305 -3
  2. package/NitroInput.podspec +4 -4
  3. package/README.md +378 -53
  4. package/android/CMakeLists.txt +5 -3
  5. package/android/src/main/cpp/JOutlineGeometry.hpp +1 -1
  6. package/android/src/main/cpp/JReflowEngine.cpp +132 -0
  7. package/android/src/main/cpp/{JMorphEngine.hpp → JReflowEngine.hpp} +7 -7
  8. package/android/src/main/cpp/JRollingEngine.cpp +222 -0
  9. package/android/src/main/cpp/JRollingEngine.hpp +68 -0
  10. package/android/src/main/cpp/cpp-adapter.cpp +4 -2
  11. package/android/src/main/java/com/margelo/nitro/nitroinput/AmountFormatter.kt +1 -1
  12. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +1 -1
  13. package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +471 -0
  14. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputPackage.kt +2 -1
  15. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +38 -16
  16. package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +1741 -0
  17. package/android/src/main/java/com/margelo/nitro/nitroinput/{MorphEngine.kt → ReflowEngine.kt} +2 -2
  18. package/android/src/main/java/com/margelo/nitro/nitroinput/RollingEngine.kt +59 -0
  19. package/cpp/AmountFormatter.cpp +5 -0
  20. package/cpp/AmountFormatter.hpp +10 -2
  21. package/cpp/{MorphEngine.cpp → ReflowEngine.cpp} +52 -47
  22. package/cpp/{MorphEngine.hpp → ReflowEngine.hpp} +12 -4
  23. package/cpp/RollingEngine.cpp +1224 -0
  24. package/cpp/RollingEngine.hpp +468 -0
  25. package/cpp/SwiftNonCopyable.hpp +22 -0
  26. package/cpp/worklets/NitroInputWorkletsBridge.cpp +3 -3
  27. package/cpp/worklets/NitroInputWorkletsBridge.hpp +1 -1
  28. package/ios/{HybridMorphInputView.swift → HybridNitroInputView.swift} +1 -1
  29. package/ios/HybridNitroNumberView.swift +439 -0
  30. package/ios/NitroInputView.swift +69 -45
  31. package/ios/NitroNumberView.swift +1934 -0
  32. package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +55 -0
  33. package/lib/commonjs/src/NitroInput.js +21 -52
  34. package/lib/commonjs/src/NitroNumber.js +139 -0
  35. package/lib/commonjs/src/index.js +4 -3
  36. package/lib/commonjs/src/specs/NitroNumber.nitro.js +2 -0
  37. package/lib/commonjs/src/styleHelpers.js +36 -0
  38. package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +55 -0
  39. package/lib/module/src/NitroInput.js +12 -43
  40. package/lib/module/src/NitroNumber.js +100 -0
  41. package/lib/module/src/index.js +1 -1
  42. package/lib/module/src/specs/NitroNumber.nitro.js +1 -0
  43. package/lib/module/src/styleHelpers.js +32 -0
  44. package/lib/typescript/src/NitroInput.d.ts +28 -21
  45. package/lib/typescript/src/NitroNumber.d.ts +211 -0
  46. package/lib/typescript/src/index.d.ts +3 -2
  47. package/lib/typescript/src/specs/NitroInput.nitro.d.ts +9 -9
  48. package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +238 -0
  49. package/lib/typescript/src/styleHelpers.d.ts +3 -0
  50. package/nitro.json +10 -0
  51. package/nitrogen/generated/android/NitroInput+autolinking.cmake +4 -0
  52. package/nitrogen/generated/android/NitroInputOnLoad.cpp +20 -0
  53. package/nitrogen/generated/android/c++/JFunc_void.hpp +75 -0
  54. package/nitrogen/generated/android/c++/JFunc_void_double_double.hpp +10 -10
  55. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +536 -0
  56. package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +156 -0
  57. package/nitrogen/generated/android/c++/JNitroNumberAffixAlign.hpp +64 -0
  58. package/nitrogen/generated/android/c++/JNitroNumberDirection.hpp +61 -0
  59. package/nitrogen/generated/android/c++/JNitroNumberEasing.hpp +67 -0
  60. package/nitrogen/generated/android/c++/JNitroNumberRevealStyle.hpp +58 -0
  61. package/nitrogen/generated/android/c++/JNitroNumberTextAlign.hpp +64 -0
  62. package/nitrogen/generated/android/c++/JNitroNumberTransition.hpp +61 -0
  63. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +299 -0
  64. package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.hpp +54 -0
  65. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void.kt +78 -0
  66. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/Func_void_double_double.kt +9 -9
  67. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +363 -0
  68. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberAffixAlign.kt +25 -0
  69. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberDirection.kt +24 -0
  70. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberEasing.kt +26 -0
  71. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberRevealStyle.kt +23 -0
  72. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberTextAlign.kt +25 -0
  73. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberTransition.kt +24 -0
  74. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroNumberViewManager.kt +96 -0
  75. package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroNumberViewStateUpdater.kt +23 -0
  76. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +25 -0
  77. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +248 -0
  78. package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +23 -0
  79. package/nitrogen/generated/ios/NitroInputAutolinking.mm +8 -0
  80. package/nitrogen/generated/ios/NitroInputAutolinking.swift +12 -0
  81. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.cpp +11 -0
  82. package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +432 -0
  83. package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +414 -0
  84. package/nitrogen/generated/ios/swift/Func_void.swift +46 -0
  85. package/nitrogen/generated/ios/swift/Func_void_double_double.swift +5 -5
  86. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +102 -0
  87. package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +1243 -0
  88. package/nitrogen/generated/ios/swift/NitroNumberAffixAlign.swift +48 -0
  89. package/nitrogen/generated/ios/swift/NitroNumberDirection.swift +44 -0
  90. package/nitrogen/generated/ios/swift/NitroNumberEasing.swift +52 -0
  91. package/nitrogen/generated/ios/swift/NitroNumberRevealStyle.swift +40 -0
  92. package/nitrogen/generated/ios/swift/NitroNumberTextAlign.swift +48 -0
  93. package/nitrogen/generated/ios/swift/NitroNumberTransition.swift +44 -0
  94. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +115 -0
  95. package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +175 -0
  96. package/nitrogen/generated/shared/c++/NitroNumberAffixAlign.hpp +84 -0
  97. package/nitrogen/generated/shared/c++/NitroNumberDirection.hpp +80 -0
  98. package/nitrogen/generated/shared/c++/NitroNumberEasing.hpp +88 -0
  99. package/nitrogen/generated/shared/c++/NitroNumberRevealStyle.hpp +76 -0
  100. package/nitrogen/generated/shared/c++/NitroNumberTextAlign.hpp +84 -0
  101. package/nitrogen/generated/shared/c++/NitroNumberTransition.hpp +80 -0
  102. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +124 -0
  103. package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +227 -0
  104. package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +55 -0
  105. package/package.json +15 -7
  106. package/src/NitroInput.tsx +37 -60
  107. package/src/NitroNumber.tsx +481 -0
  108. package/src/index.ts +20 -6
  109. package/src/specs/NitroInput.nitro.ts +9 -9
  110. package/src/specs/NitroNumber.nitro.ts +259 -0
  111. package/src/styleHelpers.ts +32 -0
  112. package/android/src/main/cpp/JMorphEngine.cpp +0 -132
  113. package/lib/commonjs/src/MorphInput.js +0 -42
  114. package/lib/module/src/MorphInput.js +0 -6
  115. package/lib/typescript/src/MorphInput.d.ts +0 -18
  116. package/src/MorphInput.tsx +0 -30
@@ -0,0 +1,1741 @@
1
+ package com.margelo.nitro.nitroinput
2
+
3
+ import android.animation.ValueAnimator
4
+ import android.content.Context
5
+ import android.content.res.Configuration
6
+ import android.database.ContentObserver
7
+ import android.graphics.Bitmap
8
+ import android.graphics.Canvas
9
+ import android.graphics.Color
10
+ import android.graphics.LinearGradient
11
+ import android.graphics.Matrix
12
+ import android.graphics.Paint
13
+ import android.graphics.Path
14
+ import android.graphics.RenderNode
15
+ import android.graphics.PorterDuff
16
+ import android.graphics.PorterDuffColorFilter
17
+ import android.graphics.PorterDuffXfermode
18
+ import android.graphics.Rect
19
+ import android.graphics.Shader
20
+ import android.graphics.Typeface
21
+ import android.os.Build
22
+ import android.os.Handler
23
+ import android.os.Looper
24
+ import android.os.SystemClock
25
+ import android.provider.Settings
26
+ import android.text.TextPaint
27
+ import android.util.TypedValue
28
+ import android.view.Choreographer
29
+ import android.view.View
30
+ import android.view.accessibility.AccessibilityEvent
31
+ import com.facebook.react.common.assets.ReactFontManager
32
+ import java.util.concurrent.atomic.AtomicReferenceArray
33
+ import kotlin.math.abs
34
+ import kotlin.math.ceil
35
+ import kotlin.math.floor
36
+ import kotlin.math.max
37
+ import kotlin.math.min
38
+
39
+ /**
40
+ * Draws a NitroNumber. All behaviour (wheel positions, rolls, stagger,
41
+ * easing, loading fade, shimmer phase) lives in the shared C++ `RollingEngine`
42
+ * (cpp/RollingEngine.hpp, reached through the [RollingEngine] JNI handle); this
43
+ * view owns fonts, layout, fit-to-width and Canvas drawing, and drives the
44
+ * engine from a Choreographer frame loop.
45
+ *
46
+ * Mirrors `NitroNumberView.swift` on iOS.
47
+ */
48
+ // The numeric transition's geometry, in line heights; mirrors
49
+ // `RollingEngine::kNumeric*`, where the effect is described.
50
+ private const val NUMERIC_OFFSET = 0.34f
51
+ private const val NUMERIC_SCALE = 0.4f
52
+ /** The blur radius at full blur, in line heights: SwiftUI's own. */
53
+ private const val NUMERIC_BLUR = 0.08f
54
+ /** Blurred copies per digit, from a touch of blur to the full one. */
55
+ private const val NUMERIC_BLUR_LEVELS = 6
56
+
57
+ /** `RollingEngine::TextSlot`. */
58
+ private const val TEXT_PREFIX = 0
59
+ private const val TEXT_SUFFIX = 1
60
+ private const val TEXT_GROUPING = 2
61
+ private const val TEXT_DECIMAL = 3
62
+ private const val TEXT_SLOTS = 4
63
+
64
+ class NitroNumberView(context: Context) : View(context) {
65
+
66
+ // region Configuration
67
+
68
+ data class Format(
69
+ val fractionDigits: Int = 0,
70
+ val minimumIntegerDigits: Int = 1,
71
+ val groupingSeparator: String = "",
72
+ val decimalSeparator: String = ".",
73
+ val prefix: String = "",
74
+ val suffix: String = "",
75
+ )
76
+
77
+ enum class AffixAlign { BASELINE, CENTER, TOP, BOTTOM }
78
+
79
+ data class Typography(
80
+ val fontSize: Float = 32f,
81
+ val prefixFontSize: Float? = null,
82
+ val suffixFontSize: Float? = null,
83
+ val fontWeight: Int = 400,
84
+ val fontFamily: String? = null,
85
+ val color: Int? = null,
86
+ val prefixAlign: AffixAlign = AffixAlign.BASELINE,
87
+ val suffixAlign: AffixAlign = AffixAlign.BASELINE,
88
+ val adjustsFontSizeToFit: Boolean = false,
89
+ val minimumFontScale: Float = 0.5f,
90
+ val allowFontScaling: Boolean = false,
91
+ val maxFontSizeMultiplier: Float = 0f,
92
+ )
93
+
94
+ enum class Easing(val raw: Int) { LINEAR(0), EASE_IN(1), EASE_OUT(2), EASE_IN_OUT(3), SPRING(4) }
95
+
96
+ enum class Direction(val raw: Int) { AUTO(0), UP(1), DOWN(2) }
97
+
98
+ data class Timing(
99
+ /** The odometer roll, or one of the glyph-swap transitions. */
100
+ val transition: Transition = Transition.ROLL,
101
+ /** A punch of the whole figure on every change, peak overshoot 0 (none) to 1. */
102
+ val popOnChange: Double = 0.0,
103
+ val durationMs: Long = 500,
104
+ val easing: Easing = Easing.EASE_IN_OUT,
105
+ val bounce: Double = 0.15,
106
+ /** Delay between the start of each wheel's roll, least significant first. */
107
+ val staggerMs: Long = 0,
108
+ val direction: Direction = Direction.AUTO,
109
+ /** Length of a jackpot reveal (the count, or until the last reel locks). */
110
+ val revealDurationMs: Long = 2200,
111
+ /** Peak overshoot of the reveal's landing pop (0 = none). */
112
+ val revealBounce: Double = 0.12,
113
+ /** Count style: how much smaller the figure opens, growing to full size over the count. */
114
+ val revealGrow: Double = 0.2,
115
+ /** The reveal's presentation. */
116
+ val revealStyle: RevealStyle = RevealStyle.COUNT,
117
+ /** Spin style: delay between reel stops, from the left. */
118
+ val revealStaggerMs: Long = 200,
119
+ /** Count style: how long the count pauses on each milestone. */
120
+ val revealMilestoneHoldMs: Long = 0,
121
+ )
122
+
123
+ enum class RevealStyle(val raw: Int) { COUNT(0), SPIN(1) }
124
+
125
+ enum class Transition(val raw: Int) { ROLL(0), NUMERIC(1), SCRAMBLE(2) }
126
+
127
+ /** The change flash: the colours a changed digit lights up in (null = off) and how long the light lasts. */
128
+ data class Flash(
129
+ val upColor: Int? = null,
130
+ val downColor: Int? = null,
131
+ val durationMs: Long = 600,
132
+ )
133
+
134
+ data class Shimmer(
135
+ /** Color of the glint's core; null uses a light neutral (dark neutral in dark mode). */
136
+ val color: Int? = null,
137
+ /** Duration of one sweep across the number. */
138
+ val durationMs: Long = 950,
139
+ )
140
+
141
+ /** `AUTO` is the start edge of the layout direction, as `Text` with no `textAlign`; the rest are absolute. */
142
+ enum class Alignment { AUTO, LEFT, CENTER, RIGHT }
143
+
144
+ var format: Format = Format()
145
+ set(value) {
146
+ if (field == value) return
147
+ val old = field
148
+ field = value
149
+ // A prefix, suffix or separator that changes while a value is shown
150
+ // swaps like a digit (`RollingEngine::changeText`): keep the text that leaves.
151
+ if (engine.hasShownValue()) {
152
+ val rtl = isRtl
153
+ fun ink(prefix: String) = if (rtl) splitAffix(prefix, spaceAtEnd = true).first else prefix
154
+ fun suffixInk(suffix: String) = if (rtl) splitAffix(suffix, spaceAtEnd = false).first else suffix
155
+ val t = now()
156
+ fun change(slot: Int, from: String, to: String) {
157
+ if (from == to) return
158
+ leavingText[slot] = from
159
+ engine.changeText(slot, t)
160
+ }
161
+ change(TEXT_PREFIX, ink(old.prefix), ink(value.prefix))
162
+ change(TEXT_SUFFIX, suffixInk(old.suffix), suffixInk(value.suffix))
163
+ change(TEXT_GROUPING, old.groupingSeparator, value.groupingSeparator)
164
+ change(TEXT_DECIMAL, old.decimalSeparator, value.decimalSeparator)
165
+ }
166
+ affixBlocksDirty = true
167
+ // Played in a glyph-swap transition; snaps otherwise (see the engine).
168
+ engine.changeFormat(value.fractionDigits, value.minimumIntegerDigits, now())
169
+ if (engine.hasShownValue()) reportIntrinsicSize()
170
+ invalidate()
171
+ scheduleFrameIfNeeded()
172
+ }
173
+
174
+ var typography: Typography = Typography()
175
+ set(value) {
176
+ if (field == value) return
177
+ field = value
178
+ rebuildFonts()
179
+ }
180
+
181
+ var timing: Timing = Timing()
182
+ set(value) {
183
+ field = value
184
+ engine.setTiming(value.durationMs / 1000.0, value.easing.raw, value.bounce, value.staggerMs / 1000.0, value.direction.raw)
185
+ engine.setTransition(value.transition.raw)
186
+ warmSwapMasks()
187
+ engine.setPopOnChange(value.popOnChange)
188
+ engine.setRevealTiming(value.revealDurationMs / 1000.0, value.revealBounce, value.revealStyle.raw, value.revealStaggerMs / 1000.0)
189
+ engine.setRevealGrow(value.revealGrow)
190
+ engine.setRevealMilestoneHold(value.revealMilestoneHoldMs / 1000.0)
191
+ }
192
+
193
+ /** Win tiers of a count-style reveal, in the figure's units. */
194
+ var revealMilestones: DoubleArray = DoubleArray(0)
195
+ set(value) {
196
+ if (field.contentEquals(value)) return
197
+ field = value
198
+ engine.clearRevealMilestones()
199
+ for (milestone in value) engine.addRevealMilestone(milestone)
200
+ }
201
+
202
+ var shimmer: Shimmer = Shimmer()
203
+ set(value) {
204
+ if (field == value) return
205
+ field = value
206
+ invalidate()
207
+ }
208
+
209
+ var flash: Flash = Flash()
210
+ set(value) {
211
+ if (field == value) return
212
+ field = value
213
+ engine.setFlash(if (value.upColor != null || value.downColor != null) value.durationMs / 1000.0 else 0.0)
214
+ invalidate()
215
+ }
216
+
217
+ /** Loading glint: full-color ink with a light band sweeping through it. */
218
+ var loading: Boolean = false
219
+ set(value) {
220
+ if (field == value) return
221
+ field = value
222
+ engine.setReduceMotion(animationsDisabled())
223
+ engine.setLoading(value, now())
224
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) stateDescription = if (value) "Loading" else null
225
+ scheduleFrameIfNeeded()
226
+ invalidate()
227
+ }
228
+
229
+ var alignment: Alignment = Alignment.AUTO
230
+ set(value) {
231
+ field = value
232
+ invalidate()
233
+ }
234
+
235
+ /** Called with the settled (target) intrinsic size, in dp, whenever it changes. */
236
+ var onIntrinsicSizeChange: ((widthDp: Float, heightDp: Float) -> Unit)? = null
237
+ /** Called once a jackpot reveal has landed (count finished, pop rung out). */
238
+ var onRevealEnd: (() -> Unit)? = null
239
+ /** Called when a count-style reveal reaches a milestone (its index and value). */
240
+ var onRevealMilestone: ((index: Int, value: Double) -> Unit)? = null
241
+
242
+ /** The value currently shown or being rolled towards. */
243
+ val targetValue: Double
244
+ get() = engine.targetValue()
245
+
246
+ /** True while a jackpot reveal counts or its landing pop rings out. */
247
+ val isRevealing: Boolean
248
+ get() = engine.isRevealing()
249
+
250
+ // endregion
251
+
252
+ // region Fonts
253
+
254
+ private enum class GlyphRole { DIGIT, PREFIX, SUFFIX }
255
+
256
+ /** Digit / prefix / suffix paints with per-glyph width caches. */
257
+ private inner class FontSet(t: Typography) {
258
+ private val scale = systemFontMultiplier(t)
259
+ val digit = makePaint(t, t.fontSize * scale)
260
+ val prefix = makePaint(t, (t.prefixFontSize ?: t.fontSize) * scale)
261
+ val suffix = makePaint(t, (t.suffixFontSize ?: t.fontSize) * scale)
262
+ private val prefixAlign = t.prefixAlign
263
+ private val suffixAlign = t.suffixAlign
264
+ private val digitMetrics: Paint.FontMetrics = digit.fontMetrics
265
+ /** Height of the line box (the digit paint's line height), in px. */
266
+ val lineHeight: Float = ceil(digitMetrics.descent - digitMetrics.ascent)
267
+ /** The numeric transition's blur radius at full blur, in line heights. */
268
+ val numericBlur: Float = NUMERIC_BLUR
269
+ /** Width of the widest digit glyph, in px. */
270
+ val digitWidth: Float
271
+ private val widthCache = Array(GlyphRole.entries.size) { java.util.concurrent.ConcurrentHashMap<String, Float>() }
272
+ /**
273
+ * A wheel's whole digit strip, per blank-zero variant: 12 slots for index
274
+ * -1 (blank) to 10 (the 0 that follows 9 on a wrap), each `lineHeight`
275
+ * tall with the digit centred in `digitWidth`. The digits are rasterized
276
+ * once by the software text renderer into a bitmap, and the bitmap is the
277
+ * whole content of a `RenderNode` layer; a wheel then draws one slot-high
278
+ * window of that layer, one quad, and a frame costs no glyph work at all:
279
+ * the same thing the iOS view does with a CALayer strip.
280
+ *
281
+ * Why both. Text rasterized by the GPU straight into a hardware layer came
282
+ * out thinner and paler than the glyphs drawn beside it (a small red digit
283
+ * next to its sign, visibly), and a bitmap's pixels are exactly what the
284
+ * text renderer put there. But drawing the bitmap itself per wheel costs
285
+ * the renderer several milliseconds a frame more than drawing a layer, so
286
+ * the bitmap goes into a layer once. Below Android 10 there is no public
287
+ * RenderNode and the bitmap is drawn directly.
288
+ *
289
+ * The strips are shared by every rolling number drawn with the same
290
+ * typography (see [StripCache]).
291
+ */
292
+ private val stripKey: String =
293
+ "${t.fontFamily}|${t.fontWeight}|${digit.textSize}|${digit.color}|${digit.typeface?.hashCode()}"
294
+
295
+ /**
296
+ * This font set's digit masks by digit and level, filled from the shared
297
+ * cache: a swapping glyph looks two up every frame, and a lookup there
298
+ * built a key string each time. Written by the warm-up thread too.
299
+ */
300
+ private val digitMasks = AtomicReferenceArray<Bitmap>(10 * (NUMERIC_BLUR_LEVELS + 1))
301
+
302
+ fun strip(blankZero: Boolean): Strip? {
303
+ if (digitWidth <= 0f || lineHeight <= 0f) return null
304
+ val strip = StripCache.get("$stripKey|$blankZero") {
305
+ Strip(renderStrip(blankZero), if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) RenderNode("rolling-number-strip") else null)
306
+ }
307
+ val node = strip.node
308
+ // HWUI deletes a node's display list once nothing in the view tree draws
309
+ // it any more (the last view drawing this strip was dropped, or the
310
+ // window gave its hardware resources back), and a node drawn without
311
+ // one draws nothing. Record again whenever that happened: one bitmap
312
+ // draw, and only then.
313
+ if (node != null && !node.hasDisplayList()) {
314
+ node.setPosition(0, 0, strip.bitmap.width, strip.bitmap.height)
315
+ node.setUseCompositingLayer(true, null)
316
+ val canvas = node.beginRecording(strip.bitmap.width, strip.bitmap.height)
317
+ try {
318
+ canvas.drawBitmap(strip.bitmap, 0f, 0f, null)
319
+ } finally {
320
+ node.endRecording()
321
+ }
322
+ }
323
+ return strip
324
+ }
325
+
326
+ /**
327
+ * The digit out of focus, for the numeric transition: the glyph drawn
328
+ * into a padded bitmap and blurred in software (three box passes, which
329
+ * is a Gaussian to the eye; HWUI has no hardware mask filter), once per
330
+ * font, colour and density and shared like the strips. A transitioning
331
+ * glyph is its sharp text and this bitmap cross-faded, a fixed cost per
332
+ * frame instead of a blur pass. The bitmap is `digitWidth + 2 pad` wide
333
+ * and `lineHeight + 2 pad` tall with the glyph centred in the column.
334
+ */
335
+ fun blurred(digitIndex: Int, level: Int): Bitmap? {
336
+ if (digitWidth <= 0f || lineHeight <= 0f) return null
337
+ // Level 0 (or no blur at all) is the glyph unblurred, still a mask: a
338
+ // swapping glyph's two copies must be the same kind of thing, drawn the
339
+ // same way at the same sub-pixel position. Hardware text snaps to whole
340
+ // pixels as it moves and a bitmap does not, and cross-faded they slid in
341
+ // and out of register as the spring settled, a bold/pale flicker.
342
+ val slot = digitIndex * (NUMERIC_BLUR_LEVELS + 1) + level.coerceIn(0, NUMERIC_BLUR_LEVELS)
343
+ digitMasks.get(slot)?.let { return it }
344
+ val radius = if (level <= 0 || numericBlur <= 0f) 0 else Math.round(lineHeight * numericBlur * level / NUMERIC_BLUR_LEVELS).coerceAtLeast(1)
345
+ val mask = BlurredGlyphCache.get("$stripKey|$digitIndex|$radius|$blurPad") {
346
+ val text = DIGITS[digitIndex]
347
+ val pad = blurPad
348
+ val w = ceil(digitWidth).toInt() + 2 * pad
349
+ val h = ceil(lineHeight).toInt() + 2 * pad
350
+ // An alpha mask, not a coloured bitmap: the glyph's coverage, blurred,
351
+ // that a draw fills with the digit paint's colour. A coloured
352
+ // ARGB_8888 bitmap round-tripped through get/setPixels came back with
353
+ // its whole rectangle faintly inked on the GPU; a mask has no colour
354
+ // to get wrong, and is a quarter of the memory.
355
+ val mask = Bitmap.createBitmap(w, h, Bitmap.Config.ALPHA_8)
356
+ val canvas = Canvas(mask)
357
+ // A paint of its own: the masks are warmed off the main thread, where
358
+ // the digit paint's alpha is being changed by the draws.
359
+ val paint = TextPaint(digit).apply { alpha = 255 }
360
+ canvas.drawText(text, pad + (digitWidth - width(text, GlyphRole.DIGIT)) / 2f, pad + baseline(GlyphRole.DIGIT, text, 0f), paint)
361
+ if (radius > 0) boxBlurMask(mask, radius)
362
+ // Immutable and uploaded ahead of its first draw: HWUI re-pins a mutable
363
+ // bitmap at every sync, and the first frame that drew a fresh mask paid
364
+ // for its texture upload.
365
+ val done = mask.copy(Bitmap.Config.ALPHA_8, false) ?: mask
366
+ if (done !== mask) mask.recycle()
367
+ done.prepareToDraw()
368
+ done
369
+ }
370
+ digitMasks.set(slot, mask)
371
+ return mask
372
+ }
373
+
374
+ /**
375
+ * [text] of [role] as an alpha mask blurred to [level] (of
376
+ * [NUMERIC_BLUR_LEVELS]; 0 sharp), `width + 2 pad` by `lineHeight + 2 pad`
377
+ * with the text's left edge at `pad`: a prefix, suffix or separator
378
+ * changing text, drawn the way a swapping digit is.
379
+ */
380
+ fun blurredText(text: String, role: GlyphRole, level: Int): Bitmap? {
381
+ if (text.isEmpty() || lineHeight <= 0f) return null
382
+ val radius = if (level <= 0 || numericBlur <= 0f) 0 else Math.round(lineHeight * numericBlur * level / NUMERIC_BLUR_LEVELS).coerceAtLeast(1)
383
+ return BlurredGlyphCache.get("$stripKey|t|${role.ordinal}|$text|$radius|$blurPad") {
384
+ val pad = blurPad
385
+ val w = ceil(width(text, role)).toInt() + 2 * pad
386
+ val h = ceil(lineHeight).toInt() + 2 * pad
387
+ val mask = Bitmap.createBitmap(w.coerceAtLeast(1), h, Bitmap.Config.ALPHA_8)
388
+ val canvas = Canvas(mask)
389
+ val paint = TextPaint(paint(role)).apply { alpha = 255 }
390
+ canvas.drawText(text, pad.toFloat(), pad + baseline(role, text, 0f), paint)
391
+ if (radius > 0) boxBlurMask(mask, radius)
392
+ val done = mask.copy(Bitmap.Config.ALPHA_8, false) ?: mask
393
+ if (done !== mask) mask.recycle()
394
+ done.prepareToDraw()
395
+ done
396
+ }
397
+ }
398
+
399
+ /** Padding around a blurred glyph's bitmap, enough for the blur's tail. */
400
+ val blurPad: Int get() = ceil(lineHeight * numericBlur * 3f).toInt().coerceAtLeast(2)
401
+
402
+ /** A digit paint in another colour, for the change flash; one per colour. */
403
+ private val tintedPaints = HashMap<Int, TextPaint>()
404
+ fun tinted(color: Int): TextPaint = tintedPaints.getOrPut(color) { TextPaint(digit).apply { this.color = color } }
405
+
406
+ private fun renderStrip(blankZero: Boolean): Bitmap {
407
+ val w = ceil(digitWidth).toInt()
408
+ val h = ceil(lineHeight * STRIP_SLOTS).toInt()
409
+ val drawn = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
410
+ val canvas = Canvas(drawn)
411
+ val baseline = baseline(GlyphRole.DIGIT, "0", 0f)
412
+ for (index in -1 until STRIP_SLOTS - 1) {
413
+ if (index < 0 || (blankZero && index == 0)) continue
414
+ val text = DIGITS[index % 10]
415
+ canvas.drawText(text, (digitWidth - width(text, GlyphRole.DIGIT)) / 2f, (index + 1) * lineHeight + baseline, digit)
416
+ }
417
+ // Immutable: the renderer uploads it once and keeps the texture.
418
+ val strip = drawn.copy(Bitmap.Config.ARGB_8888, false)
419
+ if (strip !== drawn) drawn.recycle()
420
+ return strip
421
+ }
422
+ private val capHeightCache = HashMap<GlyphRole, Float>()
423
+ private val inkDescentCache = HashMap<String, Float>()
424
+
425
+ init {
426
+ digitWidth = (0..9).maxOf { width(it.toString(), GlyphRole.DIGIT) }
427
+ }
428
+
429
+ fun paint(role: GlyphRole): TextPaint = when (role) {
430
+ GlyphRole.DIGIT -> digit
431
+ GlyphRole.PREFIX -> prefix
432
+ GlyphRole.SUFFIX -> suffix
433
+ }
434
+
435
+ // One map per role: a joined "role|text" key allocated a string on every
436
+ // lookup, and the layout looks widths up for every glyph on every frame.
437
+ fun width(text: String, role: GlyphRole): Float =
438
+ widthCache[role.ordinal].getOrPut(text) { paint(role).measureText(text) }
439
+
440
+ private val shapedCache = Array(GlyphRole.entries.size) { java.util.concurrent.ConcurrentHashMap<String, ShapedText>() }
441
+
442
+ /**
443
+ * [text] of [role] shaped once, for [Canvas.drawGlyphs]: `drawText` runs
444
+ * the text shaper on every call, and an affix or separator drawn every
445
+ * frame for every number on screen cost ~45 us a call on a Galaxy A22,
446
+ * about fifteen times a digit's. The glyphs and positions are the ones
447
+ * `drawText` would produce; the paint's own shaping settings (size,
448
+ * typeface, `tnum`) are fixed for this font set.
449
+ */
450
+ @androidx.annotation.RequiresApi(Build.VERSION_CODES.S)
451
+ fun shaped(text: String, role: GlyphRole): ShapedText =
452
+ shapedCache[role.ordinal].getOrPut(text) { ShapedText.of(text, paint(role)) }
453
+
454
+ /** Baseline y for `role` drawing `text`, given the top of the digit line box. */
455
+ fun baseline(role: GlyphRole, text: String, lineTop: Float): Float {
456
+ val digitBaseline = lineTop - digitMetrics.ascent
457
+ if (role == GlyphRole.DIGIT) return digitBaseline
458
+ val p = paint(role)
459
+ val m = p.fontMetrics
460
+ return when (if (role == GlyphRole.PREFIX) prefixAlign else suffixAlign) {
461
+ AffixAlign.BASELINE -> digitBaseline
462
+ AffixAlign.CENTER -> lineTop + (lineHeight - (m.descent - m.ascent)) / 2f - m.ascent
463
+ AffixAlign.TOP -> lineTop + (-digitMetrics.ascent - capHeight(GlyphRole.DIGIT)) + capHeight(role)
464
+ // Pin the bottom of the ink, not of the line boxes: the digits' ink ends
465
+ // on the baseline, so "USD" sits on it too instead of hanging down to
466
+ // where a comma's tail reaches.
467
+ AffixAlign.BOTTOM -> digitBaseline + inkDescent(ALL_DIGITS, GlyphRole.DIGIT) - inkDescent(text, role)
468
+ }
469
+ }
470
+
471
+ /** How far `text`'s ink hangs below the baseline (0 for digits and capitals). */
472
+ private fun inkDescent(text: String, role: GlyphRole): Float = inkDescentCache.getOrPut(role.name + "|" + text) {
473
+ val bounds = Rect()
474
+ paint(role).getTextBounds(text, 0, text.length, bounds)
475
+ max(0, bounds.bottom).toFloat()
476
+ }
477
+
478
+ private fun capHeight(role: GlyphRole): Float = capHeightCache.getOrPut(role) {
479
+ val bounds = Rect()
480
+ paint(role).getTextBounds("0", 0, 1, bounds)
481
+ -bounds.top.toFloat()
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Blurs a single-colour glyph in place: the alpha channel gets three box
487
+ * passes of [radius] in each axis, and every pixel is put back as [color]
488
+ * at its blurred coverage.
489
+ */
490
+ /**
491
+ * Blurs an ALPHA_8 [mask] in place: three box passes of [radius], which is a
492
+ * Gaussian to the eye with a standard deviation of about the radius.
493
+ */
494
+ private fun boxBlurMask(mask: Bitmap, radius: Int) {
495
+ val w = mask.width
496
+ val h = mask.height
497
+ val stride = mask.rowBytes
498
+ val bytes = java.nio.ByteBuffer.allocate(stride * h)
499
+ mask.copyPixelsToBuffer(bytes)
500
+ val alpha = FloatArray(w * h) { (bytes.get((it / w) * stride + it % w).toInt() and 0xff).toFloat() }
501
+ val scratch = FloatArray(w * h)
502
+ val window = (2 * radius + 1).toFloat()
503
+ repeat(3) {
504
+ // horizontal
505
+ for (y in 0 until h) {
506
+ val row = y * w
507
+ var sum = 0f
508
+ for (x in -radius..radius) sum += alpha[row + x.coerceIn(0, w - 1)]
509
+ for (x in 0 until w) {
510
+ scratch[row + x] = sum / window
511
+ sum += alpha[row + (x + radius + 1).coerceIn(0, w - 1)] - alpha[row + (x - radius).coerceIn(0, w - 1)]
512
+ }
513
+ }
514
+ // vertical
515
+ for (x in 0 until w) {
516
+ var sum = 0f
517
+ for (y in -radius..radius) sum += scratch[y.coerceIn(0, h - 1) * w + x]
518
+ for (y in 0 until h) {
519
+ alpha[y * w + x] = sum / window
520
+ sum += scratch[(y + radius + 1).coerceIn(0, h - 1) * w + x] - scratch[(y - radius).coerceIn(0, h - 1) * w + x]
521
+ }
522
+ }
523
+ }
524
+ for (i in alpha.indices) bytes.put((i / w) * stride + i % w, Math.round(alpha[i]).coerceIn(0, 255).toByte())
525
+ bytes.rewind()
526
+ mask.copyPixelsFromBuffer(bytes)
527
+ }
528
+
529
+ /** System font scale for `allowFontScaling`, capped by `maxFontSizeMultiplier`. */
530
+ private fun systemFontMultiplier(t: Typography): Float {
531
+ if (!t.allowFontScaling) return 1f
532
+ val multiplier = context.resources.configuration.fontScale
533
+ return if (t.maxFontSizeMultiplier > 0f) min(multiplier, t.maxFontSizeMultiplier) else multiplier
534
+ }
535
+
536
+ private fun makePaint(t: Typography, sizeDp: Float): TextPaint {
537
+ val paint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG)
538
+ paint.typeface = makeTypeface(t)
539
+ paint.textSize = sizeDp * density
540
+ paint.color = t.color ?: defaultTextColor()
541
+ paint.fontFeatureSettings = "tnum"
542
+ return paint
543
+ }
544
+
545
+ private fun makeTypeface(t: Typography): Typeface {
546
+ val family = t.fontFamily
547
+ return try {
548
+ if (!family.isNullOrEmpty()) {
549
+ ReactFontManager.getInstance().getTypeface(family, Typeface.NORMAL, t.fontWeight, context.assets)
550
+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
551
+ Typeface.create(Typeface.DEFAULT, t.fontWeight, false)
552
+ } else if (t.fontWeight >= 600) {
553
+ Typeface.DEFAULT_BOLD
554
+ } else {
555
+ Typeface.DEFAULT
556
+ }
557
+ } catch (e: Throwable) {
558
+ if (t.fontWeight >= 600) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
559
+ }
560
+ }
561
+
562
+ private fun defaultTextColor(): Int {
563
+ val value = TypedValue()
564
+ return if (context.theme.resolveAttribute(android.R.attr.textColorPrimary, value, true)) {
565
+ if (value.resourceId != 0) {
566
+ context.resources.getColorStateList(value.resourceId, context.theme).defaultColor
567
+ } else {
568
+ value.data
569
+ }
570
+ } else {
571
+ Color.BLACK
572
+ }
573
+ }
574
+
575
+ // endregion
576
+
577
+ // region State
578
+
579
+ private class Wheel(
580
+ var position: Double = 0.0,
581
+ var width: Double = 1.0,
582
+ var linear: Boolean = false,
583
+ var blankZero: Boolean = false,
584
+ /** The numeric transition's swap, as the engine reports it (see `RollingEngine.hpp`). */
585
+ var fromGlyph: Double = -1.0,
586
+ var toGlyph: Double = -1.0,
587
+ var blend: Double = 1.0,
588
+ var fromAbove: Boolean = true,
589
+ var flash: Double = 0.0,
590
+ var flashUp: Boolean = true,
591
+ var focus: Double = 1.0,
592
+ var grow: Double = 1.0,
593
+ var blurOut: Double = 1.0,
594
+ )
595
+
596
+ private val engine = RollingEngine()
597
+ /** Reused every frame so the draw path stops allocating once warm. */
598
+ private val frameElements = ElementList()
599
+ private val settledElements = ElementList()
600
+ private val settledWheels = ArrayList<Wheel>()
601
+ /** The affixes split from the space they keep against the digits (RTL only). */
602
+ private var affixBlocksDirty = true
603
+ private var affixRtl = false
604
+ private var prefixInk = ""
605
+ private var prefixGap = ""
606
+ private var suffixInk = ""
607
+ private var suffixGap = ""
608
+ private val density = context.resources.displayMetrics.density
609
+ private var fonts: FontSet = FontSet(Typography())
610
+ private var fontScale = 1f
611
+ private var lastReportedWidth = -1f
612
+ private var lastReportedHeight = -1f
613
+ private val wheels = ArrayList<Wheel>()
614
+ private var signFactor = 0.0
615
+ private var loadingProgress = 0f
616
+ private var revealScale = 1f
617
+ private var frameScheduled = false
618
+ private val frameCallback = Choreographer.FrameCallback { frameTimeNanos ->
619
+ frameScheduled = false
620
+ val wasRevealing = engine.isRevealing()
621
+ val reachedBefore = engine.revealMilestonesReached()
622
+ engine.tick(frameTimeNanos / 1e9)
623
+ if (pendingSizeReport && !engine.isRolling()) reportIntrinsicSize()
624
+ invalidate()
625
+ scheduleFrameIfNeeded()
626
+ if (wasRevealing) {
627
+ reportMilestones(reachedBefore)
628
+ if (!engine.isRevealing()) onRevealEnd?.invoke()
629
+ }
630
+ }
631
+
632
+ /** Fires [onRevealMilestone] for every milestone reached since [reachedBefore]. */
633
+ private fun reportMilestones(reachedBefore: Int) {
634
+ val reached = engine.revealMilestonesReached()
635
+ val listener = onRevealMilestone ?: return
636
+ for (index in reachedBefore until reached) listener(index, engine.revealMilestoneValue(index))
637
+ }
638
+ /** Filtered so a strip window in motion between two pixel rows blends rather than steps. */
639
+ private val stripPaint = Paint(Paint.FILTER_BITMAP_FLAG)
640
+ /** Reused by the resting-wheel draw, which runs for every resting digit on every frame. */
641
+ private val stripSrc = Rect()
642
+ private val stripDst = android.graphics.RectF()
643
+ /** The blurred glyph masks of the numeric transition, filled with the digit colour. */
644
+ private val blurPaint = Paint(Paint.FILTER_BITMAP_FLAG or Paint.ANTI_ALIAS_FLAG)
645
+ /** The strip again, in the change flash's colour: its ink replaced by the tint, at the flash's opacity. */
646
+ private val flashStripPaint = Paint(Paint.FILTER_BITMAP_FLAG)
647
+ private var flashStripColor = 0
648
+ /** The change flash's colour for this wheel this frame, or null when it is not flashing. */
649
+ private fun flashColor(wheel: Wheel): Int? =
650
+ if (wheel.flash <= 0.002) null else (if (wheel.flashUp) flash.upColor else flash.downColor)
651
+ private val shimmerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
652
+ xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
653
+ }
654
+ /** The glint's gradient, rebuilt only when its colors or the content width change; a frame just slides it. */
655
+ private var shimmerGradient: LinearGradient? = null
656
+ private var shimmerGradientWidth = -1f
657
+ private var shimmerGradientBase = 0
658
+ private var shimmerGradientHighlight = 0
659
+ private val shimmerMatrix = Matrix()
660
+
661
+ init {
662
+ importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES
663
+ }
664
+
665
+ // endregion
666
+
667
+ // region Public API
668
+
669
+ fun stopAnimation() {
670
+ if (frameScheduled) {
671
+ Choreographer.getInstance().removeFrameCallback(frameCallback)
672
+ frameScheduled = false
673
+ }
674
+ }
675
+
676
+ /**
677
+ * Returns the view to its pristine state so Fabric can reuse it for a new
678
+ * element (RecyclableView). Props are re-applied by Nitro afterwards.
679
+ */
680
+ fun resetForRecycle() {
681
+ stopAnimation()
682
+ engine.reset()
683
+ wheels.clear()
684
+ signFactor = 0.0
685
+ loadingProgress = 0f
686
+ revealScale = 1f
687
+ fontScale = 1f
688
+ lastReportedWidth = -1f
689
+ autoAnchor = null
690
+ awaitingLayout = false
691
+ laidLeft = Int.MIN_VALUE
692
+ laidRight = Int.MIN_VALUE
693
+ lastReportedHeight = -1f
694
+ format = Format()
695
+ typography = Typography()
696
+ timing = Timing()
697
+ shimmer = Shimmer()
698
+ alignment = Alignment.AUTO
699
+ revealMilestones = DoubleArray(0)
700
+ // onIntrinsicSizeChange, onRevealEnd and onRevealMilestone are the hybrid's
701
+ // wiring, not the element's props: they stay across recycling (the hybrid
702
+ // clears its own callback props).
703
+ invalidate()
704
+ }
705
+
706
+ /**
707
+ * Shows [value] immediately with continuously positioned wheels (odometer
708
+ * style). Cancels any running roll. Intended to be called every frame.
709
+ */
710
+ fun setValue(value: Double) {
711
+ engine.setValue(value)
712
+ reportIntrinsicSize()
713
+ scheduleFrameIfNeeded()
714
+ invalidate()
715
+ }
716
+
717
+ /** Rolls every wheel to [value] (snaps on first show, duration 0 or "remove animations"). */
718
+ fun animateTo(value: Double) {
719
+ engine.setReduceMotion(animationsDisabled())
720
+ engine.animateTo(value, now())
721
+ reportIntrinsicSize()
722
+ scheduleFrameIfNeeded()
723
+ invalidate()
724
+ }
725
+
726
+ /**
727
+ * Shows the opening frame of a jackpot reveal for [value] ("$0.00" in the
728
+ * target's layout), waiting for [reveal].
729
+ */
730
+ fun holdReveal(value: Double) {
731
+ engine.holdReveal(value)
732
+ reportIntrinsicSize()
733
+ scheduleFrameIfNeeded()
734
+ invalidate()
735
+ }
736
+
737
+ /** Counts up from 0 to [value] and lands with a pop (snaps when animations are off). */
738
+ fun reveal(value: Double) {
739
+ engine.setReduceMotion(animationsDisabled())
740
+ engine.reveal(value, now())
741
+ reportIntrinsicSize()
742
+ scheduleFrameIfNeeded()
743
+ invalidate()
744
+ reportMilestones(0)
745
+ // Snapped (animations off / duration 0): the reveal is over before it began.
746
+ if (!engine.isRevealing()) onRevealEnd?.invoke()
747
+ }
748
+
749
+ /** Re-sends the last reported intrinsic size (e.g. after a listener was attached). */
750
+ fun resendIntrinsicSize() {
751
+ if (lastReportedWidth < 0f) return
752
+ onIntrinsicSizeChange?.invoke(lastReportedWidth, lastReportedHeight)
753
+ }
754
+
755
+ override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
756
+ super.onSizeChanged(w, h, oldw, oldh)
757
+ // The shrink-to-fit scale depends on the width; it is re-evaluated in onDraw().
758
+ invalidate()
759
+ }
760
+
761
+ override fun onDetachedFromWindow() {
762
+ stopAnimation()
763
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
764
+ context.contentResolver.unregisterContentObserver(animatorScaleObserver)
765
+ }
766
+ super.onDetachedFromWindow()
767
+ }
768
+
769
+ override fun onAttachedToWindow() {
770
+ super.onAttachedToWindow()
771
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
772
+ animatorScale = -1f
773
+ context.contentResolver.registerContentObserver(
774
+ Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE), false, animatorScaleObserver,
775
+ )
776
+ }
777
+ scheduleFrameIfNeeded()
778
+ }
779
+
780
+ override fun onConfigurationChanged(newConfig: Configuration?) {
781
+ super.onConfigurationChanged(newConfig)
782
+ // The paints resolve the theme's text color and the system font scale when
783
+ // they are built; a light/dark switch or a text-size change rebuilds them.
784
+ rebuildFonts()
785
+ }
786
+
787
+ // endregion
788
+
789
+ // region Frame loop
790
+
791
+ private fun now(): Double = SystemClock.uptimeMillis() / 1000.0
792
+
793
+ private fun scheduleFrameIfNeeded() {
794
+ if (!frameScheduled && engine.needsFrames()) {
795
+ frameScheduled = true
796
+ Choreographer.getInstance().postFrameCallback(frameCallback)
797
+ }
798
+ }
799
+
800
+ /**
801
+ * The animator duration scale on API < 33, read once and refreshed by
802
+ * [animatorScaleObserver] (a settings query per `animateTo` was a binder
803
+ * call on every value update). -1 = not read yet.
804
+ */
805
+ private var animatorScale = -1f
806
+ private val animatorScaleObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
807
+ override fun onChange(selfChange: Boolean) {
808
+ animatorScale = -1f
809
+ }
810
+ }
811
+
812
+ /** True when the user removed animations (Android's animator scale is 0), the equivalent of Reduce Motion. */
813
+ private fun animationsDisabled(): Boolean {
814
+ val scale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
815
+ ValueAnimator.getDurationScale()
816
+ } else {
817
+ if (animatorScale < 0f) {
818
+ animatorScale = Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
819
+ }
820
+ animatorScale
821
+ }
822
+ return scale <= 0f
823
+ }
824
+
825
+ /** Reused per frame so the JNI hop never allocates (room for far more wheels than the engine's 18), then the text slots. */
826
+ private val frameBuffer = DoubleArray(4 + 13 * 32 + 4 * TEXT_SLOTS + 2)
827
+
828
+ // The decimal columns laid out now (more than the format's while dropped
829
+ // ones close) and the decimal separator's factor.
830
+ private var displayFractionDigits = 0
831
+ private var decimalFactor = 1.0
832
+
833
+ // Each text slot's swap (prefix, suffix, grouping, decimal): the text
834
+ // leaving, and the engine's clocks for it.
835
+ private val leavingText = arrayOfNulls<String>(TEXT_SLOTS)
836
+ private val textGrow = DoubleArray(TEXT_SLOTS) { 1.0 }
837
+ private val textFocus = DoubleArray(TEXT_SLOTS) { 1.0 }
838
+ private val textBlurOut = DoubleArray(TEXT_SLOTS) { 1.0 }
839
+ private val textActive = BooleanArray(TEXT_SLOTS)
840
+
841
+ /** Pulls the engine's render state into reusable [Wheel] objects (no per-frame allocation once warm). */
842
+ private fun syncFromEngine() {
843
+ val f = frameBuffer
844
+ if (engine.frameInto(f) < 0) return
845
+ signFactor = f[0]
846
+ loadingProgress = f[1].toFloat()
847
+ revealScale = f[2].toFloat()
848
+ val count = f[3].toInt()
849
+ while (wheels.size < count) wheels.add(Wheel())
850
+ while (wheels.size > count) wheels.removeAt(wheels.size - 1)
851
+ for (i in 0 until count) {
852
+ val base = 4 + i * 13
853
+ val w = wheels[i]
854
+ w.position = f[base]
855
+ w.width = f[base + 1]
856
+ w.linear = f[base + 2] != 0.0
857
+ w.blankZero = f[base + 3] != 0.0
858
+ w.fromGlyph = f[base + 4]
859
+ w.toGlyph = f[base + 5]
860
+ w.blend = f[base + 6]
861
+ w.fromAbove = f[base + 7] != 0.0
862
+ w.flash = f[base + 8]
863
+ w.flashUp = f[base + 9] != 0.0
864
+ w.focus = f[base + 10]
865
+ w.grow = f[base + 11]
866
+ w.blurOut = f[base + 12]
867
+ }
868
+ val text = 4 + count * 13
869
+ for (slot in 0 until TEXT_SLOTS) {
870
+ textGrow[slot] = f[text + slot * 4]
871
+ textFocus[slot] = f[text + slot * 4 + 1]
872
+ textBlurOut[slot] = f[text + slot * 4 + 2]
873
+ textActive[slot] = f[text + slot * 4 + 3] != 0.0
874
+ if (!textActive[slot]) leavingText[slot] = null
875
+ }
876
+ displayFractionDigits = f[text + TEXT_SLOTS * 4].toInt()
877
+ decimalFactor = f[text + TEXT_SLOTS * 4 + 1]
878
+ }
879
+
880
+ // endregion
881
+
882
+ // region Typography
883
+
884
+ private fun rebuildFonts() {
885
+ fonts = FontSet(typography)
886
+ warmSwapMasks()
887
+ fontScale = 1f
888
+ if (engine.hasShownValue()) reportIntrinsicSize()
889
+ invalidate()
890
+ }
891
+
892
+ /**
893
+ * Renders the numeric transition's glyph masks, every digit at every blur
894
+ * level, on a background thread before they are needed. Made on demand, a
895
+ * change's first frames each paid for a few software blurs on the UI
896
+ * thread and ran late; iOS warms its images the same way.
897
+ */
898
+ private fun warmSwapMasks() {
899
+ if (timing.transition != Transition.NUMERIC) return
900
+ val set = fonts
901
+ WarmExecutor.execute {
902
+ for (digit in 0..9) for (level in 0..NUMERIC_BLUR_LEVELS) set.blurred(digit, level)
903
+ }
904
+ }
905
+
906
+ /** One background thread for warming glyph masks, shared by every view. */
907
+ private object WarmExecutor : java.util.concurrent.Executor {
908
+ private val pool = java.util.concurrent.Executors.newSingleThreadExecutor { r -> Thread(r, "NitroNumberWarm").apply { isDaemon = true; priority = Thread.MIN_PRIORITY } }
909
+ override fun execute(command: Runnable) = pool.execute(command)
910
+ }
911
+
912
+ /**
913
+ * Shrink-to-fit scale for the current width and the content as it is drawn
914
+ * *right now* (including half-appeared wheels): the amount shrinks and grows
915
+ * continuously in step with the roll and never overflows.
916
+ */
917
+ private fun updateFontScale(contentWidth: Float) {
918
+ var scale = 1f
919
+ if (typography.adjustsFontSizeToFit && width > 0 && contentWidth > width) {
920
+ scale = max(min(1f, typography.minimumFontScale), width / contentWidth)
921
+ }
922
+ fontScale = scale
923
+ }
924
+
925
+ // endregion
926
+
927
+ // region Layout
928
+
929
+ private class Element {
930
+ var wheelIndex = -1 // -1 for glyph elements
931
+ var text: String? = null
932
+ var role = GlyphRole.DIGIT
933
+ var width = 0f
934
+ var fullWidth = 0f
935
+ var factor = 0.0
936
+ /** A text slot swapping: its slot, the text leaving, and the side it keeps to (-1 left, 0 centre, 1 right). */
937
+ var slot = -1
938
+ var fromText: String? = null
939
+ var anchor = 1
940
+ }
941
+
942
+ /** A list of pooled [Element]s: filling it allocates nothing once it has grown to the run's length. */
943
+ private class ElementList {
944
+ private val items = ArrayList<Element>()
945
+ var size = 0
946
+ private set
947
+
948
+ fun clear() {
949
+ size = 0
950
+ }
951
+
952
+ fun next(): Element {
953
+ if (size == items.size) items.add(Element())
954
+ return items[size++]
955
+ }
956
+
957
+ operator fun get(index: Int): Element = items[index]
958
+
959
+ fun totalWidth(): Float {
960
+ var total = 0f
961
+ for (i in 0 until size) total += items[i].width
962
+ return total
963
+ }
964
+ }
965
+
966
+ /** Lays the run out into [out] (emptied first). */
967
+ private fun buildElements(fonts: FontSet, wheels: List<Wheel>, signFactor: Double, out: ElementList, animated: Boolean = true) {
968
+ out.clear()
969
+ val fd = if (animated) displayFractionDigits else format.fractionDigits
970
+ val decimal = if (animated) decimalFactor else 1.0
971
+
972
+ fun addGlyph(text: String, role: GlyphRole, factor: Double, slot: Int = -1, anchor: Int = 1) {
973
+ if (factor <= 0.0) return
974
+ // A slot swapping its text: the width eases from the old text's to the new one's.
975
+ val from = if (animated && slot >= 0 && textActive[slot]) leavingText[slot] else null
976
+ if (from != null && from != text) {
977
+ val g = textGrow[slot].coerceIn(0.0, 1.0)
978
+ val fromWidth = fonts.width(from, role)
979
+ val toWidth = if (text.isEmpty()) 0f else fonts.width(text, role)
980
+ val e = out.next()
981
+ e.wheelIndex = -1
982
+ e.text = text
983
+ e.role = role
984
+ e.width = ((fromWidth + (toWidth - fromWidth) * g) * factor).toFloat()
985
+ e.fullWidth = max(fromWidth, toWidth)
986
+ e.factor = factor
987
+ e.slot = slot
988
+ e.fromText = from
989
+ e.anchor = anchor
990
+ return
991
+ }
992
+ if (text.isEmpty()) return
993
+ val width = fonts.width(text, role)
994
+ val e = out.next()
995
+ e.wheelIndex = -1
996
+ e.text = text
997
+ e.role = role
998
+ e.width = (width * factor).toFloat()
999
+ e.fullWidth = width
1000
+ e.factor = factor
1001
+ e.slot = -1
1002
+ e.fromText = null
1003
+ e.anchor = 1
1004
+ }
1005
+
1006
+ // Under a right-to-left layout the prefix belongs at the start edge - the
1007
+ // right - and the suffix at the end, while the digits stay a left-to-right
1008
+ // run: a number reads the same way in every script. So the run is laid out
1009
+ // block by block in mirror order, each block keeping its own order, and the
1010
+ // space an affix keeps against the digits stays against them: " USD" after
1011
+ // the number is "USD " before it.
1012
+ val rtl = isRtl
1013
+ if (affixBlocksDirty || affixRtl != rtl) updateAffixBlocks(rtl)
1014
+ // A swapping affix keeps to the digits' side; a separator is centred.
1015
+ if (rtl) {
1016
+ addGlyph(suffixInk, GlyphRole.SUFFIX, 1.0, TEXT_SUFFIX, anchor = 1)
1017
+ addGlyph(suffixGap, GlyphRole.SUFFIX, 1.0)
1018
+ } else {
1019
+ // Sign first, then the currency prefix: "-$1,234.50".
1020
+ addGlyph("-", GlyphRole.DIGIT, signFactor)
1021
+ addGlyph(prefixInk, GlyphRole.PREFIX, 1.0, TEXT_PREFIX, anchor = 1)
1022
+ }
1023
+ for (power in wheels.indices.reversed()) {
1024
+ val wheel = wheels[power]
1025
+ if (wheel.width > 0.0) {
1026
+ val e = out.next()
1027
+ e.wheelIndex = power
1028
+ e.text = null
1029
+ e.role = GlyphRole.DIGIT
1030
+ e.width = (fonts.digitWidth * wheel.width).toFloat()
1031
+ e.fullWidth = fonts.digitWidth
1032
+ e.factor = wheel.width
1033
+ e.slot = -1
1034
+ e.fromText = null
1035
+ }
1036
+ if (power > fd && (power - fd) % 3 == 0) addGlyph(format.groupingSeparator, GlyphRole.DIGIT, wheel.width, TEXT_GROUPING, anchor = 0)
1037
+ if (fd > 0 && power == fd) addGlyph(format.decimalSeparator, GlyphRole.DIGIT, decimal, TEXT_DECIMAL, anchor = 0)
1038
+ }
1039
+ if (rtl) {
1040
+ addGlyph(prefixGap, GlyphRole.PREFIX, 1.0)
1041
+ addGlyph(prefixInk, GlyphRole.PREFIX, 1.0, TEXT_PREFIX, anchor = -1)
1042
+ addGlyph("-", GlyphRole.DIGIT, signFactor)
1043
+ } else {
1044
+ addGlyph(suffixInk, GlyphRole.SUFFIX, 1.0, TEXT_SUFFIX, anchor = -1)
1045
+ }
1046
+ }
1047
+
1048
+ private fun updateAffixBlocks(rtl: Boolean) {
1049
+ val prefix = if (rtl) splitAffix(format.prefix, spaceAtEnd = true) else Pair(format.prefix, "")
1050
+ val suffix = if (rtl) splitAffix(format.suffix, spaceAtEnd = false) else Pair(format.suffix, "")
1051
+ prefixInk = prefix.first
1052
+ prefixGap = prefix.second
1053
+ suffixInk = suffix.first
1054
+ suffixGap = suffix.second
1055
+ affixRtl = rtl
1056
+ affixBlocksDirty = false
1057
+ }
1058
+
1059
+ /** Whether this view is laid out right-to-left. The hybrid sets it from the `rightToLeft` prop. */
1060
+ val isRtl: Boolean get() = layoutDirection == LAYOUT_DIRECTION_RTL
1061
+
1062
+ /**
1063
+ * `AUTO` resolved: in a box that hugs the figure, the edge the box kept the
1064
+ * last time it changed width (see [learnAnchor]), else the start edge of
1065
+ * the layout direction. The rest are already absolute.
1066
+ */
1067
+ private val resolvedAlignment: Alignment
1068
+ get() {
1069
+ if (alignment != Alignment.AUTO) return alignment
1070
+ val anchor = autoAnchor
1071
+ if (anchor != null && hugsFigure()) return anchor
1072
+ return if (isRtl) Alignment.RIGHT else Alignment.LEFT
1073
+ }
1074
+
1075
+ /**
1076
+ * A box that hugs the figure is as wide as the figure at rest, so its
1077
+ * alignment only shows while the figure grows or shrinks: the box takes the
1078
+ * new width at once and the digits open or close inside it. Which edge they
1079
+ * keep to is the edge the parent keeps the box to: a figure at the end of a
1080
+ * row (`justifyContent: 'space-between'`) keeps its right edge, and
1081
+ * start-aligned it jumped a digit to the left and then opened a gap after
1082
+ * its prefix. So `AUTO` follows the box: the edge that stayed put when its
1083
+ * width last changed, both for a centred box.
1084
+ */
1085
+ private var autoAnchor: Alignment? = null
1086
+ private var laidLeft = Int.MIN_VALUE
1087
+ private var laidRight = Int.MIN_VALUE
1088
+
1089
+ /**
1090
+ * A size reported and not yet laid out by React: for a frame or two the box
1091
+ * still has the old width. Counted as hugging, or a shrinking figure fell
1092
+ * back to the start edge for those frames and flashed across the box.
1093
+ */
1094
+ private var awaitingLayout = false
1095
+
1096
+ private fun hugsFigure(): Boolean =
1097
+ lastReportedWidth > 0f && (awaitingLayout || abs(width - lastReportedWidth * density) <= density)
1098
+
1099
+ private fun learnAnchor(left: Int, right: Int) {
1100
+ val previousLeft = laidLeft
1101
+ val previousRight = laidRight
1102
+ laidLeft = left
1103
+ laidRight = right
1104
+ if (previousLeft == Int.MIN_VALUE || right - left == previousRight - previousLeft) return
1105
+ val tolerance = 1
1106
+ val dl = left - previousLeft
1107
+ val dr = right - previousRight
1108
+ autoAnchor = when {
1109
+ abs(dl) <= tolerance -> Alignment.LEFT
1110
+ abs(dr) <= tolerance -> Alignment.RIGHT
1111
+ abs(dl + dr) <= 2 * tolerance -> Alignment.CENTER
1112
+ else -> autoAnchor
1113
+ }
1114
+ }
1115
+
1116
+ override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
1117
+ super.onLayout(changed, left, top, right, bottom)
1118
+ if (awaitingLayout && abs((right - left) - lastReportedWidth * density) <= density) awaitingLayout = false
1119
+ learnAnchor(left, right)
1120
+ }
1121
+
1122
+ override fun onRtlPropertiesChanged(layoutDirection: Int) {
1123
+ super.onRtlPropertiesChanged(layoutDirection)
1124
+ invalidate()
1125
+ }
1126
+
1127
+ /**
1128
+ * Splits an affix from the space it keeps against the digits - a prefix's
1129
+ * trailing run, a suffix's leading one - as (ink, gap). An affix that is all
1130
+ * space is one block.
1131
+ */
1132
+ private fun splitAffix(text: String, spaceAtEnd: Boolean): Pair<String, String> {
1133
+ val isSpace = { c: Char -> c == ' ' || c == '\u00A0' || c == '\u2009' || c == '\u202F' }
1134
+ var n = 0
1135
+ while (n < text.length && isSpace(if (spaceAtEnd) text[text.length - 1 - n] else text[n])) n++
1136
+ if (n == 0 || n == text.length) return Pair(text, "")
1137
+ return if (spaceAtEnd) Pair(text.substring(0, text.length - n), text.substring(text.length - n))
1138
+ else Pair(text.substring(n), text.substring(0, n))
1139
+ }
1140
+
1141
+ private fun settledWidth(): Float {
1142
+ val count = engine.settledPowerCount()
1143
+ while (settledWheels.size < count) settledWheels.add(Wheel())
1144
+ while (settledWheels.size > count) settledWheels.removeAt(settledWheels.size - 1)
1145
+ buildElements(fonts, settledWheels, if (engine.settledNegative()) 1.0 else 0.0, settledElements, animated = false)
1146
+ return settledElements.totalWidth()
1147
+ }
1148
+
1149
+ /** Formats the target the way it is displayed, for TalkBack. */
1150
+ private fun accessibleText(): String {
1151
+ val fd = format.fractionDigits
1152
+ val sb = StringBuilder()
1153
+ if (engine.settledNegative()) sb.append('-')
1154
+ sb.append(format.prefix)
1155
+ for (power in engine.settledPowerCount() - 1 downTo 0) {
1156
+ sb.append(engine.targetDigit(power))
1157
+ if (power > fd && (power - fd) % 3 == 0) sb.append(format.groupingSeparator)
1158
+ if (fd > 0 && power == fd) sb.append(format.decimalSeparator)
1159
+ }
1160
+ sb.append(format.suffix)
1161
+ return sb.toString()
1162
+ }
1163
+
1164
+ // TalkBack reads the settled figure when it asks for it, so a value update
1165
+ // (which can come every frame) formats nothing.
1166
+ override fun getContentDescription(): CharSequence? {
1167
+ if (!engine.hasShownValue()) return null
1168
+ return if (loading) accessibleText() + ", loading" else accessibleText()
1169
+ }
1170
+
1171
+ /** A narrower settled size waiting for the current roll to finish before it is reported. */
1172
+ private var pendingSizeReport = false
1173
+
1174
+ private fun reportIntrinsicSize() {
1175
+ // A no-op unless an accessibility service is on; then a focused figure re-announces.
1176
+ sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED)
1177
+ // The reported size is always the full-size one: with shrink-to-fit the view
1178
+ // keeps its height and the scaled number is centred inside it when drawing.
1179
+ val widthDp = ceil(settledWidth() / density)
1180
+ val heightDp = ceil(fonts.lineHeight / density)
1181
+ if (abs(widthDp - lastReportedWidth) <= 0.01f && abs(heightDp - lastReportedHeight) <= 0.01f) {
1182
+ pendingSizeReport = false
1183
+ return
1184
+ }
1185
+ // Growing: report right away so React widens the box before the new digit has
1186
+ // fully appeared (the view is not clipped meanwhile). Shrinking mid-roll: keep
1187
+ // the wider box until the roll has finished, otherwise adjustsFontSizeToFit
1188
+ // would squeeze the still-rolling digits into the smaller box and the whole
1189
+ // amount would visibly shrink and grow back.
1190
+ if (lastReportedWidth > 0f && widthDp < lastReportedWidth && engine.isRolling()) {
1191
+ pendingSizeReport = true
1192
+ return
1193
+ }
1194
+ pendingSizeReport = false
1195
+ // Only a box that hugged the old size will follow the new one.
1196
+ awaitingLayout = lastReportedWidth > 0f && abs(width - lastReportedWidth * density) <= density
1197
+ lastReportedWidth = widthDp
1198
+ lastReportedHeight = heightDp
1199
+ onIntrinsicSizeChange?.invoke(widthDp, heightDp)
1200
+ }
1201
+
1202
+ // endregion
1203
+
1204
+ // region Drawing
1205
+
1206
+ override fun onDraw(canvas: Canvas) {
1207
+ super.onDraw(canvas)
1208
+ if (!engine.hasShownValue()) return
1209
+ syncFromEngine()
1210
+ val fonts = this.fonts
1211
+ val elements = frameElements
1212
+ buildElements(fonts, wheels, signFactor, elements)
1213
+ val total = elements.totalWidth()
1214
+ updateFontScale(total)
1215
+ val fit = fontScale
1216
+
1217
+ // Position the (scaled) content, then draw everything in unscaled font space.
1218
+ // The reveal's landing pop scales about the content's centre on top of the fit.
1219
+ var originX = when (resolvedAlignment) {
1220
+ Alignment.AUTO, Alignment.LEFT -> 0f
1221
+ Alignment.CENTER -> (width - total * fit) / 2f
1222
+ Alignment.RIGHT -> width - total * fit
1223
+ }
1224
+ var originY = (height - fonts.lineHeight * fit) / 2f
1225
+ val pop = revealScale
1226
+ if (pop != 1f) {
1227
+ originX += total * fit * (1f - pop) / 2f
1228
+ originY += fonts.lineHeight * fit * (1f - pop) / 2f
1229
+ }
1230
+ val scale = fit * pop
1231
+ val outer = canvas.save()
1232
+ canvas.translate(originX, originY)
1233
+ canvas.scale(scale, scale)
1234
+
1235
+ val dim = loadingProgress.coerceIn(0f, 1f)
1236
+ // Everything drawn in this layer is what the sweep gets composited onto.
1237
+ val layer = if (dim > 0f) canvas.saveLayer(-1f, -1f, total + 1f, fonts.lineHeight + 1f, null) else -1
1238
+ var x = 0f
1239
+ for (i in 0 until elements.size) {
1240
+ val element = elements[i]
1241
+ val text = element.text
1242
+ if (element.wheelIndex >= 0) {
1243
+ drawWheel(canvas, fonts, wheels[element.wheelIndex], x, element.width, originX, originY, scale)
1244
+ } else if (element.fromText != null) {
1245
+ drawTextSwap(canvas, fonts, element, x)
1246
+ } else if (text != null) {
1247
+ drawGlyph(canvas, fonts, text, element.role, x, element.width, element.fullWidth, element.factor)
1248
+ }
1249
+ x += element.width
1250
+ }
1251
+ if (dim > 0f) {
1252
+ drawShimmer(canvas, fonts, total, dim)
1253
+ canvas.restoreToCount(layer)
1254
+ }
1255
+ canvas.restoreToCount(outer)
1256
+ }
1257
+
1258
+ /**
1259
+ * A "shine" glint: a text-wide, slanted band that recolors the ink from the text
1260
+ * color to the highlight and back ([base, highlight, base] at 10/50/90 %),
1261
+ * composited SRC_ATOP so only the glyphs light up.
1262
+ */
1263
+ private fun drawShimmer(canvas: Canvas, fonts: FontSet, contentWidth: Float, dim: Float) {
1264
+ if (contentWidth <= 0f) return
1265
+ val base = fonts.digit.color
1266
+ val highlight = shimmer.color ?: defaultShimmerColor()
1267
+ val phase = engine.shimmerPhase(now(), shimmer.durationMs / 1000.0).toFloat()
1268
+ val progress = SHIMMER_SEED + (1f - SHIMMER_SEED) * phase
1269
+ // Core at width * (2p - 0.5): enters at the left edge, exits past the right.
1270
+ val startX = contentWidth * (2f * progress - 1f)
1271
+ var gradient = shimmerGradient
1272
+ if (gradient == null || shimmerGradientWidth != contentWidth || shimmerGradientBase != base || shimmerGradientHighlight != highlight) {
1273
+ gradient = LinearGradient(
1274
+ 0f, 0f, contentWidth, SHIMMER_SLANT * contentWidth,
1275
+ intArrayOf(base, highlight, base), floatArrayOf(0.1f, 0.5f, 0.9f), Shader.TileMode.CLAMP,
1276
+ )
1277
+ shimmerGradient = gradient
1278
+ shimmerGradientWidth = contentWidth
1279
+ shimmerGradientBase = base
1280
+ shimmerGradientHighlight = highlight
1281
+ shimmerPaint.shader = gradient
1282
+ }
1283
+ shimmerMatrix.setTranslate(startX, 0f)
1284
+ gradient.setLocalMatrix(shimmerMatrix)
1285
+ shimmerPaint.alpha = (dim * 255f).toInt().coerceIn(0, 255)
1286
+ canvas.drawRect(-1f, -1f, contentWidth + 1f, fonts.lineHeight + 1f, shimmerPaint)
1287
+ }
1288
+
1289
+ /** Default glint color: a near-background neutral so the ink "lights up". */
1290
+ private fun defaultShimmerColor(): Int {
1291
+ val night = (context.resources.configuration.uiMode and android.content.res.Configuration.UI_MODE_NIGHT_MASK) ==
1292
+ android.content.res.Configuration.UI_MODE_NIGHT_YES
1293
+ return if (night) 0xFF2B2E37.toInt() else 0xFFD6D9E1.toInt()
1294
+ }
1295
+
1296
+ private fun drawGlyph(canvas: Canvas, fonts: FontSet, text: String, role: GlyphRole, x: Float, width: Float, fullWidth: Float, factor: Double) {
1297
+ if (width <= 0f) return
1298
+ val paint = fonts.paint(role)
1299
+ // A full cell needs no clip: the clip only matters while it opens or
1300
+ // closes. Skipping it saves the render thread a save, a clip and a
1301
+ // restore per separator and affix on every frame.
1302
+ val full = width >= fullWidth
1303
+ if (!full) canvas.save()
1304
+ // An opening or closing cell (a separator, the sign) keeps its glyph whole
1305
+ // against the text it joins and fades with the cell; see [openingAlpha].
1306
+ if (!full) canvas.clipRect(x + width - fullWidth, 0f, x + width, fonts.lineHeight)
1307
+ // The paint is shared and its alpha is the ink colour's: scale it for this
1308
+ // draw and put it back. Left faded, the next frame's digits inherited it
1309
+ // (a separator easing in drew them invisible), and set to 255 a
1310
+ // translucent colour turned opaque.
1311
+ val ink = paint.alpha
1312
+ paint.alpha = (openingAlpha(factor) * ink).toInt().coerceIn(0, 255)
1313
+ val left = x + width - fullWidth
1314
+ val baseline = fonts.baseline(role, text, 0f)
1315
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
1316
+ glyphPositions = fonts.shaped(text, role).draw(canvas, left, baseline, paint, glyphPositions)
1317
+ } else {
1318
+ canvas.drawText(text, left, baseline, paint)
1319
+ }
1320
+ paint.alpha = ink
1321
+ if (!full) canvas.restore()
1322
+ }
1323
+
1324
+ /** Scratch for [ShapedText.draw]: positions offset to where a glyph run lands. */
1325
+ private var glyphPositions = FloatArray(16)
1326
+
1327
+ /**
1328
+ * [originX], [originY] and [scale] are the content transform already on the
1329
+ * canvas, so the strip window can be landed on whole device pixels.
1330
+ */
1331
+ private fun drawWheel(canvas: Canvas, fonts: FontSet, wheel: Wheel, x: Float, width: Float, originX: Float, originY: Float, scale: Float) {
1332
+ if (width <= 0f) return
1333
+ val lineHeight = fonts.lineHeight
1334
+ if (wheel.blend < 1.0 || wheel.focus < 1.0 || wheel.grow < 1.0) {
1335
+ drawSwap(canvas, fonts, wheel, x, width, originX, originY, scale)
1336
+ return
1337
+ }
1338
+ // A settled-width wheel is a window onto the shared strip (the strip has
1339
+ // no per-wheel alpha, so a wheel still growing or shrinking, and any
1340
+ // canvas without a GPU, which cannot draw a hardware bitmap, draws its
1341
+ // two glyphs the old way).
1342
+ if (wheel.width >= 1.0 && canvas.isHardwareAccelerated) {
1343
+ val strip = fonts.strip(wheel.blankZero)
1344
+ if (strip != null) {
1345
+ // An interior wheel wraps modulo 10, negatives included (rolling down
1346
+ // through 0 shows 9); a linear wheel never wraps and uses -1 for the
1347
+ // blank slot. Either way the window lands inside the strip.
1348
+ val position = if (wheel.linear) wheel.position.coerceIn(-1.0, 10.0) else wrap10(wheel.position)
1349
+ var tx = x + width - fonts.digitWidth
1350
+ var ty = (-(position + 1) * lineHeight).toFloat()
1351
+ if (scale == 1f && position == floor(position)) {
1352
+ // At rest, land the window on whole device pixels: composited at a
1353
+ // fractional offset (a centred number, a fractional digit width) the
1354
+ // layer is resampled and a small digit goes soft. In motion the
1355
+ // fractional offsets are the motion, and stay.
1356
+ tx = Math.round(originX + tx) - originX
1357
+ ty = Math.round(originY + ty) - originY
1358
+ }
1359
+ if (position == floor(position)) {
1360
+ // At rest the window shows exactly one slot of the strip: draw that
1361
+ // slot alone, one operation where the window took five (save, clip,
1362
+ // translate, the strip, restore). The same bitmap on the same
1363
+ // pixels; the clip only ever cut transparent rows. With ~50 numbers
1364
+ // on screen the render thread replays these for every resting digit
1365
+ // on every frame, and most digits of a busy screen are resting.
1366
+ val slot = (position + 1).toInt()
1367
+ val lh = lineHeight
1368
+ stripSrc.set(0, Math.round(slot * lh), strip.bitmap.width, Math.round((slot + 1) * lh))
1369
+ val top = ty + slot * lh
1370
+ stripDst.set(tx, top, tx + strip.bitmap.width, top + (stripSrc.bottom - stripSrc.top))
1371
+ canvas.drawBitmap(strip.bitmap, stripSrc, stripDst, stripPaint)
1372
+ flashColor(wheel)?.let { color ->
1373
+ if (flashStripColor != color) {
1374
+ flashStripPaint.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN)
1375
+ flashStripColor = color
1376
+ }
1377
+ flashStripPaint.alpha = (wheel.flash * 255).toInt().coerceIn(0, 255)
1378
+ canvas.drawBitmap(strip.bitmap, stripSrc, stripDst, flashStripPaint)
1379
+ }
1380
+ return
1381
+ }
1382
+ canvas.save()
1383
+ canvas.clipRect(x, 0f, x + width, lineHeight)
1384
+ canvas.translate(tx, ty)
1385
+ if (strip.node != null) canvas.drawRenderNode(strip.node) else canvas.drawBitmap(strip.bitmap, 0f, 0f, stripPaint)
1386
+ // The change flash rides the roll: the strip once more, in the tint, at the same offset.
1387
+ flashColor(wheel)?.let { color ->
1388
+ if (flashStripColor != color) {
1389
+ flashStripPaint.colorFilter = PorterDuffColorFilter(color, PorterDuff.Mode.SRC_IN)
1390
+ flashStripColor = color
1391
+ }
1392
+ flashStripPaint.alpha = (wheel.flash * 255).toInt().coerceIn(0, 255)
1393
+ canvas.drawBitmap(strip.bitmap, 0f, 0f, flashStripPaint)
1394
+ }
1395
+ canvas.restore()
1396
+ return
1397
+ }
1398
+ }
1399
+ val baseline = fonts.baseline(GlyphRole.DIGIT, "0", 0f)
1400
+ canvas.save()
1401
+ // The roll's window, the whole digit wide: a column still opening or
1402
+ // closing is not cut to its width (the glyph read as a sliver of its right
1403
+ // edge, a ")" of a 0 rolling past), it overhangs the cell's far side, faded.
1404
+ canvas.clipRect(x + width - fonts.digitWidth, 0f, x + width, lineHeight)
1405
+ val base = floor(wheel.position)
1406
+ val fraction = (wheel.position - base).toFloat()
1407
+ val index = base.toInt()
1408
+ val columnLeft = x + width - fonts.digitWidth
1409
+ fun glyphs(paint: TextPaint, alpha: Float) {
1410
+ // Scaled from the ink colour's alpha and put back (see [drawGlyph]).
1411
+ val ink = paint.alpha
1412
+ paint.alpha = (alpha * ink).toInt().coerceIn(0, 255)
1413
+ glyphAt(index, wheel)?.let { glyph ->
1414
+ canvas.drawText(glyph, columnLeft + (fonts.digitWidth - fonts.width(glyph, GlyphRole.DIGIT)) / 2f, baseline - fraction * lineHeight, paint)
1415
+ }
1416
+ if (fraction > 0.0001f) {
1417
+ glyphAt(index + 1, wheel)?.let { glyph ->
1418
+ canvas.drawText(glyph, columnLeft + (fonts.digitWidth - fonts.width(glyph, GlyphRole.DIGIT)) / 2f, baseline + (1f - fraction) * lineHeight, paint)
1419
+ }
1420
+ }
1421
+ paint.alpha = ink
1422
+ }
1423
+ val opening = openingAlpha(wheel.width).toFloat()
1424
+ glyphs(fonts.digit, opening)
1425
+ // The change flash rides the roll: the same glyphs again, in the tint.
1426
+ flashColor(wheel)?.let { color -> glyphs(fonts.tinted(color), wheel.flash.toFloat() * opening) }
1427
+ canvas.restore()
1428
+ }
1429
+
1430
+ /**
1431
+ * The numeric transition: the leaving glyph and the arriving one, each
1432
+ * scaled about its centre, offset along the axis, faded, and cross-faded
1433
+ * with its blurred bitmap as it goes out of, or comes into, focus; the
1434
+ * geometry is `RollingEngine.hpp`'s. Not clipped to the cell: a blurred
1435
+ * glyph's haze reaches past it, and cut at the cell it read as a pale box
1436
+ * around the digit. With a change flash on, the pair is drawn again in
1437
+ * the tint at the flash's opacity: the ink mixed towards the tint.
1438
+ */
1439
+ private fun drawSwap(canvas: Canvas, fonts: FontSet, wheel: Wheel, x: Float, width: Float, originX: Float, originY: Float, scale: Float) {
1440
+ drawSwapPair(canvas, fonts, wheel, x, width, fonts.digit, 1f, originX, originY, scale)
1441
+ flashColor(wheel)?.let { color -> drawSwapPair(canvas, fonts, wheel, x, width, fonts.tinted(color), wheel.flash.toFloat(), originX, originY, scale) }
1442
+ }
1443
+
1444
+ /**
1445
+ * [originX], [originY] and [scale] are the content transform on the canvas.
1446
+ * Each glyph's bitmap is landed on whole device pixels: a sharp bitmap
1447
+ * drawn between pixels is resampled, and as it crept along the spring's
1448
+ * tail it cycled crisp and soft once per pixel of travel, a shimmer that a
1449
+ * blurred copy hides and a lightly blurred one does not. Landed, the last
1450
+ * swap frame is pixel for pixel the strip that takes over from it.
1451
+ */
1452
+ private fun drawSwapPair(canvas: Canvas, fonts: FontSet, wheel: Wheel, x: Float, width: Float, paint: TextPaint, opacity: Float, originX: Float, originY: Float, scale: Float) {
1453
+ val lineHeight = fonts.lineHeight
1454
+ // The position clock overshoots 1 (a spring); only the offsets follow it there.
1455
+ val b = wheel.blend.toFloat()
1456
+ val gRaw = wheel.grow.toFloat().coerceIn(0f, 1f)
1457
+ // Within a percent of full size the glyph is drawn at full size: scaled by
1458
+ // 0.995 it is resampled all over, and the last percent is a pixel.
1459
+ val g = if (gRaw > 0.99f) 1f else gRaw
1460
+ val f = wheel.focus.toFloat().coerceIn(0f, 1f)
1461
+ val d = if (wheel.fromAbove) 1f else -1f
1462
+ val offset = lineHeight * NUMERIC_OFFSET
1463
+ val cx = x + width - fonts.digitWidth / 2f
1464
+ val cy = lineHeight / 2f
1465
+ val column = wheel.width.toFloat().coerceIn(0f, 1f) * opacity
1466
+ val from = wheel.fromGlyph.toInt()
1467
+ val to = wheel.toGlyph.toInt()
1468
+ // The bitmap's top-left sits at (centre - digitWidth / 2 - pad); land that on a pixel.
1469
+ val cornerX = fonts.digitWidth / 2f + fonts.blurPad
1470
+ val cornerY = lineHeight / 2f + fonts.blurPad
1471
+ fun snapX(c: Float): Float = (Math.round(originX + (c - cornerX) * scale) - originX) / scale + cornerX
1472
+ fun snapY(c: Float): Float = (Math.round(originY + (c - cornerY) * scale) - originY) / scale + cornerY
1473
+ if (from >= 0) {
1474
+ drawSwapGlyph(canvas, fonts, paint, from % 10, snapX(cx), snapY(cy + d * offset * b), 1f - (1f - NUMERIC_SCALE) * g, (1f - g) * column, wheel.blurOut.toFloat().coerceIn(0f, 1f))
1475
+ }
1476
+ if (to >= 0) {
1477
+ drawSwapGlyph(canvas, fonts, paint, to % 10, snapX(cx), snapY(cy - d * offset * (1f - b)), NUMERIC_SCALE + (1f - NUMERIC_SCALE) * g, g * column, 1f - f)
1478
+ }
1479
+ }
1480
+
1481
+ /**
1482
+ * One glyph of a swap: the two blur levels nearest [blur] (of
1483
+ * [NUMERIC_BLUR_LEVELS], level 0 the sharp text), cross-faded by where
1484
+ * between them it falls, so a glyph half out of focus is half-blurred
1485
+ * rather than a sharp glyph half-hidden in a fully blurred one, which read
1486
+ * as a digit inside a glow.
1487
+ */
1488
+ private fun drawSwapGlyph(canvas: Canvas, fonts: FontSet, paint: TextPaint, digitIndex: Int, cx: Float, cy: Float, scale: Float, alpha: Float, blur: Float) {
1489
+ if (alpha <= 0.002f) return
1490
+ val text = DIGITS[digitIndex]
1491
+ val lineHeight = fonts.lineHeight
1492
+ val x = blur.coerceIn(0f, 1f) * NUMERIC_BLUR_LEVELS
1493
+ val lo = min(NUMERIC_BLUR_LEVELS, floor(x).toInt())
1494
+ val hi = min(NUMERIC_BLUR_LEVELS, lo + 1)
1495
+ val w = if (lo == NUMERIC_BLUR_LEVELS) 0f else x - lo
1496
+ // The two levels composite "over", which is not additive: drawn at
1497
+ // (1 - w) and w they came out only 75 % opaque half way between levels,
1498
+ // and the digit pulsed paler and darker at every level crossing. The
1499
+ // upper one is drawn at its share, w, of the opacity, and the lower one
1500
+ // at whatever makes the pair composite to the whole of it.
1501
+ val hiAlpha = alpha * w
1502
+ val loAlpha = if (hiAlpha >= 0.999f) 0f else alpha * (1f - w) / (1f - hiAlpha)
1503
+ canvas.save()
1504
+ canvas.translate(cx, cy)
1505
+ canvas.scale(scale, scale)
1506
+ for ((level, levelAlpha) in arrayOf(lo to loAlpha, hi to hiAlpha)) {
1507
+ if (levelAlpha <= 0.002f) continue
1508
+ val mask = fonts.blurred(digitIndex, level)
1509
+ if (mask == null) {
1510
+ // No font metrics yet: the text itself.
1511
+ val ink = paint.alpha
1512
+ paint.alpha = (levelAlpha * ink).toInt().coerceIn(0, 255)
1513
+ canvas.drawText(text, -fonts.width(text, GlyphRole.DIGIT) / 2f, fonts.baseline(GlyphRole.DIGIT, text, 0f) - lineHeight / 2f, paint)
1514
+ paint.alpha = ink
1515
+ } else {
1516
+ // An alpha mask draws in the paint's colour; the ink's own alpha scales with the level's.
1517
+ blurPaint.color = paint.color
1518
+ blurPaint.alpha = (levelAlpha * (paint.color ushr 24)).toInt().coerceIn(0, 255)
1519
+ canvas.drawBitmap(mask, -fonts.digitWidth / 2f - fonts.blurPad, -lineHeight / 2f - fonts.blurPad, blurPaint)
1520
+ }
1521
+ }
1522
+ canvas.restore()
1523
+ }
1524
+
1525
+ /**
1526
+ * A prefix, suffix or separator changing its text, drawn like a swapping
1527
+ * digit without the travel: the old text blurs and fades out as the new one
1528
+ * comes into focus, each kept to the side of the cell that faces the digits
1529
+ * (a separator centred). Not clipped: the blur's haze reaches past the cell.
1530
+ */
1531
+ private fun drawTextSwap(canvas: Canvas, fonts: FontSet, element: Element, x: Float) {
1532
+ val slot = element.slot
1533
+ val g = textGrow[slot].toFloat().coerceIn(0f, 1f)
1534
+ val opening = openingAlpha(element.factor).toFloat()
1535
+ fun left(text: String): Float {
1536
+ val w = fonts.width(text, element.role)
1537
+ return when (element.anchor) {
1538
+ -1 -> x
1539
+ 0 -> x + (element.width - w) / 2f
1540
+ else -> x + element.width - w
1541
+ }
1542
+ }
1543
+ element.fromText?.let { from ->
1544
+ if (from.isNotEmpty()) drawBlurredText(canvas, fonts, from, element.role, left(from), (1f - g) * opening, textBlurOut[slot].toFloat())
1545
+ }
1546
+ element.text?.let { to ->
1547
+ if (to.isNotEmpty()) drawBlurredText(canvas, fonts, to, element.role, left(to), g * opening, 1f - textFocus[slot].toFloat())
1548
+ }
1549
+ }
1550
+
1551
+ /** [text] at [left], faded to [alpha] and blurred by [blur] (0…1), the two nearest levels cross-faded as a digit's are. */
1552
+ private fun drawBlurredText(canvas: Canvas, fonts: FontSet, text: String, role: GlyphRole, left: Float, alpha: Float, blur: Float) {
1553
+ if (alpha <= 0.002f) return
1554
+ val levels = blur.coerceIn(0f, 1f) * NUMERIC_BLUR_LEVELS
1555
+ val lo = min(NUMERIC_BLUR_LEVELS, floor(levels).toInt())
1556
+ val hi = min(NUMERIC_BLUR_LEVELS, lo + 1)
1557
+ val w = if (lo == NUMERIC_BLUR_LEVELS) 0f else levels - lo
1558
+ val hiAlpha = alpha * w
1559
+ val loAlpha = if (hiAlpha >= 0.999f) 0f else alpha * (1f - w) / (1f - hiAlpha)
1560
+ val paint = fonts.paint(role)
1561
+ val pad = fonts.blurPad.toFloat()
1562
+ for ((level, levelAlpha) in arrayOf(lo to loAlpha, hi to hiAlpha)) {
1563
+ if (levelAlpha <= 0.002f) continue
1564
+ val mask = fonts.blurredText(text, role, level) ?: continue
1565
+ blurPaint.color = paint.color
1566
+ blurPaint.alpha = (levelAlpha * (paint.color ushr 24)).toInt().coerceIn(0, 255)
1567
+ canvas.drawBitmap(mask, left - pad, -pad, blurPaint)
1568
+ }
1569
+ }
1570
+
1571
+ /**
1572
+ * Opacity of a cell [width] open (0…1). Squared, so while a glyph
1573
+ * overhangs a narrow cell the overlap stays faint.
1574
+ */
1575
+ private fun openingAlpha(width: Double): Double {
1576
+ val w = width.coerceIn(0.0, 1.0)
1577
+ return w * w
1578
+ }
1579
+
1580
+ private fun glyphAt(index: Int, wheel: Wheel): String? {
1581
+ if (wheel.linear && index < 0) return null
1582
+ if (wheel.blankZero && index == 0) return null
1583
+ val digit = ((index % 10) + 10) % 10
1584
+ return DIGITS[digit]
1585
+ }
1586
+
1587
+ // endregion
1588
+
1589
+ /**
1590
+ * Fabric dropped the view. It stays allocated until the JS side's handle to
1591
+ * it is collected (Hermes decides when), so everything that could outlive
1592
+ * the drop stops here and everything sizeable is let go of: the frame
1593
+ * callback, the engine's wheels and the layout buffers. The strips are
1594
+ * shared and stay in their cache. The view stays usable: with view
1595
+ * recycling on, Fabric hands it to [resetForRecycle] and a new element next.
1596
+ */
1597
+ fun release() {
1598
+ stopAnimation()
1599
+ engine.reset()
1600
+ wheels.clear()
1601
+ frameElements.clear()
1602
+ settledElements.clear()
1603
+ }
1604
+
1605
+ /**
1606
+ * What one mounted rolling number costs, for the JS garbage collector
1607
+ * (Nitro's `memorySize`). Measured, not estimated: the example's
1608
+ * `footprint` benchmark mounts 100 copies, forces a collection before and
1609
+ * with them, and divides the difference; the median of three interleaved
1610
+ * rounds. Galaxy A22, Android 13, 2026-09-22: 46 KB of malloc (engine,
1611
+ * display list, paints) and 8 KB of Java heap per copy, rounds within
1612
+ * ±30 KB; plain `Text` is 26 + 5 KB. A constant, because Nitro reads it
1613
+ * from the JS thread; the shared strips are not per copy.
1614
+ */
1615
+ fun memoryEstimateBytes(): Long = 64L * 1024
1616
+
1617
+ /** Interior wheels wrap modulo 10; a roll can be any real, so fold it onto 0 ≤ p < 10. */
1618
+ private fun wrap10(position: Double): Double {
1619
+ val r = position % 10.0
1620
+ return if (r < 0) r + 10.0 else r
1621
+ }
1622
+
1623
+ /** A digit strip: the software-rendered bitmap and, from Android 10, the layer that holds it. */
1624
+ class Strip(val bitmap: Bitmap, val node: RenderNode?)
1625
+
1626
+ /** The blurred digit bitmaps of the numeric transition, shared like the strips and bounded the same way. */
1627
+ /**
1628
+ * The blurred glyph masks every rolling number shares, least recently used
1629
+ * dropped first once they pass [BUDGET] bytes. Bounded by size, not count:
1630
+ * a numeric screen in a few fonts and colours uses hundreds of masks (ten
1631
+ * digits at seven levels each), and a count of 256 dropped masks another
1632
+ * figure was about to ask for again. Alpha masks are small, so the budget
1633
+ * holds thousands.
1634
+ */
1635
+ private object BlurredGlyphCache {
1636
+ private const val BUDGET = 16L shl 20
1637
+ private val entries = LinkedHashMap<String, Bitmap>(64, 0.75f, true)
1638
+ private var bytes = 0L
1639
+
1640
+ @Synchronized
1641
+ fun get(key: String, make: () -> Bitmap): Bitmap {
1642
+ entries[key]?.let { return it }
1643
+ val bitmap = make()
1644
+ entries[key] = bitmap
1645
+ bytes += bitmap.allocationByteCount
1646
+ val eldest = entries.entries.iterator()
1647
+ while (bytes > BUDGET && eldest.hasNext()) {
1648
+ val entry = eldest.next()
1649
+ if (entry.value === bitmap) break
1650
+ bytes -= entry.value.allocationByteCount
1651
+ eldest.remove()
1652
+ }
1653
+ return bitmap
1654
+ }
1655
+ }
1656
+
1657
+ /** The digit strips every rolling number shares, most recently used last; the ones that fall off the end drop their layer. */
1658
+ private object StripCache {
1659
+ private const val CAPACITY = 24
1660
+ private val strips =
1661
+ object : LinkedHashMap<String, Strip>(CAPACITY, 0.75f, true) {
1662
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Strip>): Boolean {
1663
+ val evict = size > CAPACITY
1664
+ if (evict) {
1665
+ eldest.value.node?.setUseCompositingLayer(false, null)
1666
+ eldest.value.node?.discardDisplayList()
1667
+ }
1668
+ return evict
1669
+ }
1670
+ }
1671
+
1672
+ fun get(key: String, build: () -> Strip): Strip = strips[key] ?: build().also { strips[key] = it }
1673
+ }
1674
+
1675
+ companion object {
1676
+ /** Strip slots: blank, 0–9, and the 0 that follows 9 when a wheel wraps. */
1677
+ private const val STRIP_SLOTS = 12
1678
+ private val DIGITS = Array(10) { it.toString() }
1679
+ private const val ALL_DIGITS = "0123456789"
1680
+ /** The core starts at the glyphs' left edge instead of parked off-screen. */
1681
+ private const val SHIMMER_SEED = 0.25f
1682
+ /** How far the top of the band leads the bottom, as a fraction of the height ("/" slant). */
1683
+ private const val SHIMMER_SLANT = 0.6f
1684
+ }
1685
+ }
1686
+
1687
+ /**
1688
+ * A string shaped once ([android.graphics.text.TextRunShaper]) and drawn with
1689
+ * [Canvas.drawGlyphs]: runs of glyphs per font (a fallback font gets its own
1690
+ * run), positions relative to the run's origin on the baseline.
1691
+ */
1692
+ @androidx.annotation.RequiresApi(Build.VERSION_CODES.S)
1693
+ internal class ShapedText private constructor(
1694
+ private val fonts: Array<android.graphics.fonts.Font>,
1695
+ private val ids: Array<IntArray>,
1696
+ private val positions: Array<FloatArray>,
1697
+ ) {
1698
+ /** Draws at ([x], [baseline]); [scratch] is resized when a run is longer. */
1699
+ fun draw(canvas: Canvas, x: Float, baseline: Float, paint: Paint, scratch: FloatArray): FloatArray {
1700
+ var buffer = scratch
1701
+ for (r in fonts.indices) {
1702
+ val pos = positions[r]
1703
+ if (buffer.size < pos.size) buffer = FloatArray(pos.size)
1704
+ var i = 0
1705
+ while (i < pos.size) {
1706
+ buffer[i] = pos[i] + x
1707
+ buffer[i + 1] = pos[i + 1] + baseline
1708
+ i += 2
1709
+ }
1710
+ canvas.drawGlyphs(ids[r], 0, buffer, 0, ids[r].size, fonts[r], paint)
1711
+ }
1712
+ return buffer
1713
+ }
1714
+
1715
+ companion object {
1716
+ fun of(text: String, paint: Paint): ShapedText {
1717
+ val glyphs = android.graphics.text.TextRunShaper.shapeTextRun(text, 0, text.length, 0, text.length, 0f, 0f, false, paint)
1718
+ val runFonts = ArrayList<android.graphics.fonts.Font>()
1719
+ val runIds = ArrayList<IntArray>()
1720
+ val runPositions = ArrayList<FloatArray>()
1721
+ var start = 0
1722
+ val count = glyphs.glyphCount()
1723
+ while (start < count) {
1724
+ val font = glyphs.getFont(start)
1725
+ var end = start + 1
1726
+ while (end < count && glyphs.getFont(end) == font) end++
1727
+ val n = end - start
1728
+ val ids = IntArray(n)
1729
+ val pos = FloatArray(n * 2)
1730
+ for (i in 0 until n) {
1731
+ ids[i] = glyphs.getGlyphId(start + i)
1732
+ pos[i * 2] = glyphs.getGlyphX(start + i)
1733
+ pos[i * 2 + 1] = glyphs.getGlyphY(start + i)
1734
+ }
1735
+ runFonts.add(font); runIds.add(ids); runPositions.add(pos)
1736
+ start = end
1737
+ }
1738
+ return ShapedText(runFonts.toTypedArray(), runIds.toTypedArray(), runPositions.toTypedArray())
1739
+ }
1740
+ }
1741
+ }