blob: 81ced7b3b79a3e8c1488da6e999e43a2476879b8 [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;
Kenny Guyed131872014-04-30 03:02:21 +010031import com.android.launcher3.compat.UserManagerCompat;
32import com.android.launcher3.compat.UserHandleCompat;
Chris Wren1ada10d2013-09-13 18:01:38 -040033
Chris Wren92aa4232013-10-04 11:29:36 -040034import android.app.backup.BackupDataInputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040035import android.app.backup.BackupDataOutput;
Chris Wren4d89e2a2013-10-09 17:03:50 -040036import android.app.backup.BackupHelper;
Chris Wren1ada10d2013-09-13 18:01:38 -040037import android.app.backup.BackupManager;
Chris Wren22e130d2013-09-23 18:25:57 -040038import android.appwidget.AppWidgetManager;
39import android.appwidget.AppWidgetProviderInfo;
40import android.content.ComponentName;
Chris Wren1ada10d2013-09-13 18:01:38 -040041import android.content.ContentResolver;
Chris Wren5dee7af2013-12-20 17:22:11 -050042import android.content.ContentValues;
Chris Wren1ada10d2013-09-13 18:01:38 -040043import android.content.Context;
Chris Wren22e130d2013-09-23 18:25:57 -040044import android.content.Intent;
Chris Wren1ada10d2013-09-13 18:01:38 -040045import android.database.Cursor;
Chris Wren22e130d2013-09-23 18:25:57 -040046import android.graphics.Bitmap;
47import android.graphics.BitmapFactory;
Chris Wrenfd13c712013-09-27 15:45:19 -040048import android.graphics.drawable.Drawable;
Chris Wren1ada10d2013-09-13 18:01:38 -040049import android.os.ParcelFileDescriptor;
Chris Wren1ada10d2013-09-13 18:01:38 -040050import android.text.TextUtils;
51import android.util.Base64;
52import android.util.Log;
53
Chris Wren22e130d2013-09-23 18:25:57 -040054import java.io.ByteArrayOutputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040055import java.io.FileInputStream;
56import 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
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100113 Favorites.PROFILE_ID, // 17
Chris Wren1ada10d2013-09-13 18:01:38 -0400114 };
115
116 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400117 private static final int ID_MODIFIED = 1;
118 private static final int INTENT_INDEX = 2;
119 private static final int APPWIDGET_PROVIDER_INDEX = 3;
120 private static final int APPWIDGET_ID_INDEX = 4;
121 private static final int CELLX_INDEX = 5;
122 private static final int CELLY_INDEX = 6;
123 private static final int CONTAINER_INDEX = 7;
124 private static final int ICON_INDEX = 8;
125 private static final int ICON_PACKAGE_INDEX = 9;
126 private static final int ICON_RESOURCE_INDEX = 10;
127 private static final int ICON_TYPE_INDEX = 11;
128 private static final int ITEM_TYPE_INDEX = 12;
129 private static final int SCREEN_INDEX = 13;
130 private static final int SPANX_INDEX = 14;
131 private static final int SPANY_INDEX = 15;
132 private static final int TITLE_INDEX = 16;
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100133 private static final int PROFILE_ID_INDEX = 17;
Chris Wren1ada10d2013-09-13 18:01:38 -0400134
135 private static final String[] SCREEN_PROJECTION = {
136 WorkspaceScreens._ID, // 0
Chris Wren22e130d2013-09-23 18:25:57 -0400137 WorkspaceScreens.MODIFIED, // 1
138 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400139 };
140
Chris Wren22e130d2013-09-23 18:25:57 -0400141 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400142
Chris Wren6d0dde02014-02-10 12:16:54 -0500143 private static IconCache mIconCache;
144
Chris Wren92aa4232013-10-04 11:29:36 -0400145 private final Context mContext;
Chris Wren1ada10d2013-09-13 18:01:38 -0400146
Chris Wren4b171362014-01-13 17:39:02 -0500147 private final boolean mRestoreEnabled;
148
Chris Wren22e130d2013-09-23 18:25:57 -0400149 private HashMap<ComponentName, AppWidgetProviderInfo> mWidgetMap;
150
Chris Wren92aa4232013-10-04 11:29:36 -0400151 private ArrayList<Key> mKeys;
Chris Wren1ada10d2013-09-13 18:01:38 -0400152
Chris Wren4b171362014-01-13 17:39:02 -0500153 public LauncherBackupHelper(Context context, boolean restoreEnabled) {
Chris Wren92aa4232013-10-04 11:29:36 -0400154 mContext = context;
Chris Wren4b171362014-01-13 17:39:02 -0500155 mRestoreEnabled = restoreEnabled;
Chris Wren92aa4232013-10-04 11:29:36 -0400156 }
157
158 private void dataChanged() {
Chris Wren1ada10d2013-09-13 18:01:38 -0400159 if (sBackupManager == null) {
Chris Wren92aa4232013-10-04 11:29:36 -0400160 sBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400161 }
162 sBackupManager.dataChanged();
163 }
164
165 /**
166 * Back up launcher data so we can restore the user's state on a new device.
167 *
168 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
169 *
170 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
171 *
172 * @param oldState notes from the last backup
173 * @param data incremental key/value pairs to persist off-device
174 * @param newState notes for the next backup
175 * @throws IOException
176 */
177 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400178 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
179 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500180 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400181
182 Journal in = readJournal(oldState);
183 Journal out = new Journal();
184
185 long lastBackupTime = in.t;
186 out.t = System.currentTimeMillis();
187 out.rows = 0;
188 out.bytes = 0;
189
Chris Wren50c8f422014-01-15 16:10:39 -0500190 Log.v(TAG, "lastBackupTime = " + lastBackupTime);
Chris Wren1ada10d2013-09-13 18:01:38 -0400191
192 ArrayList<Key> keys = new ArrayList<Key>();
Chris Wren71144262014-02-27 15:49:39 -0500193 if (launcherIsReady()) {
194 try {
195 backupFavorites(in, data, out, keys);
196 backupScreens(in, data, out, keys);
197 backupIcons(in, data, out, keys);
198 backupWidgets(in, data, out, keys);
199 } catch (IOException e) {
200 Log.e(TAG, "launcher backup has failed", e);
201 }
202 out.key = keys.toArray(new BackupProtos.Key[keys.size()]);
203 } else {
204 out = in;
Chris Wren92aa4232013-10-04 11:29:36 -0400205 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400206
Chris Wren1ada10d2013-09-13 18:01:38 -0400207 writeJournal(newState, out);
208 Log.v(TAG, "onBackup: wrote " + out.bytes + "b in " + out.rows + " rows.");
Chris Wren1ada10d2013-09-13 18:01:38 -0400209 }
210
211 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400212 * Restore launcher configuration from the restored data stream.
Chris Wren1ada10d2013-09-13 18:01:38 -0400213 *
214 * <P>Keys may arrive in any order.
215 *
Chris Wren92aa4232013-10-04 11:29:36 -0400216 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400217 */
218 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400219 public void restoreEntity(BackupDataInputStream data) {
Chris Wren50c8f422014-01-15 16:10:39 -0500220 if (VERBOSE) Log.v(TAG, "restoreEntity");
Chris Wren92aa4232013-10-04 11:29:36 -0400221 if (mKeys == null) {
222 mKeys = new ArrayList<Key>();
223 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400224 byte[] buffer = new byte[512];
Chris Wren1ada10d2013-09-13 18:01:38 -0400225 String backupKey = data.getKey();
Chris Wren92aa4232013-10-04 11:29:36 -0400226 int dataSize = data.size();
Chris Wren1ada10d2013-09-13 18:01:38 -0400227 if (buffer.length < dataSize) {
228 buffer = new byte[dataSize];
229 }
230 Key key = null;
Chris Wren92aa4232013-10-04 11:29:36 -0400231 int bytesRead = 0;
232 try {
233 bytesRead = data.read(buffer, 0, dataSize);
234 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
235 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500236 Log.e(TAG, "failed to read entity from restore data", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400237 }
238 try {
239 key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500240 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400241 switch (key.type) {
242 case Key.FAVORITE:
243 restoreFavorite(key, buffer, dataSize, mKeys);
244 break;
245
246 case Key.SCREEN:
247 restoreScreen(key, buffer, dataSize, mKeys);
248 break;
249
250 case Key.ICON:
251 restoreIcon(key, buffer, dataSize, mKeys);
252 break;
253
254 case Key.WIDGET:
255 restoreWidget(key, buffer, dataSize, mKeys);
256 break;
257
258 default:
259 Log.w(TAG, "unknown restore entity type: " + key.type);
260 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400261 }
Chris Wren92aa4232013-10-04 11:29:36 -0400262 } catch (KeyParsingException e) {
263 Log.w(TAG, "ignoring unparsable backup key: " + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400264 }
265
Chris Wren92aa4232013-10-04 11:29:36 -0400266 }
267
268 /**
269 * Record the restore state for the next backup.
270 *
271 * @param newState notes about the backup state after restore.
272 */
273 @Override
274 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400275 // clear the output journal time, to force a full backup to
276 // will catch any changes the restore process might have made
Chris Wren92aa4232013-10-04 11:29:36 -0400277 Journal out = new Journal();
Chris Wren1ada10d2013-09-13 18:01:38 -0400278 out.t = 0;
Mac Duy Hai22dc65e2014-02-05 10:52:07 +0000279 out.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
Chris Wren1ada10d2013-09-13 18:01:38 -0400280 writeJournal(newState, out);
Chris Wren92aa4232013-10-04 11:29:36 -0400281 Log.v(TAG, "onRestore: read " + mKeys.size() + " rows");
282 mKeys.clear();
Chris Wren1ada10d2013-09-13 18:01:38 -0400283 }
284
285 /**
286 * Write all modified favorites to the data stream.
287 *
288 *
289 * @param in notes from last backup
290 * @param data output stream for key/value pairs
291 * @param out notes about this backup
292 * @param keys keys to mark as clean in the notes for next backup
293 * @throws IOException
294 */
295 private void backupFavorites(Journal in, BackupDataOutput data, Journal out,
296 ArrayList<Key> keys)
297 throws IOException {
298 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400299 Set<String> savedIds = getSavedIdsByType(Key.FAVORITE, in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400300 if (DEBUG) Log.d(TAG, "favorite savedIds.size()=" + savedIds.size());
301
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100302 // Don't backup apps in other profiles for now.
303 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
304 long userSerialNumber =
305 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
306
Chris Wren1ada10d2013-09-13 18:01:38 -0400307 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400308 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400309 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
310 null, null, null);
311 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400312 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400313 cursor.moveToPosition(-1);
314 while(cursor.moveToNext()) {
315 final long id = cursor.getLong(ID_INDEX);
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100316 final long profileId = cursor.getLong(PROFILE_ID_INDEX);
317 if (userSerialNumber == profileId) {
318 final long updateTime = cursor.getLong(ID_MODIFIED);
319 Key key = getKey(Key.FAVORITE, id);
320 keys.add(key);
321 final String backupKey = keyToBackupKey(key);
322 currentIds.add(backupKey);
323 if (!savedIds.contains(backupKey) || updateTime >= in.t) {
324 byte[] blob = packFavorite(cursor);
325 writeRowToBackup(key, blob, out, data);
326 } else {
327 if (VERBOSE) Log.v(TAG, "favorite " + id + " was too old: " + updateTime);
328 }
Chris Wren50c8f422014-01-15 16:10:39 -0500329 } else {
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100330 if (VERBOSE) Log.v(TAG, "favorite " + id + " is for other profile: "
331 + profileId);
Chris Wren22e130d2013-09-23 18:25:57 -0400332 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400333 }
334 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400335 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400336 }
337 if (DEBUG) Log.d(TAG, "favorite currentIds.size()=" + currentIds.size());
338
339 // these IDs must have been deleted
340 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400341 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400342 }
343
344 /**
345 * Read a favorite from the stream.
346 *
347 * <P>Keys arrive in any order, so screens and containers may not exist yet.
348 *
349 * @param key identifier for the row
350 * @param buffer the serialized proto from the stream, may be larger than dataSize
351 * @param dataSize the size of the proto from the stream
352 * @param keys keys to mark as clean in the notes for next backup
353 */
354 private void restoreFavorite(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
Chris Wren50c8f422014-01-15 16:10:39 -0500355 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400356 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
357 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
358
Chris Wren5dee7af2013-12-20 17:22:11 -0500359 if (!mRestoreEnabled) {
Chris Wren50c8f422014-01-15 16:10:39 -0500360 if (VERBOSE) Log.v(TAG, "restore not enabled: skipping database mutation");
Chris Wren5dee7af2013-12-20 17:22:11 -0500361 return;
362 }
363
Chris Wren1ada10d2013-09-13 18:01:38 -0400364 try {
Chris Wren5dee7af2013-12-20 17:22:11 -0500365 ContentResolver cr = mContext.getContentResolver();
366 ContentValues values = unpackFavorite(buffer, 0, dataSize);
367 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400368 } catch (InvalidProtocolBufferNanoException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500369 Log.e(TAG, "failed to decode favorite", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400370 }
371 }
372
373 /**
374 * Write all modified screens to the data stream.
375 *
376 *
377 * @param in notes from last backup
378 * @param data output stream for key/value pairs
379 * @param out notes about this backup
Chris Wren22e130d2013-09-23 18:25:57 -0400380 * @param keys keys to mark as clean in the notes for next backup
381 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400382 */
383 private void backupScreens(Journal in, BackupDataOutput data, Journal out,
384 ArrayList<Key> keys)
385 throws IOException {
386 // read the old ID set
Chris Wren22e130d2013-09-23 18:25:57 -0400387 Set<String> savedIds = getSavedIdsByType(Key.SCREEN, in);
388 if (DEBUG) Log.d(TAG, "screen savedIds.size()=" + savedIds.size());
Chris Wren1ada10d2013-09-13 18:01:38 -0400389
390 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400391 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400392 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
393 null, null, null);
394 Set<String> currentIds = new HashSet<String>(cursor.getCount());
Chris Wren1ada10d2013-09-13 18:01:38 -0400395 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400396 cursor.moveToPosition(-1);
Chris Wren50c8f422014-01-15 16:10:39 -0500397 if (DEBUG) Log.d(TAG, "dumping screens after: " + in.t);
Chris Wren22e130d2013-09-23 18:25:57 -0400398 while(cursor.moveToNext()) {
399 final long id = cursor.getLong(ID_INDEX);
400 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400401 Key key = getKey(Key.SCREEN, id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400402 keys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500403 final String backupKey = keyToBackupKey(key);
404 currentIds.add(backupKey);
405 if (!savedIds.contains(backupKey) || updateTime >= in.t) {
Chris Wren22e130d2013-09-23 18:25:57 -0400406 byte[] blob = packScreen(cursor);
407 writeRowToBackup(key, blob, out, data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500408 } else {
Chris Wren50c8f422014-01-15 16:10:39 -0500409 if (VERBOSE) Log.v(TAG, "screen " + id + " was too old: " + updateTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400410 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400411 }
412 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400413 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400414 }
415 if (DEBUG) Log.d(TAG, "screen currentIds.size()=" + currentIds.size());
416
417 // these IDs must have been deleted
418 savedIds.removeAll(currentIds);
Chris Wren22e130d2013-09-23 18:25:57 -0400419 out.rows += removeDeletedKeysFromBackup(savedIds, data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400420 }
421
422 /**
423 * Read a screen from the stream.
424 *
425 * <P>Keys arrive in any order, so children of this screen may already exist.
426 *
427 * @param key identifier for the row
428 * @param buffer the serialized proto from the stream, may be larger than dataSize
429 * @param dataSize the size of the proto from the stream
430 * @param keys keys to mark as clean in the notes for next backup
431 */
432 private void restoreScreen(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
Chris Wren50c8f422014-01-15 16:10:39 -0500433 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400434 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
435 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500436
437 if (!mRestoreEnabled) {
Chris Wren50c8f422014-01-15 16:10:39 -0500438 if (VERBOSE) Log.v(TAG, "restore not enabled: skipping database mutation");
Chris Wren5dee7af2013-12-20 17:22:11 -0500439 return;
440 }
441
Chris Wren1ada10d2013-09-13 18:01:38 -0400442 try {
Chris Wren5dee7af2013-12-20 17:22:11 -0500443 ContentResolver cr = mContext.getContentResolver();
444 ContentValues values = unpackScreen(buffer, 0, dataSize);
445 cr.insert(WorkspaceScreens.CONTENT_URI, values);
446
Chris Wren1ada10d2013-09-13 18:01:38 -0400447 } catch (InvalidProtocolBufferNanoException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500448 Log.e(TAG, "failed to decode screen", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400449 }
450 }
451
Chris Wren22e130d2013-09-23 18:25:57 -0400452 /**
453 * Write all the static icon resources we need to render placeholders
454 * for a package that is not installed.
455 *
456 * @param in notes from last backup
457 * @param data output stream for key/value pairs
458 * @param out notes about this backup
459 * @param keys keys to mark as clean in the notes for next backup
460 * @throws IOException
461 */
462 private void backupIcons(Journal in, BackupDataOutput data, Journal out,
463 ArrayList<Key> keys) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400464 // persist icons that haven't been persisted yet
Chris Wren6d0dde02014-02-10 12:16:54 -0500465 if (!initializeIconCache()) {
Chris Wren92aa4232013-10-04 11:29:36 -0400466 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400467 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
468 return;
469 }
Chris Wren92aa4232013-10-04 11:29:36 -0400470 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400471 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wren22e130d2013-09-23 18:25:57 -0400472
473 // read the old ID set
474 Set<String> savedIds = getSavedIdsByType(Key.ICON, in);
475 if (DEBUG) Log.d(TAG, "icon savedIds.size()=" + savedIds.size());
476
Kenny Guyed131872014-04-30 03:02:21 +0100477 // Don't backup apps in other profiles for now.
478 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
479 long userSerialNumber =
480 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
Chris Wren22e130d2013-09-23 18:25:57 -0400481 int startRows = out.rows;
482 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
Kenny Guyed131872014-04-30 03:02:21 +0100483 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100484 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Kenny Guyed131872014-04-30 03:02:21 +0100485 Favorites.PROFILE_ID + "=" + userSerialNumber;
Chris Wren22e130d2013-09-23 18:25:57 -0400486 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
487 where, null, null);
488 Set<String> currentIds = new HashSet<String>(cursor.getCount());
489 try {
490 cursor.moveToPosition(-1);
491 while(cursor.moveToNext()) {
492 final long id = cursor.getLong(ID_INDEX);
493 final String intentDescription = cursor.getString(INTENT_INDEX);
494 try {
495 Intent intent = Intent.parseUri(intentDescription, 0);
496 ComponentName cn = intent.getComponent();
497 Key key = null;
498 String backupKey = null;
499 if (cn != null) {
500 key = getKey(Key.ICON, cn.flattenToShortString());
501 backupKey = keyToBackupKey(key);
502 currentIds.add(backupKey);
503 } else {
504 Log.w(TAG, "empty intent on application favorite: " + id);
505 }
506 if (savedIds.contains(backupKey)) {
Chris Wren50c8f422014-01-15 16:10:39 -0500507 if (VERBOSE) Log.v(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400508
509 // remember that we already backed this up previously
510 keys.add(key);
511 } else if (backupKey != null) {
512 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
513 if ((out.rows - startRows) < MAX_ICONS_PER_PASS) {
Chris Wren50c8f422014-01-15 16:10:39 -0500514 if (VERBOSE) Log.v(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100515 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Chris Wren22e130d2013-09-23 18:25:57 -0400516 keys.add(key);
Kenny Guyed131872014-04-30 03:02:21 +0100517 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400518 byte[] blob = packIcon(dpi, icon);
519 writeRowToBackup(key, blob, out, data);
520 }
521 } else {
Chris Wren50c8f422014-01-15 16:10:39 -0500522 if (VERBOSE) Log.d(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400523 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400524 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400525 }
526 }
527 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500528 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400529 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500530 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400531 }
532
533 }
534 } finally {
535 cursor.close();
536 }
537 if (DEBUG) Log.d(TAG, "icon currentIds.size()=" + currentIds.size());
538
539 // these IDs must have been deleted
540 savedIds.removeAll(currentIds);
541 out.rows += removeDeletedKeysFromBackup(savedIds, data);
542 }
543
544 /**
545 * Read an icon from the stream.
546 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400547 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400548 *
549 * @param key identifier for the row
550 * @param buffer the serialized proto from the stream, may be larger than dataSize
551 * @param dataSize the size of the proto from the stream
552 * @param keys keys to mark as clean in the notes for next backup
553 */
554 private void restoreIcon(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
Chris Wren50c8f422014-01-15 16:10:39 -0500555 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400556 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
557 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500558
Chris Wren22e130d2013-09-23 18:25:57 -0400559 try {
560 Resource res = unpackIcon(buffer, 0, dataSize);
Chris Wren6d0dde02014-02-10 12:16:54 -0500561 if (DEBUG) {
562 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
563 }
564 if (DEBUG_PAYLOAD) {
565 Log.d(TAG, "read " +
566 Base64.encodeToString(res.data, 0, res.data.length,
567 Base64.NO_WRAP));
568 }
Chris Wren22e130d2013-09-23 18:25:57 -0400569 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
570 if (icon == null) {
571 Log.w(TAG, "failed to unpack icon for " + key.name);
572 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500573
574 if (!mRestoreEnabled) {
Chris Wren6d0dde02014-02-10 12:16:54 -0500575 if (VERBOSE) {
576 Log.v(TAG, "restore not enabled: skipping database mutation");
577 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500578 return;
579 } else {
Chris Wren6d0dde02014-02-10 12:16:54 -0500580 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(key.name),
581 icon, res.dpi);
Chris Wren5dee7af2013-12-20 17:22:11 -0500582 }
Chris Wren6d0dde02014-02-10 12:16:54 -0500583 } catch (IOException e) {
584 Log.d(TAG, "failed to save restored icon for: " + key.name, e);
Chris Wren22e130d2013-09-23 18:25:57 -0400585 }
586 }
587
Chris Wrenfd13c712013-09-27 15:45:19 -0400588 /**
589 * Write all the static widget resources we need to render placeholders
590 * for a package that is not installed.
591 *
592 * @param in notes from last backup
593 * @param data output stream for key/value pairs
594 * @param out notes about this backup
595 * @param keys keys to mark as clean in the notes for next backup
596 * @throws IOException
597 */
598 private void backupWidgets(Journal in, BackupDataOutput data, Journal out,
599 ArrayList<Key> keys) throws IOException {
600 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400601 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
Chris Wren6d0dde02014-02-10 12:16:54 -0500602 if (appState == null || !initializeIconCache()) {
603 Log.w(TAG, "Failed to get icon cache during restore");
Chris Wrend8fe6de2013-10-04 10:42:14 -0400604 return;
605 }
Chris Wren92aa4232013-10-04 11:29:36 -0400606 final ContentResolver cr = mContext.getContentResolver();
607 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
608 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wren92aa4232013-10-04 11:29:36 -0400609 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400610 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
611 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
612
613 // read the old ID set
614 Set<String> savedIds = getSavedIdsByType(Key.WIDGET, in);
615 if (DEBUG) Log.d(TAG, "widgets savedIds.size()=" + savedIds.size());
616
617 int startRows = out.rows;
618 if (DEBUG) Log.d(TAG, "starting here: " + startRows);
619 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET;
620 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
621 where, null, null);
622 Set<String> currentIds = new HashSet<String>(cursor.getCount());
623 try {
624 cursor.moveToPosition(-1);
625 while(cursor.moveToNext()) {
626 final long id = cursor.getLong(ID_INDEX);
627 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
628 final int spanX = cursor.getInt(SPANX_INDEX);
629 final int spanY = cursor.getInt(SPANY_INDEX);
630 final ComponentName provider = ComponentName.unflattenFromString(providerName);
631 Key key = null;
632 String backupKey = null;
633 if (provider != null) {
634 key = getKey(Key.WIDGET, providerName);
635 backupKey = keyToBackupKey(key);
636 currentIds.add(backupKey);
637 } else {
638 Log.w(TAG, "empty intent on appwidget: " + id);
639 }
640 if (savedIds.contains(backupKey)) {
Chris Wren50c8f422014-01-15 16:10:39 -0500641 if (VERBOSE) Log.v(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400642
643 // remember that we already backed this up previously
644 keys.add(key);
645 } else if (backupKey != null) {
646 if (DEBUG) Log.d(TAG, "I can count this high: " + out.rows);
647 if ((out.rows - startRows) < MAX_WIDGETS_PER_PASS) {
Chris Wren50c8f422014-01-15 16:10:39 -0500648 if (VERBOSE) Log.v(TAG, "saving widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400649 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
650 spanY * profile.cellHeightPx, widgetSpacingLayout);
Chris Wren6d0dde02014-02-10 12:16:54 -0500651 byte[] blob = packWidget(dpi, previewLoader, mIconCache, provider);
Chris Wrenb1fd63b2013-10-03 15:43:58 -0400652 keys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400653 writeRowToBackup(key, blob, out, data);
654
655 } else {
Chris Wren50c8f422014-01-15 16:10:39 -0500656 if (VERBOSE) Log.d(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400657 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400658 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400659 }
660 }
661 }
662 } finally {
663 cursor.close();
664 }
665 if (DEBUG) Log.d(TAG, "widget currentIds.size()=" + currentIds.size());
666
667 // these IDs must have been deleted
668 savedIds.removeAll(currentIds);
669 out.rows += removeDeletedKeysFromBackup(savedIds, data);
670 }
671
672 /**
673 * Read a widget from the stream.
674 *
675 * <P>Keys arrive in any order, so widgets that use this data may already exist.
676 *
677 * @param key identifier for the row
678 * @param buffer the serialized proto from the stream, may be larger than dataSize
679 * @param dataSize the size of the proto from the stream
680 * @param keys keys to mark as clean in the notes for next backup
681 */
682 private void restoreWidget(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
Chris Wren50c8f422014-01-15 16:10:39 -0500683 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400684 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
685 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
686 try {
687 Widget widget = unpackWidget(buffer, 0, dataSize);
688 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
689 if (widget.icon.data != null) {
690 Bitmap icon = BitmapFactory
691 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
692 if (icon == null) {
693 Log.w(TAG, "failed to unpack widget icon for " + key.name);
694 }
695 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500696
697 if (!mRestoreEnabled) {
Chris Wren50c8f422014-01-15 16:10:39 -0500698 if (VERBOSE) Log.v(TAG, "restore not enabled: skipping database mutation");
Chris Wren5dee7af2013-12-20 17:22:11 -0500699 return;
700 } else {
701 // future site of widget table mutation
702 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400703 } catch (InvalidProtocolBufferNanoException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500704 Log.e(TAG, "failed to decode widget", e);
Chris Wrenfd13c712013-09-27 15:45:19 -0400705 }
706 }
707
Chris Wren22e130d2013-09-23 18:25:57 -0400708 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400709 *
710 * <P> Keys contain their own checksum instead of using
711 * the heavy-weight CheckedMessage wrapper.
712 */
713 private Key getKey(int type, long id) {
714 Key key = new Key();
715 key.type = type;
716 key.id = id;
717 key.checksum = checkKey(key);
718 return key;
719 }
720
Chris Wren22e130d2013-09-23 18:25:57 -0400721 /** create a new key for a named object.
722 *
723 * <P> Keys contain their own checksum instead of using
724 * the heavy-weight CheckedMessage wrapper.
725 */
726 private Key getKey(int type, String name) {
727 Key key = new Key();
728 key.type = type;
729 key.name = name;
730 key.checksum = checkKey(key);
731 return key;
732 }
733
Chris Wren1ada10d2013-09-13 18:01:38 -0400734 /** keys need to be strings, serialize and encode. */
735 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400736 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400737 }
738
739 /** keys need to be strings, decode and parse. */
740 private Key backupKeyToKey(String backupKey) throws KeyParsingException {
741 try {
742 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
743 if (key.checksum != checkKey(key)) {
744 key = null;
745 throw new KeyParsingException("invalid key read from stream" + backupKey);
746 }
747 return key;
748 } catch (InvalidProtocolBufferNanoException e) {
749 throw new KeyParsingException(e);
750 } catch (IllegalArgumentException e) {
751 throw new KeyParsingException(e);
752 }
753 }
754
Chris Wren22e130d2013-09-23 18:25:57 -0400755 private String getKeyName(Key key) {
756 if (TextUtils.isEmpty(key.name)) {
757 return Long.toString(key.id);
758 } else {
759 return key.name;
760 }
761
762 }
763
764 private String geKeyType(Key key) {
765 switch (key.type) {
766 case Key.FAVORITE:
767 return "favorite";
768 case Key.SCREEN:
769 return "screen";
770 case Key.ICON:
771 return "icon";
Chris Wrenfd13c712013-09-27 15:45:19 -0400772 case Key.WIDGET:
773 return "widget";
Chris Wren22e130d2013-09-23 18:25:57 -0400774 default:
775 return "anonymous";
776 }
777 }
778
Chris Wren1ada10d2013-09-13 18:01:38 -0400779 /** Compute the checksum over the important bits of a key. */
780 private long checkKey(Key key) {
781 CRC32 checksum = new CRC32();
782 checksum.update(key.type);
783 checksum.update((int) (key.id & 0xffff));
784 checksum.update((int) ((key.id >> 32) & 0xffff));
785 if (!TextUtils.isEmpty(key.name)) {
786 checksum.update(key.name.getBytes());
787 }
788 return checksum.getValue();
789 }
790
791 /** Serialize a Favorite for persistence, including a checksum wrapper. */
792 private byte[] packFavorite(Cursor c) {
793 Favorite favorite = new Favorite();
794 favorite.id = c.getLong(ID_INDEX);
795 favorite.screen = c.getInt(SCREEN_INDEX);
796 favorite.container = c.getInt(CONTAINER_INDEX);
797 favorite.cellX = c.getInt(CELLX_INDEX);
798 favorite.cellY = c.getInt(CELLY_INDEX);
799 favorite.spanX = c.getInt(SPANX_INDEX);
800 favorite.spanY = c.getInt(SPANY_INDEX);
801 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
802 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
803 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
804 if (!TextUtils.isEmpty(iconPackage)) {
805 favorite.iconPackage = iconPackage;
806 }
807 String iconResource = c.getString(ICON_RESOURCE_INDEX);
808 if (!TextUtils.isEmpty(iconResource)) {
809 favorite.iconResource = iconResource;
810 }
811 }
812 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
813 byte[] blob = c.getBlob(ICON_INDEX);
814 if (blob != null && blob.length > 0) {
815 favorite.icon = blob;
816 }
817 }
818 String title = c.getString(TITLE_INDEX);
819 if (!TextUtils.isEmpty(title)) {
820 favorite.title = title;
821 }
822 String intent = c.getString(INTENT_INDEX);
823 if (!TextUtils.isEmpty(intent)) {
824 favorite.intent = intent;
825 }
826 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
827 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
828 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
829 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
830 if (!TextUtils.isEmpty(appWidgetProvider)) {
831 favorite.appWidgetProvider = appWidgetProvider;
832 }
833 }
834
835 return writeCheckedBytes(favorite);
836 }
837
838 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Chris Wren5dee7af2013-12-20 17:22:11 -0500839 private ContentValues unpackFavorite(byte[] buffer, int offset, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400840 throws InvalidProtocolBufferNanoException {
841 Favorite favorite = new Favorite();
842 MessageNano.mergeFrom(favorite, readCheckedBytes(buffer, offset, dataSize));
Chris Wren50c8f422014-01-15 16:10:39 -0500843 if (VERBOSE) Log.v(TAG, "unpacked favorite " + favorite.itemType + ", " +
844 (TextUtils.isEmpty(favorite.title) ? favorite.id : favorite.title));
Chris Wren5dee7af2013-12-20 17:22:11 -0500845 ContentValues values = new ContentValues();
846 values.put(Favorites._ID, favorite.id);
847 values.put(Favorites.SCREEN, favorite.screen);
848 values.put(Favorites.CONTAINER, favorite.container);
849 values.put(Favorites.CELLX, favorite.cellX);
850 values.put(Favorites.CELLY, favorite.cellY);
851 values.put(Favorites.SPANX, favorite.spanX);
852 values.put(Favorites.SPANY, favorite.spanY);
853 values.put(Favorites.ICON_TYPE, favorite.iconType);
854 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
855 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
856 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
857 }
858 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
859 values.put(Favorites.ICON, favorite.icon);
860 }
861 if (!TextUtils.isEmpty(favorite.title)) {
862 values.put(Favorites.TITLE, favorite.title);
863 } else {
864 values.put(Favorites.TITLE, "");
865 }
866 if (!TextUtils.isEmpty(favorite.intent)) {
867 values.put(Favorites.INTENT, favorite.intent);
868 }
869 values.put(Favorites.ITEM_TYPE, favorite.itemType);
870 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
871 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
872 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
873 }
874 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
875 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500876
877 // Let LauncherModel know we've been here.
878 values.put(LauncherSettings.Favorites.RESTORED, 1);
879
Chris Wren5dee7af2013-12-20 17:22:11 -0500880 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400881 }
882
883 /** Serialize a Screen for persistence, including a checksum wrapper. */
884 private byte[] packScreen(Cursor c) {
885 Screen screen = new Screen();
886 screen.id = c.getLong(ID_INDEX);
887 screen.rank = c.getInt(SCREEN_RANK_INDEX);
888
889 return writeCheckedBytes(screen);
890 }
891
892 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Chris Wren5dee7af2013-12-20 17:22:11 -0500893 private ContentValues unpackScreen(byte[] buffer, int offset, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400894 throws InvalidProtocolBufferNanoException {
895 Screen screen = new Screen();
896 MessageNano.mergeFrom(screen, readCheckedBytes(buffer, offset, dataSize));
Chris Wren50c8f422014-01-15 16:10:39 -0500897 if (VERBOSE) Log.v(TAG, "unpacked screen " + screen.id + "/" + screen.rank);
Chris Wren5dee7af2013-12-20 17:22:11 -0500898 ContentValues values = new ContentValues();
899 values.put(WorkspaceScreens._ID, screen.id);
900 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
901 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400902 }
903
Chris Wren22e130d2013-09-23 18:25:57 -0400904 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
905 private byte[] packIcon(int dpi, Bitmap icon) {
906 Resource res = new Resource();
907 res.dpi = dpi;
908 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400909 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400910 res.data = os.toByteArray();
911 }
912 return writeCheckedBytes(res);
913 }
914
915 /** Deserialize an icon resource from persistence, after verifying checksum wrapper. */
Chris Wren6d0dde02014-02-10 12:16:54 -0500916 private static Resource unpackIcon(byte[] buffer, int offset, int dataSize)
Chris Wren22e130d2013-09-23 18:25:57 -0400917 throws InvalidProtocolBufferNanoException {
918 Resource res = new Resource();
919 MessageNano.mergeFrom(res, readCheckedBytes(buffer, offset, dataSize));
Chris Wren50c8f422014-01-15 16:10:39 -0500920 if (VERBOSE) Log.v(TAG, "unpacked icon " + res.dpi + "/" + res.data.length);
Chris Wren22e130d2013-09-23 18:25:57 -0400921 return res;
922 }
923
Chris Wrenfd13c712013-09-27 15:45:19 -0400924 /** Serialize a widget for persistence, including a checksum wrapper. */
925 private byte[] packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
926 ComponentName provider) {
927 final AppWidgetProviderInfo info = findAppWidgetProviderInfo(provider);
928 Widget widget = new Widget();
929 widget.provider = provider.flattenToShortString();
930 widget.label = info.label;
931 widget.configure = info.configure != null;
932 if (info.icon != 0) {
933 widget.icon = new Resource();
934 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400935 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400936 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400937 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400938 widget.icon.data = os.toByteArray();
939 widget.icon.dpi = dpi;
940 }
941 }
942 if (info.previewImage != 0) {
943 widget.preview = new Resource();
944 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
945 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400946 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400947 widget.preview.data = os.toByteArray();
948 widget.preview.dpi = dpi;
949 }
950 }
951 return writeCheckedBytes(widget);
952 }
953
954 /** Deserialize a widget from persistence, after verifying checksum wrapper. */
955 private Widget unpackWidget(byte[] buffer, int offset, int dataSize)
956 throws InvalidProtocolBufferNanoException {
957 Widget widget = new Widget();
958 MessageNano.mergeFrom(widget, readCheckedBytes(buffer, offset, dataSize));
Chris Wren50c8f422014-01-15 16:10:39 -0500959 if (VERBOSE) Log.v(TAG, "unpacked widget " + widget.provider);
Chris Wrenfd13c712013-09-27 15:45:19 -0400960 return widget;
961 }
962
Chris Wren1ada10d2013-09-13 18:01:38 -0400963 /**
964 * Read the old journal from the input file.
965 *
966 * In the event of any error, just pretend we didn't have a journal,
967 * in that case, do a full backup.
968 *
969 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -0500970 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -0400971 */
972 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400973 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400974 if (oldState == null) {
975 return journal;
976 }
977 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
978 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500979 int availableBytes = inStream.available();
980 if (DEBUG) Log.d(TAG, "available " + availableBytes);
981 if (availableBytes < MAX_JOURNAL_SIZE) {
982 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -0400983 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -0500984 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -0500985 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500986 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -0400987 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500988 // OMG what are you doing? This is crazy inefficient!
989 // If we read a byte that is not ours, we will cause trouble: b/12491813
990 // However, we don't know how many bytes to expect (oops).
991 // So we have to step through *slowly*, watching for the end.
992 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -0400993 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -0500994 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -0400995 bytesRead += result;
Chris Wren65b6a602014-01-10 14:11:25 -0500996 if (DEBUG && (bytesRead % 100 == 0)) {
997 Log.d(TAG, "read some bytes: " + bytesRead);
998 }
Chris Wren92aa4232013-10-04 11:29:36 -0400999 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001000 Log.w(TAG, "unexpected end of file while reading journal.");
1001 // stop reading and see what there is to parse
1002 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001003 }
1004 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001005 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001006 availableBytes = 0;
1007 }
1008
1009 // check the buffer to see if we have a valid journal
1010 try {
1011 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, 0, bytesRead));
1012 // if we are here, then we have read a valid, checksum-verified journal
1013 valid = true;
1014 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001015 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001016 } catch (InvalidProtocolBufferNanoException e) {
1017 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001018 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001019 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001020 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001021 }
Chris Wren92aa4232013-10-04 11:29:36 -04001022 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001023 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001024 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001025 }
1026 }
Chris Wren92aa4232013-10-04 11:29:36 -04001027 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001028 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001029 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001030 try {
1031 inStream.close();
1032 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001033 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001034 }
1035 }
1036 return journal;
1037 }
1038
Chris Wren22e130d2013-09-23 18:25:57 -04001039 private void writeRowToBackup(Key key, byte[] blob, Journal out,
1040 BackupDataOutput data) throws IOException {
1041 String backupKey = keyToBackupKey(key);
1042 data.writeEntityHeader(backupKey, blob.length);
1043 data.writeEntityData(blob, blob.length);
1044 out.rows++;
1045 out.bytes += blob.length;
Chris Wren50c8f422014-01-15 16:10:39 -05001046 if (VERBOSE) Log.v(TAG, "saving " + geKeyType(key) + " " + backupKey + ": " +
Chris Wren22e130d2013-09-23 18:25:57 -04001047 getKeyName(key) + "/" + blob.length);
Chris Wren92aa4232013-10-04 11:29:36 -04001048 if(DEBUG_PAYLOAD) {
Chris Wren2b6c21d2013-10-02 14:16:04 -04001049 String encoded = Base64.encodeToString(blob, 0, blob.length, Base64.NO_WRAP);
1050 final int chunkSize = 1024;
1051 for (int offset = 0; offset < encoded.length(); offset += chunkSize) {
1052 int end = offset + chunkSize;
1053 end = Math.min(end, encoded.length());
Chris Wren50c8f422014-01-15 16:10:39 -05001054 Log.w(TAG, "wrote " + encoded.substring(offset, end));
Chris Wren2b6c21d2013-10-02 14:16:04 -04001055 }
1056 }
Chris Wren22e130d2013-09-23 18:25:57 -04001057 }
1058
1059 private Set<String> getSavedIdsByType(int type, Journal in) {
1060 Set<String> savedIds = new HashSet<String>();
1061 for(int i = 0; i < in.key.length; i++) {
1062 Key key = in.key[i];
1063 if (key.type == type) {
1064 savedIds.add(keyToBackupKey(key));
1065 }
1066 }
1067 return savedIds;
1068 }
1069
1070 private int removeDeletedKeysFromBackup(Set<String> deletedIds, BackupDataOutput data)
1071 throws IOException {
1072 int rows = 0;
1073 for(String deleted: deletedIds) {
Chris Wren50c8f422014-01-15 16:10:39 -05001074 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
Chris Wren22e130d2013-09-23 18:25:57 -04001075 data.writeEntityHeader(deleted, -1);
1076 rows++;
1077 }
1078 return rows;
1079 }
1080
Chris Wren1ada10d2013-09-13 18:01:38 -04001081 /**
1082 * Write the new journal to the output file.
1083 *
1084 * In the event of any error, just pretend we didn't have a journal,
1085 * in that case, do a full backup.
1086
1087 * @param newState the write-only file descriptor pointing to the new journal
1088 * @param journal a Journal protocol buffer
1089 */
1090 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1091 FileOutputStream outStream = null;
1092 try {
1093 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001094 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001095 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001096 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001097 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001098 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001099 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001100 }
1101 }
1102
1103 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1104 private byte[] writeCheckedBytes(MessageNano proto) {
1105 CheckedMessage wrapper = new CheckedMessage();
1106 wrapper.payload = MessageNano.toByteArray(proto);
1107 CRC32 checksum = new CRC32();
1108 checksum.update(wrapper.payload);
1109 wrapper.checksum = checksum.getValue();
1110 return MessageNano.toByteArray(wrapper);
1111 }
1112
1113 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Chris Wren6d0dde02014-02-10 12:16:54 -05001114 private static byte[] readCheckedBytes(byte[] buffer, int offset, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001115 throws InvalidProtocolBufferNanoException {
1116 CheckedMessage wrapper = new CheckedMessage();
1117 MessageNano.mergeFrom(wrapper, buffer, offset, dataSize);
1118 CRC32 checksum = new CRC32();
1119 checksum.update(wrapper.payload);
1120 if (wrapper.checksum != checksum.getValue()) {
1121 throw new InvalidProtocolBufferNanoException("checksum does not match");
1122 }
1123 return wrapper.payload;
1124 }
1125
Chris Wrenfd13c712013-09-27 15:45:19 -04001126 private AppWidgetProviderInfo findAppWidgetProviderInfo(ComponentName component) {
1127 if (mWidgetMap == null) {
1128 List<AppWidgetProviderInfo> widgets =
Chris Wren92aa4232013-10-04 11:29:36 -04001129 AppWidgetManager.getInstance(mContext).getInstalledProviders();
Chris Wrenfd13c712013-09-27 15:45:19 -04001130 mWidgetMap = new HashMap<ComponentName, AppWidgetProviderInfo>(widgets.size());
1131 for (AppWidgetProviderInfo info : widgets) {
1132 mWidgetMap.put(info.provider, info);
1133 }
1134 }
1135 return mWidgetMap.get(component);
1136 }
1137
Chris Wren6d0dde02014-02-10 12:16:54 -05001138
1139 private boolean initializeIconCache() {
1140 if (mIconCache != null) {
1141 return true;
1142 }
1143
1144 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
1145 if (appState == null) {
1146 Throwable stackTrace = new Throwable();
1147 stackTrace.fillInStackTrace();
1148 Log.w(TAG, "Failed to get app state during backup/restore", stackTrace);
1149 return false;
1150 }
1151 mIconCache = appState.getIconCache();
1152 return mIconCache != null;
1153 }
1154
Chris Wren71144262014-02-27 15:49:39 -05001155
1156 // check if the launcher is in a state to support backup
1157 private boolean launcherIsReady() {
1158 ContentResolver cr = mContext.getContentResolver();
1159 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1160 if (cursor == null) {
1161 // launcher data has been wiped, do nothing
1162 return false;
1163 }
1164 cursor.close();
1165
1166 if (!initializeIconCache()) {
1167 // launcher services are unavailable, try again later
1168 dataChanged();
1169 return false;
1170 }
1171
1172 return true;
1173 }
1174
Chris Wren1ada10d2013-09-13 18:01:38 -04001175 private class KeyParsingException extends Throwable {
1176 private KeyParsingException(Throwable cause) {
1177 super(cause);
1178 }
1179
1180 public KeyParsingException(String reason) {
1181 super(reason);
1182 }
1183 }
1184}