blob: 2a5ed69615720fc863bf59c3482452bf499191e1 [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 Wren22e130d2013-09-23 18:25:57 -0400140 private HashMap<ComponentName, AppWidgetProviderInfo> mWidgetMap;
141
Chris Wren92aa4232013-10-04 11:29:36 -0400142 private ArrayList<Key> mKeys;
Chris Wren1ada10d2013-09-13 18:01:38 -0400143
Chris Wren92aa4232013-10-04 11:29:36 -0400144 public LauncherBackupHelper(Context context) {
145 mContext = context;
146 }
147
148 private void dataChanged() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400149 if (sBackupManager == null) {
Chris Wren92aa4232013-10-04 11:29:36 -0400150 sBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400151 }
152 sBackupManager.dataChanged();
153 }
154
155 /**
156 * Back up launcher data so we can restore the user's state on a new device.
157 *
158 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
159 *
160 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
161 *
162 * @param oldState notes from the last backup
163 * @param data incremental key/value pairs to persist off-device
164 * @param newState notes for the next backup
165 * @throws IOException
166 */
167 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400168 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
169 ParcelFileDescriptor newState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400170 Log.v(TAG, "onBackup");
171
172 Journal in = readJournal(oldState);
173 Journal out = new Journal();
174
175 long lastBackupTime = in.t;
176 out.t = System.currentTimeMillis();
177 out.rows = 0;
178 out.bytes = 0;
179
180 Log.v(TAG, "lastBackupTime=" + lastBackupTime);
181
182 ArrayList<Key> keys = new ArrayList<Key>();
Chris Wren92aa4232013-10-04 11:29:36 -0400183 try {
184 backupFavorites(in, data, out, keys);
185 backupScreens(in, data, out, keys);
186 backupIcons(in, data, out, keys);
187 backupWidgets(in, data, out, keys);
188 } catch (IOException e) {
189 Log.e(TAG, "launcher backup has failed", e);
190 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400191
192 out.key = keys.toArray(BackupProtos.Key.EMPTY_ARRAY);
193 writeJournal(newState, out);
194 Log.v(TAG, "onBackup: wrote " + out.bytes + "b in " + out.rows + " rows.");
Chris Wren1ada10d2013-09-13 18:01:38 -0400195 }
196
197 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400198 * Restore launcher configuration from the restored data stream.
Chris Wren1ada10d2013-09-13 18:01:38 -0400199 *
200 * <P>Keys may arrive in any order.
201 *
Chris Wren92aa4232013-10-04 11:29:36 -0400202 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400203 */
204 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400205 public void restoreEntity(BackupDataInputStream data) {
206 Log.v(TAG, "restoreEntity");
207 if (mKeys == null) {
208 mKeys = new ArrayList<Key>();
209 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400210 byte[] buffer = new byte[512];
Chris Wren1ada10d2013-09-13 18:01:38 -0400211 String backupKey = data.getKey();
Chris Wren92aa4232013-10-04 11:29:36 -0400212 int dataSize = data.size();
Chris Wren1ada10d2013-09-13 18:01:38 -0400213 if (buffer.length < dataSize) {
214 buffer = new byte[dataSize];
215 }
216 Key key = null;
Chris Wren92aa4232013-10-04 11:29:36 -0400217 int bytesRead = 0;
218 try {
219 bytesRead = data.read(buffer, 0, dataSize);
220 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
221 } catch (IOException e) {
222 Log.d(TAG, "failed to read entity from restore data", e);
223 }
224 try {
225 key = backupKeyToKey(backupKey);
226 switch (key.type) {
227 case Key.FAVORITE:
228 restoreFavorite(key, buffer, dataSize, mKeys);
229 break;
230
231 case Key.SCREEN:
232 restoreScreen(key, buffer, dataSize, mKeys);
233 break;
234
235 case Key.ICON:
236 restoreIcon(key, buffer, dataSize, mKeys);
237 break;
238
239 case Key.WIDGET:
240 restoreWidget(key, buffer, dataSize, mKeys);
241 break;
242
243 default:
244 Log.w(TAG, "unknown restore entity type: " + key.type);
245 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400246 }
Chris Wren92aa4232013-10-04 11:29:36 -0400247 } catch (KeyParsingException e) {
248 Log.w(TAG, "ignoring unparsable backup key: " + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400249 }
250
Chris Wren92aa4232013-10-04 11:29:36 -0400251 }
252
253 /**
254 * Record the restore state for the next backup.
255 *
256 * @param newState notes about the backup state after restore.
257 */
258 @Override
259 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400260 // clear the output journal time, to force a full backup to
261 // will catch any changes the restore process might have made
Chris Wren92aa4232013-10-04 11:29:36 -0400262 Journal out = new Journal();
Chris Wren1ada10d2013-09-13 18:01:38 -0400263 out.t = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400264 out.key = mKeys.toArray(BackupProtos.Key.EMPTY_ARRAY);
Chris Wren1ada10d2013-09-13 18:01:38 -0400265 writeJournal(newState, out);
Chris Wren92aa4232013-10-04 11:29:36 -0400266 Log.v(TAG, "onRestore: read " + mKeys.size() + " rows");
267 mKeys.clear();
Chris Wren1ada10d2013-09-13 18:01:38 -0400268 }
269
270 /**
271 * Write all modified favorites to the data stream.
272 *
273 *
274 * @param in notes from last backup
275 * @param data output stream for key/value pairs
276 * @param out notes about this backup
277 * @param keys keys to mark as clean in the notes for next backup
278 * @throws IOException
279 */
280 private void backupFavorites(Journal in, BackupDataOutput data, Journal out,
281 ArrayList<Key> keys)
282 throws IOException {
283 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400284 Set<String> savedIds = getSavedIdsByType(Key.FAVORITE, in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400285 if (DEBUG) Log.d(TAG, "favorite savedIds.size()=" + savedIds.size());
286
287 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400288 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400289 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
290 null, null, null);
291 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400292 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400293 cursor.moveToPosition(-1);
294 while(cursor.moveToNext()) {
295 final long id = cursor.getLong(ID_INDEX);
296 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400297 Key key = getKey(Key.FAVORITE, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400298 keys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400299 currentIds.add(keyToBackupKey(key));
300 if (updateTime > in.t) {
301 byte[] blob = packFavorite(cursor);
302 writeRowToBackup(key, blob, out, data);
303 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400304 }
305 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400306 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400307 }
308 if (DEBUG) Log.d(TAG, "favorite currentIds.size()=" + currentIds.size());
309
310 // these IDs must have been deleted
311 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400312 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400313 }
314
315 /**
316 * Read a favorite from the stream.
317 *
318 * <P>Keys arrive in any order, so screens and containers may not exist yet.
319 *
320 * @param key identifier for the row
321 * @param buffer the serialized proto from the stream, may be larger than dataSize
322 * @param dataSize the size of the proto from the stream
323 * @param keys keys to mark as clean in the notes for next backup
324 */
325 private void restoreFavorite(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
326 Log.v(TAG, "unpacking favorite " + key.id + " (" + dataSize + " bytes)");
327 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
328 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
329
330 try {
331 Favorite favorite = unpackFavorite(buffer, 0, dataSize);
332 if (DEBUG) Log.d(TAG, "unpacked " + favorite.itemType);
333 } catch (InvalidProtocolBufferNanoException e) {
334 Log.w(TAG, "failed to decode proto", e);
335 }
336 }
337
338 /**
339 * Write all modified screens to the data stream.
340 *
341 *
342 * @param in notes from last backup
343 * @param data output stream for key/value pairs
344 * @param out notes about this backup
Chris Wren22e130d2013-09-23 18:25:57 -0400345 * @param keys keys to mark as clean in the notes for next backup
346 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400347 */
348 private void backupScreens(Journal in, BackupDataOutput data, Journal out,
349 ArrayList<Key> keys)
350 throws IOException {
351 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400352 Set<String> savedIds = getSavedIdsByType(Key.SCREEN, in);
353 if (DEBUG) Log.d(TAG, "screen savedIds.size()=" + savedIds.size());
Chris Wren1ada10d2013-09-13 18:01:38 -0400354
355 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400356 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400357 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
358 null, null, null);
359 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400360 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400361 cursor.moveToPosition(-1);
362 while(cursor.moveToNext()) {
363 final long id = cursor.getLong(ID_INDEX);
364 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400365 Key key = getKey(Key.SCREEN, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400366 keys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400367 currentIds.add(keyToBackupKey(key));
368 if (updateTime > in.t) {
369 byte[] blob = packScreen(cursor);
370 writeRowToBackup(key, blob, out, data);
371 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400372 }
373 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400374 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400375 }
376 if (DEBUG) Log.d(TAG, "screen currentIds.size()=" + currentIds.size());
377
378 // these IDs must have been deleted
379 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400380 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400381 }
382
383 /**
384 * Read a screen from the stream.
385 *
386 * <P>Keys arrive in any order, so children of this screen may already exist.
387 *
388 * @param key identifier for the row
389 * @param buffer the serialized proto from the stream, may be larger than dataSize
390 * @param dataSize the size of the proto from the stream
391 * @param keys keys to mark as clean in the notes for next backup
392 */
393 private void restoreScreen(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
394 Log.v(TAG, "unpacking screen " + key.id);
395 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
396 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
397 try {
398 Screen screen = unpackScreen(buffer, 0, dataSize);
399 if (DEBUG) Log.d(TAG, "unpacked " + screen.rank);
400 } catch (InvalidProtocolBufferNanoException e) {
401 Log.w(TAG, "failed to decode proto", e);
402 }
403 }
404
Chris Wren22e130d2013-09-23 18:25:57 -0400405 /**
406 * Write all the static icon resources we need to render placeholders
407 * for a package that is not installed.
408 *
409 * @param in notes from last backup
410 * @param data output stream for key/value pairs
411 * @param out notes about this backup
412 * @param keys keys to mark as clean in the notes for next backup
413 * @throws IOException
414 */
415 private void backupIcons(Journal in, BackupDataOutput data, Journal out,
416 ArrayList<Key> keys) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400417 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400418 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
419 if (appState == null) {
420 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400421 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
422 return;
423 }
Chris Wren92aa4232013-10-04 11:29:36 -0400424 final ContentResolver cr = mContext.getContentResolver();
425 final IconCache iconCache = appState.getIconCache();
426 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wren22e130d2013-09-23 18:25:57 -0400427
428 // read the old ID set
429 Set<String> savedIds = getSavedIdsByType(Key.ICON, in);
430 if (DEBUG) Log.d(TAG, "icon savedIds.size()=" + savedIds.size());
431
432 int startRows = out.rows;
433 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
434 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION;
435 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
436 where, null, null);
437 Set<String> currentIds = new HashSet<String>(cursor.getCount());
438 try {
439 cursor.moveToPosition(-1);
440 while(cursor.moveToNext()) {
441 final long id = cursor.getLong(ID_INDEX);
442 final String intentDescription = cursor.getString(INTENT_INDEX);
443 try {
444 Intent intent = Intent.parseUri(intentDescription, 0);
445 ComponentName cn = intent.getComponent();
446 Key key = null;
447 String backupKey = null;
448 if (cn != null) {
449 key = getKey(Key.ICON, cn.flattenToShortString());
450 backupKey = keyToBackupKey(key);
451 currentIds.add(backupKey);
452 } else {
453 Log.w(TAG, "empty intent on application favorite: " + id);
454 }
455 if (savedIds.contains(backupKey)) {
456 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
457
458 // remember that we already backed this up previously
459 keys.add(key);
460 } else if (backupKey != null) {
461 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
462 if ((out.rows - startRows) < MAX_ICONS_PER_PASS) {
463 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
464 Bitmap icon = iconCache.getIcon(intent);
465 keys.add(key);
466 if (icon != null && !iconCache.isDefaultIcon(icon)) {
467 byte[] blob = packIcon(dpi, icon);
468 writeRowToBackup(key, blob, out, data);
469 }
470 } else {
Chris Wrenfd13c712013-09-27 15:45:19 -0400471 if (DEBUG) Log.d(TAG, "scheduling another run for icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400472 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400473 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400474 }
475 }
476 } catch (URISyntaxException e) {
477 Log.w(TAG, "invalid URI on application favorite: " + id);
478 } catch (IOException e) {
479 Log.w(TAG, "unable to save application icon for favorite: " + id);
480 }
481
482 }
483 } finally {
484 cursor.close();
485 }
486 if (DEBUG) Log.d(TAG, "icon currentIds.size()=" + currentIds.size());
487
488 // these IDs must have been deleted
489 savedIds.removeAll(currentIds);
490 out.rows += removeDeletedKeysFromBackup(savedIds, data);
491 }
492
493 /**
494 * Read an icon from the stream.
495 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400496 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400497 *
498 * @param key identifier for the row
499 * @param buffer the serialized proto from the stream, may be larger than dataSize
500 * @param dataSize the size of the proto from the stream
501 * @param keys keys to mark as clean in the notes for next backup
502 */
503 private void restoreIcon(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
504 Log.v(TAG, "unpacking icon " + key.id);
505 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
506 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
507 try {
508 Resource res = unpackIcon(buffer, 0, dataSize);
509 if (DEBUG) Log.d(TAG, "unpacked " + res.dpi);
510 if (DEBUG) Log.d(TAG, "read " +
511 Base64.encodeToString(res.data, 0, res.data.length,
512 Base64.NO_WRAP));
513 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
514 if (icon == null) {
515 Log.w(TAG, "failed to unpack icon for " + key.name);
516 }
517 } catch (InvalidProtocolBufferNanoException e) {
518 Log.w(TAG, "failed to decode proto", e);
519 }
520 }
521
Chris Wrenfd13c712013-09-27 15:45:19 -0400522 /**
523 * Write all the static widget resources we need to render placeholders
524 * for a package that is not installed.
525 *
526 * @param in notes from last backup
527 * @param data output stream for key/value pairs
528 * @param out notes about this backup
529 * @param keys keys to mark as clean in the notes for next backup
530 * @throws IOException
531 */
532 private void backupWidgets(Journal in, BackupDataOutput data, Journal out,
533 ArrayList<Key> keys) throws IOException {
534 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400535 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
536 if (appState == null) {
Chris Wren92aa4232013-10-04 11:29:36 -0400537 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400538 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying widget backup");
539 return;
540 }
Chris Wren92aa4232013-10-04 11:29:36 -0400541 final ContentResolver cr = mContext.getContentResolver();
542 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
543 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400544 final IconCache iconCache = appState.getIconCache();
Chris Wren92aa4232013-10-04 11:29:36 -0400545 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400546 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
547 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
548
549 // read the old ID set
550 Set<String> savedIds = getSavedIdsByType(Key.WIDGET, in);
551 if (DEBUG) Log.d(TAG, "widgets savedIds.size()=" + savedIds.size());
552
553 int startRows = out.rows;
554 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
555 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET;
556 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
557 where, null, null);
558 Set<String> currentIds = new HashSet<String>(cursor.getCount());
559 try {
560 cursor.moveToPosition(-1);
561 while(cursor.moveToNext()) {
562 final long id = cursor.getLong(ID_INDEX);
563 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
564 final int spanX = cursor.getInt(SPANX_INDEX);
565 final int spanY = cursor.getInt(SPANY_INDEX);
566 final ComponentName provider = ComponentName.unflattenFromString(providerName);
567 Key key = null;
568 String backupKey = null;
569 if (provider != null) {
570 key = getKey(Key.WIDGET, providerName);
571 backupKey = keyToBackupKey(key);
572 currentIds.add(backupKey);
573 } else {
574 Log.w(TAG, "empty intent on appwidget: " + id);
575 }
576 if (savedIds.contains(backupKey)) {
577 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
578
579 // remember that we already backed this up previously
580 keys.add(key);
581 } else if (backupKey != null) {
582 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
583 if ((out.rows - startRows) < MAX_WIDGETS_PER_PASS) {
584 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
585 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
586 spanY * profile.cellHeightPx, widgetSpacingLayout);
587 byte[] blob = packWidget(dpi, previewLoader, iconCache, provider);
Chris Wrenb1fd63b2013-10-03 15:43:58 -0400588 keys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400589 writeRowToBackup(key, blob, out, data);
590
591 } else {
592 if (DEBUG) Log.d(TAG, "scheduling another run for widget " + backupKey);
593 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400594 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400595 }
596 }
597 }
598 } finally {
599 cursor.close();
600 }
601 if (DEBUG) Log.d(TAG, "widget currentIds.size()=" + currentIds.size());
602
603 // these IDs must have been deleted
604 savedIds.removeAll(currentIds);
605 out.rows += removeDeletedKeysFromBackup(savedIds, data);
606 }
607
608 /**
609 * Read a widget from the stream.
610 *
611 * <P>Keys arrive in any order, so widgets that use this data may already exist.
612 *
613 * @param key identifier for the row
614 * @param buffer the serialized proto from the stream, may be larger than dataSize
615 * @param dataSize the size of the proto from the stream
616 * @param keys keys to mark as clean in the notes for next backup
617 */
618 private void restoreWidget(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
619 Log.v(TAG, "unpacking widget " + key.id);
620 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
621 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
622 try {
623 Widget widget = unpackWidget(buffer, 0, dataSize);
624 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
625 if (widget.icon.data != null) {
626 Bitmap icon = BitmapFactory
627 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
628 if (icon == null) {
629 Log.w(TAG, "failed to unpack widget icon for " + key.name);
630 }
631 }
632 } catch (InvalidProtocolBufferNanoException e) {
633 Log.w(TAG, "failed to decode proto", e);
634 }
635 }
636
Chris Wren22e130d2013-09-23 18:25:57 -0400637 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400638 *
639 * <P> Keys contain their own checksum instead of using
640 * the heavy-weight CheckedMessage wrapper.
641 */
642 private Key getKey(int type, long id) {
643 Key key = new Key();
644 key.type = type;
645 key.id = id;
646 key.checksum = checkKey(key);
647 return key;
648 }
649
Chris Wren22e130d2013-09-23 18:25:57 -0400650 /** create a new key for a named object.
651 *
652 * <P> Keys contain their own checksum instead of using
653 * the heavy-weight CheckedMessage wrapper.
654 */
655 private Key getKey(int type, String name) {
656 Key key = new Key();
657 key.type = type;
658 key.name = name;
659 key.checksum = checkKey(key);
660 return key;
661 }
662
Chris Wren1ada10d2013-09-13 18:01:38 -0400663 /** keys need to be strings, serialize and encode. */
664 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400665 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400666 }
667
668 /** keys need to be strings, decode and parse. */
669 private Key backupKeyToKey(String backupKey) throws KeyParsingException {
670 try {
671 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
672 if (key.checksum != checkKey(key)) {
673 key = null;
674 throw new KeyParsingException("invalid key read from stream" + backupKey);
675 }
676 return key;
677 } catch (InvalidProtocolBufferNanoException e) {
678 throw new KeyParsingException(e);
679 } catch (IllegalArgumentException e) {
680 throw new KeyParsingException(e);
681 }
682 }
683
Chris Wren22e130d2013-09-23 18:25:57 -0400684 private String getKeyName(Key key) {
685 if (TextUtils.isEmpty(key.name)) {
686 return Long.toString(key.id);
687 } else {
688 return key.name;
689 }
690
691 }
692
693 private String geKeyType(Key key) {
694 switch (key.type) {
695 case Key.FAVORITE:
696 return "favorite";
697 case Key.SCREEN:
698 return "screen";
699 case Key.ICON:
700 return "icon";
Chris Wrenfd13c712013-09-27 15:45:19 -0400701 case Key.WIDGET:
702 return "widget";
Chris Wren22e130d2013-09-23 18:25:57 -0400703 default:
704 return "anonymous";
705 }
706 }
707
Chris Wren1ada10d2013-09-13 18:01:38 -0400708 /** Compute the checksum over the important bits of a key. */
709 private long checkKey(Key key) {
710 CRC32 checksum = new CRC32();
711 checksum.update(key.type);
712 checksum.update((int) (key.id & 0xffff));
713 checksum.update((int) ((key.id >> 32) & 0xffff));
714 if (!TextUtils.isEmpty(key.name)) {
715 checksum.update(key.name.getBytes());
716 }
717 return checksum.getValue();
718 }
719
720 /** Serialize a Favorite for persistence, including a checksum wrapper. */
721 private byte[] packFavorite(Cursor c) {
722 Favorite favorite = new Favorite();
723 favorite.id = c.getLong(ID_INDEX);
724 favorite.screen = c.getInt(SCREEN_INDEX);
725 favorite.container = c.getInt(CONTAINER_INDEX);
726 favorite.cellX = c.getInt(CELLX_INDEX);
727 favorite.cellY = c.getInt(CELLY_INDEX);
728 favorite.spanX = c.getInt(SPANX_INDEX);
729 favorite.spanY = c.getInt(SPANY_INDEX);
730 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
731 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
732 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
733 if (!TextUtils.isEmpty(iconPackage)) {
734 favorite.iconPackage = iconPackage;
735 }
736 String iconResource = c.getString(ICON_RESOURCE_INDEX);
737 if (!TextUtils.isEmpty(iconResource)) {
738 favorite.iconResource = iconResource;
739 }
740 }
741 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
742 byte[] blob = c.getBlob(ICON_INDEX);
743 if (blob != null && blob.length > 0) {
744 favorite.icon = blob;
745 }
746 }
747 String title = c.getString(TITLE_INDEX);
748 if (!TextUtils.isEmpty(title)) {
749 favorite.title = title;
750 }
751 String intent = c.getString(INTENT_INDEX);
752 if (!TextUtils.isEmpty(intent)) {
753 favorite.intent = intent;
754 }
755 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
756 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
757 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
758 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
759 if (!TextUtils.isEmpty(appWidgetProvider)) {
760 favorite.appWidgetProvider = appWidgetProvider;
761 }
762 }
763
764 return writeCheckedBytes(favorite);
765 }
766
767 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
768 private Favorite unpackFavorite(byte[] buffer, int offset, int dataSize)
769 throws InvalidProtocolBufferNanoException {
770 Favorite favorite = new Favorite();
771 MessageNano.mergeFrom(favorite, readCheckedBytes(buffer, offset, dataSize));
772 return favorite;
773 }
774
775 /** Serialize a Screen for persistence, including a checksum wrapper. */
776 private byte[] packScreen(Cursor c) {
777 Screen screen = new Screen();
778 screen.id = c.getLong(ID_INDEX);
779 screen.rank = c.getInt(SCREEN_RANK_INDEX);
780
781 return writeCheckedBytes(screen);
782 }
783
784 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
785 private Screen unpackScreen(byte[] buffer, int offset, int dataSize)
786 throws InvalidProtocolBufferNanoException {
787 Screen screen = new Screen();
788 MessageNano.mergeFrom(screen, readCheckedBytes(buffer, offset, dataSize));
789 return screen;
790 }
791
Chris Wren22e130d2013-09-23 18:25:57 -0400792 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
793 private byte[] packIcon(int dpi, Bitmap icon) {
794 Resource res = new Resource();
795 res.dpi = dpi;
796 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400797 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400798 res.data = os.toByteArray();
799 }
800 return writeCheckedBytes(res);
801 }
802
803 /** Deserialize an icon resource from persistence, after verifying checksum wrapper. */
804 private Resource unpackIcon(byte[] buffer, int offset, int dataSize)
805 throws InvalidProtocolBufferNanoException {
806 Resource res = new Resource();
807 MessageNano.mergeFrom(res, readCheckedBytes(buffer, offset, dataSize));
808 return res;
809 }
810
Chris Wrenfd13c712013-09-27 15:45:19 -0400811 /** Serialize a widget for persistence, including a checksum wrapper. */
812 private byte[] packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
813 ComponentName provider) {
814 final AppWidgetProviderInfo info = findAppWidgetProviderInfo(provider);
815 Widget widget = new Widget();
816 widget.provider = provider.flattenToShortString();
817 widget.label = info.label;
818 widget.configure = info.configure != null;
819 if (info.icon != 0) {
820 widget.icon = new Resource();
821 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400822 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400823 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400824 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400825 widget.icon.data = os.toByteArray();
826 widget.icon.dpi = dpi;
827 }
828 }
829 if (info.previewImage != 0) {
830 widget.preview = new Resource();
831 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
832 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400833 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400834 widget.preview.data = os.toByteArray();
835 widget.preview.dpi = dpi;
836 }
837 }
838 return writeCheckedBytes(widget);
839 }
840
841 /** Deserialize a widget from persistence, after verifying checksum wrapper. */
842 private Widget unpackWidget(byte[] buffer, int offset, int dataSize)
843 throws InvalidProtocolBufferNanoException {
844 Widget widget = new Widget();
845 MessageNano.mergeFrom(widget, readCheckedBytes(buffer, offset, dataSize));
846 return widget;
847 }
848
Chris Wren1ada10d2013-09-13 18:01:38 -0400849 /**
850 * Read the old journal from the input file.
851 *
852 * In the event of any error, just pretend we didn't have a journal,
853 * in that case, do a full backup.
854 *
855 * @param oldState the read-0only file descriptor pointing to the old journal
856 * @return a Journal protocol bugffer
857 */
858 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400859 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400860 if (oldState == null) {
861 return journal;
862 }
863 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
864 try {
865 int remaining = inStream.available();
866 if (DEBUG) Log.d(TAG, "available " + remaining);
867 if (remaining < MAX_JOURNAL_SIZE) {
868 byte[] buffer = new byte[remaining];
Chris Wren1ada10d2013-09-13 18:01:38 -0400869 int bytesRead = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400870 while (remaining > 0) {
871 try {
872 int result = inStream.read(buffer, bytesRead, remaining);
873 if (result > 0) {
874 if (DEBUG) Log.d(TAG, "read some bytes: " + result);
875 remaining -= result;
876 bytesRead += result;
877 } else {
878 // stop reading ands see what there is to parse
879 Log.w(TAG, "read error: " + result);
880 remaining = 0;
881 }
882 } catch (IOException e) {
883 Log.w(TAG, "failed to read the journal", e);
884 buffer = null;
885 remaining = 0;
886 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400887 }
Chris Wren92aa4232013-10-04 11:29:36 -0400888 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
889
890 if (buffer != null) {
891 try {
892 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, 0, bytesRead));
893 } catch (InvalidProtocolBufferNanoException e) {
894 Log.d(TAG, "failed to read the journal", e);
895 journal.clear();
896 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400897 }
898 }
Chris Wren92aa4232013-10-04 11:29:36 -0400899 } catch (IOException e) {
900 Log.d(TAG, "failed to close the journal", e);
901 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -0400902 try {
903 inStream.close();
904 } catch (IOException e) {
905 Log.d(TAG, "failed to close the journal", e);
906 }
907 }
908 return journal;
909 }
910
Chris Wren22e130d2013-09-23 18:25:57 -0400911 private void writeRowToBackup(Key key, byte[] blob, Journal out,
912 BackupDataOutput data) throws IOException {
913 String backupKey = keyToBackupKey(key);
914 data.writeEntityHeader(backupKey, blob.length);
915 data.writeEntityData(blob, blob.length);
916 out.rows++;
917 out.bytes += blob.length;
918 Log.v(TAG, "saving " + geKeyType(key) + " " + backupKey + ": " +
919 getKeyName(key) + "/" + blob.length);
Chris Wren92aa4232013-10-04 11:29:36 -0400920 if(DEBUG_PAYLOAD) {
Chris Wren2b6c21d2013-10-02 14:16:04 -0400921 String encoded = Base64.encodeToString(blob, 0, blob.length, Base64.NO_WRAP);
922 final int chunkSize = 1024;
923 for (int offset = 0; offset < encoded.length(); offset += chunkSize) {
924 int end = offset + chunkSize;
925 end = Math.min(end, encoded.length());
926 Log.d(TAG, "wrote " + encoded.substring(offset, end));
927 }
928 }
Chris Wren22e130d2013-09-23 18:25:57 -0400929 }
930
931 private Set<String> getSavedIdsByType(int type, Journal in) {
932 Set<String> savedIds = new HashSet<String>();
933 for(int i = 0; i < in.key.length; i++) {
934 Key key = in.key[i];
935 if (key.type == type) {
936 savedIds.add(keyToBackupKey(key));
937 }
938 }
939 return savedIds;
940 }
941
942 private int removeDeletedKeysFromBackup(Set<String> deletedIds, BackupDataOutput data)
943 throws IOException {
944 int rows = 0;
945 for(String deleted: deletedIds) {
946 Log.v(TAG, "dropping icon " + deleted);
947 data.writeEntityHeader(deleted, -1);
948 rows++;
949 }
950 return rows;
951 }
952
Chris Wren1ada10d2013-09-13 18:01:38 -0400953 /**
954 * Write the new journal to the output file.
955 *
956 * In the event of any error, just pretend we didn't have a journal,
957 * in that case, do a full backup.
958
959 * @param newState the write-only file descriptor pointing to the new journal
960 * @param journal a Journal protocol buffer
961 */
962 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
963 FileOutputStream outStream = null;
964 try {
965 outStream = new FileOutputStream(newState.getFileDescriptor());
966 outStream.write(writeCheckedBytes(journal));
967 outStream.close();
968 } catch (IOException e) {
969 Log.d(TAG, "failed to write backup journal", e);
970 }
971 }
972
973 /** Wrap a proto in a CheckedMessage and compute the checksum. */
974 private byte[] writeCheckedBytes(MessageNano proto) {
975 CheckedMessage wrapper = new CheckedMessage();
976 wrapper.payload = MessageNano.toByteArray(proto);
977 CRC32 checksum = new CRC32();
978 checksum.update(wrapper.payload);
979 wrapper.checksum = checksum.getValue();
980 return MessageNano.toByteArray(wrapper);
981 }
982
983 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
984 private byte[] readCheckedBytes(byte[] buffer, int offset, int dataSize)
985 throws InvalidProtocolBufferNanoException {
986 CheckedMessage wrapper = new CheckedMessage();
987 MessageNano.mergeFrom(wrapper, buffer, offset, dataSize);
988 CRC32 checksum = new CRC32();
989 checksum.update(wrapper.payload);
990 if (wrapper.checksum != checksum.getValue()) {
991 throw new InvalidProtocolBufferNanoException("checksum does not match");
992 }
993 return wrapper.payload;
994 }
995
Chris Wrenfd13c712013-09-27 15:45:19 -0400996 private AppWidgetProviderInfo findAppWidgetProviderInfo(ComponentName component) {
997 if (mWidgetMap == null) {
998 List<AppWidgetProviderInfo> widgets =
Chris Wren92aa4232013-10-04 11:29:36 -0400999 AppWidgetManager.getInstance(mContext).getInstalledProviders();
Chris Wrenfd13c712013-09-27 15:45:19 -04001000 mWidgetMap = new HashMap<ComponentName, AppWidgetProviderInfo>(widgets.size());
1001 for (AppWidgetProviderInfo info : widgets) {
1002 mWidgetMap.put(info.provider, info);
1003 }
1004 }
1005 return mWidgetMap.get(component);
1006 }
1007
Chris Wren1ada10d2013-09-13 18:01:38 -04001008 private class KeyParsingException extends Throwable {
1009 private KeyParsingException(Throwable cause) {
1010 super(cause);
1011 }
1012
1013 public KeyParsingException(String reason) {
1014 super(reason);
1015 }
1016 }
1017}