1 package com.android.wallpaper.picker.customization.ui.view
2 
3 import android.content.Context
4 import android.util.AttributeSet
5 import android.view.SurfaceView
6 import android.view.View
7 import android.view.ViewParent
8 import androidx.core.view.isVisible
9 import com.android.wallpaper.R
10 
11 /**
12  * A SurfaceView to handle a few things specific to live wallpaper previews.
13  *
14  * <p>Visibility updates: this is an interim solution until b/287618705 is fixed.
15  *
16  * <p>We need to notify the wallpaper engine when its surface changes visibility. ViewTreeObserver
17  * changes aren't reliable for tab switches (why?) so we need to override onVisibilityChanged.
18  * onVisibilityChanged happens when visibility changes, but doesn't always reflect tab visibility,
19  * so we look up the tree until we find the owning scroll container and reports its visibility
20  * instead.
21  */
22 class WallpaperSurfaceView(context: Context, attrs: AttributeSet? = null) :
23     SurfaceView(context, attrs) {
24 
<lambda>null25     var visibilityCallback: (visible: Boolean) -> Unit = {}
26     val visibilityViewIds = listOf(R.id.lock_scroll_container, R.id.home_scroll_container)
27     var scrollContainer: View? = null
28 
onVisibilityChangednull29     override fun onVisibilityChanged(changedView: View, visibility: Int) {
30         super.onVisibilityChanged(changedView, visibility)
31         val visible = scrollContainer?.isVisible ?: false
32         visibilityCallback(visible)
33     }
34 
35     init {
36         addOnAttachStateChangeListener(
37             object : OnAttachStateChangeListener {
onViewAttachedToWindownull38                 override fun onViewAttachedToWindow(v: View) {
39                     var parent: ViewParent? = v.parent
40                     while (parent != null && scrollContainer == null) {
41                         parent = parent.parent
42                         val view = parent as? View
43                         if (view?.id in visibilityViewIds) {
44                             scrollContainer = view
45                         }
46                     }
47                 }
48 
onViewDetachedFromWindownull49                 override fun onViewDetachedFromWindow(v: View) {
50                     // Do nothing
51                 }
52             }
53         )
54     }
55 }
56