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.os.Looper
21 import android.os.Process
22 import android.tracing.Flags
23 import android.util.Log
24 
25 /**
26  * Factory to create polymorphic instances of ViewCapture according to build configurations and
27  * flags.
28  */
29 class ViewCaptureFactory {
30     companion object {
31         private val TAG = ViewCaptureFactory::class.java.simpleName
32         private var instance: ViewCapture? = null
33 
34         @JvmStatic
getInstancenull35         fun getInstance(context: Context): ViewCapture {
36             if (Looper.myLooper() != Looper.getMainLooper()) {
37                 return ViewCapture.MAIN_EXECUTOR.submit { getInstance(context) }.get()
38             }
39 
40             if (instance != null) {
41                 return instance!!
42             }
43 
44             return when {
45                 !android.os.Build.IS_DEBUGGABLE -> {
46                     Log.i(TAG, "instantiating ${NoOpViewCapture::class.java.simpleName}")
47                     NoOpViewCapture()
48                 }
49                 !Flags.perfettoViewCaptureTracing() -> {
50                     Log.i(TAG, "instantiating ${SettingsAwareViewCapture::class.java.simpleName}")
51                     SettingsAwareViewCapture(
52                         context.applicationContext,
53                         ViewCapture.createAndStartNewLooperExecutor(
54                             "SAViewCapture",
55                             Process.THREAD_PRIORITY_FOREGROUND
56                         )
57                     )
58                 }
59                 else -> {
60                     Log.i(TAG, "instantiating ${PerfettoViewCapture::class.java.simpleName}")
61                     PerfettoViewCapture(
62                         context.applicationContext,
63                         ViewCapture.createAndStartNewLooperExecutor(
64                             "PerfettoViewCapture",
65                             Process.THREAD_PRIORITY_FOREGROUND
66                         )
67                     )
68                 }
69             }.also { instance = it }
70         }
71     }
72 }
73