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