-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy pathPosthogFlutterPlugin.kt
More file actions
1864 lines (1666 loc) · 66.7 KB
/
Copy pathPosthogFlutterPlugin.kt
File metadata and controls
1864 lines (1666 loc) · 66.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.posthog.flutter
import android.app.Activity
import android.app.Application
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.PixelCopy
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import com.posthog.PersonProfiles
import com.posthog.PostHog
import com.posthog.PostHogBootstrapConfig
import com.posthog.PostHogConfig
import com.posthog.PostHogOnFeatureFlags
import com.posthog.android.PostHogAndroid
import com.posthog.android.PostHogAndroidConfig
import com.posthog.android.internal.getApplicationInfo
import com.posthog.android.replay.PostHogInternalReplayApi
import com.posthog.android.replay.PostHogReplayIntegration
import com.posthog.logs.PostHogLogSeverity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.util.Date
import java.util.concurrent.Executors
import java.util.concurrent.RejectedExecutionException
import kotlin.math.roundToInt
private const val FLUTTER_VIEW_CLASS_PREFIX = "io.flutter"
private const val OCCLUSION_TICK_MS = 1000L
private const val BRIDGE_FAILURE_STRIKE_LIMIT = 3
/** PosthogFlutterPlugin */
class PosthogFlutterPlugin :
FlutterPlugin,
ActivityAware,
MethodCallHandler {
// / The MethodChannel that will be the communication between Flutter and native Android
// /
// / This local reference serves to register the plugin with the Flutter Engine and unregister it
// / when the Flutter Engine is detached from the Activity
private lateinit var channel: MethodChannel
private lateinit var applicationContext: Context
private var activity: Activity? = null
private var application: Application? = null
private var postHogConfig: PostHogAndroidConfig? = null
// Occluded = host activity STOPPED (not just paused — a translucent/dialog
// activity pauses the host while Flutter stays visible) AND one of our own
// activities resumed on top (a stopped host alone is just backgrounding).
// Out-of-process covers (Custom Tabs, Google Pay) are intentionally missed.
@Volatile
private var isHostActivityStopped = false
// A count, not a boolean: under multi-resume (Android 10+ split-screen)
// two non-host activities can be resumed at once, and pausing one must
// not read as "nothing covers the host" while the other still does.
@Volatile
private var otherResumedCount = 0
private val activityLifecycleCallbacks =
object : Application.ActivityLifecycleCallbacks {
override fun onActivityResumed(act: Activity) {
if (act !== activity) {
otherResumedCount++
nudgeOcclusionDetector()
}
}
override fun onActivityPaused(act: Activity) {
// Floor at zero: a pause for a resume we never observed (the
// callbacks registered while it was already resumed) must not
// underflow the count.
if (act !== activity && otherResumedCount > 0) {
otherResumedCount--
}
}
override fun onActivityCreated(
act: Activity,
savedInstanceState: Bundle?,
) {}
override fun onActivityStarted(act: Activity) {
if (act === activity) {
isHostActivityStopped = false
nudgeOcclusionDetector()
}
}
override fun onActivityStopped(act: Activity) {
if (act === activity) {
isHostActivityStopped = true
nudgeOcclusionDetector()
}
}
override fun onActivitySaveInstanceState(
act: Activity,
outState: Bundle,
) {}
override fun onActivityDestroyed(act: Activity) {}
}
private val mainHandler = Handler(Looper.getMainLooper())
private val bitmapExportExecutor = Executors.newSingleThreadExecutor()
// The native SDK stamps its replay events (touches, bridged frames) with
// config.dateProvider, which prefers the network-time clock on API 33+ and
// can diverge from System.currentTimeMillis. Replay is ordered by
// timestamp, so Flutter frames must use the same clock.
private val snapshotSender =
SnapshotSender {
postHogConfig?.dateProvider?.currentTimeMillis() ?: System.currentTimeMillis()
}
private var flutterSurveysDelegate: PostHogFlutterSurveysDelegate? = null
override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
channel = MethodChannel(flutterPluginBinding.binaryMessenger, "posthog_flutter")
this.applicationContext = flutterPluginBinding.applicationContext
initPlugin()
channel.setMethodCallHandler(this)
}
private fun initPlugin() {
try {
val ai = getApplicationInfo(applicationContext)
val bundle = ai.metaData ?: Bundle()
val autoInit = bundle.getBoolean("com.posthog.posthog.AUTO_INIT", true)
if (!autoInit) {
Log.i("PostHog", "com.posthog.posthog.AUTO_INIT is disabled!")
return
}
val projectToken =
(
bundle.getString("com.posthog.posthog.PROJECT_TOKEN")
?: bundle.getString("com.posthog.posthog.API_KEY")
)?.trim()
if (!bundle.containsKey("com.posthog.posthog.PROJECT_TOKEN") && bundle.containsKey("com.posthog.posthog.API_KEY")) {
Log.w(
"PostHog",
"com.posthog.posthog.API_KEY is deprecated and will be removed in the next major version. Use com.posthog.posthog.PROJECT_TOKEN instead!",
)
}
if (projectToken.isNullOrEmpty()) {
Log.e("PostHog", "Either com.posthog.posthog.PROJECT_TOKEN or com.posthog.posthog.API_KEY must be provided!")
return
}
val host =
bundle
.getString("com.posthog.posthog.POSTHOG_HOST", PostHogConfig.DEFAULT_HOST)
?.trim()
?.takeIf { it.isNotEmpty() }
?: PostHogConfig.DEFAULT_HOST
// Check new key first, then legacy key, default to true
val captureApplicationLifecycleEvents =
if (bundle.containsKey("com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS")) {
bundle.getBoolean("com.posthog.posthog.CAPTURE_APPLICATION_LIFECYCLE_EVENTS", true)
} else {
bundle.getBoolean("com.posthog.posthog.TRACK_APPLICATION_LIFECYCLE_EVENTS", true)
}
val debug = bundle.getBoolean("com.posthog.posthog.DEBUG", false)
val posthogConfig = mutableMapOf<String, Any>()
posthogConfig["projectToken"] = projectToken
posthogConfig["apiKey"] = projectToken
posthogConfig["host"] = host
posthogConfig["captureApplicationLifecycleEvents"] = captureApplicationLifecycleEvents
posthogConfig["debug"] = debug
setupPostHog(posthogConfig)
} catch (e: Throwable) {
Log.e("PostHog", "initPlugin error: $e")
}
}
override fun onMethodCall(
call: MethodCall,
result: Result,
) {
when (call.method) {
"setup" -> {
setup(call, result)
}
"identify" -> {
identify(call, result)
}
"setPersonProperties" -> {
setPersonProperties(call, result)
}
"capture" -> {
capture(call, result)
}
"screen" -> {
screen(call, result)
}
"captureLog" -> {
captureLog(call, result)
}
"alias" -> {
alias(call, result)
}
"distinctId" -> {
distinctId(result)
}
"reset" -> {
reset(result)
}
"disable" -> {
disable(result)
}
"enable" -> {
enable(result)
}
"isOptOut" -> {
isOptOut(result)
}
"isFeatureEnabled" -> {
isFeatureEnabled(call, result)
}
"reloadFeatureFlags" -> {
reloadFeatureFlags(result)
}
"setPersonPropertiesForFlags" -> {
setPersonPropertiesForFlags(call, result)
}
"resetPersonPropertiesForFlags" -> {
resetPersonPropertiesForFlags(result)
}
"setGroupPropertiesForFlags" -> {
setGroupPropertiesForFlags(call, result)
}
"resetGroupPropertiesForFlags" -> {
resetGroupPropertiesForFlags(call, result)
}
"group" -> {
group(call, result)
}
"getFeatureFlag" -> {
getFeatureFlag(call, result)
}
"getFeatureFlagPayload" -> {
getFeatureFlagPayload(call, result)
}
"getFeatureFlagResult" -> {
getFeatureFlagResult(call, result)
}
"register" -> {
register(call, result)
}
"unregister" -> {
unregister(call, result)
}
"debug" -> {
debug(call, result)
}
"flush" -> {
flush(result)
}
"captureException" -> {
captureException(call, result)
}
"addExceptionStep" -> {
addExceptionStep(call, result)
}
"close" -> {
close(result)
}
"sendMetaEvent" -> {
handleMetaEvent(call, result)
}
"sendFullSnapshot" -> {
handleSendFullSnapshot(call, result)
}
"captureNativeScreenshots" -> {
handleCaptureNativeScreenshots(call, result)
}
"enableNativeBridge" -> {
try {
// Episode-scoped: a stale enable must not re-arm the bridge
// for an episode Dart never handed off.
val episode = call.argument<Int>("episode")
val accepted =
isOccluded && episode == occlusionEpisode &&
replayIntegration() != null && isSessionReplayActive()
if (accepted) {
bridgeEnabled = true
nudgeOcclusionDetector()
}
result.success(accepted)
} catch (e: Throwable) {
// A decline never throws across the channel; Dart falls
// back to the placeholder.
result.success(false)
}
}
"setCaptureNativeScreens" -> {
val enabled = call.argument<Boolean>("enabled") ?: false
mainHandler.post {
if (enabled) {
startOcclusionDetector()
} else {
disableOcclusionDetector()
}
}
result.success(null)
}
"isSessionReplayActive" -> {
result.success(isSessionReplayActive())
}
"startSessionRecording" -> {
startSessionRecording(call, result)
}
"stopSessionRecording" -> {
stopSessionRecording(result)
}
"getSessionId" -> {
getSessionId(result)
}
"openUrl" -> {
openUrl(call, result)
}
"surveyAction" -> {
handleSurveyAction(call, result)
}
"displaySurvey" -> {
displaySurvey(call, result)
}
else -> {
result.notImplemented()
}
}
}
private fun isSessionReplayActive(): Boolean = PostHog.isSessionReplayActive()
private fun startSessionRecording(
call: MethodCall,
result: Result,
) {
val resumeCurrent = call.arguments as? Boolean ?: true
PostHog.startSessionReplay(resumeCurrent)
result.success(null)
}
private fun stopSessionRecording(result: Result) {
PostHog.stopSessionReplay()
result.success(null)
}
private fun handleMetaEvent(
call: MethodCall,
result: Result,
) {
try {
val width = call.argument<Int>("width") ?: 0
val height = call.argument<Int>("height") ?: 0
val screen = call.argument<String>("screen") ?: ""
if (width == 0 || height == 0) {
result.error("INVALID_ARGUMENT", "Width or height is 0", null)
return
}
snapshotSender.sendMetaEvent(width, height, screen)
result.success(null)
} catch (e: Throwable) {
result.error("PosthogFlutterException", e.localizedMessage, null)
}
}
private fun setup(
call: MethodCall,
result: Result,
) {
try {
val args = call.arguments() as Map<String, Any>? ?: mapOf<String, Any>()
if (args.isEmpty()) {
result.error("PosthogFlutterException", "Arguments is null or empty", null)
return
}
setupPostHog(args)
result.success(null)
} catch (e: Throwable) {
result.error("PosthogFlutterException", e.localizedMessage, null)
}
}
private fun setupPostHog(posthogConfig: Map<String, Any>) {
val projectToken =
(
(posthogConfig["projectToken"] as String?)
?: (posthogConfig["apiKey"] as String?)
)?.trim()
if (!posthogConfig.containsKey("projectToken") && posthogConfig.containsKey("apiKey")) {
Log.w(
"PostHog",
"apiKey is deprecated and will be removed in the next major version. Use projectToken instead!",
)
}
if (projectToken.isNullOrEmpty()) {
Log.e("PostHog", "Either projectToken or apiKey must be provided!")
return
}
val host =
(posthogConfig["host"] as String?)
?.trim()
?.takeIf { it.isNotEmpty() }
?: PostHogConfig.DEFAULT_HOST
val config =
PostHogAndroidConfig(projectToken, host).apply {
captureScreenViews = false
captureDeepLinks = false
posthogConfig.getIfNotNull<Boolean>("captureApplicationLifecycleEvents") {
captureApplicationLifecycleEvents = it
}
posthogConfig.getIfNotNull<Boolean>("debug") {
debug = it
}
posthogConfig.getIfNotNull<Int>("flushAt") {
flushAt = it
}
posthogConfig.getIfNotNull<Int>("maxQueueSize") {
maxQueueSize = it
}
posthogConfig.getIfNotNull<Int>("maxBatchSize") {
maxBatchSize = it
}
posthogConfig.getIfNotNull<Int>("flushInterval") {
flushIntervalSeconds = it
}
posthogConfig.getIfNotNull<Boolean>("sendFeatureFlagEvents") {
sendFeatureFlagEvent = it
}
posthogConfig.getIfNotNull<Boolean>("preloadFeatureFlags") {
preloadFeatureFlags = it
}
posthogConfig.getIfNotNull<Boolean>("optOut") {
optOut = it
}
posthogConfig.getIfNotNull<String>("personProfiles") {
when (it) {
"never" -> personProfiles = PersonProfiles.NEVER
"always" -> personProfiles = PersonProfiles.ALWAYS
"identifiedOnly" -> personProfiles = PersonProfiles.IDENTIFIED_ONLY
}
}
posthogConfig.getIfNotNull<Boolean>("sessionReplay") {
sessionReplay = it
}
this.sessionReplayConfig.captureLogcat = false
posthogConfig.getIfNotNull<Map<String, Any>>("sessionReplayConfig") { replayConfig ->
replayConfig.getIfNotNull<Double>("sampleRate") {
this.sessionReplayConfig.sampleRate = it
}
if (sessionReplay) {
val captureNativeScreens =
replayConfig["captureNativeScreens"] as? Boolean ?: false
// Unconditional: only bridged captures read these, so a
// runtime bridge toggle honors them.
(replayConfig["maskAllTexts"] as? Boolean)?.let {
this.sessionReplayConfig.maskAllTextInputs = it
}
(replayConfig["maskAllImages"] as? Boolean)?.let {
this.sessionReplayConfig.maskAllImages = it
}
if (captureNativeScreens) {
mainHandler.post { startOcclusionDetector() }
} else {
mainHandler.post { disableOcclusionDetector() }
}
} else {
mainHandler.post { disableOcclusionDetector() }
}
}
// Configure surveys
posthogConfig.getIfNotNull<Boolean>("surveys") {
surveys = it
if (surveys) {
val delegate = PostHogFlutterSurveysDelegate(channel)
surveysConfig.surveysDelegate = delegate
flutterSurveysDelegate = delegate
}
}
// Configure error tracking autocapture
posthogConfig.getIfNotNull<Map<String, Any>>("errorTrackingConfig") { errorConfig ->
errorConfig.getIfNotNull<Boolean>("captureNativeExceptions") {
errorTrackingConfig.autoCapture = it
}
errorConfig.getIfNotNull<List<String>>("inAppIncludes") { includes ->
errorTrackingConfig.inAppIncludes.addAll(includes)
}
errorConfig.getIfNotNull<Map<String, Any>>("exceptionSteps") { stepsConfig ->
stepsConfig.getIfNotNull<Boolean>("enabled") {
errorTrackingConfig.exceptionSteps.enabled = it
}
stepsConfig.getIfNotNull<Int>("maxBytes") {
errorTrackingConfig.exceptionSteps.maxBytes = it
}
}
}
// Configure logs (beforeSend runs Dart-side). Each field is only
// present when the user set it; unset fields keep native defaults.
posthogConfig.getIfNotNull<Map<String, Any>>("logs") { logsConfig ->
logsConfig.getIfNotNull<String>("serviceName") {
logs.serviceName = it
}
logsConfig.getIfNotNull<String>("serviceVersion") {
logs.serviceVersion = it
}
logsConfig.getIfNotNull<String>("environment") {
logs.environment = it
}
logsConfig.getIfNotNull<Map<String, Any>>("resourceAttributes") {
logs.resourceAttributes = it
}
logsConfig.getIfNotNull<Int>("flushIntervalSeconds") {
logs.flushIntervalSeconds = it
}
logsConfig.getIfNotNull<Int>("flushAt") {
logs.flushAt = it
}
logsConfig.getIfNotNull<Int>("maxBatchSize") {
logs.maxBatchSize = it
}
logsConfig.getIfNotNull<Int>("maxBufferSize") {
logs.maxBufferSize = it
}
logsConfig.getIfNotNull<Int>("rateCapMaxLogs") {
logs.rateCapMaxLogs = it
}
logsConfig.getIfNotNull<Int>("rateCapWindowSeconds") {
logs.rateCapWindowSeconds = it
}
}
// Bootstrap precedence and flag layering live in the native SDK; forward values only.
posthogConfig.getIfNotNull<Map<String, Any>>("bootstrap") {
this.bootstrap = bootstrapConfigFromMap(it)
}
sdkName = "posthog-flutter"
sdkVersion = postHogVersion
onFeatureFlags =
PostHogOnFeatureFlags {
Log.i("PostHogFlutter", "Android onFeatureFlags triggered. Notifying Dart.")
invokeFlutterMethod("onFeatureFlagsCallback", emptyMap<String, Any?>())
}
}
PostHogAndroid.setup(applicationContext, config)
postHogConfig = config
cachedReplayIntegration = null
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
application = binding.activity.application
// Only if the detector is already running; else the setup path registers
// it. Keeps a default-off feature from installing app-wide callbacks.
if (occlusionDetectorRunning) {
registerLifecycleTracking()
}
}
override fun onDetachedFromActivityForConfigChanges() {
unregisterLifecycleTracking()
activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
application = binding.activity.application
if (occlusionDetectorRunning) {
registerLifecycleTracking()
}
}
override fun onDetachedFromActivity() {
unregisterLifecycleTracking()
activity = null
}
// Idempotent: registering the same callbacks twice makes them fire twice.
private fun registerLifecycleTracking() {
val app = application ?: return
if (lifecycleCallbacksRegistered) {
return
}
isHostActivityStopped = false
otherResumedCount = 0
app.registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
lifecycleCallbacksRegistered = true
}
private fun unregisterLifecycleTracking() {
if (!lifecycleCallbacksRegistered) {
return
}
application?.unregisterActivityLifecycleCallbacks(activityLifecycleCallbacks)
lifecycleCallbacksRegistered = false
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
stopOcclusionDetector()
channel.setMethodCallHandler(null)
bitmapExportExecutor.shutdown()
}
private var cachedReplayIntegration: PostHogReplayIntegration? = null
private fun replayIntegration(): PostHogReplayIntegration? {
cachedReplayIntegration?.let { return it }
return postHogConfig
?.integrations
?.filterIsInstance<PostHogReplayIntegration>()
?.firstOrNull()
.also { cachedReplayIntegration = it }
}
// Occlusion episode protocol: a main-thread ticker — independent of Flutter's
// frame lifecycle, which can pause under a native cover — pushes occlusion
// transitions to Dart and drives bridge captures. State below is @Volatile
// for the capture executor.
@Volatile
internal var isOccluded = false
@Volatile
internal var bridgeEnabled = false
// Whether the episode has delivered its first bridged frame.
private var bridgeEpisodeStarted = false
// End-transition debounce: ticks reading not-occluded while an episode is active.
private var notOccludedTicks = 0
// Monotonic episode id, stamped into every push so Dart drops stale-episode
// async work. Volatile: re-read on the capture executor.
@Volatile
internal var occlusionEpisode = 0
// Failed captures before the episode's first delivered frame; at the limit it
// falls back (bridgeFailed). In-flight captures don't count; after first
// delivery, failures never demote.
private var bridgeFailureStrikes = 0
// Set while a capture is scheduled but its result hasn't posted back — stops
// stacking captures and mistaking in-flight for a delivery gap.
private var bridgeCaptureInFlight = false
private var occlusionDetectorRunning = false
private var lifecycleCallbacksRegistered = false
// One guarded tick. The running check no-ops a stale runnable (ticker or nudge)
// that removeCallbacks missed post-teardown; the catch stops a throw (channel
// invoke / peekDecorView on a dead window) from crashing the app.
private fun runTickSafely() {
if (!occlusionDetectorRunning) {
return
}
try {
occlusionTick()
} catch (e: Throwable) {
Log.w("PostHog", "Occlusion tick failed: $e")
}
}
private val occlusionTicker =
object : Runnable {
override fun run() {
runTickSafely()
// Reschedule while running, even after a caught throw, so a
// transient failure never kills the detector.
if (occlusionDetectorRunning) {
mainHandler.postDelayed(this, OCCLUSION_TICK_MS)
}
}
}
// A named instance (not an anonymous lambda) so stopOcclusionDetector can
// actually cancel a pending nudge.
private val nudgeRunnable = Runnable { runTickSafely() }
private fun startOcclusionDetector() {
if (occlusionDetectorRunning) {
return
}
occlusionDetectorRunning = true
// Callbacks feed the detector and only run while it does — registered
// here, not on attach, so a disabled bridge installs nothing.
registerLifecycleTracking()
mainHandler.postDelayed(occlusionTicker, OCCLUSION_TICK_MS)
}
// Runs a tick immediately on a lifecycle transition instead of waiting for
// the next poll, so a native screen appears in replay within a frame or two.
// Never reschedules the ticker.
private fun nudgeOcclusionDetector() {
if (!occlusionDetectorRunning) {
return
}
// Coalesce a burst of lifecycle callbacks into one immediate tick.
mainHandler.removeCallbacks(nudgeRunnable)
mainHandler.post(nudgeRunnable)
}
private fun stopOcclusionDetector() {
occlusionDetectorRunning = false
mainHandler.removeCallbacks(occlusionTicker)
mainHandler.removeCallbacks(nudgeRunnable)
unregisterLifecycleTracking()
}
// For a setup() re-run that drops the feature: unlike a bare stop, ends any
// active episode, otherwise Dart never learns and keeps its capture
// suppressed.
private fun disableOcclusionDetector() {
stopOcclusionDetector()
if (isOccluded || bridgeEnabled) {
isOccluded = false
bridgeEnabled = false
bridgeEpisodeStarted = false
bridgeFailureStrikes = 0
bridgeCaptureInFlight = false
pushOcclusionEvent(occluded = false)
}
}
private fun pushOcclusionEvent(
occluded: Boolean,
bridgeFailed: Boolean = false,
) {
channel.invokeMethod(
"onNativeOcclusionChanged",
mapOf(
"occluded" to occluded,
"episode" to occlusionEpisode,
"bridgeFailed" to bridgeFailed,
),
)
}
@OptIn(PostHogInternalReplayApi::class)
private fun occlusionTick() {
if (!isSessionReplayActive()) {
if (isOccluded || bridgeEnabled) {
isOccluded = false
bridgeEnabled = false
bridgeEpisodeStarted = false
bridgeFailureStrikes = 0
bridgeCaptureInFlight = false
// Dart must learn the episode ended, otherwise the next
// occluded=true push looks like unchanged state.
pushOcclusionEvent(occluded = false)
}
return
}
// Null activity (config-change detach) fails open — the captured Flutter
// tree has no native pixels. Known limitation: a host recreation
// mid-episode never re-fires onActivityResumed, ending the episode early.
val occludedNow =
activity != null && isHostActivityStopped && otherResumedCount > 0
// Debounce END only: a native→native handoff (A pauses before B resumes)
// briefly reads not-occluded; ending the episode there would flash a
// stale Flutter frame into the native flow.
if (!occludedNow && isOccluded && notOccludedTicks < 1) {
notOccludedTicks++
return
}
// Occluded again after a blip = the cover was swapped. The old cover's
// bridge grant must not carry over; re-handshake under a new episode
// id. No end event, so Dart's suppression never lapses.
val coverSwapped = occludedNow && isOccluded && notOccludedTicks > 0
notOccludedTicks = 0
if (occludedNow != isOccluded) {
val previousOccluded = isOccluded
val previousEpisode = occlusionEpisode
isOccluded = occludedNow
if (occludedNow) {
occlusionEpisode++
} else {
bridgeEnabled = false
}
bridgeEpisodeStarted = false
bridgeFailureStrikes = 0
bridgeCaptureInFlight = false
try {
pushOcclusionEvent(occluded = occludedNow)
} catch (e: Throwable) {
// The transition never reached Dart. Roll the episode state
// back so the next tick re-detects and re-pushes it, instead
// of advancing to an episode Dart never heard begin — whose
// bridge frames it would then silently drop as stale.
isOccluded = previousOccluded
occlusionEpisode = previousEpisode
throw e
}
} else if (coverSwapped) {
val previousEpisode = occlusionEpisode
occlusionEpisode++
bridgeEnabled = false
bridgeEpisodeStarted = false
bridgeFailureStrikes = 0
bridgeCaptureInFlight = false
try {
pushOcclusionEvent(occluded = true)
} catch (e: Throwable) {
// The re-handshake never reached Dart; the bridge stays
// disarmed (failing toward not capturing), but roll the episode
// back so in-flight results still match their episode.
occlusionEpisode = previousEpisode
throw e
}
}
if (occludedNow && bridgeEnabled && !bridgeCaptureInFlight) {
// excludeView and validity are resolved at call time (surviving host
// recreation); the first capture resets the decor view's snapshot
// state so a reused activity opens with a full snapshot.
val isFirst = !bridgeEpisodeStarted
val episode = occlusionEpisode
bridgeCaptureInFlight = true
// Applies a capture outcome on the main thread (the capture callback
// fires off it), ignoring a result that lands after the episode
// moved on. Posted so it never runs re-entrantly within this tick.
fun postResult(delivered: Boolean) {
mainHandler.post {
// Engine detach can land between capture and result; the
// channel is dead then and a strike-limit push would throw
// uncaught on the main looper.
if (!occlusionDetectorRunning || occlusionEpisode != episode) {
return@post
}
bridgeCaptureInFlight = false
try {
onBridgeCaptureResult(delivered)
} catch (e: Throwable) {
Log.w("PostHog", "Occlusion bridge result failed: $e")
}
}
}
val scheduled =
try {
replayIntegration()?.captureSessionReplaySnapshot(
activity?.window?.peekDecorView(),
isFirst,
{ isOccluded && bridgeEnabled && occlusionEpisode == episode },
) { delivered -> postResult(delivered) } ?: false
} catch (e: Throwable) {
// peekDecorView / captureSessionReplaySnapshot can throw on
// a torn-down window. Treat as not-scheduled so postResult
// below clears the in-flight latch; leaving it set would
// block every later capture for the rest of the episode.
Log.w("PostHog", "Occlusion bridge capture failed to schedule: $e")
false
}
// Nothing was queued, so the capture callback will never fire —
// record the delivery gap.
if (!scheduled) {
postResult(false)
}
}
}
// Demotion is gated on the episode never having delivered: captures fail
// transiently during interaction (the SDK rejects redraw-racing captures to
// keep masks aligned), so demoting a working episode would swap real frames
// for the fallback. After the first delivered frame, failures just hold the
// last good frame.
private fun onBridgeCaptureResult(delivered: Boolean) {
if (!isOccluded || !bridgeEnabled) {
return
}
if (delivered) {
bridgeEpisodeStarted = true
bridgeFailureStrikes = 0
} else if (!bridgeEpisodeStarted) {
bridgeFailureStrikes++
if (bridgeFailureStrikes >= BRIDGE_FAILURE_STRIKE_LIMIT) {
bridgeEnabled = false
pushOcclusionEvent(occluded = true, bridgeFailed = true)
}
}
}
private fun handleSendFullSnapshot(
call: MethodCall,
result: Result,
) {
try {
val imageBytes = call.argument<ByteArray>("imageBytes")
val id = call.argument<Int>("id") ?: 1
val x = call.argument<Int>("x") ?: 0
val y = call.argument<Int>("y") ?: 0
if (imageBytes != null) {
snapshotSender.sendFullSnapshot(imageBytes, id, x, y)
result.success(null)
} else {
result.error("INVALID_ARGUMENT", "Image bytes are null", null)
}
} catch (e: Throwable) {
result.error("PosthogFlutterException", e.localizedMessage, null)
}
}
private fun handleCaptureNativeScreenshots(
call: MethodCall,
result: Result,
) {
try {
val currentActivity =
activity ?: run {
result.success(emptyList<ByteArray?>())
return
}
@Suppress("UNCHECKED_CAST")
val views = call.argument<List<Map<String, Int>>>("views") ?: emptyList()
if (views.isEmpty()) {