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.navigationbar.gestural.data.respository
18 
19 import com.android.systemui.dagger.SysUISingleton
20 import com.android.systemui.dagger.qualifiers.Main
21 import com.android.systemui.navigationbar.gestural.domain.TaskMatcher
22 import javax.inject.Inject
23 import kotlinx.coroutines.CoroutineDispatcher
24 import kotlinx.coroutines.flow.MutableStateFlow
25 import kotlinx.coroutines.flow.StateFlow
26 import kotlinx.coroutines.withContext
27 
28 /** A repository for storing gesture related information */
29 interface GestureRepository {
30     /** A {@link StateFlow} tracking matchers that can block gestures. */
31     val gestureBlockedMatchers: StateFlow<Set<TaskMatcher>>
32 
33     /** Adds a matcher to determine whether a gesture should be blocked. */
addGestureBlockedMatchernull34     suspend fun addGestureBlockedMatcher(matcher: TaskMatcher)
35 
36     /** Removes a matcher from blocking from gestures. */
37     suspend fun removeGestureBlockedMatcher(matcher: TaskMatcher)
38 }
39 
40 @SysUISingleton
41 class GestureRepositoryImpl
42 @Inject
43 constructor(@Main private val mainDispatcher: CoroutineDispatcher) : GestureRepository {
44     private val _gestureBlockedMatchers = MutableStateFlow<Set<TaskMatcher>>(emptySet())
45 
46     override val gestureBlockedMatchers: StateFlow<Set<TaskMatcher>>
47         get() = _gestureBlockedMatchers
48 
49     override suspend fun addGestureBlockedMatcher(matcher: TaskMatcher) =
50         withContext(mainDispatcher) {
51             val existingMatchers = _gestureBlockedMatchers.value
52             if (existingMatchers.contains(matcher)) {
53                 return@withContext
54             }
55 
56             _gestureBlockedMatchers.value = existingMatchers.toMutableSet().apply { add(matcher) }
57         }
58 
59     override suspend fun removeGestureBlockedMatcher(matcher: TaskMatcher) =
60         withContext(mainDispatcher) {
61             val existingMatchers = _gestureBlockedMatchers.value
62             if (!existingMatchers.contains(matcher)) {
63                 return@withContext
64             }
65 
66             _gestureBlockedMatchers.value =
67                 existingMatchers.toMutableSet().apply { remove(matcher) }
68         }
69 }
70