-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathRiveReactNativeView.kt
More file actions
1347 lines (1168 loc) · 41.7 KB
/
RiveReactNativeView.kt
File metadata and controls
1347 lines (1168 loc) · 41.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.rivereactnative
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.graphics.Color
import android.net.Uri
import android.widget.FrameLayout
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import app.rive.runtime.kotlin.RiveAnimationView
import app.rive.runtime.kotlin.RiveViewLifecycleObserver
import app.rive.runtime.kotlin.controllers.RiveFileController
import app.rive.runtime.kotlin.core.*
import app.rive.runtime.kotlin.core.errors.*
import app.rive.runtime.kotlin.renderers.PointerEvents
import com.android.volley.DefaultRetryPolicy
import com.android.volley.NetworkResponse
import com.android.volley.ParseError
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.HttpHeaderParser
import com.android.volley.toolbox.Volley
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.ReadableType
import com.facebook.react.bridge.WritableMap
import com.facebook.react.modules.core.DeviceEventManagerModule
import com.facebook.react.modules.core.ExceptionsManagerModule
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.uimanager.events.RCTEventEmitter
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream
import java.io.UnsupportedEncodingException
import java.net.MalformedURLException
import java.net.URI
import java.net.URISyntaxException
import java.net.URL
class ReactNativeRiveViewLifecycleObserver(dependencies: MutableList<RefCount>) :
RiveViewLifecycleObserver(dependencies) {
/**
* OnDestroy is different in Rive ReactNative compared to Rive Android.
* Releasing dependencies is managed in `ReactNativeRiveAnimationView.dispose()`
*/
@SuppressLint("MissingSuperCall")
override fun onDestroy(owner: LifecycleOwner) {
owner.lifecycle.removeObserver(this)
}
fun dispose() {
dependencies.forEach { it.release() }
dependencies.clear()
}
}
@SuppressLint("ViewConstructor")
class ReactNativeRiveAnimationView(private val context: ThemedReactContext) :
RiveAnimationView(context) {
fun dispose() {
(lifecycleObserver as ReactNativeRiveViewLifecycleObserver).dispose()
}
@SuppressLint("VisibleForTests")
override fun createObserver(): LifecycleObserver {
return ReactNativeRiveViewLifecycleObserver(
listOfNotNull(
controller, rendererAttributes.assetLoader
).toMutableList()
)
}
}
@SuppressLint("ViewConstructor")
class RiveReactNativeView(private val context: ThemedReactContext) : FrameLayout(context) {
private var riveAnimationView: ReactNativeRiveAnimationView? = null
private var resourceName: String? = null
private var resId: Int = -1
private var url: String? = null
private var animationName: String? = null
private var stateMachineName: String? = null
private var artboardName: String? = null
private var fit: Fit = Fit.CONTAIN
private var layoutScaleFactor: Float? = null
private var alignment: Alignment = Alignment.CENTER
private var autoplay: Boolean = false
private var referencedAssets: ReadableMap? = null
private var shouldBeReloaded = true
private var exceptionManager: ExceptionsManagerModule? = null
private var isUserHandlingErrors = false
private var willDispose = false
private var listener: RiveFileController.Listener
private var eventListener: RiveFileController.RiveEventListener
private var assetStore: RiveReactNativeAssetStore? = null
private val scope = CoroutineScope(Dispatchers.Default)
private var dataBindingConfig: DataBindingConfig? = null
private val propertyListeners = mutableMapOf<String, PropertyListener>()
enum class Events(private val mName: String) {
PLAY("onPlay"), PAUSE("onPause"), STOP("onStop"), LOOP_END("onLoopEnd"), STATE_CHANGED("onStateChanged"), RIVE_EVENT(
"onRiveEventReceived"
),
ERROR("onError");
override fun toString(): String {
return mName
}
}
init {
riveAnimationView = ReactNativeRiveAnimationView(context)
listener = object : RiveFileController.Listener {
override fun notifyLoop(animation: PlayableInstance) {
if (animation is LinearAnimationInstance) {
onLoopEnd(animation.name, RNLoopMode.mapToRNLoopMode(animation.loop))
} else {
throw IllegalArgumentException("Only animation can be passed as an argument")
}
}
override fun notifyPause(animation: PlayableInstance) {
if (animation is LinearAnimationInstance) {
onPause(animation.name)
}
if (animation is StateMachineInstance) {
onPause(animation.name, true)
}
}
override fun notifyPlay(animation: PlayableInstance) {
if (animation is LinearAnimationInstance) {
onPlay(animation.name)
}
if (animation is StateMachineInstance) {
onPlay(animation.name, true)
}
}
override fun notifyStateChanged(stateMachineName: String, stateName: String) {
onStateChanged(stateMachineName, stateName)
}
override fun notifyStop(animation: PlayableInstance) {
if (animation is LinearAnimationInstance) {
onStop(animation.name)
}
if (animation is StateMachineInstance) {
onStop(animation.name, true)
}
}
}
eventListener = object : RiveFileController.RiveEventListener {
override fun notifyEvent(event: RiveEvent) {
when (event) {
is RiveGeneralEvent -> onRiveEventReceived(event)
is RiveOpenURLEvent -> onRiveEventReceived(event)
}
}
}
addListeners()
autoplay = false
addView(riveAnimationView)
}
fun dispose() {
willDispose = true
}
override fun onDetachedFromWindow() {
if (willDispose) {
scope.cancel()
assetStore?.dispose()
riveAnimationView?.dispose()
removeListeners()
clearReferences()
}
super.onDetachedFromWindow()
}
private fun addListeners() {
riveAnimationView?.registerListener(listener)
riveAnimationView?.addEventListener(eventListener)
}
private fun removeListeners() {
clearPropertyListeners()
riveAnimationView?.unregisterListener(listener)
riveAnimationView?.removeEventListener(eventListener)
}
private fun clearReferences() {
assetStore = null
riveAnimationView = null
exceptionManager = null
referencedAssets = null
}
fun onPlay(animationName: String, isStateMachine: Boolean = false) {
val reactContext = context as ReactContext
val data = Arguments.createMap()
data.putString("animationName", animationName)
data.putBoolean("isStateMachine", isStateMachine)
reactContext.getJSModule(RCTEventEmitter::class.java)
.receiveEvent(id, Events.PLAY.toString(), data)
}
fun onPause(animationName: String, isStateMachine: Boolean = false) {
val reactContext = context as ReactContext
val data = Arguments.createMap()
data.putString("animationName", animationName)
data.putBoolean("isStateMachine", isStateMachine)
reactContext.getJSModule(RCTEventEmitter::class.java)
.receiveEvent(id, Events.PAUSE.toString(), data)
}
fun onStop(animationName: String, isStateMachine: Boolean = false) {
val reactContext = context as ReactContext
val data = Arguments.createMap()
data.putString("animationName", animationName)
data.putBoolean("isStateMachine", isStateMachine)
reactContext.getJSModule(RCTEventEmitter::class.java)
.receiveEvent(id, Events.STOP.toString(), data)
}
fun onLoopEnd(animationName: String, loopMode: RNLoopMode) {
val reactContext = context as ReactContext
val data = Arguments.createMap()
data.putString("animationName", animationName)
data.putString("loopMode", loopMode.toString())
reactContext.getJSModule(RCTEventEmitter::class.java)
.receiveEvent(id, Events.LOOP_END.toString(), data)
}
fun onStateChanged(stateMachineName: String, stateName: String) {
val reactContext = context as ReactContext
val data = Arguments.createMap()
data.putString("stateMachineName", stateMachineName)
data.putString("stateName", stateName)
reactContext.getJSModule(RCTEventEmitter::class.java)
.receiveEvent(id, Events.STATE_CHANGED.toString(), data)
}
private fun convertHashMapToWritableMap(hashMap: HashMap<String, Any>): WritableMap {
val writableMap = Arguments.createMap()
for ((key, value) in hashMap) {
when (value) {
is String -> writableMap.putString(key, value)
is Int -> writableMap.putInt(key, value)
is Float -> writableMap.putDouble(key, value.toDouble())
is Double -> writableMap.putDouble(key, value)
is Boolean -> writableMap.putBoolean(key, value)
}
}
return writableMap
}
fun onRiveEventReceived(event: RiveEvent) {
val reactContext = context as ReactContext
val topLevelDict = Arguments.createMap()
val eventProperties = Arguments.createMap().apply {
putString("name", event.name)
putDouble("delay", event.delay.toDouble())
putMap("properties", convertHashMapToWritableMap(event.properties))
}
if (event is RiveOpenURLEvent) {
eventProperties.putString("url", event.url)
eventProperties.putString("target", event.target)
}
topLevelDict.putMap(
"riveEvent", eventProperties
)
reactContext.getJSModule(RCTEventEmitter::class.java)
.receiveEvent(id, Events.RIVE_EVENT.toString(), topLevelDict)
}
fun play(
animationName: String, rnLoopMode: RNLoopMode, rnDirection: RNDirection, isStateMachine: Boolean
) {
val loop = RNLoopMode.mapToRiveLoop(rnLoopMode)
val direction = RNDirection.mapToRiveDirection(rnDirection)
if (animationName.isEmpty()) {
riveAnimationView?.play(
loop, direction
) // intentionally we skipped areStateMachines argument to keep same behaviour as it is in the native sdk
} else {
try {
riveAnimationView?.play(animationName, loop, direction, isStateMachine)
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
}
fun pause() {
try {
if (riveAnimationView?.playingAnimations?.isNotEmpty() == true) {
riveAnimationView!!.pause(riveAnimationView!!.playingAnimations.first().name)
} else if (riveAnimationView?.playingStateMachines?.isNotEmpty() == true) {
riveAnimationView!!.pause(riveAnimationView!!.playingStateMachines.first().name, true)
} else {
riveAnimationView?.pause()
}
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun stop() {
try {
riveAnimationView?.stop()
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun reset() {
url?.let {
if (resId == -1) {
riveAnimationView?.artboardRenderer?.reset()
}
} ?: run {
if (resId != -1) {
riveAnimationView?.reset()
}
}
}
fun touchBegan(x: Float, y: Float) {
riveAnimationView?.controller?.pointerEvent(PointerEvents.POINTER_DOWN, 0, x, y)
}
fun touchEnded(x: Float, y: Float) {
riveAnimationView?.controller?.pointerEvent(PointerEvents.POINTER_UP, 0, x, y)
}
fun setTextRunValue(textRunName: String, textValue: String) {
try {
riveAnimationView?.controller?.activeArtboard?.textRun(textRunName)?.text = textValue
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun setTextRunValueAtPath(textRunName: String, textValue: String, path: String) {
try {
riveAnimationView?.controller?.activeArtboard?.textRun(textRunName, path)?.text = textValue
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
private fun getViewModelInstance(): ViewModelInstance? {
return riveAnimationView?.controller?.activeArtboard?.viewModelInstance
}
fun setBooleanPropertyValue(path: String, value: Boolean) {
try {
getViewModelInstance()?.getBooleanProperty(path)?.value = value
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun setStringPropertyValue(path: String, value: String) {
try {
getViewModelInstance()?.getStringProperty(path)?.value = value
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun setNumberPropertyValue(path: String, value: Float) {
try {
getViewModelInstance()?.getNumberProperty(path)?.value = value
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun setColorPropertyValue(path: String, r: Int, g: Int, b: Int, a: Int) {
try {
val color = Color.argb(a, r, g, b)
getViewModelInstance()?.getColorProperty(path)?.value = color
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun setEnumPropertyValue(path: String, value: String) {
try {
getViewModelInstance()?.getEnumProperty(path)?.value = value
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun fireTriggerProperty(path: String) {
try {
getViewModelInstance()?.getTriggerProperty(path)?.trigger()
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
private fun removePropertyListener(key: String) {
propertyListeners[key]?.job?.cancel()
propertyListeners.remove(key)
}
fun registerPropertyListener(path: String, propertyType: String) {
val key = "$propertyType:$path:$id"
// Make sure to remove current listeners, as the same listener may have been registered but
// on a new view model instance.
// We play it safe and always remove the listener and re-add it
removePropertyListener(key)
val propertyTypeEnum = RNPropertyType.mapToRNPropertyType(propertyType)
try {
val viewModelInstance = getViewModelInstance() ?: return
val property = when (propertyTypeEnum) {
RNPropertyType.String -> viewModelInstance.getStringProperty(path)
RNPropertyType.Boolean -> viewModelInstance.getBooleanProperty(path)
RNPropertyType.Number -> viewModelInstance.getNumberProperty(path)
RNPropertyType.Color -> viewModelInstance.getColorProperty(path)
RNPropertyType.Enum -> viewModelInstance.getEnumProperty(path)
RNPropertyType.Trigger -> viewModelInstance.getTriggerProperty(path)
}
val job = scope.launch {
when (propertyTypeEnum) {
RNPropertyType.Trigger -> {
// We drop the first value as a trigger has no initial value
property.valueFlow.drop(1).collect { _ ->
sendEvent(key, null)
}
}
else -> {
property.valueFlow.collect { value ->
sendEvent(key, value)
}
}
}
}
propertyListeners[key] = PropertyListener(viewModelInstance, path, propertyType, job)
} catch (ex: RiveException) {
handleRiveException(ex)
} catch (ex: Exception) {
showRNRiveError("Unexpected error during data binding configuration", ex)
}
}
private val loadedTag: String
get() = "RiveReactNativeLoaded:${this.id}"
private fun sendRiveLoadedEvent() {
sendEvent(loadedTag, null)
}
private fun sendEvent(eventName: String, value: Any?) {
context
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
.emit(eventName, value)
}
private fun configureDataBinding() {
try {
val file = riveAnimationView?.controller?.file ?: return
val artboard = riveAnimationView?.controller?.activeArtboard ?: return
val viewModel = file.defaultViewModelForArtboard(artboard)
fun bindInstance(instance: ViewModelInstance) {
riveAnimationView?.controller?.stateMachines?.first()?.viewModelInstance = instance
riveAnimationView?.controller?.activeArtboard?.viewModelInstance = instance
// Re-register the listener if the listener wasn't added on this view model instance.
// As calling registerPropertyListener from JS may have been done before/after/during
// this configuration.
propertyListeners.toList().forEach { (_, listener) ->
if (listener.instance != instance) {
registerPropertyListener(listener.path, listener.propertyType)
}
}
}
when (val config = dataBindingConfig) {
is DataBindingConfig.AutoBind -> {
// Auto binding is done within the view creation
// The whole view needs to be reloaded
shouldBeReloaded = true
}
is DataBindingConfig.Index -> {
bindInstance(viewModel.createInstanceFromIndex(config.index))
}
is DataBindingConfig.Name -> {
bindInstance(viewModel.createInstanceFromName(config.name))
}
is DataBindingConfig.Empty -> {
bindInstance(viewModel.createBlankInstance())
}
null -> {}
}
} catch (ex: RiveException) {
handleRiveException(ex)
} catch (ex: Exception) {
showRNRiveError("Unexpected error during data binding configuration", ex)
}
}
// If the user set autoBind to true
private val shouldAutoBind: Boolean
get() {
val dbConfig = dataBindingConfig
return dbConfig is DataBindingConfig.AutoBind && dbConfig.autoBind
}
private fun clearPropertyListeners() {
propertyListeners.values.forEach { it.job.cancel() }
propertyListeners.clear()
}
fun update() {
reloadIfNeeded()
}
fun setResourceName(resourceName: String?) {
if (this.resourceName == resourceName) return
this.resourceName = resourceName
resourceName?.let {
resId = resources.getIdentifier(resourceName, "raw", context.packageName)
if (resId == 0) {
resId = -1
}
} ?: run {
resId = -1
}
shouldBeReloaded = true
}
fun setFit(rnFit: RNFit) {
val riveFit = RNFit.mapToRiveFit(rnFit)
if (this.fit == riveFit) return
this.fit = riveFit
riveAnimationView?.fit = riveFit
}
fun setLayoutScaleFactor(layoutScaleFactor: Float?) {
this.layoutScaleFactor = layoutScaleFactor
riveAnimationView?.layoutScaleFactor = layoutScaleFactor
}
fun setAlignment(rnAlignment: RNAlignment) {
val riveAlignment = RNAlignment.mapToRiveAlignment(rnAlignment)
this.alignment = riveAlignment
riveAnimationView?.alignment = riveAlignment
}
fun setAutoplay(autoplay: Boolean) {
if (this.autoplay == autoplay) return
this.autoplay = autoplay
shouldBeReloaded = true
}
fun setUrl(url: String?) {
if (this.url == url) return
this.url = url
shouldBeReloaded = true
}
private fun handleSourceAssetId(source: String, asset: FileAsset) {
val scheme = runCatching { Uri.parse(source).scheme }.getOrNull()
// Handle dev mode (URL instead of asset id)
if (scheme != null) {
handleSourceUrl(source, asset)
return
}
// Handle release mode (asset id)
// Resource needs to be loaded in release mode
// https://github.com/facebook/react-native/issues/24963#issuecomment-532168307
val resourceId = getResourceId(source)
var errorMessage: String? = null
if (resourceId != 0) {
try {
resources.openRawResource(resourceId).use {
val bytes = it.readBytes()
processAssetBytes(bytes, asset)
}
} catch (e: IOException) {
errorMessage = "IO Exception while reading resource: $source"
} catch (e: Resources.NotFoundException) {
errorMessage = "Resource not found: $source"
} catch (e: Exception) {
errorMessage = "Unexpected error while processing resource: $source"
}
} else {
errorMessage = "Resource not found: $source"
}
errorMessage?.let {
if (isUserHandlingErrors) {
val rnRiveError = RNRiveError.FileNotFound
rnRiveError.message = errorMessage
sendErrorToRN(rnRiveError)
} else {
throw IllegalStateException(errorMessage)
}
}
}
private fun handleSourceUrl(source: String, asset: FileAsset) {
downloadUrlAsset(source) { bytes -> processAssetBytes(bytes, asset) }
}
private fun handleSourceAsset(fileName: String, path: String?, asset: FileAsset) {
val fullPath = if (path == null) fileName else constructFilePath(fileName, path)
val assetBytes = readAssetBytes(context, fullPath)
assetBytes?.let {
processAssetBytes(it, asset)
}
}
private fun loadAsset(source: ReadableMap, asset: FileAsset) {
val sourceAssetId = source.getString("sourceAssetId")
val sourceUrl = source.getString("sourceUrl")
val sourceAsset = source.getString("sourceAsset")
when {
sourceAssetId != null -> handleSourceAssetId(sourceAssetId, asset)
sourceUrl != null -> handleSourceUrl(sourceUrl, asset)
sourceAsset != null -> handleSourceAsset(sourceAsset, source.getString("path"), asset)
}
}
private fun reloadIfNeeded() {
if (shouldBeReloaded) {
assetStore?.dispose()
assetStore = referencedAssets?.let {
RiveReactNativeAssetStore(
it, loadAssetHandler = ::loadAsset
)
}
if (assetStore != null) {
riveAnimationView?.setAssetLoader(assetStore)
}
url?.let {
if (resId == -1) {
setUrlRiveResource(it)
} else {
throw IllegalStateException("You cannot pass both resourceName and url at the same time")
}
} ?: run {
if (resId != -1) {
try {
riveAnimationView?.setRiveResource(
resId,
fit = this.fit,
alignment = this.alignment,
autoplay = this.autoplay,
autoBind = shouldAutoBind,
stateMachineName = this.stateMachineName,
animationName = this.animationName,
artboardName = this.artboardName
)
warnForUnusedAssets()
configureDataBinding()
sendRiveLoadedEvent()
url = null
} catch (ex: RiveException) {
handleRiveException(ex)
}
} else {
handleFileNotFound()
}
}
shouldBeReloaded = false
}
}
private fun setUrlRiveResource(url: String) {
downloadUrlAsset(url) { bytes ->
try {
// Validate that we have valid content before attempting to create Rive file
if (bytes.isEmpty()) {
if (isUserHandlingErrors) {
val rnRiveError = RNRiveError.IncorrectRiveFileUrl
rnRiveError.message = "Downloaded file is empty from: $url"
sendErrorToRN(rnRiveError)
} else {
showRNRiveError("Downloaded file is empty from: $url", null)
}
return@downloadUrlAsset
}
// Basic validation - check if the content starts with the Rive file signature
if (!isValidRiveContent(bytes)) {
if (isUserHandlingErrors) {
val rnRiveError = RNRiveError.MalformedFile
rnRiveError.message = "Downloaded content is not a valid Rive file from: $url"
sendErrorToRN(rnRiveError)
} else {
showRNRiveError("Downloaded content is not a valid Rive file from: $url", null)
}
return@downloadUrlAsset
}
riveAnimationView?.setRiveBytes(
bytes,
fit = this.fit,
alignment = this.alignment,
autoplay = autoplay,
autoBind = shouldAutoBind,
stateMachineName = this.stateMachineName,
animationName = this.animationName,
artboardName = this.artboardName
)
configureDataBinding()
sendRiveLoadedEvent()
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
}
/**
* Validates if the downloaded content is a valid Rive file by checking file signatures
*/
private fun isValidRiveContent(bytes: ByteArray): Boolean {
if (bytes.size < 4) return false
// Check for Rive file signature (RIVE magic number)
// Rive files start with specific byte patterns
val header = bytes.take(4).toByteArray()
// Check for "RIVE" header (0x52495645)
if (header[0] == 0x52.toByte() &&
header[1] == 0x49.toByte() &&
header[2] == 0x56.toByte() &&
header[3] == 0x45.toByte()) {
return true
}
// Additional validation - check for common non-Rive content patterns
val headerString = String(header, Charsets.UTF_8)
// Check if it's HTML (error pages)
if (headerString.startsWith("<!DO") || headerString.startsWith("<htm")) {
return false
}
// Check if it's JSON (API error responses)
if (headerString.startsWith("{") || headerString.startsWith("[")) {
return false
}
// If we can't definitively identify it as non-Rive, let the Rive runtime validate it
// This allows for different Rive file formats/versions
return true
}
fun setArtboardName(artboardName: String) {
try {
this.artboardName = artboardName
riveAnimationView?.artboardName = artboardName // it causes reloading
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun setAnimationName(animationName: String) {
if (this.animationName == animationName) return
this.animationName = animationName
shouldBeReloaded = true
}
fun setReferencedAssets(referencedAssets: ReadableMap?) {
if (this.referencedAssets?.toMap() == referencedAssets?.toMap()) return
val previousReferencedAssets = this.referencedAssets
this.referencedAssets = referencedAssets
if (previousReferencedAssets == null || referencedAssets == null) {
shouldBeReloaded = true
return
}
val previousKeys = previousReferencedAssets.keysList()
val newKeys = referencedAssets.keysList()
if (previousKeys.toSet() != newKeys.toSet()) {
shouldBeReloaded = true
return
}
for (key in newKeys) {
val previousValue = previousReferencedAssets.getMap(key)
val newValue = referencedAssets.getMap(key)
if (previousValue?.toMap() != newValue?.toMap()) {
val source = newValue?.getMap("source")
val asset = assetStore?.cachedFileAssets?.get(key)
if (source != null && asset != null) {
loadAsset(source, asset)
}
}
}
}
fun setDataBinding(dataBinding: ReadableMap?) {
dataBinding?.let {
val type = it.getString("type") ?: return
val value = it.getDynamic("value")
val newConfig = when (type) {
"autobind" -> {
if (value.type == ReadableType.Boolean) {
val booleanValue = value.asBoolean()
DataBindingConfig.AutoBind(booleanValue)
} else null
}
"index" -> {
if (value.type == ReadableType.Number) { // React Native numbers are treated as Double
val numberValue = value.asInt()
DataBindingConfig.Index(numberValue)
} else null
}
"name" -> {
if (value.type == ReadableType.String) {
value.asString()?.let { DataBindingConfig.Name(it) }
} else null
}
"empty" -> DataBindingConfig.Empty
else -> null
}
if (newConfig != dataBindingConfig) {
dataBindingConfig = newConfig
configureDataBinding()
}
}
}
fun setStateMachineName(stateMachineName: String) {
if (this.stateMachineName == stateMachineName) return
this.stateMachineName = stateMachineName
shouldBeReloaded = true
}
fun setIsUserHandlingErrors(isUserHandlingErrors: Boolean) {
this.isUserHandlingErrors = isUserHandlingErrors
}
fun fireState(stateMachineName: String, inputName: String) {
try {
riveAnimationView?.fireState(stateMachineName, inputName)
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun setBooleanState(stateMachineName: String, inputName: String, value: Boolean) {
try {
riveAnimationView?.setBooleanState(stateMachineName, inputName, value)
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun getBooleanState(inputName: String): Boolean? {
return try {
val smi = riveAnimationView?.controller?.stateMachines?.get(0)
val smiInput = smi?.input(inputName)
if (smiInput is SMIBoolean) {
smiInput.value
} else {
null
}
} catch (ex: RiveException) {
handleRiveException(ex)
null
}
}
fun setNumberState(stateMachineName: String, inputName: String, value: Float) {
try {
riveAnimationView?.setNumberState(stateMachineName, inputName, value)
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun getNumberState(inputName: String): Float? {
return try {
val smi = riveAnimationView?.controller?.stateMachines?.get(0)
val smiInput = smi?.input(inputName)
if (smiInput is SMINumber) {
smiInput.value
} else {
null
}
} catch (ex: RiveException) {
handleRiveException(ex)
null
}
}
fun fireStateAtPath(inputName: String, path: String) {
try {
riveAnimationView?.fireStateAtPath(inputName, path)
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun setBooleanStateAtPath(inputName: String, value: Boolean, path: String) {
try {
riveAnimationView?.setBooleanStateAtPath(inputName, value, path)
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun getBooleanStateAtPath(inputName: String, path: String): Boolean? {
return try {
val artboard = riveAnimationView?.controller?.activeArtboard
val smiInput = artboard?.input(inputName, path)
if (smiInput is SMIBoolean) {
smiInput.value
} else {
null
}
} catch (ex: RiveException) {
handleRiveException(ex)
null
}
}
fun setNumberStateAtPath(inputName: String, value: Float, path: String) {
try {
riveAnimationView?.setNumberStateAtPath(inputName, value, path)
} catch (ex: RiveException) {
handleRiveException(ex)
}
}
fun getNumberStateAtPath(inputName: String, path: String): Float? {
return try {
val artboard = riveAnimationView?.controller?.activeArtboard
val smiInput = artboard?.input(inputName, path)
if (smiInput is SMINumber) {
smiInput.value
} else {
null
}
} catch (ex: RiveException) {
handleRiveException(ex)