1 /*
<lambda>null2  * 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.qs.panels.data.repository
18 
19 import android.content.Context
20 import android.content.SharedPreferences
21 import com.android.systemui.dagger.SysUISingleton
22 import com.android.systemui.dagger.qualifiers.Background
23 import com.android.systemui.settings.UserFileManager
24 import com.android.systemui.user.data.repository.UserRepository
25 import com.android.systemui.util.kotlin.SharedPreferencesExt.observe
26 import com.android.systemui.util.kotlin.emitOnStart
27 import javax.inject.Inject
28 import kotlinx.coroutines.CoroutineDispatcher
29 import kotlinx.coroutines.ExperimentalCoroutinesApi
30 import kotlinx.coroutines.flow.Flow
31 import kotlinx.coroutines.flow.flatMapLatest
32 import kotlinx.coroutines.flow.flowOn
33 import kotlinx.coroutines.flow.map
34 
35 /** Repository for QS user preferences. */
36 @OptIn(ExperimentalCoroutinesApi::class)
37 @SysUISingleton
38 class QSPreferencesRepository
39 @Inject
40 constructor(
41     private val userFileManager: UserFileManager,
42     private val userRepository: UserRepository,
43     @Background private val backgroundDispatcher: CoroutineDispatcher,
44 ) {
45     /** Whether to show the labels on icon tiles for the current user. */
46     val showLabels: Flow<Boolean> =
47         userRepository.selectedUserInfo
48             .flatMapLatest { userInfo ->
49                 val prefs = getSharedPrefs(userInfo.id)
50                 prefs.observe().emitOnStart().map { prefs.getBoolean(ICON_LABELS_KEY, false) }
51             }
52             .flowOn(backgroundDispatcher)
53 
54     /** Sets for the current user whether to show the labels on icon tiles. */
55     fun setShowLabels(showLabels: Boolean) {
56         with(getSharedPrefs(userRepository.getSelectedUserInfo().id)) {
57             edit().putBoolean(ICON_LABELS_KEY, showLabels).apply()
58         }
59     }
60 
61     private fun getSharedPrefs(userId: Int): SharedPreferences {
62         return userFileManager.getSharedPreferences(
63             FILE_NAME,
64             Context.MODE_PRIVATE,
65             userId,
66         )
67     }
68 
69     companion object {
70         private const val ICON_LABELS_KEY = "show_icon_labels"
71         const val FILE_NAME = "quick_settings_prefs"
72     }
73 }
74