blob: 38a4bdeb46c602881f3ccdffce5ee07fd34a657c [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
Sunny Goyalc115e642015-07-20 14:23:43 -0700156 // When migrating from a device which different hotseat configuration, the icons are shifted
157 // to center along the new all-apps icon.
158 private int mHotseatShift = 0;
159
Sunny Goyal33d44382014-10-16 09:24:19 -0700160 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400161 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700162 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700163 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700164 restoreSuccessful = true;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800165 mItemTypeMatchers = new ItemTypeMatcher[CommonAppTypeParser.SUPPORTED_TYPE_COUNT];
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800166
167 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
168 mUserSerial = userManager.getSerialNumberForUser(UserHandleCompat.myUserHandle());
Chris Wren92aa4232013-10-04 11:29:36 -0400169 }
170
171 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700172 if (mBackupManager == null) {
173 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400174 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700175 mBackupManager.dataChanged();
176 }
177
178 private void applyJournal(Journal journal) {
179 mLastBackupRestoreTime = journal.t;
180 mExistingKeys.clear();
181 if (journal.key != null) {
182 for (Key key : journal.key) {
183 mExistingKeys.add(keyToBackupKey(key));
184 }
185 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700186 restoredBackupVersion = journal.backupVersion;
Chris Wren1ada10d2013-09-13 18:01:38 -0400187 }
188
189 /**
190 * Back up launcher data so we can restore the user's state on a new device.
191 *
192 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
193 *
194 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
195 *
196 * @param oldState notes from the last backup
197 * @param data incremental key/value pairs to persist off-device
198 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400199 */
200 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400201 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
202 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500203 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400204
205 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700206 if (!launcherIsReady()) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700207 dataChanged();
Sunny Goyalef728d42014-10-22 11:28:28 -0700208 // Perform backup later.
209 writeJournal(newState, in);
210 return;
211 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700212
Sunny Goyal96373642015-06-05 11:14:01 -0700213 if (mDeviceProfileData == null) {
214 LauncherAppState app = LauncherAppState.getInstance();
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700215 mIdp = app.getInvariantDeviceProfile();
216 mDeviceProfileData = initDeviceProfileData(mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700217 mIconCache = app.getIconCache();
218 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700219
Sunny Goyalef728d42014-10-22 11:28:28 -0700220 Log.v(TAG, "lastBackupTime = " + in.t);
221 mKeys.clear();
222 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400223
Sunny Goyalef728d42014-10-22 11:28:28 -0700224 // Record the time before performing backup so that entries edited while the backup
225 // was going on, do not get missed in next backup.
226 long newBackupTime = System.currentTimeMillis();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800227 mBackupDataWasUpdated = false;
Sunny Goyalef728d42014-10-22 11:28:28 -0700228 try {
229 backupFavorites(data);
230 backupScreens(data);
231 backupIcons(data);
232 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400233
Sunny Goyalef728d42014-10-22 11:28:28 -0700234 // Delete any key which still exist in the old backup, but is not valid anymore.
235 HashSet<String> validKeys = new HashSet<String>();
236 for (Key key : mKeys) {
237 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500238 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700239 mExistingKeys.removeAll(validKeys);
240
241 // Delete anything left in the existing keys.
242 for (String deleted: mExistingKeys) {
243 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
244 data.writeEntityHeader(deleted, -1);
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800245 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -0700246 }
247
248 mExistingKeys.clear();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800249 if (!mBackupDataWasUpdated) {
250 // Check if any metadata has changed
251 mBackupDataWasUpdated = (in.profile == null)
252 || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
Sunny Goyal96373642015-06-05 11:14:01 -0700253 DeviceProfieData.toByteArray(mDeviceProfileData))
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800254 || (in.backupVersion != BACKUP_VERSION)
255 || (in.appVersion != getAppVersion());
256 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700257
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800258 if (mBackupDataWasUpdated) {
259 mLastBackupRestoreTime = newBackupTime;
260
261 // We store the journal at two places.
262 // 1) Storing it in newState allows us to do partial backups by comparing old state
263 // 2) Storing it in backup data allows us to validate keys during restore
264 Journal state = getCurrentStateJournal();
265 writeRowToBackup(JOURNAL_KEY, state, data);
266 } else {
267 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
268 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700269 } catch (IOException e) {
270 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400271 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400272
Sunny Goyalef728d42014-10-22 11:28:28 -0700273 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400274 }
275
276 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700277 * @return true if the backup corresponding to oldstate can be successfully applied
278 * to this device.
279 */
280 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal96373642015-06-05 11:14:01 -0700281 DeviceProfieData currentProfile = mDeviceProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700282 DeviceProfieData oldProfile = oldState.profile;
283
284 if (oldProfile == null || oldProfile.desktopCols == 0) {
285 // Profile info is not valid, ignore the check.
286 return true;
287 }
288
289 boolean isHotsetCompatible = false;
290 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
291 isHotsetCompatible = true;
Sunny Goyalc115e642015-07-20 14:23:43 -0700292 mHotseatShift = 0;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700293 }
Sunny Goyalc115e642015-07-20 14:23:43 -0700294
295 if ((currentProfile.allappsRank >= oldProfile.allappsRank)
296 && ((currentProfile.hotseatCount - currentProfile.allappsRank) >=
297 (oldProfile.hotseatCount - oldProfile.allappsRank))) {
298 // There is enough space on both sides of the hotseat.
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700299 isHotsetCompatible = true;
Sunny Goyalc115e642015-07-20 14:23:43 -0700300 mHotseatShift = currentProfile.allappsRank - oldProfile.allappsRank;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700301 }
302
303 return isHotsetCompatible && (currentProfile.desktopCols >= oldProfile.desktopCols)
304 && (currentProfile.desktopRows >= oldProfile.desktopRows);
Sunny Goyal33d44382014-10-16 09:24:19 -0700305 }
306
307 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400308 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700309 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
310 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400311 *
Chris Wren92aa4232013-10-04 11:29:36 -0400312 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400313 */
314 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400315 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700316 if (!restoreSuccessful) {
317 return;
318 }
Sunny Goyal96373642015-06-05 11:14:01 -0700319
320 if (mDeviceProfileData == null) {
321 // This call does not happen on a looper thread. So LauncherAppState
322 // can't be created . Instead initialize required dependencies directly.
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700323 mIdp = new InvariantDeviceProfile(mContext);
324 mDeviceProfileData = initDeviceProfileData(mIdp);
325 mIconCache = new IconCache(mContext, mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700326 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700327
Sunny Goyalef728d42014-10-22 11:28:28 -0700328 int dataSize = data.size();
329 if (mBuffer.length < dataSize) {
330 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400331 }
332 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700333 int bytesRead = data.read(mBuffer, 0, dataSize);
334 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
335 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700336
337 if (JOURNAL_KEY.equals(backupKey)) {
338 if (VERBOSE) Log.v(TAG, "Journal entry restored");
339 if (!mKeys.isEmpty()) {
340 // We received the journal key after a restore key.
341 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
342 restoreSuccessful = false;
343 return;
344 }
345
346 Journal journal = new Journal();
347 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
348 applyJournal(journal);
349 restoreSuccessful = isBackupCompatible(journal);
350 return;
351 }
352
353 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
354 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
355 return;
356 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700357 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500358 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400359 switch (key.type) {
360 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700361 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400362 break;
363
364 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700365 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400366 break;
367
368 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700369 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400370 break;
371
372 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700373 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400374 break;
375
376 default:
377 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700378 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400379 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400380 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700381 } catch (IOException e) {
382 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400383 }
Chris Wren92aa4232013-10-04 11:29:36 -0400384 }
385
386 /**
387 * Record the restore state for the next backup.
388 *
389 * @param newState notes about the backup state after restore.
390 */
391 @Override
392 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700393 writeJournal(newState, getCurrentStateJournal());
394 }
395
396 private Journal getCurrentStateJournal() {
397 Journal journal = new Journal();
398 journal.t = mLastBackupRestoreTime;
399 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
400 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700401 journal.backupVersion = BACKUP_VERSION;
Sunny Goyal96373642015-06-05 11:14:01 -0700402 journal.profile = mDeviceProfileData;
Sunny Goyalef728d42014-10-22 11:28:28 -0700403 return journal;
404 }
405
406 private int getAppVersion() {
407 try {
408 return mContext.getPackageManager()
409 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
410 } catch (NameNotFoundException e) {
411 return 0;
412 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400413 }
414
Adam Cohen2e6da152015-05-06 11:42:25 -0700415 private DeviceProfieData initDeviceProfileData(InvariantDeviceProfile profile) {
416 DeviceProfieData data = new DeviceProfieData();
417 data.desktopRows = profile.numRows;
418 data.desktopCols = profile.numColumns;
419 data.hotseatCount = profile.numHotseatIcons;
420 data.allappsRank = profile.hotseatAllAppsRank;
421 return data;
Sunny Goyal33d44382014-10-16 09:24:19 -0700422 }
423
424 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400425 * Write all modified favorites to the data stream.
426 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400427 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400428 * @throws IOException
429 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700430 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400431 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400432 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700433 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400434 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700435 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400436 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400437 cursor.moveToPosition(-1);
438 while(cursor.moveToNext()) {
439 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700440 final long updateTime = cursor.getLong(ID_MODIFIED);
441 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700442 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700443 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700444 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
445 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500446 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700447 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400448 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400449 }
450 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400451 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400452 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400453 }
454
455 /**
456 * Read a favorite from the stream.
457 *
458 * <P>Keys arrive in any order, so screens and containers may not exist yet.
459 *
460 * @param key identifier for the row
461 * @param buffer the serialized proto from the stream, may be larger than dataSize
462 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400463 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700464 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500465 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400466 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
467 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
468
Sunny Goyalef728d42014-10-22 11:28:28 -0700469 ContentResolver cr = mContext.getContentResolver();
470 ContentValues values = unpackFavorite(buffer, dataSize);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700471 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400472 }
473
474 /**
475 * Write all modified screens to the data stream.
476 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400477 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400478 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700480 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400481 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400482 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400483 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
484 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400485 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400486 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700487 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400488 while(cursor.moveToNext()) {
489 final long id = cursor.getLong(ID_INDEX);
490 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400491 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700492 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500493 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700494 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
495 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500496 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700497 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400498 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400499 }
500 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400501 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400502 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400503 }
504
505 /**
506 * Read a screen from the stream.
507 *
508 * <P>Keys arrive in any order, so children of this screen may already exist.
509 *
510 * @param key identifier for the row
511 * @param buffer the serialized proto from the stream, may be larger than dataSize
512 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400513 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700514 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500515 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400516 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
517 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500518
Sunny Goyalef728d42014-10-22 11:28:28 -0700519 ContentResolver cr = mContext.getContentResolver();
520 ContentValues values = unpackScreen(buffer, dataSize);
521 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400522 }
523
Chris Wren22e130d2013-09-23 18:25:57 -0400524 /**
525 * Write all the static icon resources we need to render placeholders
526 * for a package that is not installed.
527 *
Chris Wren22e130d2013-09-23 18:25:57 -0400528 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400529 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700530 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400531 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400532 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400533 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700534 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700535 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400536
Kenny Guyed131872014-04-30 03:02:21 +0100537 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100538 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100539 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700540 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400541 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
542 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400543 try {
544 cursor.moveToPosition(-1);
545 while(cursor.moveToNext()) {
546 final long id = cursor.getLong(ID_INDEX);
547 final String intentDescription = cursor.getString(INTENT_INDEX);
548 try {
549 Intent intent = Intent.parseUri(intentDescription, 0);
550 ComponentName cn = intent.getComponent();
551 Key key = null;
552 String backupKey = null;
553 if (cn != null) {
554 key = getKey(Key.ICON, cn.flattenToShortString());
555 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400556 } else {
557 Log.w(TAG, "empty intent on application favorite: " + id);
558 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700559 if (mExistingKeys.contains(backupKey)) {
560 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400561
562 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700563 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400564 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700565 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
566 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
567 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100568 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100569 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700570 writeRowToBackup(key, packIcon(dpi, icon), data);
571 mKeys.add(key);
572 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400573 }
574 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700575 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400576 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400577 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400578 }
579 }
580 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500581 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400582 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500583 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400584 }
585
586 }
587 } finally {
588 cursor.close();
589 }
Chris Wren22e130d2013-09-23 18:25:57 -0400590 }
591
592 /**
593 * Read an icon from the stream.
594 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400595 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400596 *
597 * @param key identifier for the row
598 * @param buffer the serialized proto from the stream, may be larger than dataSize
599 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400600 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700601 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500602 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400603 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
604 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500605
Sunny Goyalef728d42014-10-22 11:28:28 -0700606 Resource res = unpackProto(new Resource(), buffer, dataSize);
607 if (DEBUG) {
608 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400609 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700610 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
611 if (icon == null) {
612 Log.w(TAG, "failed to unpack icon for " + key.name);
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700613 } else {
614 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
615 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
616 "" /* label */, mUserSerial, mIdp);
Sunny Goyalef728d42014-10-22 11:28:28 -0700617 }
Chris Wren22e130d2013-09-23 18:25:57 -0400618 }
619
Chris Wrenfd13c712013-09-27 15:45:19 -0400620 /**
621 * Write all the static widget resources we need to render placeholders
622 * for a package that is not installed.
623 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400624 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400625 * @throws IOException
626 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700627 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400628 // persist static widget info that hasn't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400629 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400630 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalef728d42014-10-22 11:28:28 -0700631 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400632
Sunny Goyalffe83f12014-08-14 17:39:34 -0700633 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
634 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400635 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
636 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400637 try {
638 cursor.moveToPosition(-1);
639 while(cursor.moveToNext()) {
640 final long id = cursor.getLong(ID_INDEX);
641 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
Chris Wrenfd13c712013-09-27 15:45:19 -0400642 final ComponentName provider = ComponentName.unflattenFromString(providerName);
643 Key key = null;
644 String backupKey = null;
645 if (provider != null) {
646 key = getKey(Key.WIDGET, providerName);
647 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400648 } else {
649 Log.w(TAG, "empty intent on appwidget: " + id);
650 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700651 if (mExistingKeys.contains(backupKey) && restoredBackupVersion >= BACKUP_VERSION) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700652 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400653
654 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700655 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400656 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700657 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
658 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
659 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Robin Lee26ace122015-03-16 19:41:43 +0000660 UserHandleCompat user = UserHandleCompat.myUserHandle();
Sunny Goyal96373642015-06-05 11:14:01 -0700661 writeRowToBackup(key, packWidget(dpi, provider, user), data);
Sunny Goyalef728d42014-10-22 11:28:28 -0700662 mKeys.add(key);
663 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400664 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700665 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400666 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400667 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400668 }
669 }
670 }
671 } finally {
672 cursor.close();
673 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400674 }
675
676 /**
677 * Read a widget from the stream.
678 *
679 * <P>Keys arrive in any order, so widgets that use this data may already exist.
680 *
681 * @param key identifier for the row
682 * @param buffer the serialized proto from the stream, may be larger than dataSize
683 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400684 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700685 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500686 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400687 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
688 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700689 Widget widget = unpackProto(new Widget(), buffer, dataSize);
690 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
691 if (widget.icon.data != null) {
692 Bitmap icon = BitmapFactory
693 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
694 if (icon == null) {
695 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500696 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800697 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700698 icon, widget.icon.dpi, widget.label, mUserSerial, mIdp);
Chris Wren5dee7af2013-12-20 17:22:11 -0500699 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400700 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700701
702 // future site of widget table mutation
Chris Wrenfd13c712013-09-27 15:45:19 -0400703 }
704
Chris Wren22e130d2013-09-23 18:25:57 -0400705 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400706 *
707 * <P> Keys contain their own checksum instead of using
708 * the heavy-weight CheckedMessage wrapper.
709 */
710 private Key getKey(int type, long id) {
711 Key key = new Key();
712 key.type = type;
713 key.id = id;
714 key.checksum = checkKey(key);
715 return key;
716 }
717
Chris Wren22e130d2013-09-23 18:25:57 -0400718 /** create a new key for a named object.
719 *
720 * <P> Keys contain their own checksum instead of using
721 * the heavy-weight CheckedMessage wrapper.
722 */
723 private Key getKey(int type, String name) {
724 Key key = new Key();
725 key.type = type;
726 key.name = name;
727 key.checksum = checkKey(key);
728 return key;
729 }
730
Chris Wren1ada10d2013-09-13 18:01:38 -0400731 /** keys need to be strings, serialize and encode. */
732 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400733 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400734 }
735
736 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700737 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400738 try {
739 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
740 if (key.checksum != checkKey(key)) {
741 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700742 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400743 }
744 return key;
745 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700746 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400747 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700748 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400749 }
750 }
751
752 /** Compute the checksum over the important bits of a key. */
753 private long checkKey(Key key) {
754 CRC32 checksum = new CRC32();
755 checksum.update(key.type);
756 checksum.update((int) (key.id & 0xffff));
757 checksum.update((int) ((key.id >> 32) & 0xffff));
758 if (!TextUtils.isEmpty(key.name)) {
759 checksum.update(key.name.getBytes());
760 }
761 return checksum.getValue();
762 }
763
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800764 /**
765 * @return true if its an hotseat item, that can be replaced during restore.
766 * TODO: Extend check for folders in hotseat.
767 */
768 private boolean isReplaceableHotseatItem(Favorite favorite) {
769 return favorite.container == Favorites.CONTAINER_HOTSEAT
770 && favorite.intent != null
771 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
772 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
773 }
774
Chris Wren1ada10d2013-09-13 18:01:38 -0400775 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700776 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400777 Favorite favorite = new Favorite();
778 favorite.id = c.getLong(ID_INDEX);
779 favorite.screen = c.getInt(SCREEN_INDEX);
780 favorite.container = c.getInt(CONTAINER_INDEX);
781 favorite.cellX = c.getInt(CELLX_INDEX);
782 favorite.cellY = c.getInt(CELLY_INDEX);
783 favorite.spanX = c.getInt(SPANX_INDEX);
784 favorite.spanY = c.getInt(SPANY_INDEX);
785 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700786
Chris Wren1ada10d2013-09-13 18:01:38 -0400787 String title = c.getString(TITLE_INDEX);
788 if (!TextUtils.isEmpty(title)) {
789 favorite.title = title;
790 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100791 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800792 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100793 if (!TextUtils.isEmpty(intentDescription)) {
794 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800795 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100796 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
797 favorite.intent = intent.toUri(0);
798 } catch (URISyntaxException e) {
799 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700800 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400801 }
802 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
803 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
804 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
805 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
806 if (!TextUtils.isEmpty(appWidgetProvider)) {
807 favorite.appWidgetProvider = appWidgetProvider;
808 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700809 } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
810 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
811 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
812 if (!TextUtils.isEmpty(iconPackage)) {
813 favorite.iconPackage = iconPackage;
814 }
815 String iconResource = c.getString(ICON_RESOURCE_INDEX);
816 if (!TextUtils.isEmpty(iconResource)) {
817 favorite.iconResource = iconResource;
818 }
819 }
820
821 byte[] blob = c.getBlob(ICON_INDEX);
822 if (blob != null && blob.length > 0) {
823 favorite.icon = blob;
824 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400825 }
826
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800827 if (isReplaceableHotseatItem(favorite)) {
828 if (intent != null && intent.getComponent() != null) {
829 PackageManager pm = mContext.getPackageManager();
830 ActivityInfo activity = null;;
831 try {
832 activity = pm.getActivityInfo(intent.getComponent(), 0);
833 } catch (NameNotFoundException e) {
834 Log.e(TAG, "Target not found", e);
835 }
836 if (activity == null) {
837 return favorite;
838 }
839 for (int i = 0; i < mItemTypeMatchers.length; i++) {
840 if (mItemTypeMatchers[i] == null) {
841 mItemTypeMatchers[i] = new ItemTypeMatcher(
842 CommonAppTypeParser.getResourceForItemType(i));
843 }
844 if (mItemTypeMatchers[i].matches(activity, pm)) {
845 favorite.targetType = i;
846 break;
847 }
848 }
849 }
850 }
851
Sunny Goyalef728d42014-10-22 11:28:28 -0700852 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400853 }
854
855 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700856 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700857 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700858 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800859
Sunny Goyalc115e642015-07-20 14:23:43 -0700860 // If it is a hotseat item, move it accordingly.
861 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
862 favorite.screen += mHotseatShift;
863 }
864
Chris Wren5dee7af2013-12-20 17:22:11 -0500865 ContentValues values = new ContentValues();
866 values.put(Favorites._ID, favorite.id);
867 values.put(Favorites.SCREEN, favorite.screen);
868 values.put(Favorites.CONTAINER, favorite.container);
869 values.put(Favorites.CELLX, favorite.cellX);
870 values.put(Favorites.CELLY, favorite.cellY);
871 values.put(Favorites.SPANX, favorite.spanX);
872 values.put(Favorites.SPANY, favorite.spanY);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700873
874 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
875 values.put(Favorites.ICON_TYPE, favorite.iconType);
876 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
877 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
878 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
879 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500880 values.put(Favorites.ICON, favorite.icon);
881 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700882
Chris Wren5dee7af2013-12-20 17:22:11 -0500883 if (!TextUtils.isEmpty(favorite.title)) {
884 values.put(Favorites.TITLE, favorite.title);
885 } else {
886 values.put(Favorites.TITLE, "");
887 }
888 if (!TextUtils.isEmpty(favorite.intent)) {
889 values.put(Favorites.INTENT, favorite.intent);
890 }
891 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500892
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100893 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
894 long userSerialNumber =
895 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
896 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
897
Sunny Goyal96373642015-06-05 11:14:01 -0700898 DeviceProfieData currentProfile = mDeviceProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700899
Sunny Goyalff572272014-07-23 13:58:07 -0700900 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
901 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
902 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
903 }
904 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
905 values.put(LauncherSettings.Favorites.RESTORED,
906 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
907 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
908 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700909
910 // Verify placement
911 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
912 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
913 restoreSuccessful = false;
914 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
915 }
Sunny Goyalff572272014-07-23 13:58:07 -0700916 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800917 // Check if it is an hotseat item, that can be replaced.
918 if (isReplaceableHotseatItem(favorite)
919 && favorite.targetType != Favorite.TARGET_NONE
920 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
921 Log.e(TAG, "Added item type flag");
922 values.put(LauncherSettings.Favorites.RESTORED,
923 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
924 } else {
925 // Let LauncherModel know we've been here.
926 values.put(LauncherSettings.Favorites.RESTORED, 1);
927 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700928
929 // Verify placement
930 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
931 if ((favorite.screen >= currentProfile.hotseatCount)
932 || (favorite.screen == currentProfile.allappsRank)) {
933 restoreSuccessful = false;
934 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
935 }
936 } else {
937 if ((favorite.cellX >= currentProfile.desktopCols)
938 || (favorite.cellY >= currentProfile.desktopRows)) {
939 restoreSuccessful = false;
940 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
941 }
942 }
Sunny Goyalff572272014-07-23 13:58:07 -0700943 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500944
Chris Wren5dee7af2013-12-20 17:22:11 -0500945 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400946 }
947
948 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700949 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400950 Screen screen = new Screen();
951 screen.id = c.getLong(ID_INDEX);
952 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700953 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400954 }
955
956 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700957 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400958 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700959 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500960 ContentValues values = new ContentValues();
961 values.put(WorkspaceScreens._ID, screen.id);
962 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
963 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400964 }
965
Chris Wren22e130d2013-09-23 18:25:57 -0400966 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700967 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400968 Resource res = new Resource();
969 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -0700970 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -0400971 return res;
972 }
973
Chris Wrenfd13c712013-09-27 15:45:19 -0400974 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal96373642015-06-05 11:14:01 -0700975 private Widget packWidget(int dpi, ComponentName provider, UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -0800976 final LauncherAppWidgetProviderInfo info =
Robin Lee26ace122015-03-16 19:41:43 +0000977 LauncherModel.getProviderInfo(mContext, provider, user);
Chris Wrenfd13c712013-09-27 15:45:19 -0400978 Widget widget = new Widget();
979 widget.provider = provider.flattenToShortString();
980 widget.label = info.label;
981 widget.configure = info.configure != null;
982 if (info.icon != 0) {
983 widget.icon = new Resource();
Sunny Goyal96373642015-06-05 11:14:01 -0700984 Drawable fullResIcon = mIconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400985 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -0700986 widget.icon.data = Utilities.flattenBitmap(icon);
987 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400988 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700989
990 // Calculate the spans corresponding to any one of the orientations as it should not change
991 // based on orientation.
992 int[] minSpans = CellLayout.rectToCell(
993 mIdp.portraitProfile, mContext, info.minResizeWidth, info.minResizeHeight, null);
994 widget.minSpanX = (info.resizeMode & LauncherAppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0
995 ? minSpans[0] : -1;
996 widget.minSpanY = (info.resizeMode & LauncherAppWidgetProviderInfo.RESIZE_VERTICAL) != 0
997 ? minSpans[1] : -1;
998
Sunny Goyalef728d42014-10-22 11:28:28 -0700999 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001000 }
1001
Sunny Goyalef728d42014-10-22 11:28:28 -07001002 /**
1003 * Deserialize a proto after verifying checksum wrapper.
1004 */
1005 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001006 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001007 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1008 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1009 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001010 }
1011
Chris Wren1ada10d2013-09-13 18:01:38 -04001012 /**
1013 * Read the old journal from the input file.
1014 *
1015 * In the event of any error, just pretend we didn't have a journal,
1016 * in that case, do a full backup.
1017 *
1018 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001019 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001020 */
1021 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001022 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001023 if (oldState == null) {
1024 return journal;
1025 }
1026 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1027 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001028 int availableBytes = inStream.available();
1029 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1030 if (availableBytes < MAX_JOURNAL_SIZE) {
1031 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001032 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001033 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001034 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001035 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001036 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001037 // OMG what are you doing? This is crazy inefficient!
1038 // If we read a byte that is not ours, we will cause trouble: b/12491813
1039 // However, we don't know how many bytes to expect (oops).
1040 // So we have to step through *slowly*, watching for the end.
1041 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001042 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001043 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001044 bytesRead += result;
1045 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001046 Log.w(TAG, "unexpected end of file while reading journal.");
1047 // stop reading and see what there is to parse
1048 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001049 }
1050 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001051 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001052 availableBytes = 0;
1053 }
1054
1055 // check the buffer to see if we have a valid journal
1056 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001057 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001058 // if we are here, then we have read a valid, checksum-verified journal
1059 valid = true;
1060 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001061 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001062 } catch (InvalidProtocolBufferNanoException e) {
1063 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001064 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001065 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001066 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001067 }
Chris Wren92aa4232013-10-04 11:29:36 -04001068 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001069 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001070 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001071 }
1072 }
Chris Wren92aa4232013-10-04 11:29:36 -04001073 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001074 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001075 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001076 try {
1077 inStream.close();
1078 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001079 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001080 }
1081 }
1082 return journal;
1083 }
1084
Sunny Goyalef728d42014-10-22 11:28:28 -07001085 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1086 throws IOException {
1087 writeRowToBackup(keyToBackupKey(key), proto, data);
1088 }
1089
1090 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001091 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001092 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001093 data.writeEntityHeader(backupKey, blob.length);
1094 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001095 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001096 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001097 }
1098
Chris Wren1ada10d2013-09-13 18:01:38 -04001099 /**
1100 * Write the new journal to the output file.
1101 *
1102 * In the event of any error, just pretend we didn't have a journal,
1103 * in that case, do a full backup.
1104
1105 * @param newState the write-only file descriptor pointing to the new journal
1106 * @param journal a Journal protocol buffer
1107 */
1108 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1109 FileOutputStream outStream = null;
1110 try {
1111 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001112 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001113 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001114 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001115 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001116 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001117 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001118 }
1119 }
1120
1121 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1122 private byte[] writeCheckedBytes(MessageNano proto) {
1123 CheckedMessage wrapper = new CheckedMessage();
1124 wrapper.payload = MessageNano.toByteArray(proto);
1125 CRC32 checksum = new CRC32();
1126 checksum.update(wrapper.payload);
1127 wrapper.checksum = checksum.getValue();
1128 return MessageNano.toByteArray(wrapper);
1129 }
1130
1131 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001132 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001133 throws InvalidProtocolBufferNanoException {
1134 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001135 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001136 CRC32 checksum = new CRC32();
1137 checksum.update(wrapper.payload);
1138 if (wrapper.checksum != checksum.getValue()) {
1139 throw new InvalidProtocolBufferNanoException("checksum does not match");
1140 }
1141 return wrapper.payload;
1142 }
1143
Sunny Goyalef728d42014-10-22 11:28:28 -07001144 /**
1145 * @return true if the launcher is in a state to support backup
1146 */
Chris Wren71144262014-02-27 15:49:39 -05001147 private boolean launcherIsReady() {
1148 ContentResolver cr = mContext.getContentResolver();
1149 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1150 if (cursor == null) {
1151 // launcher data has been wiped, do nothing
1152 return false;
1153 }
1154 cursor.close();
1155
Adam Cohen2e6da152015-05-06 11:42:25 -07001156 if (LauncherAppState.getInstanceNoCreate() == null) {
Chris Wren71144262014-02-27 15:49:39 -05001157 // launcher services are unavailable, try again later
Chris Wren71144262014-02-27 15:49:39 -05001158 return false;
1159 }
1160
1161 return true;
1162 }
1163
Sunny Goyalffe83f12014-08-14 17:39:34 -07001164 private String getUserSelectionArg() {
1165 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1166 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1167 }
1168
Sunny Goyal316490e2015-06-02 09:38:28 -07001169 @Thunk class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001170
1171 private static final long serialVersionUID = 8931456637211665082L;
1172
Sunny Goyal316490e2015-06-02 09:38:28 -07001173 @Thunk InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001174 super(cause);
1175 }
1176
Sunny Goyal316490e2015-06-02 09:38:28 -07001177 @Thunk InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001178 super(reason);
1179 }
1180 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001181
1182 /**
1183 * A class to check if an activity can handle one of the intents from a list of
1184 * predefined intents.
1185 */
1186 private class ItemTypeMatcher {
1187
1188 private final ArrayList<Intent> mIntents;
1189
1190 ItemTypeMatcher(int xml_res) {
1191 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1192 }
1193
1194 private ArrayList<Intent> parseIntents(int xml_res) {
1195 ArrayList<Intent> intents = new ArrayList<Intent>();
1196 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1197 try {
1198 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1199 final int depth = parser.getDepth();
1200 int type;
1201 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1202 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1203 if (type != XmlPullParser.START_TAG) {
1204 continue;
1205 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1206 final String uri = DefaultLayoutParser.getAttributeValue(
1207 parser, DefaultLayoutParser.ATTR_URI);
1208 intents.add(Intent.parseUri(uri, 0));
1209 }
1210 }
1211 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1212 Log.e(TAG, "Unable to parse " + xml_res, e);
1213 } finally {
1214 parser.close();
1215 }
1216 return intents;
1217 }
1218
1219 public boolean matches(ActivityInfo activity, PackageManager pm) {
1220 for (Intent intent : mIntents) {
1221 intent.setPackage(activity.packageName);
1222 ResolveInfo info = pm.resolveActivity(intent, 0);
1223 if (info != null && (info.activityInfo.name.equals(activity.name)
1224 || info.activityInfo.name.equals(activity.targetActivity))) {
1225 return true;
1226 }
1227 }
1228 return false;
1229 }
1230 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001231}