summaryrefslogtreecommitdiffstats
path: root/src/com/android/mail/preferences/VersionedPrefs.java
blob: f115f88b969dc43260e40033e3aea8f0a40544b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*
 * Copyright (C) 2012 Google Inc.
 * Licensed to The Android Open Source Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.mail.preferences;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;

import android.app.backup.BackupManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.android.mail.MailIntentService;
import com.android.mail.utils.LogTag;
import com.android.mail.utils.LogUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * A high-level API to store and retrieve preferences, that can be versioned in a similar manner as
 * SQLite databases. You must not use the preference key
 * {@value VersionedPrefs#PREFS_VERSION_NUMBER}
 */
public abstract class VersionedPrefs {
    private final Context mContext;
    private final String mSharedPreferencesName;
    private final SharedPreferences mSharedPreferences;
    private final Editor mEditor;

    /** The key for the version number of the {@link SharedPreferences} file. */
    private static final String PREFS_VERSION_NUMBER = "prefs-version-number";

    /**
     * The current version number for {@link SharedPreferences}. This is a constant for all
     * applications based on UnifiedEmail.
     */
    protected static final int CURRENT_VERSION_NUMBER = 4;

    protected static final String LOG_TAG = LogTag.getLogTag();

    /**
     * @param sharedPrefsName The name of the {@link SharedPreferences} file to use
     */
    protected VersionedPrefs(final Context context, final String sharedPrefsName) {
        mContext = context.getApplicationContext();
        mSharedPreferencesName = sharedPrefsName;
        mSharedPreferences = context.getSharedPreferences(sharedPrefsName, Context.MODE_PRIVATE);
        mEditor = mSharedPreferences.edit();

        final int oldVersion = getCurrentVersion();

        performUpgrade(oldVersion, CURRENT_VERSION_NUMBER);
        setCurrentVersion(CURRENT_VERSION_NUMBER);

        if (!hasMigrationCompleted()) {
            final BasePreferenceMigrator preferenceMigrator =
                    PreferenceMigratorHolder.createPreferenceMigrator();
            final boolean migrationComplete;
            if (preferenceMigrator != null) {
                migrationComplete = preferenceMigrator
                        .performMigration(context, oldVersion, CURRENT_VERSION_NUMBER);
            } else {
                LogUtils.w(LogUtils.TAG, "No preference migrator found, not migrating preferences");
                migrationComplete = false;
            }

            if (migrationComplete) {
                setMigrationComplete();
            }
        }
    }

    protected Context getContext() {
        return mContext;
    }

    public String getSharedPreferencesName() {
        return mSharedPreferencesName;
    }

    protected SharedPreferences getSharedPreferences() {
        return mSharedPreferences;
    }

    protected Editor getEditor() {
        return mEditor;
    }

    public void registerOnSharedPreferenceChangeListener(
            SharedPreferences.OnSharedPreferenceChangeListener listener) {
        mSharedPreferences.registerOnSharedPreferenceChangeListener(listener);
    }

    public void unregisterOnSharedPreferenceChangeListener(
            SharedPreferences.OnSharedPreferenceChangeListener listener) {
        mSharedPreferences.unregisterOnSharedPreferenceChangeListener(listener);
    }

    /**
     * Returns the current version of the {@link SharedPreferences} file.
     */
    private int getCurrentVersion() {
        return mSharedPreferences.getInt(PREFS_VERSION_NUMBER, 0);
    }

    private void setCurrentVersion(final int versionNumber) {
        getEditor().putInt(PREFS_VERSION_NUMBER, versionNumber);

        /*
         * If the only preference we have is the version number, we do not want to commit it.
         * Instead, we will wait for some other preference to be written. This prevents us from
         * creating a file with only the version number.
         */
        if (shouldBackUp()) {
            getEditor().apply();
        }
    }

    protected boolean hasMigrationCompleted() {
        return MailPrefs.get(mContext).hasMigrationCompleted();
    }

    protected void setMigrationComplete() {
        MailPrefs.get(mContext).setMigrationComplete();
    }

    /**
     * Commits all pending changes to the preferences.
     */
    public void commit() {
        getEditor().commit();
    }

    /**
     * Upgrades the {@link SharedPreferences} file.
     *
     * @param oldVersion The current version
     * @param newVersion The new version
     */
    protected abstract void performUpgrade(int oldVersion, int newVersion);

    @VisibleForTesting
    public void clearAllPreferences() {
        getEditor().clear().commit();
    }

    protected abstract boolean canBackup(String key);

    /**
     * Gets the value to backup for a given key-value pair. By default, returns the passed in value.
     *
     * @param key The key to backup
     * @param value The locally stored value for the given key
     * @return The value to backup
     */
    protected Object getBackupValue(final String key, final Object value) {
        return value;
    }

    /**
     * Gets the value to restore for a given key-value pair. By default, returns the passed in
     * value.
     *
     * @param key The key to restore
     * @param value The backed up value for the given key
     * @return The value to restore
     */
    protected Object getRestoreValue(final String key, final Object value) {
        return value;
    }

    /**
     * Return a list of shared preferences that should be backed up.
     */
    public List<BackupSharedPreference> getBackupPreferences() {
        final List<BackupSharedPreference> backupPreferences = Lists.newArrayList();
        final SharedPreferences sharedPreferences = getSharedPreferences();
        final Map<String, ?> preferences = sharedPreferences.getAll();

        for (final Map.Entry<String, ?> entry : preferences.entrySet()) {
            final String key = entry.getKey();

            if (!canBackup(key)) {
                continue;
            }

            final Object value = entry.getValue();
            final Object backupValue = getBackupValue(key, value);

            if (backupValue != null) {
                backupPreferences.add(new SimpleBackupSharedPreference(key, backupValue));
            }
        }

        return backupPreferences;
    }

    /**
     * Restores preferences from a backup.
     */
    public void restorePreferences(final List<BackupSharedPreference> preferences) {
        for (final BackupSharedPreference preference : preferences) {
            final String key = preference.getKey();
            final Object value = preference.getValue();

            if (!canBackup(key) || value == null) {
                continue;
            }

            final Object restoreValue = getRestoreValue(key, value);

            if (restoreValue instanceof Boolean) {
                getEditor().putBoolean(key, (Boolean) restoreValue);
                LogUtils.v(LOG_TAG, "MailPrefs Restore: %s", preference);
            } else if (restoreValue instanceof Float) {
                getEditor().putFloat(key, (Float) restoreValue);
                LogUtils.v(LOG_TAG, "MailPrefs Restore: %s", preference);
            } else if (restoreValue instanceof Integer) {
                getEditor().putInt(key, (Integer) restoreValue);
                LogUtils.v(LOG_TAG, "MailPrefs Restore: %s", preference);
            } else if (restoreValue instanceof Long) {
                getEditor().putLong(key, (Long) restoreValue);
                LogUtils.v(LOG_TAG, "MailPrefs Restore: %s", preference);
            } else if (restoreValue instanceof String) {
                getEditor().putString(key, (String) restoreValue);
                LogUtils.v(LOG_TAG, "MailPrefs Restore: %s", preference);
            } else if (restoreValue instanceof Set) {
                getEditor().putStringSet(key, (Set<String>) restoreValue);
            } else {
                LogUtils.e(LOG_TAG, "Unknown MailPrefs preference data type: %s", value.getClass());
            }
        }

        getEditor().apply();
    }

    /**
     * <p>
     * Checks if any of the preferences eligible for backup have been modified from their default
     * values, and therefore should be backed up.
     * </p>
     *
     * @return <code>true</code> if anything has been modified, <code>false</code> otherwise
     */
    public boolean shouldBackUp() {
        final Map<String, ?> allPrefs = getSharedPreferences().getAll();

        for (final String key : allPrefs.keySet()) {
            if (canBackup(key)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Notifies {@link BackupManager} that we have new data to back up.
     */
    protected void notifyBackupPreferenceChanged() {
        MailIntentService.broadcastBackupDataChanged(getContext());
    }
}