blob: 744f73bdad95fbb3dacfda58284cb856c5d4658b [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;
Sunny Goyal316490e2015-06-02 09:38:28 -070054import com.android.launcher3.util.Thunk;
Sunny Goyalef728d42014-10-22 11:28:28 -070055import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
56import com.google.protobuf.nano.MessageNano;
57
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080058import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60
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 Goyal3a30cfe2015-07-16 17:27:43 -070078 private static final int BACKUP_VERSION = 3;
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
Chris Wren1ada10d2013-09-13 18:01:38 -040091 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070092 Favorites._ID, // 0
93 Favorites.MODIFIED, // 1
94 Favorites.INTENT, // 2
95 Favorites.APPWIDGET_PROVIDER, // 3
96 Favorites.APPWIDGET_ID, // 4
97 Favorites.CELLX, // 5
98 Favorites.CELLY, // 6
99 Favorites.CONTAINER, // 7
100 Favorites.ICON, // 8
101 Favorites.ICON_PACKAGE, // 9
102 Favorites.ICON_RESOURCE, // 10
103 Favorites.ICON_TYPE, // 11
104 Favorites.ITEM_TYPE, // 12
105 Favorites.SCREEN, // 13
106 Favorites.SPANX, // 14
107 Favorites.SPANY, // 15
108 Favorites.TITLE, // 16
109 Favorites.PROFILE_ID, // 17
Chris Wren1ada10d2013-09-13 18:01:38 -0400110 };
111
112 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400113 private static final int ID_MODIFIED = 1;
114 private static final int INTENT_INDEX = 2;
115 private static final int APPWIDGET_PROVIDER_INDEX = 3;
116 private static final int APPWIDGET_ID_INDEX = 4;
117 private static final int CELLX_INDEX = 5;
118 private static final int CELLY_INDEX = 6;
119 private static final int CONTAINER_INDEX = 7;
120 private static final int ICON_INDEX = 8;
121 private static final int ICON_PACKAGE_INDEX = 9;
122 private static final int ICON_RESOURCE_INDEX = 10;
123 private static final int ICON_TYPE_INDEX = 11;
124 private static final int ITEM_TYPE_INDEX = 12;
125 private static final int SCREEN_INDEX = 13;
126 private static final int SPANX_INDEX = 14;
127 private static final int SPANY_INDEX = 15;
128 private static final int TITLE_INDEX = 16;
Chris Wren1ada10d2013-09-13 18:01:38 -0400129
130 private static final String[] SCREEN_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -0700131 WorkspaceScreens._ID, // 0
132 WorkspaceScreens.MODIFIED, // 1
133 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400134 };
135
Chris Wren22e130d2013-09-23 18:25:57 -0400136 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400137
Sunny Goyal316490e2015-06-02 09:38:28 -0700138 @Thunk final Context mContext;
Sunny Goyalef728d42014-10-22 11:28:28 -0700139 private final HashSet<String> mExistingKeys;
Sunny Goyal42de82f2014-09-26 22:09:29 -0700140 private final ArrayList<Key> mKeys;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800141 private final ItemTypeMatcher[] mItemTypeMatchers;
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800142 private final long mUserSerial;
Chris Wren1ada10d2013-09-13 18:01:38 -0400143
Sunny Goyalef728d42014-10-22 11:28:28 -0700144 private BackupManager mBackupManager;
Sunny Goyalef728d42014-10-22 11:28:28 -0700145 private byte[] mBuffer = new byte[512];
146 private long mLastBackupRestoreTime;
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800147 private boolean mBackupDataWasUpdated;
Sunny Goyalef728d42014-10-22 11:28:28 -0700148
Adam Cohen2e6da152015-05-06 11:42:25 -0700149 private IconCache mIconCache;
150 private DeviceProfieData mDeviceProfileData;
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700151 private InvariantDeviceProfile mIdp;
Adam Cohen2e6da152015-05-06 11:42:25 -0700152
Sunny Goyal33d44382014-10-16 09:24:19 -0700153 boolean restoreSuccessful;
Sunny Goyal08f72612015-01-05 13:41:43 -0800154 int restoredBackupVersion = 1;
Sunny Goyal33d44382014-10-16 09:24:19 -0700155
156 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400157 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700158 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700159 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700160 restoreSuccessful = true;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800161 mItemTypeMatchers = new ItemTypeMatcher[CommonAppTypeParser.SUPPORTED_TYPE_COUNT];
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800162
163 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
164 mUserSerial = userManager.getSerialNumberForUser(UserHandleCompat.myUserHandle());
Chris Wren92aa4232013-10-04 11:29:36 -0400165 }
166
167 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700168 if (mBackupManager == null) {
169 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400170 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700171 mBackupManager.dataChanged();
172 }
173
174 private void applyJournal(Journal journal) {
175 mLastBackupRestoreTime = journal.t;
176 mExistingKeys.clear();
177 if (journal.key != null) {
178 for (Key key : journal.key) {
179 mExistingKeys.add(keyToBackupKey(key));
180 }
181 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700182 restoredBackupVersion = journal.backupVersion;
Chris Wren1ada10d2013-09-13 18:01:38 -0400183 }
184
185 /**
186 * Back up launcher data so we can restore the user's state on a new device.
187 *
188 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
189 *
190 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
191 *
192 * @param oldState notes from the last backup
193 * @param data incremental key/value pairs to persist off-device
194 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400195 */
196 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400197 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
198 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500199 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400200
201 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700202 if (!launcherIsReady()) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700203 dataChanged();
Sunny Goyalef728d42014-10-22 11:28:28 -0700204 // Perform backup later.
205 writeJournal(newState, in);
206 return;
207 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700208
Sunny Goyal96373642015-06-05 11:14:01 -0700209 if (mDeviceProfileData == null) {
210 LauncherAppState app = LauncherAppState.getInstance();
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700211 mIdp = app.getInvariantDeviceProfile();
212 mDeviceProfileData = initDeviceProfileData(mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700213 mIconCache = app.getIconCache();
214 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700215
Sunny Goyalef728d42014-10-22 11:28:28 -0700216 Log.v(TAG, "lastBackupTime = " + in.t);
217 mKeys.clear();
218 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400219
Sunny Goyalef728d42014-10-22 11:28:28 -0700220 // Record the time before performing backup so that entries edited while the backup
221 // was going on, do not get missed in next backup.
222 long newBackupTime = System.currentTimeMillis();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800223 mBackupDataWasUpdated = false;
Sunny Goyalef728d42014-10-22 11:28:28 -0700224 try {
225 backupFavorites(data);
226 backupScreens(data);
227 backupIcons(data);
228 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400229
Sunny Goyalef728d42014-10-22 11:28:28 -0700230 // Delete any key which still exist in the old backup, but is not valid anymore.
231 HashSet<String> validKeys = new HashSet<String>();
232 for (Key key : mKeys) {
233 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500234 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700235 mExistingKeys.removeAll(validKeys);
236
237 // Delete anything left in the existing keys.
238 for (String deleted: mExistingKeys) {
239 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
240 data.writeEntityHeader(deleted, -1);
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800241 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -0700242 }
243
244 mExistingKeys.clear();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800245 if (!mBackupDataWasUpdated) {
246 // Check if any metadata has changed
247 mBackupDataWasUpdated = (in.profile == null)
248 || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
Sunny Goyal96373642015-06-05 11:14:01 -0700249 DeviceProfieData.toByteArray(mDeviceProfileData))
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800250 || (in.backupVersion != BACKUP_VERSION)
251 || (in.appVersion != getAppVersion());
252 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700253
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800254 if (mBackupDataWasUpdated) {
255 mLastBackupRestoreTime = newBackupTime;
256
257 // We store the journal at two places.
258 // 1) Storing it in newState allows us to do partial backups by comparing old state
259 // 2) Storing it in backup data allows us to validate keys during restore
260 Journal state = getCurrentStateJournal();
261 writeRowToBackup(JOURNAL_KEY, state, data);
262 } else {
263 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
264 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700265 } catch (IOException e) {
266 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400267 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400268
Sunny Goyalef728d42014-10-22 11:28:28 -0700269 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400270 }
271
272 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700273 * @return true if the backup corresponding to oldstate can be successfully applied
274 * to this device.
275 */
276 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal96373642015-06-05 11:14:01 -0700277 DeviceProfieData currentProfile = mDeviceProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700278 DeviceProfieData oldProfile = oldState.profile;
279
280 if (oldProfile == null || oldProfile.desktopCols == 0) {
281 // Profile info is not valid, ignore the check.
282 return true;
283 }
284
285 boolean isHotsetCompatible = false;
286 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
287 isHotsetCompatible = true;
288 }
289 if ((currentProfile.hotseatCount >= oldProfile.hotseatCount) &&
290 (currentProfile.allappsRank == oldProfile.allappsRank)) {
291 isHotsetCompatible = true;
292 }
293
294 return isHotsetCompatible && (currentProfile.desktopCols >= oldProfile.desktopCols)
295 && (currentProfile.desktopRows >= oldProfile.desktopRows);
Sunny Goyal33d44382014-10-16 09:24:19 -0700296 }
297
298 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400299 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700300 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
301 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400302 *
Chris Wren92aa4232013-10-04 11:29:36 -0400303 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400304 */
305 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400306 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700307 if (!restoreSuccessful) {
308 return;
309 }
Sunny Goyal96373642015-06-05 11:14:01 -0700310
311 if (mDeviceProfileData == null) {
312 // This call does not happen on a looper thread. So LauncherAppState
313 // can't be created . Instead initialize required dependencies directly.
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700314 mIdp = new InvariantDeviceProfile(mContext);
315 mDeviceProfileData = initDeviceProfileData(mIdp);
316 mIconCache = new IconCache(mContext, mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700317 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700318
Sunny Goyalef728d42014-10-22 11:28:28 -0700319 int dataSize = data.size();
320 if (mBuffer.length < dataSize) {
321 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400322 }
323 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700324 int bytesRead = data.read(mBuffer, 0, dataSize);
325 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
326 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700327
328 if (JOURNAL_KEY.equals(backupKey)) {
329 if (VERBOSE) Log.v(TAG, "Journal entry restored");
330 if (!mKeys.isEmpty()) {
331 // We received the journal key after a restore key.
332 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
333 restoreSuccessful = false;
334 return;
335 }
336
337 Journal journal = new Journal();
338 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
339 applyJournal(journal);
340 restoreSuccessful = isBackupCompatible(journal);
341 return;
342 }
343
344 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
345 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
346 return;
347 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700348 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500349 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400350 switch (key.type) {
351 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700352 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400353 break;
354
355 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700356 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400357 break;
358
359 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700360 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400361 break;
362
363 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700364 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400365 break;
366
367 default:
368 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700369 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400370 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400371 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700372 } catch (IOException e) {
373 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400374 }
Chris Wren92aa4232013-10-04 11:29:36 -0400375 }
376
377 /**
378 * Record the restore state for the next backup.
379 *
380 * @param newState notes about the backup state after restore.
381 */
382 @Override
383 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700384 writeJournal(newState, getCurrentStateJournal());
385 }
386
387 private Journal getCurrentStateJournal() {
388 Journal journal = new Journal();
389 journal.t = mLastBackupRestoreTime;
390 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
391 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700392 journal.backupVersion = BACKUP_VERSION;
Sunny Goyal96373642015-06-05 11:14:01 -0700393 journal.profile = mDeviceProfileData;
Sunny Goyalef728d42014-10-22 11:28:28 -0700394 return journal;
395 }
396
397 private int getAppVersion() {
398 try {
399 return mContext.getPackageManager()
400 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
401 } catch (NameNotFoundException e) {
402 return 0;
403 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400404 }
405
Adam Cohen2e6da152015-05-06 11:42:25 -0700406 private DeviceProfieData initDeviceProfileData(InvariantDeviceProfile profile) {
407 DeviceProfieData data = new DeviceProfieData();
408 data.desktopRows = profile.numRows;
409 data.desktopCols = profile.numColumns;
410 data.hotseatCount = profile.numHotseatIcons;
411 data.allappsRank = profile.hotseatAllAppsRank;
412 return data;
Sunny Goyal33d44382014-10-16 09:24:19 -0700413 }
414
415 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400416 * Write all modified favorites to the data stream.
417 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400418 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400419 * @throws IOException
420 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700421 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400422 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400423 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700424 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400425 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700426 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400427 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400428 cursor.moveToPosition(-1);
429 while(cursor.moveToNext()) {
430 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700431 final long updateTime = cursor.getLong(ID_MODIFIED);
432 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700433 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700434 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700435 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
436 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500437 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700438 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400439 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400440 }
441 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400442 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400443 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400444 }
445
446 /**
447 * Read a favorite from the stream.
448 *
449 * <P>Keys arrive in any order, so screens and containers may not exist yet.
450 *
451 * @param key identifier for the row
452 * @param buffer the serialized proto from the stream, may be larger than dataSize
453 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400454 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700455 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500456 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400457 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
458 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
459
Sunny Goyalef728d42014-10-22 11:28:28 -0700460 ContentResolver cr = mContext.getContentResolver();
461 ContentValues values = unpackFavorite(buffer, dataSize);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700462 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400463 }
464
465 /**
466 * Write all modified screens to the data stream.
467 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400468 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400469 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400470 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700471 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400472 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400473 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400474 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
475 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400476 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400477 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700478 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400479 while(cursor.moveToNext()) {
480 final long id = cursor.getLong(ID_INDEX);
481 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400482 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700483 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500484 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700485 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
486 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500487 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700488 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400489 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400490 }
491 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400492 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400493 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400494 }
495
496 /**
497 * Read a screen from the stream.
498 *
499 * <P>Keys arrive in any order, so children of this screen may already exist.
500 *
501 * @param key identifier for the row
502 * @param buffer the serialized proto from the stream, may be larger than dataSize
503 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400504 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700505 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500506 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400507 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
508 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500509
Sunny Goyalef728d42014-10-22 11:28:28 -0700510 ContentResolver cr = mContext.getContentResolver();
511 ContentValues values = unpackScreen(buffer, dataSize);
512 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400513 }
514
Chris Wren22e130d2013-09-23 18:25:57 -0400515 /**
516 * Write all the static icon resources we need to render placeholders
517 * for a package that is not installed.
518 *
Chris Wren22e130d2013-09-23 18:25:57 -0400519 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400520 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700521 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400522 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400523 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400524 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700525 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700526 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400527
Kenny Guyed131872014-04-30 03:02:21 +0100528 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100529 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100530 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700531 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400532 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
533 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400534 try {
535 cursor.moveToPosition(-1);
536 while(cursor.moveToNext()) {
537 final long id = cursor.getLong(ID_INDEX);
538 final String intentDescription = cursor.getString(INTENT_INDEX);
539 try {
540 Intent intent = Intent.parseUri(intentDescription, 0);
541 ComponentName cn = intent.getComponent();
542 Key key = null;
543 String backupKey = null;
544 if (cn != null) {
545 key = getKey(Key.ICON, cn.flattenToShortString());
546 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400547 } else {
548 Log.w(TAG, "empty intent on application favorite: " + id);
549 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700550 if (mExistingKeys.contains(backupKey)) {
551 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400552
553 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700554 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400555 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700556 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
557 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
558 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100559 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100560 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700561 writeRowToBackup(key, packIcon(dpi, icon), data);
562 mKeys.add(key);
563 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400564 }
565 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700566 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400567 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400568 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400569 }
570 }
571 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500572 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400573 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500574 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400575 }
576
577 }
578 } finally {
579 cursor.close();
580 }
Chris Wren22e130d2013-09-23 18:25:57 -0400581 }
582
583 /**
584 * Read an icon from the stream.
585 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400586 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400587 *
588 * @param key identifier for the row
589 * @param buffer the serialized proto from the stream, may be larger than dataSize
590 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400591 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700592 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500593 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400594 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
595 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500596
Sunny Goyalef728d42014-10-22 11:28:28 -0700597 Resource res = unpackProto(new Resource(), buffer, dataSize);
598 if (DEBUG) {
599 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400600 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700601 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
602 if (icon == null) {
603 Log.w(TAG, "failed to unpack icon for " + key.name);
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700604 } else {
605 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
606 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
607 "" /* label */, mUserSerial, mIdp);
Sunny Goyalef728d42014-10-22 11:28:28 -0700608 }
Chris Wren22e130d2013-09-23 18:25:57 -0400609 }
610
Chris Wrenfd13c712013-09-27 15:45:19 -0400611 /**
612 * Write all the static widget resources we need to render placeholders
613 * for a package that is not installed.
614 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400615 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400616 * @throws IOException
617 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700618 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400619 // persist static widget info that hasn't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400620 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400621 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalef728d42014-10-22 11:28:28 -0700622 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400623
Sunny Goyalffe83f12014-08-14 17:39:34 -0700624 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
625 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400626 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
627 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400628 try {
629 cursor.moveToPosition(-1);
630 while(cursor.moveToNext()) {
631 final long id = cursor.getLong(ID_INDEX);
632 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
Chris Wrenfd13c712013-09-27 15:45:19 -0400633 final ComponentName provider = ComponentName.unflattenFromString(providerName);
634 Key key = null;
635 String backupKey = null;
636 if (provider != null) {
637 key = getKey(Key.WIDGET, providerName);
638 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400639 } else {
640 Log.w(TAG, "empty intent on appwidget: " + id);
641 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700642 if (mExistingKeys.contains(backupKey) && restoredBackupVersion >= BACKUP_VERSION) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700643 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400644
645 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700646 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400647 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700648 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
649 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
650 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Robin Lee26ace122015-03-16 19:41:43 +0000651 UserHandleCompat user = UserHandleCompat.myUserHandle();
Sunny Goyal96373642015-06-05 11:14:01 -0700652 writeRowToBackup(key, packWidget(dpi, provider, user), data);
Sunny Goyalef728d42014-10-22 11:28:28 -0700653 mKeys.add(key);
654 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400655 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700656 if (VERBOSE) Log.v(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 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400665 }
666
667 /**
668 * Read a widget from the stream.
669 *
670 * <P>Keys arrive in any order, so widgets that use this data may already exist.
671 *
672 * @param key identifier for the row
673 * @param buffer the serialized proto from the stream, may be larger than dataSize
674 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400675 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700676 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500677 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400678 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
679 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700680 Widget widget = unpackProto(new Widget(), buffer, dataSize);
681 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
682 if (widget.icon.data != null) {
683 Bitmap icon = BitmapFactory
684 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
685 if (icon == null) {
686 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500687 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800688 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700689 icon, widget.icon.dpi, widget.label, mUserSerial, mIdp);
Chris Wren5dee7af2013-12-20 17:22:11 -0500690 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400691 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700692
693 // future site of widget table mutation
Chris Wrenfd13c712013-09-27 15:45:19 -0400694 }
695
Chris Wren22e130d2013-09-23 18:25:57 -0400696 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400697 *
698 * <P> Keys contain their own checksum instead of using
699 * the heavy-weight CheckedMessage wrapper.
700 */
701 private Key getKey(int type, long id) {
702 Key key = new Key();
703 key.type = type;
704 key.id = id;
705 key.checksum = checkKey(key);
706 return key;
707 }
708
Chris Wren22e130d2013-09-23 18:25:57 -0400709 /** create a new key for a named object.
710 *
711 * <P> Keys contain their own checksum instead of using
712 * the heavy-weight CheckedMessage wrapper.
713 */
714 private Key getKey(int type, String name) {
715 Key key = new Key();
716 key.type = type;
717 key.name = name;
718 key.checksum = checkKey(key);
719 return key;
720 }
721
Chris Wren1ada10d2013-09-13 18:01:38 -0400722 /** keys need to be strings, serialize and encode. */
723 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400724 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400725 }
726
727 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700728 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400729 try {
730 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
731 if (key.checksum != checkKey(key)) {
732 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700733 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400734 }
735 return key;
736 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700737 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400738 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700739 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400740 }
741 }
742
743 /** Compute the checksum over the important bits of a key. */
744 private long checkKey(Key key) {
745 CRC32 checksum = new CRC32();
746 checksum.update(key.type);
747 checksum.update((int) (key.id & 0xffff));
748 checksum.update((int) ((key.id >> 32) & 0xffff));
749 if (!TextUtils.isEmpty(key.name)) {
750 checksum.update(key.name.getBytes());
751 }
752 return checksum.getValue();
753 }
754
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800755 /**
756 * @return true if its an hotseat item, that can be replaced during restore.
757 * TODO: Extend check for folders in hotseat.
758 */
759 private boolean isReplaceableHotseatItem(Favorite favorite) {
760 return favorite.container == Favorites.CONTAINER_HOTSEAT
761 && favorite.intent != null
762 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
763 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
764 }
765
Chris Wren1ada10d2013-09-13 18:01:38 -0400766 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700767 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400768 Favorite favorite = new Favorite();
769 favorite.id = c.getLong(ID_INDEX);
770 favorite.screen = c.getInt(SCREEN_INDEX);
771 favorite.container = c.getInt(CONTAINER_INDEX);
772 favorite.cellX = c.getInt(CELLX_INDEX);
773 favorite.cellY = c.getInt(CELLY_INDEX);
774 favorite.spanX = c.getInt(SPANX_INDEX);
775 favorite.spanY = c.getInt(SPANY_INDEX);
776 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700777
Chris Wren1ada10d2013-09-13 18:01:38 -0400778 String title = c.getString(TITLE_INDEX);
779 if (!TextUtils.isEmpty(title)) {
780 favorite.title = title;
781 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100782 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800783 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100784 if (!TextUtils.isEmpty(intentDescription)) {
785 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800786 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100787 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
788 favorite.intent = intent.toUri(0);
789 } catch (URISyntaxException e) {
790 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700791 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400792 }
793 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
794 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
795 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
796 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
797 if (!TextUtils.isEmpty(appWidgetProvider)) {
798 favorite.appWidgetProvider = appWidgetProvider;
799 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700800 } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
801 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
802 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
803 if (!TextUtils.isEmpty(iconPackage)) {
804 favorite.iconPackage = iconPackage;
805 }
806 String iconResource = c.getString(ICON_RESOURCE_INDEX);
807 if (!TextUtils.isEmpty(iconResource)) {
808 favorite.iconResource = iconResource;
809 }
810 }
811
812 byte[] blob = c.getBlob(ICON_INDEX);
813 if (blob != null && blob.length > 0) {
814 favorite.icon = blob;
815 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400816 }
817
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800818 if (isReplaceableHotseatItem(favorite)) {
819 if (intent != null && intent.getComponent() != null) {
820 PackageManager pm = mContext.getPackageManager();
821 ActivityInfo activity = null;;
822 try {
823 activity = pm.getActivityInfo(intent.getComponent(), 0);
824 } catch (NameNotFoundException e) {
825 Log.e(TAG, "Target not found", e);
826 }
827 if (activity == null) {
828 return favorite;
829 }
830 for (int i = 0; i < mItemTypeMatchers.length; i++) {
831 if (mItemTypeMatchers[i] == null) {
832 mItemTypeMatchers[i] = new ItemTypeMatcher(
833 CommonAppTypeParser.getResourceForItemType(i));
834 }
835 if (mItemTypeMatchers[i].matches(activity, pm)) {
836 favorite.targetType = i;
837 break;
838 }
839 }
840 }
841 }
842
Sunny Goyalef728d42014-10-22 11:28:28 -0700843 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400844 }
845
846 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700847 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700848 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700849 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800850
Chris Wren5dee7af2013-12-20 17:22:11 -0500851 ContentValues values = new ContentValues();
852 values.put(Favorites._ID, favorite.id);
853 values.put(Favorites.SCREEN, favorite.screen);
854 values.put(Favorites.CONTAINER, favorite.container);
855 values.put(Favorites.CELLX, favorite.cellX);
856 values.put(Favorites.CELLY, favorite.cellY);
857 values.put(Favorites.SPANX, favorite.spanX);
858 values.put(Favorites.SPANY, favorite.spanY);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700859
860 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
861 values.put(Favorites.ICON_TYPE, favorite.iconType);
862 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
863 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
864 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
865 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500866 values.put(Favorites.ICON, favorite.icon);
867 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700868
Chris Wren5dee7af2013-12-20 17:22:11 -0500869 if (!TextUtils.isEmpty(favorite.title)) {
870 values.put(Favorites.TITLE, favorite.title);
871 } else {
872 values.put(Favorites.TITLE, "");
873 }
874 if (!TextUtils.isEmpty(favorite.intent)) {
875 values.put(Favorites.INTENT, favorite.intent);
876 }
877 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500878
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100879 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
880 long userSerialNumber =
881 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
882 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
883
Sunny Goyal96373642015-06-05 11:14:01 -0700884 DeviceProfieData currentProfile = mDeviceProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700885
Sunny Goyalff572272014-07-23 13:58:07 -0700886 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
887 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
888 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
889 }
890 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
891 values.put(LauncherSettings.Favorites.RESTORED,
892 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
893 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
894 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700895
896 // Verify placement
897 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
898 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
899 restoreSuccessful = false;
900 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
901 }
Sunny Goyalff572272014-07-23 13:58:07 -0700902 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800903 // Check if it is an hotseat item, that can be replaced.
904 if (isReplaceableHotseatItem(favorite)
905 && favorite.targetType != Favorite.TARGET_NONE
906 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
907 Log.e(TAG, "Added item type flag");
908 values.put(LauncherSettings.Favorites.RESTORED,
909 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
910 } else {
911 // Let LauncherModel know we've been here.
912 values.put(LauncherSettings.Favorites.RESTORED, 1);
913 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700914
915 // Verify placement
916 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
917 if ((favorite.screen >= currentProfile.hotseatCount)
918 || (favorite.screen == currentProfile.allappsRank)) {
919 restoreSuccessful = false;
920 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
921 }
922 } else {
923 if ((favorite.cellX >= currentProfile.desktopCols)
924 || (favorite.cellY >= currentProfile.desktopRows)) {
925 restoreSuccessful = false;
926 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
927 }
928 }
Sunny Goyalff572272014-07-23 13:58:07 -0700929 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500930
Chris Wren5dee7af2013-12-20 17:22:11 -0500931 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400932 }
933
934 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700935 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400936 Screen screen = new Screen();
937 screen.id = c.getLong(ID_INDEX);
938 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700939 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400940 }
941
942 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700943 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400944 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700945 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500946 ContentValues values = new ContentValues();
947 values.put(WorkspaceScreens._ID, screen.id);
948 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
949 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400950 }
951
Chris Wren22e130d2013-09-23 18:25:57 -0400952 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700953 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400954 Resource res = new Resource();
955 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -0700956 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -0400957 return res;
958 }
959
Chris Wrenfd13c712013-09-27 15:45:19 -0400960 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal96373642015-06-05 11:14:01 -0700961 private Widget packWidget(int dpi, ComponentName provider, UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -0800962 final LauncherAppWidgetProviderInfo info =
Robin Lee26ace122015-03-16 19:41:43 +0000963 LauncherModel.getProviderInfo(mContext, provider, user);
Chris Wrenfd13c712013-09-27 15:45:19 -0400964 Widget widget = new Widget();
965 widget.provider = provider.flattenToShortString();
966 widget.label = info.label;
967 widget.configure = info.configure != null;
968 if (info.icon != 0) {
969 widget.icon = new Resource();
Sunny Goyal96373642015-06-05 11:14:01 -0700970 Drawable fullResIcon = mIconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400971 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -0700972 widget.icon.data = Utilities.flattenBitmap(icon);
973 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400974 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700975
976 // Calculate the spans corresponding to any one of the orientations as it should not change
977 // based on orientation.
978 int[] minSpans = CellLayout.rectToCell(
979 mIdp.portraitProfile, mContext, info.minResizeWidth, info.minResizeHeight, null);
980 widget.minSpanX = (info.resizeMode & LauncherAppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0
981 ? minSpans[0] : -1;
982 widget.minSpanY = (info.resizeMode & LauncherAppWidgetProviderInfo.RESIZE_VERTICAL) != 0
983 ? minSpans[1] : -1;
984
Sunny Goyalef728d42014-10-22 11:28:28 -0700985 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -0400986 }
987
Sunny Goyalef728d42014-10-22 11:28:28 -0700988 /**
989 * Deserialize a proto after verifying checksum wrapper.
990 */
991 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -0400992 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700993 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
994 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
995 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -0400996 }
997
Chris Wren1ada10d2013-09-13 18:01:38 -0400998 /**
999 * Read the old journal from the input file.
1000 *
1001 * In the event of any error, just pretend we didn't have a journal,
1002 * in that case, do a full backup.
1003 *
1004 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001005 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001006 */
1007 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001008 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001009 if (oldState == null) {
1010 return journal;
1011 }
1012 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1013 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001014 int availableBytes = inStream.available();
1015 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1016 if (availableBytes < MAX_JOURNAL_SIZE) {
1017 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001018 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001019 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001020 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001021 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001022 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001023 // OMG what are you doing? This is crazy inefficient!
1024 // If we read a byte that is not ours, we will cause trouble: b/12491813
1025 // However, we don't know how many bytes to expect (oops).
1026 // So we have to step through *slowly*, watching for the end.
1027 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001028 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001029 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001030 bytesRead += result;
1031 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001032 Log.w(TAG, "unexpected end of file while reading journal.");
1033 // stop reading and see what there is to parse
1034 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001035 }
1036 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001037 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001038 availableBytes = 0;
1039 }
1040
1041 // check the buffer to see if we have a valid journal
1042 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001043 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001044 // if we are here, then we have read a valid, checksum-verified journal
1045 valid = true;
1046 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001047 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001048 } catch (InvalidProtocolBufferNanoException e) {
1049 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001050 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001051 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001052 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001053 }
Chris Wren92aa4232013-10-04 11:29:36 -04001054 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001055 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001056 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001057 }
1058 }
Chris Wren92aa4232013-10-04 11:29:36 -04001059 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001060 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001061 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001062 try {
1063 inStream.close();
1064 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001065 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001066 }
1067 }
1068 return journal;
1069 }
1070
Sunny Goyalef728d42014-10-22 11:28:28 -07001071 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1072 throws IOException {
1073 writeRowToBackup(keyToBackupKey(key), proto, data);
1074 }
1075
1076 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001077 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001078 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001079 data.writeEntityHeader(backupKey, blob.length);
1080 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001081 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001082 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001083 }
1084
Chris Wren1ada10d2013-09-13 18:01:38 -04001085 /**
1086 * Write the new journal to the output file.
1087 *
1088 * In the event of any error, just pretend we didn't have a journal,
1089 * in that case, do a full backup.
1090
1091 * @param newState the write-only file descriptor pointing to the new journal
1092 * @param journal a Journal protocol buffer
1093 */
1094 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1095 FileOutputStream outStream = null;
1096 try {
1097 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001098 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001099 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001100 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001101 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001102 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001103 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001104 }
1105 }
1106
1107 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1108 private byte[] writeCheckedBytes(MessageNano proto) {
1109 CheckedMessage wrapper = new CheckedMessage();
1110 wrapper.payload = MessageNano.toByteArray(proto);
1111 CRC32 checksum = new CRC32();
1112 checksum.update(wrapper.payload);
1113 wrapper.checksum = checksum.getValue();
1114 return MessageNano.toByteArray(wrapper);
1115 }
1116
1117 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001118 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001119 throws InvalidProtocolBufferNanoException {
1120 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001121 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001122 CRC32 checksum = new CRC32();
1123 checksum.update(wrapper.payload);
1124 if (wrapper.checksum != checksum.getValue()) {
1125 throw new InvalidProtocolBufferNanoException("checksum does not match");
1126 }
1127 return wrapper.payload;
1128 }
1129
Sunny Goyalef728d42014-10-22 11:28:28 -07001130 /**
1131 * @return true if the launcher is in a state to support backup
1132 */
Chris Wren71144262014-02-27 15:49:39 -05001133 private boolean launcherIsReady() {
1134 ContentResolver cr = mContext.getContentResolver();
1135 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1136 if (cursor == null) {
1137 // launcher data has been wiped, do nothing
1138 return false;
1139 }
1140 cursor.close();
1141
Adam Cohen2e6da152015-05-06 11:42:25 -07001142 if (LauncherAppState.getInstanceNoCreate() == null) {
Chris Wren71144262014-02-27 15:49:39 -05001143 // launcher services are unavailable, try again later
Chris Wren71144262014-02-27 15:49:39 -05001144 return false;
1145 }
1146
1147 return true;
1148 }
1149
Sunny Goyalffe83f12014-08-14 17:39:34 -07001150 private String getUserSelectionArg() {
1151 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1152 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1153 }
1154
Sunny Goyal316490e2015-06-02 09:38:28 -07001155 @Thunk class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001156
1157 private static final long serialVersionUID = 8931456637211665082L;
1158
Sunny Goyal316490e2015-06-02 09:38:28 -07001159 @Thunk InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001160 super(cause);
1161 }
1162
Sunny Goyal316490e2015-06-02 09:38:28 -07001163 @Thunk InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001164 super(reason);
1165 }
1166 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001167
1168 /**
1169 * A class to check if an activity can handle one of the intents from a list of
1170 * predefined intents.
1171 */
1172 private class ItemTypeMatcher {
1173
1174 private final ArrayList<Intent> mIntents;
1175
1176 ItemTypeMatcher(int xml_res) {
1177 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1178 }
1179
1180 private ArrayList<Intent> parseIntents(int xml_res) {
1181 ArrayList<Intent> intents = new ArrayList<Intent>();
1182 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1183 try {
1184 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1185 final int depth = parser.getDepth();
1186 int type;
1187 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1188 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1189 if (type != XmlPullParser.START_TAG) {
1190 continue;
1191 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1192 final String uri = DefaultLayoutParser.getAttributeValue(
1193 parser, DefaultLayoutParser.ATTR_URI);
1194 intents.add(Intent.parseUri(uri, 0));
1195 }
1196 }
1197 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1198 Log.e(TAG, "Unable to parse " + xml_res, e);
1199 } finally {
1200 parser.close();
1201 }
1202 return intents;
1203 }
1204
1205 public boolean matches(ActivityInfo activity, PackageManager pm) {
1206 for (Intent intent : mIntents) {
1207 intent.setPackage(activity.packageName);
1208 ResolveInfo info = pm.resolveActivity(intent, 0);
1209 if (info != null && (info.activityInfo.name.equals(activity.name)
1210 || info.activityInfo.name.equals(activity.targetActivity))) {
1211 return true;
1212 }
1213 }
1214 return false;
1215 }
1216 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001217}