1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.app.viewcapture 18 19 import android.content.Context 20 import android.media.permission.SafeCloseable 21 import android.os.IBinder 22 import android.view.View 23 import android.view.ViewGroup 24 import android.view.Window 25 import android.view.WindowManager 26 import android.view.WindowManagerImpl 27 28 /** 29 * [WindowManager] implementation to enable view tracing. Adds [ViewCapture] to associated window 30 * when it is added to view hierarchy. Use [ViewCaptureAwareWindowManagerFactory] to create an 31 * instance of this class. 32 */ 33 internal class ViewCaptureAwareWindowManager( 34 private val context: Context, 35 private val parent: Window? = null, 36 private val windowContextToken: IBinder? = null, 37 ) : WindowManagerImpl(context, parent, windowContextToken) { 38 39 private var viewCaptureCloseableMap: MutableMap<View, SafeCloseable> = mutableMapOf() 40 addViewnull41 override fun addView(view: View, params: ViewGroup.LayoutParams) { 42 super.addView(view, params) 43 val viewCaptureCloseable: SafeCloseable = 44 ViewCaptureFactory.getInstance(context).startCapture(view, getViewName(view)) 45 viewCaptureCloseableMap[view] = viewCaptureCloseable 46 } 47 removeViewnull48 override fun removeView(view: View?) { 49 removeViewFromCloseableMap(view) 50 super.removeView(view) 51 } 52 removeViewImmediatenull53 override fun removeViewImmediate(view: View?) { 54 removeViewFromCloseableMap(view) 55 super.removeViewImmediate(view) 56 } 57 getViewNamenull58 private fun getViewName(view: View) = "." + view.javaClass.name 59 60 private fun removeViewFromCloseableMap(view: View?) { 61 if (viewCaptureCloseableMap.containsKey(view)) { 62 viewCaptureCloseableMap[view]?.close() 63 viewCaptureCloseableMap.remove(view) 64 } 65 } 66 } 67