blob: ad592d8deafc2d838d54ac235796a69e467d2ced [file] [log] [blame]
Stefan Andonian5bd9a222023-02-23 00:58:33 +00001/*
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 */
Stefan Andonian146701c2022-11-10 23:07:40 +000016package com.android.launcher3
17
18import android.content.Context
Stefan Andonian5bd9a222023-02-23 00:58:33 +000019import android.content.Context.MODE_PRIVATE
Stefan Andonian146701c2022-11-10 23:07:40 +000020import android.content.SharedPreferences
Stefan Andoniand1b33b32022-12-16 21:22:27 +000021import androidx.annotation.VisibleForTesting
fbarone58aaf12023-09-25 11:34:56 -070022import com.android.launcher3.BuildConfig.WIDGET_ON_FIRST_SCREEN
Charlie Andersonbad2be42024-12-06 16:32:03 -050023import com.android.launcher3.InvariantDeviceProfile.GRID_NAME_PREFS_KEY
Stefan Andonian4c9612b2023-02-22 00:00:03 +000024import com.android.launcher3.LauncherFiles.DEVICE_PREFERENCES_KEY
25import com.android.launcher3.LauncherFiles.SHARED_PREFERENCES_KEY
Sunny Goyale79d4532024-12-31 00:10:20 -080026import com.android.launcher3.dagger.ApplicationContext
27import com.android.launcher3.dagger.LauncherAppComponent
28import com.android.launcher3.dagger.LauncherAppSingleton
Stefan Andoniand1b33b32022-12-16 21:22:27 +000029import com.android.launcher3.model.DeviceGridState
30import com.android.launcher3.pm.InstallSessionHelper
31import com.android.launcher3.provider.RestoreDbTask
Charlie Anderson511421c2023-10-26 11:22:26 -040032import com.android.launcher3.provider.RestoreDbTask.FIRST_LOAD_AFTER_RESTORE_KEY
Sebastian Franco9e4c99b2024-10-02 15:16:37 -070033import com.android.launcher3.settings.SettingsActivity
Stefan Andonian1d7f7032023-01-23 21:55:04 +000034import com.android.launcher3.states.RotationHelper
Sunny Goyale79d4532024-12-31 00:10:20 -080035import com.android.launcher3.util.DaggerSingletonObject
Stefan Andonian1d7f7032023-01-23 21:55:04 +000036import com.android.launcher3.util.DisplayController
Stefan Andoniand1b33b32022-12-16 21:22:27 +000037import com.android.launcher3.util.Themes
Sunny Goyale79d4532024-12-31 00:10:20 -080038import javax.inject.Inject
Stefan Andonian146701c2022-11-10 23:07:40 +000039
Stefan Andoniand1b33b32022-12-16 21:22:27 +000040/**
Brian Isganitis9cbc4782024-10-08 14:47:17 -040041 * Manages Launcher [SharedPreferences] through [Item] instances.
Jordan Demeulenaerebe82bc62023-03-01 09:11:48 +000042 *
Stefan Andoniand1b33b32022-12-16 21:22:27 +000043 * TODO(b/262721340): Replace all direct SharedPreference refs with LauncherPrefs / Item methods.
44 */
Sunny Goyale79d4532024-12-31 00:10:20 -080045@LauncherAppSingleton
46open class LauncherPrefs
47@Inject
48constructor(@ApplicationContext private val encryptedContext: Context) {
49
50 private val deviceProtectedSharedPrefs: SharedPreferences by lazy {
51 encryptedContext
52 .createDeviceProtectedStorageContext()
53 .getSharedPreferences(BOOT_AWARE_PREFS_KEY, MODE_PRIVATE)
54 }
55
56 open val Item.sharedPrefs: SharedPreferences
57 get() =
58 if (encryptionType == EncryptionType.DEVICE_PROTECTED) deviceProtectedSharedPrefs
59 else encryptedContext.getSharedPreferences(sharedPrefFile, MODE_PRIVATE)
Brian Isganitis9cbc4782024-10-08 14:47:17 -040060
61 /** Returns the value with type [T] for [item]. */
Sunny Goyale79d4532024-12-31 00:10:20 -080062 fun <T> get(item: ContextualItem<T>): T =
63 getInner(item, item.defaultValueFromContext(encryptedContext))
Brian Isganitis9cbc4782024-10-08 14:47:17 -040064
65 /** Returns the value with type [T] for [item]. */
Sunny Goyale79d4532024-12-31 00:10:20 -080066 fun <T> get(item: ConstantItem<T>): T = getInner(item, item.defaultValue)
Brian Isganitis9cbc4782024-10-08 14:47:17 -040067
Sunny Goyale79d4532024-12-31 00:10:20 -080068 /**
69 * Retrieves the value for an [Item] from [SharedPreferences]. It handles method typing via the
70 * default value type, and will throw an error if the type of the item provided is not a
71 * `String`, `Boolean`, `Float`, `Int`, `Long`, or `Set<String>`.
72 */
73 @Suppress("IMPLICIT_CAST_TO_ANY", "UNCHECKED_CAST")
74 private fun <T> getInner(item: Item, default: T): T {
75 val sp = item.sharedPrefs
Brian Isganitis9cbc4782024-10-08 14:47:17 -040076
Sunny Goyale79d4532024-12-31 00:10:20 -080077 return when (item.type) {
78 String::class.java -> sp.getString(item.sharedPrefKey, default as? String)
79 Boolean::class.java,
80 java.lang.Boolean::class.java -> sp.getBoolean(item.sharedPrefKey, default as Boolean)
81 Int::class.java,
82 java.lang.Integer::class.java -> sp.getInt(item.sharedPrefKey, default as Int)
83 Float::class.java,
84 java.lang.Float::class.java -> sp.getFloat(item.sharedPrefKey, default as Float)
85 Long::class.java,
86 java.lang.Long::class.java -> sp.getLong(item.sharedPrefKey, default as Long)
87 Set::class.java -> sp.getStringSet(item.sharedPrefKey, default as? Set<String>)
88 else ->
89 throw IllegalArgumentException(
90 "item type: ${item.type}" + " is not compatible with sharedPref methods"
91 )
92 }
93 as T
94 }
Brian Isganitis9cbc4782024-10-08 14:47:17 -040095
Sunny Goyale79d4532024-12-31 00:10:20 -080096 /**
97 * Stores each of the values provided in `SharedPreferences` according to the configuration
98 * contained within the associated items provided. Internally, it uses apply, so the caller
99 * cannot assume that the values that have been put are immediately available for use.
100 *
101 * The forEach loop is necessary here since there is 1 `SharedPreference.Editor` returned from
102 * prepareToPutValue(itemsToValues) for every distinct `SharedPreferences` file present in the
103 * provided item configurations.
104 */
105 fun put(vararg itemsToValues: Pair<Item, Any>): Unit =
106 prepareToPutValues(itemsToValues).forEach { it.apply() }
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400107
Sunny Goyale79d4532024-12-31 00:10:20 -0800108 /** See referenced `put` method above. */
109 fun <T : Any> put(item: Item, value: T): Unit = put(item.to(value))
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400110
Sunny Goyale79d4532024-12-31 00:10:20 -0800111 /**
112 * Synchronously stores all the values provided according to their associated Item
113 * configuration.
114 */
115 fun putSync(vararg itemsToValues: Pair<Item, Any>): Unit =
116 prepareToPutValues(itemsToValues).forEach { it.commit() }
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400117
Sunny Goyale79d4532024-12-31 00:10:20 -0800118 /**
119 * Updates the values stored in `SharedPreferences` for each corresponding Item-value pair. If
120 * the item is boot aware, this method updates both the boot aware and the encrypted files. This
121 * is done because: 1) It allows for easy roll-back if the data is already in encrypted prefs
122 * and we need to turn off the boot aware data feature & 2) It simplifies Backup/Restore, which
123 * already points to encrypted storage.
124 *
125 * Returns a list of editors with all transactions added so that the caller can determine to use
126 * .apply() or .commit()
127 */
128 private fun prepareToPutValues(
129 updates: Array<out Pair<Item, Any>>
130 ): List<SharedPreferences.Editor> {
131 val updatesPerPrefFile = updates.groupBy { it.first.sharedPrefs }.toMap()
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400132
Sunny Goyale79d4532024-12-31 00:10:20 -0800133 return updatesPerPrefFile.map { (sharedPref, itemList) ->
134 sharedPref.edit().apply { itemList.forEach { (item, value) -> putValue(item, value) } }
135 }
136 }
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400137
Sunny Goyale79d4532024-12-31 00:10:20 -0800138 /**
139 * Handles adding values to `SharedPreferences` regardless of type. This method is especially
140 * helpful for updating `SharedPreferences` values for `List<<Item>Any>` that have multiple
141 * types of Item values.
142 */
143 @Suppress("UNCHECKED_CAST")
144 private fun SharedPreferences.Editor.putValue(
145 item: Item,
146 value: Any?,
147 ): SharedPreferences.Editor =
148 when (item.type) {
149 String::class.java -> putString(item.sharedPrefKey, value as? String)
150 Boolean::class.java,
151 java.lang.Boolean::class.java -> putBoolean(item.sharedPrefKey, value as Boolean)
152 Int::class.java,
153 java.lang.Integer::class.java -> putInt(item.sharedPrefKey, value as Int)
154 Float::class.java,
155 java.lang.Float::class.java -> putFloat(item.sharedPrefKey, value as Float)
156 Long::class.java,
157 java.lang.Long::class.java -> putLong(item.sharedPrefKey, value as Long)
158 Set::class.java -> putStringSet(item.sharedPrefKey, value as? Set<String>)
159 else ->
160 throw IllegalArgumentException(
161 "item type: ${item.type} is not compatible with sharedPref methods"
162 )
163 }
164
165 /**
166 * After calling this method, the listener will be notified of any future updates to the
167 * `SharedPreferences` files associated with the provided list of items. The listener will need
168 * to filter update notifications so they don't activate for non-relevant updates.
169 */
170 fun addListener(listener: LauncherPrefChangeListener, vararg items: Item) {
171 items
172 .map { it.sharedPrefs }
173 .distinct()
174 .forEach { it.registerOnSharedPreferenceChangeListener(listener) }
175 }
176
177 /**
178 * Stops the listener from getting notified of any more updates to any of the
179 * `SharedPreferences` files associated with any of the provided list of [Item].
180 */
181 fun removeListener(listener: LauncherPrefChangeListener, vararg items: Item) {
182 // If a listener is not registered to a SharedPreference, unregistering it does nothing
183 items
184 .map { it.sharedPrefs }
185 .distinct()
186 .forEach { it.unregisterOnSharedPreferenceChangeListener(listener) }
187 }
188
189 /**
190 * Checks if all the provided [Item] have values stored in their corresponding
191 * `SharedPreferences` files.
192 */
193 fun has(vararg items: Item): Boolean {
194 items
195 .groupBy { it.sharedPrefs }
196 .forEach { (prefs, itemsSublist) ->
197 if (!itemsSublist.none { !prefs.contains(it.sharedPrefKey) }) return false
198 }
199 return true
200 }
201
202 /**
203 * Asynchronously removes the [Item]'s value from its corresponding `SharedPreferences` file.
204 */
205 fun remove(vararg items: Item) = prepareToRemove(items).forEach { it.apply() }
206
207 /** Synchronously removes the [Item]'s value from its corresponding `SharedPreferences` file. */
208 fun removeSync(vararg items: Item) = prepareToRemove(items).forEach { it.commit() }
209
210 /**
211 * Removes the key value pairs stored in `SharedPreferences` for each corresponding Item. If the
212 * item is boot aware, this method removes the data from both the boot aware and encrypted
213 * files.
214 *
215 * @return a list of editors with all transactions added so that the caller can determine to use
216 * .apply() or .commit()
217 */
218 private fun prepareToRemove(items: Array<out Item>): List<SharedPreferences.Editor> {
219 val itemsPerFile = items.groupBy { it.sharedPrefs }.toMap()
220
221 return itemsPerFile.map { (prefs, items) ->
222 prefs.edit().also { editor ->
223 items.forEach { item -> editor.remove(item.sharedPrefKey) }
224 }
225 }
226 }
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400227
228 companion object {
229 @VisibleForTesting const val BOOT_AWARE_PREFS_KEY = "boot_aware_prefs"
230
Sunny Goyale79d4532024-12-31 00:10:20 -0800231 @JvmField val INSTANCE = DaggerSingletonObject(LauncherAppComponent::getLauncherPrefs)
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400232
233 @JvmStatic fun get(context: Context): LauncherPrefs = INSTANCE.get(context)
234
235 const val TASKBAR_PINNING_KEY = "TASKBAR_PINNING_KEY"
236 const val TASKBAR_PINNING_DESKTOP_MODE_KEY = "TASKBAR_PINNING_DESKTOP_MODE_KEY"
237 const val SHOULD_SHOW_SMARTSPACE_KEY = "SHOULD_SHOW_SMARTSPACE_KEY"
238 @JvmField
239 val ICON_STATE = nonRestorableItem("pref_icon_shape_path", "", EncryptionType.ENCRYPTED)
240
241 @JvmField
242 val ENABLE_TWOLINE_ALLAPPS_TOGGLE = backedUpItem("pref_enable_two_line_toggle", false)
243 @JvmField
244 val THEMED_ICONS = backedUpItem(Themes.KEY_THEMED_ICONS, false, EncryptionType.ENCRYPTED)
245 @JvmField val PROMISE_ICON_IDS = backedUpItem(InstallSessionHelper.PROMISE_ICON_IDS, "")
246 @JvmField val WORK_EDU_STEP = backedUpItem("showed_work_profile_edu", 0)
247 @JvmField
248 val WORKSPACE_SIZE =
249 backedUpItem(DeviceGridState.KEY_WORKSPACE_SIZE, "", EncryptionType.ENCRYPTED)
250 @JvmField
251 val HOTSEAT_COUNT =
252 backedUpItem(DeviceGridState.KEY_HOTSEAT_COUNT, -1, EncryptionType.ENCRYPTED)
253 @JvmField
254 val TASKBAR_PINNING =
255 backedUpItem(TASKBAR_PINNING_KEY, false, EncryptionType.DEVICE_PROTECTED)
256 @JvmField
257 val TASKBAR_PINNING_IN_DESKTOP_MODE =
258 backedUpItem(TASKBAR_PINNING_DESKTOP_MODE_KEY, true, EncryptionType.DEVICE_PROTECTED)
259
260 @JvmField
261 val DEVICE_TYPE =
262 backedUpItem(
263 DeviceGridState.KEY_DEVICE_TYPE,
264 InvariantDeviceProfile.TYPE_PHONE,
265 EncryptionType.ENCRYPTED,
266 )
267 @JvmField
268 val DB_FILE = backedUpItem(DeviceGridState.KEY_DB_FILE, "", EncryptionType.ENCRYPTED)
269 @JvmField
270 val SHOULD_SHOW_SMARTSPACE =
271 backedUpItem(
272 SHOULD_SHOW_SMARTSPACE_KEY,
273 WIDGET_ON_FIRST_SCREEN,
274 EncryptionType.DEVICE_PROTECTED,
275 )
276 @JvmField
277 val RESTORE_DEVICE =
278 backedUpItem(
279 RestoreDbTask.RESTORED_DEVICE_TYPE,
280 InvariantDeviceProfile.TYPE_PHONE,
281 EncryptionType.ENCRYPTED,
282 )
283 @JvmField
Stefan Andonian8c0a7872024-10-21 14:26:27 -0700284 val NO_DB_FILES_RESTORED =
285 nonRestorableItem("no_db_files_restored", false, EncryptionType.DEVICE_PROTECTED)
286 @JvmField
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400287 val IS_FIRST_LOAD_AFTER_RESTORE =
288 nonRestorableItem(FIRST_LOAD_AFTER_RESTORE_KEY, false, EncryptionType.ENCRYPTED)
289 @JvmField val APP_WIDGET_IDS = backedUpItem(RestoreDbTask.APPWIDGET_IDS, "")
290 @JvmField val OLD_APP_WIDGET_IDS = backedUpItem(RestoreDbTask.APPWIDGET_OLD_IDS, "")
Sebastian Franco9e4c99b2024-10-02 15:16:37 -0700291
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400292 @JvmField
293 val GRID_NAME =
294 ConstantItem(
Charlie Andersonbad2be42024-12-06 16:32:03 -0500295 GRID_NAME_PREFS_KEY,
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400296 isBackedUp = true,
297 defaultValue = null,
298 encryptionType = EncryptionType.ENCRYPTED,
299 type = String::class.java,
300 )
301 @JvmField
302 val ALLOW_ROTATION =
303 backedUpItem(RotationHelper.ALLOW_ROTATION_PREFERENCE_KEY, Boolean::class.java) {
304 RotationHelper.getAllowRotationDefaultValue(DisplayController.INSTANCE.get(it).info)
305 }
306
Sebastian Franco9e4c99b2024-10-02 15:16:37 -0700307 @JvmField
308 val FIXED_LANDSCAPE_MODE = backedUpItem(SettingsActivity.FIXED_LANDSCAPE_MODE, false)
309
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400310 // Preferences for widget configurations
311 @JvmField
312 val RECONFIGURABLE_WIDGET_EDUCATION_TIP_SEEN =
313 backedUpItem("launcher.reconfigurable_widget_education_tip_seen", false)
314
315 @JvmStatic
316 fun <T> backedUpItem(
317 sharedPrefKey: String,
318 defaultValue: T,
319 encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
320 ): ConstantItem<T> =
321 ConstantItem(sharedPrefKey, isBackedUp = true, defaultValue, encryptionType)
322
323 @JvmStatic
324 fun <T> backedUpItem(
325 sharedPrefKey: String,
326 type: Class<out T>,
327 encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
328 defaultValueFromContext: (c: Context) -> T,
329 ): ContextualItem<T> =
330 ContextualItem(
331 sharedPrefKey,
332 isBackedUp = true,
333 defaultValueFromContext,
334 encryptionType,
335 type,
336 )
337
338 @JvmStatic
339 fun <T> nonRestorableItem(
340 sharedPrefKey: String,
341 defaultValue: T,
342 encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
343 ): ConstantItem<T> =
344 ConstantItem(sharedPrefKey, isBackedUp = false, defaultValue, encryptionType)
345
346 @Deprecated("Don't use shared preferences directly. Use other LauncherPref methods.")
347 @JvmStatic
348 fun getPrefs(context: Context): SharedPreferences {
349 // Use application context for shared preferences, so we use single cached instance
350 return context.applicationContext.getSharedPreferences(
351 SHARED_PREFERENCES_KEY,
352 MODE_PRIVATE,
353 )
354 }
355
356 @Deprecated("Don't use shared preferences directly. Use other LauncherPref methods.")
357 @JvmStatic
358 fun getDevicePrefs(context: Context): SharedPreferences {
359 // Use application context for shared preferences, so we use a single cached instance
360 return context.applicationContext.getSharedPreferences(
361 DEVICE_PREFERENCES_KEY,
362 MODE_PRIVATE,
363 )
364 }
365 }
366}
367
Stefan Andonian1d7f7032023-01-23 21:55:04 +0000368abstract class Item {
369 abstract val sharedPrefKey: String
Stefan Andonian4c9612b2023-02-22 00:00:03 +0000370 abstract val isBackedUp: Boolean
371 abstract val type: Class<*>
Stefan Andonian54495f32023-09-29 23:41:26 +0000372 abstract val encryptionType: EncryptionType
Stefan Andonian246eeaa2023-02-21 22:14:47 +0000373 val sharedPrefFile: String
374 get() = if (isBackedUp) SHARED_PREFERENCES_KEY else DEVICE_PREFERENCES_KEY
Stefan Andonian1d7f7032023-01-23 21:55:04 +0000375
376 fun <T> to(value: T): Pair<Item, T> = Pair(this, value)
377}
378
379data class ConstantItem<T>(
380 override val sharedPrefKey: String,
Stefan Andonian4c9612b2023-02-22 00:00:03 +0000381 override val isBackedUp: Boolean,
382 val defaultValue: T,
Stefan Andonian54495f32023-09-29 23:41:26 +0000383 override val encryptionType: EncryptionType,
Stefan Andonian4c9612b2023-02-22 00:00:03 +0000384 // The default value can be null. If so, the type needs to be explicitly stated, or else NPE
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400385 override val type: Class<out T> = defaultValue!!::class.java,
Stefan Andonian5bd9a222023-02-23 00:58:33 +0000386) : Item() {
Sunny Goyalcd447402023-10-06 13:47:50 -0700387
388 fun get(c: Context): T = LauncherPrefs.get(c).get(this)
Stefan Andonian5bd9a222023-02-23 00:58:33 +0000389}
Stefan Andonian1d7f7032023-01-23 21:55:04 +0000390
391data class ContextualItem<T>(
392 override val sharedPrefKey: String,
Stefan Andonian4c9612b2023-02-22 00:00:03 +0000393 override val isBackedUp: Boolean,
394 private val defaultSupplier: (c: Context) -> T,
Stefan Andonian54495f32023-09-29 23:41:26 +0000395 override val encryptionType: EncryptionType,
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400396 override val type: Class<out T>,
Stefan Andonian1d7f7032023-01-23 21:55:04 +0000397) : Item() {
398 private var default: T? = null
399
400 fun defaultValueFromContext(context: Context): T {
401 if (default == null) {
402 default = defaultSupplier(context)
403 }
404 return default!!
405 }
Sunny Goyalcd447402023-10-06 13:47:50 -0700406
407 fun get(c: Context): T = LauncherPrefs.get(c).get(this)
Thales Lima03ac3772023-01-06 15:16:41 +0000408}
Stefan Andonian54495f32023-09-29 23:41:26 +0000409
410enum class EncryptionType {
411 ENCRYPTED,
412 DEVICE_PROTECTED,
Stefan Andonian54495f32023-09-29 23:41:26 +0000413}