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