blob: 484cef4da55c60821f893ce1c5843793b28bf7a1 [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
Sunny Goyale79d4532024-12-31 00:10:20 -080037import javax.inject.Inject
Stefan Andonian146701c2022-11-10 23:07:40 +000038
Stefan Andoniand1b33b32022-12-16 21:22:27 +000039/**
Brian Isganitis9cbc4782024-10-08 14:47:17 -040040 * Manages Launcher [SharedPreferences] through [Item] instances.
Jordan Demeulenaerebe82bc62023-03-01 09:11:48 +000041 *
Stefan Andoniand1b33b32022-12-16 21:22:27 +000042 * TODO(b/262721340): Replace all direct SharedPreference refs with LauncherPrefs / Item methods.
43 */
Sunny Goyale79d4532024-12-31 00:10:20 -080044@LauncherAppSingleton
45open class LauncherPrefs
46@Inject
47constructor(@ApplicationContext private val encryptedContext: Context) {
48
49 private val deviceProtectedSharedPrefs: SharedPreferences by lazy {
50 encryptedContext
51 .createDeviceProtectedStorageContext()
52 .getSharedPreferences(BOOT_AWARE_PREFS_KEY, MODE_PRIVATE)
53 }
54
55 open val Item.sharedPrefs: SharedPreferences
56 get() =
57 if (encryptionType == EncryptionType.DEVICE_PROTECTED) deviceProtectedSharedPrefs
58 else encryptedContext.getSharedPreferences(sharedPrefFile, MODE_PRIVATE)
Brian Isganitis9cbc4782024-10-08 14:47:17 -040059
60 /** Returns the value with type [T] for [item]. */
Sunny Goyal4c261f72025-01-27 23:30:06 -080061 open fun <T> get(item: ContextualItem<T>): T =
Sunny Goyale79d4532024-12-31 00:10:20 -080062 getInner(item, item.defaultValueFromContext(encryptedContext))
Brian Isganitis9cbc4782024-10-08 14:47:17 -040063
64 /** Returns the value with type [T] for [item]. */
Sunny Goyal4c261f72025-01-27 23:30:06 -080065 open fun <T> get(item: ConstantItem<T>): T = getInner(item, item.defaultValue)
Brian Isganitis9cbc4782024-10-08 14:47:17 -040066
Sunny Goyale79d4532024-12-31 00:10:20 -080067 /**
68 * Retrieves the value for an [Item] from [SharedPreferences]. It handles method typing via the
69 * default value type, and will throw an error if the type of the item provided is not a
70 * `String`, `Boolean`, `Float`, `Int`, `Long`, or `Set<String>`.
71 */
72 @Suppress("IMPLICIT_CAST_TO_ANY", "UNCHECKED_CAST")
73 private fun <T> getInner(item: Item, default: T): T {
74 val sp = item.sharedPrefs
Brian Isganitis9cbc4782024-10-08 14:47:17 -040075
Sunny Goyale79d4532024-12-31 00:10:20 -080076 return when (item.type) {
77 String::class.java -> sp.getString(item.sharedPrefKey, default as? String)
78 Boolean::class.java,
79 java.lang.Boolean::class.java -> sp.getBoolean(item.sharedPrefKey, default as Boolean)
80 Int::class.java,
81 java.lang.Integer::class.java -> sp.getInt(item.sharedPrefKey, default as Int)
82 Float::class.java,
83 java.lang.Float::class.java -> sp.getFloat(item.sharedPrefKey, default as Float)
84 Long::class.java,
85 java.lang.Long::class.java -> sp.getLong(item.sharedPrefKey, default as Long)
86 Set::class.java -> sp.getStringSet(item.sharedPrefKey, default as? Set<String>)
87 else ->
88 throw IllegalArgumentException(
89 "item type: ${item.type}" + " is not compatible with sharedPref methods"
90 )
91 }
92 as T
93 }
Brian Isganitis9cbc4782024-10-08 14:47:17 -040094
Sunny Goyale79d4532024-12-31 00:10:20 -080095 /**
96 * Stores each of the values provided in `SharedPreferences` according to the configuration
97 * contained within the associated items provided. Internally, it uses apply, so the caller
98 * cannot assume that the values that have been put are immediately available for use.
99 *
100 * The forEach loop is necessary here since there is 1 `SharedPreference.Editor` returned from
101 * prepareToPutValue(itemsToValues) for every distinct `SharedPreferences` file present in the
102 * provided item configurations.
103 */
104 fun put(vararg itemsToValues: Pair<Item, Any>): Unit =
105 prepareToPutValues(itemsToValues).forEach { it.apply() }
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400106
Sunny Goyale79d4532024-12-31 00:10:20 -0800107 /** See referenced `put` method above. */
108 fun <T : Any> put(item: Item, value: T): Unit = put(item.to(value))
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400109
Sunny Goyale79d4532024-12-31 00:10:20 -0800110 /**
111 * Synchronously stores all the values provided according to their associated Item
112 * configuration.
113 */
114 fun putSync(vararg itemsToValues: Pair<Item, Any>): Unit =
115 prepareToPutValues(itemsToValues).forEach { it.commit() }
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400116
Sunny Goyale79d4532024-12-31 00:10:20 -0800117 /**
118 * Updates the values stored in `SharedPreferences` for each corresponding Item-value pair. If
119 * the item is boot aware, this method updates both the boot aware and the encrypted files. This
120 * is done because: 1) It allows for easy roll-back if the data is already in encrypted prefs
121 * and we need to turn off the boot aware data feature & 2) It simplifies Backup/Restore, which
122 * already points to encrypted storage.
123 *
124 * Returns a list of editors with all transactions added so that the caller can determine to use
125 * .apply() or .commit()
126 */
127 private fun prepareToPutValues(
128 updates: Array<out Pair<Item, Any>>
129 ): List<SharedPreferences.Editor> {
130 val updatesPerPrefFile = updates.groupBy { it.first.sharedPrefs }.toMap()
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400131
Sunny Goyale79d4532024-12-31 00:10:20 -0800132 return updatesPerPrefFile.map { (sharedPref, itemList) ->
133 sharedPref.edit().apply { itemList.forEach { (item, value) -> putValue(item, value) } }
134 }
135 }
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400136
Sunny Goyale79d4532024-12-31 00:10:20 -0800137 /**
138 * Handles adding values to `SharedPreferences` regardless of type. This method is especially
139 * helpful for updating `SharedPreferences` values for `List<<Item>Any>` that have multiple
140 * types of Item values.
141 */
142 @Suppress("UNCHECKED_CAST")
143 private fun SharedPreferences.Editor.putValue(
144 item: Item,
145 value: Any?,
146 ): SharedPreferences.Editor =
147 when (item.type) {
148 String::class.java -> putString(item.sharedPrefKey, value as? String)
149 Boolean::class.java,
150 java.lang.Boolean::class.java -> putBoolean(item.sharedPrefKey, value as Boolean)
151 Int::class.java,
152 java.lang.Integer::class.java -> putInt(item.sharedPrefKey, value as Int)
153 Float::class.java,
154 java.lang.Float::class.java -> putFloat(item.sharedPrefKey, value as Float)
155 Long::class.java,
156 java.lang.Long::class.java -> putLong(item.sharedPrefKey, value as Long)
157 Set::class.java -> putStringSet(item.sharedPrefKey, value as? Set<String>)
158 else ->
159 throw IllegalArgumentException(
160 "item type: ${item.type} is not compatible with sharedPref methods"
161 )
162 }
163
164 /**
165 * After calling this method, the listener will be notified of any future updates to the
166 * `SharedPreferences` files associated with the provided list of items. The listener will need
167 * to filter update notifications so they don't activate for non-relevant updates.
168 */
169 fun addListener(listener: LauncherPrefChangeListener, vararg items: Item) {
170 items
171 .map { it.sharedPrefs }
172 .distinct()
173 .forEach { it.registerOnSharedPreferenceChangeListener(listener) }
174 }
175
176 /**
177 * Stops the listener from getting notified of any more updates to any of the
178 * `SharedPreferences` files associated with any of the provided list of [Item].
179 */
180 fun removeListener(listener: LauncherPrefChangeListener, vararg items: Item) {
181 // If a listener is not registered to a SharedPreference, unregistering it does nothing
182 items
183 .map { it.sharedPrefs }
184 .distinct()
185 .forEach { it.unregisterOnSharedPreferenceChangeListener(listener) }
186 }
187
188 /**
189 * Checks if all the provided [Item] have values stored in their corresponding
190 * `SharedPreferences` files.
191 */
192 fun has(vararg items: Item): Boolean {
193 items
194 .groupBy { it.sharedPrefs }
195 .forEach { (prefs, itemsSublist) ->
196 if (!itemsSublist.none { !prefs.contains(it.sharedPrefKey) }) return false
197 }
198 return true
199 }
200
201 /**
202 * Asynchronously removes the [Item]'s value from its corresponding `SharedPreferences` file.
203 */
204 fun remove(vararg items: Item) = prepareToRemove(items).forEach { it.apply() }
205
206 /** Synchronously removes the [Item]'s value from its corresponding `SharedPreferences` file. */
207 fun removeSync(vararg items: Item) = prepareToRemove(items).forEach { it.commit() }
208
209 /**
210 * Removes the key value pairs stored in `SharedPreferences` for each corresponding Item. If the
211 * item is boot aware, this method removes the data from both the boot aware and encrypted
212 * files.
213 *
214 * @return a list of editors with all transactions added so that the caller can determine to use
215 * .apply() or .commit()
216 */
217 private fun prepareToRemove(items: Array<out Item>): List<SharedPreferences.Editor> {
218 val itemsPerFile = items.groupBy { it.sharedPrefs }.toMap()
219
220 return itemsPerFile.map { (prefs, items) ->
221 prefs.edit().also { editor ->
222 items.forEach { item -> editor.remove(item.sharedPrefKey) }
223 }
224 }
225 }
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400226
227 companion object {
228 @VisibleForTesting const val BOOT_AWARE_PREFS_KEY = "boot_aware_prefs"
229
Sunny Goyale79d4532024-12-31 00:10:20 -0800230 @JvmField val INSTANCE = DaggerSingletonObject(LauncherAppComponent::getLauncherPrefs)
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400231
232 @JvmStatic fun get(context: Context): LauncherPrefs = INSTANCE.get(context)
233
234 const val TASKBAR_PINNING_KEY = "TASKBAR_PINNING_KEY"
235 const val TASKBAR_PINNING_DESKTOP_MODE_KEY = "TASKBAR_PINNING_DESKTOP_MODE_KEY"
236 const val SHOULD_SHOW_SMARTSPACE_KEY = "SHOULD_SHOW_SMARTSPACE_KEY"
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400237
238 @JvmField
239 val ENABLE_TWOLINE_ALLAPPS_TOGGLE = backedUpItem("pref_enable_two_line_toggle", false)
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400240 @JvmField val PROMISE_ICON_IDS = backedUpItem(InstallSessionHelper.PROMISE_ICON_IDS, "")
241 @JvmField val WORK_EDU_STEP = backedUpItem("showed_work_profile_edu", 0)
242 @JvmField
243 val WORKSPACE_SIZE =
244 backedUpItem(DeviceGridState.KEY_WORKSPACE_SIZE, "", EncryptionType.ENCRYPTED)
245 @JvmField
246 val HOTSEAT_COUNT =
247 backedUpItem(DeviceGridState.KEY_HOTSEAT_COUNT, -1, EncryptionType.ENCRYPTED)
248 @JvmField
249 val TASKBAR_PINNING =
250 backedUpItem(TASKBAR_PINNING_KEY, false, EncryptionType.DEVICE_PROTECTED)
251 @JvmField
252 val TASKBAR_PINNING_IN_DESKTOP_MODE =
253 backedUpItem(TASKBAR_PINNING_DESKTOP_MODE_KEY, true, EncryptionType.DEVICE_PROTECTED)
254
255 @JvmField
256 val DEVICE_TYPE =
257 backedUpItem(
258 DeviceGridState.KEY_DEVICE_TYPE,
259 InvariantDeviceProfile.TYPE_PHONE,
260 EncryptionType.ENCRYPTED,
261 )
262 @JvmField
263 val DB_FILE = backedUpItem(DeviceGridState.KEY_DB_FILE, "", EncryptionType.ENCRYPTED)
264 @JvmField
265 val SHOULD_SHOW_SMARTSPACE =
266 backedUpItem(
267 SHOULD_SHOW_SMARTSPACE_KEY,
268 WIDGET_ON_FIRST_SCREEN,
269 EncryptionType.DEVICE_PROTECTED,
270 )
271 @JvmField
272 val RESTORE_DEVICE =
273 backedUpItem(
274 RestoreDbTask.RESTORED_DEVICE_TYPE,
275 InvariantDeviceProfile.TYPE_PHONE,
276 EncryptionType.ENCRYPTED,
277 )
278 @JvmField
Stefan Andonian8c0a7872024-10-21 14:26:27 -0700279 val NO_DB_FILES_RESTORED =
280 nonRestorableItem("no_db_files_restored", false, EncryptionType.DEVICE_PROTECTED)
281 @JvmField
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400282 val IS_FIRST_LOAD_AFTER_RESTORE =
283 nonRestorableItem(FIRST_LOAD_AFTER_RESTORE_KEY, false, EncryptionType.ENCRYPTED)
284 @JvmField val APP_WIDGET_IDS = backedUpItem(RestoreDbTask.APPWIDGET_IDS, "")
285 @JvmField val OLD_APP_WIDGET_IDS = backedUpItem(RestoreDbTask.APPWIDGET_OLD_IDS, "")
Sebastian Franco9e4c99b2024-10-02 15:16:37 -0700286
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400287 @JvmField
288 val GRID_NAME =
289 ConstantItem(
Charlie Andersonbad2be42024-12-06 16:32:03 -0500290 GRID_NAME_PREFS_KEY,
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400291 isBackedUp = true,
292 defaultValue = null,
293 encryptionType = EncryptionType.ENCRYPTED,
294 type = String::class.java,
295 )
296 @JvmField
297 val ALLOW_ROTATION =
298 backedUpItem(RotationHelper.ALLOW_ROTATION_PREFERENCE_KEY, Boolean::class.java) {
299 RotationHelper.getAllowRotationDefaultValue(DisplayController.INSTANCE.get(it).info)
300 }
301
Sebastian Franco9e4c99b2024-10-02 15:16:37 -0700302 @JvmField
303 val FIXED_LANDSCAPE_MODE = backedUpItem(SettingsActivity.FIXED_LANDSCAPE_MODE, false)
304
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400305 // Preferences for widget configurations
306 @JvmField
307 val RECONFIGURABLE_WIDGET_EDUCATION_TIP_SEEN =
308 backedUpItem("launcher.reconfigurable_widget_education_tip_seen", false)
309
310 @JvmStatic
311 fun <T> backedUpItem(
312 sharedPrefKey: String,
313 defaultValue: T,
314 encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
315 ): ConstantItem<T> =
316 ConstantItem(sharedPrefKey, isBackedUp = true, defaultValue, encryptionType)
317
318 @JvmStatic
319 fun <T> backedUpItem(
320 sharedPrefKey: String,
321 type: Class<out T>,
322 encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
323 defaultValueFromContext: (c: Context) -> T,
324 ): ContextualItem<T> =
325 ContextualItem(
326 sharedPrefKey,
327 isBackedUp = true,
328 defaultValueFromContext,
329 encryptionType,
330 type,
331 )
332
333 @JvmStatic
334 fun <T> nonRestorableItem(
335 sharedPrefKey: String,
336 defaultValue: T,
337 encryptionType: EncryptionType = EncryptionType.ENCRYPTED,
338 ): ConstantItem<T> =
339 ConstantItem(sharedPrefKey, isBackedUp = false, defaultValue, encryptionType)
340
341 @Deprecated("Don't use shared preferences directly. Use other LauncherPref methods.")
342 @JvmStatic
343 fun getPrefs(context: Context): SharedPreferences {
344 // Use application context for shared preferences, so we use single cached instance
345 return context.applicationContext.getSharedPreferences(
346 SHARED_PREFERENCES_KEY,
347 MODE_PRIVATE,
348 )
349 }
350
351 @Deprecated("Don't use shared preferences directly. Use other LauncherPref methods.")
352 @JvmStatic
353 fun getDevicePrefs(context: Context): SharedPreferences {
354 // Use application context for shared preferences, so we use a single cached instance
355 return context.applicationContext.getSharedPreferences(
356 DEVICE_PREFERENCES_KEY,
357 MODE_PRIVATE,
358 )
359 }
360 }
361}
362
Stefan Andonian1d7f7032023-01-23 21:55:04 +0000363abstract class Item {
364 abstract val sharedPrefKey: String
Stefan Andonian4c9612b2023-02-22 00:00:03 +0000365 abstract val isBackedUp: Boolean
366 abstract val type: Class<*>
Stefan Andonian54495f32023-09-29 23:41:26 +0000367 abstract val encryptionType: EncryptionType
Stefan Andonian246eeaa2023-02-21 22:14:47 +0000368 val sharedPrefFile: String
369 get() = if (isBackedUp) SHARED_PREFERENCES_KEY else DEVICE_PREFERENCES_KEY
Stefan Andonian1d7f7032023-01-23 21:55:04 +0000370
371 fun <T> to(value: T): Pair<Item, T> = Pair(this, value)
372}
373
374data class ConstantItem<T>(
375 override val sharedPrefKey: String,
Stefan Andonian4c9612b2023-02-22 00:00:03 +0000376 override val isBackedUp: Boolean,
377 val defaultValue: T,
Stefan Andonian54495f32023-09-29 23:41:26 +0000378 override val encryptionType: EncryptionType,
Stefan Andonian4c9612b2023-02-22 00:00:03 +0000379 // 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 -0400380 override val type: Class<out T> = defaultValue!!::class.java,
Stefan Andonian5bd9a222023-02-23 00:58:33 +0000381) : Item() {
Sunny Goyalcd447402023-10-06 13:47:50 -0700382
383 fun get(c: Context): T = LauncherPrefs.get(c).get(this)
Stefan Andonian5bd9a222023-02-23 00:58:33 +0000384}
Stefan Andonian1d7f7032023-01-23 21:55:04 +0000385
386data class ContextualItem<T>(
387 override val sharedPrefKey: String,
Stefan Andonian4c9612b2023-02-22 00:00:03 +0000388 override val isBackedUp: Boolean,
389 private val defaultSupplier: (c: Context) -> T,
Stefan Andonian54495f32023-09-29 23:41:26 +0000390 override val encryptionType: EncryptionType,
Brian Isganitis9cbc4782024-10-08 14:47:17 -0400391 override val type: Class<out T>,
Stefan Andonian1d7f7032023-01-23 21:55:04 +0000392) : Item() {
393 private var default: T? = null
394
395 fun defaultValueFromContext(context: Context): T {
396 if (default == null) {
397 default = defaultSupplier(context)
398 }
399 return default!!
400 }
Sunny Goyalcd447402023-10-06 13:47:50 -0700401
402 fun get(c: Context): T = LauncherPrefs.get(c).get(this)
Thales Lima03ac3772023-01-06 15:16:41 +0000403}
Stefan Andonian54495f32023-09-29 23:41:26 +0000404
405enum class EncryptionType {
406 ENCRYPTED,
407 DEVICE_PROTECTED,
Stefan Andonian54495f32023-09-29 23:41:26 +0000408}
Sunny Goyal4c261f72025-01-27 23:30:06 -0800409
410/**
411 * LauncherPrefs which delegates all lookup to [prefs] but uses the real prefs for initial values
412 */
413class ProxyPrefs(context: Context, private val prefs: SharedPreferences) : LauncherPrefs(context) {
414
415 private val realPrefs = LauncherPrefs(context)
416
417 override val Item.sharedPrefs: SharedPreferences
418 get() = prefs
419
420 override fun <T> get(item: ConstantItem<T>) =
421 super.get(backedUpItem(item.sharedPrefKey, realPrefs.get(item)))
422
423 override fun <T> get(item: ContextualItem<T>) =
424 super.get(backedUpItem(item.sharedPrefKey, realPrefs.get(item)))
425}