react-native-nitro-input 0.3.7 → 0.4.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.
- package/CHANGELOG.md +133 -0
- package/README.md +9 -4
- package/android/CMakeLists.txt +1 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputMeasure.kt +52 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroInputView.kt +74 -80
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroNumberView.kt +18 -18
- package/android/src/main/java/com/margelo/nitro/nitroinput/HybridNitroTextView.kt +14 -14
- package/android/src/main/java/com/margelo/nitro/nitroinput/InputFonts.kt +199 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/InputSizing.kt +398 -0
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroInputView.kt +112 -333
- package/android/src/main/java/com/margelo/nitro/nitroinput/NitroNumberView.kt +178 -30
- package/cpp/RollingEngine.cpp +68 -5
- package/cpp/RollingEngine.hpp +13 -0
- package/cpp/numberformat/FormatFigure.cpp +134 -0
- package/cpp/numberformat/FormatFigure.hpp +65 -0
- package/cpp/numberformat/HybridNitroNumberFormat.cpp +32 -10
- package/cpp/numberformat/HybridNitroNumberFormat.hpp +9 -1
- package/ios/HybridNitroInputView.swift +69 -75
- package/ios/HybridNitroNumberView.swift +18 -18
- package/ios/HybridNitroTextView.swift +14 -14
- package/ios/InputSizing.swift +534 -0
- package/ios/NitroInputView.swift +102 -198
- package/ios/NitroNumberView.swift +98 -23
- package/lib/commonjs/nitrogen/generated/shared/json/NitroInputViewConfig.json +12 -8
- package/lib/commonjs/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
- package/lib/commonjs/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
- package/lib/commonjs/src/NitroInput.js +164 -23
- package/lib/commonjs/src/NitroNumber.js +19 -11
- package/lib/commonjs/src/NitroText.js +6 -6
- package/lib/commonjs/src/NumberFormat.js +20 -0
- package/lib/commonjs/src/formatProps.js +57 -81
- package/lib/commonjs/src/specs/NitroInputMeasure.nitro.js +2 -0
- package/lib/module/nitrogen/generated/shared/json/NitroInputViewConfig.json +12 -8
- package/lib/module/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
- package/lib/module/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
- package/lib/module/src/NitroInput.js +165 -24
- package/lib/module/src/NitroNumber.js +20 -12
- package/lib/module/src/NitroText.js +6 -6
- package/lib/module/src/NumberFormat.js +18 -0
- package/lib/module/src/formatProps.js +54 -81
- package/lib/module/src/specs/NitroInputMeasure.nitro.js +1 -0
- package/lib/typescript/src/NitroInput.d.ts +9 -16
- package/lib/typescript/src/NitroNumber.d.ts +25 -7
- package/lib/typescript/src/NumberFormat.d.ts +15 -1
- package/lib/typescript/src/formatProps.d.ts +23 -18
- package/lib/typescript/src/specs/NitroInput.nitro.d.ts +17 -8
- package/lib/typescript/src/specs/NitroInputMeasure.nitro.d.ts +67 -0
- package/lib/typescript/src/specs/NitroNumber.nitro.d.ts +6 -6
- package/lib/typescript/src/specs/NitroText.nitro.d.ts +6 -6
- package/lib/typescript/src/specs/NumberFormat.nitro.d.ts +33 -0
- package/nitro.json +10 -0
- package/nitrogen/generated/android/NitroInput+autolinking.cmake +2 -0
- package/nitrogen/generated/android/NitroInputOnLoad.cpp +16 -0
- package/nitrogen/generated/android/c++/JHybridNitroInputMeasureSpec.cpp +93 -0
- package/nitrogen/generated/android/c++/JHybridNitroInputMeasureSpec.hpp +63 -0
- package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.cpp +76 -40
- package/nitrogen/generated/android/c++/JHybridNitroInputViewSpec.hpp +24 -16
- package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.cpp +30 -30
- package/nitrogen/generated/android/c++/JHybridNitroNumberViewSpec.hpp +12 -12
- package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.cpp +30 -30
- package/nitrogen/generated/android/c++/JHybridNitroTextViewSpec.hpp +12 -12
- package/nitrogen/generated/android/c++/JNitroInputSize.hpp +61 -0
- package/nitrogen/generated/android/c++/JNitroInputSizing.hpp +284 -0
- package/nitrogen/generated/android/c++/views/JHybridNitroInputViewStateUpdater.cpp +44 -24
- package/nitrogen/generated/android/c++/views/JHybridNitroNumberViewStateUpdater.cpp +18 -18
- package/nitrogen/generated/android/c++/views/JHybridNitroTextViewStateUpdater.cpp +18 -18
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputMeasureSpec.kt +56 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroInputViewSpec.kt +32 -8
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroNumberViewSpec.kt +6 -6
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/HybridNitroTextViewSpec.kt +6 -6
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSize.kt +56 -0
- package/nitrogen/generated/android/kotlin/com/margelo/nitro/nitroinput/NitroInputSizing.kt +246 -0
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.cpp +17 -0
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Bridge.hpp +29 -0
- package/nitrogen/generated/ios/NitroInput-Swift-Cxx-Umbrella.hpp +11 -0
- package/nitrogen/generated/ios/NitroInputAutolinking.mm +8 -0
- package/nitrogen/generated/ios/NitroInputAutolinking.swift +12 -0
- package/nitrogen/generated/ios/c++/HybridNitroInputMeasureSpecSwift.cpp +11 -0
- package/nitrogen/generated/ios/c++/HybridNitroInputMeasureSpecSwift.hpp +112 -0
- package/nitrogen/generated/ios/c++/HybridNitroInputViewSpecSwift.hpp +56 -32
- package/nitrogen/generated/ios/c++/HybridNitroNumberViewSpecSwift.hpp +24 -24
- package/nitrogen/generated/ios/c++/HybridNitroTextViewSpecSwift.hpp +24 -24
- package/nitrogen/generated/ios/c++/views/HybridNitroInputViewComponent.mm +56 -32
- package/nitrogen/generated/ios/c++/views/HybridNitroNumberViewComponent.mm +24 -24
- package/nitrogen/generated/ios/c++/views/HybridNitroTextViewComponent.mm +24 -24
- package/nitrogen/generated/ios/swift/HybridNitroInputMeasureSpec.swift +55 -0
- package/nitrogen/generated/ios/swift/HybridNitroInputMeasureSpec_cxx.swift +138 -0
- package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec.swift +12 -8
- package/nitrogen/generated/ios/swift/HybridNitroInputViewSpec_cxx.swift +68 -24
- package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec.swift +6 -6
- package/nitrogen/generated/ios/swift/HybridNitroNumberViewSpec_cxx.swift +18 -18
- package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec.swift +6 -6
- package/nitrogen/generated/ios/swift/HybridNitroTextViewSpec_cxx.swift +18 -18
- package/nitrogen/generated/ios/swift/NitroInputSize.swift +34 -0
- package/nitrogen/generated/ios/swift/NitroInputSizing.swift +242 -0
- package/nitrogen/generated/shared/c++/HybridNitroInputMeasureSpec.cpp +21 -0
- package/nitrogen/generated/shared/c++/HybridNitroInputMeasureSpec.hpp +66 -0
- package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.cpp +24 -16
- package/nitrogen/generated/shared/c++/HybridNitroInputViewSpec.hpp +24 -16
- package/nitrogen/generated/shared/c++/HybridNitroNumberFormatSpec.cpp +2 -0
- package/nitrogen/generated/shared/c++/HybridNitroNumberFormatSpec.hpp +8 -0
- package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.cpp +12 -12
- package/nitrogen/generated/shared/c++/HybridNitroNumberViewSpec.hpp +12 -12
- package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.cpp +12 -12
- package/nitrogen/generated/shared/c++/HybridNitroTextViewSpec.hpp +12 -12
- package/nitrogen/generated/shared/c++/NitroInputSize.hpp +87 -0
- package/nitrogen/generated/shared/c++/NitroInputSizing.hpp +263 -0
- package/nitrogen/generated/shared/c++/NumberFigure.hpp +95 -0
- package/nitrogen/generated/shared/c++/NumberFormatLayout.hpp +112 -0
- package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.cpp +24 -16
- package/nitrogen/generated/shared/c++/views/HybridNitroInputViewComponent.hpp +36 -24
- package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.cpp +12 -12
- package/nitrogen/generated/shared/c++/views/HybridNitroNumberViewComponent.hpp +18 -18
- package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.cpp +12 -12
- package/nitrogen/generated/shared/c++/views/HybridNitroTextViewComponent.hpp +18 -18
- package/nitrogen/generated/shared/json/NitroInputViewConfig.json +12 -8
- package/nitrogen/generated/shared/json/NitroNumberViewConfig.json +6 -6
- package/nitrogen/generated/shared/json/NitroTextViewConfig.json +6 -6
- package/package.json +5 -3
- package/src/NitroInput.tsx +201 -64
- package/src/NitroNumber.tsx +54 -25
- package/src/NitroText.tsx +6 -6
- package/src/NumberFormat.ts +22 -0
- package/src/formatProps.ts +59 -99
- package/src/specs/NitroInput.nitro.ts +17 -8
- package/src/specs/NitroInputMeasure.nitro.ts +76 -0
- package/src/specs/NitroNumber.nitro.ts +6 -6
- package/src/specs/NitroText.nitro.ts +6 -6
- package/src/specs/NumberFormat.nitro.ts +35 -0
|
@@ -54,6 +54,8 @@ private const val NUMERIC_BLUR = 0.08f
|
|
|
54
54
|
/** Blurred copies per digit, from a touch of blur to the full one. */
|
|
55
55
|
private const val NUMERIC_BLUR_LEVELS = 6
|
|
56
56
|
|
|
57
|
+
private fun isMainThread(): Boolean = Looper.myLooper() === Looper.getMainLooper()
|
|
58
|
+
|
|
57
59
|
/** `RollingEngine::TextSlot`. */
|
|
58
60
|
private const val TEXT_PREFIX = 0
|
|
59
61
|
private const val TEXT_SUFFIX = 1
|
|
@@ -449,7 +451,20 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
449
451
|
digitIndex * (NUMERIC_BLUR_LEVELS + 1) + level.coerceIn(0, NUMERIC_BLUR_LEVELS)
|
|
450
452
|
digitMasks.get(slot)?.let { return it }
|
|
451
453
|
val radius = if (level <= 0 || numericBlur <= 0f) 0 else Math.round(lineHeight * numericBlur * level / NUMERIC_BLUR_LEVELS).coerceAtLeast(1)
|
|
452
|
-
val
|
|
454
|
+
val cacheKey = "${key(role)}|$digitIndex|$radius|$blurPad"
|
|
455
|
+
if (radius > 0 && isMainThread()) {
|
|
456
|
+
// Not warmed yet (a font or size that just changed): blur it on the
|
|
457
|
+
// warm thread and draw the sharp mask this frame. A blur in onDraw was
|
|
458
|
+
// ANRing low-end phones, see [BlurredGlyphCache].
|
|
459
|
+
val ready = BlurredGlyphCache.peek(cacheKey)
|
|
460
|
+
if (ready == null) {
|
|
461
|
+
WarmExecutor.request(cacheKey) { blurred(role, digitIndex, level) }
|
|
462
|
+
return blurred(role, digitIndex, 0)
|
|
463
|
+
}
|
|
464
|
+
digitMasks.set(slot, ready)
|
|
465
|
+
return ready
|
|
466
|
+
}
|
|
467
|
+
val mask = BlurredGlyphCache.get(cacheKey) {
|
|
453
468
|
val text = glyphs[digitIndex]
|
|
454
469
|
val pad = blurPad
|
|
455
470
|
val w = ceil(cell).toInt() + 2 * pad
|
|
@@ -463,7 +478,7 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
463
478
|
val canvas = Canvas(mask)
|
|
464
479
|
// A paint of its own: the masks are warmed off the main thread, where
|
|
465
480
|
// the digit paint's alpha is being changed by the draws.
|
|
466
|
-
val paint = TextPaint(
|
|
481
|
+
val paint = TextPaint(threadPaint(role)).apply { alpha = 255 }
|
|
467
482
|
canvas.drawText(text, pad + (cell - width(text, role)) / 2f, pad + digitBaseline(role), paint)
|
|
468
483
|
if (radius > 0) boxBlurMask(mask, radius)
|
|
469
484
|
// Immutable and uploaded ahead of its first draw: HWUI re-pins a mutable
|
|
@@ -471,7 +486,6 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
471
486
|
// for its texture upload.
|
|
472
487
|
val done = mask.copy(Bitmap.Config.ALPHA_8, false) ?: mask
|
|
473
488
|
if (done !== mask) mask.recycle()
|
|
474
|
-
done.prepareToDraw()
|
|
475
489
|
done
|
|
476
490
|
}
|
|
477
491
|
digitMasks.set(slot, mask)
|
|
@@ -487,18 +501,25 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
487
501
|
fun blurredText(text: String, role: GlyphRole, level: Int): Bitmap? {
|
|
488
502
|
if (text.isEmpty() || lineHeight <= 0f) return null
|
|
489
503
|
val radius = if (level <= 0 || numericBlur <= 0f) 0 else Math.round(lineHeight * numericBlur * level / NUMERIC_BLUR_LEVELS).coerceAtLeast(1)
|
|
490
|
-
|
|
504
|
+
val cacheKey = "${key(role)}|t|$text|$radius|$blurPad"
|
|
505
|
+
if (radius > 0 && isMainThread()) {
|
|
506
|
+
// Never warmed ahead (any text can change into any other): blurred on
|
|
507
|
+
// the warm thread, sharp until it lands, as [blurred] does.
|
|
508
|
+
BlurredGlyphCache.peek(cacheKey)?.let { return it }
|
|
509
|
+
WarmExecutor.request(cacheKey) { blurredText(text, role, level) }
|
|
510
|
+
return blurredText(text, role, 0)
|
|
511
|
+
}
|
|
512
|
+
return BlurredGlyphCache.get(cacheKey) {
|
|
491
513
|
val pad = blurPad
|
|
492
514
|
val w = ceil(width(text, role)).toInt() + 2 * pad
|
|
493
515
|
val h = ceil(lineHeight).toInt() + 2 * pad
|
|
494
516
|
val mask = Bitmap.createBitmap(w.coerceAtLeast(1), h, Bitmap.Config.ALPHA_8)
|
|
495
517
|
val canvas = Canvas(mask)
|
|
496
|
-
val paint = TextPaint(
|
|
518
|
+
val paint = TextPaint(threadPaint(role)).apply { alpha = 255 }
|
|
497
519
|
canvas.drawText(text, pad.toFloat(), pad + baseline(role, text, 0f), paint)
|
|
498
520
|
if (radius > 0) boxBlurMask(mask, radius)
|
|
499
521
|
val done = mask.copy(Bitmap.Config.ALPHA_8, false) ?: mask
|
|
500
522
|
if (done !== mask) mask.recycle()
|
|
501
|
-
done.prepareToDraw()
|
|
502
523
|
done
|
|
503
524
|
}
|
|
504
525
|
}
|
|
@@ -547,8 +568,10 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
547
568
|
if (strip !== drawn) drawn.recycle()
|
|
548
569
|
return strip
|
|
549
570
|
}
|
|
550
|
-
|
|
551
|
-
|
|
571
|
+
// Concurrent: a prefix or suffix blurred on the warm thread ([blurredText])
|
|
572
|
+
// aligns itself through these while the UI thread draws through them.
|
|
573
|
+
private val capHeightCache = java.util.concurrent.ConcurrentHashMap<GlyphRole, Float>()
|
|
574
|
+
private val inkDescentCache = java.util.concurrent.ConcurrentHashMap<String, Float>()
|
|
552
575
|
|
|
553
576
|
/** A fraction digit's baseline in the line box, at its alignment. */
|
|
554
577
|
private val fractionBaseline: Float
|
|
@@ -560,6 +583,15 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
560
583
|
* strips and masks are keyed by it.
|
|
561
584
|
*/
|
|
562
585
|
private val roleKeys: Array<String>
|
|
586
|
+
/**
|
|
587
|
+
* Each role's paint as the font set was made, never changed after: what
|
|
588
|
+
* the warm thread measures and draws masks with. The UI thread changes the
|
|
589
|
+
* role paints' alpha as it draws, and a Paint promises no thread safety.
|
|
590
|
+
*/
|
|
591
|
+
private val maskPaints: Array<TextPaint>
|
|
592
|
+
|
|
593
|
+
/** The paint to measure or draw [role] with on this thread: the UI thread's own, the warm thread's unchanging copy. */
|
|
594
|
+
private fun threadPaint(role: GlyphRole): TextPaint = if (isMainThread()) paint(role) else maskPaints[role.ordinal]
|
|
563
595
|
|
|
564
596
|
init {
|
|
565
597
|
for (d in 0..9) digitWidths[d] = width(glyphs[d], GlyphRole.DIGIT)
|
|
@@ -575,6 +607,7 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
575
607
|
"${t.fontFamily}|${t.fontWeight}|${digit.textSize}|${p.textSize}|${p.color}|${p.typeface?.hashCode()}|${p.fontFeatureSettings}|" +
|
|
576
608
|
"${role.name}|${alignment(role)}|${if (role == GlyphRole.PREFIX) prefixOffset else if (role == GlyphRole.SUFFIX) suffixOffset else 0f}|$glyphsKey"
|
|
577
609
|
}
|
|
610
|
+
maskPaints = Array(GlyphRole.entries.size) { TextPaint(paint(GlyphRole.entries[it])).apply { alpha = 255 } }
|
|
578
611
|
}
|
|
579
612
|
|
|
580
613
|
private fun key(role: GlyphRole): String = roleKeys[role.ordinal]
|
|
@@ -600,7 +633,7 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
600
633
|
// One map per role: a joined "role|text" key allocated a string on every
|
|
601
634
|
// lookup, and the layout looks widths up for every glyph on every frame.
|
|
602
635
|
fun width(text: String, role: GlyphRole): Float =
|
|
603
|
-
widthCache[role.ordinal].getOrPut(text) {
|
|
636
|
+
widthCache[role.ordinal].getOrPut(text) { threadPaint(role).measureText(text) }
|
|
604
637
|
|
|
605
638
|
private val shapedCache = Array(GlyphRole.entries.size) { java.util.concurrent.ConcurrentHashMap<String, ShapedText>() }
|
|
606
639
|
|
|
@@ -656,13 +689,13 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
656
689
|
/** How far `text`'s ink hangs below the baseline (0 for digits and capitals). */
|
|
657
690
|
private fun inkDescent(text: String, role: GlyphRole): Float = inkDescentCache.getOrPut(role.name + "|" + text) {
|
|
658
691
|
val bounds = Rect()
|
|
659
|
-
|
|
692
|
+
threadPaint(role).getTextBounds(text, 0, text.length, bounds)
|
|
660
693
|
max(0, bounds.bottom).toFloat()
|
|
661
694
|
}
|
|
662
695
|
|
|
663
696
|
private fun capHeight(role: GlyphRole): Float = capHeightCache.getOrPut(role) {
|
|
664
697
|
val bounds = Rect()
|
|
665
|
-
|
|
698
|
+
threadPaint(role).getTextBounds("0", 0, 1, bounds)
|
|
666
699
|
-bounds.top.toFloat()
|
|
667
700
|
}
|
|
668
701
|
}
|
|
@@ -680,10 +713,16 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
680
713
|
val w = mask.width
|
|
681
714
|
val h = mask.height
|
|
682
715
|
val stride = mask.rowBytes
|
|
683
|
-
|
|
716
|
+
// Reused, not allocated per mask: two float copies of a large glyph went
|
|
717
|
+
// to the large-object heap, and a screenful of masks collected mid-frame.
|
|
718
|
+
val buffers = BlurBuffers.get(stride * h, w * h)
|
|
719
|
+
val bytes = buffers.bytes
|
|
720
|
+
bytes.clear()
|
|
721
|
+
bytes.limit(stride * h)
|
|
684
722
|
mask.copyPixelsToBuffer(bytes)
|
|
685
|
-
val alpha =
|
|
686
|
-
val scratch =
|
|
723
|
+
val alpha = buffers.alpha
|
|
724
|
+
val scratch = buffers.scratch
|
|
725
|
+
for (i in 0 until w * h) alpha[i] = (bytes.get((i / w) * stride + i % w).toInt() and 0xff).toFloat()
|
|
687
726
|
val window = (2 * radius + 1).toFloat()
|
|
688
727
|
repeat(3) {
|
|
689
728
|
// horizontal
|
|
@@ -706,7 +745,7 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
706
745
|
}
|
|
707
746
|
}
|
|
708
747
|
}
|
|
709
|
-
for (i in
|
|
748
|
+
for (i in 0 until w * h) bytes.put((i / w) * stride + i % w, Math.round(alpha[i]).coerceIn(0, 255).toByte())
|
|
710
749
|
bytes.rewind()
|
|
711
750
|
mask.copyPixelsFromBuffer(bytes)
|
|
712
751
|
}
|
|
@@ -1142,16 +1181,105 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
1142
1181
|
if (timing.transition != Transition.NUMERIC) return
|
|
1143
1182
|
val set = fonts
|
|
1144
1183
|
val fraction = format.fractionDigits > 0
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1184
|
+
// One task a mask, so a mask the UI thread asks for meanwhile is made
|
|
1185
|
+
// next rather than after the whole set (70 to 140 blurs).
|
|
1186
|
+
val roles = if (fraction) listOf(GlyphRole.DIGIT, GlyphRole.FRACTION) else listOf(GlyphRole.DIGIT)
|
|
1187
|
+
for (role in roles) for (digit in 0..9) for (level in 0..NUMERIC_BLUR_LEVELS) {
|
|
1188
|
+
WarmExecutor.execute { set.blurred(role, digit, level) }
|
|
1148
1189
|
}
|
|
1149
1190
|
}
|
|
1150
1191
|
|
|
1151
|
-
/**
|
|
1192
|
+
/**
|
|
1193
|
+
* One background thread for glyph masks, shared by every view. A mask the UI
|
|
1194
|
+
* thread is waiting on ([request]) goes to the front of the queue, ahead of
|
|
1195
|
+
* the ten-digits-at-every-level warm-ups ([execute]): behind a font change's
|
|
1196
|
+
* warm-up, the glyph on screen stayed sharp for its whole swap.
|
|
1197
|
+
*
|
|
1198
|
+
* At background priority plus one step (Glide's choice): below the UI
|
|
1199
|
+
* thread, not starved under load (Thread.MIN_PRIORITY is the lowest nice
|
|
1200
|
+
* level there is). A mask that cannot be made (out of memory, say) is
|
|
1201
|
+
* skipped, the glyph stays sharp, and it is not asked for again for a
|
|
1202
|
+
* while: an exception escaping a thread of its own takes the whole app down
|
|
1203
|
+
* on Android, and a failure retried every frame logged every frame. Any
|
|
1204
|
+
* other Error is a bug and is not swallowed.
|
|
1205
|
+
*/
|
|
1152
1206
|
private object WarmExecutor : java.util.concurrent.Executor {
|
|
1153
|
-
private val
|
|
1154
|
-
|
|
1207
|
+
private val queue = java.util.concurrent.LinkedBlockingDeque<Runnable>()
|
|
1208
|
+
/** Masks the UI thread has asked for and the warm thread has not made yet. */
|
|
1209
|
+
private val pending = java.util.concurrent.ConcurrentHashMap.newKeySet<String>()
|
|
1210
|
+
/** When a mask last failed, by key: not asked for again until [RETRY_MS] later. */
|
|
1211
|
+
private val failed = java.util.concurrent.ConcurrentHashMap<String, Long>()
|
|
1212
|
+
private const val RETRY_MS = 2000L
|
|
1213
|
+
|
|
1214
|
+
init {
|
|
1215
|
+
Thread({
|
|
1216
|
+
android.os.Process.setThreadPriority(
|
|
1217
|
+
android.os.Process.THREAD_PRIORITY_BACKGROUND + android.os.Process.THREAD_PRIORITY_MORE_FAVORABLE
|
|
1218
|
+
)
|
|
1219
|
+
while (true) {
|
|
1220
|
+
val task = try {
|
|
1221
|
+
queue.take()
|
|
1222
|
+
} catch (_: InterruptedException) {
|
|
1223
|
+
continue
|
|
1224
|
+
}
|
|
1225
|
+
try {
|
|
1226
|
+
task.run()
|
|
1227
|
+
} catch (e: Exception) {
|
|
1228
|
+
android.util.Log.w("NitroNumber", "A glyph mask could not be made; the glyph is drawn sharp", e)
|
|
1229
|
+
} catch (e: OutOfMemoryError) {
|
|
1230
|
+
android.util.Log.w("NitroNumber", "Out of memory making a glyph mask; the glyph is drawn sharp", e)
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
}, "NitroNumberWarm").apply {
|
|
1234
|
+
isDaemon = true
|
|
1235
|
+
start()
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
|
|
1239
|
+
override fun execute(command: Runnable) {
|
|
1240
|
+
queue.offerLast(command)
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/** Makes [key]'s mask on the warm thread next, once however many frames ask for it while it is queued. */
|
|
1244
|
+
fun request(key: String, make: () -> Unit) {
|
|
1245
|
+
failed[key]?.let { if (SystemClock.uptimeMillis() - it < RETRY_MS) return }
|
|
1246
|
+
if (!pending.add(key)) return
|
|
1247
|
+
queue.offerFirst(
|
|
1248
|
+
Runnable {
|
|
1249
|
+
try {
|
|
1250
|
+
make()
|
|
1251
|
+
failed.remove(key)
|
|
1252
|
+
} catch (e: Exception) {
|
|
1253
|
+
failed[key] = SystemClock.uptimeMillis()
|
|
1254
|
+
throw e
|
|
1255
|
+
} catch (e: OutOfMemoryError) {
|
|
1256
|
+
failed[key] = SystemClock.uptimeMillis()
|
|
1257
|
+
throw e
|
|
1258
|
+
} finally {
|
|
1259
|
+
pending.remove(key)
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
)
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
/** Per-thread buffers for [boxBlurMask], grown to the largest mask that thread has blurred. */
|
|
1267
|
+
private object BlurBuffers {
|
|
1268
|
+
class Buffers {
|
|
1269
|
+
var bytes: java.nio.ByteBuffer = java.nio.ByteBuffer.allocate(0)
|
|
1270
|
+
var alpha = FloatArray(0)
|
|
1271
|
+
var scratch = FloatArray(0)
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
private val local = ThreadLocal.withInitial { Buffers() }
|
|
1275
|
+
|
|
1276
|
+
fun get(byteCount: Int, pixelCount: Int): Buffers = local.get()!!.apply {
|
|
1277
|
+
if (bytes.capacity() < byteCount) bytes = java.nio.ByteBuffer.allocate(byteCount)
|
|
1278
|
+
if (alpha.size < pixelCount) {
|
|
1279
|
+
alpha = FloatArray(pixelCount)
|
|
1280
|
+
scratch = FloatArray(pixelCount)
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1155
1283
|
}
|
|
1156
1284
|
|
|
1157
1285
|
/**
|
|
@@ -2028,18 +2156,38 @@ class NitroNumberView(context: Context) : View(context) {
|
|
|
2028
2156
|
private var bytes = 0L
|
|
2029
2157
|
|
|
2030
2158
|
@Synchronized
|
|
2159
|
+
fun peek(key: String): Bitmap? = entries[key]
|
|
2160
|
+
|
|
2161
|
+
/**
|
|
2162
|
+
* [make] runs OUTSIDE the lock. Run inside it, the warm thread (then at
|
|
2163
|
+
* Thread.MIN_PRIORITY) held the lock through each blur, and the UI thread's
|
|
2164
|
+
* lookup in onDraw waited on it: ANRs with the main thread `Blocked` in
|
|
2165
|
+
* `get`. Two threads making the same key both make it; the second keeps
|
|
2166
|
+
* the first's bitmap and recycles its own, which nobody has seen.
|
|
2167
|
+
*/
|
|
2031
2168
|
fun get(key: String, make: () -> Bitmap): Bitmap {
|
|
2032
|
-
|
|
2169
|
+
peek(key)?.let { return it }
|
|
2033
2170
|
val bitmap = make()
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
bytes
|
|
2041
|
-
eldest.
|
|
2171
|
+
synchronized(this) {
|
|
2172
|
+
entries[key]?.let { existing ->
|
|
2173
|
+
bitmap.recycle()
|
|
2174
|
+
return existing
|
|
2175
|
+
}
|
|
2176
|
+
entries[key] = bitmap
|
|
2177
|
+
bytes += bitmap.allocationByteCount
|
|
2178
|
+
val eldest = entries.entries.iterator()
|
|
2179
|
+
while (bytes > BUDGET && eldest.hasNext()) {
|
|
2180
|
+
val entry = eldest.next()
|
|
2181
|
+
if (entry.value === bitmap) break
|
|
2182
|
+
bytes -= entry.value.allocationByteCount
|
|
2183
|
+
eldest.remove()
|
|
2184
|
+
}
|
|
2042
2185
|
}
|
|
2186
|
+
// Immutable and uploaded ahead of its first draw: HWUI re-pins a mutable
|
|
2187
|
+
// bitmap at every sync, and the first frame that drew a fresh mask paid
|
|
2188
|
+
// for its texture upload. Only the one that is kept: a race's loser is
|
|
2189
|
+
// recycled above, unseen.
|
|
2190
|
+
bitmap.prepareToDraw()
|
|
2043
2191
|
return bitmap
|
|
2044
2192
|
}
|
|
2045
2193
|
}
|
package/cpp/RollingEngine.cpp
CHANGED
|
@@ -459,12 +459,39 @@ void RollingEngine::animateTo(double value, double now) {
|
|
|
459
459
|
popStart_ = now;
|
|
460
460
|
}
|
|
461
461
|
|
|
462
|
+
// On the spring, a wheel that was already rolling carries its speed into
|
|
463
|
+
// this roll. The spring's step response starts at rest, so every value of
|
|
464
|
+
// a stream (a slider, a dial, a live price) stopped each wheel and started
|
|
465
|
+
// it again: a figure fed by a slider stood still until the finger stopped.
|
|
466
|
+
if (easing_ == 4 && !next.numeric && transition_.active && !transition_.numeric && next.duration > 0) {
|
|
467
|
+
constexpr double h = 1.0 / 240.0;
|
|
468
|
+
const size_t shared = std::min(next.wheels.size(), transition_.wheels.size());
|
|
469
|
+
for (size_t i = 0; i < shared; i++) {
|
|
470
|
+
WheelTransition& wt = next.wheels[i];
|
|
471
|
+
const double travel = wt.to.position - wt.from.position;
|
|
472
|
+
if (std::fabs(travel) < 1e-6 || wt.from.linear != transition_.wheels[i].from.linear) {
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
const double speed = (rollPosition(transition_, i, now) - rollPosition(transition_, i, now - h)) / h;
|
|
476
|
+
wt.carriesSpeed = true;
|
|
477
|
+
wt.startSpeed = speed * next.duration / travel;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
462
481
|
transition_ = std::move(next);
|
|
463
482
|
apply(0);
|
|
464
483
|
applyEffects(now);
|
|
465
484
|
settle(target);
|
|
466
485
|
}
|
|
467
486
|
|
|
487
|
+
double RollingEngine::rollPosition(const Transition& tr, size_t index, double now) const {
|
|
488
|
+
const WheelTransition& wt = tr.wheels[index];
|
|
489
|
+
const double delay = index < tr.delays.size() ? tr.delays[index] : 0;
|
|
490
|
+
const double raw = tr.duration > 0 ? clamp01((now - tr.start - delay) / tr.duration) : 1.0;
|
|
491
|
+
const double t = !tr.fromMotion ? ease(raw) : wt.carriesSpeed ? easeFromMotion(raw, wt.startSpeed) : easeFromMotion(raw);
|
|
492
|
+
return wt.from.position + (wt.to.position - wt.from.position) * t;
|
|
493
|
+
}
|
|
494
|
+
|
|
468
495
|
void RollingEngine::planRoll(Transition& next, const Target& target, bool increasing, int count, int mandatory) const {
|
|
469
496
|
const int currentCount = static_cast<int>(wheels_.size());
|
|
470
497
|
// Below `pad`: decimal columns the format dropped (`changeFormat`).
|
|
@@ -510,15 +537,29 @@ void RollingEngine::planRoll(Transition& next, const Target& target, bool increa
|
|
|
510
537
|
// Interior wheel: shortest roll in the direction of the change, or
|
|
511
538
|
// with `shortest` the shorter way round for this wheel alone (8 → 2
|
|
512
539
|
// rolls back through 5), a tie (five apart) going with the change.
|
|
513
|
-
|
|
514
|
-
from
|
|
540
|
+
// A value arriving mid-roll moves where the wheel is going, not where
|
|
541
|
+
// it stands: by the step from the digit it was rolling to, onto the
|
|
542
|
+
// one it still had to cover (NumberFlow's accumulating composite). A
|
|
543
|
+
// stream that runs one way piles up and the wheel spins to keep up;
|
|
544
|
+
// one that turns back takes it off, and the wheel slows and turns with
|
|
545
|
+
// it. Measured from where the wheel stood, a wheel that lagged behind
|
|
546
|
+
// or ran past its digit went a whole turn round, or the short way
|
|
547
|
+
// backwards, and a fast drag left it stalling.
|
|
548
|
+
const bool rolling = next.fromMotion && transition_.active && !transition_.numeric &&
|
|
549
|
+
power < static_cast<int>(transition_.wheels.size()) && !current.linear &&
|
|
550
|
+
!transition_.wheels[static_cast<size_t>(power)].to.linear && current.blend >= 1;
|
|
551
|
+
const double heading = rolling ? transition_.wheels[static_cast<size_t>(power)].to.position : 0;
|
|
552
|
+
const double base = rolling ? wrapTo(heading, modulus) : wrapTo(from.position, modulus);
|
|
553
|
+
if (!rolling) {
|
|
554
|
+
from.position = base;
|
|
555
|
+
}
|
|
515
556
|
from.linear = false;
|
|
516
557
|
const double up = wrapTo(digit - base, modulus);
|
|
517
558
|
const double down = wrapTo(base - digit, modulus);
|
|
518
559
|
double delta = increasing ? up : -down;
|
|
519
560
|
if (direction_ == 3 && up != down) delta = up < down ? up : -down;
|
|
520
561
|
if (delta == 0 && power < highestChange) delta = increasing ? modulus : -modulus;
|
|
521
|
-
to = Wheel{base + delta, 1.0, false, false};
|
|
562
|
+
to = Wheel{(rolling ? heading : base) + delta, 1.0, false, false};
|
|
522
563
|
}
|
|
523
564
|
next.finals.push_back(Wheel{digit, 1.0, false, false});
|
|
524
565
|
} else {
|
|
@@ -961,7 +1002,7 @@ void RollingEngine::apply(double elapsed) {
|
|
|
961
1002
|
// a column opens and closes over the duration itself.
|
|
962
1003
|
const double span = tr.style == 1 ? tr.duration / kNumericTail : tr.duration;
|
|
963
1004
|
const double rawSpan = span > 0 ? clamp01((elapsed - delay) / span) : 1.0;
|
|
964
|
-
double t = tr.fromMotion ? easeFromMotion(rawSpan) :
|
|
1005
|
+
double t = !tr.fromMotion ? ease(rawSpan) : wt.carriesSpeed ? easeFromMotion(rawSpan, wt.startSpeed) : easeFromMotion(rawSpan);
|
|
965
1006
|
if (tr.numeric) {
|
|
966
1007
|
// A column opens on the arriving glyph's size-and-opacity spring and
|
|
967
1008
|
// closes on the leaving glyph's blur, the faster one: on the
|
|
@@ -1223,12 +1264,34 @@ double RollingEngine::easeFromMotion(double t) const {
|
|
|
1223
1264
|
case 1:
|
|
1224
1265
|
return t; // linear / easeIn: keep the wheel moving at a steady pace
|
|
1225
1266
|
case 4:
|
|
1226
|
-
return spring(t, bounce_); //
|
|
1267
|
+
return spring(t, bounce_); // from rest; a wheel in motion carries its speed (below)
|
|
1227
1268
|
default:
|
|
1228
1269
|
return 1 - std::pow(1 - t, 3); // easeOut / easeInOut: decelerate into the new target
|
|
1229
1270
|
}
|
|
1230
1271
|
}
|
|
1231
1272
|
|
|
1273
|
+
double RollingEngine::easeFromMotion(double t, double startSpeed) const {
|
|
1274
|
+
if (easing_ == 4) {
|
|
1275
|
+
// Bounded: a wheel a hair from its digit would otherwise read as flying.
|
|
1276
|
+
return springFrom(t, bounce_, std::min(12.0, std::max(-12.0, startSpeed)));
|
|
1277
|
+
}
|
|
1278
|
+
return easeFromMotion(t);
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
double RollingEngine::springFrom(double t, double bounce, double startSpeed) {
|
|
1282
|
+
// x(t) of the same spring as `spring`, released at 0 towards 1 at speed v0:
|
|
1283
|
+
// 1 - e^{-kt}(cos ωd t + ((k - v0)/ωd) sin ωd t), or 1 - (1 + (k - v0)t)e^{-kt}
|
|
1284
|
+
// critically damped. v0 = 0 is `spring` exactly.
|
|
1285
|
+
const double zeta = std::min(1.0, std::max(0.05, 1.0 - clamp01(bounce)));
|
|
1286
|
+
const double omega = 3.0 * kPi;
|
|
1287
|
+
const double k = zeta * omega;
|
|
1288
|
+
if (zeta >= 0.999) {
|
|
1289
|
+
return 1 - (1 + (k - startSpeed) * t) * std::exp(-k * t);
|
|
1290
|
+
}
|
|
1291
|
+
const double wd = omega * std::sqrt(1 - zeta * zeta);
|
|
1292
|
+
return 1 - std::exp(-k * t) * (std::cos(wd * t) + ((k - startSpeed) / wd) * std::sin(wd * t));
|
|
1293
|
+
}
|
|
1294
|
+
|
|
1232
1295
|
/// Step response of a damped spring, normalised so it has settled at t == 1.
|
|
1233
1296
|
/// `bounce` maps to the damping ratio like SwiftUI's `.spring(duration:bounce:)`.
|
|
1234
1297
|
double RollingEngine::spring(double t, double bounce) {
|
package/cpp/RollingEngine.hpp
CHANGED
|
@@ -341,6 +341,11 @@ private:
|
|
|
341
341
|
/// being cut short. `clock` is how far into the swap it was (seconds).
|
|
342
342
|
bool continues = false;
|
|
343
343
|
double clock = 0;
|
|
344
|
+
/// Roll: the wheel was already moving when the value changed, at
|
|
345
|
+
/// `startSpeed` in this roll's own units (its travel per duration); the
|
|
346
|
+
/// spring starts at that speed rather than from rest.
|
|
347
|
+
bool carriesSpeed = false;
|
|
348
|
+
double startSpeed = 0;
|
|
344
349
|
};
|
|
345
350
|
struct Transition {
|
|
346
351
|
bool active = false;
|
|
@@ -427,7 +432,15 @@ private:
|
|
|
427
432
|
/// The curve used when re-targeting mid-roll: the ease-in curves collapse to
|
|
428
433
|
/// their ease-out / linear counterparts so a wheel in motion never stalls.
|
|
429
434
|
double easeFromMotion(double t) const;
|
|
435
|
+
/// The roll's curve for a wheel that was already moving at `startSpeed`
|
|
436
|
+
/// (travel per duration) when the value changed: the spring starts at that
|
|
437
|
+
/// speed, the other curves are `easeFromMotion(t)`.
|
|
438
|
+
double easeFromMotion(double t, double startSpeed) const;
|
|
430
439
|
static double spring(double t, double bounce);
|
|
440
|
+
/// `spring` starting at `startSpeed` (travel per duration) instead of from rest.
|
|
441
|
+
static double springFrom(double t, double bounce, double startSpeed);
|
|
442
|
+
/// Where wheel `index` of a roll stands at `now`.
|
|
443
|
+
double rollPosition(const Transition& tr, size_t index, double now) const;
|
|
431
444
|
/// Step response of a damped spring with damping ratio `zeta`, scaled so it
|
|
432
445
|
/// has settled (within 2 %) at t == `settle`; 0 at t <= 0.
|
|
433
446
|
static double damped(double t, double zeta, double settle);
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
//
|
|
2
|
+
// FormatFigure.cpp
|
|
3
|
+
// NitroInput
|
|
4
|
+
//
|
|
5
|
+
|
|
6
|
+
#include "FormatFigure.hpp"
|
|
7
|
+
|
|
8
|
+
#include <cstdlib>
|
|
9
|
+
|
|
10
|
+
namespace margelo::nitro::nitroinput::numberformat {
|
|
11
|
+
|
|
12
|
+
namespace {
|
|
13
|
+
|
|
14
|
+
bool isNumberPart(PartType type) {
|
|
15
|
+
return type == PartType::Integer || type == PartType::Group || type == PartType::Decimal || type == PartType::Fraction;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/// `text` with the locale's digits written as Latin ones.
|
|
19
|
+
std::string latin(const std::string& text, const std::array<std::string, 10>& localeDigits) {
|
|
20
|
+
std::string out;
|
|
21
|
+
out.reserve(text.size());
|
|
22
|
+
size_t i = 0;
|
|
23
|
+
while (i < text.size()) {
|
|
24
|
+
bool matched = false;
|
|
25
|
+
for (int d = 0; d < 10; d++) {
|
|
26
|
+
const std::string& glyph = localeDigits[static_cast<size_t>(d)];
|
|
27
|
+
if (!glyph.empty() && text.compare(i, glyph.size(), glyph) == 0) {
|
|
28
|
+
out.push_back(static_cast<char>('0' + d));
|
|
29
|
+
i += glyph.size();
|
|
30
|
+
matched = true;
|
|
31
|
+
break;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
if (!matched) out.push_back(text[i++]);
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
std::string joined(const std::vector<Part>& parts, PartType type, const std::array<std::string, 10>& localeDigits) {
|
|
40
|
+
std::string out;
|
|
41
|
+
for (const Part& p : parts) {
|
|
42
|
+
if (p.type == type) out += p.value;
|
|
43
|
+
}
|
|
44
|
+
return latin(out, localeDigits);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/// The text before and after the number in `parts`; the sign is the components' own glyph, not part of either.
|
|
48
|
+
void affixesOf(const std::vector<Part>& parts, std::string& prefix, std::string& suffix) {
|
|
49
|
+
int first = -1;
|
|
50
|
+
int last = -1;
|
|
51
|
+
for (int i = 0; i < static_cast<int>(parts.size()); i++) {
|
|
52
|
+
if (isNumberPart(parts[static_cast<size_t>(i)].type)) {
|
|
53
|
+
if (first < 0) first = i;
|
|
54
|
+
last = i;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
prefix.clear();
|
|
58
|
+
suffix.clear();
|
|
59
|
+
if (first < 0) return;
|
|
60
|
+
for (int i = 0; i < static_cast<int>(parts.size()); i++) {
|
|
61
|
+
const Part& p = parts[static_cast<size_t>(i)];
|
|
62
|
+
if (p.type == PartType::MinusSign || p.type == PartType::PlusSign) continue;
|
|
63
|
+
if (i < first) prefix += p.value;
|
|
64
|
+
if (i > last) suffix += p.value;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
bool isLatin(const std::array<std::string, 10>& localeDigits) {
|
|
69
|
+
for (int d = 0; d < 10; d++) {
|
|
70
|
+
if (localeDigits[static_cast<size_t>(d)] != std::string(1, static_cast<char>('0' + d))) return false;
|
|
71
|
+
}
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
} // namespace
|
|
76
|
+
|
|
77
|
+
double Figure::value() const {
|
|
78
|
+
if (!finite) return 0;
|
|
79
|
+
const double magnitude = std::strtod(digits.c_str(), nullptr);
|
|
80
|
+
if (magnitude == 0) return 0;
|
|
81
|
+
return negative ? -magnitude : magnitude;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
Figure figureOf(const std::vector<Part>& parts, bool negative, const std::array<std::string, 10>& localeDigits) {
|
|
85
|
+
Figure figure;
|
|
86
|
+
affixesOf(parts, figure.prefix, figure.suffix);
|
|
87
|
+
const std::string integer = joined(parts, PartType::Integer, localeDigits);
|
|
88
|
+
const std::string fraction = joined(parts, PartType::Fraction, localeDigits);
|
|
89
|
+
// NaN and infinities have no integer part: nothing the digits can roll to.
|
|
90
|
+
if (integer.empty()) return figure;
|
|
91
|
+
figure.finite = true;
|
|
92
|
+
figure.digits = fraction.empty() ? integer : integer + "." + fraction;
|
|
93
|
+
figure.fractionDigits = static_cast<int>(fraction.size());
|
|
94
|
+
bool nonZero = false;
|
|
95
|
+
for (char c : figure.digits) nonZero = nonZero || (c >= '1' && c <= '9');
|
|
96
|
+
figure.negative = negative && nonZero;
|
|
97
|
+
return figure;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
Layout layoutOf(const std::vector<Part>& sample, const std::vector<Part>& negativeOne, const std::array<std::string, 10>& localeDigits) {
|
|
101
|
+
Layout layout;
|
|
102
|
+
affixesOf(sample, layout.prefix, layout.suffix);
|
|
103
|
+
std::vector<int> integers;
|
|
104
|
+
bool hasGroup = false;
|
|
105
|
+
bool hasDecimal = false;
|
|
106
|
+
for (const Part& p : sample) {
|
|
107
|
+
if (p.type == PartType::Group && !hasGroup) {
|
|
108
|
+
layout.groupingSeparator = p.value;
|
|
109
|
+
hasGroup = true;
|
|
110
|
+
} else if (p.type == PartType::Decimal && !hasDecimal) {
|
|
111
|
+
layout.decimalSeparator = p.value;
|
|
112
|
+
hasDecimal = true;
|
|
113
|
+
} else if (p.type == PartType::Integer) {
|
|
114
|
+
integers.push_back(static_cast<int>(latin(p.value, localeDigits).size()));
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// "12,34,567": the last group is the first size, the one before it every later one.
|
|
118
|
+
if (integers.size() >= 3) {
|
|
119
|
+
layout.groupingSizes = {integers[integers.size() - 1], integers[integers.size() - 2]};
|
|
120
|
+
}
|
|
121
|
+
int minus = -1;
|
|
122
|
+
int currency = -1;
|
|
123
|
+
for (int i = 0; i < static_cast<int>(negativeOne.size()); i++) {
|
|
124
|
+
const PartType type = negativeOne[static_cast<size_t>(i)].type;
|
|
125
|
+
if (type == PartType::MinusSign && minus < 0) minus = i;
|
|
126
|
+
if ((type == PartType::Currency || type == PartType::PercentSign) && currency < 0) currency = i;
|
|
127
|
+
}
|
|
128
|
+
if (minus >= 0) layout.minusSign = negativeOne[static_cast<size_t>(minus)].value;
|
|
129
|
+
layout.signAfterAffix = minus >= 0 && currency >= 0 && minus > currency;
|
|
130
|
+
if (!isLatin(localeDigits)) layout.digitGlyphs.assign(localeDigits.begin(), localeDigits.end());
|
|
131
|
+
return layout;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
} // namespace margelo::nitro::nitroinput::numberformat
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
//
|
|
2
|
+
// FormatFigure.hpp
|
|
3
|
+
// NitroInput
|
|
4
|
+
//
|
|
5
|
+
// What `NitroNumber` and `NitroInput` take from a formatted number: the
|
|
6
|
+
// figure the digits show, and the text around it. Read off the parts the
|
|
7
|
+
// formatter produced, so the figure is rounded and trimmed exactly as the
|
|
8
|
+
// format prints it (its rounding mode, trailing zeros, significant digits,
|
|
9
|
+
// compact notation), from the decimal the value was, never through a double.
|
|
10
|
+
// Plain C++, unit-tested on the host.
|
|
11
|
+
//
|
|
12
|
+
|
|
13
|
+
#pragma once
|
|
14
|
+
|
|
15
|
+
#include "NumberFormatCore.hpp"
|
|
16
|
+
|
|
17
|
+
#include <array>
|
|
18
|
+
#include <string>
|
|
19
|
+
#include <vector>
|
|
20
|
+
|
|
21
|
+
namespace margelo::nitro::nitroinput::numberformat {
|
|
22
|
+
|
|
23
|
+
/// One formatted value, as the rolling figure takes it.
|
|
24
|
+
struct Figure {
|
|
25
|
+
/// Finite, and so a figure the digits can roll to (NaN and infinities are not).
|
|
26
|
+
bool finite = false;
|
|
27
|
+
/// The value was below zero and its shown digits are not all zero: "-$0.00" is not negative.
|
|
28
|
+
bool negative = false;
|
|
29
|
+
/// The digits shown, in Latin digits with "." before the fraction ("1234.5"), without sign or grouping.
|
|
30
|
+
std::string digits;
|
|
31
|
+
/// How many of `digits` follow the point: what this value shows ("$1,234" 0, "$1,234.50" 2).
|
|
32
|
+
int fractionDigits = 0;
|
|
33
|
+
/// The text before and after the number, without the sign: the components draw their own.
|
|
34
|
+
std::string prefix;
|
|
35
|
+
std::string suffix;
|
|
36
|
+
|
|
37
|
+
/// The figure as a double: its digits, signed. 0 (never -0) for a figure that is not finite or rounds to nothing.
|
|
38
|
+
double value() const;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/// The figure in `parts`, formatted from a value that was `negative`.
|
|
42
|
+
/// `localeDigits` are the format's digits 0…9, which map back to Latin ones.
|
|
43
|
+
Figure figureOf(const std::vector<Part>& parts, bool negative, const std::array<std::string, 10>& localeDigits);
|
|
44
|
+
|
|
45
|
+
/// The shape of a format, as the components lay a number out.
|
|
46
|
+
struct Layout {
|
|
47
|
+
std::string prefix;
|
|
48
|
+
std::string suffix;
|
|
49
|
+
/// Empty when the format does not group.
|
|
50
|
+
std::string groupingSeparator;
|
|
51
|
+
std::string decimalSeparator = ".";
|
|
52
|
+
/// A negative amount's sign comes after the prefix ("$-5"), not before it ("-$5").
|
|
53
|
+
bool signAfterAffix = false;
|
|
54
|
+
std::string minusSign = "-";
|
|
55
|
+
/// The group nearest the decimal point and every one before it ([3, 2]: 12,34,567).
|
|
56
|
+
std::vector<int> groupingSizes = {3};
|
|
57
|
+
/// The format's digits 0…9, or empty for Latin ones.
|
|
58
|
+
std::vector<std::string> digitGlyphs;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/// The layout of a format, read off its parts for a value with every part
|
|
62
|
+
/// (`sample`: 1234567, or 1234567.5 when it shows a fraction) and for -1.
|
|
63
|
+
Layout layoutOf(const std::vector<Part>& sample, const std::vector<Part>& negativeOne, const std::array<std::string, 10>& localeDigits);
|
|
64
|
+
|
|
65
|
+
} // namespace margelo::nitro::nitroinput::numberformat
|