summaryrefslogtreecommitdiffstats
path: root/src/com/android/providers/contacts/FastScrollingIndexCache.java
blob: 7a5d82da94ee13994b56af10f8e2ada0acd32128 (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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
/*
 * Copyright (C) 2012 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.providers.contacts;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract.Contacts;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.collect.Maps;
import com.google.common.annotations.VisibleForTesting;

import java.util.Map;
import java.util.regex.Pattern;

/**
 * Cache for the "fast scrolling index".
 *
 * It's a cache from "keys" and "bundles" (see {@link #mCache} for what they are).  The cache
 * content is also persisted in the shared preferences, so it'll survive even if the process
 * is killed or the device reboots.
 *
 * All the content will be invalidated when the provider detects an operation that could potentially
 * change the index.
 *
 * There's no maximum number for cached entries.  It's okay because we store keys and values in
 * a compact form in both the in-memory cache and the preferences.  Also the query in question
 * (the query for contact lists) has relatively low number of variations.
 *
 * This class is thread-safe.
 */
public class FastScrollingIndexCache {
    private static final String TAG = "LetterCountCache";

    @VisibleForTesting
    static final String PREFERENCE_KEY = "LetterCountCache";

    /**
     * Separator used for in-memory structure.
     */
    private static final String SEPARATOR = "\u0001";
    private static final Pattern SEPARATOR_PATTERN = Pattern.compile(SEPARATOR);

    /**
     * Separator used for serializing values for preferences.
     */
    private static final String SAVE_SEPARATOR = "\u0002";
    private static final Pattern SAVE_SEPARATOR_PATTERN = Pattern.compile(SAVE_SEPARATOR);

    private final SharedPreferences mPrefs;

    private boolean mPreferenceLoaded;

    /**
     * In-memory cache.
     *
     * It's essentially a map from keys, which are query parameters passed to {@link #get}, to
     * values, which are {@link Bundle}s that will be appended to a {@link Cursor} as extras.
     *
     * However, in order to save memory, we store stringified keys and values in the cache.
     * Key strings are generated by {@link #buildCacheKey} and values are generated by
     * {@link #buildCacheValue}.
     *
     * We store those strings joined with {@link #SAVE_SEPARATOR} as the separator when saving
     * to shared preferences.
     */
    private final Map<String, String> mCache = Maps.newHashMap();

    private static FastScrollingIndexCache sSingleton;

    public static FastScrollingIndexCache getInstance(Context context) {
        if (sSingleton == null) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            sSingleton = new FastScrollingIndexCache(prefs);
        }
        return sSingleton;
    }

    @VisibleForTesting
    static synchronized FastScrollingIndexCache getInstanceForTest(
            SharedPreferences prefs) {
        sSingleton = new FastScrollingIndexCache(prefs);
        return sSingleton;
    }

    private FastScrollingIndexCache(SharedPreferences prefs) {
        mPrefs = prefs;
    }

    /**
     * Append a {@link String} to a {@link StringBuilder}.
     *
     * Unlike the original {@link StringBuilder#append}, it does *not* append the string "null" if
     * {@code value} is null.
     */
    private static void appendIfNotNull(StringBuilder sb, Object value) {
        if (value != null) {
            sb.append(value.toString());
        }
    }

    private static String buildCacheKey(Uri queryUri, String selection, String[] selectionArgs,
            String sortOrder, String countExpression) {
        final StringBuilder sb = new StringBuilder();

        appendIfNotNull(sb, queryUri);
        appendIfNotNull(sb, SEPARATOR);
        appendIfNotNull(sb, selection);
        appendIfNotNull(sb, SEPARATOR);
        appendIfNotNull(sb, sortOrder);
        appendIfNotNull(sb, SEPARATOR);
        appendIfNotNull(sb, countExpression);

        if (selectionArgs != null) {
            for (int i = 0; i < selectionArgs.length; i++) {
                appendIfNotNull(sb, SEPARATOR);
                appendIfNotNull(sb, selectionArgs[i]);
            }
        }
        return sb.toString();
    }

    @VisibleForTesting
    static String buildCacheValue(String[] titles, int[] counts) {
        final StringBuilder sb = new StringBuilder();

        for (int i = 0; i < titles.length; i++) {
            if (i > 0) {
                appendIfNotNull(sb, SEPARATOR);
            }
            appendIfNotNull(sb, titles[i]);
            appendIfNotNull(sb, SEPARATOR);
            appendIfNotNull(sb, Integer.toString(counts[i]));
        }

        return sb.toString();
    }

    /**
     * Creates and returns a {@link Bundle} that is appended to a {@link Cursor} as extras.
     */
    public static final Bundle buildExtraBundle(String[] titles, int[] counts) {
        Bundle bundle = new Bundle();
        bundle.putStringArray(Contacts.EXTRA_ADDRESS_BOOK_INDEX_TITLES, titles);
        bundle.putIntArray(Contacts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS, counts);
        return bundle;
    }

    @VisibleForTesting
    static Bundle buildExtraBundleFromValue(String value) {
        final String[] values;
        if (TextUtils.isEmpty(value)) {
            values = new String[0];
        } else {
            values = SEPARATOR_PATTERN.split(value);
        }

        if ((values.length) % 2 != 0) {
            return null; // malformed
        }

        try {
            final int numTitles = values.length / 2;
            final String[] titles = new String[numTitles];
            final int[] counts = new int[numTitles];

            for (int i = 0; i < numTitles; i++) {
                titles[i] = values[i * 2];
                counts[i] = Integer.parseInt(values[i * 2 + 1]);
            }

            return buildExtraBundle(titles, counts);
        } catch (RuntimeException e) {
            Log.w(TAG, "Failed to parse cached value", e);
            return null; // malformed
        }
    }

    public Bundle get(Uri queryUri, String selection, String[] selectionArgs, String sortOrder,
            String countExpression) {
        synchronized (mCache) {
            ensureLoaded();
            final String key = buildCacheKey(queryUri, selection, selectionArgs, sortOrder,
                    countExpression);
            final String value = mCache.get(key);
            if (value == null) {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.v(TAG, "Miss: " + key);
                }
                return null;
            }

            final Bundle b = buildExtraBundleFromValue(value);
            if (b == null) {
                // Value was malformed for whatever reason.
                mCache.remove(key);
                save();
            } else {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.v(TAG, "Hit:  " + key);
                }
            }
            return b;
        }
    }

    /**
     * Put a {@link Bundle} into the cache.  {@link Bundle} MUST be built with
     * {@link #buildExtraBundle(String[], int[])}.
     */
    public void put(Uri queryUri, String selection, String[] selectionArgs, String sortOrder,
            String countExpression, Bundle bundle) {
        synchronized (mCache) {
            ensureLoaded();
            final String key = buildCacheKey(queryUri, selection, selectionArgs, sortOrder,
                    countExpression);
            mCache.put(key, buildCacheValue(
                    bundle.getStringArray(Contacts.EXTRA_ADDRESS_BOOK_INDEX_TITLES),
                    bundle.getIntArray(Contacts.EXTRA_ADDRESS_BOOK_INDEX_COUNTS)));
            save();

            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Put: " + key);
            }
        }
    }

    public void invalidate() {
        synchronized (mCache) {
            mPrefs.edit().remove(PREFERENCE_KEY).commit();
            mCache.clear();
            mPreferenceLoaded = true;

            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, "Invalidated");
            }
        }
    }

    /**
     * Store the cache to the preferences.
     *
     * We concatenate all key+value pairs into one string and save it.
     */
    private void save() {
        final StringBuilder sb = new StringBuilder();
        for (String key : mCache.keySet()) {
            if (sb.length() > 0) {
                appendIfNotNull(sb, SAVE_SEPARATOR);
            }
            appendIfNotNull(sb, key);
            appendIfNotNull(sb, SAVE_SEPARATOR);
            appendIfNotNull(sb, mCache.get(key));
        }
        mPrefs.edit().putString(PREFERENCE_KEY, sb.toString()).apply();
    }

    private void ensureLoaded() {
        if (mPreferenceLoaded) return;

        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Loading...");
        }

        // Even when we fail to load, don't retry loading again.
        mPreferenceLoaded = true;

        boolean successfullyLoaded = false;
        try {
            final String savedValue = mPrefs.getString(PREFERENCE_KEY, null);

            if (!TextUtils.isEmpty(savedValue)) {

                final String[] keysAndValues = SAVE_SEPARATOR_PATTERN.split(savedValue);

                if ((keysAndValues.length % 2) != 0) {
                    return; // malformed
                }

                for (int i = 1; i < keysAndValues.length; i += 2) {
                    final String key = keysAndValues[i - 1];
                    final String value = keysAndValues[i];

                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "Loaded: " + key);
                    }

                    mCache.put(key, value);
                }
            }
            successfullyLoaded = true;
        } catch (RuntimeException e) {
            Log.w(TAG, "Failed to load from preferences", e);
            // But don't crash apps!
        } finally {
            if (!successfullyLoaded) {
                invalidate();
            }
        }
    }
}