• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.systemui.keyboard.shortcut.data.repository
18 
19 import android.hardware.input.InputManager
20 import android.view.KeyCharacterMap.VIRTUAL_KEYBOARD
21 import com.android.systemui.dagger.SysUISingleton
22 import com.android.systemui.dagger.qualifiers.Background
23 import com.android.systemui.keyboard.shortcut.shared.model.ShortcutHelperState
24 import com.android.systemui.keyboard.shortcut.shared.model.ShortcutHelperState.Active
25 import com.android.systemui.keyboard.shortcut.shared.model.ShortcutHelperState.Inactive
26 import com.android.systemui.shared.hardware.findInputDevice
27 import kotlinx.coroutines.CoroutineDispatcher
28 import kotlinx.coroutines.flow.MutableStateFlow
29 import kotlinx.coroutines.flow.asStateFlow
30 import kotlinx.coroutines.withContext
31 import javax.inject.Inject
32 
33 @SysUISingleton
34 class ShortcutHelperStateRepository
35 @Inject
36 constructor(
37     private val inputManager: InputManager,
38     @Background private val backgroundDispatcher: CoroutineDispatcher,
39 ) {
40     private val _state = MutableStateFlow<ShortcutHelperState>(Inactive)
41     val state = _state.asStateFlow()
42 
togglenull43     suspend fun toggle(deviceId: Int? = null) {
44         if (_state.value is Inactive) {
45             show(deviceId)
46         } else {
47             hide()
48         }
49     }
50 
shownull51     suspend fun show(deviceId: Int? = null) {
52         _state.value = Active(deviceId ?: findPhysicalKeyboardId())
53     }
54 
hidenull55     fun hide() {
56         _state.value = Inactive
57     }
58 
findPhysicalKeyboardIdnull59     private suspend fun findPhysicalKeyboardId() =
60         withContext(backgroundDispatcher) {
61             val firstEnabledPhysicalKeyboard =
62                 inputManager.findInputDevice { it.isEnabled && it.isFullKeyboard && !it.isVirtual }
63             return@withContext firstEnabledPhysicalKeyboard?.id ?: VIRTUAL_KEYBOARD
64         }
65 
66 }
67