blob: 97ff327909e9a4041dcb6d2df58df729fb8e6044 [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
Chris Wren92aa4232013-10-04 11:29:36 -040018import android.app.backup.BackupDataInputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040019import android.app.backup.BackupDataOutput;
Chris Wren4d89e2a2013-10-09 17:03:50 -040020import android.app.backup.BackupHelper;
Chris Wren1ada10d2013-09-13 18:01:38 -040021import android.app.backup.BackupManager;
Chris Wren22e130d2013-09-23 18:25:57 -040022import android.content.ComponentName;
Chris Wren1ada10d2013-09-13 18:01:38 -040023import android.content.ContentResolver;
Chris Wren5dee7af2013-12-20 17:22:11 -050024import android.content.ContentValues;
Chris Wren1ada10d2013-09-13 18:01:38 -040025import android.content.Context;
Chris Wren22e130d2013-09-23 18:25:57 -040026import android.content.Intent;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080027import android.content.pm.ActivityInfo;
28import android.content.pm.PackageManager;
Sunny Goyalef728d42014-10-22 11:28:28 -070029import android.content.pm.PackageManager.NameNotFoundException;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080030import android.content.pm.ResolveInfo;
31import android.content.res.XmlResourceParser;
Chris Wren1ada10d2013-09-13 18:01:38 -040032import android.database.Cursor;
Chris Wren22e130d2013-09-23 18:25:57 -040033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Chris Wrenfd13c712013-09-27 15:45:19 -040035import android.graphics.drawable.Drawable;
Chris Wren1ada10d2013-09-13 18:01:38 -040036import android.os.ParcelFileDescriptor;
Chris Wren1ada10d2013-09-13 18:01:38 -040037import android.text.TextUtils;
38import android.util.Base64;
39import android.util.Log;
40
Sunny Goyalef728d42014-10-22 11:28:28 -070041import com.android.launcher3.LauncherSettings.Favorites;
42import com.android.launcher3.LauncherSettings.WorkspaceScreens;
43import com.android.launcher3.backup.BackupProtos;
44import com.android.launcher3.backup.BackupProtos.CheckedMessage;
Sunny Goyal33d44382014-10-16 09:24:19 -070045import com.android.launcher3.backup.BackupProtos.DeviceProfieData;
Sunny Goyalef728d42014-10-22 11:28:28 -070046import com.android.launcher3.backup.BackupProtos.Favorite;
47import com.android.launcher3.backup.BackupProtos.Journal;
48import com.android.launcher3.backup.BackupProtos.Key;
49import com.android.launcher3.backup.BackupProtos.Resource;
50import com.android.launcher3.backup.BackupProtos.Screen;
51import com.android.launcher3.backup.BackupProtos.Widget;
52import com.android.launcher3.compat.UserHandleCompat;
53import com.android.launcher3.compat.UserManagerCompat;
54import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
55import com.google.protobuf.nano.MessageNano;
56
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080057import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59
Chris Wren22e130d2013-09-23 18:25:57 -040060import java.io.ByteArrayOutputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040061import java.io.FileInputStream;
62import java.io.FileOutputStream;
63import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040064import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040065import java.util.ArrayList;
Sunny Goyalc0ee6752015-01-16 14:10:32 -080066import java.util.Arrays;
Chris Wren1ada10d2013-09-13 18:01:38 -040067import java.util.HashSet;
Chris Wren1ada10d2013-09-13 18:01:38 -040068import java.util.zip.CRC32;
69
70/**
71 * Persist the launcher home state across calamities.
72 */
Chris Wren92aa4232013-10-04 11:29:36 -040073public class LauncherBackupHelper implements BackupHelper {
Chris Wren92aa4232013-10-04 11:29:36 -040074 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050075 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
76 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren1ada10d2013-09-13 18:01:38 -040077
Sunny Goyal33d44382014-10-16 09:24:19 -070078 private static final int BACKUP_VERSION = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -040079 private static final int MAX_JOURNAL_SIZE = 1000000;
80
Sunny Goyal33d44382014-10-16 09:24:19 -070081 // Journal key is such that it is always smaller than any dynamically generated
82 // key (any Base64 encoded string).
83 private static final String JOURNAL_KEY = "#";
84
Chris Wrenfd13c712013-09-27 15:45:19 -040085 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040086 private static final int MAX_ICONS_PER_PASS = 10;
87
Chris Wrenfd13c712013-09-27 15:45:19 -040088 /** widgets contain previews, which are very large, dribble them out */
89 private static final int MAX_WIDGETS_PER_PASS = 5;
90
Sunny Goyal33d44382014-10-16 09:24:19 -070091 private static final int IMAGE_COMPRESSION_QUALITY = 75;
Chris Wren45297f82013-10-17 15:16:48 -040092
Chris Wrenb86f0762013-10-04 10:10:21 -040093 private static final Bitmap.CompressFormat IMAGE_FORMAT =
94 android.graphics.Bitmap.CompressFormat.PNG;
95
Chris Wren1ada10d2013-09-13 18:01:38 -040096 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070097 Favorites._ID, // 0
98 Favorites.MODIFIED, // 1
99 Favorites.INTENT, // 2
100 Favorites.APPWIDGET_PROVIDER, // 3
101 Favorites.APPWIDGET_ID, // 4
102 Favorites.CELLX, // 5
103 Favorites.CELLY, // 6
104 Favorites.CONTAINER, // 7
105 Favorites.ICON, // 8
106 Favorites.ICON_PACKAGE, // 9
107 Favorites.ICON_RESOURCE, // 10
108 Favorites.ICON_TYPE, // 11
109 Favorites.ITEM_TYPE, // 12
110 Favorites.SCREEN, // 13
111 Favorites.SPANX, // 14
112 Favorites.SPANY, // 15
113 Favorites.TITLE, // 16
114 Favorites.PROFILE_ID, // 17
Chris Wren1ada10d2013-09-13 18:01:38 -0400115 };
116
117 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400118 private static final int ID_MODIFIED = 1;
119 private static final int INTENT_INDEX = 2;
120 private static final int APPWIDGET_PROVIDER_INDEX = 3;
121 private static final int APPWIDGET_ID_INDEX = 4;
122 private static final int CELLX_INDEX = 5;
123 private static final int CELLY_INDEX = 6;
124 private static final int CONTAINER_INDEX = 7;
125 private static final int ICON_INDEX = 8;
126 private static final int ICON_PACKAGE_INDEX = 9;
127 private static final int ICON_RESOURCE_INDEX = 10;
128 private static final int ICON_TYPE_INDEX = 11;
129 private static final int ITEM_TYPE_INDEX = 12;
130 private static final int SCREEN_INDEX = 13;
131 private static final int SPANX_INDEX = 14;
132 private static final int SPANY_INDEX = 15;
133 private static final int TITLE_INDEX = 16;
Chris Wren1ada10d2013-09-13 18:01:38 -0400134
135 private static final String[] SCREEN_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -0700136 WorkspaceScreens._ID, // 0
137 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 Wren92aa4232013-10-04 11:29:36 -0400143 private final Context mContext;
Sunny Goyalef728d42014-10-22 11:28:28 -0700144 private final HashSet<String> mExistingKeys;
Sunny Goyal42de82f2014-09-26 22:09:29 -0700145 private final ArrayList<Key> mKeys;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800146 private final ItemTypeMatcher[] mItemTypeMatchers;
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800147 private final long mUserSerial;
Chris Wren1ada10d2013-09-13 18:01:38 -0400148
Sunny Goyalef728d42014-10-22 11:28:28 -0700149 private IconCache mIconCache;
150 private BackupManager mBackupManager;
Sunny Goyalef728d42014-10-22 11:28:28 -0700151 private byte[] mBuffer = new byte[512];
152 private long mLastBackupRestoreTime;
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800153 private boolean mBackupDataWasUpdated;
Sunny Goyalef728d42014-10-22 11:28:28 -0700154
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700155 private DeviceProfieData mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700156 boolean restoreSuccessful;
Sunny Goyal08f72612015-01-05 13:41:43 -0800157 int restoredBackupVersion = 1;
Sunny Goyal33d44382014-10-16 09:24:19 -0700158
159 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400160 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700161 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700162 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700163 restoreSuccessful = true;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800164 mItemTypeMatchers = new ItemTypeMatcher[CommonAppTypeParser.SUPPORTED_TYPE_COUNT];
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800165
166 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
167 mUserSerial = userManager.getSerialNumberForUser(UserHandleCompat.myUserHandle());
Chris Wren92aa4232013-10-04 11:29:36 -0400168 }
169
170 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700171 if (mBackupManager == null) {
172 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400173 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700174 mBackupManager.dataChanged();
175 }
176
177 private void applyJournal(Journal journal) {
178 mLastBackupRestoreTime = journal.t;
179 mExistingKeys.clear();
180 if (journal.key != null) {
181 for (Key key : journal.key) {
182 mExistingKeys.add(keyToBackupKey(key));
183 }
184 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400185 }
186
187 /**
188 * Back up launcher data so we can restore the user's state on a new device.
189 *
190 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
191 *
192 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
193 *
194 * @param oldState notes from the last backup
195 * @param data incremental key/value pairs to persist off-device
196 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400197 */
198 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400199 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
200 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500201 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400202
203 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700204 if (!launcherIsReady()) {
205 // Perform backup later.
206 writeJournal(newState, in);
207 return;
208 }
209 Log.v(TAG, "lastBackupTime = " + in.t);
210 mKeys.clear();
211 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400212
Sunny Goyalef728d42014-10-22 11:28:28 -0700213 // Record the time before performing backup so that entries edited while the backup
214 // was going on, do not get missed in next backup.
215 long newBackupTime = System.currentTimeMillis();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800216 mBackupDataWasUpdated = false;
Sunny Goyalef728d42014-10-22 11:28:28 -0700217 try {
218 backupFavorites(data);
219 backupScreens(data);
220 backupIcons(data);
221 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400222
Sunny Goyalef728d42014-10-22 11:28:28 -0700223 // Delete any key which still exist in the old backup, but is not valid anymore.
224 HashSet<String> validKeys = new HashSet<String>();
225 for (Key key : mKeys) {
226 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500227 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700228 mExistingKeys.removeAll(validKeys);
229
230 // Delete anything left in the existing keys.
231 for (String deleted: mExistingKeys) {
232 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
233 data.writeEntityHeader(deleted, -1);
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800234 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -0700235 }
236
237 mExistingKeys.clear();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800238 if (!mBackupDataWasUpdated) {
239 // Check if any metadata has changed
240 mBackupDataWasUpdated = (in.profile == null)
241 || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
242 DeviceProfieData.toByteArray(getDeviceProfieData()))
243 || (in.backupVersion != BACKUP_VERSION)
244 || (in.appVersion != getAppVersion());
245 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700246
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800247 if (mBackupDataWasUpdated) {
248 mLastBackupRestoreTime = newBackupTime;
249
250 // We store the journal at two places.
251 // 1) Storing it in newState allows us to do partial backups by comparing old state
252 // 2) Storing it in backup data allows us to validate keys during restore
253 Journal state = getCurrentStateJournal();
254 writeRowToBackup(JOURNAL_KEY, state, data);
255 } else {
256 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
257 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700258 } catch (IOException e) {
259 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400260 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400261
Sunny Goyalef728d42014-10-22 11:28:28 -0700262 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400263 }
264
265 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700266 * @return true if the backup corresponding to oldstate can be successfully applied
267 * to this device.
268 */
269 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700270 DeviceProfieData currentProfile = getDeviceProfieData();
271
272 DeviceProfieData oldProfile = oldState.profile;
273
274 if (oldProfile == null || oldProfile.desktopCols == 0) {
275 // Profile info is not valid, ignore the check.
276 return true;
277 }
278
279 boolean isHotsetCompatible = false;
280 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
281 isHotsetCompatible = true;
282 }
283 if ((currentProfile.hotseatCount >= oldProfile.hotseatCount) &&
284 (currentProfile.allappsRank == oldProfile.allappsRank)) {
285 isHotsetCompatible = true;
286 }
287
288 return isHotsetCompatible && (currentProfile.desktopCols >= oldProfile.desktopCols)
289 && (currentProfile.desktopRows >= oldProfile.desktopRows);
Sunny Goyal33d44382014-10-16 09:24:19 -0700290 }
291
292 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400293 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700294 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
295 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400296 *
Chris Wren92aa4232013-10-04 11:29:36 -0400297 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400298 */
299 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400300 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700301 if (!restoreSuccessful) {
302 return;
303 }
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800304 if (!initializeIconCache()) {
305 // During restore we do not need an initialized instance of IconCache. We can create
306 // a temporary icon cache here, as the process will be rebooted after restore
307 // is complete.
308 mIconCache = new IconCache(mContext);
309 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700310
Sunny Goyalef728d42014-10-22 11:28:28 -0700311 int dataSize = data.size();
312 if (mBuffer.length < dataSize) {
313 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400314 }
315 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700316 int bytesRead = data.read(mBuffer, 0, dataSize);
317 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
318 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700319
320 if (JOURNAL_KEY.equals(backupKey)) {
321 if (VERBOSE) Log.v(TAG, "Journal entry restored");
322 if (!mKeys.isEmpty()) {
323 // We received the journal key after a restore key.
324 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
325 restoreSuccessful = false;
326 return;
327 }
328
329 Journal journal = new Journal();
330 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
331 applyJournal(journal);
332 restoreSuccessful = isBackupCompatible(journal);
Sunny Goyal08f72612015-01-05 13:41:43 -0800333 restoredBackupVersion = journal.backupVersion;
Sunny Goyal33d44382014-10-16 09:24:19 -0700334 return;
335 }
336
337 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
338 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
339 return;
340 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700341 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500342 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400343 switch (key.type) {
344 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700345 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400346 break;
347
348 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700349 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400350 break;
351
352 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700353 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400354 break;
355
356 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700357 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400358 break;
359
360 default:
361 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700362 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400363 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400364 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700365 } catch (IOException e) {
366 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400367 }
Chris Wren92aa4232013-10-04 11:29:36 -0400368 }
369
370 /**
371 * Record the restore state for the next backup.
372 *
373 * @param newState notes about the backup state after restore.
374 */
375 @Override
376 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700377 writeJournal(newState, getCurrentStateJournal());
378 }
379
380 private Journal getCurrentStateJournal() {
381 Journal journal = new Journal();
382 journal.t = mLastBackupRestoreTime;
383 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
384 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700385 journal.backupVersion = BACKUP_VERSION;
386 journal.profile = getDeviceProfieData();
Sunny Goyalef728d42014-10-22 11:28:28 -0700387 return journal;
388 }
389
390 private int getAppVersion() {
391 try {
392 return mContext.getPackageManager()
393 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
394 } catch (NameNotFoundException e) {
395 return 0;
396 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400397 }
398
399 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700400 * @return the current device profile information.
401 */
402 private DeviceProfieData getDeviceProfieData() {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700403 if (mCurrentProfile != null) {
404 return mCurrentProfile;
405 }
Chris Wrenb02e6112014-11-24 16:57:54 -0500406 final Context applicationContext = mContext.getApplicationContext();
407 DeviceProfile profile = LauncherAppState.createDynamicGrid(applicationContext, null)
408 .getDeviceProfile();
Sunny Goyal33d44382014-10-16 09:24:19 -0700409
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700410 mCurrentProfile = new DeviceProfieData();
411 mCurrentProfile.desktopRows = profile.numRows;
412 mCurrentProfile.desktopCols = profile.numColumns;
413 mCurrentProfile.hotseatCount = profile.numHotseatIcons;
414 mCurrentProfile.allappsRank = profile.hotseatAllAppsRank;
415 return mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700416 }
417
418 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400419 * Write all modified favorites to the data stream.
420 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400421 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400422 * @throws IOException
423 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700424 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400425 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400426 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700427 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400428 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700429 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400430 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400431 cursor.moveToPosition(-1);
432 while(cursor.moveToNext()) {
433 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700434 final long updateTime = cursor.getLong(ID_MODIFIED);
435 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700436 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700437 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700438 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
439 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500440 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700441 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400442 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400443 }
444 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400445 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400446 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400447 }
448
449 /**
450 * Read a favorite from the stream.
451 *
452 * <P>Keys arrive in any order, so screens and containers may not exist yet.
453 *
454 * @param key identifier for the row
455 * @param buffer the serialized proto from the stream, may be larger than dataSize
456 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400457 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700458 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500459 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400460 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
461 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
462
Sunny Goyalef728d42014-10-22 11:28:28 -0700463 ContentResolver cr = mContext.getContentResolver();
464 ContentValues values = unpackFavorite(buffer, dataSize);
465 cr.insert(Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400466 }
467
468 /**
469 * Write all modified screens to the data stream.
470 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400471 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400472 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400473 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700474 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400475 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400476 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400477 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
478 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400480 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700481 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400482 while(cursor.moveToNext()) {
483 final long id = cursor.getLong(ID_INDEX);
484 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400485 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700486 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500487 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700488 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
489 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500490 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700491 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400492 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400493 }
494 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400495 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400496 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400497 }
498
499 /**
500 * Read a screen from the stream.
501 *
502 * <P>Keys arrive in any order, so children of this screen may already exist.
503 *
504 * @param key identifier for the row
505 * @param buffer the serialized proto from the stream, may be larger than dataSize
506 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400507 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700508 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500509 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400510 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
511 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500512
Sunny Goyalef728d42014-10-22 11:28:28 -0700513 ContentResolver cr = mContext.getContentResolver();
514 ContentValues values = unpackScreen(buffer, dataSize);
515 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400516 }
517
Chris Wren22e130d2013-09-23 18:25:57 -0400518 /**
519 * Write all the static icon resources we need to render placeholders
520 * for a package that is not installed.
521 *
Chris Wren22e130d2013-09-23 18:25:57 -0400522 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400523 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700524 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400525 // persist icons that haven't been persisted yet
Chris Wren6d0dde02014-02-10 12:16:54 -0500526 if (!initializeIconCache()) {
Chris Wren92aa4232013-10-04 11:29:36 -0400527 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400528 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
529 return;
530 }
Chris Wren92aa4232013-10-04 11:29:36 -0400531 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400532 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700533 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700534 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400535
Kenny Guyed131872014-04-30 03:02:21 +0100536 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100537 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100538 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700539 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400540 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
541 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400542 try {
543 cursor.moveToPosition(-1);
544 while(cursor.moveToNext()) {
545 final long id = cursor.getLong(ID_INDEX);
546 final String intentDescription = cursor.getString(INTENT_INDEX);
547 try {
548 Intent intent = Intent.parseUri(intentDescription, 0);
549 ComponentName cn = intent.getComponent();
550 Key key = null;
551 String backupKey = null;
552 if (cn != null) {
553 key = getKey(Key.ICON, cn.flattenToShortString());
554 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400555 } else {
556 Log.w(TAG, "empty intent on application favorite: " + id);
557 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700558 if (mExistingKeys.contains(backupKey)) {
559 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400560
561 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700562 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400563 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700564 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
565 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
566 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100567 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100568 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700569 writeRowToBackup(key, packIcon(dpi, icon), data);
570 mKeys.add(key);
571 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400572 }
573 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700574 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400575 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400576 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400577 }
578 }
579 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500580 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400581 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500582 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400583 }
584
585 }
586 } finally {
587 cursor.close();
588 }
Chris Wren22e130d2013-09-23 18:25:57 -0400589 }
590
591 /**
592 * Read an icon from the stream.
593 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400594 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400595 *
596 * @param key identifier for the row
597 * @param buffer the serialized proto from the stream, may be larger than dataSize
598 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400599 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700600 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500601 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400602 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
603 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500604
Sunny Goyalef728d42014-10-22 11:28:28 -0700605 Resource res = unpackProto(new Resource(), buffer, dataSize);
606 if (DEBUG) {
607 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400608 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700609 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
610 if (icon == null) {
611 Log.w(TAG, "failed to unpack icon for " + key.name);
612 }
613 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800614 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
615 "" /* label */, mUserSerial);
Chris Wren22e130d2013-09-23 18:25:57 -0400616 }
617
Chris Wrenfd13c712013-09-27 15:45:19 -0400618 /**
619 * Write all the static widget resources we need to render placeholders
620 * for a package that is not installed.
621 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400622 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400623 * @throws IOException
624 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700625 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400626 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400627 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
Chris Wren6d0dde02014-02-10 12:16:54 -0500628 if (appState == null || !initializeIconCache()) {
629 Log.w(TAG, "Failed to get icon cache during restore");
Chris Wrend8fe6de2013-10-04 10:42:14 -0400630 return;
631 }
Chris Wren92aa4232013-10-04 11:29:36 -0400632 final ContentResolver cr = mContext.getContentResolver();
633 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
634 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wren92aa4232013-10-04 11:29:36 -0400635 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400636 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
637 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
Sunny Goyalef728d42014-10-22 11:28:28 -0700638 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400639
Sunny Goyalffe83f12014-08-14 17:39:34 -0700640 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
641 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400642 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
643 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400644 try {
645 cursor.moveToPosition(-1);
646 while(cursor.moveToNext()) {
647 final long id = cursor.getLong(ID_INDEX);
648 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
649 final int spanX = cursor.getInt(SPANX_INDEX);
650 final int spanY = cursor.getInt(SPANY_INDEX);
651 final ComponentName provider = ComponentName.unflattenFromString(providerName);
652 Key key = null;
653 String backupKey = null;
654 if (provider != null) {
655 key = getKey(Key.WIDGET, providerName);
656 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400657 } else {
658 Log.w(TAG, "empty intent on appwidget: " + id);
659 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700660 if (mExistingKeys.contains(backupKey)) {
661 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400662
663 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700664 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400665 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700666 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
667 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
668 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400669 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
670 spanY * profile.cellHeightPx, widgetSpacingLayout);
Sunny Goyalef728d42014-10-22 11:28:28 -0700671 writeRowToBackup(key, packWidget(dpi, previewLoader, mIconCache, provider), data);
672 mKeys.add(key);
673 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400674 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700675 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400676 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400677 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400678 }
679 }
680 }
681 } finally {
682 cursor.close();
683 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400684 }
685
686 /**
687 * Read a widget from the stream.
688 *
689 * <P>Keys arrive in any order, so widgets that use this data may already exist.
690 *
691 * @param key identifier for the row
692 * @param buffer the serialized proto from the stream, may be larger than dataSize
693 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400694 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700695 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500696 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400697 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
698 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700699 Widget widget = unpackProto(new Widget(), buffer, dataSize);
700 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
701 if (widget.icon.data != null) {
702 Bitmap icon = BitmapFactory
703 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
704 if (icon == null) {
705 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500706 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800707 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
708 icon, widget.icon.dpi, widget.label, mUserSerial);
Chris Wren5dee7af2013-12-20 17:22:11 -0500709 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400710 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700711
712 // future site of widget table mutation
Chris Wrenfd13c712013-09-27 15:45:19 -0400713 }
714
Chris Wren22e130d2013-09-23 18:25:57 -0400715 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400716 *
717 * <P> Keys contain their own checksum instead of using
718 * the heavy-weight CheckedMessage wrapper.
719 */
720 private Key getKey(int type, long id) {
721 Key key = new Key();
722 key.type = type;
723 key.id = id;
724 key.checksum = checkKey(key);
725 return key;
726 }
727
Chris Wren22e130d2013-09-23 18:25:57 -0400728 /** create a new key for a named object.
729 *
730 * <P> Keys contain their own checksum instead of using
731 * the heavy-weight CheckedMessage wrapper.
732 */
733 private Key getKey(int type, String name) {
734 Key key = new Key();
735 key.type = type;
736 key.name = name;
737 key.checksum = checkKey(key);
738 return key;
739 }
740
Chris Wren1ada10d2013-09-13 18:01:38 -0400741 /** keys need to be strings, serialize and encode. */
742 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400743 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400744 }
745
746 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700747 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400748 try {
749 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
750 if (key.checksum != checkKey(key)) {
751 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700752 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400753 }
754 return key;
755 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700756 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400757 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700758 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400759 }
760 }
761
762 /** Compute the checksum over the important bits of a key. */
763 private long checkKey(Key key) {
764 CRC32 checksum = new CRC32();
765 checksum.update(key.type);
766 checksum.update((int) (key.id & 0xffff));
767 checksum.update((int) ((key.id >> 32) & 0xffff));
768 if (!TextUtils.isEmpty(key.name)) {
769 checksum.update(key.name.getBytes());
770 }
771 return checksum.getValue();
772 }
773
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800774 /**
775 * @return true if its an hotseat item, that can be replaced during restore.
776 * TODO: Extend check for folders in hotseat.
777 */
778 private boolean isReplaceableHotseatItem(Favorite favorite) {
779 return favorite.container == Favorites.CONTAINER_HOTSEAT
780 && favorite.intent != null
781 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
782 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
783 }
784
Chris Wren1ada10d2013-09-13 18:01:38 -0400785 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700786 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400787 Favorite favorite = new Favorite();
788 favorite.id = c.getLong(ID_INDEX);
789 favorite.screen = c.getInt(SCREEN_INDEX);
790 favorite.container = c.getInt(CONTAINER_INDEX);
791 favorite.cellX = c.getInt(CELLX_INDEX);
792 favorite.cellY = c.getInt(CELLY_INDEX);
793 favorite.spanX = c.getInt(SPANX_INDEX);
794 favorite.spanY = c.getInt(SPANY_INDEX);
795 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
796 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
797 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
798 if (!TextUtils.isEmpty(iconPackage)) {
799 favorite.iconPackage = iconPackage;
800 }
801 String iconResource = c.getString(ICON_RESOURCE_INDEX);
802 if (!TextUtils.isEmpty(iconResource)) {
803 favorite.iconResource = iconResource;
804 }
805 }
806 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
807 byte[] blob = c.getBlob(ICON_INDEX);
808 if (blob != null && blob.length > 0) {
809 favorite.icon = blob;
810 }
811 }
812 String title = c.getString(TITLE_INDEX);
813 if (!TextUtils.isEmpty(title)) {
814 favorite.title = title;
815 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100816 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800817 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100818 if (!TextUtils.isEmpty(intentDescription)) {
819 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800820 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100821 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
822 favorite.intent = intent.toUri(0);
823 } catch (URISyntaxException e) {
824 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700825 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400826 }
827 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
828 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
829 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
830 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
831 if (!TextUtils.isEmpty(appWidgetProvider)) {
832 favorite.appWidgetProvider = appWidgetProvider;
833 }
834 }
835
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800836 if (isReplaceableHotseatItem(favorite)) {
837 if (intent != null && intent.getComponent() != null) {
838 PackageManager pm = mContext.getPackageManager();
839 ActivityInfo activity = null;;
840 try {
841 activity = pm.getActivityInfo(intent.getComponent(), 0);
842 } catch (NameNotFoundException e) {
843 Log.e(TAG, "Target not found", e);
844 }
845 if (activity == null) {
846 return favorite;
847 }
848 for (int i = 0; i < mItemTypeMatchers.length; i++) {
849 if (mItemTypeMatchers[i] == null) {
850 mItemTypeMatchers[i] = new ItemTypeMatcher(
851 CommonAppTypeParser.getResourceForItemType(i));
852 }
853 if (mItemTypeMatchers[i].matches(activity, pm)) {
854 favorite.targetType = i;
855 break;
856 }
857 }
858 }
859 }
860
Sunny Goyalef728d42014-10-22 11:28:28 -0700861 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400862 }
863
864 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700865 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700866 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700867 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800868
Chris Wren5dee7af2013-12-20 17:22:11 -0500869 ContentValues values = new ContentValues();
870 values.put(Favorites._ID, favorite.id);
871 values.put(Favorites.SCREEN, favorite.screen);
872 values.put(Favorites.CONTAINER, favorite.container);
873 values.put(Favorites.CELLX, favorite.cellX);
874 values.put(Favorites.CELLY, favorite.cellY);
875 values.put(Favorites.SPANX, favorite.spanX);
876 values.put(Favorites.SPANY, favorite.spanY);
877 values.put(Favorites.ICON_TYPE, favorite.iconType);
878 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
879 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
880 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
881 }
882 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
883 values.put(Favorites.ICON, favorite.icon);
884 }
885 if (!TextUtils.isEmpty(favorite.title)) {
886 values.put(Favorites.TITLE, favorite.title);
887 } else {
888 values.put(Favorites.TITLE, "");
889 }
890 if (!TextUtils.isEmpty(favorite.intent)) {
891 values.put(Favorites.INTENT, favorite.intent);
892 }
893 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500894
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100895 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
896 long userSerialNumber =
897 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
898 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
899
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700900 DeviceProfieData currentProfile = getDeviceProfieData();
901
Sunny Goyalff572272014-07-23 13:58:07 -0700902 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
903 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
904 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
905 }
906 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
907 values.put(LauncherSettings.Favorites.RESTORED,
908 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
909 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
910 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700911
912 // Verify placement
913 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
914 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
915 restoreSuccessful = false;
916 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
917 }
Sunny Goyalff572272014-07-23 13:58:07 -0700918 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800919 // Check if it is an hotseat item, that can be replaced.
920 if (isReplaceableHotseatItem(favorite)
921 && favorite.targetType != Favorite.TARGET_NONE
922 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
923 Log.e(TAG, "Added item type flag");
924 values.put(LauncherSettings.Favorites.RESTORED,
925 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
926 } else {
927 // Let LauncherModel know we've been here.
928 values.put(LauncherSettings.Favorites.RESTORED, 1);
929 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700930
931 // Verify placement
932 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
933 if ((favorite.screen >= currentProfile.hotseatCount)
934 || (favorite.screen == currentProfile.allappsRank)) {
935 restoreSuccessful = false;
936 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
937 }
938 } else {
939 if ((favorite.cellX >= currentProfile.desktopCols)
940 || (favorite.cellY >= currentProfile.desktopRows)) {
941 restoreSuccessful = false;
942 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
943 }
944 }
Sunny Goyalff572272014-07-23 13:58:07 -0700945 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500946
Chris Wren5dee7af2013-12-20 17:22:11 -0500947 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400948 }
949
950 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700951 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400952 Screen screen = new Screen();
953 screen.id = c.getLong(ID_INDEX);
954 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700955 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400956 }
957
958 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700959 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400960 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700961 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500962 ContentValues values = new ContentValues();
963 values.put(WorkspaceScreens._ID, screen.id);
964 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
965 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400966 }
967
Chris Wren22e130d2013-09-23 18:25:57 -0400968 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700969 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400970 Resource res = new Resource();
971 res.dpi = dpi;
972 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400973 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400974 res.data = os.toByteArray();
975 }
Chris Wren22e130d2013-09-23 18:25:57 -0400976 return res;
977 }
978
Chris Wrenfd13c712013-09-27 15:45:19 -0400979 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700980 private Widget packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
Chris Wrenfd13c712013-09-27 15:45:19 -0400981 ComponentName provider) {
Adam Cohen59400422014-03-05 18:07:04 -0800982 final LauncherAppWidgetProviderInfo info =
983 LauncherModel.getProviderInfo(mContext, provider);
Chris Wrenfd13c712013-09-27 15:45:19 -0400984 Widget widget = new Widget();
985 widget.provider = provider.flattenToShortString();
986 widget.label = info.label;
987 widget.configure = info.configure != null;
988 if (info.icon != 0) {
989 widget.icon = new Resource();
990 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400991 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400992 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400993 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400994 widget.icon.data = os.toByteArray();
995 widget.icon.dpi = dpi;
996 }
997 }
998 if (info.previewImage != 0) {
999 widget.preview = new Resource();
1000 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
1001 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -04001002 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -04001003 widget.preview.data = os.toByteArray();
1004 widget.preview.dpi = dpi;
1005 }
1006 }
Sunny Goyalef728d42014-10-22 11:28:28 -07001007 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001008 }
1009
Sunny Goyalef728d42014-10-22 11:28:28 -07001010 /**
1011 * Deserialize a proto after verifying checksum wrapper.
1012 */
1013 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001014 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001015 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1016 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1017 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001018 }
1019
Chris Wren1ada10d2013-09-13 18:01:38 -04001020 /**
1021 * Read the old journal from the input file.
1022 *
1023 * In the event of any error, just pretend we didn't have a journal,
1024 * in that case, do a full backup.
1025 *
1026 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001027 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001028 */
1029 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001030 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001031 if (oldState == null) {
1032 return journal;
1033 }
1034 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1035 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001036 int availableBytes = inStream.available();
1037 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1038 if (availableBytes < MAX_JOURNAL_SIZE) {
1039 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001040 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001041 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001042 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001043 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001044 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001045 // OMG what are you doing? This is crazy inefficient!
1046 // If we read a byte that is not ours, we will cause trouble: b/12491813
1047 // However, we don't know how many bytes to expect (oops).
1048 // So we have to step through *slowly*, watching for the end.
1049 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001050 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001051 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001052 bytesRead += result;
1053 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001054 Log.w(TAG, "unexpected end of file while reading journal.");
1055 // stop reading and see what there is to parse
1056 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001057 }
1058 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001059 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001060 availableBytes = 0;
1061 }
1062
1063 // check the buffer to see if we have a valid journal
1064 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001065 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001066 // if we are here, then we have read a valid, checksum-verified journal
1067 valid = true;
1068 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001069 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001070 } catch (InvalidProtocolBufferNanoException e) {
1071 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001072 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001073 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001074 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001075 }
Chris Wren92aa4232013-10-04 11:29:36 -04001076 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001077 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001078 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001079 }
1080 }
Chris Wren92aa4232013-10-04 11:29:36 -04001081 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001082 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001083 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001084 try {
1085 inStream.close();
1086 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001087 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001088 }
1089 }
1090 return journal;
1091 }
1092
Sunny Goyalef728d42014-10-22 11:28:28 -07001093 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1094 throws IOException {
1095 writeRowToBackup(keyToBackupKey(key), proto, data);
1096 }
1097
1098 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001099 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001100 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001101 data.writeEntityHeader(backupKey, blob.length);
1102 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001103 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001104 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001105 }
1106
Chris Wren1ada10d2013-09-13 18:01:38 -04001107 /**
1108 * Write the new journal to the output file.
1109 *
1110 * In the event of any error, just pretend we didn't have a journal,
1111 * in that case, do a full backup.
1112
1113 * @param newState the write-only file descriptor pointing to the new journal
1114 * @param journal a Journal protocol buffer
1115 */
1116 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1117 FileOutputStream outStream = null;
1118 try {
1119 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001120 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001121 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001122 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001123 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001124 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001125 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001126 }
1127 }
1128
1129 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1130 private byte[] writeCheckedBytes(MessageNano proto) {
1131 CheckedMessage wrapper = new CheckedMessage();
1132 wrapper.payload = MessageNano.toByteArray(proto);
1133 CRC32 checksum = new CRC32();
1134 checksum.update(wrapper.payload);
1135 wrapper.checksum = checksum.getValue();
1136 return MessageNano.toByteArray(wrapper);
1137 }
1138
1139 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001140 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001141 throws InvalidProtocolBufferNanoException {
1142 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001143 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001144 CRC32 checksum = new CRC32();
1145 checksum.update(wrapper.payload);
1146 if (wrapper.checksum != checksum.getValue()) {
1147 throw new InvalidProtocolBufferNanoException("checksum does not match");
1148 }
1149 return wrapper.payload;
1150 }
1151
Chris Wren6d0dde02014-02-10 12:16:54 -05001152 private boolean initializeIconCache() {
1153 if (mIconCache != null) {
1154 return true;
1155 }
1156
1157 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
1158 if (appState == null) {
Sunny Goyal4fbc3822015-02-18 16:46:50 -08001159 if (DEBUG) {
1160 Throwable stackTrace = new Throwable();
1161 stackTrace.fillInStackTrace();
1162 Log.w(TAG, "Failed to get app state during backup/restore", stackTrace);
1163 }
Chris Wren6d0dde02014-02-10 12:16:54 -05001164 return false;
1165 }
1166 mIconCache = appState.getIconCache();
1167 return mIconCache != null;
1168 }
1169
Chris Wren71144262014-02-27 15:49:39 -05001170
Sunny Goyalef728d42014-10-22 11:28:28 -07001171 /**
1172 * @return true if the launcher is in a state to support backup
1173 */
Chris Wren71144262014-02-27 15:49:39 -05001174 private boolean launcherIsReady() {
1175 ContentResolver cr = mContext.getContentResolver();
1176 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1177 if (cursor == null) {
1178 // launcher data has been wiped, do nothing
1179 return false;
1180 }
1181 cursor.close();
1182
1183 if (!initializeIconCache()) {
1184 // launcher services are unavailable, try again later
1185 dataChanged();
1186 return false;
1187 }
1188
1189 return true;
1190 }
1191
Sunny Goyalffe83f12014-08-14 17:39:34 -07001192 private String getUserSelectionArg() {
1193 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1194 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1195 }
1196
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001197 private class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001198
1199 private static final long serialVersionUID = 8931456637211665082L;
1200
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001201 private InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001202 super(cause);
1203 }
1204
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001205 public InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001206 super(reason);
1207 }
1208 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001209
1210 /**
1211 * A class to check if an activity can handle one of the intents from a list of
1212 * predefined intents.
1213 */
1214 private class ItemTypeMatcher {
1215
1216 private final ArrayList<Intent> mIntents;
1217
1218 ItemTypeMatcher(int xml_res) {
1219 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1220 }
1221
1222 private ArrayList<Intent> parseIntents(int xml_res) {
1223 ArrayList<Intent> intents = new ArrayList<Intent>();
1224 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1225 try {
1226 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1227 final int depth = parser.getDepth();
1228 int type;
1229 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1230 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1231 if (type != XmlPullParser.START_TAG) {
1232 continue;
1233 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1234 final String uri = DefaultLayoutParser.getAttributeValue(
1235 parser, DefaultLayoutParser.ATTR_URI);
1236 intents.add(Intent.parseUri(uri, 0));
1237 }
1238 }
1239 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1240 Log.e(TAG, "Unable to parse " + xml_res, e);
1241 } finally {
1242 parser.close();
1243 }
1244 return intents;
1245 }
1246
1247 public boolean matches(ActivityInfo activity, PackageManager pm) {
1248 for (Intent intent : mIntents) {
1249 intent.setPackage(activity.packageName);
1250 ResolveInfo info = pm.resolveActivity(intent, 0);
1251 if (info != null && (info.activityInfo.name.equals(activity.name)
1252 || info.activityInfo.name.equals(activity.targetActivity))) {
1253 return true;
1254 }
1255 }
1256 return false;
1257 }
1258 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001259}