1 /*
2  * 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 android.tools.device.apphelpers
18 
19 import android.app.Instrumentation
20 import android.content.Intent
21 import android.content.pm.PackageManager
22 import android.content.pm.ResolveInfo
23 import android.provider.MediaStore
24 import android.tools.traces.component.ComponentNameMatcher
25 import android.tools.traces.component.IComponentNameMatcher
26 import androidx.test.platform.app.InstrumentationRegistry
27 
28 /** Helper to launch the Camera app. */
29 class CameraAppHelper
30 @JvmOverloads
31 constructor(
32     instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation(),
33     pkgManager: PackageManager = instrumentation.context.packageManager,
34     appName: String = getCameraLauncherName(pkgManager),
35     appComponent: IComponentNameMatcher = getCameraComponent(pkgManager),
36 ) : StandardAppHelper(instrumentation, appName, appComponent) {
37 
38     override val openAppIntent =
39         pkgManager.getLaunchIntentForPackage(packageName)
40             ?: error("Unable to find intent for camera")
41 
42     companion object {
getCameraIntentnull43         private fun getCameraIntent(): Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
44 
45         private fun getResolveInfo(pkgManager: PackageManager): ResolveInfo =
46             pkgManager.resolveActivity(getCameraIntent(), PackageManager.MATCH_DEFAULT_ONLY)
47                 ?: error("unable to resolve camera activity")
48 
49         private fun getCameraComponent(pkgManager: PackageManager): ComponentNameMatcher =
50             ComponentNameMatcher(
51                 getResolveInfo(pkgManager).activityInfo.packageName,
52                 className = "",
53             )
54 
55         private fun getCameraLauncherName(pkgManager: PackageManager): String =
56             getResolveInfo(pkgManager).loadLabel(pkgManager).toString()
57     }
58 }
59