forked from PostHog/posthog-android
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostHogReplayIntegration.kt
1211 lines (1055 loc) · 41.6 KB
/
PostHogReplayIntegration.kt
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.posthog.android.replay
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.Rect
import android.graphics.RectF
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.graphics.drawable.InsetDrawable
import android.graphics.drawable.LayerDrawable
import android.graphics.drawable.RippleDrawable
import android.graphics.drawable.VectorDrawable
import android.os.Build
import android.os.Handler
import android.os.HandlerThread
import android.text.InputType
import android.util.Base64
import android.util.TypedValue
import android.view.Gravity
import android.view.MotionEvent
import android.view.PixelCopy
import android.view.View
import android.view.ViewGroup
import android.view.ViewStub
import android.view.Window
import android.view.accessibility.AccessibilityNodeInfo
import android.webkit.WebView
import android.widget.Button
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.EditText
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.RatingBar
import android.widget.Spinner
import android.widget.Switch
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.posthog.PostHog
import com.posthog.PostHogIntegration
import com.posthog.android.PostHogAndroidConfig
import com.posthog.android.internal.MainHandler
import com.posthog.android.internal.densityValue
import com.posthog.android.internal.displayMetrics
import com.posthog.android.internal.screenSize
import com.posthog.android.replay.internal.NextDrawListener.Companion.onNextDraw
import com.posthog.android.replay.internal.ViewTreeSnapshotStatus
import com.posthog.android.replay.internal.isAliveAndAttachedToWindow
import com.posthog.internal.PostHogThreadFactory
import com.posthog.internal.replay.RRCustomEvent
import com.posthog.internal.replay.RREvent
import com.posthog.internal.replay.RRFullSnapshotEvent
import com.posthog.internal.replay.RRIncrementalMouseInteractionData
import com.posthog.internal.replay.RRIncrementalMouseInteractionEvent
import com.posthog.internal.replay.RRIncrementalMutationData
import com.posthog.internal.replay.RRIncrementalSnapshotEvent
import com.posthog.internal.replay.RRMetaEvent
import com.posthog.internal.replay.RRMouseInteraction
import com.posthog.internal.replay.RRMutatedNode
import com.posthog.internal.replay.RRRemovedNode
import com.posthog.internal.replay.RRStyle
import com.posthog.internal.replay.RRWireframe
import com.posthog.internal.replay.capture
import curtains.Curtains
import curtains.OnRootViewsChangedListener
import curtains.TouchEventInterceptor
import curtains.onDecorViewReady
import curtains.phoneWindow
import curtains.touchEventInterceptors
import curtains.windowAttachCount
import java.io.ByteArrayOutputStream
import java.lang.ref.WeakReference
import java.util.WeakHashMap
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
public class PostHogReplayIntegration(
private val context: Context,
private val config: PostHogAndroidConfig,
private val mainHandler: MainHandler,
) : PostHogIntegration {
private val decorViews = WeakHashMap<View, ViewTreeSnapshotStatus>()
private val passwordInputTypes =
listOf(
InputType.TYPE_TEXT_VARIATION_PASSWORD,
InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD,
InputType.TYPE_TEXT_VARIATION_WEB_PASSWORD,
InputType.TYPE_NUMBER_VARIATION_PASSWORD,
)
private val executor by lazy {
Executors.newSingleThreadScheduledExecutor(PostHogThreadFactory("PostHogReplayThread"))
}
private val displayMetrics by lazy {
context.displayMetrics()
}
private val paint =
Paint().apply {
color = Color.BLACK
}
private val isSessionReplayEnabled: Boolean
get() = PostHog.isSessionReplayActive()
private var sessionStartTime = 0L
private var sessionEndTime = 0L
private fun addView(
view: View,
added: Boolean = true,
) {
try {
view.phoneWindow?.let { window ->
var hasDecorView = false
// react native already has the window attached
// so we check if the decor view exists otherwise we need the onDecorViewReady anyways
window.peekDecorView()?.let { decorView ->
hasDecorView = decorViews[decorView] != null
}
if (added) {
if (view.windowAttachCount == 0 || !hasDecorView) {
window.onDecorViewReady { decorView ->
try {
val listener =
decorView.onNextDraw(
mainHandler,
config.dateProvider,
config.sessionReplayConfig.debouncerDelayMs,
) {
if (!isSessionReplayEnabled) {
return@onNextDraw
}
val timestamp = config.dateProvider.currentTimeMillis()
executor.submit {
try {
generateSnapshot(
WeakReference(decorView),
WeakReference(window),
timestamp
)
} catch (e: Throwable) {
config.logger.log("Session Replay generateSnapshot failed: $e.")
}
}
}
val status = ViewTreeSnapshotStatus(listener)
decorViews[decorView] = status
} catch (e: Throwable) {
config.logger.log("Session Replay onDecorViewReady failed: $e.")
}
}
window.touchEventInterceptors += onTouchEventListener
// TODO: can check if user pressed hardware back button (KEYCODE_BACK)
// window.keyEventInterceptors
} else {
config.logger.log("Session Replay already has onDecorViewReady.")
}
} else {
window.peekDecorView()?.let { decorView ->
decorViews[decorView]?.let { status ->
cleanSessionState(decorView, status)
}
}
}
}
} catch (e: Throwable) {
config.logger.log("Session Replay OnRootViewsChangedListener failed: $e.")
}
}
private val onRootViewsChangedListener =
OnRootViewsChangedListener { view, added ->
addView(view, added)
}
private fun detectKeyboardVisibility(
view: View,
visible: Boolean,
): Pair<Boolean, RRCustomEvent?> {
val insets = ViewCompat.getRootWindowInsets(view) ?: return Pair(visible, null)
val imeVisible = insets.isVisible(WindowInsetsCompat.Type.ime())
if (visible == imeVisible) {
return Pair(visible, null)
}
val payload = mutableMapOf<String, Any>()
if (imeVisible) {
val imeHeight = insets.getInsets(WindowInsetsCompat.Type.ime()).bottom
payload["open"] = true
payload["height"] = imeHeight.densityValue(displayMetrics.density)
} else {
payload["open"] = false
}
val event =
RRCustomEvent(
tag = "keyboard",
payload = payload,
config.dateProvider.currentTimeMillis(),
)
return Pair(imeVisible, event)
}
private val onTouchEventListener =
TouchEventInterceptor { motionEvent, dispatch ->
val timestamp = config.dateProvider.currentTimeMillis()
try {
val state = dispatch(motionEvent)
executor.submit {
try {
if (!isSessionReplayEnabled) {
return@submit
}
when (motionEvent.action.and(MotionEvent.ACTION_MASK)) {
MotionEvent.ACTION_DOWN -> {
generateMouseInteractions(
timestamp,
motionEvent,
RRMouseInteraction.TouchStart
)
}
MotionEvent.ACTION_UP -> {
generateMouseInteractions(
timestamp,
motionEvent,
RRMouseInteraction.TouchEnd
)
}
}
} catch (e: Throwable) {
config.logger.log("Executor#OnTouchEventListener $motionEvent failed: $e.")
}
}
state
} catch (e: Throwable) {
config.logger.log("TouchEventInterceptor $motionEvent failed: $e.")
throw e
}
}
private fun generateMouseInteractions(
timestamp: Long,
motionEvent: MotionEvent,
type: RRMouseInteraction,
) {
val mouseInteractions = mutableListOf<RRIncrementalMouseInteractionEvent>()
for (index in 0 until motionEvent.pointerCount) {
// if the id is 0, BE transformer will set it to the virtual bodyId
val id = motionEvent.getPointerId(index)
val absX = motionEvent.getRawXCompat(index).toInt().densityValue(displayMetrics.density)
val absY = motionEvent.getRawYCompat(index).toInt().densityValue(displayMetrics.density)
val mouseInteractionData =
RRIncrementalMouseInteractionData(
id = id,
type = type,
x = absX,
y = absY,
)
val mouseInteraction =
RRIncrementalMouseInteractionEvent(mouseInteractionData, timestamp)
mouseInteractions.add(mouseInteraction)
}
if (mouseInteractions.isNotEmpty()) {
// TODO: we can probably batch those
// if we batch them, we need to be aware that the order of the events matters
// also because if we send a mouse interaction later, it might be attached to the wrong
// screen
mouseInteractions.capture()
}
}
private fun cleanSessionState(
view: View,
status: ViewTreeSnapshotStatus,
) {
if (view.isAliveAndAttachedToWindow()) {
mainHandler.handler.post {
// 2nd check to avoid:
// Exception java.lang.IllegalStateException: This ViewTreeObserver is not alive
// Since the post might be executed a bit later if the thread is busy
if (view.isAliveAndAttachedToWindow()) {
try {
// swallow the exception because we still wanna remove it from the decorViews
view.viewTreeObserver?.removeOnDrawListener(status.listener)
} catch (e: Throwable) {
config.logger.log("Removing the viewTreeObserver failed: $e.")
}
}
}
}
view.phoneWindow?.let { window ->
window.touchEventInterceptors -= onTouchEventListener
}
decorViews.remove(view)
}
override fun install() {
if (!isSupported()) {
return
}
// workaround for react native that is started after the window is added
// Curtains.rootViews should be empty for normal apps yet
sessionStartTime = config.dateProvider.currentTimeMillis()
Curtains.rootViews.forEach { view ->
addView(view)
}
try {
Curtains.onRootViewsChangedListeners += onRootViewsChangedListener
} catch (e: Throwable) {
config.logger.log("Session Replay setup failed: $e.")
}
}
override fun uninstall() {
try {
sessionEndTime = config.dateProvider.currentTimeMillis()
//TODO improve this
if (sessionEndTime - sessionStartTime <= config.sessionReplayConfig.minSessionDurationMs) {
//Delete existing session recording?
}
Curtains.onRootViewsChangedListeners -= onRootViewsChangedListener
decorViews.entries.forEach {
cleanSessionState(it.key, it.value)
}
} catch (e: Throwable) {
config.logger.log("Session Replay uninstall failed: $e.")
}
}
private fun Resources.Theme.toRGBColor(): String? {
val value = TypedValue()
resolveAttribute(android.R.attr.windowBackground, value, true)
return if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT &&
value.type <= TypedValue.TYPE_LAST_COLOR_INT
) {
value.data
} else {
null
}?.toRGBColor()
}
private fun generateSnapshot(
viewRef: WeakReference<View>,
windowRef: WeakReference<Window>,
timestamp: Long,
) {
val view = viewRef.get() ?: return
val status = decorViews[view] ?: return
val window = windowRef.get() ?: return
val wireframe =
if (config.sessionReplayConfig.screenshot) {
view.toScreenshotWireframe(
window,
) ?: return
} else {
view.toWireframe() ?: return
}
// if the decorView has no backgroundColor, we use the theme color
// no need to do this if we are capturing a screenshot
if (wireframe.style?.backgroundColor == null && !config.sessionReplayConfig.screenshot) {
context.theme?.toRGBColor()?.let {
wireframe.style?.backgroundColor = it
}
}
val events = mutableListOf<RREvent>()
if (!status.sentMetaEvent) {
val title = view.phoneWindow?.attributes?.title?.toString()?.substringAfter("/") ?: ""
// TODO: cache and compare, if size changes, we send a ViewportResize event
val screenSizeInfo = view.context.screenSize() ?: return
val metaEvent =
RRMetaEvent(
href = title,
width = screenSizeInfo.width,
height = screenSizeInfo.height,
timestamp = timestamp,
)
events.add(metaEvent)
status.sentMetaEvent = true
}
if (!status.sentFullSnapshot) {
val event =
RRFullSnapshotEvent(
listOf(wireframe),
initialOffsetTop = 0,
initialOffsetLeft = 0,
timestamp = timestamp,
)
events.add(event)
status.sentFullSnapshot = true
} else {
val lastSnapshot = status.lastSnapshot
val lastSnapshots = if (lastSnapshot != null) listOf(lastSnapshot) else emptyList()
val (addedItems, removedItems, updatedItems) =
findAddedAndRemovedItems(
lastSnapshots.flattenChildren(),
listOf(wireframe).flattenChildren(),
)
val addedNodes = mutableListOf<RRMutatedNode>()
addedItems.forEach {
val item = RRMutatedNode(it, parentId = it.parentId)
addedNodes.add(item)
}
val removedNodes = mutableListOf<RRRemovedNode>()
removedItems.forEach {
val item = RRRemovedNode(it.id, parentId = it.parentId)
removedNodes.add(item)
}
val updatedNodes = mutableListOf<RRMutatedNode>()
updatedItems.forEach {
val item = RRMutatedNode(it, parentId = it.parentId)
updatedNodes.add(item)
}
if (addedNodes.isNotEmpty() || removedNodes.isNotEmpty() || updatedNodes.isNotEmpty()) {
val incrementalMutationData =
RRIncrementalMutationData(
adds = addedNodes.ifEmpty { null },
removes = removedNodes.ifEmpty { null },
updates = updatedNodes.ifEmpty { null },
)
val incrementalSnapshotEvent =
RRIncrementalSnapshotEvent(
mutationData = incrementalMutationData,
timestamp = timestamp,
)
events.add(incrementalSnapshotEvent)
}
}
// detect keyboard visibility
val (visible, event) = detectKeyboardVisibility(view, status.keyboardVisible)
status.keyboardVisible = visible
event?.let {
events.add(it)
}
if (events.isNotEmpty()) {
events.capture()
}
status.lastSnapshot = wireframe
}
private fun View.isVisible(): Boolean {
// TODO: also check for getGlobalVisibleRect intersects the display
val visible = isShown && width >= 0 && height >= 0 && this !is ViewStub
// Between API 16 and API 29, this method may incorrectly return false when magnification
// is enabled. On other versions, a node is considered visible even if it is not on
// the screen because magnification is active.
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {
return visible
}
val nodeInfo = AccessibilityNodeInfo()
onInitializeAccessibilityNodeInfo(nodeInfo)
return visible && nodeInfo.isVisibleToUser
}
private fun Drawable.shouldMaskDrawable(): Boolean {
return when (this) {
is InsetDrawable, is ColorDrawable, is VectorDrawable, is GradientDrawable, is LayerDrawable -> false
// otherwise its not accessible anyway
is BitmapDrawable -> !bitmap.isRecycled
else -> true
}
}
private fun View.globalVisibleRect(): Rect {
val rect = Rect()
getGlobalVisibleRect(rect)
return rect
}
private fun View.isTextInputSensitive(): Boolean {
return isNoCapture(config.sessionReplayConfig.maskAllTextInputs)
}
private fun View.isAnyInputSensitive(): Boolean {
return this.isTextInputSensitive() || config.sessionReplayConfig.maskAllImages
}
private fun TextView.shouldMaskTextView(): Boolean {
// inputType is 0-based
return this.isTextInputSensitive() || passwordInputTypes.contains(inputType - 1)
}
private fun findMaskableWidgets(
view: View,
maskableWidgets: MutableList<Rect>,
) {
if (view is TextView) {
val viewText = view.text?.toString()
var maskIt = false
if (!viewText.isNullOrEmpty()) {
maskIt =
view.shouldMaskTextView()
}
val hint = view.hint?.toString()
if (!maskIt && !hint.isNullOrEmpty()) {
maskIt =
view.shouldMaskTextView()
}
if (maskIt) {
val rect = view.globalVisibleRect()
maskableWidgets.add(rect)
return
}
}
if (view is Spinner) {
if (view.shouldMaskSpinner()) {
val rect = view.globalVisibleRect()
maskableWidgets.add(rect)
return
}
}
if (view is ImageView) {
if (view.shouldMaskImage()) {
val rect = view.globalVisibleRect()
maskableWidgets.add(rect)
return
}
}
if (view is WebView) {
if (view.isAnyInputSensitive()) {
val rect = view.globalVisibleRect()
maskableWidgets.add(rect)
return
}
}
// if a view parent of any type is tagged as non masking, mask it
if (view.isNoCapture()) {
val rect = view.globalVisibleRect()
maskableWidgets.add(rect)
return
}
if (view is ViewGroup && view.childCount > 0) {
for (i in 0 until view.childCount) {
val viewChild = view.getChildAt(i) ?: continue
if (!viewChild.isVisible()) {
continue
}
findMaskableWidgets(viewChild, maskableWidgets)
}
}
}
// PixelCopy is only API >= 24 but this is already protected by the isSupported method
@SuppressLint("NewApi")
private fun View.toScreenshotWireframe(window: Window): RRWireframe? {
val view = this
if (!view.isVisible()) {
return null
}
val viewId = System.identityHashCode(view)
val coordinates = IntArray(2)
view.getLocationOnScreen(coordinates)
val x = coordinates[0].densityValue(displayMetrics.density)
val y = coordinates[1].densityValue(displayMetrics.density)
val width = view.width.densityValue(displayMetrics.density)
val height = view.height.densityValue(displayMetrics.density)
var base64: String? = null
val maskableWidgets = mutableListOf<Rect>()
findMaskableWidgets(this, maskableWidgets)
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
val latch = CountDownLatch(1)
val thread = HandlerThread("PostHogReplayScreenshot")
thread.start()
// unfortunately we cannot use the Looper.myLooper() because it will be null
val handler = Handler(thread.looper)
try {
var success = true
PixelCopy.request(window, bitmap, { copyResult ->
if (copyResult != PixelCopy.SUCCESS) {
success = false
bitmap.recycle()
}
latch.countDown()
}, handler)
// await for 1s max
latch.await(1000, TimeUnit.MILLISECONDS)
if (success) {
val canvas = Canvas(bitmap)
maskableWidgets.forEach {
canvas.drawRoundRect(RectF(it), 10f, 10f, paint)
}
base64 = bitmap.base64()
}
} catch (e: Throwable) {
config.logger.log("Session Replay PixelCopy failed: $e.")
} finally {
thread.quit()
bitmap.recycle()
}
return RRWireframe(
id = viewId,
x = x,
y = y,
width = width,
height = height,
type = "screenshot",
base64 = base64,
style = RRStyle(),
)
}
private fun ImageView.shouldMaskImage(): Boolean {
return isNoCapture(config.sessionReplayConfig.maskAllImages) && drawable?.shouldMaskDrawable() == true
}
private fun Spinner.shouldMaskSpinner(): Boolean {
return this.isTextInputSensitive()
}
private fun View.toWireframe(parentId: Int? = null): RRWireframe? {
val view = this
if (!view.isVisible()) {
return null
}
val viewId = System.identityHashCode(view)
val coordinates = IntArray(2)
view.getLocationOnScreen(coordinates)
val x = coordinates[0].densityValue(displayMetrics.density)
val y = coordinates[1].densityValue(displayMetrics.density)
val width = view.width.densityValue(displayMetrics.density)
val height = view.height.densityValue(displayMetrics.density)
var base64: String? = null
var type: String? = null
if (view.id == android.R.id.statusBarBackground) {
type = "status_bar"
}
if (view.id == android.R.id.navigationBarBackground) {
type = "navigation_bar"
}
val style = RRStyle()
view.background?.let { background ->
background.toRGBColor()?.let { color ->
style.backgroundColor = color
} ?: run {
style.backgroundImage = background.base64(view.width, view.height)
}
}
var checked: Boolean? = null
var text: String? = null
var inputType: String? = null
var value: Any? = null
// button inherits from textview
if (view is TextView) {
val viewText = view.text?.toString()
if (!viewText.isNullOrEmpty()) {
text =
if (!view.shouldMaskTextView()) {
viewText
} else {
viewText.mask()
}
}
val hint = view.hint?.toString()
if (text.isNullOrEmpty() && !hint.isNullOrEmpty()) {
text =
if (!view.shouldMaskTextView()) {
hint
} else {
hint.mask()
}
}
type = "text"
style.color = view.currentTextColor.toRGBColor()
// CompoundButton is a subclass of CheckBox, RadioButton, Switch, etc
if (view is Button && view !is CompoundButton) {
style.borderWidth = 1
style.borderColor = "#000000"
type = "input"
inputType = "button"
value = text
text = null
}
// TODO: do this when we upgrade API to 34
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
// style.fontFamily = view.typeface?.systemFontFamilyName
// } else {
view.typeface?.let {
when (it) {
Typeface.DEFAULT -> style.fontFamily = "sans-serif"
Typeface.DEFAULT_BOLD -> style.fontFamily = "sans-serif-bold"
Typeface.MONOSPACE -> style.fontFamily = "monospace"
Typeface.SERIF -> style.fontFamily = "serif"
}
}
// }
style.fontSize = view.textSize.toInt().densityValue(displayMetrics.density)
when (view.textAlignment) {
View.TEXT_ALIGNMENT_CENTER -> {
style.verticalAlign = "center"
style.horizontalAlign = "center"
}
View.TEXT_ALIGNMENT_TEXT_END, View.TEXT_ALIGNMENT_VIEW_END -> {
style.verticalAlign = "center"
style.horizontalAlign = "right"
}
View.TEXT_ALIGNMENT_TEXT_START, View.TEXT_ALIGNMENT_VIEW_START -> {
style.verticalAlign = "center"
style.horizontalAlign = "left"
}
View.TEXT_ALIGNMENT_GRAVITY -> {
val horizontalAlignment =
when (view.gravity.and(Gravity.HORIZONTAL_GRAVITY_MASK)) {
Gravity.START, Gravity.LEFT -> "left"
Gravity.END, Gravity.RIGHT -> "right"
Gravity.CENTER, Gravity.CENTER_HORIZONTAL -> "center"
else -> "left"
}
style.horizontalAlign = horizontalAlignment
val verticalAlignment =
when (view.gravity.and(Gravity.VERTICAL_GRAVITY_MASK)) {
Gravity.TOP -> "top"
Gravity.BOTTOM -> "bottom"
Gravity.CENTER_VERTICAL, Gravity.CENTER -> "center"
else -> "center"
}
style.verticalAlign = verticalAlignment
}
else -> {
style.verticalAlign = "center"
style.horizontalAlign = "left"
}
}
// left, top, right, bottom
view.compoundDrawables.forEachIndexed { index, drawable ->
drawable?.let {
val drawableBase64 = it.base64(view.width, view.height)
// TODO: the 2 other possible drawables (top and bottom are not common)
when (index) {
0 -> style.iconLeft = drawableBase64
// 1 -> style.iconTop = drawableBase64
2 -> style.iconRight = drawableBase64
// 3 -> style.iconBottom = drawableBase64
}
}
}
// Do not set padding if the text is centered, otherwise the padding will be off
if (style.verticalAlign != "center") {
style.paddingTop = view.totalPaddingTop.densityValue(displayMetrics.density)
style.paddingBottom = view.totalPaddingBottom.densityValue(displayMetrics.density)
}
if (style.horizontalAlign != "center") {
style.paddingLeft = view.totalPaddingLeft.densityValue(displayMetrics.density)
style.paddingRight = view.totalPaddingRight.densityValue(displayMetrics.density)
}
}
var label: String? = null
if (view is CheckBox) {
type = "input"
inputType = "checkbox"
label = text
text = null
checked = view.isChecked
}
if (view is RadioGroup) {
type = "radio_group"
}
if (view is RadioButton) {
type = "input"
inputType = "radio"
label = text
text = null
checked = view.isChecked
}
if (view is EditText) {
type = "input"
inputType = "text_area"
value = text
text = null
}
var options: List<String>? = null
if (view is Spinner) {
type = "input"
inputType = "select"
val mask = view.shouldMaskSpinner()
view.selectedItem?.let {
val theValue =
if (!mask) {
it.toString()
} else {
it.toString().mask()
}
value = theValue
}
view.adapter?.let {
val items = mutableListOf<String>()
for (i in 0 until it.count) {
val item = it.getItem(i)?.toString() ?: continue
val theItem =
if (!mask) {
item
} else {
item.mask()
}
items.add(theItem)
}
options = items.ifEmpty { null }
}
}
if (view is ImageView) {
type = "image"
if (!view.shouldMaskImage()) {
// TODO: we can probably do a LRU caching here for already captured images
view.drawable?.let { drawable ->
base64 = drawable.base64(view.width, view.height)
// style.paddingTop = view.paddingTop.densityValue(displayMetrics.density)
// style.paddingBottom = view.paddingBottom.densityValue(displayMetrics.density)
// style.paddingLeft = view.paddingLeft.densityValue(displayMetrics.density)
// style.paddingRight = view.paddingRight.densityValue(displayMetrics.density)
}
}
}
var max: Int? = null // can be a Int or Float
if (view is ProgressBar) {
inputType = "progress"
type = "input"
val bar =
if (view.isIndeterminate) {
"circular"
} else {
max = view.max
value = view.progress
"horizontal"
}
style.bar = bar
}
if (view is RatingBar) {
style.bar = "rating"
// since stars allow half stars, we need to divide the max by 2, because
// 5 stars is 10
max = (view.max / 2)
value = view.rating
}
if (view is Switch) {
type = "input"
inputType = "toggle"
checked = view.isChecked
label = text
text = null
}
// TODO: people might be used androidx.webkit:webkit though
if (view is WebView) {
type = "web_view"
}
val children = mutableListOf<RRWireframe>()
if (view is ViewGroup && view.childCount > 0) {
for (i in 0 until view.childCount) {
val viewChild = view.getChildAt(i) ?: continue
viewChild.toWireframe(parentId = viewId)?.let {
children.add(it)
}
}
}
return RRWireframe(
id = viewId,
x = x,
y = y,
width = width,
height = height,
text = text,
type = type,
style = style,
childWireframes = children.ifEmpty { null },
base64 = base64,
parentId = parentId,
disabled = !view.isEnabled,
checked = checked,
inputType = inputType,
value = value,
label = label,
options = options,
max = max,
)
}
private fun runDrawableConverter(drawable: Drawable): Bitmap? {
return config.sessionReplayConfig.drawableConverter?.convert(drawable)
}
private fun Drawable.toRGBColor(): String? {
when (this) {
is ColorDrawable -> {
return color.toRGBColor()
}
is RippleDrawable -> {
try {
return getFirstDrawable()?.toRGBColor()
} catch (e: Throwable) {
// ignore
}
}
is InsetDrawable -> {
return drawable?.toRGBColor()
}
is GradientDrawable -> {
colors?.let { rgcColors ->
if (rgcColors.isNotEmpty()) {
// Get the first color from the array