blob: c706cf17453681c710be556f7fc049413609e7d7 [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 */
Chris Wren1ada10d2013-09-13 18:01:38 -040016package com.android.launcher3;
17
18import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
19import com.google.protobuf.nano.MessageNano;
20
Chris Wren1ada10d2013-09-13 18:01:38 -040021import com.android.launcher3.LauncherSettings.Favorites;
22import com.android.launcher3.LauncherSettings.WorkspaceScreens;
23import com.android.launcher3.backup.BackupProtos;
24import com.android.launcher3.backup.BackupProtos.CheckedMessage;
25import com.android.launcher3.backup.BackupProtos.Favorite;
26import com.android.launcher3.backup.BackupProtos.Journal;
27import com.android.launcher3.backup.BackupProtos.Key;
Chris Wren22e130d2013-09-23 18:25:57 -040028import com.android.launcher3.backup.BackupProtos.Resource;
Chris Wren1ada10d2013-09-13 18:01:38 -040029import com.android.launcher3.backup.BackupProtos.Screen;
Chris Wrenfd13c712013-09-27 15:45:19 -040030import com.android.launcher3.backup.BackupProtos.Widget;
Chris Wren1ada10d2013-09-13 18:01:38 -040031
Chris Wren92aa4232013-10-04 11:29:36 -040032import android.app.backup.BackupDataInputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040033import android.app.backup.BackupDataOutput;
Chris Wren4d89e2a2013-10-09 17:03:50 -040034import android.app.backup.BackupHelper;
Chris Wren1ada10d2013-09-13 18:01:38 -040035import android.app.backup.BackupManager;
Chris Wren22e130d2013-09-23 18:25:57 -040036import android.appwidget.AppWidgetManager;
37import android.appwidget.AppWidgetProviderInfo;
38import android.content.ComponentName;
Chris Wren1ada10d2013-09-13 18:01:38 -040039import android.content.ContentResolver;
Chris Wren5dee7af2013-12-20 17:22:11 -050040import android.content.ContentValues;
Chris Wren1ada10d2013-09-13 18:01:38 -040041import 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 Wren6d0dde02014-02-10 12:16:54 -050053import java.io.File;
Chris Wren1ada10d2013-09-13 18:01:38 -040054import java.io.FileInputStream;
Chris Wren6d0dde02014-02-10 12:16:54 -050055import java.io.FileNotFoundException;
Chris Wren1ada10d2013-09-13 18:01:38 -040056import java.io.FileOutputStream;
57import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040058import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040059import java.util.ArrayList;
Chris Wren22e130d2013-09-23 18:25:57 -040060import java.util.HashMap;
Chris Wren1ada10d2013-09-13 18:01:38 -040061import java.util.HashSet;
Chris Wren22e130d2013-09-23 18:25:57 -040062import java.util.List;
Chris Wren1ada10d2013-09-13 18:01:38 -040063import java.util.Set;
64import java.util.zip.CRC32;
65
66/**
67 * Persist the launcher home state across calamities.
68 */
Chris Wren92aa4232013-10-04 11:29:36 -040069public class LauncherBackupHelper implements BackupHelper {
Chris Wren1ada10d2013-09-13 18:01:38 -040070
Chris Wren92aa4232013-10-04 11:29:36 -040071 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050072 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
73 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren92aa4232013-10-04 11:29:36 -040074 private static final boolean DEBUG_PAYLOAD = false;
Chris Wren1ada10d2013-09-13 18:01:38 -040075
76 private static final int MAX_JOURNAL_SIZE = 1000000;
77
Chris Wrenfd13c712013-09-27 15:45:19 -040078 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040079 private static final int MAX_ICONS_PER_PASS = 10;
80
Chris Wrenfd13c712013-09-27 15:45:19 -040081 /** widgets contain previews, which are very large, dribble them out */
82 private static final int MAX_WIDGETS_PER_PASS = 5;
83
84 public static final int IMAGE_COMPRESSION_QUALITY = 75;
85
Chris Wren92aa4232013-10-04 11:29:36 -040086 public static final String LAUNCHER_PREFIX = "L";
87
Chris Wren45297f82013-10-17 15:16:48 -040088 public static final String LAUNCHER_PREFS_PREFIX = "LP";
89
Chris Wrenb86f0762013-10-04 10:10:21 -040090 private static final Bitmap.CompressFormat IMAGE_FORMAT =
91 android.graphics.Bitmap.CompressFormat.PNG;
92
Chris Wren1ada10d2013-09-13 18:01:38 -040093 private static BackupManager sBackupManager;
94
95 private static final String[] FAVORITE_PROJECTION = {
96 Favorites._ID, // 0
Chris Wren22e130d2013-09-23 18:25:57 -040097 Favorites.MODIFIED, // 1
98 Favorites.INTENT, // 2
99 Favorites.APPWIDGET_PROVIDER, // 3
100 Favorites.APPWIDGET_ID, // 4
101 Favorites.CELLX, // 5
102 Favorites.CELLY, // 6
103 Favorites.CONTAINER, // 7
104 Favorites.ICON, // 8
105 Favorites.ICON_PACKAGE, // 9
106 Favorites.ICON_RESOURCE, // 10
107 Favorites.ICON_TYPE, // 11
108 Favorites.ITEM_TYPE, // 12
109 Favorites.SCREEN, // 13
110 Favorites.SPANX, // 14
111 Favorites.SPANY, // 15
112 Favorites.TITLE, // 16
Chris Wren1ada10d2013-09-13 18:01:38 -0400113 };
114
115 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400116 private static final int ID_MODIFIED = 1;
117 private static final int INTENT_INDEX = 2;
118 private static final int APPWIDGET_PROVIDER_INDEX = 3;
119 private static final int APPWIDGET_ID_INDEX = 4;
120 private static final int CELLX_INDEX = 5;
121 private static final int CELLY_INDEX = 6;
122 private static final int CONTAINER_INDEX = 7;
123 private static final int ICON_INDEX = 8;
124 private static final int ICON_PACKAGE_INDEX = 9;
125 private static final int ICON_RESOURCE_INDEX = 10;
126 private static final int ICON_TYPE_INDEX = 11;
127 private static final int ITEM_TYPE_INDEX = 12;
128 private static final int SCREEN_INDEX = 13;
129 private static final int SPANX_INDEX = 14;
130 private static final int SPANY_INDEX = 15;
131 private static final int TITLE_INDEX = 16;
Chris Wren1ada10d2013-09-13 18:01:38 -0400132
133 private static final String[] SCREEN_PROJECTION = {
134 WorkspaceScreens._ID, // 0
Chris Wren22e130d2013-09-23 18:25:57 -0400135 WorkspaceScreens.MODIFIED, // 1
136 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400137 };
138
Chris Wren22e130d2013-09-23 18:25:57 -0400139 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400140
Chris Wren6d0dde02014-02-10 12:16:54 -0500141 private static IconCache mIconCache;
142
Chris Wren92aa4232013-10-04 11:29:36 -0400143 private final Context mContext;
Chris Wren1ada10d2013-09-13 18:01:38 -0400144
Chris Wren4b171362014-01-13 17:39:02 -0500145 private final boolean mRestoreEnabled;
146
Chris Wren22e130d2013-09-23 18:25:57 -0400147 private HashMap<ComponentName, AppWidgetProviderInfo> mWidgetMap;
148
Chris Wren92aa4232013-10-04 11:29:36 -0400149 private ArrayList<Key> mKeys;
Chris Wren1ada10d2013-09-13 18:01:38 -0400150
Chris Wren4b171362014-01-13 17:39:02 -0500151 public LauncherBackupHelper(Context context, boolean restoreEnabled) {
Chris Wren92aa4232013-10-04 11:29:36 -0400152 mContext = context;
Chris Wren4b171362014-01-13 17:39:02 -0500153 mRestoreEnabled = restoreEnabled;
Chris Wren92aa4232013-10-04 11:29:36 -0400154 }
155
156 private void dataChanged() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400157 if (sBackupManager == null) {
Chris Wren92aa4232013-10-04 11:29:36 -0400158 sBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400159 }
160 sBackupManager.dataChanged();
161 }
162
163 /**
164 * Back up launcher data so we can restore the user's state on a new device.
165 *
166 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
167 *
168 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
169 *
170 * @param oldState notes from the last backup
171 * @param data incremental key/value pairs to persist off-device
172 * @param newState notes for the next backup
173 * @throws IOException
174 */
175 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400176 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
177 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500178 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400179
180 Journal in = readJournal(oldState);
181 Journal out = new Journal();
182
183 long lastBackupTime = in.t;
184 out.t = System.currentTimeMillis();
185 out.rows = 0;
186 out.bytes = 0;
187
Chris Wren50c8f422014-01-15 16:10:39 -0500188 Log.v(TAG, "lastBackupTime = " + lastBackupTime);
Chris Wren1ada10d2013-09-13 18:01:38 -0400189
190 ArrayList<Key> keys = new ArrayList<Key>();
Chris Wren92aa4232013-10-04 11:29:36 -0400191 try {
192 backupFavorites(in, data, out, keys);
193 backupScreens(in, data, out, keys);
194 backupIcons(in, data, out, keys);
195 backupWidgets(in, data, out, keys);
196 } catch (IOException e) {
197 Log.e(TAG, "launcher backup has failed", e);
198 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400199
Mac Duy Hai22dc65e2014-02-05 10:52:07 +0000200 out.key = keys.toArray(new BackupProtos.Key[keys.size()]);
Chris Wren1ada10d2013-09-13 18:01:38 -0400201 writeJournal(newState, out);
202 Log.v(TAG, "onBackup: wrote " + out.bytes + "b in " + out.rows + " rows.");
Chris Wren1ada10d2013-09-13 18:01:38 -0400203 }
204
205 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400206 * Restore launcher configuration from the restored data stream.
Chris Wren1ada10d2013-09-13 18:01:38 -0400207 *
208 * <P>Keys may arrive in any order.
209 *
Chris Wren92aa4232013-10-04 11:29:36 -0400210 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400211 */
212 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400213 public void restoreEntity(BackupDataInputStream data) {
Chris Wren50c8f422014-01-15 16:10:39 -0500214 if (VERBOSE) Log.v(TAG, "restoreEntity");
Chris Wren92aa4232013-10-04 11:29:36 -0400215 if (mKeys == null) {
216 mKeys = new ArrayList<Key>();
217 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400218 byte[] buffer = new byte[512];
Chris Wren1ada10d2013-09-13 18:01:38 -0400219 String backupKey = data.getKey();
Chris Wren92aa4232013-10-04 11:29:36 -0400220 int dataSize = data.size();
Chris Wren1ada10d2013-09-13 18:01:38 -0400221 if (buffer.length < dataSize) {
222 buffer = new byte[dataSize];
223 }
224 Key key = null;
Chris Wren92aa4232013-10-04 11:29:36 -0400225 int bytesRead = 0;
226 try {
227 bytesRead = data.read(buffer, 0, dataSize);
228 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
229 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500230 Log.e(TAG, "failed to read entity from restore data", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400231 }
232 try {
233 key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500234 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400235 switch (key.type) {
236 case Key.FAVORITE:
237 restoreFavorite(key, buffer, dataSize, mKeys);
238 break;
239
240 case Key.SCREEN:
241 restoreScreen(key, buffer, dataSize, mKeys);
242 break;
243
244 case Key.ICON:
245 restoreIcon(key, buffer, dataSize, mKeys);
246 break;
247
248 case Key.WIDGET:
249 restoreWidget(key, buffer, dataSize, mKeys);
250 break;
251
252 default:
253 Log.w(TAG, "unknown restore entity type: " + key.type);
254 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400255 }
Chris Wren92aa4232013-10-04 11:29:36 -0400256 } catch (KeyParsingException e) {
257 Log.w(TAG, "ignoring unparsable backup key: " + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400258 }
259
Chris Wren92aa4232013-10-04 11:29:36 -0400260 }
261
262 /**
263 * Record the restore state for the next backup.
264 *
265 * @param newState notes about the backup state after restore.
266 */
267 @Override
268 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400269 // clear the output journal time, to force a full backup to
270 // will catch any changes the restore process might have made
Chris Wren92aa4232013-10-04 11:29:36 -0400271 Journal out = new Journal();
Chris Wren1ada10d2013-09-13 18:01:38 -0400272 out.t = 0;
Mac Duy Hai22dc65e2014-02-05 10:52:07 +0000273 out.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
Chris Wren1ada10d2013-09-13 18:01:38 -0400274 writeJournal(newState, out);
Chris Wren92aa4232013-10-04 11:29:36 -0400275 Log.v(TAG, "onRestore: read " + mKeys.size() + " rows");
276 mKeys.clear();
Chris Wren1ada10d2013-09-13 18:01:38 -0400277 }
278
279 /**
280 * Write all modified favorites to the data stream.
281 *
282 *
283 * @param in notes from last backup
284 * @param data output stream for key/value pairs
285 * @param out notes about this backup
286 * @param keys keys to mark as clean in the notes for next backup
287 * @throws IOException
288 */
289 private void backupFavorites(Journal in, BackupDataOutput data, Journal out,
290 ArrayList<Key> keys)
291 throws IOException {
292 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400293 Set<String> savedIds = getSavedIdsByType(Key.FAVORITE, in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400294 if (DEBUG) Log.d(TAG, "favorite savedIds.size()=" + savedIds.size());
295
296 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400297 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400298 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
299 null, null, null);
300 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400301 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400302 cursor.moveToPosition(-1);
303 while(cursor.moveToNext()) {
304 final long id = cursor.getLong(ID_INDEX);
305 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400306 Key key = getKey(Key.FAVORITE, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400307 keys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500308 final String backupKey = keyToBackupKey(key);
309 currentIds.add(backupKey);
310 if (!savedIds.contains(backupKey) || updateTime >= in.t) {
Chris Wren22e130d2013-09-23 18:25:57 -0400311 byte[] blob = packFavorite(cursor);
312 writeRowToBackup(key, blob, out, data);
Chris Wren50c8f422014-01-15 16:10:39 -0500313 } else {
314 if (VERBOSE) Log.v(TAG, "favorite " + id + " was too old: " + updateTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400315 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400316 }
317 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400318 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400319 }
320 if (DEBUG) Log.d(TAG, "favorite currentIds.size()=" + currentIds.size());
321
322 // these IDs must have been deleted
323 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400324 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400325 }
326
327 /**
328 * Read a favorite from the stream.
329 *
330 * <P>Keys arrive in any order, so screens and containers may not exist yet.
331 *
332 * @param key identifier for the row
333 * @param buffer the serialized proto from the stream, may be larger than dataSize
334 * @param dataSize the size of the proto from the stream
335 * @param keys keys to mark as clean in the notes for next backup
336 */
337 private void restoreFavorite(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
Chris Wren50c8f422014-01-15 16:10:39 -0500338 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400339 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
340 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
341
Chris Wren5dee7af2013-12-20 17:22:11 -0500342 if (!mRestoreEnabled) {
Chris Wren50c8f422014-01-15 16:10:39 -0500343 if (VERBOSE) Log.v(TAG, "restore not enabled: skipping database mutation");
Chris Wren5dee7af2013-12-20 17:22:11 -0500344 return;
345 }
346
Chris Wren1ada10d2013-09-13 18:01:38 -0400347 try {
Chris Wren5dee7af2013-12-20 17:22:11 -0500348 ContentResolver cr = mContext.getContentResolver();
349 ContentValues values = unpackFavorite(buffer, 0, dataSize);
350 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400351 } catch (InvalidProtocolBufferNanoException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500352 Log.e(TAG, "failed to decode favorite", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400353 }
354 }
355
356 /**
357 * Write all modified screens to the data stream.
358 *
359 *
360 * @param in notes from last backup
361 * @param data output stream for key/value pairs
362 * @param out notes about this backup
Chris Wren22e130d2013-09-23 18:25:57 -0400363 * @param keys keys to mark as clean in the notes for next backup
364 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400365 */
366 private void backupScreens(Journal in, BackupDataOutput data, Journal out,
367 ArrayList<Key> keys)
368 throws IOException {
369 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400370 Set<String> savedIds = getSavedIdsByType(Key.SCREEN, in);
371 if (DEBUG) Log.d(TAG, "screen savedIds.size()=" + savedIds.size());
Chris Wren1ada10d2013-09-13 18:01:38 -0400372
373 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400374 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400375 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
376 null, null, null);
377 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400378 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400379 cursor.moveToPosition(-1);
Chris Wren50c8f422014-01-15 16:10:39 -0500380 if (DEBUG) Log.d(TAG, "dumping screens after: " + in.t);
Chris Wren22e130d2013-09-23 18:25:57 -0400381 while(cursor.moveToNext()) {
382 final long id = cursor.getLong(ID_INDEX);
383 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400384 Key key = getKey(Key.SCREEN, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400385 keys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500386 final String backupKey = keyToBackupKey(key);
387 currentIds.add(backupKey);
388 if (!savedIds.contains(backupKey) || updateTime >= in.t) {
Chris Wren22e130d2013-09-23 18:25:57 -0400389 byte[] blob = packScreen(cursor);
390 writeRowToBackup(key, blob, out, data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500391 } else {
Chris Wren50c8f422014-01-15 16:10:39 -0500392 if (VERBOSE) Log.v(TAG, "screen " + id + " was too old: " + updateTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400393 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400394 }
395 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400396 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400397 }
398 if (DEBUG) Log.d(TAG, "screen currentIds.size()=" + currentIds.size());
399
400 // these IDs must have been deleted
401 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400402 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400403 }
404
405 /**
406 * Read a screen from the stream.
407 *
408 * <P>Keys arrive in any order, so children of this screen may already exist.
409 *
410 * @param key identifier for the row
411 * @param buffer the serialized proto from the stream, may be larger than dataSize
412 * @param dataSize the size of the proto from the stream
413 * @param keys keys to mark as clean in the notes for next backup
414 */
415 private void restoreScreen(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
Chris Wren50c8f422014-01-15 16:10:39 -0500416 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400417 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
418 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500419
420 if (!mRestoreEnabled) {
Chris Wren50c8f422014-01-15 16:10:39 -0500421 if (VERBOSE) Log.v(TAG, "restore not enabled: skipping database mutation");
Chris Wren5dee7af2013-12-20 17:22:11 -0500422 return;
423 }
424
Chris Wren1ada10d2013-09-13 18:01:38 -0400425 try {
Chris Wren5dee7af2013-12-20 17:22:11 -0500426 ContentResolver cr = mContext.getContentResolver();
427 ContentValues values = unpackScreen(buffer, 0, dataSize);
428 cr.insert(WorkspaceScreens.CONTENT_URI, values);
429
Chris Wren1ada10d2013-09-13 18:01:38 -0400430 } catch (InvalidProtocolBufferNanoException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500431 Log.e(TAG, "failed to decode screen", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400432 }
433 }
434
Chris Wren22e130d2013-09-23 18:25:57 -0400435 /**
436 * Write all the static icon resources we need to render placeholders
437 * for a package that is not installed.
438 *
439 * @param in notes from last backup
440 * @param data output stream for key/value pairs
441 * @param out notes about this backup
442 * @param keys keys to mark as clean in the notes for next backup
443 * @throws IOException
444 */
445 private void backupIcons(Journal in, BackupDataOutput data, Journal out,
446 ArrayList<Key> keys) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400447 // persist icons that haven't been persisted yet
Chris Wren6d0dde02014-02-10 12:16:54 -0500448 if (!initializeIconCache()) {
Chris Wren92aa4232013-10-04 11:29:36 -0400449 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400450 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
451 return;
452 }
Chris Wren92aa4232013-10-04 11:29:36 -0400453 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400454 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wren22e130d2013-09-23 18:25:57 -0400455
456 // read the old ID set
457 Set<String> savedIds = getSavedIdsByType(Key.ICON, in);
458 if (DEBUG) Log.d(TAG, "icon savedIds.size()=" + savedIds.size());
459
460 int startRows = out.rows;
461 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
462 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION;
463 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
464 where, null, null);
465 Set<String> currentIds = new HashSet<String>(cursor.getCount());
466 try {
467 cursor.moveToPosition(-1);
468 while(cursor.moveToNext()) {
469 final long id = cursor.getLong(ID_INDEX);
470 final String intentDescription = cursor.getString(INTENT_INDEX);
471 try {
472 Intent intent = Intent.parseUri(intentDescription, 0);
473 ComponentName cn = intent.getComponent();
474 Key key = null;
475 String backupKey = null;
476 if (cn != null) {
477 key = getKey(Key.ICON, cn.flattenToShortString());
478 backupKey = keyToBackupKey(key);
479 currentIds.add(backupKey);
480 } else {
481 Log.w(TAG, "empty intent on application favorite: " + id);
482 }
483 if (savedIds.contains(backupKey)) {
Chris Wren50c8f422014-01-15 16:10:39 -0500484 if (VERBOSE) Log.v(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400485
486 // remember that we already backed this up previously
487 keys.add(key);
488 } else if (backupKey != null) {
489 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
490 if ((out.rows - startRows) < MAX_ICONS_PER_PASS) {
Chris Wren50c8f422014-01-15 16:10:39 -0500491 if (VERBOSE) Log.v(TAG, "saving icon " + backupKey);
Chris Wren6d0dde02014-02-10 12:16:54 -0500492 Bitmap icon = mIconCache.getIcon(intent);
Chris Wren22e130d2013-09-23 18:25:57 -0400493 keys.add(key);
Chris Wren6d0dde02014-02-10 12:16:54 -0500494 if (icon != null && !mIconCache.isDefaultIcon(icon)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400495 byte[] blob = packIcon(dpi, icon);
496 writeRowToBackup(key, blob, out, data);
497 }
498 } else {
Chris Wren50c8f422014-01-15 16:10:39 -0500499 if (VERBOSE) Log.d(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400500 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400501 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400502 }
503 }
504 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500505 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400506 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500507 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400508 }
509
510 }
511 } finally {
512 cursor.close();
513 }
514 if (DEBUG) Log.d(TAG, "icon currentIds.size()=" + currentIds.size());
515
516 // these IDs must have been deleted
517 savedIds.removeAll(currentIds);
518 out.rows += removeDeletedKeysFromBackup(savedIds, data);
519 }
520
521 /**
522 * Read an icon from the stream.
523 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400524 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400525 *
526 * @param key identifier for the row
527 * @param buffer the serialized proto from the stream, may be larger than dataSize
528 * @param dataSize the size of the proto from the stream
529 * @param keys keys to mark as clean in the notes for next backup
530 */
531 private void restoreIcon(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
Chris Wren50c8f422014-01-15 16:10:39 -0500532 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400533 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
534 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500535
Chris Wren22e130d2013-09-23 18:25:57 -0400536 try {
537 Resource res = unpackIcon(buffer, 0, dataSize);
Chris Wren6d0dde02014-02-10 12:16:54 -0500538 if (DEBUG) {
539 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
540 }
541 if (DEBUG_PAYLOAD) {
542 Log.d(TAG, "read " +
543 Base64.encodeToString(res.data, 0, res.data.length,
544 Base64.NO_WRAP));
545 }
Chris Wren22e130d2013-09-23 18:25:57 -0400546 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
547 if (icon == null) {
548 Log.w(TAG, "failed to unpack icon for " + key.name);
549 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500550
551 if (!mRestoreEnabled) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500552 if (VERBOSE) {
553 Log.v(TAG, "restore not enabled: skipping database mutation");
554 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500555 return;
556 } else {
Chris Wren6d0dde02014-02-10 12:16:54 -0500557 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(key.name),
558 icon, res.dpi);
Chris Wren5dee7af2013-12-20 17:22:11 -0500559 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500560 } catch (IOException e) {
561 Log.d(TAG, "failed to save restored icon for: " + key.name, e);
Chris Wren22e130d2013-09-23 18:25:57 -0400562 }
563 }
564
Chris Wrenfd13c712013-09-27 15:45:19 -0400565 /**
566 * Write all the static widget resources we need to render placeholders
567 * for a package that is not installed.
568 *
569 * @param in notes from last backup
570 * @param data output stream for key/value pairs
571 * @param out notes about this backup
572 * @param keys keys to mark as clean in the notes for next backup
573 * @throws IOException
574 */
575 private void backupWidgets(Journal in, BackupDataOutput data, Journal out,
576 ArrayList<Key> keys) throws IOException {
577 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400578 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
Chris Wren6d0dde02014-02-10 12:16:54 -0500579 if (appState == null || !initializeIconCache()) {
580 Log.w(TAG, "Failed to get icon cache during restore");
Chris Wrend8fe6de2013-10-04 10:42:14 -0400581 return;
582 }
Chris Wren92aa4232013-10-04 11:29:36 -0400583 final ContentResolver cr = mContext.getContentResolver();
584 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
585 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wren92aa4232013-10-04 11:29:36 -0400586 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400587 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
588 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
589
590 // read the old ID set
591 Set<String> savedIds = getSavedIdsByType(Key.WIDGET, in);
592 if (DEBUG) Log.d(TAG, "widgets savedIds.size()=" + savedIds.size());
593
594 int startRows = out.rows;
595 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
596 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET;
597 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
598 where, null, null);
599 Set<String> currentIds = new HashSet<String>(cursor.getCount());
600 try {
601 cursor.moveToPosition(-1);
602 while(cursor.moveToNext()) {
603 final long id = cursor.getLong(ID_INDEX);
604 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
605 final int spanX = cursor.getInt(SPANX_INDEX);
606 final int spanY = cursor.getInt(SPANY_INDEX);
607 final ComponentName provider = ComponentName.unflattenFromString(providerName);
608 Key key = null;
609 String backupKey = null;
610 if (provider != null) {
611 key = getKey(Key.WIDGET, providerName);
612 backupKey = keyToBackupKey(key);
613 currentIds.add(backupKey);
614 } else {
615 Log.w(TAG, "empty intent on appwidget: " + id);
616 }
617 if (savedIds.contains(backupKey)) {
Chris Wren50c8f422014-01-15 16:10:39 -0500618 if (VERBOSE) Log.v(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400619
620 // remember that we already backed this up previously
621 keys.add(key);
622 } else if (backupKey != null) {
623 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
624 if ((out.rows - startRows) < MAX_WIDGETS_PER_PASS) {
Chris Wren50c8f422014-01-15 16:10:39 -0500625 if (VERBOSE) Log.v(TAG, "saving widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400626 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
627 spanY * profile.cellHeightPx, widgetSpacingLayout);
Chris Wren6d0dde02014-02-10 12:16:54 -0500628 byte[] blob = packWidget(dpi, previewLoader, mIconCache, provider);
Chris Wrenb1fd63b2013-10-03 15:43:58 -0400629 keys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400630 writeRowToBackup(key, blob, out, data);
631
632 } else {
Chris Wren50c8f422014-01-15 16:10:39 -0500633 if (VERBOSE) Log.d(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400634 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400635 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400636 }
637 }
638 }
639 } finally {
640 cursor.close();
641 }
642 if (DEBUG) Log.d(TAG, "widget currentIds.size()=" + currentIds.size());
643
644 // these IDs must have been deleted
645 savedIds.removeAll(currentIds);
646 out.rows += removeDeletedKeysFromBackup(savedIds, data);
647 }
648
649 /**
650 * Read a widget from the stream.
651 *
652 * <P>Keys arrive in any order, so widgets that use this data may already exist.
653 *
654 * @param key identifier for the row
655 * @param buffer the serialized proto from the stream, may be larger than dataSize
656 * @param dataSize the size of the proto from the stream
657 * @param keys keys to mark as clean in the notes for next backup
658 */
659 private void restoreWidget(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
Chris Wren50c8f422014-01-15 16:10:39 -0500660 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400661 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
662 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
663 try {
664 Widget widget = unpackWidget(buffer, 0, dataSize);
665 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
666 if (widget.icon.data != null) {
667 Bitmap icon = BitmapFactory
668 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
669 if (icon == null) {
670 Log.w(TAG, "failed to unpack widget icon for " + key.name);
671 }
672 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500673
674 if (!mRestoreEnabled) {
Chris Wren50c8f422014-01-15 16:10:39 -0500675 if (VERBOSE) Log.v(TAG, "restore not enabled: skipping database mutation");
Chris Wren5dee7af2013-12-20 17:22:11 -0500676 return;
677 } else {
678 // future site of widget table mutation
679 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400680 } catch (InvalidProtocolBufferNanoException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500681 Log.e(TAG, "failed to decode widget", e);
Chris Wrenfd13c712013-09-27 15:45:19 -0400682 }
683 }
684
Chris Wren22e130d2013-09-23 18:25:57 -0400685 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400686 *
687 * <P> Keys contain their own checksum instead of using
688 * the heavy-weight CheckedMessage wrapper.
689 */
690 private Key getKey(int type, long id) {
691 Key key = new Key();
692 key.type = type;
693 key.id = id;
694 key.checksum = checkKey(key);
695 return key;
696 }
697
Chris Wren22e130d2013-09-23 18:25:57 -0400698 /** create a new key for a named object.
699 *
700 * <P> Keys contain their own checksum instead of using
701 * the heavy-weight CheckedMessage wrapper.
702 */
703 private Key getKey(int type, String name) {
704 Key key = new Key();
705 key.type = type;
706 key.name = name;
707 key.checksum = checkKey(key);
708 return key;
709 }
710
Chris Wren1ada10d2013-09-13 18:01:38 -0400711 /** keys need to be strings, serialize and encode. */
712 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400713 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400714 }
715
716 /** keys need to be strings, decode and parse. */
717 private Key backupKeyToKey(String backupKey) throws KeyParsingException {
718 try {
719 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
720 if (key.checksum != checkKey(key)) {
721 key = null;
722 throw new KeyParsingException("invalid key read from stream" + backupKey);
723 }
724 return key;
725 } catch (InvalidProtocolBufferNanoException e) {
726 throw new KeyParsingException(e);
727 } catch (IllegalArgumentException e) {
728 throw new KeyParsingException(e);
729 }
730 }
731
Chris Wren22e130d2013-09-23 18:25:57 -0400732 private String getKeyName(Key key) {
733 if (TextUtils.isEmpty(key.name)) {
734 return Long.toString(key.id);
735 } else {
736 return key.name;
737 }
738
739 }
740
741 private String geKeyType(Key key) {
742 switch (key.type) {
743 case Key.FAVORITE:
744 return "favorite";
745 case Key.SCREEN:
746 return "screen";
747 case Key.ICON:
748 return "icon";
Chris Wrenfd13c712013-09-27 15:45:19 -0400749 case Key.WIDGET:
750 return "widget";
Chris Wren22e130d2013-09-23 18:25:57 -0400751 default:
752 return "anonymous";
753 }
754 }
755
Chris Wren1ada10d2013-09-13 18:01:38 -0400756 /** Compute the checksum over the important bits of a key. */
757 private long checkKey(Key key) {
758 CRC32 checksum = new CRC32();
759 checksum.update(key.type);
760 checksum.update((int) (key.id & 0xffff));
761 checksum.update((int) ((key.id >> 32) & 0xffff));
762 if (!TextUtils.isEmpty(key.name)) {
763 checksum.update(key.name.getBytes());
764 }
765 return checksum.getValue();
766 }
767
768 /** Serialize a Favorite for persistence, including a checksum wrapper. */
769 private byte[] packFavorite(Cursor c) {
770 Favorite favorite = new Favorite();
771 favorite.id = c.getLong(ID_INDEX);
772 favorite.screen = c.getInt(SCREEN_INDEX);
773 favorite.container = c.getInt(CONTAINER_INDEX);
774 favorite.cellX = c.getInt(CELLX_INDEX);
775 favorite.cellY = c.getInt(CELLY_INDEX);
776 favorite.spanX = c.getInt(SPANX_INDEX);
777 favorite.spanY = c.getInt(SPANY_INDEX);
778 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
779 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
780 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
781 if (!TextUtils.isEmpty(iconPackage)) {
782 favorite.iconPackage = iconPackage;
783 }
784 String iconResource = c.getString(ICON_RESOURCE_INDEX);
785 if (!TextUtils.isEmpty(iconResource)) {
786 favorite.iconResource = iconResource;
787 }
788 }
789 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
790 byte[] blob = c.getBlob(ICON_INDEX);
791 if (blob != null && blob.length > 0) {
792 favorite.icon = blob;
793 }
794 }
795 String title = c.getString(TITLE_INDEX);
796 if (!TextUtils.isEmpty(title)) {
797 favorite.title = title;
798 }
799 String intent = c.getString(INTENT_INDEX);
800 if (!TextUtils.isEmpty(intent)) {
801 favorite.intent = intent;
802 }
803 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
804 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
805 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
806 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
807 if (!TextUtils.isEmpty(appWidgetProvider)) {
808 favorite.appWidgetProvider = appWidgetProvider;
809 }
810 }
811
812 return writeCheckedBytes(favorite);
813 }
814
815 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Chris Wren5dee7af2013-12-20 17:22:11 -0500816 private ContentValues unpackFavorite(byte[] buffer, int offset, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400817 throws InvalidProtocolBufferNanoException {
818 Favorite favorite = new Favorite();
819 MessageNano.mergeFrom(favorite, readCheckedBytes(buffer, offset, dataSize));
Chris Wren50c8f422014-01-15 16:10:39 -0500820 if (VERBOSE) Log.v(TAG, "unpacked favorite " + favorite.itemType + ", " +
821 (TextUtils.isEmpty(favorite.title) ? favorite.id : favorite.title));
Chris Wren5dee7af2013-12-20 17:22:11 -0500822 ContentValues values = new ContentValues();
823 values.put(Favorites._ID, favorite.id);
824 values.put(Favorites.SCREEN, favorite.screen);
825 values.put(Favorites.CONTAINER, favorite.container);
826 values.put(Favorites.CELLX, favorite.cellX);
827 values.put(Favorites.CELLY, favorite.cellY);
828 values.put(Favorites.SPANX, favorite.spanX);
829 values.put(Favorites.SPANY, favorite.spanY);
830 values.put(Favorites.ICON_TYPE, favorite.iconType);
831 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
832 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
833 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
834 }
835 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
836 values.put(Favorites.ICON, favorite.icon);
837 }
838 if (!TextUtils.isEmpty(favorite.title)) {
839 values.put(Favorites.TITLE, favorite.title);
840 } else {
841 values.put(Favorites.TITLE, "");
842 }
843 if (!TextUtils.isEmpty(favorite.intent)) {
844 values.put(Favorites.INTENT, favorite.intent);
845 }
846 values.put(Favorites.ITEM_TYPE, favorite.itemType);
847 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
848 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
849 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
850 }
851 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
852 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500853
854 // Let LauncherModel know we've been here.
855 values.put(LauncherSettings.Favorites.RESTORED, 1);
856
Chris Wren5dee7af2013-12-20 17:22:11 -0500857 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400858 }
859
860 /** Serialize a Screen for persistence, including a checksum wrapper. */
861 private byte[] packScreen(Cursor c) {
862 Screen screen = new Screen();
863 screen.id = c.getLong(ID_INDEX);
864 screen.rank = c.getInt(SCREEN_RANK_INDEX);
865
866 return writeCheckedBytes(screen);
867 }
868
869 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Chris Wren5dee7af2013-12-20 17:22:11 -0500870 private ContentValues unpackScreen(byte[] buffer, int offset, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400871 throws InvalidProtocolBufferNanoException {
872 Screen screen = new Screen();
873 MessageNano.mergeFrom(screen, readCheckedBytes(buffer, offset, dataSize));
Chris Wren50c8f422014-01-15 16:10:39 -0500874 if (VERBOSE) Log.v(TAG, "unpacked screen " + screen.id + "/" + screen.rank);
Chris Wren5dee7af2013-12-20 17:22:11 -0500875 ContentValues values = new ContentValues();
876 values.put(WorkspaceScreens._ID, screen.id);
877 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
878 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400879 }
880
Chris Wren22e130d2013-09-23 18:25:57 -0400881 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
882 private byte[] packIcon(int dpi, Bitmap icon) {
883 Resource res = new Resource();
884 res.dpi = dpi;
885 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400886 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400887 res.data = os.toByteArray();
888 }
889 return writeCheckedBytes(res);
890 }
891
892 /** Deserialize an icon resource from persistence, after verifying checksum wrapper. */
Chris Wren6d0dde02014-02-10 12:16:54 -0500893 private static Resource unpackIcon(byte[] buffer, int offset, int dataSize)
Chris Wren22e130d2013-09-23 18:25:57 -0400894 throws InvalidProtocolBufferNanoException {
895 Resource res = new Resource();
896 MessageNano.mergeFrom(res, readCheckedBytes(buffer, offset, dataSize));
Chris Wren50c8f422014-01-15 16:10:39 -0500897 if (VERBOSE) Log.v(TAG, "unpacked icon " + res.dpi + "/" + res.data.length);
Chris Wren22e130d2013-09-23 18:25:57 -0400898 return res;
899 }
900
Chris Wrenfd13c712013-09-27 15:45:19 -0400901 /** Serialize a widget for persistence, including a checksum wrapper. */
902 private byte[] packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
903 ComponentName provider) {
904 final AppWidgetProviderInfo info = findAppWidgetProviderInfo(provider);
905 Widget widget = new Widget();
906 widget.provider = provider.flattenToShortString();
907 widget.label = info.label;
908 widget.configure = info.configure != null;
909 if (info.icon != 0) {
910 widget.icon = new Resource();
911 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400912 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400913 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400914 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400915 widget.icon.data = os.toByteArray();
916 widget.icon.dpi = dpi;
917 }
918 }
919 if (info.previewImage != 0) {
920 widget.preview = new Resource();
921 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
922 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400923 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400924 widget.preview.data = os.toByteArray();
925 widget.preview.dpi = dpi;
926 }
927 }
928 return writeCheckedBytes(widget);
929 }
930
931 /** Deserialize a widget from persistence, after verifying checksum wrapper. */
932 private Widget unpackWidget(byte[] buffer, int offset, int dataSize)
933 throws InvalidProtocolBufferNanoException {
934 Widget widget = new Widget();
935 MessageNano.mergeFrom(widget, readCheckedBytes(buffer, offset, dataSize));
Chris Wren50c8f422014-01-15 16:10:39 -0500936 if (VERBOSE) Log.v(TAG, "unpacked widget " + widget.provider);
Chris Wrenfd13c712013-09-27 15:45:19 -0400937 return widget;
938 }
939
Chris Wren1ada10d2013-09-13 18:01:38 -0400940 /**
941 * Read the old journal from the input file.
942 *
943 * In the event of any error, just pretend we didn't have a journal,
944 * in that case, do a full backup.
945 *
946 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -0500947 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -0400948 */
949 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400950 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400951 if (oldState == null) {
952 return journal;
953 }
954 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
955 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500956 int availableBytes = inStream.available();
957 if (DEBUG) Log.d(TAG, "available " + availableBytes);
958 if (availableBytes < MAX_JOURNAL_SIZE) {
959 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -0400960 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -0500961 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -0500962 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500963 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -0400964 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500965 // OMG what are you doing? This is crazy inefficient!
966 // If we read a byte that is not ours, we will cause trouble: b/12491813
967 // However, we don't know how many bytes to expect (oops).
968 // So we have to step through *slowly*, watching for the end.
969 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -0400970 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -0500971 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -0400972 bytesRead += result;
Chris Wren65b6a602014-01-10 14:11:25 -0500973 if (DEBUG && (bytesRead % 100 == 0)) {
974 Log.d(TAG, "read some bytes: " + bytesRead);
975 }
Chris Wren92aa4232013-10-04 11:29:36 -0400976 } else {
Chris Wren65b6a602014-01-10 14:11:25 -0500977 Log.w(TAG, "unexpected end of file while reading journal.");
978 // stop reading and see what there is to parse
979 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400980 }
981 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -0400982 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500983 availableBytes = 0;
984 }
985
986 // check the buffer to see if we have a valid journal
987 try {
988 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, 0, bytesRead));
989 // if we are here, then we have read a valid, checksum-verified journal
990 valid = true;
991 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -0500992 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -0500993 } catch (InvalidProtocolBufferNanoException e) {
994 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -0500995 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -0500996 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -0400997 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400998 }
Chris Wren92aa4232013-10-04 11:29:36 -0400999 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001000 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001001 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001002 }
1003 }
Chris Wren92aa4232013-10-04 11:29:36 -04001004 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001005 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001006 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001007 try {
1008 inStream.close();
1009 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001010 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001011 }
1012 }
1013 return journal;
1014 }
1015
Chris Wren22e130d2013-09-23 18:25:57 -04001016 private void writeRowToBackup(Key key, byte[] blob, Journal out,
1017 BackupDataOutput data) throws IOException {
1018 String backupKey = keyToBackupKey(key);
1019 data.writeEntityHeader(backupKey, blob.length);
1020 data.writeEntityData(blob, blob.length);
1021 out.rows++;
1022 out.bytes += blob.length;
Chris Wren50c8f422014-01-15 16:10:39 -05001023 if (VERBOSE) Log.v(TAG, "saving " + geKeyType(key) + " " + backupKey + ": " +
Chris Wren22e130d2013-09-23 18:25:57 -04001024 getKeyName(key) + "/" + blob.length);
Chris Wren92aa4232013-10-04 11:29:36 -04001025 if(DEBUG_PAYLOAD) {
Chris Wren2b6c21d2013-10-02 14:16:04 -04001026 String encoded = Base64.encodeToString(blob, 0, blob.length, Base64.NO_WRAP);
1027 final int chunkSize = 1024;
1028 for (int offset = 0; offset < encoded.length(); offset += chunkSize) {
1029 int end = offset + chunkSize;
1030 end = Math.min(end, encoded.length());
Chris Wren50c8f422014-01-15 16:10:39 -05001031 Log.w(TAG, "wrote " + encoded.substring(offset, end));
Chris Wren2b6c21d2013-10-02 14:16:04 -04001032 }
1033 }
Chris Wren22e130d2013-09-23 18:25:57 -04001034 }
1035
1036 private Set<String> getSavedIdsByType(int type, Journal in) {
1037 Set<String> savedIds = new HashSet<String>();
1038 for(int i = 0; i < in.key.length; i++) {
1039 Key key = in.key[i];
1040 if (key.type == type) {
1041 savedIds.add(keyToBackupKey(key));
1042 }
1043 }
1044 return savedIds;
1045 }
1046
1047 private int removeDeletedKeysFromBackup(Set<String> deletedIds, BackupDataOutput data)
1048 throws IOException {
1049 int rows = 0;
1050 for(String deleted: deletedIds) {
Chris Wren50c8f422014-01-15 16:10:39 -05001051 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
Chris Wren22e130d2013-09-23 18:25:57 -04001052 data.writeEntityHeader(deleted, -1);
1053 rows++;
1054 }
1055 return rows;
1056 }
1057
Chris Wren1ada10d2013-09-13 18:01:38 -04001058 /**
1059 * Write the new journal to the output file.
1060 *
1061 * In the event of any error, just pretend we didn't have a journal,
1062 * in that case, do a full backup.
1063
1064 * @param newState the write-only file descriptor pointing to the new journal
1065 * @param journal a Journal protocol buffer
1066 */
1067 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1068 FileOutputStream outStream = null;
1069 try {
1070 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001071 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001072 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001073 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001074 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001075 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001076 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001077 }
1078 }
1079
1080 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1081 private byte[] writeCheckedBytes(MessageNano proto) {
1082 CheckedMessage wrapper = new CheckedMessage();
1083 wrapper.payload = MessageNano.toByteArray(proto);
1084 CRC32 checksum = new CRC32();
1085 checksum.update(wrapper.payload);
1086 wrapper.checksum = checksum.getValue();
1087 return MessageNano.toByteArray(wrapper);
1088 }
1089
1090 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Chris Wren6d0dde02014-02-10 12:16:54 -05001091 private static byte[] readCheckedBytes(byte[] buffer, int offset, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001092 throws InvalidProtocolBufferNanoException {
1093 CheckedMessage wrapper = new CheckedMessage();
1094 MessageNano.mergeFrom(wrapper, buffer, offset, dataSize);
1095 CRC32 checksum = new CRC32();
1096 checksum.update(wrapper.payload);
1097 if (wrapper.checksum != checksum.getValue()) {
1098 throw new InvalidProtocolBufferNanoException("checksum does not match");
1099 }
1100 return wrapper.payload;
1101 }
1102
Chris Wrenfd13c712013-09-27 15:45:19 -04001103 private AppWidgetProviderInfo findAppWidgetProviderInfo(ComponentName component) {
1104 if (mWidgetMap == null) {
1105 List<AppWidgetProviderInfo> widgets =
Chris Wren92aa4232013-10-04 11:29:36 -04001106 AppWidgetManager.getInstance(mContext).getInstalledProviders();
Chris Wrenfd13c712013-09-27 15:45:19 -04001107 mWidgetMap = new HashMap<ComponentName, AppWidgetProviderInfo>(widgets.size());
1108 for (AppWidgetProviderInfo info : widgets) {
1109 mWidgetMap.put(info.provider, info);
1110 }
1111 }
1112 return mWidgetMap.get(component);
1113 }
1114
Chris Wren6d0dde02014-02-10 12:16:54 -05001115
1116 private boolean initializeIconCache() {
1117 if (mIconCache != null) {
1118 return true;
1119 }
1120
1121 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
1122 if (appState == null) {
1123 Throwable stackTrace = new Throwable();
1124 stackTrace.fillInStackTrace();
1125 Log.w(TAG, "Failed to get app state during backup/restore", stackTrace);
1126 return false;
1127 }
1128 mIconCache = appState.getIconCache();
1129 return mIconCache != null;
1130 }
1131
Chris Wren1ada10d2013-09-13 18:01:38 -04001132 private class KeyParsingException extends Throwable {
1133 private KeyParsingException(Throwable cause) {
1134 super(cause);
1135 }
1136
1137 public KeyParsingException(String reason) {
1138 super(reason);
1139 }
1140 }
1141}