1
0
Fork 0

Adds setters and property delegates in `Settings` (#4809)

* Change Settings to use setters

* Add delegate for shared preferences
master
Tiger Oakes 2019-08-20 13:47:55 -04:00 committed by Sawyer Blatz
parent ac6c1ec2ee
commit 33f3b14c29
18 changed files with 379 additions and 244 deletions

View File

@ -38,7 +38,7 @@ class DefaultBrowsingModeManager(
override var mode: BrowsingMode override var mode: BrowsingMode
get() = BrowsingMode.fromBoolean(settings.usePrivateMode) get() = BrowsingMode.fromBoolean(settings.usePrivateMode)
set(value) { set(value) {
settings.setPrivateMode(value.isPrivate) settings.usePrivateMode = value.isPrivate
modeDidChange(value) modeDidChange(value)
} }
} }

View File

@ -29,9 +29,9 @@ import mozilla.components.support.ktx.android.content.isMainProcess
import mozilla.components.support.ktx.android.content.runOnlyInMainProcess import mozilla.components.support.ktx.android.content.runOnlyInMainProcess
import mozilla.components.support.rusthttp.RustHttpConfig import mozilla.components.support.rusthttp.RustHttpConfig
import mozilla.components.support.rustlog.RustLog import mozilla.components.support.rustlog.RustLog
import org.mozilla.fenix.GleanMetrics.ExperimentsMetrics
import org.mozilla.fenix.components.Components import org.mozilla.fenix.components.Components
import org.mozilla.fenix.utils.Settings import org.mozilla.fenix.utils.Settings
import org.mozilla.fenix.GleanMetrics.ExperimentsMetrics
import java.io.File import java.io.File
@SuppressLint("Registered") @SuppressLint("Registered")
@ -241,12 +241,12 @@ open class FenixApplication : Application() {
AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
) )
settings.setFollowDeviceTheme(true) settings.shouldFollowDeviceTheme = true
} else { } else {
AppCompatDelegate.setDefaultNightMode( AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_NO AppCompatDelegate.MODE_NIGHT_NO
) )
settings.setLightTheme(true) settings.shouldUseLightTheme = true
} }
} }
} }

View File

