blob: 556d4af791ae46fae872305b93d6ffb1a5c20fe9 [file] [log] [blame]
Chris Wren1ada10d2013-09-13 18:01:38 -04001/*
2 * Copyright (C) 2013 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 */
16
17package com.android.launcher3;
18
19import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
20import com.google.protobuf.nano.MessageNano;
21
Chris Wren1ada10d2013-09-13 18:01:38 -040022import com.android.launcher3.LauncherSettings.Favorites;
23import com.android.launcher3.LauncherSettings.WorkspaceScreens;
24import com.android.launcher3.backup.BackupProtos;
25import com.android.launcher3.backup.BackupProtos.CheckedMessage;
26import com.android.launcher3.backup.BackupProtos.Favorite;
27import com.android.launcher3.backup.BackupProtos.Journal;
28import com.android.launcher3.backup.BackupProtos.Key;
Chris Wren22e130d2013-09-23 18:25:57 -040029import com.android.launcher3.backup.BackupProtos.Resource;
Chris Wren1ada10d2013-09-13 18:01:38 -040030import com.android.launcher3.backup.BackupProtos.Screen;
Chris Wrenfd13c712013-09-27 15:45:19 -040031import com.android.launcher3.backup.BackupProtos.Widget;
Chris Wren1ada10d2013-09-13 18:01:38 -040032
Chris Wren92aa4232013-10-04 11:29:36 -040033import android.app.backup.BackupDataInputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040034import android.app.backup.BackupDataOutput;
Chris Wren4d89e2a2013-10-09 17:03:50 -040035import android.app.backup.BackupHelper;
Chris Wren1ada10d2013-09-13 18:01:38 -040036import android.app.backup.BackupManager;
Chris Wren22e130d2013-09-23 18:25:57 -040037import android.appwidget.AppWidgetManager;
38import android.appwidget.AppWidgetProviderInfo;
39import android.content.ComponentName;
Chris Wren1ada10d2013-09-13 18:01:38 -040040import android.content.ContentResolver;
41import android.content.Context;
Chris Wren22e130d2013-09-23 18:25:57 -040042import android.content.Intent;
Chris Wren1ada10d2013-09-13 18:01:38 -040043import android.database.Cursor;
Chris Wren22e130d2013-09-23 18:25:57 -040044import android.graphics.Bitmap;
45import android.graphics.BitmapFactory;
Chris Wrenfd13c712013-09-27 15:45:19 -040046import android.graphics.drawable.Drawable;
Chris Wren1ada10d2013-09-13 18:01:38 -040047import android.os.ParcelFileDescriptor;
Chris Wren1ada10d2013-09-13 18:01:38 -040048import android.text.TextUtils;
49import android.util.Base64;
50import android.util.Log;
51
Chris Wren22e130d2013-09-23 18:25:57 -040052import java.io.ByteArrayOutputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040053import java.io.FileInputStream;
54import java.io.FileOutputStream;
55import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040056import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040057import java.util.ArrayList;
Chris Wren22e130d2013-09-23 18:25:57 -040058import java.util.HashMap;
Chris Wren1ada10d2013-09-13 18:01:38 -040059import java.util.HashSet;
Chris Wren22e130d2013-09-23 18:25:57 -040060import java.util.List;
Chris Wren1ada10d2013-09-13 18:01:38 -040061import java.util.Set;
62import java.util.zip.CRC32;
63
64/**
65 * Persist the launcher home state across calamities.
66 */
Chris Wren92aa4232013-10-04 11:29:36 -040067public class LauncherBackupHelper implements BackupHelper {
Chris Wren1ada10d2013-09-13 18:01:38 -040068
Chris Wren92aa4232013-10-04 11:29:36 -040069 private static final String TAG = "LauncherBackupHelper";
Chris Wrenfd13c712013-09-27 15:45:19 -040070 private static final boolean DEBUG = false;
Chris Wren92aa4232013-10-04 11:29:36 -040071 private static final boolean DEBUG_PAYLOAD = false;
Chris Wren1ada10d2013-09-13 18:01:38 -040072
73 private static final int MAX_JOURNAL_SIZE = 1000000;
74
Chris Wrenfd13c712013-09-27 15:45:19 -040075 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040076 private static final int MAX_ICONS_PER_PASS = 10;
77
Chris Wrenfd13c712013-09-27 15:45:19 -040078 /** widgets contain previews, which are very large, dribble them out */
79 private static final int MAX_WIDGETS_PER_PASS = 5;
80
81 public static final int IMAGE_COMPRESSION_QUALITY = 75;
82
Chris Wren92aa4232013-10-04 11:29:36 -040083 public static final String LAUNCHER_PREFIX = "L";
84
Chris Wren45297f82013-10-17 15:16:48 -040085 public static final String LAUNCHER_PREFS_PREFIX = "LP";
86
Chris Wrenb86f0762013-10-04 10:10:21 -040087 private static final Bitmap.CompressFormat IMAGE_FORMAT =
88 android.graphics.Bitmap.CompressFormat.PNG;
89
Chris Wren1ada10d2013-09-13 18:01:38 -040090 private static BackupManager sBackupManager;
91
92 private static final String[] FAVORITE_PROJECTION = {
93 Favorites._ID, // 0
Chris Wren22e130d2013-09-23 18:25:57 -040094 Favorites.MODIFIED, // 1
95 Favorites.INTENT, // 2
96 Favorites.APPWIDGET_PROVIDER, // 3
97 Favorites.APPWIDGET_ID, // 4
98 Favorites.CELLX, // 5
99 Favorites.CELLY, // 6
100 Favorites.CONTAINER, // 7
101 Favorites.ICON, // 8
102 Favorites.ICON_PACKAGE, // 9
103 Favorites.ICON_RESOURCE, // 10
104 Favorites.ICON_TYPE, // 11
105 Favorites.ITEM_TYPE, // 12
106 Favorites.SCREEN, // 13
107 Favorites.SPANX, // 14
108 Favorites.SPANY, // 15
109 Favorites.TITLE, // 16
Chris Wren1ada10d2013-09-13 18:01:38 -0400110 };
111
112 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400113 private static final int ID_MODIFIED = 1;
114 private static final int INTENT_INDEX = 2;
115 private static final int APPWIDGET_PROVIDER_INDEX = 3;
116 private static final int APPWIDGET_ID_INDEX = 4;
117 private static final int CELLX_INDEX = 5;
118 private static final int CELLY_INDEX = 6;
119 private static final int CONTAINER_INDEX = 7;
120 private static final int ICON_INDEX = 8;
121 private static final int ICON_PACKAGE_INDEX = 9;
122 private static final int ICON_RESOURCE_INDEX = 10;
123 private static final int ICON_TYPE_INDEX = 11;
124 private static final int ITEM_TYPE_INDEX = 12;
125 private static final int SCREEN_INDEX = 13;
126 private static final int SPANX_INDEX = 14;
127 private static final int SPANY_INDEX = 15;
128 private static final int TITLE_INDEX = 16;
Chris Wren1ada10d2013-09-13 18:01:38 -0400129
130 private static final String[] SCREEN_PROJECTION = {
131 WorkspaceScreens._ID, // 0
Chris Wren22e130d2013-09-23 18:25:57 -0400132 WorkspaceScreens.MODIFIED, // 1
133 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400134 };
135
Chris Wren22e130d2013-09-23 18:25:57 -0400136 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400137
Chris Wren92aa4232013-10-04 11:29:36 -0400138 private final Context mContext;
Chris Wren1ada10d2013-09-13 18:01:38 -0400139
Chris Wren4b171362014-01-13 17:39:02 -0500140 private final boolean mRestoreEnabled;
141
Chris Wren22e130d2013-09-23 18:25:57 -0400142 private HashMap<ComponentName, AppWidgetProviderInfo> mWidgetMap;
143
Chris Wren92aa4232013-10-04 11:29:36 -0400144 private ArrayList<Key> mKeys;
Chris Wren1ada10d2013-09-13 18:01:38 -0400145
Chris Wren4b171362014-01-13 17:39:02 -0500146 public LauncherBackupHelper(Context context, boolean restoreEnabled) {
Chris Wren92aa4232013-10-04 11:29:36 -0400147 mContext = context;
Chris Wren4b171362014-01-13 17:39:02 -0500148 mRestoreEnabled = restoreEnabled;
Chris Wren92aa4232013-10-04 11:29:36 -0400149 }
150
151 private void dataChanged() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400152 if (sBackupManager == null) {
Chris Wren92aa4232013-10-04 11:29:36 -0400153 sBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400154 }
155 sBackupManager.dataChanged();
156 }
157
158 /**
159 * Back up launcher data so we can restore the user's state on a new device.
160 *
161 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
162 *
163 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
164 *
165 * @param oldState notes from the last backup
166 * @param data incremental key/value pairs to persist off-device
167 * @param newState notes for the next backup
168 * @throws IOException
169 */
170 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400171 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
172 ParcelFileDescriptor newState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400173 Log.v(TAG, "onBackup");
174
175 Journal in = readJournal(oldState);
176 Journal out = new Journal();
177
178 long lastBackupTime = in.t;
179 out.t = System.currentTimeMillis();
180 out.rows = 0;
181 out.bytes = 0;
182
183 Log.v(TAG, "lastBackupTime=" + lastBackupTime);
184
185 ArrayList<Key> keys = new ArrayList<Key>();
Chris Wren92aa4232013-10-04 11:29:36 -0400186 try {
187 backupFavorites(in, data, out, keys);
188 backupScreens(in, data, out, keys);
189 backupIcons(in, data, out, keys);
190 backupWidgets(in, data, out, keys);
191 } catch (IOException e) {
192 Log.e(TAG, "launcher backup has failed", e);
193 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400194
195 out.key = keys.toArray(BackupProtos.Key.EMPTY_ARRAY);
196 writeJournal(newState, out);
197 Log.v(TAG, "onBackup: wrote " + out.bytes + "b in " + out.rows + " rows.");
Chris Wren1ada10d2013-09-13 18:01:38 -0400198 }
199
200 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400201 * Restore launcher configuration from the restored data stream.
Chris Wren1ada10d2013-09-13 18:01:38 -0400202 *
203 * <P>Keys may arrive in any order.
204 *
Chris Wren92aa4232013-10-04 11:29:36 -0400205 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400206 */
207 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400208 public void restoreEntity(BackupDataInputStream data) {
209 Log.v(TAG, "restoreEntity");
210 if (mKeys == null) {
211 mKeys = new ArrayList<Key>();
212 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400213 byte[] buffer = new byte[512];
Chris Wren1ada10d2013-09-13 18:01:38 -0400214 String backupKey = data.getKey();
Chris Wren92aa4232013-10-04 11:29:36 -0400215 int dataSize = data.size();
Chris Wren1ada10d2013-09-13 18:01:38 -0400216 if (buffer.length < dataSize) {
217 buffer = new byte[dataSize];
218 }
219 Key key = null;
Chris Wren92aa4232013-10-04 11:29:36 -0400220 int bytesRead = 0;
221 try {
222 bytesRead = data.read(buffer, 0, dataSize);
223 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
224 } catch (IOException e) {
225 Log.d(TAG, "failed to read entity from restore data", e);
226 }
227 try {
228 key = backupKeyToKey(backupKey);
229 switch (key.type) {
230 case Key.FAVORITE:
231 restoreFavorite(key, buffer, dataSize, mKeys);
232 break;
233
234 case Key.SCREEN:
235 restoreScreen(key, buffer, dataSize, mKeys);
236 break;
237
238 case Key.ICON:
239 restoreIcon(key, buffer, dataSize, mKeys);
240 break;
241
242 case Key.WIDGET:
243 restoreWidget(key, buffer, dataSize, mKeys);
244 break;
245
246 default:
247 Log.w(TAG, "unknown restore entity type: " + key.type);
248 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400249 }
Chris Wren92aa4232013-10-04 11:29:36 -0400250 } catch (KeyParsingException e) {
251 Log.w(TAG, "ignoring unparsable backup key: " + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400252 }
253
Chris Wren92aa4232013-10-04 11:29:36 -0400254 }
255
256 /**
257 * Record the restore state for the next backup.
258 *
259 * @param newState notes about the backup state after restore.
260 */
261 @Override
262 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400263 // clear the output journal time, to force a full backup to
264 // will catch any changes the restore process might have made
Chris Wren92aa4232013-10-04 11:29:36 -0400265 Journal out = new Journal();
Chris Wren1ada10d2013-09-13 18:01:38 -0400266 out.t = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400267 out.key = mKeys.toArray(BackupProtos.Key.EMPTY_ARRAY);
Chris Wren1ada10d2013-09-13 18:01:38 -0400268 writeJournal(newState, out);
Chris Wren92aa4232013-10-04 11:29:36 -0400269 Log.v(TAG, "onRestore: read " + mKeys.size() + " rows");
270 mKeys.clear();
Chris Wren1ada10d2013-09-13 18:01:38 -0400271 }
272
273 /**
274 * Write all modified favorites to the data stream.
275 *
276 *
277 * @param in notes from last backup
278 * @param data output stream for key/value pairs
279 * @param out notes about this backup
280 * @param keys keys to mark as clean in the notes for next backup
281 * @throws IOException
282 */
283 private void backupFavorites(Journal in, BackupDataOutput data, Journal out,
284 ArrayList<Key> keys)
285 throws IOException {
286 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400287 Set<String> savedIds = getSavedIdsByType(Key.FAVORITE, in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400288 if (DEBUG) Log.d(TAG, "favorite savedIds.size()=" + savedIds.size());
289
290 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400291 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400292 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
293 null, null, null);
294 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400295 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400296 cursor.moveToPosition(-1);
297 while(cursor.moveToNext()) {
298 final long id = cursor.getLong(ID_INDEX);
299 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400300 Key key = getKey(Key.FAVORITE, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400301 keys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500302 final String backupKey = keyToBackupKey(key);
303 currentIds.add(backupKey);
304 if (!savedIds.contains(backupKey) || updateTime >= in.t) {
Chris Wren22e130d2013-09-23 18:25:57 -0400305 byte[] blob = packFavorite(cursor);
306 writeRowToBackup(key, blob, out, data);
307 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400308 }
309 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400310 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400311 }
312 if (DEBUG) Log.d(TAG, "favorite currentIds.size()=" + currentIds.size());
313
314 // these IDs must have been deleted
315 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400316 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400317 }
318
319 /**
320 * Read a favorite from the stream.
321 *
322 * <P>Keys arrive in any order, so screens and containers may not exist yet.
323 *
324 * @param key identifier for the row
325 * @param buffer the serialized proto from the stream, may be larger than dataSize
326 * @param dataSize the size of the proto from the stream
327 * @param keys keys to mark as clean in the notes for next backup
328 */
329 private void restoreFavorite(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
330 Log.v(TAG, "unpacking favorite " + key.id + " (" + dataSize + " bytes)");
331 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
332 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
333
334 try {
335 Favorite favorite = unpackFavorite(buffer, 0, dataSize);
336 if (DEBUG) Log.d(TAG, "unpacked " + favorite.itemType);
337 } catch (InvalidProtocolBufferNanoException e) {
338 Log.w(TAG, "failed to decode proto", e);
339 }
340 }
341
342 /**
343 * Write all modified screens to the data stream.
344 *
345 *
346 * @param in notes from last backup
347 * @param data output stream for key/value pairs
348 * @param out notes about this backup
Chris Wren22e130d2013-09-23 18:25:57 -0400349 * @param keys keys to mark as clean in the notes for next backup
350 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400351 */
352 private void backupScreens(Journal in, BackupDataOutput data, Journal out,
353 ArrayList<Key> keys)
354 throws IOException {
355 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400356 Set<String> savedIds = getSavedIdsByType(Key.SCREEN, in);
357 if (DEBUG) Log.d(TAG, "screen savedIds.size()=" + savedIds.size());
Chris Wren1ada10d2013-09-13 18:01:38 -0400358
359 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400360 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400361 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
362 null, null, null);
363 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400364 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400365 cursor.moveToPosition(-1);
366 while(cursor.moveToNext()) {
367 final long id = cursor.getLong(ID_INDEX);
368 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400369 Key key = getKey(Key.SCREEN, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400370 keys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500371 final String backupKey = keyToBackupKey(key);
372 currentIds.add(backupKey);
373 if (!savedIds.contains(backupKey) || updateTime >= in.t) {
Chris Wren22e130d2013-09-23 18:25:57 -0400374 byte[] blob = packScreen(cursor);
375 writeRowToBackup(key, blob, out, data);
376 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400377 }
378 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400379 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400380 }
381 if (DEBUG) Log.d(TAG, "screen currentIds.size()=" + currentIds.size());
382
383 // these IDs must have been deleted
384 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400385 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400386 }
387
388 /**
389 * Read a screen from the stream.
390 *
391 * <P>Keys arrive in any order, so children of this screen may already exist.
392 *
393 * @param key identifier for the row
394 * @param buffer the serialized proto from the stream, may be larger than dataSize
395 * @param dataSize the size of the proto from the stream
396 * @param keys keys to mark as clean in the notes for next backup
397 */
398 private void restoreScreen(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
399 Log.v(TAG, "unpacking screen " + key.id);
400 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
401 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
402 try {
403 Screen screen = unpackScreen(buffer, 0, dataSize);
404 if (DEBUG) Log.d(TAG, "unpacked " + screen.rank);
405 } catch (InvalidProtocolBufferNanoException e) {
406 Log.w(TAG, "failed to decode proto", e);
407 }
408 }
409
Chris Wren22e130d2013-09-23 18:25:57 -0400410 /**
411 * Write all the static icon resources we need to render placeholders
412 * for a package that is not installed.
413 *
414 * @param in notes from last backup
415 * @param data output stream for key/value pairs
416 * @param out notes about this backup
417 * @param keys keys to mark as clean in the notes for next backup
418 * @throws IOException
419 */
420 private void backupIcons(Journal in, BackupDataOutput data, Journal out,
421 ArrayList<Key> keys) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400422 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400423 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
424 if (appState == null) {
425 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400426 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
427 return;
428 }
Chris Wren92aa4232013-10-04 11:29:36 -0400429 final ContentResolver cr = mContext.getContentResolver();
430 final IconCache iconCache = appState.getIconCache();
431 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wren22e130d2013-09-23 18:25:57 -0400432
433 // read the old ID set
434 Set<String> savedIds = getSavedIdsByType(Key.ICON, in);
435 if (DEBUG) Log.d(TAG, "icon savedIds.size()=" + savedIds.size());
436
437 int startRows = out.rows;
438 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
439 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION;
440 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
441 where, null, null);
442 Set<String> currentIds = new HashSet<String>(cursor.getCount());
443 try {
444 cursor.moveToPosition(-1);
445 while(cursor.moveToNext()) {
446 final long id = cursor.getLong(ID_INDEX);
447 final String intentDescription = cursor.getString(INTENT_INDEX);
448 try {
449 Intent intent = Intent.parseUri(intentDescription, 0);
450 ComponentName cn = intent.getComponent();
451 Key key = null;
452 String backupKey = null;
453 if (cn != null) {
454 key = getKey(Key.ICON, cn.flattenToShortString());
455 backupKey = keyToBackupKey(key);
456 currentIds.add(backupKey);
457 } else {
458 Log.w(TAG, "empty intent on application favorite: " + id);
459 }
460 if (savedIds.contains(backupKey)) {
461 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
462
463 // remember that we already backed this up previously
464 keys.add(key);
465 } else if (backupKey != null) {
466 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
467 if ((out.rows - startRows) < MAX_ICONS_PER_PASS) {
468 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
469 Bitmap icon = iconCache.getIcon(intent);
470 keys.add(key);
471 if (icon != null && !iconCache.isDefaultIcon(icon)) {
472 byte[] blob = packIcon(dpi, icon);
473 writeRowToBackup(key, blob, out, data);
474 }
475 } else {
Chris Wrenfd13c712013-09-27 15:45:19 -0400476 if (DEBUG) Log.d(TAG, "scheduling another run for icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400477 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400478 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400479 }
480 }
481 } catch (URISyntaxException e) {
482 Log.w(TAG, "invalid URI on application favorite: " + id);
483 } catch (IOException e) {
484 Log.w(TAG, "unable to save application icon for favorite: " + id);
485 }
486
487 }
488 } finally {
489 cursor.close();
490 }
491 if (DEBUG) Log.d(TAG, "icon currentIds.size()=" + currentIds.size());
492
493 // these IDs must have been deleted
494 savedIds.removeAll(currentIds);
495 out.rows += removeDeletedKeysFromBackup(savedIds, data);
496 }
497
498 /**
499 * Read an icon from the stream.
500 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400501 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400502 *
503 * @param key identifier for the row
504 * @param buffer the serialized proto from the stream, may be larger than dataSize
505 * @param dataSize the size of the proto from the stream
506 * @param keys keys to mark as clean in the notes for next backup
507 */
508 private void restoreIcon(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
509 Log.v(TAG, "unpacking icon " + key.id);
510 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
511 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
512 try {
513 Resource res = unpackIcon(buffer, 0, dataSize);
514 if (DEBUG) Log.d(TAG, "unpacked " + res.dpi);
515 if (DEBUG) Log.d(TAG, "read " +
516 Base64.encodeToString(res.data, 0, res.data.length,
517 Base64.NO_WRAP));
518 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
519 if (icon == null) {
520 Log.w(TAG, "failed to unpack icon for " + key.name);
521 }
522 } catch (InvalidProtocolBufferNanoException e) {
523 Log.w(TAG, "failed to decode proto", e);
524 }
525 }
526
Chris Wrenfd13c712013-09-27 15:45:19 -0400527 /**
528 * Write all the static widget resources we need to render placeholders
529 * for a package that is not installed.
530 *
531 * @param in notes from last backup
532 * @param data output stream for key/value pairs
533 * @param out notes about this backup
534 * @param keys keys to mark as clean in the notes for next backup
535 * @throws IOException
536 */
537 private void backupWidgets(Journal in, BackupDataOutput data, Journal out,
538 ArrayList<Key> keys) throws IOException {
539 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400540 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
541 if (appState == null) {
Chris Wren92aa4232013-10-04 11:29:36 -0400542 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400543 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying widget backup");
544 return;
545 }
Chris Wren92aa4232013-10-04 11:29:36 -0400546 final ContentResolver cr = mContext.getContentResolver();
547 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
548 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400549 final IconCache iconCache = appState.getIconCache();
Chris Wren92aa4232013-10-04 11:29:36 -0400550 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400551 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
552 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
553
554 // read the old ID set
555 Set<String> savedIds = getSavedIdsByType(Key.WIDGET, in);
556 if (DEBUG) Log.d(TAG, "widgets savedIds.size()=" + savedIds.size());
557
558 int startRows = out.rows;
559 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
560 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET;
561 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
562 where, null, null);
563 Set<String> currentIds = new HashSet<String>(cursor.getCount());
564 try {
565 cursor.moveToPosition(-1);
566 while(cursor.moveToNext()) {
567 final long id = cursor.getLong(ID_INDEX);
568 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
569 final int spanX = cursor.getInt(SPANX_INDEX);
570 final int spanY = cursor.getInt(SPANY_INDEX);
571 final ComponentName provider = ComponentName.unflattenFromString(providerName);
572 Key key = null;
573 String backupKey = null;
574 if (provider != null) {
575 key = getKey(Key.WIDGET, providerName);
576 backupKey = keyToBackupKey(key);
577 currentIds.add(backupKey);
578 } else {
579 Log.w(TAG, "empty intent on appwidget: " + id);
580 }
581 if (savedIds.contains(backupKey)) {
582 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
583
584 // remember that we already backed this up previously
585 keys.add(key);
586 } else if (backupKey != null) {
587 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
588 if ((out.rows - startRows) < MAX_WIDGETS_PER_PASS) {
589 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
590 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
591 spanY * profile.cellHeightPx, widgetSpacingLayout);
592 byte[] blob = packWidget(dpi, previewLoader, iconCache, provider);
Chris Wrenb1fd63b2013-10-03 15:43:58 -0400593 keys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400594 writeRowToBackup(key, blob, out, data);
595
596 } else {
597 if (DEBUG) Log.d(TAG, "scheduling another run for widget " + backupKey);
598 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400599 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400600 }
601 }
602 }
603 } finally {
604 cursor.close();
605 }
606 if (DEBUG) Log.d(TAG, "widget currentIds.size()=" + currentIds.size());
607
608 // these IDs must have been deleted
609 savedIds.removeAll(currentIds);
610 out.rows += removeDeletedKeysFromBackup(savedIds, data);
611 }
612
613 /**
614 * Read a widget from the stream.
615 *
616 * <P>Keys arrive in any order, so widgets that use this data may already exist.
617 *
618 * @param key identifier for the row
619 * @param buffer the serialized proto from the stream, may be larger than dataSize
620 * @param dataSize the size of the proto from the stream
621 * @param keys keys to mark as clean in the notes for next backup
622 */
623 private void restoreWidget(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
624 Log.v(TAG, "unpacking widget " + key.id);
625 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
626 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
627 try {
628 Widget widget = unpackWidget(buffer, 0, dataSize);
629 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
630 if (widget.icon.data != null) {
631 Bitmap icon = BitmapFactory
632 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
633 if (icon == null) {
634 Log.w(TAG, "failed to unpack widget icon for " + key.name);
635 }
636 }
637 } catch (InvalidProtocolBufferNanoException e) {
638 Log.w(TAG, "failed to decode proto", e);
639 }
640 }
641
Chris Wren22e130d2013-09-23 18:25:57 -0400642 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400643 *
644 * <P> Keys contain their own checksum instead of using
645 * the heavy-weight CheckedMessage wrapper.
646 */
647 private Key getKey(int type, long id) {
648 Key key = new Key();
649 key.type = type;
650 key.id = id;
651 key.checksum = checkKey(key);
652 return key;
653 }
654
Chris Wren22e130d2013-09-23 18:25:57 -0400655 /** create a new key for a named object.
656 *
657 * <P> Keys contain their own checksum instead of using
658 * the heavy-weight CheckedMessage wrapper.
659 */
660 private Key getKey(int type, String name) {
661 Key key = new Key();
662 key.type = type;
663 key.name = name;
664 key.checksum = checkKey(key);
665 return key;
666 }
667
Chris Wren1ada10d2013-09-13 18:01:38 -0400668 /** keys need to be strings, serialize and encode. */
669 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400670 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400671 }
672
673 /** keys need to be strings, decode and parse. */
674 private Key backupKeyToKey(String backupKey) throws KeyParsingException {
675 try {
676 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
677 if (key.checksum != checkKey(key)) {
678 key = null;
679 throw new KeyParsingException("invalid key read from stream" + backupKey);
680 }
681 return key;
682 } catch (InvalidProtocolBufferNanoException e) {
683 throw new KeyParsingException(e);
684 } catch (IllegalArgumentException e) {
685 throw new KeyParsingException(e);
686 }
687 }
688
Chris Wren22e130d2013-09-23 18:25:57 -0400689 private String getKeyName(Key key) {
690 if (TextUtils.isEmpty(key.name)) {
691 return Long.toString(key.id);
692 } else {
693 return key.name;
694 }
695
696 }
697
698 private String geKeyType(Key key) {
699 switch (key.type) {
700 case Key.FAVORITE:
701 return "favorite";
702 case Key.SCREEN:
703 return "screen";
704 case Key.ICON:
705 return "icon";
Chris Wrenfd13c712013-09-27 15:45:19 -0400706 case Key.WIDGET:
707 return "widget";
Chris Wren22e130d2013-09-23 18:25:57 -0400708 default:
709 return "anonymous";
710 }
711 }
712
Chris Wren1ada10d2013-09-13 18:01:38 -0400713 /** Compute the checksum over the important bits of a key. */
714 private long checkKey(Key key) {
715 CRC32 checksum = new CRC32();
716 checksum.update(key.type);
717 checksum.update((int) (key.id & 0xffff));
718 checksum.update((int) ((key.id >> 32) & 0xffff));
719 if (!TextUtils.isEmpty(key.name)) {
720 checksum.update(key.name.getBytes());
721 }
722 return checksum.getValue();
723 }
724
725 /** Serialize a Favorite for persistence, including a checksum wrapper. */
726 private byte[] packFavorite(Cursor c) {
727 Favorite favorite = new Favorite();
728 favorite.id = c.getLong(ID_INDEX);
729 favorite.screen = c.getInt(SCREEN_INDEX);
730 favorite.container = c.getInt(CONTAINER_INDEX);
731 favorite.cellX = c.getInt(CELLX_INDEX);
732 favorite.cellY = c.getInt(CELLY_INDEX);
733 favorite.spanX = c.getInt(SPANX_INDEX);
734 favorite.spanY = c.getInt(SPANY_INDEX);
735 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
736 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
737 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
738 if (!TextUtils.isEmpty(iconPackage)) {
739 favorite.iconPackage = iconPackage;
740 }
741 String iconResource = c.getString(ICON_RESOURCE_INDEX);
742 if (!TextUtils.isEmpty(iconResource)) {
743 favorite.iconResource = iconResource;
744 }
745 }
746 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
747 byte[] blob = c.getBlob(ICON_INDEX);
748 if (blob != null && blob.length > 0) {
749 favorite.icon = blob;
750 }
751 }
752 String title = c.getString(TITLE_INDEX);
753 if (!TextUtils.isEmpty(title)) {
754 favorite.title = title;
755 }
756 String intent = c.getString(INTENT_INDEX);
757 if (!TextUtils.isEmpty(intent)) {
758 favorite.intent = intent;
759 }
760 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
761 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
762 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
763 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
764 if (!TextUtils.isEmpty(appWidgetProvider)) {
765 favorite.appWidgetProvider = appWidgetProvider;
766 }
767 }
768
769 return writeCheckedBytes(favorite);
770 }
771
772 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
773 private Favorite unpackFavorite(byte[] buffer, int offset, int dataSize)
774 throws InvalidProtocolBufferNanoException {
775 Favorite favorite = new Favorite();
776 MessageNano.mergeFrom(favorite, readCheckedBytes(buffer, offset, dataSize));
777 return favorite;
778 }
779
780 /** Serialize a Screen for persistence, including a checksum wrapper. */
781 private byte[] packScreen(Cursor c) {
782 Screen screen = new Screen();
783 screen.id = c.getLong(ID_INDEX);
784 screen.rank = c.getInt(SCREEN_RANK_INDEX);
785
786 return writeCheckedBytes(screen);
787 }
788
789 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
790 private Screen unpackScreen(byte[] buffer, int offset, int dataSize)
791 throws InvalidProtocolBufferNanoException {
792 Screen screen = new Screen();
793 MessageNano.mergeFrom(screen, readCheckedBytes(buffer, offset, dataSize));
794 return screen;
795 }
796
Chris Wren22e130d2013-09-23 18:25:57 -0400797 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
798 private byte[] packIcon(int dpi, Bitmap icon) {
799 Resource res = new Resource();
800 res.dpi = dpi;
801 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400802 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400803 res.data = os.toByteArray();
804 }
805 return writeCheckedBytes(res);
806 }
807
808 /** Deserialize an icon resource from persistence, after verifying checksum wrapper. */
809 private Resource unpackIcon(byte[] buffer, int offset, int dataSize)
810 throws InvalidProtocolBufferNanoException {
811 Resource res = new Resource();
812 MessageNano.mergeFrom(res, readCheckedBytes(buffer, offset, dataSize));
813 return res;
814 }
815
Chris Wrenfd13c712013-09-27 15:45:19 -0400816 /** Serialize a widget for persistence, including a checksum wrapper. */
817 private byte[] packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
818 ComponentName provider) {
819 final AppWidgetProviderInfo info = findAppWidgetProviderInfo(provider);
820 Widget widget = new Widget();
821 widget.provider = provider.flattenToShortString();
822 widget.label = info.label;
823 widget.configure = info.configure != null;
824 if (info.icon != 0) {
825 widget.icon = new Resource();
826 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400827 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400828 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400829 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400830 widget.icon.data = os.toByteArray();
831 widget.icon.dpi = dpi;
832 }
833 }
834 if (info.previewImage != 0) {
835 widget.preview = new Resource();
836 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
837 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400838 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400839 widget.preview.data = os.toByteArray();
840 widget.preview.dpi = dpi;
841 }
842 }
843 return writeCheckedBytes(widget);
844 }
845
846 /** Deserialize a widget from persistence, after verifying checksum wrapper. */
847 private Widget unpackWidget(byte[] buffer, int offset, int dataSize)
848 throws InvalidProtocolBufferNanoException {
849 Widget widget = new Widget();
850 MessageNano.mergeFrom(widget, readCheckedBytes(buffer, offset, dataSize));
851 return widget;
852 }
853
Chris Wren1ada10d2013-09-13 18:01:38 -0400854 /**
855 * Read the old journal from the input file.
856 *
857 * In the event of any error, just pretend we didn't have a journal,
858 * in that case, do a full backup.
859 *
860 * @param oldState the read-0only file descriptor pointing to the old journal
861 * @return a Journal protocol bugffer
862 */
863 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400864 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400865 if (oldState == null) {
866 return journal;
867 }
868 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
869 try {
870 int remaining = inStream.available();
871 if (DEBUG) Log.d(TAG, "available " + remaining);
872 if (remaining < MAX_JOURNAL_SIZE) {
873 byte[] buffer = new byte[remaining];
Chris Wren1ada10d2013-09-13 18:01:38 -0400874 int bytesRead = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400875 while (remaining > 0) {
876 try {
877 int result = inStream.read(buffer, bytesRead, remaining);
878 if (result > 0) {
879 if (DEBUG) Log.d(TAG, "read some bytes: " + result);
880 remaining -= result;
881 bytesRead += result;
882 } else {
883 // stop reading ands see what there is to parse
884 Log.w(TAG, "read error: " + result);
885 remaining = 0;
886 }
887 } catch (IOException e) {
888 Log.w(TAG, "failed to read the journal", e);
889 buffer = null;
890 remaining = 0;
891 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400892 }
Chris Wren92aa4232013-10-04 11:29:36 -0400893 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
894
895 if (buffer != null) {
896 try {
897 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, 0, bytesRead));
898 } catch (InvalidProtocolBufferNanoException e) {
899 Log.d(TAG, "failed to read the journal", e);
900 journal.clear();
901 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400902 }
903 }
Chris Wren92aa4232013-10-04 11:29:36 -0400904 } catch (IOException e) {
905 Log.d(TAG, "failed to close the journal", e);
906 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -0400907 try {
908 inStream.close();
909 } catch (IOException e) {
910 Log.d(TAG, "failed to close the journal", e);
911 }
912 }
913 return journal;
914 }
915
Chris Wren22e130d2013-09-23 18:25:57 -0400916 private void writeRowToBackup(Key key, byte[] blob, Journal out,
917 BackupDataOutput data) throws IOException {
918 String backupKey = keyToBackupKey(key);
919 data.writeEntityHeader(backupKey, blob.length);
920 data.writeEntityData(blob, blob.length);
921 out.rows++;
922 out.bytes += blob.length;
923 Log.v(TAG, "saving " + geKeyType(key) + " " + backupKey + ": " +
924 getKeyName(key) + "/" + blob.length);
Chris Wren92aa4232013-10-04 11:29:36 -0400925 if(DEBUG_PAYLOAD) {
Chris Wren2b6c21d2013-10-02 14:16:04 -0400926 String encoded = Base64.encodeToString(blob, 0, blob.length, Base64.NO_WRAP);
927 final int chunkSize = 1024;
928 for (int offset = 0; offset < encoded.length(); offset += chunkSize) {
929 int end = offset + chunkSize;
930 end = Math.min(end, encoded.length());
931 Log.d(TAG, "wrote " + encoded.substring(offset, end));
932 }
933 }
Chris Wren22e130d2013-09-23 18:25:57 -0400934 }
935
936 private Set<String> getSavedIdsByType(int type, Journal in) {
937 Set<String> savedIds = new HashSet<String>();
938 for(int i = 0; i < in.key.length; i++) {
939 Key key = in.key[i];
940 if (key.type == type) {
941 savedIds.add(keyToBackupKey(key));
942 }
943 }
944 return savedIds;
945 }
946
947 private int removeDeletedKeysFromBackup(Set<String> deletedIds, BackupDataOutput data)
948 throws IOException {
949 int rows = 0;
950 for(String deleted: deletedIds) {
951 Log.v(TAG, "dropping icon " + deleted);
952 data.writeEntityHeader(deleted, -1);
953 rows++;
954 }
955 return rows;
956 }
957
Chris Wren1ada10d2013-09-13 18:01:38 -0400958 /**
959 * Write the new journal to the output file.
960 *
961 * In the event of any error, just pretend we didn't have a journal,
962 * in that case, do a full backup.
963
964 * @param newState the write-only file descriptor pointing to the new journal
965 * @param journal a Journal protocol buffer
966 */
967 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
968 FileOutputStream outStream = null;
969 try {
970 outStream = new FileOutputStream(newState.getFileDescriptor());
971 outStream.write(writeCheckedBytes(journal));
972 outStream.close();
973 } catch (IOException e) {
974 Log.d(TAG, "failed to write backup journal", e);
975 }
976 }
977
978 /** Wrap a proto in a CheckedMessage and compute the checksum. */
979 private byte[] writeCheckedBytes(MessageNano proto) {
980 CheckedMessage wrapper = new CheckedMessage();
981 wrapper.payload = MessageNano.toByteArray(proto);
982 CRC32 checksum = new CRC32();
983 checksum.update(wrapper.payload);
984 wrapper.checksum = checksum.getValue();
985 return MessageNano.toByteArray(wrapper);
986 }
987
988 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
989 private byte[] readCheckedBytes(byte[] buffer, int offset, int dataSize)
990 throws InvalidProtocolBufferNanoException {
991 CheckedMessage wrapper = new CheckedMessage();
992 MessageNano.mergeFrom(wrapper, buffer, offset, dataSize);
993 CRC32 checksum = new CRC32();
994 checksum.update(wrapper.payload);
995 if (wrapper.checksum != checksum.getValue()) {
996 throw new InvalidProtocolBufferNanoException("checksum does not match");
997 }
998 return wrapper.payload;
999 }
1000
Chris Wrenfd13c712013-09-27 15:45:19 -04001001 private AppWidgetProviderInfo findAppWidgetProviderInfo(ComponentName component) {
1002 if (mWidgetMap == null) {
1003 List<AppWidgetProviderInfo> widgets =
Chris Wren92aa4232013-10-04 11:29:36 -04001004 AppWidgetManager.getInstance(mContext).getInstalledProviders();
Chris Wrenfd13c712013-09-27 15:45:19 -04001005 mWidgetMap = new HashMap<ComponentName, AppWidgetProviderInfo>(widgets.size());
1006 for (AppWidgetProviderInfo info : widgets) {
1007 mWidgetMap.put(info.provider, info);
1008 }
1009 }
1010 return mWidgetMap.get(component);
1011 }
1012
Chris Wren1ada10d2013-09-13 18:01:38 -04001013 private class KeyParsingException extends Throwable {
1014 private KeyParsingException(Throwable cause) {
1015 super(cause);
1016 }
1017
1018 public KeyParsingException(String reason) {
1019 super(reason);
1020 }
1021 }
1022}