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 com.android.systemui.keyevent.domain.interactor
18 
19 import android.view.KeyEvent
20 import com.android.systemui.back.domain.interactor.BackActionInteractor
21 import com.android.systemui.dagger.SysUISingleton
22 import com.android.systemui.keyguard.domain.interactor.KeyguardKeyEventInteractor
23 import javax.inject.Inject
24 
25 /**
26  * Sends key events to the appropriate interactors and then acts upon key events that haven't
27  * already been handled but should be handled by SystemUI.
28  */
29 @SysUISingleton
30 class KeyEventInteractor
31 @Inject
32 constructor(
33     private val backActionInteractor: BackActionInteractor,
34     private val keyguardKeyEventInteractor: KeyguardKeyEventInteractor,
35 ) {
36     fun dispatchKeyEvent(event: KeyEvent): Boolean {
37         if (keyguardKeyEventInteractor.dispatchKeyEvent(event)) {
38             return true
39         }
40 
41         when (event.keyCode) {
42             KeyEvent.KEYCODE_BACK -> {
43                 if (event.handleAction()) {
44                     backActionInteractor.onBackRequested()
45                 }
46                 return true
47             }
48         }
49         return false
50     }
51 
52     fun interceptMediaKey(event: KeyEvent): Boolean {
53         return keyguardKeyEventInteractor.interceptMediaKey(event)
54     }
55 
56     fun dispatchKeyEventPreIme(event: KeyEvent): Boolean {
57         return keyguardKeyEventInteractor.dispatchKeyEventPreIme(event)
58     }
59 
60     companion object {
61         // Most actions shouldn't be handled on the down event and instead handled on subsequent
62         // key events like ACTION_UP.
63         fun KeyEvent.handleAction(): Boolean {
64             return action != KeyEvent.ACTION_DOWN
65         }
66     }
67 }
68