@ -21,15 +21,15 @@ import mozilla.components.concept.sync.DeviceEvent
import mozilla.components.concept.sync.DeviceEventsObserver import mozilla.components.concept.sync.DeviceEventsObserver
import mozilla.components.concept.sync.DevicePushSubscription import mozilla.components.concept.sync.DevicePushSubscription
import mozilla.components.concept.sync.DeviceType import mozilla.components.concept.sync.DeviceType
import mozilla.components.service.fxa.DeviceConfig
import mozilla.components.service.fxa.ServerConfig
import mozilla.components.service.fxa.SyncConfig
import mozilla.components.concept.sync.OAuthAccount import mozilla.components.concept.sync.OAuthAccount
import mozilla.components.feature.push.AutoPushFeature import mozilla.components.feature.push.AutoPushFeature
import mozilla.components.feature.push.AutoPushSubscription import mozilla.components.feature.push.AutoPushSubscription
import mozilla.components.feature.push.PushConfig import mozilla.components.feature.push.PushConfig
import mozilla.components.feature.push.PushSubscriptionObserver import mozilla.components.feature.push.PushSubscriptionObserver
import mozilla.components.feature.push.PushType import mozilla.components.feature.push.PushType
import mozilla.components.service.fxa.DeviceConfig
import mozilla.components.service.fxa.ServerConfig
import mozilla.components.service.fxa.SyncConfig
import mozilla.components.service.fxa.manager.FxaAccountManager import mozilla.components.service.fxa.manager.FxaAccountManager
import mozilla.components.service.fxa.sync.GlobalSyncableStoreProvider import mozilla.components.service.fxa.sync.GlobalSyncableStoreProvider
import mozilla.components.support.base.log.logger.Logger import mozilla.components.support.base.log.logger.Logger
@ -143,7 +143,7 @@ class BackgroundServices(
context.components.analytics.metrics.track(Event.SyncAuthSignOut) context.components.analytics.metrics.track(Event.SyncAuthSignOut)
Settings.instance?.setFxaSignedIn(false) Settings.instance?.fxaSignedIn = false
} }
override fun onAuthenticated(account: OAuthAccount, newAccount: Boolean) { override fun onAuthenticated(account: OAuthAccount, newAccount: Boolean) {
@ -156,7 +156,7 @@ class BackgroundServices(
context.components.analytics.metrics.track(Event.SyncAuthSignIn) context.components.analytics.metrics.track(Event.SyncAuthSignIn)
Settings.instance?.setFxaSignedIn(true) Settings.instance?.fxaSignedIn = true
} }
} }
@ -178,7 +178,7 @@ class BackgroundServices(
// See https://github.com/mozilla-mobile/android-components/issues/3732 // See https://github.com/mozilla-mobile/android-components/issues/3732
setOf("https://identity.mozilla.com/apps/oldsync") setOf("https://identity.mozilla.com/apps/oldsync")
).also { ).also {
Settings.instance?.setFxaHasSyncedItems(syncConfig?.syncableStores?.isNotEmpty() ?: false) Settings.instance?.fxaHasSyncedItems = syncConfig?.syncableStores?.isNotEmpty() ?: false
if (FeatureFlags.sendTabEnabled) { if (FeatureFlags.sendTabEnabled) {
it.registerForDeviceEvents(deviceEventObserver, ProcessLifecycleOwner.get(), false) it.registerForDeviceEvents(deviceEventObserver, ProcessLifecycleOwner.get(), false)

View File

@ -31,7 +31,7 @@ class OnboardingTrackingProtectionViewHolder(view: View) : RecyclerView.ViewHold
} }
private fun updateTrackingProtectionSetting(enabled: Boolean) { private fun updateTrackingProtectionSetting(enabled: Boolean) {
Settings.getInstance(itemView.context).setTrackingProtection(enabled) Settings.getInstance(itemView.context).shouldUseTrackingProtection = enabled
with(itemView.context.components) { with(itemView.context.components) {
val policy = core.createTrackingProtectionPolicy(enabled) val policy = core.createTrackingProtectionPolicy(enabled)
useCases.settingsUseCases.updateTrackingProtection.invoke(policy) useCases.settingsUseCases.updateTrackingProtection.invoke(policy)

View File

@ -25,7 +25,7 @@ class AccessibilityFragment : PreferenceFragmentCompat() {
(newValue as? Int).let { (newValue as? Int).let {
// Value is mapped from 0->30 in steps of 1 so let's convert to float in range 0.5->2.0 // Value is mapped from 0->30 in steps of 1 so let's convert to float in range 0.5->2.0
val newTextScale = ((newValue as Int * STEP_SIZE) + MIN_SCALE_VALUE).toFloat() / PERCENT_TO_DECIMAL val newTextScale = ((newValue as Int * STEP_SIZE) + MIN_SCALE_VALUE).toFloat() / PERCENT_TO_DECIMAL
Settings.getInstance(context!!).setFontSizeFactor(newTextScale) Settings.getInstance(context!!).fontSizeFactor = newTextScale
requireComponents.core.engine.settings.fontSizeFactor = newTextScale requireComponents.core.engine.settings.fontSizeFactor = newTextScale
requireComponents.useCases.sessionUseCases.reload.invoke() requireComponents.useCases.sessionUseCases.reload.invoke()
} }
@ -37,7 +37,7 @@ class AccessibilityFragment : PreferenceFragmentCompat() {
val useAutoSizePreference = val useAutoSizePreference =
findPreference<SwitchPreference>(getString(R.string.pref_key_accessibility_auto_size)) findPreference<SwitchPreference>(getString(R.string.pref_key_accessibility_auto_size))
useAutoSizePreference?.setOnPreferenceChangeListener { _, newValue -> useAutoSizePreference?.setOnPreferenceChangeListener { _, newValue ->
Settings.getInstance(context!!).setAutoSize(newValue as Boolean) Settings.getInstance(context!!).shouldUseAutoSize = newValue as Boolean
requireComponents.core.engine.settings.automaticFontSizeAdjustment = newValue requireComponents.core.engine.settings.automaticFontSizeAdjustment = newValue
if (!newValue) { if (!newValue) {
requireComponents.core.engine.settings.fontSizeFactor = Settings.getInstance(context!!).fontSizeFactor requireComponents.core.engine.settings.fontSizeFactor = Settings.getInstance(context!!).fontSizeFactor

View File

@ -35,22 +35,22 @@ enum class PhoneFeature(val id: Int, val androidPermissionsList: Array<String>)
val label = when (this) { val label = when (this) {
CAMERA -> { CAMERA -> {
sitePermissions?.camera?.toString(context) ?: settings sitePermissions?.camera?.toString(context) ?: settings
?.getSitePermissionsPhoneFeatureCameraAction() ?.sitePermissionsPhoneFeatureCameraAction
?.toString(context) ?.toString(context)
} }
LOCATION -> { LOCATION -> {
sitePermissions?.location?.toString(context) ?: settings sitePermissions?.location?.toString(context) ?: settings
?.getSitePermissionsPhoneFeatureLocation() ?.sitePermissionsPhoneFeatureLocation
?.toString(context) ?.toString(context)
} }
MICROPHONE -> { MICROPHONE -> {
sitePermissions?.microphone?.toString(context) ?: settings sitePermissions?.microphone?.toString(context) ?: settings
?.getSitePermissionsPhoneFeatureMicrophoneAction() ?.sitePermissionsPhoneFeatureMicrophoneAction
?.toString(context) ?.toString(context)
} }
NOTIFICATION -> { NOTIFICATION -> {
sitePermissions?.notification?.toString(context) ?: settings sitePermissions?.notification?.toString(context) ?: settings
?.getSitePermissionsPhoneFeatureNotificationAction() ?.sitePermissionsPhoneFeatureNotificationAction
?.toString(context) ?.toString(context)
} }
} }
@ -61,22 +61,22 @@ enum class PhoneFeature(val id: Int, val androidPermissionsList: Array<String>)
val status = when (this) { val status = when (this) {
CAMERA -> { CAMERA -> {
sitePermissions?.camera ?: settings sitePermissions?.camera ?: settings
?.getSitePermissionsPhoneFeatureCameraAction() ?.sitePermissionsPhoneFeatureCameraAction
?.toStatus() ?.toStatus()
} }
LOCATION -> { LOCATION -> {
sitePermissions?.location ?: settings sitePermissions?.location ?: settings
?.getSitePermissionsPhoneFeatureLocation() ?.sitePermissionsPhoneFeatureLocation
?.toStatus() ?.toStatus()
} }
MICROPHONE -> { MICROPHONE -> {
sitePermissions?.microphone ?: settings sitePermissions?.microphone ?: settings
?.getSitePermissionsPhoneFeatureMicrophoneAction() ?.sitePermissionsPhoneFeatureMicrophoneAction
?.toStatus() ?.toStatus()
} }
NOTIFICATION -> { NOTIFICATION -> {
sitePermissions?.notification ?: settings sitePermissions?.notification ?: settings
?.getSitePermissionsPhoneFeatureNotificationAction() ?.sitePermissionsPhoneFeatureNotificationAction
?.toStatus() ?.toStatus()
} }
} }

View File

@ -26,6 +26,6 @@ class RadioSearchEngineListPreference @JvmOverloads constructor(
override fun onSearchEngineSelected(searchEngine: SearchEngine) { override fun onSearchEngineSelected(searchEngine: SearchEngine) {
context.components.search.searchEngineManager.defaultSearchEngine = searchEngine context.components.search.searchEngineManager.defaultSearchEngine = searchEngine
Settings.getInstance(context).setDefaultSearchEngineByName(searchEngine.name) Settings.getInstance(context).defaultSearchEngineName = searchEngine.name
} }
} }

View File

@ -11,10 +11,10 @@ import androidx.preference.Preference
import androidx.preference.Preference.OnPreferenceClickListener import androidx.preference.Preference.OnPreferenceClickListener
import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceFragmentCompat
import org.mozilla.fenix.R import org.mozilla.fenix.R
import org.mozilla.fenix.settings.PhoneFeature.NOTIFICATION
import org.mozilla.fenix.settings.PhoneFeature.LOCATION
import org.mozilla.fenix.settings.PhoneFeature.CAMERA import org.mozilla.fenix.settings.PhoneFeature.CAMERA
import org.mozilla.fenix.settings.PhoneFeature.LOCATION
import org.mozilla.fenix.settings.PhoneFeature.MICROPHONE import org.mozilla.fenix.settings.PhoneFeature.MICROPHONE
import org.mozilla.fenix.settings.PhoneFeature.NOTIFICATION
import org.mozilla.fenix.utils.Settings import org.mozilla.fenix.utils.Settings
@SuppressWarnings("TooManyFunctions") @SuppressWarnings("TooManyFunctions")
@ -56,19 +56,19 @@ class SitePermissionsFragment : PreferenceFragmentCompat() {
val settings = Settings.getInstance(requireContext()) val settings = Settings.getInstance(requireContext())
val cameraAction = settings val cameraAction = settings
.getSitePermissionsPhoneFeatureCameraAction() .sitePermissionsPhoneFeatureCameraAction
.toString(requireContext()) .toString(requireContext())
val locationAction = settings val locationAction = settings
.getSitePermissionsPhoneFeatureLocation() .sitePermissionsPhoneFeatureLocation
.toString(requireContext()) .toString(requireContext())
val microPhoneAction = settings val microPhoneAction = settings
.getSitePermissionsPhoneFeatureMicrophoneAction() .sitePermissionsPhoneFeatureMicrophoneAction
.toString(requireContext()) .toString(requireContext())
val notificationAction = settings val notificationAction = settings
.getSitePermissionsPhoneFeatureNotificationAction() .sitePermissionsPhoneFeatureNotificationAction
.toString(requireContext()) .toString(requireContext())
initPhoneFeature(CAMERA, cameraAction) initPhoneFeature(CAMERA, cameraAction)

View File

@ -122,10 +122,10 @@ class SitePermissionsManagePhoneFeatureFragment : Fragment() {
private val PhoneFeature.action: SitePermissionsRules.Action private val PhoneFeature.action: SitePermissionsRules.Action
get() { get() {
return when (phoneFeature) { return when (phoneFeature) {
PhoneFeature.CAMERA -> settings.getSitePermissionsPhoneFeatureCameraAction() PhoneFeature.CAMERA -> settings.sitePermissionsPhoneFeatureCameraAction
PhoneFeature.LOCATION -> settings.getSitePermissionsPhoneFeatureLocation() PhoneFeature.LOCATION -> settings.sitePermissionsPhoneFeatureLocation
PhoneFeature.MICROPHONE -> settings.getSitePermissionsPhoneFeatureMicrophoneAction() PhoneFeature.MICROPHONE -> settings.sitePermissionsPhoneFeatureMicrophoneAction
PhoneFeature.NOTIFICATION -> settings.getSitePermissionsPhoneFeatureNotificationAction() PhoneFeature.NOTIFICATION -> settings.sitePermissionsPhoneFeatureNotificationAction
} }
} }
@ -145,10 +145,10 @@ class SitePermissionsManagePhoneFeatureFragment : Fragment() {
private fun saveActionInSettings(action: SitePermissionsRules.Action) { private fun saveActionInSettings(action: SitePermissionsRules.Action) {
when (phoneFeature) { when (phoneFeature) {
PhoneFeature.CAMERA -> settings.setSitePermissionsPhoneFeatureCameraAction(action) PhoneFeature.CAMERA -> settings.sitePermissionsPhoneFeatureCameraAction = action
PhoneFeature.LOCATION -> settings.setSitePermissionsPhoneFeatureLocation(action) PhoneFeature.LOCATION -> settings.sitePermissionsPhoneFeatureLocation = action
PhoneFeature.MICROPHONE -> settings.setSitePermissionsPhoneFeatureMicrophoneAction(action) PhoneFeature.MICROPHONE -> settings.sitePermissionsPhoneFeatureMicrophoneAction = action
PhoneFeature.NOTIFICATION -> settings.setSitePermissionsPhoneFeatureNotificationAction(action) PhoneFeature.NOTIFICATION -> settings.sitePermissionsPhoneFeatureNotificationAction = action
} }
} }
} }

View File

@ -33,8 +33,7 @@ class TrackingProtectionFragment : PreferenceFragmentCompat() {
preferenceTP?.isChecked = Settings.getInstance(context!!).shouldUseTrackingProtection preferenceTP?.isChecked = Settings.getInstance(context!!).shouldUseTrackingProtection
preferenceTP?.onPreferenceChangeListener = preferenceTP?.onPreferenceChangeListener =
Preference.OnPreferenceChangeListener { _, newValue -> Preference.OnPreferenceChangeListener { _, newValue ->
Settings.getInstance(requireContext()) Settings.getInstance(requireContext()).shouldUseTrackingProtection = newValue as Boolean
.setTrackingProtection(newValue = newValue as Boolean)
with(requireComponents) { with(requireComponents) {
val policy = core.createTrackingProtectionPolicy(newValue) val policy = core.createTrackingProtectionPolicy(newValue)
useCases.settingsUseCases.updateTrackingProtection.invoke(policy) useCases.settingsUseCases.updateTrackingProtection.invoke(policy)

View File

@ -9,14 +9,14 @@ import android.view.ViewGroup
import androidx.core.net.toUri import androidx.core.net.toUri
import mozilla.components.feature.sitepermissions.SitePermissions import mozilla.components.feature.sitepermissions.SitePermissions
import org.mozilla.fenix.ext.components import org.mozilla.fenix.ext.components
import org.mozilla.fenix.mvi.ViewState
import org.mozilla.fenix.mvi.Change
import org.mozilla.fenix.mvi.Action import org.mozilla.fenix.mvi.Action
import org.mozilla.fenix.mvi.ActionBusFactory import org.mozilla.fenix.mvi.ActionBusFactory
import org.mozilla.fenix.mvi.Change
import org.mozilla.fenix.mvi.UIComponent import org.mozilla.fenix.mvi.UIComponent
import org.mozilla.fenix.mvi.UIComponentViewModelBase import org.mozilla.fenix.mvi.UIComponentViewModelBase
import org.mozilla.fenix.mvi.UIComponentViewModelProvider import org.mozilla.fenix.mvi.UIComponentViewModelProvider
import org.mozilla.fenix.mvi.UIView import org.mozilla.fenix.mvi.UIView
import org.mozilla.fenix.mvi.ViewState
import org.mozilla.fenix.settings.PhoneFeature import org.mozilla.fenix.settings.PhoneFeature
import org.mozilla.fenix.settings.toggle import org.mozilla.fenix.settings.toggle
import org.mozilla.fenix.utils.Settings import org.mozilla.fenix.utils.Settings
@ -48,10 +48,10 @@ class QuickSettingsComponent(
return if (sitePermissions == null) { return if (sitePermissions == null) {
val settings = Settings.getInstance(context) val settings = Settings.getInstance(context)
val origin = requireNotNull(url.toUri().host) val origin = requireNotNull(url.toUri().host)
var location = settings.getSitePermissionsPhoneFeatureLocation().toStatus() var location = settings.sitePermissionsPhoneFeatureLocation.toStatus()
var camera = settings.getSitePermissionsPhoneFeatureCameraAction().toStatus() var camera = settings.sitePermissionsPhoneFeatureCameraAction.toStatus()
var microphone = settings.getSitePermissionsPhoneFeatureMicrophoneAction().toStatus() var microphone = settings.sitePermissionsPhoneFeatureMicrophoneAction.toStatus()
var notification = settings.getSitePermissionsPhoneFeatureNotificationAction().toStatus() var notification = settings.sitePermissionsPhoneFeatureNotificationAction.toStatus()
when (featurePhone) { when (featurePhone) {
PhoneFeature.CAMERA -> camera = camera.toggle() PhoneFeature.CAMERA -> camera = camera.toggle()

View File

@ -0,0 +1,27 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.fenix.settings.sharedpreferences
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private class BooleanPreference(
private val key: String,
private val default: Boolean
) : ReadWriteProperty<PreferencesHolder, Boolean> {
override fun getValue(thisRef: PreferencesHolder, property: KProperty<*>): Boolean =
thisRef.preferences.getBoolean(key, default)
override fun setValue(thisRef: PreferencesHolder, property: KProperty<*>, value: Boolean) {
thisRef.preferences.edit().putBoolean(key, value).apply()
}
}
/**
* Property delegate for getting and setting a boolean shared preference.
*/
fun booleanPreference(key: String, default: Boolean): ReadWriteProperty<PreferencesHolder, Boolean> =
BooleanPreference(key, default)

View File

@ -0,0 +1,11 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.fenix.settings.sharedpreferences
import android.content.SharedPreferences
interface PreferencesHolder {
val preferences: SharedPreferences
}

View File

@ -0,0 +1,45 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.fenix.settings.sharedpreferences
import mozilla.components.feature.sitepermissions.SitePermissionsRules
import java.security.InvalidParameterException
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
private class SitePermissionsRulesActionPreference(
private val key: String
) : ReadWriteProperty<PreferencesHolder, SitePermissionsRules.Action> {
override fun getValue(thisRef: PreferencesHolder, property: KProperty<*>): SitePermissionsRules.Action =
intToAction(thisRef.preferences.getInt(key, ASK_TO_ALLOW_INT))
override fun setValue(thisRef: PreferencesHolder, property: KProperty<*>, value: SitePermissionsRules.Action) {
thisRef.preferences.edit().putInt(key, actionToInt(value)).apply()
}
companion object {
private const val BLOCKED_INT = 0
private const val ASK_TO_ALLOW_INT = 1
private fun actionToInt(action: SitePermissionsRules.Action) = when (action) {
SitePermissionsRules.Action.BLOCKED -> BLOCKED_INT
SitePermissionsRules.Action.ASK_TO_ALLOW -> ASK_TO_ALLOW_INT
}
private fun intToAction(action: Int) = when (action) {
BLOCKED_INT -> SitePermissionsRules.Action.BLOCKED
ASK_TO_ALLOW_INT -> SitePermissionsRules.Action.ASK_TO_ALLOW
else -> throw InvalidParameterException("$action is not a valid SitePermissionsRules.Action")
}
}
}
/**
* Property delegate for getting and setting a [SitePermissionsRules.Action] preference.
*/
fun sitePermissionsRulesActionPreference(
key: String
): ReadWriteProperty<PreferencesHolder, SitePermissionsRules.Action> = SitePermissionsRulesActionPreference(key)

View File

@ -14,16 +14,17 @@ import org.mozilla.fenix.BuildConfig
import org.mozilla.fenix.Config import org.mozilla.fenix.Config
import org.mozilla.fenix.R import org.mozilla.fenix.R
import org.mozilla.fenix.ext.getPreferenceKey import org.mozilla.fenix.ext.getPreferenceKey
import java.security.InvalidParameterException import org.mozilla.fenix.settings.sharedpreferences.PreferencesHolder
import org.mozilla.fenix.settings.sharedpreferences.booleanPreference
import org.mozilla.fenix.settings.sharedpreferences.sitePermissionsRulesActionPreference
/** /**
* A simple wrapper for SharedPreferences that makes reading preference a little bit easier. * A simple wrapper for SharedPreferences that makes reading preference a little bit easier.
*/ */
@SuppressWarnings("TooManyFunctions")
class Settings private constructor( class Settings private constructor(
context: Context, context: Context,
private val isCrashReportEnabledInBuild: Boolean private val isCrashReportEnabledInBuild: Boolean
) { ) : PreferencesHolder {
companion object { companion object {
const val autoBounceMaximumCount = 2 const val autoBounceMaximumCount = 2
@ -46,110 +47,80 @@ class Settings private constructor(
private val appContext = context.applicationContext private val appContext = context.applicationContext
val preferences: SharedPreferences = override val preferences: SharedPreferences =
appContext.getSharedPreferences(FENIX_PREFERENCES, MODE_PRIVATE) appContext.getSharedPreferences(FENIX_PREFERENCES, MODE_PRIVATE)
val usePrivateMode: Boolean var usePrivateMode by booleanPreference(
get() = preferences.getBoolean(appContext.getPreferenceKey(R.string.pref_key_private_mode), false) appContext.getPreferenceKey(R.string.pref_key_private_mode),
default = false
)
fun setPrivateMode(newValue: Boolean) { var defaultSearchEngineName: String
preferences.edit().putBoolean(appContext.getPreferenceKey(R.string.pref_key_private_mode), newValue).apply()
}
val defaultSearchEngineName: String
get() = preferences.getString(appContext.getPreferenceKey(R.string.pref_key_search_engine), "") ?: "" get() = preferences.getString(appContext.getPreferenceKey(R.string.pref_key_search_engine), "") ?: ""
set(name) = preferences.edit()
.putString(appContext.getPreferenceKey(R.string.pref_key_search_engine), name)
.apply()
val isCrashReportingEnabled: Boolean val isCrashReportingEnabled: Boolean
get() = isCrashReportEnabledInBuild && get() = isCrashReportEnabledInBuild &&
preferences.getBoolean(appContext.getPreferenceKey(R.string.pref_key_crash_reporter), true) preferences.getBoolean(appContext.getPreferenceKey(R.string.pref_key_crash_reporter), true)
val isRemoteDebuggingEnabled: Boolean val isRemoteDebuggingEnabled by booleanPreference(
get() = preferences.getBoolean(appContext.getPreferenceKey(R.string.pref_key_remote_debugging), false) appContext.getPreferenceKey(R.string.pref_key_remote_debugging),
default = false
)
val isTelemetryEnabled: Boolean val isTelemetryEnabled by booleanPreference(
get() = preferences.getBoolean(appContext.getPreferenceKey(R.string.pref_key_telemetry), true) appContext.getPreferenceKey(R.string.pref_key_telemetry),
default = true
)
val shouldAutoBounceQuickActionSheet: Boolean val shouldAutoBounceQuickActionSheet: Boolean
get() = autoBounceQuickActionSheetCount < autoBounceMaximumCount get() = autoBounceQuickActionSheetCount < autoBounceMaximumCount
val shouldUseLightTheme: Boolean var shouldUseLightTheme by booleanPreference(
get() = preferences.getBoolean( appContext.getPreferenceKey(R.string.pref_key_light_theme),
appContext.getPreferenceKey(R.string.pref_key_light_theme), default = false
false )
)
fun setLightTheme(newValue: Boolean) { var shouldUseAutoSize by booleanPreference(
preferences.edit().putBoolean( appContext.getPreferenceKey(R.string.pref_key_accessibility_auto_size),
appContext.getPreferenceKey(R.string.pref_key_light_theme), default = true
newValue )
).apply()
}
fun setAutoSize(newValue: Boolean) { var fontSizeFactor: Float
preferences.edit().putBoolean(appContext.getPreferenceKey(R.string.pref_key_accessibility_auto_size), newValue)
.apply()
}
val shouldUseAutoSize: Boolean
get() = preferences.getBoolean(
appContext.getPreferenceKey(R.string.pref_key_accessibility_auto_size),
true
)
fun setFontSizeFactor(newValue: Float) {
preferences.edit().putFloat(appContext.getPreferenceKey(R.string.pref_key_accessibility_font_scale), newValue)
.apply()
}
val fontSizeFactor: Float
get() = preferences.getFloat( get() = preferences.getFloat(
appContext.getPreferenceKey(R.string.pref_key_accessibility_font_scale), appContext.getPreferenceKey(R.string.pref_key_accessibility_font_scale),
1f 1f
) )
set(value) = preferences.edit()
.putFloat(appContext.getPreferenceKey(R.string.pref_key_accessibility_font_scale), value)
.apply()
val shouldShowVisitedSitesBookmarks: Boolean val shouldShowVisitedSitesBookmarks by booleanPreference(
get() = preferences.getBoolean( appContext.getPreferenceKey(R.string.pref_key_show_visited_sites_bookmarks),
appContext.getPreferenceKey(R.string.pref_key_show_visited_sites_bookmarks), default = true
true )
)
val shouldUseDarkTheme: Boolean val shouldUseDarkTheme by booleanPreference(
get() = preferences.getBoolean( appContext.getPreferenceKey(R.string.pref_key_dark_theme),
appContext.getPreferenceKey(R.string.pref_key_dark_theme), default = false
false )
)
val shouldFollowDeviceTheme: Boolean var shouldFollowDeviceTheme by booleanPreference(
get() = preferences.getBoolean( appContext.getPreferenceKey(R.string.pref_key_follow_device_theme),
appContext.getPreferenceKey(R.string.pref_key_follow_device_theme), default = false
false )
)
fun setFollowDeviceTheme(newValue: Boolean) { var shouldUseTrackingProtection by booleanPreference(
preferences.edit().putBoolean( appContext.getPreferenceKey(R.string.pref_key_tracking_protection),
appContext.getPreferenceKey(R.string.pref_key_follow_device_theme), default = true
newValue )
).apply()
}
val shouldUseTrackingProtection: Boolean val shouldUseAutoBatteryTheme by booleanPreference(
get() = preferences.getBoolean( appContext.getPreferenceKey(R.string.pref_key_auto_battery_theme),
appContext.getPreferenceKey(R.string.pref_key_tracking_protection), default = false
true )
)
fun setTrackingProtection(newValue: Boolean) {
preferences.edit().putBoolean(
appContext.getPreferenceKey(R.string.pref_key_tracking_protection),
newValue
).apply()
}
val shouldUseAutoBatteryTheme: Boolean
get() = preferences.getBoolean(
appContext.getPreferenceKey(R.string.pref_key_auto_battery_theme),
false
)
val themeSettingString: String val themeSettingString: String
get() = when { get() = when {
@ -162,7 +133,7 @@ class Settings private constructor(
@VisibleForTesting(otherwise = PRIVATE) @VisibleForTesting(otherwise = PRIVATE)
internal val autoBounceQuickActionSheetCount: Int internal val autoBounceQuickActionSheetCount: Int
get() = (preferences.getInt(appContext.getPreferenceKey(R.string.pref_key_bounce_quick_action), 0)) get() = preferences.getInt(appContext.getPreferenceKey(R.string.pref_key_bounce_quick_action), 0)
fun incrementAutomaticBounceQuickActionSheetCount() { fun incrementAutomaticBounceQuickActionSheetCount() {
preferences.edit().putInt( preferences.edit().putInt(
@ -171,91 +142,42 @@ class Settings private constructor(
).apply() ).apply()
} }
fun setDefaultSearchEngineByName(name: String) { val showSearchSuggestions by booleanPreference(
preferences.edit() appContext.getPreferenceKey(R.string.pref_key_show_search_suggestions),
.putString(appContext.getPreferenceKey(R.string.pref_key_search_engine), name) default = true
.apply() )
}
val showSearchSuggestions: Boolean var sitePermissionsPhoneFeatureCameraAction by sitePermissionsRulesActionPreference(
get() = preferences.getBoolean( appContext.getPreferenceKey(R.string.pref_key_phone_feature_camera)
appContext.getPreferenceKey(R.string.pref_key_show_search_suggestions), true )
)
fun setSitePermissionsPhoneFeatureCameraAction(action: SitePermissionsRules.Action) { var sitePermissionsPhoneFeatureMicrophoneAction by sitePermissionsRulesActionPreference(
preferences.edit() appContext.getPreferenceKey(R.string.pref_key_phone_feature_microphone)
.putInt(appContext.getPreferenceKey(R.string.pref_key_phone_feature_camera), action.id) )
.apply()
}
fun getSitePermissionsPhoneFeatureCameraAction(): SitePermissionsRules.Action { var sitePermissionsPhoneFeatureNotificationAction by sitePermissionsRulesActionPreference(
return preferences.getInt(appContext.getPreferenceKey(R.string.pref_key_phone_feature_camera), 1) appContext.getPreferenceKey(R.string.pref_key_phone_feature_notification)
.toSitePermissionsRulesAction() )
}
fun setSitePermissionsPhoneFeatureMicrophoneAction(action: SitePermissionsRules.Action) { var sitePermissionsPhoneFeatureLocation by sitePermissionsRulesActionPreference(
preferences.edit() appContext.getPreferenceKey(R.string.pref_key_phone_feature_location)
.putInt(appContext.getPreferenceKey(R.string.pref_key_phone_feature_microphone), action.id) )
.apply()
}
fun getSitePermissionsPhoneFeatureMicrophoneAction(): SitePermissionsRules.Action {
return preferences.getInt(appContext.getPreferenceKey(R.string.pref_key_phone_feature_microphone), 1)
.toSitePermissionsRulesAction()
}
fun setSitePermissionsPhoneFeatureNotificationAction(action: SitePermissionsRules.Action) {
preferences.edit()
.putInt(appContext.getPreferenceKey(R.string.pref_key_phone_feature_notification), action.id)
.apply()
}
fun getSitePermissionsPhoneFeatureNotificationAction(): SitePermissionsRules.Action {
return preferences.getInt(appContext.getPreferenceKey(R.string.pref_key_phone_feature_notification), 1)
.toSitePermissionsRulesAction()
}
fun setSitePermissionsPhoneFeatureLocation(action: SitePermissionsRules.Action) {
preferences.edit()
.putInt(appContext.getPreferenceKey(R.string.pref_key_phone_feature_location), action.id)
.apply()
}
fun getSitePermissionsPhoneFeatureLocation(): SitePermissionsRules.Action {
return preferences.getInt(appContext.getPreferenceKey(R.string.pref_key_phone_feature_location), 1)
.toSitePermissionsRulesAction()
}
fun getSitePermissionsCustomSettingsRules(): SitePermissionsRules { fun getSitePermissionsCustomSettingsRules(): SitePermissionsRules {
return SitePermissionsRules( return SitePermissionsRules(
notification = getSitePermissionsPhoneFeatureNotificationAction(), notification = sitePermissionsPhoneFeatureNotificationAction,
microphone = getSitePermissionsPhoneFeatureMicrophoneAction(), microphone = sitePermissionsPhoneFeatureMicrophoneAction,
location = getSitePermissionsPhoneFeatureLocation(), location = sitePermissionsPhoneFeatureLocation,
camera = getSitePermissionsPhoneFeatureCameraAction() camera = sitePermissionsPhoneFeatureCameraAction
) )
} }
fun setFxaSignedIn(isSignedIn: Boolean) { var fxaSignedIn by booleanPreference(appContext.getPreferenceKey(R.string.pref_key_fxa_signed_in), default = true)
preferences.edit()
.putBoolean(appContext.getPreferenceKey(R.string.pref_key_fxa_signed_in), isSignedIn)
.apply()
}
val fxaSignedIn: Boolean var fxaHasSyncedItems by booleanPreference(
get() = preferences.getBoolean( appContext.getPreferenceKey(R.string.pref_key_fxa_has_synced_items),
appContext.getPreferenceKey(R.string.pref_key_fxa_signed_in), true default = true
) )
fun setFxaHasSyncedItems(hasSyncedItems: Boolean) {
preferences.edit()
.putBoolean(appContext.getPreferenceKey(R.string.pref_key_fxa_has_synced_items), hasSyncedItems)
.apply()
}
val fxaHasSyncedItems: Boolean
get() = preferences.getBoolean(
appContext.getPreferenceKey(R.string.pref_key_fxa_has_synced_items), true
)
fun addSearchWidgetInstalled(count: Int) { fun addSearchWidgetInstalled(count: Int) {
val key = appContext.getPreferenceKey(R.string.pref_key_search_widget_installed) val key = appContext.getPreferenceKey(R.string.pref_key_search_widget_installed)
@ -266,23 +188,5 @@ class Settings private constructor(
} }
val searchWidgetInstalled: Boolean val searchWidgetInstalled: Boolean
get() = 0 < preferences.getInt( get() = 0 < preferences.getInt(appContext.getPreferenceKey(R.string.pref_key_search_widget_installed), 0)
appContext.getPreferenceKey(R.string.pref_key_search_widget_installed), 0
)
private val SitePermissionsRules.Action.id: Int
get() {
return when (this) {
SitePermissionsRules.Action.BLOCKED -> 0
SitePermissionsRules.Action.ASK_TO_ALLOW -> 1
}
}
private fun Int.toSitePermissionsRulesAction(): SitePermissionsRules.Action {
return when (this) {
0 -> SitePermissionsRules.Action.BLOCKED
1 -> SitePermissionsRules.Action.ASK_TO_ALLOW
else -> throw InvalidParameterException("$this is not a valid SitePermissionsRules.Action")
}
}
} }

View File

@ -0,0 +1,76 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.fenix.settings.sharedpreferences
import android.content.SharedPreferences
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class BooleanPreferenceTest {
private lateinit var sharedPrefs: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
@Before
fun setup() {
sharedPrefs = mockk(relaxed = true)
editor = mockk()
every { sharedPrefs.edit() } returns editor
every { editor.putBoolean(any(), any()) } returns editor
every { editor.apply() } just runs
}
@Test
fun `getter returns boolean from shared preferences`() {
val holder = object : PreferencesHolder {
override val preferences = sharedPrefs
val test by booleanPreference("test_pref_key", default = false)
}
every { sharedPrefs.getBoolean("test_pref_key", false) } returns true
assertTrue(holder.test)
verify { sharedPrefs.getBoolean("test_pref_key", false) }
}
@Test
fun `setter applies boolean to shared preferences`() {
val holder = object : PreferencesHolder {
override val preferences = sharedPrefs
var test by booleanPreference("pref", default = true)
}
holder.test = false
verify { editor.putBoolean("pref", false) }
verify { editor.apply() }
}
@Test
fun `getter uses default value`() {
val holderFalse = object : PreferencesHolder {
override val preferences = sharedPrefs
val test by booleanPreference("test_pref_key", default = false)
}
// Call the getter for the test
holderFalse.test
verify { sharedPrefs.getBoolean("test_pref_key", false) }
val holderTrue = object : PreferencesHolder {
override val preferences = sharedPrefs
val test by booleanPreference("test_pref_key", default = true)
}
// Call the getter for the test
holderTrue.test
verify { sharedPrefs.getBoolean("test_pref_key", true) }
}
}

View File

@ -0,0 +1,73 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.fenix.settings.sharedpreferences
import android.content.SharedPreferences
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import mozilla.components.feature.sitepermissions.SitePermissionsRules
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class SitePermissionsRulesActionPreferenceTest {
private lateinit var sharedPrefs: SharedPreferences
private lateinit var editor: SharedPreferences.Editor
@Before
fun setup() {
sharedPrefs = mockk(relaxed = true)
editor = mockk()
every { sharedPrefs.edit() } returns editor
every { editor.putInt(any(), any()) } returns editor
every { editor.apply() } just runs
}
@Test
fun `getter returns action from shared preferences`() {
val holder = object : PreferencesHolder {
override val preferences = sharedPrefs
val test by sitePermissionsRulesActionPreference("test_preference_key")
}
every { sharedPrefs.getInt("test_preference_key", 1) } returns 0
assertEquals(SitePermissionsRules.Action.BLOCKED, holder.test)
verify { sharedPrefs.getInt("test_preference_key", 1) }
}
@Test
fun `setter applies boolean to shared preferences`() {
val holder = object : PreferencesHolder {
override val preferences = sharedPrefs
var test by sitePermissionsRulesActionPreference("pref")
}
holder.test = SitePermissionsRules.Action.BLOCKED
verify { editor.putInt("pref", 0) }
verify { editor.apply() }
holder.test = SitePermissionsRules.Action.ASK_TO_ALLOW
verify { editor.putInt("pref", 1) }
verify { editor.apply() }
}
@Test
fun `getter defaults to ASK_TO_ALLOW`() {
every { sharedPrefs.getInt("key", 1) } returns 1
val holder = object : PreferencesHolder {
override val preferences = sharedPrefs
val action by sitePermissionsRulesActionPreference("key")
}
assertEquals(SitePermissionsRules.Action.ASK_TO_ALLOW, holder.action)
verify { sharedPrefs.getInt("key", 1) }
}
}

View File

@ -40,13 +40,13 @@ class SettingsTest {
assertFalse(settings.usePrivateMode) assertFalse(settings.usePrivateMode)
// When // When
settings.setPrivateMode(true) settings.usePrivateMode = true
// Then // Then
assertTrue(settings.usePrivateMode) assertTrue(settings.usePrivateMode)
// When // When
settings.setPrivateMode(false) settings.usePrivateMode = false
// Then // Then
assertFalse(settings.usePrivateMode) assertFalse(settings.usePrivateMode)
@ -59,7 +59,7 @@ class SettingsTest {
assertEquals("", settings.defaultSearchEngineName) assertEquals("", settings.defaultSearchEngineName)
// When // When
settings.setDefaultSearchEngineByName("Mozilla") settings.defaultSearchEngineName = "Mozilla"
// Then // Then
assertEquals("Mozilla", settings.defaultSearchEngineName) assertEquals("Mozilla", settings.defaultSearchEngineName)
@ -141,7 +141,7 @@ class SettingsTest {
assertFalse(settings.shouldUseLightTheme) assertFalse(settings.shouldUseLightTheme)
// When // When
settings.setLightTheme(true) settings.shouldUseLightTheme = true
// Then // Then
assertTrue(settings.shouldUseLightTheme) assertTrue(settings.shouldUseLightTheme)
@ -154,7 +154,7 @@ class SettingsTest {
assertTrue(settings.shouldUseAutoSize) assertTrue(settings.shouldUseAutoSize)
// When // When
settings.setAutoSize(false) settings.shouldUseAutoSize = false
// Then // Then
assertFalse(settings.shouldUseAutoSize) assertFalse(settings.shouldUseAutoSize)
@ -167,7 +167,7 @@ class SettingsTest {
assertEquals(1f, settings.fontSizeFactor) assertEquals(1f, settings.fontSizeFactor)
// When // When
settings.setFontSizeFactor(2f) settings.fontSizeFactor = 2f
// Then // Then
assertEquals(2f, settings.fontSizeFactor) assertEquals(2f, settings.fontSizeFactor)
@ -194,7 +194,7 @@ class SettingsTest {
assertFalse(settings.shouldFollowDeviceTheme) assertFalse(settings.shouldFollowDeviceTheme)
// When // When
settings.setFollowDeviceTheme(true) settings.shouldFollowDeviceTheme = true
// Then // Then
assertTrue(settings.shouldFollowDeviceTheme) assertTrue(settings.shouldFollowDeviceTheme)
@ -207,7 +207,7 @@ class SettingsTest {
assertTrue(settings.shouldUseTrackingProtection) assertTrue(settings.shouldUseTrackingProtection)
// When // When
settings.setTrackingProtection(false) settings.shouldUseTrackingProtection = false
// Then // Then
assertFalse(settings.shouldUseTrackingProtection) assertFalse(settings.shouldUseTrackingProtection)
@ -231,52 +231,52 @@ class SettingsTest {
fun sitePermissionsPhoneFeatureCameraAction() { fun sitePermissionsPhoneFeatureCameraAction() {
// When just created // When just created
// Then // Then
assertEquals(ASK_TO_ALLOW, settings.getSitePermissionsPhoneFeatureCameraAction()) assertEquals(ASK_TO_ALLOW, settings.sitePermissionsPhoneFeatureCameraAction)
// When // When
settings.setSitePermissionsPhoneFeatureCameraAction(BLOCKED) settings.sitePermissionsPhoneFeatureCameraAction = BLOCKED
// Then // Then
assertEquals(BLOCKED, settings.getSitePermissionsPhoneFeatureCameraAction()) assertEquals(BLOCKED, settings.sitePermissionsPhoneFeatureCameraAction)
} }
@Test @Test
fun sitePermissionsPhoneFeatureMicrophoneAction() { fun sitePermissionsPhoneFeatureMicrophoneAction() {
// When just created // When just created
// Then // Then
assertEquals(ASK_TO_ALLOW, settings.getSitePermissionsPhoneFeatureMicrophoneAction()) assertEquals(ASK_TO_ALLOW, settings.sitePermissionsPhoneFeatureMicrophoneAction)
// When // When
settings.setSitePermissionsPhoneFeatureMicrophoneAction(BLOCKED) settings.sitePermissionsPhoneFeatureMicrophoneAction = BLOCKED
// Then // Then
assertEquals(BLOCKED, settings.getSitePermissionsPhoneFeatureMicrophoneAction()) assertEquals(BLOCKED, settings.sitePermissionsPhoneFeatureMicrophoneAction)
} }
@Test @Test
fun sitePermissionsPhoneFeatureNotificationAction() { fun sitePermissionsPhoneFeatureNotificationAction() {
// When just created // When just created
// Then // Then
assertEquals(ASK_TO_ALLOW, settings.getSitePermissionsPhoneFeatureNotificationAction()) assertEquals(ASK_TO_ALLOW, settings.sitePermissionsPhoneFeatureNotificationAction)
// When // When
settings.setSitePermissionsPhoneFeatureNotificationAction(BLOCKED) settings.sitePermissionsPhoneFeatureNotificationAction = BLOCKED
// Then // Then
assertEquals(BLOCKED, settings.getSitePermissionsPhoneFeatureNotificationAction()) assertEquals(BLOCKED, settings.sitePermissionsPhoneFeatureNotificationAction)
} }
@Test @Test
fun sitePermissionsPhoneFeatureLocation() { fun sitePermissionsPhoneFeatureLocation() {
// When just created // When just created
// Then // Then
assertEquals(ASK_TO_ALLOW, settings.getSitePermissionsPhoneFeatureLocation()) assertEquals(ASK_TO_ALLOW, settings.sitePermissionsPhoneFeatureLocation)
// When // When
settings.setSitePermissionsPhoneFeatureLocation(BLOCKED) settings.sitePermissionsPhoneFeatureLocation = BLOCKED
// Then // Then
assertEquals(BLOCKED, settings.getSitePermissionsPhoneFeatureLocation()) assertEquals(BLOCKED, settings.sitePermissionsPhoneFeatureLocation)
} }
@Test @Test
@ -292,7 +292,7 @@ class SettingsTest {
@Test @Test
fun getSitePermissionsCustomSettingsRules_camera() { fun getSitePermissionsCustomSettingsRules_camera() {
// When // When
settings.setSitePermissionsPhoneFeatureCameraAction(BLOCKED) settings.sitePermissionsPhoneFeatureCameraAction = BLOCKED
// Then // Then
assertEquals( assertEquals(
@ -304,7 +304,7 @@ class SettingsTest {
@Test @Test
fun getSitePermissionsCustomSettingsRules_notification() { fun getSitePermissionsCustomSettingsRules_notification() {
// When // When
settings.setSitePermissionsPhoneFeatureNotificationAction(BLOCKED) settings.sitePermissionsPhoneFeatureNotificationAction = BLOCKED
// Then // Then
assertEquals( assertEquals(
@ -316,7 +316,7 @@ class SettingsTest {
@Test @Test
fun getSitePermissionsCustomSettingsRules_location() { fun getSitePermissionsCustomSettingsRules_location() {
// When // When
settings.setSitePermissionsPhoneFeatureLocation(BLOCKED) settings.sitePermissionsPhoneFeatureLocation = BLOCKED
// Then // Then
assertEquals( assertEquals(
@ -328,7 +328,7 @@ class SettingsTest {
@Test @Test
fun getSitePermissionsCustomSettingsRules_microphone() { fun getSitePermissionsCustomSettingsRules_microphone() {
// When // When
settings.setSitePermissionsPhoneFeatureMicrophoneAction(BLOCKED) settings.sitePermissionsPhoneFeatureMicrophoneAction = BLOCKED
// Then // Then
assertEquals( assertEquals(