1 /* <lambda>null2 * Copyright (C) 2023 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.content.pm.LauncherApps 21 import android.database.ContentObserver 22 import android.os.Handler 23 import android.os.ParcelFileDescriptor 24 import android.provider.Settings 25 import android.util.Log 26 import android.window.IDumpCallback 27 import androidx.annotation.AnyThread 28 import androidx.annotation.VisibleForTesting 29 import java.util.concurrent.Executor 30 31 private val TAG = SettingsAwareViewCapture::class.java.simpleName 32 33 /** 34 * ViewCapture that listens to system updates and enables / disables attached ViewCapture 35 * WindowListeners accordingly. The Settings toggle is currently controlled by the Winscope 36 * developer tile in the System developer options. 37 */ 38 internal class SettingsAwareViewCapture 39 internal constructor(private val context: Context, executor: Executor) : 40 ViewCapture(DEFAULT_MEMORY_SIZE, DEFAULT_INIT_POOL_SIZE, executor) { 41 /** Dumps all the active view captures to the wm trace directory via LauncherAppService */ 42 private val mDumpCallback: IDumpCallback.Stub = object : IDumpCallback.Stub() { 43 override fun onDump(out: ParcelFileDescriptor) { 44 try { 45 ParcelFileDescriptor.AutoCloseOutputStream(out).use { os -> dumpTo(os, context) } 46 } catch (e: Exception) { 47 Log.e(TAG, "failed to dump data to wm trace", e) 48 } 49 } 50 } 51 52 init { 53 enableOrDisableWindowListeners() 54 context.contentResolver.registerContentObserver( 55 Settings.Global.getUriFor(VIEW_CAPTURE_ENABLED), 56 false, 57 object : ContentObserver(Handler()) { 58 override fun onChange(selfChange: Boolean) { 59 enableOrDisableWindowListeners() 60 } 61 }) 62 } 63 64 @AnyThread 65 private fun enableOrDisableWindowListeners() { 66 mBgExecutor.execute { 67 val isEnabled = Settings.Global.getInt(context.contentResolver, VIEW_CAPTURE_ENABLED, 68 0) != 0 69 MAIN_EXECUTOR.execute { 70 enableOrDisableWindowListeners(isEnabled) 71 } 72 val launcherApps = context.getSystemService(LauncherApps::class.java) 73 if (isEnabled) { 74 launcherApps?.registerDumpCallback(mDumpCallback) 75 } else { 76 launcherApps?.unRegisterDumpCallback(mDumpCallback) 77 } 78 } 79 } 80 81 companion object { 82 @VisibleForTesting internal const val VIEW_CAPTURE_ENABLED = "view_capture_enabled" 83 } 84 }