1616
1717package com.duckduckgo.adblocking.impl
1818
19+ import android.view.ViewTreeObserver
1920import android.webkit.WebView
2021import androidx.annotation.UiThread
22+ import androidx.fragment.app.Fragment
23+ import androidx.fragment.app.FragmentManager
24+ import androidx.lifecycle.findViewTreeLifecycleOwner
25+ import androidx.lifecycle.lifecycleScope
2126import com.duckduckgo.di.scopes.AppScope
2227import com.squareup.anvil.annotations.ContributesBinding
28+ import kotlinx.coroutines.launch
29+ import kotlinx.coroutines.suspendCancellableCoroutine
2330import javax.inject.Inject
31+ import kotlin.coroutines.resume
2432
2533interface ContingencyMessageView {
2634 @UiThread
@@ -31,6 +39,32 @@ interface ContingencyMessageView {
3139class RealContingencyMessageView @Inject constructor() : ContingencyMessageView {
3240
3341 override fun show (webView : WebView ) {
34- ContingencyMessageBottomSheet (webView.context).show()
42+ val lifecycleOwner = webView.findViewTreeLifecycleOwner() ? : return
43+ lifecycleOwner.lifecycleScope.launch {
44+ webView.awaitWindowFocus()
45+ val fragment: Fragment = FragmentManager .findFragment(webView)
46+ val fragmentManager = fragment.childFragmentManager
47+ if (fragmentManager.findFragmentByTag(ContingencyMessageBottomSheetFragment .TAG ) == null ) {
48+ ContingencyMessageBottomSheetFragment .newInstance()
49+ .show(fragmentManager, ContingencyMessageBottomSheetFragment .TAG )
50+ }
51+ }
52+ }
53+ }
54+
55+ private suspend fun WebView.awaitWindowFocus () {
56+ if (hasWindowFocus()) return
57+ suspendCancellableCoroutine { continuation ->
58+ val observer = viewTreeObserver
59+ val listener = object : ViewTreeObserver .OnWindowFocusChangeListener {
60+ override fun onWindowFocusChanged (hasFocus : Boolean ) {
61+ if (hasFocus) {
62+ observer.removeOnWindowFocusChangeListener(this )
63+ continuation.resume(Unit )
64+ }
65+ }
66+ }
67+ observer.addOnWindowFocusChangeListener(listener)
68+ continuation.invokeOnCancellation { observer.removeOnWindowFocusChangeListener(listener) }
3569 }
3670}
0 commit comments