1 /* 2 * Copyright 2022 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 androidx.camera.camera2.pipe.testing 18 19 import android.os.Handler 20 import android.os.HandlerThread 21 import androidx.camera.camera2.pipe.core.Threads 22 import kotlinx.coroutines.CoroutineDispatcher 23 import kotlinx.coroutines.CoroutineName 24 import kotlinx.coroutines.CoroutineScope 25 import kotlinx.coroutines.asExecutor 26 import kotlinx.coroutines.test.StandardTestDispatcher 27 import kotlinx.coroutines.test.TestScope 28 29 public object FakeThreads { fromDispatchernull30 public fun fromDispatcher( 31 dispatcher: CoroutineDispatcher, 32 blockingDispatcher: CoroutineDispatcher? = null, 33 ): Threads { 34 val scope = CoroutineScope(dispatcher + CoroutineName("CXCP-TestScope")) 35 return create(scope, dispatcher, blockingDispatcher) 36 } 37 fromTestScopenull38 public fun fromTestScope( 39 scope: TestScope, 40 blockingDispatcher: CoroutineDispatcher? = null, 41 ): Threads { 42 val dispatcher = StandardTestDispatcher(scope.testScheduler, "CXCP-TestScope") 43 return create(scope, dispatcher, blockingDispatcher) 44 } 45 createnull46 private fun create( 47 scope: CoroutineScope, 48 dispatcher: CoroutineDispatcher, 49 blockingDispatcher: CoroutineDispatcher?, 50 ): Threads { 51 val executor = dispatcher.asExecutor() 52 53 @Suppress("deprecation") 54 val fakeHandler = { 55 val handlerThread = HandlerThread("FakeHandlerThread").apply { start() } 56 Handler(handlerThread.looper) 57 } 58 59 return Threads( 60 scope, 61 blockingExecutor = blockingDispatcher?.asExecutor() ?: executor, 62 blockingDispatcher = blockingDispatcher ?: dispatcher, 63 backgroundExecutor = executor, 64 backgroundDispatcher = dispatcher, 65 lightweightExecutor = executor, 66 lightweightDispatcher = dispatcher, 67 camera2Handler = fakeHandler, 68 camera2Executor = { executor } 69 ) 70 } 71 } 72