react-native-nitro-input 0.3.0 → 0.3.1
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.
- package/CHANGELOG.md +49 -0
- package/README.md +90 -2
- package/android/src/main/cpp/JReflowEngine.cpp +32 -0
- package/android/src/main/cpp/JReflowEngine.hpp +13 -0
- package/android/src/main/cpp/JRollingEngine.cpp +42 -2
- package/android/src/main/cpp/JRollingEngine.hpp +9 -1
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberFormatPlatform.kt +76 -1
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +88 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroTextMeasure.kt +25 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroTextView.kt +140 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputPackage.kt +2 -1
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +388 -136
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroTextView.kt +868 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/ReflowEngine.kt +21 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/RollingEngine.kt +13 -2
- package/cpp/RollingEngine.cpp +92 -8
- package/cpp/RollingEngine.hpp +36 -2
- package/ios/HybridNitroNumberFormatPlatform.swift +87 -9
- package/ios/HybridNitroNumberView.swift +82 -1
- package/ios/HybridNitroTextView.swift +134 -0
- package/ios/NitroNumberView.swift +368 -135
- package/ios/NitroTextView.swift +583 -0
- package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +20 -0
- package/lib/commonjs/nitrogen/generated/shared/json/NitroTextViewConfig.json +30 -0
- package/lib/commonjs/src/NitroNumber.js +52 -3
- package/lib/commonjs/src/NitroText.js +138 -0
- package/lib/commonjs/src/NitroTime.js +65 -0
- package/lib/commonjs/src/formatProps.js +76 -16
- package/lib/commonjs/src/index.js +6 -1
- package/lib/commonjs/src/specs/NitroText.nitro.js +2 -0
- package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +20 -0
- package/lib/module/nitrogen/generated/shared/json/NitroTextViewConfig.json +30 -0
- package/lib/module/src/NitroNumber.js +53 -4
- package/lib/module/src/NitroText.js +98 -0
- package/lib/module/src/NitroTime.js +29 -0
- package/lib/module/src/formatProps.js +76 -17
- package/lib/module/src/index.js +2 -0
- package/lib/module/src/specs/NitroText.nitro.js +1 -0
- package/lib/typescript/src/NitroNumber.d.ts +79 -1
- package/lib/typescript/src/NitroText.d.ts +67 -0
- package/lib/typescript/src/NitroTime.d.ts +19 -0
- package/lib/typescript/src/formatProps.d.ts +30 -4
- package/lib/typescript/src/index.d.ts +4 -1
- package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +67 -0
- package/lib/typescript/src/specs/NitroText.nitro.d.ts +60 -0
- package/nitro.json +20 -0
- package/nitrogen/generated/android/NitroInput+autolinking.cmake +6 -0
- package/nitrogen/generated/android/NitroInputOnLoad.cpp +34 -0
- package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +243 -0
- package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +40 -0
- package/nitrogen/generated/android/c++/JHybridNitroTextMeasureSpec.cpp +58 -0
- package/nitrogen/generated/android/c++/JHybridNitroTextMeasureSpec.hpp +64 -0
- package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.cpp +253 -0
- package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.hpp +104 -0
- package/nitrogen/generated/android/c++/JNitroNumberShimmerDirection.hpp +61 -0
- package/nitrogen/generated/android/c++/JNitroNumberSignDisplay.hpp +67 -0
- package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +100 -0
- package/nitrogen/generated/android/c++/views/JHybridNitroTextViewStateUpdater.cpp +174 -0
- package/nitrogen/generated/android/c++/views/JHybridNitroTextViewStateUpdater.hpp +54 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +136 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroTextMeasureSpec.kt +60 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroTextViewSpec.kt +179 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberShimmerDirection.kt +24 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroNumberSignDisplay.kt +26 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroTextViewManager.kt +96 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/views/HybridNitroTextViewStateUpdater.kt +23 -0
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +34 -0
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +132 -11
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +16 -0
- package/nitrogen/generated/ios/NitroInputAutolinking.mm +16 -0
- package/nitrogen/generated/ios/NitroInputAutolinking.swift +24 -0
- package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +146 -0
- package/nitrogen/generated/ios/c++/HybridNitroTextMeasureSpecSwift.cpp +11 -0
- package/nitrogen/generated/ios/c++/HybridNitroTextMeasureSpecSwift.hpp +90 -0
- package/nitrogen/generated/ios/c++/HybridNitroTextViewSpecSwift.cpp +11 -0
- package/nitrogen/generated/ios/c++/HybridNitroTextViewSpecSwift.hpp +233 -0
- package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +120 -0
- package/nitrogen/generated/ios/c++/views/HybridNitroTextViewComponent.mm +264 -0
- package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +20 -0
- package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +493 -0
- package/nitrogen/generated/ios/swift/HybridNitroTextMeasureSpec.swift +56 -0
- package/nitrogen/generated/ios/swift/HybridNitroTextMeasureSpec_cxx.swift +150 -0
- package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec.swift +75 -0
- package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec_cxx.swift +608 -0
- package/nitrogen/generated/ios/swift/NitroNumberShimmerDirection.swift +44 -0
- package/nitrogen/generated/ios/swift/NitroNumberSignDisplay.swift +52 -0
- package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +40 -0
- package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +46 -0
- package/nitrogen/generated/shared/c++/HybridNitroTextMeasureSpec.cpp +22 -0
- package/nitrogen/generated/shared/c++/HybridNitroTextMeasureSpec.hpp +63 -0
- package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.cpp +62 -0
- package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.hpp +115 -0
- package/nitrogen/generated/shared/c++/NitroNumberShimmerDirection.hpp +80 -0
- package/nitrogen/generated/shared/c++/NitroNumberSignDisplay.hpp +88 -0
- package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +40 -0
- package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +62 -0
- package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.cpp +74 -0
- package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.hpp +149 -0
- package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +20 -0
- package/nitrogen/generated/shared/json/NitroTextViewConfig.json +30 -0
- package/package.json +1 -1
- package/src/NitroNumber.tsx +183 -9
- package/src/NitroText.tsx +166 -0
- package/src/NitroTime.tsx +68 -0
- package/src/formatProps.ts +108 -18
- package/src/index.ts +5 -0
- package/src/specs/NitroNumber.nitro.ts +69 -0
- package/src/specs/NitroText.nitro.ts +65 -0
|
@@ -0,0 +1,868 @@
|
|
|
1
|
+
package com.margelo.nitro.nitroinput
|
|
2
|
+
|
|
3
|
+
import android.animation.ValueAnimator
|
|
4
|
+
import android.content.Context
|
|
5
|
+
import android.content.res.AssetManager
|
|
6
|
+
import android.content.res.Configuration
|
|
7
|
+
import android.content.res.Resources
|
|
8
|
+
import android.database.ContentObserver
|
|
9
|
+
import android.graphics.Canvas
|
|
10
|
+
import android.graphics.Color
|
|
11
|
+
import android.graphics.LinearGradient
|
|
12
|
+
import android.graphics.Matrix
|
|
13
|
+
import android.graphics.Paint
|
|
14
|
+
import android.graphics.PorterDuff
|
|
15
|
+
import android.graphics.PorterDuffXfermode
|
|
16
|
+
import android.graphics.Shader
|
|
17
|
+
import android.graphics.Typeface
|
|
18
|
+
import android.os.Build
|
|
19
|
+
import android.os.Handler
|
|
20
|
+
import android.os.Looper
|
|
21
|
+
import android.os.SystemClock
|
|
22
|
+
import android.provider.Settings
|
|
23
|
+
import android.text.TextPaint
|
|
24
|
+
import android.util.SparseArray
|
|
25
|
+
import android.util.TypedValue
|
|
26
|
+
import android.view.Choreographer
|
|
27
|
+
import android.view.View
|
|
28
|
+
import android.view.accessibility.AccessibilityEvent
|
|
29
|
+
import androidx.annotation.RequiresApi
|
|
30
|
+
import com.facebook.react.common.assets.ReactFontManager
|
|
31
|
+
import com.margelo.nitro.NitroModules
|
|
32
|
+
import kotlin.math.ceil
|
|
33
|
+
import kotlin.math.max
|
|
34
|
+
import kotlin.math.min
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A single line of text that morphs to the next (NitroText). The C++
|
|
38
|
+
* `ReflowEngine` decides where every character is while a morph runs, and
|
|
39
|
+
* this view draws every character at its own position, opacity and scale,
|
|
40
|
+
* frame by frame. At rest the line is one draw (per font run, glyphs shaped
|
|
41
|
+
* once and placed at their advances) and the engine is not involved: a label
|
|
42
|
+
* that never changes never crosses JNI. There is
|
|
43
|
+
* no text field and no child view, so mounting a thousand of them costs about
|
|
44
|
+
* what a thousand labels do. [HybridNitroTextMeasure] measures a line the same
|
|
45
|
+
* way ([NitroTextFonts]), so the JS side gives the view its size in the commit
|
|
46
|
+
* that mounts it.
|
|
47
|
+
*
|
|
48
|
+
* Mirrors `NitroTextView.swift` on iOS.
|
|
49
|
+
*/
|
|
50
|
+
// `ReflowEngine::Kind` / `Role`.
|
|
51
|
+
private const val KIND_TEXT = 0
|
|
52
|
+
private const val KIND_DIGIT = 1
|
|
53
|
+
private const val KIND_SEPARATOR = 2
|
|
54
|
+
private const val KIND_DECIMAL = 3
|
|
55
|
+
private const val ROLE_BODY = 1
|
|
56
|
+
/** Doubles per glyph in the engine's frame buffer (`ReflowEngine.frameInto`). */
|
|
57
|
+
private const val GLYPH_FIELDS = 11
|
|
58
|
+
/** The loading fade, in seconds. */
|
|
59
|
+
private const val LOADING_FADE = 0.25
|
|
60
|
+
/** Where the glint starts its sweep, as NitroNumber's. */
|
|
61
|
+
private const val SHIMMER_SEED = 0.25f
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The fonts NitroText draws with, shared by every view and the measurer: a
|
|
65
|
+
* paint per size, weight and family, and each character's advance (and, on
|
|
66
|
+
* API 31+, its shaped glyphs) in it. Measured on the JS thread and drawn on
|
|
67
|
+
* the main thread, so it locks. Sizes are in dp going in, px coming out.
|
|
68
|
+
*/
|
|
69
|
+
internal object NitroTextFonts {
|
|
70
|
+
class Entry(val paint: TextPaint) {
|
|
71
|
+
private val metrics: Paint.FontMetrics = paint.fontMetrics
|
|
72
|
+
/** The line box, in px. */
|
|
73
|
+
val lineHeight: Float = ceil(metrics.descent - metrics.ascent)
|
|
74
|
+
/** From the line box's top to the baseline, in px. */
|
|
75
|
+
val baseline: Float = -metrics.ascent
|
|
76
|
+
internal val advances = SparseArray<Float>()
|
|
77
|
+
internal val shaped = SparseArray<Any>()
|
|
78
|
+
/**
|
|
79
|
+
* The same for the first [DIRECT] code points, read without the lock:
|
|
80
|
+
* every commit and every frame looks characters up, and on the main thread
|
|
81
|
+
* the lock and the binary search cost more than the lookup. Written under
|
|
82
|
+
* the lock; a reader that sees no value yet takes the locked path. A float
|
|
83
|
+
* store is atomic, and a shaped entry is immutable (final fields), so a
|
|
84
|
+
* value seen is a whole one.
|
|
85
|
+
*/
|
|
86
|
+
internal val directAdvances = FloatArray(DIRECT) { Float.NaN }
|
|
87
|
+
internal val directShaped = arrayOfNulls<Any>(DIRECT)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Code points below this (Latin, Greek, Cyrillic) have lock-free slots. */
|
|
91
|
+
private const val DIRECT = 0x530
|
|
92
|
+
|
|
93
|
+
/** The one density the views and the measurer convert with. */
|
|
94
|
+
val density: Float =
|
|
95
|
+
(NitroModules.applicationContext?.resources ?: Resources.getSystem()).displayMetrics.density
|
|
96
|
+
|
|
97
|
+
private val entries = HashMap<String, Entry>()
|
|
98
|
+
private val lock = Any()
|
|
99
|
+
/** A code point's UTF-16 units, reused under [lock]. */
|
|
100
|
+
private val chars = CharArray(2)
|
|
101
|
+
|
|
102
|
+
fun entry(fontSize: Double, fontWeight: Double, fontFamily: String, assets: AssetManager? = null): Entry {
|
|
103
|
+
val size = if (fontSize.isFinite() && fontSize > 0) fontSize else 17.0
|
|
104
|
+
val weight = if (fontWeight.isFinite()) fontWeight else 400.0
|
|
105
|
+
val key = "$size|$weight|$fontFamily"
|
|
106
|
+
synchronized(lock) {
|
|
107
|
+
entries[key]?.let { return it }
|
|
108
|
+
val entry = Entry(makePaint(size, weight, fontFamily, assets ?: NitroModules.applicationContext?.assets))
|
|
109
|
+
if (entries.size > 64) entries.clear()
|
|
110
|
+
entries[key] = entry
|
|
111
|
+
return entry
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A drawing copy of [entry]'s paint (the shared one is only measured with). */
|
|
116
|
+
fun paintCopy(entry: Entry): TextPaint = synchronized(lock) { TextPaint(entry.paint) }
|
|
117
|
+
|
|
118
|
+
/** One character's advance in px, as the view lays it out (no kerning with its neighbours). */
|
|
119
|
+
fun advance(codePoint: Int, entry: Entry): Float {
|
|
120
|
+
if (codePoint in 0 until DIRECT) {
|
|
121
|
+
val width = entry.directAdvances[codePoint]
|
|
122
|
+
if (!width.isNaN()) return width
|
|
123
|
+
}
|
|
124
|
+
return synchronized(lock) {
|
|
125
|
+
entry.advances.get(codePoint)?.let { return it }
|
|
126
|
+
val n = Character.toChars(codePoint, chars, 0)
|
|
127
|
+
val width = entry.paint.measureText(chars, 0, n)
|
|
128
|
+
entry.advances.put(codePoint, width)
|
|
129
|
+
if (codePoint in 0 until DIRECT) entry.directAdvances[codePoint] = width
|
|
130
|
+
width
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** The line's width in px: every character's advance and the letter spacing after it. */
|
|
135
|
+
fun width(text: String, entry: Entry, letterSpacingPx: Float): Float {
|
|
136
|
+
var total = 0f
|
|
137
|
+
var i = 0
|
|
138
|
+
while (i < text.length) {
|
|
139
|
+
val cp = text.codePointAt(i)
|
|
140
|
+
total += advance(cp, entry) + letterSpacingPx
|
|
141
|
+
i += Character.charCount(cp)
|
|
142
|
+
}
|
|
143
|
+
return total
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** One character shaped once, for [Canvas.drawGlyphs]. */
|
|
147
|
+
@RequiresApi(Build.VERSION_CODES.S)
|
|
148
|
+
fun shaped(codePoint: Int, entry: Entry): NitroTextGlyphs {
|
|
149
|
+
if (codePoint in 0 until DIRECT) {
|
|
150
|
+
(entry.directShaped[codePoint] as NitroTextGlyphs?)?.let { return it }
|
|
151
|
+
}
|
|
152
|
+
return synchronized(lock) {
|
|
153
|
+
(entry.shaped.get(codePoint) as NitroTextGlyphs?)?.let { return it }
|
|
154
|
+
val n = Character.toChars(codePoint, chars, 0)
|
|
155
|
+
val glyphs = NitroTextGlyphs.of(chars, n, entry.paint)
|
|
156
|
+
entry.shaped.put(codePoint, glyphs)
|
|
157
|
+
if (codePoint in 0 until DIRECT) entry.directShaped[codePoint] = glyphs
|
|
158
|
+
glyphs
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
private fun makePaint(sizeDp: Double, weight: Double, family: String, assets: AssetManager?): TextPaint {
|
|
163
|
+
val paint = TextPaint(Paint.ANTI_ALIAS_FLAG or Paint.SUBPIXEL_TEXT_FLAG)
|
|
164
|
+
paint.typeface = makeTypeface(Math.rint(weight).toInt().coerceIn(1, 1000), family, assets)
|
|
165
|
+
paint.textSize = (sizeDp * density).toFloat()
|
|
166
|
+
// Tabular digits: a column keeps its width while its digit morphs.
|
|
167
|
+
paint.fontFeatureSettings = "tnum"
|
|
168
|
+
return paint
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
private fun makeTypeface(weight: Int, family: String, assets: AssetManager?): Typeface = try {
|
|
172
|
+
if (family.isNotEmpty() && assets != null) {
|
|
173
|
+
ReactFontManager.getInstance().getTypeface(family, Typeface.NORMAL, weight, assets)
|
|
174
|
+
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
|
175
|
+
Typeface.create(Typeface.DEFAULT, weight, false)
|
|
176
|
+
} else if (weight >= 600) {
|
|
177
|
+
Typeface.DEFAULT_BOLD
|
|
178
|
+
} else {
|
|
179
|
+
Typeface.DEFAULT
|
|
180
|
+
}
|
|
181
|
+
} catch (e: Throwable) {
|
|
182
|
+
if (weight >= 600) Typeface.DEFAULT_BOLD else Typeface.DEFAULT
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* A character shaped once ([android.graphics.text.TextRunShaper]): runs of
|
|
188
|
+
* glyphs per font (a fallback font gets its own run), positions relative to
|
|
189
|
+
* the character's origin on the baseline.
|
|
190
|
+
*/
|
|
191
|
+
@RequiresApi(Build.VERSION_CODES.S)
|
|
192
|
+
internal class NitroTextGlyphs private constructor(
|
|
193
|
+
val fonts: Array<android.graphics.fonts.Font>,
|
|
194
|
+
val ids: Array<IntArray>,
|
|
195
|
+
val positions: Array<FloatArray>,
|
|
196
|
+
) {
|
|
197
|
+
/** Draws at ([x], [baseline]); [scratch] is replaced (and returned) when a run is longer. */
|
|
198
|
+
fun draw(canvas: Canvas, x: Float, baseline: Float, paint: Paint, scratch: FloatArray): FloatArray {
|
|
199
|
+
var buffer = scratch
|
|
200
|
+
for (r in fonts.indices) {
|
|
201
|
+
val pos = positions[r]
|
|
202
|
+
if (buffer.size < pos.size) buffer = FloatArray(pos.size)
|
|
203
|
+
var i = 0
|
|
204
|
+
while (i < pos.size) {
|
|
205
|
+
buffer[i] = pos[i] + x
|
|
206
|
+
buffer[i + 1] = pos[i + 1] + baseline
|
|
207
|
+
i += 2
|
|
208
|
+
}
|
|
209
|
+
canvas.drawGlyphs(ids[r], 0, buffer, 0, ids[r].size, fonts[r], paint)
|
|
210
|
+
}
|
|
211
|
+
return buffer
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
companion object {
|
|
215
|
+
fun of(chars: CharArray, count: Int, paint: Paint): NitroTextGlyphs {
|
|
216
|
+
val glyphs = android.graphics.text.TextRunShaper.shapeTextRun(chars, 0, count, 0, count, 0f, 0f, false, paint)
|
|
217
|
+
val runFonts = ArrayList<android.graphics.fonts.Font>()
|
|
218
|
+
val runIds = ArrayList<IntArray>()
|
|
219
|
+
val runPositions = ArrayList<FloatArray>()
|
|
220
|
+
var start = 0
|
|
221
|
+
val total = glyphs.glyphCount()
|
|
222
|
+
while (start < total) {
|
|
223
|
+
val font = glyphs.getFont(start)
|
|
224
|
+
var end = start + 1
|
|
225
|
+
while (end < total && glyphs.getFont(end) == font) end++
|
|
226
|
+
val n = end - start
|
|
227
|
+
val ids = IntArray(n)
|
|
228
|
+
val pos = FloatArray(n * 2)
|
|
229
|
+
for (i in 0 until n) {
|
|
230
|
+
ids[i] = glyphs.getGlyphId(start + i)
|
|
231
|
+
pos[i * 2] = glyphs.getGlyphX(start + i)
|
|
232
|
+
pos[i * 2 + 1] = glyphs.getGlyphY(start + i)
|
|
233
|
+
}
|
|
234
|
+
runFonts.add(font); runIds.add(ids); runPositions.add(pos)
|
|
235
|
+
start = end
|
|
236
|
+
}
|
|
237
|
+
return NitroTextGlyphs(runFonts.toTypedArray(), runIds.toTypedArray(), runPositions.toTypedArray())
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
class NitroTextView(context: Context) : View(context) {
|
|
243
|
+
|
|
244
|
+
data class Style(
|
|
245
|
+
/** In dp. */
|
|
246
|
+
val fontSize: Double = 17.0,
|
|
247
|
+
val fontWeight: Double = 400.0,
|
|
248
|
+
/** Empty: the system font. */
|
|
249
|
+
val fontFamily: String = "",
|
|
250
|
+
/** Null: the theme's primary text colour. */
|
|
251
|
+
val color: Int? = null,
|
|
252
|
+
/** After every character, in dp. */
|
|
253
|
+
val letterSpacing: Float = 0f,
|
|
254
|
+
val textAlign: NitroNumberView.Alignment = NitroNumberView.Alignment.AUTO,
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
data class Timing(
|
|
258
|
+
val durationSeconds: Double = 0.4,
|
|
259
|
+
/** 0 expo, 1 easeOut, 2 easeInOut, 3 linear, 4 spring. */
|
|
260
|
+
val easing: Int = 0,
|
|
261
|
+
val bounce: Double = 0.15,
|
|
262
|
+
/** 0 auto, 1 slide, 2 fade. */
|
|
263
|
+
val effect: Int = 0,
|
|
264
|
+
val respectReduceMotion: Boolean = true,
|
|
265
|
+
)
|
|
266
|
+
|
|
267
|
+
var style: Style = Style()
|
|
268
|
+
set(value) {
|
|
269
|
+
if (field == value) return
|
|
270
|
+
field = value
|
|
271
|
+
applyFonts()
|
|
272
|
+
// New advances: the engine lays the line out again when it next morphs.
|
|
273
|
+
engineText = null
|
|
274
|
+
invalidate()
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
var timing: Timing = Timing()
|
|
278
|
+
set(value) {
|
|
279
|
+
if (field == value) return
|
|
280
|
+
field = value
|
|
281
|
+
engine.setTiming(value.durationSeconds, value.easing, value.bounce)
|
|
282
|
+
engine.setEffect(value.effect)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
var shimmer: NitroNumberView.Shimmer = NitroNumberView.Shimmer()
|
|
286
|
+
set(value) {
|
|
287
|
+
if (field == value) return
|
|
288
|
+
field = value
|
|
289
|
+
if (loading) invalidate()
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
var text: String
|
|
293
|
+
get() = shownText
|
|
294
|
+
set(value) {
|
|
295
|
+
val old = shownText
|
|
296
|
+
if (old == value) {
|
|
297
|
+
// Shown even when unchanged: a recycled view handed its own text again.
|
|
298
|
+
shown = true
|
|
299
|
+
return
|
|
300
|
+
}
|
|
301
|
+
shownText = value
|
|
302
|
+
restValid = false
|
|
303
|
+
if (shown && morphs()) {
|
|
304
|
+
// Hand the engine what is on screen first if it doesn't hold it: it
|
|
305
|
+
// only learns a line when that line has to morph.
|
|
306
|
+
if (engineText != old) commit(old, animated = false)
|
|
307
|
+
commit(value, animated = true)
|
|
308
|
+
} else {
|
|
309
|
+
engineText = null
|
|
310
|
+
}
|
|
311
|
+
shown = true
|
|
312
|
+
scheduleFrameIfNeeded()
|
|
313
|
+
invalidate()
|
|
314
|
+
// A no-op unless an accessibility service is on.
|
|
315
|
+
sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED)
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
var loading: Boolean = false
|
|
319
|
+
set(value) {
|
|
320
|
+
if (field == value) return
|
|
321
|
+
field = value
|
|
322
|
+
loadingFrom = loadingProgress
|
|
323
|
+
loadingStart = now()
|
|
324
|
+
scheduleFrameIfNeeded()
|
|
325
|
+
invalidate()
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
var rightToLeft: Boolean = false
|
|
329
|
+
set(value) {
|
|
330
|
+
if (field == value) return
|
|
331
|
+
field = value
|
|
332
|
+
engine.setRightToLeft(value)
|
|
333
|
+
restValid = false
|
|
334
|
+
invalidate()
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
private val engine = ReflowEngine()
|
|
338
|
+
private var shownText = ""
|
|
339
|
+
/**
|
|
340
|
+
* The line the engine holds (its target, while it morphs); null when it is
|
|
341
|
+
* out of date and the view draws [shownText] on its own.
|
|
342
|
+
*/
|
|
343
|
+
private var engineText: String? = null
|
|
344
|
+
/** A line has been shown: the next one morphs from it. */
|
|
345
|
+
private var shown = false
|
|
346
|
+
/** The engine's `needsFrames()` as of its last commit or tick, kept here so asking costs no JNI crossing. */
|
|
347
|
+
private var engineMoving = false
|
|
348
|
+
/** [frameBuffer] holds the engine's frame since its last commit. */
|
|
349
|
+
private var frameFresh = false
|
|
350
|
+
/** A line on its way to the engine: one crossing per commit ([ReflowEngine.commitLine]). */
|
|
351
|
+
private var lineChars = IntArray(32)
|
|
352
|
+
private var lineKinds = IntArray(32)
|
|
353
|
+
private var lineWidths = DoubleArray(32)
|
|
354
|
+
private var fonts: NitroTextFonts.Entry = NitroTextFonts.entry(17.0, 400.0, "", context.assets)
|
|
355
|
+
private var paint: TextPaint = NitroTextFonts.paintCopy(fonts)
|
|
356
|
+
private var letterSpacingPx = 0f
|
|
357
|
+
private var defaultInk = defaultTextColor()
|
|
358
|
+
private var loadingProgress = 0f
|
|
359
|
+
private var loadingFrom = 0f
|
|
360
|
+
private var loadingStart = 0.0
|
|
361
|
+
private var frameScheduled = false
|
|
362
|
+
/** Reused every frame so the JNI hop never allocates once warm. */
|
|
363
|
+
private var frameBuffer = DoubleArray(3 + GLYPH_FIELDS * 64)
|
|
364
|
+
private var frameCount = 0
|
|
365
|
+
private var frameContentWidth = 0f
|
|
366
|
+
/** A code point's UTF-16 units for `drawText` (API < 31). */
|
|
367
|
+
private val chars = CharArray(2)
|
|
368
|
+
/** Positions handed to `drawGlyphs` (API 31+), grown when a run is longer. */
|
|
369
|
+
private var glyphPositions = FloatArray(16)
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* The line at rest (API 31+): every glyph of every character, by font, at
|
|
373
|
+
* its advance, so a settled line is one `drawGlyphs` per font. Rebuilt when
|
|
374
|
+
* the text or the font changes, reused in between.
|
|
375
|
+
*/
|
|
376
|
+
private class RestRun {
|
|
377
|
+
var font: Any? = null
|
|
378
|
+
var ids = IntArray(16)
|
|
379
|
+
var positions = FloatArray(32)
|
|
380
|
+
var count = 0
|
|
381
|
+
}
|
|
382
|
+
private val restRuns = ArrayList<RestRun>()
|
|
383
|
+
private var restRunCount = 0
|
|
384
|
+
private var restContentWidth = 0f
|
|
385
|
+
private var restValid = false
|
|
386
|
+
/** Where each character of the line at rest starts (API < 31 draws them one by one). */
|
|
387
|
+
private var restXs = FloatArray(16)
|
|
388
|
+
|
|
389
|
+
private val frameCallback = Choreographer.FrameCallback { frameTimeNanos ->
|
|
390
|
+
frameScheduled = false
|
|
391
|
+
if (engineText != null) tick(frameTimeNanos / 1e9)
|
|
392
|
+
val target = if (loading) 1f else 0f
|
|
393
|
+
if (loadingProgress != target) {
|
|
394
|
+
val t = min(1.0, (now() - loadingStart) / LOADING_FADE).toFloat()
|
|
395
|
+
loadingProgress = loadingFrom + (target - loadingFrom) * t
|
|
396
|
+
}
|
|
397
|
+
// A view scrolled out of sight is not drawn every frame (a parent
|
|
398
|
+
// records every invalidated child, on screen or not); it is drawn once
|
|
399
|
+
// when it settles, and every frame again as soon as it is in sight.
|
|
400
|
+
if (onScreen()) {
|
|
401
|
+
invalidate()
|
|
402
|
+
framesSkipped = false
|
|
403
|
+
} else {
|
|
404
|
+
framesSkipped = true
|
|
405
|
+
}
|
|
406
|
+
scheduleFrameIfNeeded()
|
|
407
|
+
if (!frameScheduled && framesSkipped) {
|
|
408
|
+
framesSkipped = false
|
|
409
|
+
invalidate()
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
private val visibleRect = android.graphics.Rect()
|
|
414
|
+
/** Frames went undrawn while the view was out of sight. */
|
|
415
|
+
private var framesSkipped = false
|
|
416
|
+
|
|
417
|
+
private fun onScreen(): Boolean = isAttachedToWindow && getLocalVisibleRect(visibleRect)
|
|
418
|
+
|
|
419
|
+
private val shimmerPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
|
|
420
|
+
xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
|
|
421
|
+
}
|
|
422
|
+
/** The glint's gradient, rebuilt only when its colours or size change; a frame just slides it. */
|
|
423
|
+
private var shimmerGradient: LinearGradient? = null
|
|
424
|
+
private var shimmerGradientBase = 0
|
|
425
|
+
private var shimmerGradientHighlight = 0
|
|
426
|
+
private var shimmerGradientLength = -1f
|
|
427
|
+
private var shimmerGradientSlant = Float.NaN
|
|
428
|
+
private val shimmerMatrix = Matrix()
|
|
429
|
+
|
|
430
|
+
/** An `accessibilityLabel` the app set, which TalkBack reads instead of the text. */
|
|
431
|
+
private var explicitDescription: CharSequence? = null
|
|
432
|
+
|
|
433
|
+
init {
|
|
434
|
+
setWillNotDraw(false)
|
|
435
|
+
isFocusable = false
|
|
436
|
+
importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_YES
|
|
437
|
+
engine.setTiming(timing.durationSeconds, timing.easing, timing.bounce)
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// region Accessibility
|
|
441
|
+
|
|
442
|
+
override fun setContentDescription(contentDescription: CharSequence?) {
|
|
443
|
+
explicitDescription = contentDescription
|
|
444
|
+
super.setContentDescription(contentDescription)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
override fun getContentDescription(): CharSequence? {
|
|
448
|
+
explicitDescription?.let { if (it.isNotEmpty()) return it }
|
|
449
|
+
if (text.isEmpty()) return null
|
|
450
|
+
return if (loading) "$text, loading" else text
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// endregion
|
|
454
|
+
|
|
455
|
+
// region Lifecycle
|
|
456
|
+
|
|
457
|
+
/**
|
|
458
|
+
* Fabric is about to reuse this view: forget every animation, and that a
|
|
459
|
+
* line was shown, so the next element's text appears instead of morphing.
|
|
460
|
+
* The text and what is drawn stay, as a label's do: an element with the
|
|
461
|
+
* same text and style (a list scrolled back, a screen mounted again) draws
|
|
462
|
+
* nothing.
|
|
463
|
+
*/
|
|
464
|
+
fun resetForRecycle() {
|
|
465
|
+
val settled = !moving() && loadingProgress == 0f && !loading
|
|
466
|
+
stopFrames()
|
|
467
|
+
engine.reset()
|
|
468
|
+
engine.setTiming(timing.durationSeconds, timing.easing, timing.bounce)
|
|
469
|
+
engine.setEffect(timing.effect)
|
|
470
|
+
engine.setRightToLeft(rightToLeft)
|
|
471
|
+
engineText = null
|
|
472
|
+
shown = false
|
|
473
|
+
engineMoving = false
|
|
474
|
+
frameFresh = false
|
|
475
|
+
frameCount = 0
|
|
476
|
+
loadingProgress = 0f
|
|
477
|
+
loadingFrom = 0f
|
|
478
|
+
loading = false
|
|
479
|
+
explicitDescription = null
|
|
480
|
+
// Caught mid-morph or loading: the next draw is the line at rest.
|
|
481
|
+
if (!settled) invalidate()
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
fun stopFrames() {
|
|
485
|
+
if (frameScheduled) {
|
|
486
|
+
Choreographer.getInstance().removeFrameCallback(frameCallback)
|
|
487
|
+
frameScheduled = false
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
override fun onAttachedToWindow() {
|
|
492
|
+
super.onAttachedToWindow()
|
|
493
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
|
494
|
+
animatorScale = -1f
|
|
495
|
+
context.contentResolver.registerContentObserver(
|
|
496
|
+
Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE), false, animatorScaleObserver,
|
|
497
|
+
)
|
|
498
|
+
}
|
|
499
|
+
scheduleFrameIfNeeded()
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
override fun onDetachedFromWindow() {
|
|
503
|
+
stopFrames()
|
|
504
|
+
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
|
|
505
|
+
context.contentResolver.unregisterContentObserver(animatorScaleObserver)
|
|
506
|
+
}
|
|
507
|
+
super.onDetachedFromWindow()
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
override fun onConfigurationChanged(newConfig: Configuration?) {
|
|
511
|
+
super.onConfigurationChanged(newConfig)
|
|
512
|
+
// The default ink and the glint follow the theme (light / dark).
|
|
513
|
+
defaultInk = defaultTextColor()
|
|
514
|
+
invalidate()
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
// endregion
|
|
518
|
+
|
|
519
|
+
// region Text
|
|
520
|
+
|
|
521
|
+
private fun applyFonts() {
|
|
522
|
+
fonts = NitroTextFonts.entry(style.fontSize, style.fontWeight, style.fontFamily, context.assets)
|
|
523
|
+
paint = NitroTextFonts.paintCopy(fonts)
|
|
524
|
+
letterSpacingPx = style.letterSpacing * NitroTextFonts.density
|
|
525
|
+
restValid = false
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
/**
|
|
529
|
+
* Hands the engine the text, one glyph per code point with its advance;
|
|
530
|
+
* digits match by place and separators travel with their digits, the rest
|
|
531
|
+
* by the longest common run.
|
|
532
|
+
*/
|
|
533
|
+
private fun commit(s: String, animated: Boolean) {
|
|
534
|
+
val entry = fonts
|
|
535
|
+
var n = 0
|
|
536
|
+
var previous = -1
|
|
537
|
+
var i = 0
|
|
538
|
+
while (i < s.length) {
|
|
539
|
+
val cp = s.codePointAt(i)
|
|
540
|
+
val next = i + Character.charCount(cp)
|
|
541
|
+
val following = if (next < s.length) s.codePointAt(next) else -1
|
|
542
|
+
if (n == lineChars.size) {
|
|
543
|
+
lineChars = lineChars.copyOf(n * 2)
|
|
544
|
+
lineKinds = lineKinds.copyOf(n * 2)
|
|
545
|
+
lineWidths = lineWidths.copyOf(n * 2)
|
|
546
|
+
}
|
|
547
|
+
lineChars[n] = cp
|
|
548
|
+
lineKinds[n] = kind(cp, previous, following)
|
|
549
|
+
lineWidths[n] = (NitroTextFonts.advance(cp, entry) + letterSpacingPx).toDouble()
|
|
550
|
+
n++
|
|
551
|
+
previous = cp
|
|
552
|
+
i = next
|
|
553
|
+
}
|
|
554
|
+
engineMoving = engine.commitLine(lineChars, lineKinds, lineWidths, n, ROLE_BODY, !animated, -1, now())
|
|
555
|
+
engineText = s
|
|
556
|
+
frameFresh = false
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** A change morphs unless it can't be seen to: no duration, or animations off. */
|
|
560
|
+
private fun morphs(): Boolean =
|
|
561
|
+
timing.durationSeconds > 0 && !(timing.respectReduceMotion && animationsDisabled())
|
|
562
|
+
|
|
563
|
+
private fun moving(): Boolean = engineText != null && engineMoving
|
|
564
|
+
|
|
565
|
+
/** One crossing per frame: the engine ticks and hands back its frame ([ReflowEngine.tickInto]). */
|
|
566
|
+
private fun tick(now: Double) {
|
|
567
|
+
val result = engine.tickInto(now, frameBuffer)
|
|
568
|
+
if (result < 0) {
|
|
569
|
+
readFrame()
|
|
570
|
+
engineMoving = engine.needsFrames()
|
|
571
|
+
return
|
|
572
|
+
}
|
|
573
|
+
engineMoving = (result and ReflowEngine.MORE_FRAMES) != 0
|
|
574
|
+
frameCount = frameBuffer[0].toInt()
|
|
575
|
+
frameContentWidth = frameBuffer[1].toFloat()
|
|
576
|
+
frameFresh = true
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
private fun isDigit(cp: Int): Boolean = cp in 48..57
|
|
580
|
+
|
|
581
|
+
private fun kind(cp: Int, previous: Int, following: Int): Int {
|
|
582
|
+
if (isDigit(cp)) return KIND_DIGIT
|
|
583
|
+
// A comma or a point between two digits belongs to the number.
|
|
584
|
+
if (!isDigit(previous) || !isDigit(following)) return KIND_TEXT
|
|
585
|
+
return when (cp) {
|
|
586
|
+
','.code, 0x202F, 0x00A0, '\''.code -> KIND_SEPARATOR
|
|
587
|
+
'.'.code -> KIND_DECIMAL
|
|
588
|
+
else -> KIND_TEXT
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
// endregion
|
|
593
|
+
|
|
594
|
+
// region Frames
|
|
595
|
+
|
|
596
|
+
private fun now(): Double = SystemClock.uptimeMillis() / 1000.0
|
|
597
|
+
|
|
598
|
+
private fun needsFrames(): Boolean = moving() || loading || loadingProgress > 0f
|
|
599
|
+
|
|
600
|
+
private fun scheduleFrameIfNeeded() {
|
|
601
|
+
if (!frameScheduled && needsFrames()) {
|
|
602
|
+
frameScheduled = true
|
|
603
|
+
Choreographer.getInstance().postFrameCallback(frameCallback)
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
/**
|
|
608
|
+
* The animator duration scale on API < 33, read once and refreshed by
|
|
609
|
+
* [animatorScaleObserver]. -1 = not read yet.
|
|
610
|
+
*/
|
|
611
|
+
private var animatorScale = -1f
|
|
612
|
+
private val animatorScaleObserver = object : ContentObserver(Handler(Looper.getMainLooper())) {
|
|
613
|
+
override fun onChange(selfChange: Boolean) {
|
|
614
|
+
animatorScale = -1f
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** True when the user removed animations (Android's animator scale is 0), the equivalent of Reduce Motion. */
|
|
619
|
+
private fun animationsDisabled(): Boolean {
|
|
620
|
+
val scale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
|
621
|
+
ValueAnimator.getDurationScale()
|
|
622
|
+
} else {
|
|
623
|
+
if (animatorScale < 0f) {
|
|
624
|
+
animatorScale = Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
|
|
625
|
+
}
|
|
626
|
+
animatorScale
|
|
627
|
+
}
|
|
628
|
+
return scale <= 0f
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
/** Pulls the engine's glyphs into [frameBuffer] (no allocation once warm). */
|
|
632
|
+
private fun readFrame(): Boolean {
|
|
633
|
+
var written = engine.frameInto(frameBuffer)
|
|
634
|
+
if (written < 0) {
|
|
635
|
+
frameBuffer = DoubleArray(3 + GLYPH_FIELDS * (engine.glyphCount() + 32))
|
|
636
|
+
written = engine.frameInto(frameBuffer)
|
|
637
|
+
if (written < 0) return false
|
|
638
|
+
}
|
|
639
|
+
frameCount = frameBuffer[0].toInt()
|
|
640
|
+
frameContentWidth = frameBuffer[1].toFloat()
|
|
641
|
+
frameFresh = true
|
|
642
|
+
return true
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// endregion
|
|
646
|
+
|
|
647
|
+
// region Drawing
|
|
648
|
+
|
|
649
|
+
override fun onDraw(canvas: Canvas) {
|
|
650
|
+
super.onDraw(canvas)
|
|
651
|
+
val moving = moving()
|
|
652
|
+
if (!moving && shownText.isEmpty()) return
|
|
653
|
+
val entry = fonts
|
|
654
|
+
val lineHeight = entry.lineHeight
|
|
655
|
+
if (moving) {
|
|
656
|
+
if (!frameFresh && !readFrame()) return
|
|
657
|
+
} else if (!restValid) {
|
|
658
|
+
buildRestLine(entry)
|
|
659
|
+
}
|
|
660
|
+
val content = if (moving) frameContentWidth else restContentWidth
|
|
661
|
+
val originX = when (style.textAlign) {
|
|
662
|
+
NitroNumberView.Alignment.LEFT -> 0f
|
|
663
|
+
NitroNumberView.Alignment.RIGHT -> width - content
|
|
664
|
+
NitroNumberView.Alignment.CENTER -> (width - content) / 2f
|
|
665
|
+
NitroNumberView.Alignment.AUTO -> if (rightToLeft) width - content else 0f
|
|
666
|
+
}
|
|
667
|
+
val originY = (height - lineHeight) / 2f
|
|
668
|
+
val ink = style.color ?: defaultInk
|
|
669
|
+
paint.color = ink
|
|
670
|
+
|
|
671
|
+
val dim = loadingProgress.coerceIn(0f, 1f)
|
|
672
|
+
// Everything drawn in this layer is what the glint is composited onto;
|
|
673
|
+
// a line height of room around the line for glyphs sliding through it.
|
|
674
|
+
val layerLeft = originX - lineHeight
|
|
675
|
+
val layerTop = originY - lineHeight
|
|
676
|
+
val layerRight = originX + content + lineHeight
|
|
677
|
+
val layerBottom = originY + lineHeight * 2f
|
|
678
|
+
val layer = if (dim > 0f) canvas.saveLayer(layerLeft, layerTop, layerRight, layerBottom, null) else -1
|
|
679
|
+
if (moving) {
|
|
680
|
+
drawGlyphs(canvas, entry, originX, originY, lineHeight, ink)
|
|
681
|
+
} else {
|
|
682
|
+
drawRest(canvas, originX, originY + entry.baseline)
|
|
683
|
+
}
|
|
684
|
+
if (dim > 0f) {
|
|
685
|
+
drawShimmer(canvas, ink, originX, content, originY, dim, layerLeft, layerTop, layerRight, layerBottom)
|
|
686
|
+
canvas.restoreToCount(layer)
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* Lays the line at rest out from the text alone: each character at the sum
|
|
692
|
+
* of the advances (and letter spacing) before it, as the engine would; on
|
|
693
|
+
* API 31+ its shaped glyphs gathered into [restRuns] by font.
|
|
694
|
+
*/
|
|
695
|
+
private fun buildRestLine(entry: NitroTextFonts.Entry) {
|
|
696
|
+
for (r in 0 until restRunCount) restRuns[r].count = 0
|
|
697
|
+
restRunCount = 0
|
|
698
|
+
val s = shownText
|
|
699
|
+
var x = 0f
|
|
700
|
+
var n = 0
|
|
701
|
+
var i = 0
|
|
702
|
+
while (i < s.length) {
|
|
703
|
+
val cp = s.codePointAt(i)
|
|
704
|
+
if (restXs.size <= n) restXs = restXs.copyOf(restXs.size * 2)
|
|
705
|
+
restXs[n++] = x
|
|
706
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) addToRest(cp, x, entry)
|
|
707
|
+
x += NitroTextFonts.advance(cp, entry) + letterSpacingPx
|
|
708
|
+
i += Character.charCount(cp)
|
|
709
|
+
}
|
|
710
|
+
restContentWidth = x
|
|
711
|
+
restValid = true
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
@RequiresApi(Build.VERSION_CODES.S)
|
|
715
|
+
private fun addToRest(codePoint: Int, x: Float, entry: NitroTextFonts.Entry) {
|
|
716
|
+
val shaped = NitroTextFonts.shaped(codePoint, entry)
|
|
717
|
+
for (r in shaped.fonts.indices) {
|
|
718
|
+
val run = restRun(shaped.fonts[r])
|
|
719
|
+
val ids = shaped.ids[r]
|
|
720
|
+
val pos = shaped.positions[r]
|
|
721
|
+
if (run.ids.size < run.count + ids.size) {
|
|
722
|
+
run.ids = run.ids.copyOf(max(run.ids.size * 2, run.count + ids.size))
|
|
723
|
+
run.positions = run.positions.copyOf(run.ids.size * 2)
|
|
724
|
+
}
|
|
725
|
+
for (g in ids.indices) {
|
|
726
|
+
run.ids[run.count] = ids[g]
|
|
727
|
+
run.positions[run.count * 2] = pos[g * 2] + x
|
|
728
|
+
run.positions[run.count * 2 + 1] = pos[g * 2 + 1]
|
|
729
|
+
run.count++
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/** The rest run drawn in [font], reusing the run objects of earlier lines. */
|
|
735
|
+
private fun restRun(font: Any): RestRun {
|
|
736
|
+
for (r in 0 until restRunCount) {
|
|
737
|
+
if (restRuns[r].font == font) return restRuns[r]
|
|
738
|
+
}
|
|
739
|
+
if (restRunCount == restRuns.size) restRuns.add(RestRun())
|
|
740
|
+
val run = restRuns[restRunCount++]
|
|
741
|
+
run.font = font
|
|
742
|
+
run.count = 0
|
|
743
|
+
return run
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** At rest: the whole line, one `drawGlyphs` per font (per character below API 31). */
|
|
747
|
+
private fun drawRest(canvas: Canvas, x: Float, baseline: Float) {
|
|
748
|
+
val saved = canvas.save()
|
|
749
|
+
canvas.translate(x, baseline)
|
|
750
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
|
751
|
+
for (r in 0 until restRunCount) {
|
|
752
|
+
val run = restRuns[r]
|
|
753
|
+
if (run.count == 0) continue
|
|
754
|
+
canvas.drawGlyphs(run.ids, 0, run.positions, 0, run.count, run.font as android.graphics.fonts.Font, paint)
|
|
755
|
+
}
|
|
756
|
+
} else {
|
|
757
|
+
val s = shownText
|
|
758
|
+
var n = 0
|
|
759
|
+
var i = 0
|
|
760
|
+
while (i < s.length) {
|
|
761
|
+
val cp = s.codePointAt(i)
|
|
762
|
+
val count = Character.toChars(cp, chars, 0)
|
|
763
|
+
canvas.drawText(chars, 0, count, restXs[n++], 0f, paint)
|
|
764
|
+
i += Character.charCount(cp)
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
canvas.restoreToCount(saved)
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** Every glyph at its own position, opacity and scale (a morph, or any line below API 31). */
|
|
771
|
+
private fun drawGlyphs(canvas: Canvas, entry: NitroTextFonts.Entry, originX: Float, originY: Float, lineHeight: Float, ink: Int) {
|
|
772
|
+
val f = frameBuffer
|
|
773
|
+
val inkAlpha = Color.alpha(ink)
|
|
774
|
+
for (i in 0 until frameCount) {
|
|
775
|
+
val base = 3 + i * GLYPH_FIELDS
|
|
776
|
+
val opacity = f[base + 8].toFloat().coerceIn(0f, 1f)
|
|
777
|
+
if (opacity <= 0.002f) continue
|
|
778
|
+
val alpha = Math.round(inkAlpha * opacity).coerceIn(0, 255)
|
|
779
|
+
if (alpha == 0) continue
|
|
780
|
+
paint.alpha = alpha
|
|
781
|
+
val codePoint = f[base + 1].toInt()
|
|
782
|
+
val x = originX + f[base + 6].toFloat()
|
|
783
|
+
val top = originY + f[base + 7].toFloat() * lineHeight
|
|
784
|
+
val scale = f[base + 9].toFloat()
|
|
785
|
+
val scaled = Math.abs(scale - 1f) > 0.0001f
|
|
786
|
+
val saved = if (scaled) canvas.save() else -1
|
|
787
|
+
if (scaled) canvas.scale(scale, scale, x + f[base + 4].toFloat() / 2f, top + lineHeight / 2f)
|
|
788
|
+
val baseline = top + entry.baseline
|
|
789
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
|
790
|
+
glyphPositions = NitroTextFonts.shaped(codePoint, entry).draw(canvas, x, baseline, paint, glyphPositions)
|
|
791
|
+
} else if (Character.isValidCodePoint(codePoint)) {
|
|
792
|
+
val n = Character.toChars(codePoint, chars, 0)
|
|
793
|
+
canvas.drawText(chars, 0, n, x, baseline, paint)
|
|
794
|
+
}
|
|
795
|
+
if (scaled) canvas.restoreToCount(saved)
|
|
796
|
+
}
|
|
797
|
+
paint.alpha = inkAlpha
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/**
|
|
801
|
+
* The loading glint, as NitroNumber draws it: a slanted band recolouring
|
|
802
|
+
* the ink from the base colour to the highlight and back ([base, highlight,
|
|
803
|
+
* base] at 10/50/90 %), composited SRC_ATOP so only the glyphs light up.
|
|
804
|
+
*/
|
|
805
|
+
private fun drawShimmer(
|
|
806
|
+
canvas: Canvas, ink: Int, left: Float, width: Float, top: Float, dim: Float,
|
|
807
|
+
layerLeft: Float, layerTop: Float, layerRight: Float, layerBottom: Float,
|
|
808
|
+
) {
|
|
809
|
+
if (width <= 0f) return
|
|
810
|
+
val base = shimmer.baseColor ?: ink
|
|
811
|
+
val highlight = shimmer.color ?: defaultShimmerColor()
|
|
812
|
+
// One sweep takes `durationMs`; the band then waits off the far edge for `delayMs`.
|
|
813
|
+
// On the shared clock, so every loading line on screen sweeps together.
|
|
814
|
+
val durationMs = max(1L, shimmer.durationMs)
|
|
815
|
+
val cycleMs = durationMs + max(0L, shimmer.delayMs)
|
|
816
|
+
val reduceMotion = timing.respectReduceMotion && animationsDisabled()
|
|
817
|
+
val elapsedMs = if (reduceMotion) 0L else SystemClock.uptimeMillis() % cycleMs
|
|
818
|
+
val phase = min(1f, elapsedMs.toFloat() / durationMs)
|
|
819
|
+
val seeded = SHIMMER_SEED + (1f - SHIMMER_SEED) * phase
|
|
820
|
+
val ltr = shimmer.leftToRight ?: !rightToLeft
|
|
821
|
+
val progress = if (ltr) seeded else 1f - seeded
|
|
822
|
+
// The gradient runs `length` along x (its slant on top): it enters at the
|
|
823
|
+
// left edge and leaves past the right, or the mirror image.
|
|
824
|
+
val length = width * shimmer.width.coerceAtLeast(0.05f)
|
|
825
|
+
val startX = left + (width + length) * progress - length
|
|
826
|
+
val slant = Math.tan(Math.toRadians(shimmer.angle.coerceIn(-75f, 75f).toDouble())).toFloat() * (if (ltr) 1f else -1f)
|
|
827
|
+
var gradient = shimmerGradient
|
|
828
|
+
if (gradient == null || shimmerGradientBase != base || shimmerGradientHighlight != highlight ||
|
|
829
|
+
shimmerGradientLength != length || shimmerGradientSlant != slant
|
|
830
|
+
) {
|
|
831
|
+
gradient = LinearGradient(
|
|
832
|
+
0f, 0f, length, slant * length,
|
|
833
|
+
intArrayOf(base, highlight, base), floatArrayOf(0.1f, 0.5f, 0.9f), Shader.TileMode.CLAMP,
|
|
834
|
+
)
|
|
835
|
+
shimmerGradient = gradient
|
|
836
|
+
shimmerGradientBase = base
|
|
837
|
+
shimmerGradientHighlight = highlight
|
|
838
|
+
shimmerGradientLength = length
|
|
839
|
+
shimmerGradientSlant = slant
|
|
840
|
+
shimmerPaint.shader = gradient
|
|
841
|
+
}
|
|
842
|
+
shimmerMatrix.setTranslate(startX, top)
|
|
843
|
+
gradient.setLocalMatrix(shimmerMatrix)
|
|
844
|
+
shimmerPaint.alpha = (dim * 255f).toInt().coerceIn(0, 255)
|
|
845
|
+
canvas.drawRect(layerLeft, layerTop, layerRight, layerBottom, shimmerPaint)
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** Default glint colour: a near-background neutral so the ink "lights up". */
|
|
849
|
+
private fun defaultShimmerColor(): Int {
|
|
850
|
+
val night = (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
|
|
851
|
+
return if (night) 0xFF2B2E37.toInt() else 0xFFD6D9E1.toInt()
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
private fun defaultTextColor(): Int {
|
|
855
|
+
val value = TypedValue()
|
|
856
|
+
return if (context.theme.resolveAttribute(android.R.attr.textColorPrimary, value, true)) {
|
|
857
|
+
if (value.resourceId != 0) {
|
|
858
|
+
context.resources.getColorStateList(value.resourceId, context.theme).defaultColor
|
|
859
|
+
} else {
|
|
860
|
+
value.data
|
|
861
|
+
}
|
|
862
|
+
} else {
|
|
863
|
+
Color.BLACK
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
// endregion
|
|
868
|
+
}
|