blob: f29bb1fad4be5bce8dda1427eedcc02d8748f7b2 [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
33import android.app.backup.BackupAgent;
34import android.app.backup.BackupDataInput;
35import android.app.backup.BackupDataOutput;
36import 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 */
67public class LauncherBackupAgent extends BackupAgent {
68
69 private static final String TAG = "LauncherBackupAgent";
Chris Wrenfd13c712013-09-27 15:45:19 -040070 private static final boolean DEBUG = false;
Chris Wren1ada10d2013-09-13 18:01:38 -040071
72 private static final int MAX_JOURNAL_SIZE = 1000000;
73
Chris Wrenfd13c712013-09-27 15:45:19 -040074 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040075 private static final int MAX_ICONS_PER_PASS = 10;
76
Chris Wrenfd13c712013-09-27 15:45:19 -040077 /** widgets contain previews, which are very large, dribble them out */
78 private static final int MAX_WIDGETS_PER_PASS = 5;
79
80 public static final int IMAGE_COMPRESSION_QUALITY = 75;
81
Chris Wrenb86f0762013-10-04 10:10:21 -040082 private static final Bitmap.CompressFormat IMAGE_FORMAT =
83 android.graphics.Bitmap.CompressFormat.PNG;
84
Chris Wren1ada10d2013-09-13 18:01:38 -040085 private static BackupManager sBackupManager;
86
87 private static final String[] FAVORITE_PROJECTION = {
88 Favorites._ID, // 0
Chris Wren22e130d2013-09-23 18:25:57 -040089 Favorites.MODIFIED, // 1
90 Favorites.INTENT, // 2
91 Favorites.APPWIDGET_PROVIDER, // 3
92 Favorites.APPWIDGET_ID, // 4
93 Favorites.CELLX, // 5
94 Favorites.CELLY, // 6
95 Favorites.CONTAINER, // 7
96 Favorites.ICON, // 8
97 Favorites.ICON_PACKAGE, // 9
98 Favorites.ICON_RESOURCE, // 10
99 Favorites.ICON_TYPE, // 11
100 Favorites.ITEM_TYPE, // 12
101 Favorites.SCREEN, // 13
102 Favorites.SPANX, // 14
103 Favorites.SPANY, // 15
104 Favorites.TITLE, // 16
Chris Wren1ada10d2013-09-13 18:01:38 -0400105 };
106
107 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400108 private static final int ID_MODIFIED = 1;
109 private static final int INTENT_INDEX = 2;
110 private static final int APPWIDGET_PROVIDER_INDEX = 3;
111 private static final int APPWIDGET_ID_INDEX = 4;
112 private static final int CELLX_INDEX = 5;
113 private static final int CELLY_INDEX = 6;
114 private static final int CONTAINER_INDEX = 7;
115 private static final int ICON_INDEX = 8;
116 private static final int ICON_PACKAGE_INDEX = 9;
117 private static final int ICON_RESOURCE_INDEX = 10;
118 private static final int ICON_TYPE_INDEX = 11;
119 private static final int ITEM_TYPE_INDEX = 12;
120 private static final int SCREEN_INDEX = 13;
121 private static final int SPANX_INDEX = 14;
122 private static final int SPANY_INDEX = 15;
123 private static final int TITLE_INDEX = 16;
Chris Wren1ada10d2013-09-13 18:01:38 -0400124
125 private static final String[] SCREEN_PROJECTION = {
126 WorkspaceScreens._ID, // 0
Chris Wren22e130d2013-09-23 18:25:57 -0400127 WorkspaceScreens.MODIFIED, // 1
128 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400129 };
130
Chris Wren22e130d2013-09-23 18:25:57 -0400131 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400132
Chris Wren22e130d2013-09-23 18:25:57 -0400133
134 private static final String[] ICON_PROJECTION = {
135 Favorites._ID, // 0
136 Favorites.MODIFIED, // 1
137 Favorites.INTENT // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400138 };
139
Chris Wren22e130d2013-09-23 18:25:57 -0400140 private HashMap<ComponentName, AppWidgetProviderInfo> mWidgetMap;
141
Chris Wren1ada10d2013-09-13 18:01:38 -0400142
143 /**
144 * Notify the backup manager that out database is dirty.
145 *
146 * <P>This does not force an immediate backup.
147 *
148 * @param context application context
149 */
150 public static void dataChanged(Context context) {
151 if (sBackupManager == null) {
152 sBackupManager = new BackupManager(context);
153 }
154 sBackupManager.dataChanged();
155 }
156
157 /**
158 * Back up launcher data so we can restore the user's state on a new device.
159 *
160 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
161 *
162 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
163 *
164 * @param oldState notes from the last backup
165 * @param data incremental key/value pairs to persist off-device
166 * @param newState notes for the next backup
167 * @throws IOException
168 */
169 @Override
170 public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
171 ParcelFileDescriptor newState)
172 throws IOException {
173 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>();
186 backupFavorites(in, data, out, keys);
187 backupScreens(in, data, out, keys);
Chris Wren22e130d2013-09-23 18:25:57 -0400188 backupIcons(in, data, out, keys);
Chris Wrenfd13c712013-09-27 15:45:19 -0400189 backupWidgets(in, data, out, keys);
Chris Wren1ada10d2013-09-13 18:01:38 -0400190
191 out.key = keys.toArray(BackupProtos.Key.EMPTY_ARRAY);
192 writeJournal(newState, out);
193 Log.v(TAG, "onBackup: wrote " + out.bytes + "b in " + out.rows + " rows.");
Chris Wren1ada10d2013-09-13 18:01:38 -0400194 }
195
196 /**
197 * Restore home screen from the restored data stream.
198 *
199 * <P>Keys may arrive in any order.
200 *
201 * @param data the key/value pairs from the server
202 * @param versionCode the version of the app that generated the data
203 * @param newState notes for the next backup
204 * @throws IOException
205 */
206 @Override
207 public void onRestore(BackupDataInput data, int versionCode, ParcelFileDescriptor newState)
208 throws IOException {
209 Log.v(TAG, "onRestore");
210 int numRows = 0;
211 Journal out = new Journal();
212
213 ArrayList<Key> keys = new ArrayList<Key>();
214 byte[] buffer = new byte[512];
215 while (data.readNextHeader()) {
216 numRows++;
217 String backupKey = data.getKey();
218 int dataSize = data.getDataSize();
219 if (buffer.length < dataSize) {
220 buffer = new byte[dataSize];
221 }
222 Key key = null;
223 int bytesRead = data.readEntityData(buffer, 0, dataSize);
224 if (DEBUG) {
225 Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
226 }
227 try {
228 key = backupKeyToKey(backupKey);
229 switch (key.type) {
230 case Key.FAVORITE:
231 restoreFavorite(key, buffer, dataSize, keys);
232 break;
233
234 case Key.SCREEN:
235 restoreScreen(key, buffer, dataSize, keys);
236 break;
237
Chris Wren22e130d2013-09-23 18:25:57 -0400238 case Key.ICON:
239 restoreIcon(key, buffer, dataSize, keys);
240 break;
241
Chris Wrenfd13c712013-09-27 15:45:19 -0400242 case Key.WIDGET:
243 restoreWidget(key, buffer, dataSize, keys);
244 break;
245
Chris Wren1ada10d2013-09-13 18:01:38 -0400246 default:
247 Log.w(TAG, "unknown restore entity type: " + key.type);
248 break;
249 }
250 } catch (KeyParsingException e) {
251 Log.w(TAG, "ignoring unparsable backup key: " + backupKey);
252 }
253 }
254
255 // clear the output journal time, to force a full backup to
256 // will catch any changes the restore process might have made
257 out.t = 0;
258 out.key = keys.toArray(BackupProtos.Key.EMPTY_ARRAY);
259 writeJournal(newState, out);
260 Log.v(TAG, "onRestore: read " + numRows + " rows");
261 }
262
263 /**
264 * Write all modified favorites to the data stream.
265 *
266 *
267 * @param in notes from last backup
268 * @param data output stream for key/value pairs
269 * @param out notes about this backup
270 * @param keys keys to mark as clean in the notes for next backup
271 * @throws IOException
272 */
273 private void backupFavorites(Journal in, BackupDataOutput data, Journal out,
274 ArrayList<Key> keys)
275 throws IOException {
276 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400277 Set<String> savedIds = getSavedIdsByType(Key.FAVORITE, in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400278 if (DEBUG) Log.d(TAG, "favorite savedIds.size()=" + savedIds.size());
279
280 // persist things that have changed since the last backup
281 ContentResolver cr = getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400282 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
283 null, null, null);
284 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400285 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400286 cursor.moveToPosition(-1);
287 while(cursor.moveToNext()) {
288 final long id = cursor.getLong(ID_INDEX);
289 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400290 Key key = getKey(Key.FAVORITE, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400291 keys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400292 currentIds.add(keyToBackupKey(key));
293 if (updateTime > in.t) {
294 byte[] blob = packFavorite(cursor);
295 writeRowToBackup(key, blob, out, data);
296 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400297 }
298 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400299 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400300 }
301 if (DEBUG) Log.d(TAG, "favorite currentIds.size()=" + currentIds.size());
302
303 // these IDs must have been deleted
304 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400305 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400306 }
307
308 /**
309 * Read a favorite from the stream.
310 *
311 * <P>Keys arrive in any order, so screens and containers may not exist yet.
312 *
313 * @param key identifier for the row
314 * @param buffer the serialized proto from the stream, may be larger than dataSize
315 * @param dataSize the size of the proto from the stream
316 * @param keys keys to mark as clean in the notes for next backup
317 */
318 private void restoreFavorite(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
319 Log.v(TAG, "unpacking favorite " + key.id + " (" + dataSize + " bytes)");
320 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
321 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
322
323 try {
324 Favorite favorite = unpackFavorite(buffer, 0, dataSize);
325 if (DEBUG) Log.d(TAG, "unpacked " + favorite.itemType);
326 } catch (InvalidProtocolBufferNanoException e) {
327 Log.w(TAG, "failed to decode proto", e);
328 }
329 }
330
331 /**
332 * Write all modified screens to the data stream.
333 *
334 *
335 * @param in notes from last backup
336 * @param data output stream for key/value pairs
337 * @param out notes about this backup
Chris Wren22e130d2013-09-23 18:25:57 -0400338 * @param keys keys to mark as clean in the notes for next backup
339 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400340 */
341 private void backupScreens(Journal in, BackupDataOutput data, Journal out,
342 ArrayList<Key> keys)
343 throws IOException {
344 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400345 Set<String> savedIds = getSavedIdsByType(Key.SCREEN, in);
346 if (DEBUG) Log.d(TAG, "screen savedIds.size()=" + savedIds.size());
Chris Wren1ada10d2013-09-13 18:01:38 -0400347
348 // persist things that have changed since the last backup
349 ContentResolver cr = getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400350 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
351 null, null, null);
352 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400353 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400354 cursor.moveToPosition(-1);
355 while(cursor.moveToNext()) {
356 final long id = cursor.getLong(ID_INDEX);
357 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400358 Key key = getKey(Key.SCREEN, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400359 keys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400360 currentIds.add(keyToBackupKey(key));
361 if (updateTime > in.t) {
362 byte[] blob = packScreen(cursor);
363 writeRowToBackup(key, blob, out, data);
364 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400365 }
366 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400367 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400368 }
369 if (DEBUG) Log.d(TAG, "screen currentIds.size()=" + currentIds.size());
370
371 // these IDs must have been deleted
372 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400373 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400374 }
375
376 /**
377 * Read a screen from the stream.
378 *
379 * <P>Keys arrive in any order, so children of this screen may already exist.
380 *
381 * @param key identifier for the row
382 * @param buffer the serialized proto from the stream, may be larger than dataSize
383 * @param dataSize the size of the proto from the stream
384 * @param keys keys to mark as clean in the notes for next backup
385 */
386 private void restoreScreen(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
387 Log.v(TAG, "unpacking screen " + key.id);
388 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
389 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
390 try {
391 Screen screen = unpackScreen(buffer, 0, dataSize);
392 if (DEBUG) Log.d(TAG, "unpacked " + screen.rank);
393 } catch (InvalidProtocolBufferNanoException e) {
394 Log.w(TAG, "failed to decode proto", e);
395 }
396 }
397
Chris Wren22e130d2013-09-23 18:25:57 -0400398 /**
399 * Write all the static icon resources we need to render placeholders
400 * for a package that is not installed.
401 *
402 * @param in notes from last backup
403 * @param data output stream for key/value pairs
404 * @param out notes about this backup
405 * @param keys keys to mark as clean in the notes for next backup
406 * @throws IOException
407 */
408 private void backupIcons(Journal in, BackupDataOutput data, Journal out,
409 ArrayList<Key> keys) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400410 // persist icons that haven't been persisted yet
Chris Wren22e130d2013-09-23 18:25:57 -0400411 final ContentResolver cr = getContentResolver();
Chris Wrenfd13c712013-09-27 15:45:19 -0400412 final LauncherAppState app = LauncherAppState.getInstance();
413 final IconCache iconCache = app.getIconCache();
Chris Wren22e130d2013-09-23 18:25:57 -0400414 final int dpi = getResources().getDisplayMetrics().densityDpi;
415
416 // read the old ID set
417 Set<String> savedIds = getSavedIdsByType(Key.ICON, in);
418 if (DEBUG) Log.d(TAG, "icon savedIds.size()=" + savedIds.size());
419
420 int startRows = out.rows;
421 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
422 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION;
423 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
424 where, null, null);
425 Set<String> currentIds = new HashSet<String>(cursor.getCount());
426 try {
427 cursor.moveToPosition(-1);
428 while(cursor.moveToNext()) {
429 final long id = cursor.getLong(ID_INDEX);
430 final String intentDescription = cursor.getString(INTENT_INDEX);
431 try {
432 Intent intent = Intent.parseUri(intentDescription, 0);
433 ComponentName cn = intent.getComponent();
434 Key key = null;
435 String backupKey = null;
436 if (cn != null) {
437 key = getKey(Key.ICON, cn.flattenToShortString());
438 backupKey = keyToBackupKey(key);
439 currentIds.add(backupKey);
440 } else {
441 Log.w(TAG, "empty intent on application favorite: " + id);
442 }
443 if (savedIds.contains(backupKey)) {
444 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
445
446 // remember that we already backed this up previously
447 keys.add(key);
448 } else if (backupKey != null) {
449 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
450 if ((out.rows - startRows) < MAX_ICONS_PER_PASS) {
451 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
452 Bitmap icon = iconCache.getIcon(intent);
453 keys.add(key);
454 if (icon != null && !iconCache.isDefaultIcon(icon)) {
455 byte[] blob = packIcon(dpi, icon);
456 writeRowToBackup(key, blob, out, data);
457 }
458 } else {
Chris Wrenfd13c712013-09-27 15:45:19 -0400459 if (DEBUG) Log.d(TAG, "scheduling another run for icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400460 // too many icons for this pass, request another.
461 dataChanged(this);
462 }
463 }
464 } catch (URISyntaxException e) {
465 Log.w(TAG, "invalid URI on application favorite: " + id);
466 } catch (IOException e) {
467 Log.w(TAG, "unable to save application icon for favorite: " + id);
468 }
469
470 }
471 } finally {
472 cursor.close();
473 }
474 if (DEBUG) Log.d(TAG, "icon currentIds.size()=" + currentIds.size());
475
476 // these IDs must have been deleted
477 savedIds.removeAll(currentIds);
478 out.rows += removeDeletedKeysFromBackup(savedIds, data);
479 }
480
481 /**
482 * Read an icon from the stream.
483 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400484 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400485 *
486 * @param key identifier for the row
487 * @param buffer the serialized proto from the stream, may be larger than dataSize
488 * @param dataSize the size of the proto from the stream
489 * @param keys keys to mark as clean in the notes for next backup
490 */
491 private void restoreIcon(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
492 Log.v(TAG, "unpacking icon " + key.id);
493 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
494 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
495 try {
496 Resource res = unpackIcon(buffer, 0, dataSize);
497 if (DEBUG) Log.d(TAG, "unpacked " + res.dpi);
498 if (DEBUG) Log.d(TAG, "read " +
499 Base64.encodeToString(res.data, 0, res.data.length,
500 Base64.NO_WRAP));
501 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
502 if (icon == null) {
503 Log.w(TAG, "failed to unpack icon for " + key.name);
504 }
505 } catch (InvalidProtocolBufferNanoException e) {
506 Log.w(TAG, "failed to decode proto", e);
507 }
508 }
509
Chris Wrenfd13c712013-09-27 15:45:19 -0400510 /**
511 * Write all the static widget resources we need to render placeholders
512 * for a package that is not installed.
513 *
514 * @param in notes from last backup
515 * @param data output stream for key/value pairs
516 * @param out notes about this backup
517 * @param keys keys to mark as clean in the notes for next backup
518 * @throws IOException
519 */
520 private void backupWidgets(Journal in, BackupDataOutput data, Journal out,
521 ArrayList<Key> keys) throws IOException {
522 // persist static widget info that hasn't been persisted yet
523 final ContentResolver cr = getContentResolver();
524 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(this);
525 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(this);
526 final LauncherAppState appState = LauncherAppState.getInstance();
527 final IconCache iconCache = appState.getIconCache();
528 final int dpi = getResources().getDisplayMetrics().densityDpi;
529 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
530 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
531
532 // read the old ID set
533 Set<String> savedIds = getSavedIdsByType(Key.WIDGET, in);
534 if (DEBUG) Log.d(TAG, "widgets savedIds.size()=" + savedIds.size());
535
536 int startRows = out.rows;
537 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
538 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET;
539 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
540 where, null, null);
541 Set<String> currentIds = new HashSet<String>(cursor.getCount());
542 try {
543 cursor.moveToPosition(-1);
544 while(cursor.moveToNext()) {
545 final long id = cursor.getLong(ID_INDEX);
546 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
547 final int spanX = cursor.getInt(SPANX_INDEX);
548 final int spanY = cursor.getInt(SPANY_INDEX);
549 final ComponentName provider = ComponentName.unflattenFromString(providerName);
550 Key key = null;
551 String backupKey = null;
552 if (provider != null) {
553 key = getKey(Key.WIDGET, providerName);
554 backupKey = keyToBackupKey(key);
555 currentIds.add(backupKey);
556 } else {
557 Log.w(TAG, "empty intent on appwidget: " + id);
558 }
559 if (savedIds.contains(backupKey)) {
560 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
561
562 // remember that we already backed this up previously
563 keys.add(key);
564 } else if (backupKey != null) {
565 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
566 if ((out.rows - startRows) < MAX_WIDGETS_PER_PASS) {
567 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
568 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
569 spanY * profile.cellHeightPx, widgetSpacingLayout);
570 byte[] blob = packWidget(dpi, previewLoader, iconCache, provider);
Chris Wrenb1fd63b2013-10-03 15:43:58 -0400571 keys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400572 writeRowToBackup(key, blob, out, data);
573
574 } else {
575 if (DEBUG) Log.d(TAG, "scheduling another run for widget " + backupKey);
576 // too many widgets for this pass, request another.
577 dataChanged(this);
578 }
579 }
580 }
581 } finally {
582 cursor.close();
583 }
584 if (DEBUG) Log.d(TAG, "widget currentIds.size()=" + currentIds.size());
585
586 // these IDs must have been deleted
587 savedIds.removeAll(currentIds);
588 out.rows += removeDeletedKeysFromBackup(savedIds, data);
589 }
590
591 /**
592 * Read a widget from the stream.
593 *
594 * <P>Keys arrive in any order, so widgets that use this data may already exist.
595 *
596 * @param key identifier for the row
597 * @param buffer the serialized proto from the stream, may be larger than dataSize
598 * @param dataSize the size of the proto from the stream
599 * @param keys keys to mark as clean in the notes for next backup
600 */
601 private void restoreWidget(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
602 Log.v(TAG, "unpacking widget " + key.id);
603 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
604 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
605 try {
606 Widget widget = unpackWidget(buffer, 0, dataSize);
607 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
608 if (widget.icon.data != null) {
609 Bitmap icon = BitmapFactory
610 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
611 if (icon == null) {
612 Log.w(TAG, "failed to unpack widget icon for " + key.name);
613 }
614 }
615 } catch (InvalidProtocolBufferNanoException e) {
616 Log.w(TAG, "failed to decode proto", e);
617 }
618 }
619
Chris Wren22e130d2013-09-23 18:25:57 -0400620 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400621 *
622 * <P> Keys contain their own checksum instead of using
623 * the heavy-weight CheckedMessage wrapper.
624 */
625 private Key getKey(int type, long id) {
626 Key key = new Key();
627 key.type = type;
628 key.id = id;
629 key.checksum = checkKey(key);
630 return key;
631 }
632
Chris Wren22e130d2013-09-23 18:25:57 -0400633 /** create a new key for a named object.
634 *
635 * <P> Keys contain their own checksum instead of using
636 * the heavy-weight CheckedMessage wrapper.
637 */
638 private Key getKey(int type, String name) {
639 Key key = new Key();
640 key.type = type;
641 key.name = name;
642 key.checksum = checkKey(key);
643 return key;
644 }
645
Chris Wren1ada10d2013-09-13 18:01:38 -0400646 /** keys need to be strings, serialize and encode. */
647 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400648 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400649 }
650
651 /** keys need to be strings, decode and parse. */
652 private Key backupKeyToKey(String backupKey) throws KeyParsingException {
653 try {
654 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
655 if (key.checksum != checkKey(key)) {
656 key = null;
657 throw new KeyParsingException("invalid key read from stream" + backupKey);
658 }
659 return key;
660 } catch (InvalidProtocolBufferNanoException e) {
661 throw new KeyParsingException(e);
662 } catch (IllegalArgumentException e) {
663 throw new KeyParsingException(e);
664 }
665 }
666
Chris Wren22e130d2013-09-23 18:25:57 -0400667 private String getKeyName(Key key) {
668 if (TextUtils.isEmpty(key.name)) {
669 return Long.toString(key.id);
670 } else {
671 return key.name;
672 }
673
674 }
675
676 private String geKeyType(Key key) {
677 switch (key.type) {
678 case Key.FAVORITE:
679 return "favorite";
680 case Key.SCREEN:
681 return "screen";
682 case Key.ICON:
683 return "icon";
Chris Wrenfd13c712013-09-27 15:45:19 -0400684 case Key.WIDGET:
685 return "widget";
Chris Wren22e130d2013-09-23 18:25:57 -0400686 default:
687 return "anonymous";
688 }
689 }
690
Chris Wren1ada10d2013-09-13 18:01:38 -0400691 /** Compute the checksum over the important bits of a key. */
692 private long checkKey(Key key) {
693 CRC32 checksum = new CRC32();
694 checksum.update(key.type);
695 checksum.update((int) (key.id & 0xffff));
696 checksum.update((int) ((key.id >> 32) & 0xffff));
697 if (!TextUtils.isEmpty(key.name)) {
698 checksum.update(key.name.getBytes());
699 }
700 return checksum.getValue();
701 }
702
703 /** Serialize a Favorite for persistence, including a checksum wrapper. */
704 private byte[] packFavorite(Cursor c) {
705 Favorite favorite = new Favorite();
706 favorite.id = c.getLong(ID_INDEX);
707 favorite.screen = c.getInt(SCREEN_INDEX);
708 favorite.container = c.getInt(CONTAINER_INDEX);
709 favorite.cellX = c.getInt(CELLX_INDEX);
710 favorite.cellY = c.getInt(CELLY_INDEX);
711 favorite.spanX = c.getInt(SPANX_INDEX);
712 favorite.spanY = c.getInt(SPANY_INDEX);
713 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
714 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
715 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
716 if (!TextUtils.isEmpty(iconPackage)) {
717 favorite.iconPackage = iconPackage;
718 }
719 String iconResource = c.getString(ICON_RESOURCE_INDEX);
720 if (!TextUtils.isEmpty(iconResource)) {
721 favorite.iconResource = iconResource;
722 }
723 }
724 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
725 byte[] blob = c.getBlob(ICON_INDEX);
726 if (blob != null && blob.length > 0) {
727 favorite.icon = blob;
728 }
729 }
730 String title = c.getString(TITLE_INDEX);
731 if (!TextUtils.isEmpty(title)) {
732 favorite.title = title;
733 }
734 String intent = c.getString(INTENT_INDEX);
735 if (!TextUtils.isEmpty(intent)) {
736 favorite.intent = intent;
737 }
738 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
739 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
740 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
741 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
742 if (!TextUtils.isEmpty(appWidgetProvider)) {
743 favorite.appWidgetProvider = appWidgetProvider;
744 }
745 }
746
747 return writeCheckedBytes(favorite);
748 }
749
750 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
751 private Favorite unpackFavorite(byte[] buffer, int offset, int dataSize)
752 throws InvalidProtocolBufferNanoException {
753 Favorite favorite = new Favorite();
754 MessageNano.mergeFrom(favorite, readCheckedBytes(buffer, offset, dataSize));
755 return favorite;
756 }
757
758 /** Serialize a Screen for persistence, including a checksum wrapper. */
759 private byte[] packScreen(Cursor c) {
760 Screen screen = new Screen();
761 screen.id = c.getLong(ID_INDEX);
762 screen.rank = c.getInt(SCREEN_RANK_INDEX);
763
764 return writeCheckedBytes(screen);
765 }
766
767 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
768 private Screen unpackScreen(byte[] buffer, int offset, int dataSize)
769 throws InvalidProtocolBufferNanoException {
770 Screen screen = new Screen();
771 MessageNano.mergeFrom(screen, readCheckedBytes(buffer, offset, dataSize));
772 return screen;
773 }
774
Chris Wren22e130d2013-09-23 18:25:57 -0400775 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
776 private byte[] packIcon(int dpi, Bitmap icon) {
777 Resource res = new Resource();
778 res.dpi = dpi;
779 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400780 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400781 res.data = os.toByteArray();
782 }
783 return writeCheckedBytes(res);
784 }
785
786 /** Deserialize an icon resource from persistence, after verifying checksum wrapper. */
787 private Resource unpackIcon(byte[] buffer, int offset, int dataSize)
788 throws InvalidProtocolBufferNanoException {
789 Resource res = new Resource();
790 MessageNano.mergeFrom(res, readCheckedBytes(buffer, offset, dataSize));
791 return res;
792 }
793
Chris Wrenfd13c712013-09-27 15:45:19 -0400794 /** Serialize a widget for persistence, including a checksum wrapper. */
795 private byte[] packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
796 ComponentName provider) {
797 final AppWidgetProviderInfo info = findAppWidgetProviderInfo(provider);
798 Widget widget = new Widget();
799 widget.provider = provider.flattenToShortString();
800 widget.label = info.label;
801 widget.configure = info.configure != null;
802 if (info.icon != 0) {
803 widget.icon = new Resource();
804 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
805 Bitmap icon = Utilities.createIconBitmap(fullResIcon, this);
806 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400807 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400808 widget.icon.data = os.toByteArray();
809 widget.icon.dpi = dpi;
810 }
811 }
812 if (info.previewImage != 0) {
813 widget.preview = new Resource();
814 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
815 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400816 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400817 widget.preview.data = os.toByteArray();
818 widget.preview.dpi = dpi;
819 }
820 }
821 return writeCheckedBytes(widget);
822 }
823
824 /** Deserialize a widget from persistence, after verifying checksum wrapper. */
825 private Widget unpackWidget(byte[] buffer, int offset, int dataSize)
826 throws InvalidProtocolBufferNanoException {
827 Widget widget = new Widget();
828 MessageNano.mergeFrom(widget, readCheckedBytes(buffer, offset, dataSize));
829 return widget;
830 }
831
Chris Wren1ada10d2013-09-13 18:01:38 -0400832 /**
833 * Read the old journal from the input file.
834 *
835 * In the event of any error, just pretend we didn't have a journal,
836 * in that case, do a full backup.
837 *
838 * @param oldState the read-0only file descriptor pointing to the old journal
839 * @return a Journal protocol bugffer
840 */
841 private Journal readJournal(ParcelFileDescriptor oldState) {
842 int fileSize = (int) oldState.getStatSize();
843 int remaining = fileSize;
844 byte[] buffer = null;
845 Journal journal = new Journal();
846 if (remaining < MAX_JOURNAL_SIZE) {
847 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
848 int offset = 0;
849
850 buffer = new byte[remaining];
851 while (remaining > 0) {
852 int bytesRead = 0;
853 try {
854 bytesRead = inStream.read(buffer, offset, remaining);
855 } catch (IOException e) {
856 Log.w(TAG, "failed to read the journal", e);
857 buffer = null;
858 remaining = 0;
859 }
860 if (bytesRead > 0) {
861 remaining -= bytesRead;
862 } else {
863 // act like there is not journal
864 Log.w(TAG, "failed to read the journal");
865 buffer = null;
866 remaining = 0;
867 }
868 }
869
870 if (buffer != null) {
871 try {
872 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, 0, fileSize));
873 } catch (InvalidProtocolBufferNanoException e) {
874 Log.d(TAG, "failed to read the journal", e);
875 journal.clear();
876 }
877 }
878
879 try {
880 inStream.close();
881 } catch (IOException e) {
882 Log.d(TAG, "failed to close the journal", e);
883 }
884 }
885 return journal;
886 }
887
Chris Wren22e130d2013-09-23 18:25:57 -0400888 private void writeRowToBackup(Key key, byte[] blob, Journal out,
889 BackupDataOutput data) throws IOException {
890 String backupKey = keyToBackupKey(key);
891 data.writeEntityHeader(backupKey, blob.length);
892 data.writeEntityData(blob, blob.length);
893 out.rows++;
894 out.bytes += blob.length;
895 Log.v(TAG, "saving " + geKeyType(key) + " " + backupKey + ": " +
896 getKeyName(key) + "/" + blob.length);
Chris Wren2b6c21d2013-10-02 14:16:04 -0400897 if(DEBUG) {
898 String encoded = Base64.encodeToString(blob, 0, blob.length, Base64.NO_WRAP);
899 final int chunkSize = 1024;
900 for (int offset = 0; offset < encoded.length(); offset += chunkSize) {
901 int end = offset + chunkSize;
902 end = Math.min(end, encoded.length());
903 Log.d(TAG, "wrote " + encoded.substring(offset, end));
904 }
905 }
Chris Wren22e130d2013-09-23 18:25:57 -0400906 }
907
908 private Set<String> getSavedIdsByType(int type, Journal in) {
909 Set<String> savedIds = new HashSet<String>();
910 for(int i = 0; i < in.key.length; i++) {
911 Key key = in.key[i];
912 if (key.type == type) {
913 savedIds.add(keyToBackupKey(key));
914 }
915 }
916 return savedIds;
917 }
918
919 private int removeDeletedKeysFromBackup(Set<String> deletedIds, BackupDataOutput data)
920 throws IOException {
921 int rows = 0;
922 for(String deleted: deletedIds) {
923 Log.v(TAG, "dropping icon " + deleted);
924 data.writeEntityHeader(deleted, -1);
925 rows++;
926 }
927 return rows;
928 }
929
Chris Wren1ada10d2013-09-13 18:01:38 -0400930 /**
931 * Write the new journal to the output file.
932 *
933 * In the event of any error, just pretend we didn't have a journal,
934 * in that case, do a full backup.
935
936 * @param newState the write-only file descriptor pointing to the new journal
937 * @param journal a Journal protocol buffer
938 */
939 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
940 FileOutputStream outStream = null;
941 try {
942 outStream = new FileOutputStream(newState.getFileDescriptor());
943 outStream.write(writeCheckedBytes(journal));
944 outStream.close();
945 } catch (IOException e) {
946 Log.d(TAG, "failed to write backup journal", e);
947 }
948 }
949
950 /** Wrap a proto in a CheckedMessage and compute the checksum. */
951 private byte[] writeCheckedBytes(MessageNano proto) {
952 CheckedMessage wrapper = new CheckedMessage();
953 wrapper.payload = MessageNano.toByteArray(proto);
954 CRC32 checksum = new CRC32();
955 checksum.update(wrapper.payload);
956 wrapper.checksum = checksum.getValue();
957 return MessageNano.toByteArray(wrapper);
958 }
959
960 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
961 private byte[] readCheckedBytes(byte[] buffer, int offset, int dataSize)
962 throws InvalidProtocolBufferNanoException {
963 CheckedMessage wrapper = new CheckedMessage();
964 MessageNano.mergeFrom(wrapper, buffer, offset, dataSize);
965 CRC32 checksum = new CRC32();
966 checksum.update(wrapper.payload);
967 if (wrapper.checksum != checksum.getValue()) {
968 throw new InvalidProtocolBufferNanoException("checksum does not match");
969 }
970 return wrapper.payload;
971 }
972
Chris Wrenfd13c712013-09-27 15:45:19 -0400973 private AppWidgetProviderInfo findAppWidgetProviderInfo(ComponentName component) {
974 if (mWidgetMap == null) {
975 List<AppWidgetProviderInfo> widgets =
976 AppWidgetManager.getInstance(this).getInstalledProviders();
977 mWidgetMap = new HashMap<ComponentName, AppWidgetProviderInfo>(widgets.size());
978 for (AppWidgetProviderInfo info : widgets) {
979 mWidgetMap.put(info.provider, info);
980 }
981 }
982 return mWidgetMap.get(component);
983 }
984
Chris Wren1ada10d2013-09-13 18:01:38 -0400985 private class KeyParsingException extends Throwable {
986 private KeyParsingException(Throwable cause) {
987 super(cause);
988 }
989
990 public KeyParsingException(String reason) {
991 super(reason);
992 }
993 }
994}