blob: 704d790dae9c754bb32525ad8d13e27cf31770e2 [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 Wren22e130d2013-09-23 18:25:57 -0400302 currentIds.add(keyToBackupKey(key));
Chris Wren33f4c2d2014-01-09 11:54:15 -0500303 if (updateTime >= in.t) {
Chris Wren22e130d2013-09-23 18:25:57 -0400304 byte[] blob = packFavorite(cursor);
305 writeRowToBackup(key, blob, out, data);
306 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400307 }
308 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400309 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400310 }
311 if (DEBUG) Log.d(TAG, "favorite currentIds.size()=" + currentIds.size());
312
313 // these IDs must have been deleted
314 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400315 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400316 }
317
318 /**
319 * Read a favorite from the stream.
320 *
321 * <P>Keys arrive in any order, so screens and containers may not exist yet.
322 *
323 * @param key identifier for the row
324 * @param buffer the serialized proto from the stream, may be larger than dataSize
325 * @param dataSize the size of the proto from the stream
326 * @param keys keys to mark as clean in the notes for next backup
327 */
328 private void restoreFavorite(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
329 Log.v(TAG, "unpacking favorite " + key.id + " (" + dataSize + " bytes)");
330 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
331 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
332
333 try {
334 Favorite favorite = unpackFavorite(buffer, 0, dataSize);
335 if (DEBUG) Log.d(TAG, "unpacked " + favorite.itemType);
336 } catch (InvalidProtocolBufferNanoException e) {
337 Log.w(TAG, "failed to decode proto", e);
338 }
339 }
340
341 /**
342 * Write all modified screens to the data stream.
343 *
344 *
345 * @param in notes from last backup
346 * @param data output stream for key/value pairs
347 * @param out notes about this backup
Chris Wren22e130d2013-09-23 18:25:57 -0400348 * @param keys keys to mark as clean in the notes for next backup
349 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400350 */
351 private void backupScreens(Journal in, BackupDataOutput data, Journal out,
352 ArrayList<Key> keys)
353 throws IOException {
354 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400355 Set<String> savedIds = getSavedIdsByType(Key.SCREEN, in);
356 if (DEBUG) Log.d(TAG, "screen savedIds.size()=" + savedIds.size());
Chris Wren1ada10d2013-09-13 18:01:38 -0400357
358 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400359 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400360 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
361 null, null, null);
362 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400363 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400364 cursor.moveToPosition(-1);
365 while(cursor.moveToNext()) {
366 final long id = cursor.getLong(ID_INDEX);
367 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400368 Key key = getKey(Key.SCREEN, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400369 keys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400370 currentIds.add(keyToBackupKey(key));
Chris Wren33f4c2d2014-01-09 11:54:15 -0500371 if (updateTime >= in.t) {
Chris Wren22e130d2013-09-23 18:25:57 -0400372 byte[] blob = packScreen(cursor);
373 writeRowToBackup(key, blob, out, data);
374 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400375 }
376 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400377 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400378 }
379 if (DEBUG) Log.d(TAG, "screen currentIds.size()=" + currentIds.size());
380
381 // these IDs must have been deleted
382 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400383 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400384 }
385
386 /**
387 * Read a screen from the stream.
388 *
389 * <P>Keys arrive in any order, so children of this screen may already exist.
390 *
391 * @param key identifier for the row
392 * @param buffer the serialized proto from the stream, may be larger than dataSize
393 * @param dataSize the size of the proto from the stream
394 * @param keys keys to mark as clean in the notes for next backup
395 */
396 private void restoreScreen(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
397 Log.v(TAG, "unpacking screen " + key.id);
398 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
399 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
400 try {
401 Screen screen = unpackScreen(buffer, 0, dataSize);
402 if (DEBUG) Log.d(TAG, "unpacked " + screen.rank);
403 } catch (InvalidProtocolBufferNanoException e) {
404 Log.w(TAG, "failed to decode proto", e);
405 }
406 }
407
Chris Wren22e130d2013-09-23 18:25:57 -0400408 /**
409 * Write all the static icon resources we need to render placeholders
410 * for a package that is not installed.
411 *
412 * @param in notes from last backup
413 * @param data output stream for key/value pairs
414 * @param out notes about this backup
415 * @param keys keys to mark as clean in the notes for next backup
416 * @throws IOException
417 */
418 private void backupIcons(Journal in, BackupDataOutput data, Journal out,
419 ArrayList<Key> keys) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400420 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400421 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
422 if (appState == null) {
423 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400424 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
425 return;
426 }
Chris Wren92aa4232013-10-04 11:29:36 -0400427 final ContentResolver cr = mContext.getContentResolver();
428 final IconCache iconCache = appState.getIconCache();
429 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wren22e130d2013-09-23 18:25:57 -0400430
431 // read the old ID set
432 Set<String> savedIds = getSavedIdsByType(Key.ICON, in);
433 if (DEBUG) Log.d(TAG, "icon savedIds.size()=" + savedIds.size());
434
435 int startRows = out.rows;
436 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
437 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION;
438 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
439 where, null, null);
440 Set<String> currentIds = new HashSet<String>(cursor.getCount());
441 try {
442 cursor.moveToPosition(-1);
443 while(cursor.moveToNext()) {
444 final long id = cursor.getLong(ID_INDEX);
445 final String intentDescription = cursor.getString(INTENT_INDEX);
446 try {
447 Intent intent = Intent.parseUri(intentDescription, 0);
448 ComponentName cn = intent.getComponent();
449 Key key = null;
450 String backupKey = null;
451 if (cn != null) {
452 key = getKey(Key.ICON, cn.flattenToShortString());
453 backupKey = keyToBackupKey(key);
454 currentIds.add(backupKey);
455 } else {
456 Log.w(TAG, "empty intent on application favorite: " + id);
457 }
458 if (savedIds.contains(backupKey)) {
459 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
460
461 // remember that we already backed this up previously
462 keys.add(key);
463 } else if (backupKey != null) {
464 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
465 if ((out.rows - startRows) < MAX_ICONS_PER_PASS) {
466 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
467 Bitmap icon = iconCache.getIcon(intent);
468 keys.add(key);
469 if (icon != null && !iconCache.isDefaultIcon(icon)) {
470 byte[] blob = packIcon(dpi, icon);
471 writeRowToBackup(key, blob, out, data);
472 }
473 } else {
Chris Wrenfd13c712013-09-27 15:45:19 -0400474 if (DEBUG) Log.d(TAG, "scheduling another run for icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400475 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400476 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400477 }
478 }
479 } catch (URISyntaxException e) {
480 Log.w(TAG, "invalid URI on application favorite: " + id);
481 } catch (IOException e) {
482 Log.w(TAG, "unable to save application icon for favorite: " + id);
483 }
484
485 }
486 } finally {
487 cursor.close();
488 }
489 if (DEBUG) Log.d(TAG, "icon currentIds.size()=" + currentIds.size());
490
491 // these IDs must have been deleted
492 savedIds.removeAll(currentIds);
493 out.rows += removeDeletedKeysFromBackup(savedIds, data);
494 }
495
496 /**
497 * Read an icon from the stream.
498 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400499 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400500 *
501 * @param key identifier for the row
502 * @param buffer the serialized proto from the stream, may be larger than dataSize
503 * @param dataSize the size of the proto from the stream
504 * @param keys keys to mark as clean in the notes for next backup
505 */
506 private void restoreIcon(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
507 Log.v(TAG, "unpacking icon " + key.id);
508 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
509 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
510 try {
511 Resource res = unpackIcon(buffer, 0, dataSize);
512 if (DEBUG) Log.d(TAG, "unpacked " + res.dpi);
513 if (DEBUG) Log.d(TAG, "read " +
514 Base64.encodeToString(res.data, 0, res.data.length,
515 Base64.NO_WRAP));
516 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
517 if (icon == null) {
518 Log.w(TAG, "failed to unpack icon for " + key.name);
519 }
520 } catch (InvalidProtocolBufferNanoException e) {
521 Log.w(TAG, "failed to decode proto", e);
522 }
523 }
524
Chris Wrenfd13c712013-09-27 15:45:19 -0400525 /**
526 * Write all the static widget resources we need to render placeholders
527 * for a package that is not installed.
528 *
529 * @param in notes from last backup
530 * @param data output stream for key/value pairs
531 * @param out notes about this backup
532 * @param keys keys to mark as clean in the notes for next backup
533 * @throws IOException
534 */
535 private void backupWidgets(Journal in, BackupDataOutput data, Journal out,
536 ArrayList<Key> keys) throws IOException {
537 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400538 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
539 if (appState == null) {
Chris Wren92aa4232013-10-04 11:29:36 -0400540 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400541 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying widget backup");
542 return;
543 }
Chris Wren92aa4232013-10-04 11:29:36 -0400544 final ContentResolver cr = mContext.getContentResolver();
545 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
546 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400547 final IconCache iconCache = appState.getIconCache();
Chris Wren92aa4232013-10-04 11:29:36 -0400548 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400549 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
550 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
551
552 // read the old ID set
553 Set<String> savedIds = getSavedIdsByType(Key.WIDGET, in);
554 if (DEBUG) Log.d(TAG, "widgets savedIds.size()=" + savedIds.size());
555
556 int startRows = out.rows;
557 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
558 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET;
559 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
560 where, null, null);
561 Set<String> currentIds = new HashSet<String>(cursor.getCount());
562 try {
563 cursor.moveToPosition(-1);
564 while(cursor.moveToNext()) {
565 final long id = cursor.getLong(ID_INDEX);
566 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
567 final int spanX = cursor.getInt(SPANX_INDEX);
568 final int spanY = cursor.getInt(SPANY_INDEX);
569 final ComponentName provider = ComponentName.unflattenFromString(providerName);
570 Key key = null;
571 String backupKey = null;
572 if (provider != null) {
573 key = getKey(Key.WIDGET, providerName);
574 backupKey = keyToBackupKey(key);
575 currentIds.add(backupKey);
576 } else {
577 Log.w(TAG, "empty intent on appwidget: " + id);
578 }
579 if (savedIds.contains(backupKey)) {
580 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
581
582 // remember that we already backed this up previously
583 keys.add(key);
584 } else if (backupKey != null) {
585 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
586 if ((out.rows - startRows) < MAX_WIDGETS_PER_PASS) {
587 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
588 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
589 spanY * profile.cellHeightPx, widgetSpacingLayout);
590 byte[] blob = packWidget(dpi, previewLoader, iconCache, provider);
Chris Wrenb1fd63b2013-10-03 15:43:58 -0400591 keys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400592 writeRowToBackup(key, blob, out, data);
593
594 } else {
595 if (DEBUG) Log.d(TAG, "scheduling another run for widget " + backupKey);
596 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400597 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400598 }
599 }
600 }
601 } finally {
602 cursor.close();
603 }
604 if (DEBUG) Log.d(TAG, "widget currentIds.size()=" + currentIds.size());
605
606 // these IDs must have been deleted
607 savedIds.removeAll(currentIds);
608 out.rows += removeDeletedKeysFromBackup(savedIds, data);
609 }
610
611 /**
612 * Read a widget from the stream.
613 *
614 * <P>Keys arrive in any order, so widgets that use this data may already exist.
615 *
616 * @param key identifier for the row
617 * @param buffer the serialized proto from the stream, may be larger than dataSize
618 * @param dataSize the size of the proto from the stream
619 * @param keys keys to mark as clean in the notes for next backup
620 */
621 private void restoreWidget(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
622 Log.v(TAG, "unpacking widget " + key.id);
623 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
624 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
625 try {
626 Widget widget = unpackWidget(buffer, 0, dataSize);
627 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
628 if (widget.icon.data != null) {
629 Bitmap icon = BitmapFactory
630 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
631 if (icon == null) {
632 Log.w(TAG, "failed to unpack widget icon for " + key.name);
633 }
634 }
635 } catch (InvalidProtocolBufferNanoException e) {
636 Log.w(TAG, "failed to decode proto", e);
637 }
638 }
639
Chris Wren22e130d2013-09-23 18:25:57 -0400640 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400641 *
642 * <P> Keys contain their own checksum instead of using
643 * the heavy-weight CheckedMessage wrapper.
644 */
645 private Key getKey(int type, long id) {
646 Key key = new Key();
647 key.type = type;
648 key.id = id;
649 key.checksum = checkKey(key);
650 return key;
651 }
652
Chris Wren22e130d2013-09-23 18:25:57 -0400653 /** create a new key for a named object.
654 *
655 * <P> Keys contain their own checksum instead of using
656 * the heavy-weight CheckedMessage wrapper.
657 */
658 private Key getKey(int type, String name) {
659 Key key = new Key();
660 key.type = type;
661 key.name = name;
662 key.checksum = checkKey(key);
663 return key;
664 }
665
Chris Wren1ada10d2013-09-13 18:01:38 -0400666 /** keys need to be strings, serialize and encode. */
667 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400668 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400669 }
670
671 /** keys need to be strings, decode and parse. */
672 private Key backupKeyToKey(String backupKey) throws KeyParsingException {
673 try {
674 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
675 if (key.checksum != checkKey(key)) {
676 key = null;
677 throw new KeyParsingException("invalid key read from stream" + backupKey);
678 }
679 return key;
680 } catch (InvalidProtocolBufferNanoException e) {
681 throw new KeyParsingException(e);
682 } catch (IllegalArgumentException e) {
683 throw new KeyParsingException(e);
684 }
685 }
686
Chris Wren22e130d2013-09-23 18:25:57 -0400687 private String getKeyName(Key key) {
688 if (TextUtils.isEmpty(key.name)) {
689 return Long.toString(key.id);
690 } else {
691 return key.name;
692 }
693
694 }
695
696 private String geKeyType(Key key) {
697 switch (key.type) {
698 case Key.FAVORITE:
699 return "favorite";
700 case Key.SCREEN:
701 return "screen";
702 case Key.ICON:
703 return "icon";
Chris Wrenfd13c712013-09-27 15:45:19 -0400704 case Key.WIDGET:
705 return "widget";
Chris Wren22e130d2013-09-23 18:25:57 -0400706 default:
707 return "anonymous";
708 }
709 }
710
Chris Wren1ada10d2013-09-13 18:01:38 -0400711 /** Compute the checksum over the important bits of a key. */
712 private long checkKey(Key key) {
713 CRC32 checksum = new CRC32();
714 checksum.update(key.type);
715 checksum.update((int) (key.id & 0xffff));
716 checksum.update((int) ((key.id >> 32) & 0xffff));
717 if (!TextUtils.isEmpty(key.name)) {
718 checksum.update(key.name.getBytes());
719 }
720 return checksum.getValue();
721 }
722
723 /** Serialize a Favorite for persistence, including a checksum wrapper. */
724 private byte[] packFavorite(Cursor c) {
725 Favorite favorite = new Favorite();
726 favorite.id = c.getLong(ID_INDEX);
727 favorite.screen = c.getInt(SCREEN_INDEX);
728 favorite.container = c.getInt(CONTAINER_INDEX);
729 favorite.cellX = c.getInt(CELLX_INDEX);
730 favorite.cellY = c.getInt(CELLY_INDEX);
731 favorite.spanX = c.getInt(SPANX_INDEX);
732 favorite.spanY = c.getInt(SPANY_INDEX);
733 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
734 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
735 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
736 if (!TextUtils.isEmpty(iconPackage)) {
737 favorite.iconPackage = iconPackage;
738 }
739 String iconResource = c.getString(ICON_RESOURCE_INDEX);
740 if (!TextUtils.isEmpty(iconResource)) {
741 favorite.iconResource = iconResource;
742 }
743 }
744 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
745 byte[] blob = c.getBlob(ICON_INDEX);
746 if (blob != null && blob.length > 0) {
747 favorite.icon = blob;
748 }
749 }
750 String title = c.getString(TITLE_INDEX);
751 if (!TextUtils.isEmpty(title)) {
752 favorite.title = title;
753 }
754 String intent = c.getString(INTENT_INDEX);
755 if (!TextUtils.isEmpty(intent)) {
756 favorite.intent = intent;
757 }
758 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
759 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
760 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
761 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
762 if (!TextUtils.isEmpty(appWidgetProvider)) {
763 favorite.appWidgetProvider = appWidgetProvider;
764 }
765 }
766
767 return writeCheckedBytes(favorite);
768 }
769
770 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
771 private Favorite unpackFavorite(byte[] buffer, int offset, int dataSize)
772 throws InvalidProtocolBufferNanoException {
773 Favorite favorite = new Favorite();
774 MessageNano.mergeFrom(favorite, readCheckedBytes(buffer, offset, dataSize));
775 return favorite;
776 }
777
778 /** Serialize a Screen for persistence, including a checksum wrapper. */
779 private byte[] packScreen(Cursor c) {
780 Screen screen = new Screen();
781 screen.id = c.getLong(ID_INDEX);
782 screen.rank = c.getInt(SCREEN_RANK_INDEX);
783
784 return writeCheckedBytes(screen);
785 }
786
787 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
788 private Screen unpackScreen(byte[] buffer, int offset, int dataSize)
789 throws InvalidProtocolBufferNanoException {
790 Screen screen = new Screen();
791 MessageNano.mergeFrom(screen, readCheckedBytes(buffer, offset, dataSize));
792 return screen;
793 }
794
Chris Wren22e130d2013-09-23 18:25:57 -0400795 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
796 private byte[] packIcon(int dpi, Bitmap icon) {
797 Resource res = new Resource();
798 res.dpi = dpi;
799 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400800 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400801 res.data = os.toByteArray();
802 }
803 return writeCheckedBytes(res);
804 }
805
806 /** Deserialize an icon resource from persistence, after verifying checksum wrapper. */
807 private Resource unpackIcon(byte[] buffer, int offset, int dataSize)
808 throws InvalidProtocolBufferNanoException {
809 Resource res = new Resource();
810 MessageNano.mergeFrom(res, readCheckedBytes(buffer, offset, dataSize));
811 return res;
812 }
813
Chris Wrenfd13c712013-09-27 15:45:19 -0400814 /** Serialize a widget for persistence, including a checksum wrapper. */
815 private byte[] packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
816 ComponentName provider) {
817 final AppWidgetProviderInfo info = findAppWidgetProviderInfo(provider);
818 Widget widget = new Widget();
819 widget.provider = provider.flattenToShortString();
820 widget.label = info.label;
821 widget.configure = info.configure != null;
822 if (info.icon != 0) {
823 widget.icon = new Resource();
824 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400825 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400826 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400827 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400828 widget.icon.data = os.toByteArray();
829 widget.icon.dpi = dpi;
830 }
831 }
832 if (info.previewImage != 0) {
833 widget.preview = new Resource();
834 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
835 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400836 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400837 widget.preview.data = os.toByteArray();
838 widget.preview.dpi = dpi;
839 }
840 }
841 return writeCheckedBytes(widget);
842 }
843
844 /** Deserialize a widget from persistence, after verifying checksum wrapper. */
845 private Widget unpackWidget(byte[] buffer, int offset, int dataSize)
846 throws InvalidProtocolBufferNanoException {
847 Widget widget = new Widget();
848 MessageNano.mergeFrom(widget, readCheckedBytes(buffer, offset, dataSize));
849 return widget;
850 }
851
Chris Wren1ada10d2013-09-13 18:01:38 -0400852 /**
853 * Read the old journal from the input file.
854 *
855 * In the event of any error, just pretend we didn't have a journal,
856 * in that case, do a full backup.
857 *
858 * @param oldState the read-0only file descriptor pointing to the old journal
859 * @return a Journal protocol bugffer
860 */
861 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400862 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400863 if (oldState == null) {
864 return journal;
865 }
866 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
867 try {
868 int remaining = inStream.available();
869 if (DEBUG) Log.d(TAG, "available " + remaining);
870 if (remaining < MAX_JOURNAL_SIZE) {
871 byte[] buffer = new byte[remaining];
Chris Wren1ada10d2013-09-13 18:01:38 -0400872 int bytesRead = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400873 while (remaining > 0) {
874 try {
875 int result = inStream.read(buffer, bytesRead, remaining);
876 if (result > 0) {
877 if (DEBUG) Log.d(TAG, "read some bytes: " + result);
878 remaining -= result;
879 bytesRead += result;
880 } else {
881 // stop reading ands see what there is to parse
882 Log.w(TAG, "read error: " + result);
883 remaining = 0;
884 }
885 } catch (IOException e) {
886 Log.w(TAG, "failed to read the journal", e);
887 buffer = null;
888 remaining = 0;
889 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400890 }
Chris Wren92aa4232013-10-04 11:29:36 -0400891 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
892
893 if (buffer != null) {
894 try {
895 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, 0, bytesRead));
896 } catch (InvalidProtocolBufferNanoException e) {
897 Log.d(TAG, "failed to read the journal", e);
898 journal.clear();
899 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400900 }
901 }
Chris Wren92aa4232013-10-04 11:29:36 -0400902 } catch (IOException e) {
903 Log.d(TAG, "failed to close the journal", e);
904 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -0400905 try {
906 inStream.close();
907 } catch (IOException e) {
908 Log.d(TAG, "failed to close the journal", e);
909 }
910 }
911 return journal;
912 }
913
Chris Wren22e130d2013-09-23 18:25:57 -0400914 private void writeRowToBackup(Key key, byte[] blob, Journal out,
915 BackupDataOutput data) throws IOException {
916 String backupKey = keyToBackupKey(key);
917 data.writeEntityHeader(backupKey, blob.length);
918 data.writeEntityData(blob, blob.length);
919 out.rows++;
920 out.bytes += blob.length;
921 Log.v(TAG, "saving " + geKeyType(key) + " " + backupKey + ": " +
922 getKeyName(key) + "/" + blob.length);
Chris Wren92aa4232013-10-04 11:29:36 -0400923 if(DEBUG_PAYLOAD) {
Chris Wren2b6c21d2013-10-02 14:16:04 -0400924 String encoded = Base64.encodeToString(blob, 0, blob.length, Base64.NO_WRAP);
925 final int chunkSize = 1024;
926 for (int offset = 0; offset < encoded.length(); offset += chunkSize) {
927 int end = offset + chunkSize;
928 end = Math.min(end, encoded.length());
929 Log.d(TAG, "wrote " + encoded.substring(offset, end));
930 }
931 }
Chris Wren22e130d2013-09-23 18:25:57 -0400932 }
933
934 private Set<String> getSavedIdsByType(int type, Journal in) {
935 Set<String> savedIds = new HashSet<String>();
936 for(int i = 0; i < in.key.length; i++) {
937 Key key = in.key[i];
938 if (key.type == type) {
939 savedIds.add(keyToBackupKey(key));
940 }
941 }
942 return savedIds;
943 }
944
945 private int removeDeletedKeysFromBackup(Set<String> deletedIds, BackupDataOutput data)
946 throws IOException {
947 int rows = 0;
948 for(String deleted: deletedIds) {
949 Log.v(TAG, "dropping icon " + deleted);
950 data.writeEntityHeader(deleted, -1);
951 rows++;
952 }
953 return rows;
954 }
955
Chris Wren1ada10d2013-09-13 18:01:38 -0400956 /**
957 * Write the new journal to the output file.
958 *
959 * In the event of any error, just pretend we didn't have a journal,
960 * in that case, do a full backup.
961
962 * @param newState the write-only file descriptor pointing to the new journal
963 * @param journal a Journal protocol buffer
964 */
965 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
966 FileOutputStream outStream = null;
967 try {
968 outStream = new FileOutputStream(newState.getFileDescriptor());
969 outStream.write(writeCheckedBytes(journal));
970 outStream.close();
971 } catch (IOException e) {
972 Log.d(TAG, "failed to write backup journal", e);
973 }
974 }
975
976 /** Wrap a proto in a CheckedMessage and compute the checksum. */
977 private byte[] writeCheckedBytes(MessageNano proto) {
978 CheckedMessage wrapper = new CheckedMessage();
979 wrapper.payload = MessageNano.toByteArray(proto);
980 CRC32 checksum = new CRC32();
981 checksum.update(wrapper.payload);
982 wrapper.checksum = checksum.getValue();
983 return MessageNano.toByteArray(wrapper);
984 }
985
986 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
987 private byte[] readCheckedBytes(byte[] buffer, int offset, int dataSize)
988 throws InvalidProtocolBufferNanoException {
989 CheckedMessage wrapper = new CheckedMessage();
990 MessageNano.mergeFrom(wrapper, buffer, offset, dataSize);
991 CRC32 checksum = new CRC32();
992 checksum.update(wrapper.payload);
993 if (wrapper.checksum != checksum.getValue()) {
994 throw new InvalidProtocolBufferNanoException("checksum does not match");
995 }
996 return wrapper.payload;
997 }
998
Chris Wrenfd13c712013-09-27 15:45:19 -0400999 private AppWidgetProviderInfo findAppWidgetProviderInfo(ComponentName component) {
1000 if (mWidgetMap == null) {
1001 List<AppWidgetProviderInfo> widgets =
Chris Wren92aa4232013-10-04 11:29:36 -04001002 AppWidgetManager.getInstance(mContext).getInstalledProviders();
Chris Wrenfd13c712013-09-27 15:45:19 -04001003 mWidgetMap = new HashMap<ComponentName, AppWidgetProviderInfo>(widgets.size());
1004 for (AppWidgetProviderInfo info : widgets) {
1005 mWidgetMap.put(info.provider, info);
1006 }
1007 }
1008 return mWidgetMap.get(component);
1009 }
1010
Chris Wren1ada10d2013-09-13 18:01:38 -04001011 private class KeyParsingException extends Throwable {
1012 private KeyParsingException(Throwable cause) {
1013 super(cause);
1014 }
1015
1016 public KeyParsingException(String reason) {
1017 super(reason);
1018 }
1019 }
1020}