blob: 2d11d3af1262338b493c08dd9754c086884656ff [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;
Sunny Goyale5bb7052015-07-27 14:36:07 -070035import android.graphics.Point;
Chris Wrenfd13c712013-09-27 15:45:19 -040036import android.graphics.drawable.Drawable;
Chris Wren1ada10d2013-09-13 18:01:38 -040037import android.os.ParcelFileDescriptor;
Chris Wren1ada10d2013-09-13 18:01:38 -040038import android.text.TextUtils;
39import android.util.Base64;
40import android.util.Log;
41
Sunny Goyalef728d42014-10-22 11:28:28 -070042import com.android.launcher3.LauncherSettings.Favorites;
43import com.android.launcher3.LauncherSettings.WorkspaceScreens;
44import com.android.launcher3.backup.BackupProtos;
45import com.android.launcher3.backup.BackupProtos.CheckedMessage;
Sunny Goyal33d44382014-10-16 09:24:19 -070046import com.android.launcher3.backup.BackupProtos.DeviceProfieData;
Sunny Goyalef728d42014-10-22 11:28:28 -070047import com.android.launcher3.backup.BackupProtos.Favorite;
48import com.android.launcher3.backup.BackupProtos.Journal;
49import com.android.launcher3.backup.BackupProtos.Key;
50import com.android.launcher3.backup.BackupProtos.Resource;
51import com.android.launcher3.backup.BackupProtos.Screen;
52import com.android.launcher3.backup.BackupProtos.Widget;
53import com.android.launcher3.compat.UserHandleCompat;
54import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal6579e1e2015-08-11 12:10:34 -070055import com.android.launcher3.model.MigrateFromRestoreTask;
Sunny Goyal316490e2015-06-02 09:38:28 -070056import com.android.launcher3.util.Thunk;
Sunny Goyalef728d42014-10-22 11:28:28 -070057import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
58import com.google.protobuf.nano.MessageNano;
59
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080060import org.xmlpull.v1.XmlPullParser;
61import org.xmlpull.v1.XmlPullParserException;
62
Chris Wren1ada10d2013-09-13 18:01:38 -040063import java.io.FileInputStream;
64import java.io.FileOutputStream;
65import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040066import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040067import java.util.ArrayList;
Sunny Goyalc0ee6752015-01-16 14:10:32 -080068import java.util.Arrays;
Chris Wren1ada10d2013-09-13 18:01:38 -040069import java.util.HashSet;
Chris Wren1ada10d2013-09-13 18:01:38 -040070import java.util.zip.CRC32;
71
72/**
73 * Persist the launcher home state across calamities.
74 */
Chris Wren92aa4232013-10-04 11:29:36 -040075public class LauncherBackupHelper implements BackupHelper {
Chris Wren92aa4232013-10-04 11:29:36 -040076 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050077 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
78 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren1ada10d2013-09-13 18:01:38 -040079
Sunny Goyal107ea632015-07-20 12:59:39 -070080 private static final int BACKUP_VERSION = 4;
Chris Wren1ada10d2013-09-13 18:01:38 -040081 private static final int MAX_JOURNAL_SIZE = 1000000;
82
Sunny Goyal33d44382014-10-16 09:24:19 -070083 // Journal key is such that it is always smaller than any dynamically generated
84 // key (any Base64 encoded string).
85 private static final String JOURNAL_KEY = "#";
86
Chris Wrenfd13c712013-09-27 15:45:19 -040087 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040088 private static final int MAX_ICONS_PER_PASS = 10;
89
Chris Wrenfd13c712013-09-27 15:45:19 -040090 /** widgets contain previews, which are very large, dribble them out */
91 private static final int MAX_WIDGETS_PER_PASS = 5;
92
Chris Wren1ada10d2013-09-13 18:01:38 -040093 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070094 Favorites._ID, // 0
95 Favorites.MODIFIED, // 1
96 Favorites.INTENT, // 2
97 Favorites.APPWIDGET_PROVIDER, // 3
98 Favorites.APPWIDGET_ID, // 4
99 Favorites.CELLX, // 5
100 Favorites.CELLY, // 6
101 Favorites.CONTAINER, // 7
102 Favorites.ICON, // 8
103 Favorites.ICON_PACKAGE, // 9
104 Favorites.ICON_RESOURCE, // 10
105 Favorites.ICON_TYPE, // 11
106 Favorites.ITEM_TYPE, // 12
107 Favorites.SCREEN, // 13
108 Favorites.SPANX, // 14
109 Favorites.SPANY, // 15
110 Favorites.TITLE, // 16
111 Favorites.PROFILE_ID, // 17
Sunny Goyal107ea632015-07-20 12:59:39 -0700112 Favorites.RANK, // 18
Chris Wren1ada10d2013-09-13 18:01:38 -0400113 };
114
115 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400116 private static final int ID_MODIFIED = 1;
117 private static final int INTENT_INDEX = 2;
118 private static final int APPWIDGET_PROVIDER_INDEX = 3;
119 private static final int APPWIDGET_ID_INDEX = 4;
120 private static final int CELLX_INDEX = 5;
121 private static final int CELLY_INDEX = 6;
122 private static final int CONTAINER_INDEX = 7;
123 private static final int ICON_INDEX = 8;
124 private static final int ICON_PACKAGE_INDEX = 9;
125 private static final int ICON_RESOURCE_INDEX = 10;
126 private static final int ICON_TYPE_INDEX = 11;
127 private static final int ITEM_TYPE_INDEX = 12;
128 private static final int SCREEN_INDEX = 13;
129 private static final int SPANX_INDEX = 14;
130 private static final int SPANY_INDEX = 15;
131 private static final int TITLE_INDEX = 16;
Sunny Goyal107ea632015-07-20 12:59:39 -0700132 private static final int RANK_INDEX = 18;
Chris Wren1ada10d2013-09-13 18:01:38 -0400133
134 private static final String[] SCREEN_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -0700135 WorkspaceScreens._ID, // 0
136 WorkspaceScreens.MODIFIED, // 1
137 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400138 };
139
Chris Wren22e130d2013-09-23 18:25:57 -0400140 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400141
Sunny Goyal316490e2015-06-02 09:38:28 -0700142 @Thunk final Context mContext;
Sunny Goyalef728d42014-10-22 11:28:28 -0700143 private final HashSet<String> mExistingKeys;
Sunny Goyal42de82f2014-09-26 22:09:29 -0700144 private final ArrayList<Key> mKeys;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800145 private final ItemTypeMatcher[] mItemTypeMatchers;
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800146 private final long mUserSerial;
Chris Wren1ada10d2013-09-13 18:01:38 -0400147
Sunny Goyalef728d42014-10-22 11:28:28 -0700148 private BackupManager mBackupManager;
Sunny Goyalef728d42014-10-22 11:28:28 -0700149 private byte[] mBuffer = new byte[512];
150 private long mLastBackupRestoreTime;
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800151 private boolean mBackupDataWasUpdated;
Sunny Goyalef728d42014-10-22 11:28:28 -0700152
Adam Cohen2e6da152015-05-06 11:42:25 -0700153 private IconCache mIconCache;
154 private DeviceProfieData mDeviceProfileData;
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700155 private InvariantDeviceProfile mIdp;
Adam Cohen2e6da152015-05-06 11:42:25 -0700156
Sunny Goyale5bb7052015-07-27 14:36:07 -0700157 DeviceProfieData migrationCompatibleProfileData;
158 HashSet<String> widgetSizes = new HashSet<>();
159
Sunny Goyal33d44382014-10-16 09:24:19 -0700160 boolean restoreSuccessful;
Sunny Goyal08f72612015-01-05 13:41:43 -0800161 int restoredBackupVersion = 1;
Sunny Goyal33d44382014-10-16 09:24:19 -0700162
Sunny Goyalc115e642015-07-20 14:23:43 -0700163 // When migrating from a device which different hotseat configuration, the icons are shifted
164 // to center along the new all-apps icon.
165 private int mHotseatShift = 0;
166
Sunny Goyal33d44382014-10-16 09:24:19 -0700167 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400168 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700169 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700170 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700171 restoreSuccessful = true;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800172 mItemTypeMatchers = new ItemTypeMatcher[CommonAppTypeParser.SUPPORTED_TYPE_COUNT];
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800173
174 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
175 mUserSerial = userManager.getSerialNumberForUser(UserHandleCompat.myUserHandle());
Chris Wren92aa4232013-10-04 11:29:36 -0400176 }
177
178 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700179 if (mBackupManager == null) {
180 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400181 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700182 mBackupManager.dataChanged();
183 }
184
185 private void applyJournal(Journal journal) {
186 mLastBackupRestoreTime = journal.t;
187 mExistingKeys.clear();
188 if (journal.key != null) {
189 for (Key key : journal.key) {
190 mExistingKeys.add(keyToBackupKey(key));
191 }
192 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700193 restoredBackupVersion = journal.backupVersion;
Chris Wren1ada10d2013-09-13 18:01:38 -0400194 }
195
196 /**
197 * Back up launcher data so we can restore the user's state on a new device.
198 *
199 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
200 *
201 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
202 *
203 * @param oldState notes from the last backup
204 * @param data incremental key/value pairs to persist off-device
205 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400206 */
207 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400208 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
209 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500210 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400211
212 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700213 if (!launcherIsReady()) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700214 dataChanged();
Sunny Goyalef728d42014-10-22 11:28:28 -0700215 // Perform backup later.
216 writeJournal(newState, in);
217 return;
218 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700219
Sunny Goyal96373642015-06-05 11:14:01 -0700220 if (mDeviceProfileData == null) {
221 LauncherAppState app = LauncherAppState.getInstance();
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700222 mIdp = app.getInvariantDeviceProfile();
223 mDeviceProfileData = initDeviceProfileData(mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700224 mIconCache = app.getIconCache();
225 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700226
Sunny Goyalef728d42014-10-22 11:28:28 -0700227 Log.v(TAG, "lastBackupTime = " + in.t);
228 mKeys.clear();
229 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400230
Sunny Goyalef728d42014-10-22 11:28:28 -0700231 // Record the time before performing backup so that entries edited while the backup
232 // was going on, do not get missed in next backup.
233 long newBackupTime = System.currentTimeMillis();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800234 mBackupDataWasUpdated = false;
Sunny Goyalef728d42014-10-22 11:28:28 -0700235 try {
236 backupFavorites(data);
237 backupScreens(data);
238 backupIcons(data);
239 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400240
Sunny Goyalef728d42014-10-22 11:28:28 -0700241 // Delete any key which still exist in the old backup, but is not valid anymore.
242 HashSet<String> validKeys = new HashSet<String>();
243 for (Key key : mKeys) {
244 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500245 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700246 mExistingKeys.removeAll(validKeys);
247
248 // Delete anything left in the existing keys.
249 for (String deleted: mExistingKeys) {
250 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
251 data.writeEntityHeader(deleted, -1);
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800252 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -0700253 }
254
255 mExistingKeys.clear();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800256 if (!mBackupDataWasUpdated) {
257 // Check if any metadata has changed
258 mBackupDataWasUpdated = (in.profile == null)
259 || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
Sunny Goyal96373642015-06-05 11:14:01 -0700260 DeviceProfieData.toByteArray(mDeviceProfileData))
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800261 || (in.backupVersion != BACKUP_VERSION)
262 || (in.appVersion != getAppVersion());
263 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700264
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800265 if (mBackupDataWasUpdated) {
266 mLastBackupRestoreTime = newBackupTime;
267
268 // We store the journal at two places.
269 // 1) Storing it in newState allows us to do partial backups by comparing old state
270 // 2) Storing it in backup data allows us to validate keys during restore
271 Journal state = getCurrentStateJournal();
272 writeRowToBackup(JOURNAL_KEY, state, data);
273 } else {
274 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
275 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700276 } catch (IOException e) {
277 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400278 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400279
Sunny Goyalef728d42014-10-22 11:28:28 -0700280 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400281 }
282
283 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700284 * @return true if the backup corresponding to oldstate can be successfully applied
285 * to this device.
286 */
287 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal96373642015-06-05 11:14:01 -0700288 DeviceProfieData currentProfile = mDeviceProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700289 DeviceProfieData oldProfile = oldState.profile;
290
291 if (oldProfile == null || oldProfile.desktopCols == 0) {
292 // Profile info is not valid, ignore the check.
293 return true;
294 }
295
Sunny Goyale5bb7052015-07-27 14:36:07 -0700296 boolean isHotseatCompatible = false;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700297 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
Sunny Goyale5bb7052015-07-27 14:36:07 -0700298 isHotseatCompatible = true;
Sunny Goyalc115e642015-07-20 14:23:43 -0700299 mHotseatShift = 0;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700300 }
Sunny Goyalc115e642015-07-20 14:23:43 -0700301
302 if ((currentProfile.allappsRank >= oldProfile.allappsRank)
303 && ((currentProfile.hotseatCount - currentProfile.allappsRank) >=
304 (oldProfile.hotseatCount - oldProfile.allappsRank))) {
305 // There is enough space on both sides of the hotseat.
Sunny Goyale5bb7052015-07-27 14:36:07 -0700306 isHotseatCompatible = true;
Sunny Goyalc115e642015-07-20 14:23:43 -0700307 mHotseatShift = currentProfile.allappsRank - oldProfile.allappsRank;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700308 }
309
Sunny Goyale5bb7052015-07-27 14:36:07 -0700310 if (!isHotseatCompatible) {
311 return false;
312 }
313 if ((currentProfile.desktopCols >= oldProfile.desktopCols)
314 && (currentProfile.desktopRows >= oldProfile.desktopRows)) {
315 return true;
316 }
317
Sunny Goyal6579e1e2015-08-11 12:10:34 -0700318 if (MigrateFromRestoreTask.ENABLED &&
319 (oldProfile.desktopCols - currentProfile.desktopCols <= 1) &&
Sunny Goyale5bb7052015-07-27 14:36:07 -0700320 (oldProfile.desktopRows - currentProfile.desktopRows <= 1)) {
321 // Allow desktop migration when row and/or column count contracts by 1.
322
323 migrationCompatibleProfileData = initDeviceProfileData(mIdp);
324 migrationCompatibleProfileData.desktopCols = oldProfile.desktopCols;
325 migrationCompatibleProfileData.desktopRows = oldProfile.desktopRows;
326 return true;
327 }
328 return false;
Sunny Goyal33d44382014-10-16 09:24:19 -0700329 }
330
331 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400332 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700333 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
334 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400335 *
Chris Wren92aa4232013-10-04 11:29:36 -0400336 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400337 */
338 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400339 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700340 if (!restoreSuccessful) {
341 return;
342 }
Sunny Goyal96373642015-06-05 11:14:01 -0700343
344 if (mDeviceProfileData == null) {
345 // This call does not happen on a looper thread. So LauncherAppState
346 // can't be created . Instead initialize required dependencies directly.
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700347 mIdp = new InvariantDeviceProfile(mContext);
348 mDeviceProfileData = initDeviceProfileData(mIdp);
349 mIconCache = new IconCache(mContext, mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700350 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700351
Sunny Goyalef728d42014-10-22 11:28:28 -0700352 int dataSize = data.size();
353 if (mBuffer.length < dataSize) {
354 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400355 }
356 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700357 int bytesRead = data.read(mBuffer, 0, dataSize);
358 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
359 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700360
361 if (JOURNAL_KEY.equals(backupKey)) {
362 if (VERBOSE) Log.v(TAG, "Journal entry restored");
363 if (!mKeys.isEmpty()) {
364 // We received the journal key after a restore key.
365 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
366 restoreSuccessful = false;
367 return;
368 }
369
370 Journal journal = new Journal();
371 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
372 applyJournal(journal);
373 restoreSuccessful = isBackupCompatible(journal);
374 return;
375 }
376
377 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
378 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
379 return;
380 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700381 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500382 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400383 switch (key.type) {
384 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700385 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400386 break;
387
388 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700389 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400390 break;
391
392 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700393 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400394 break;
395
396 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700397 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400398 break;
399
400 default:
401 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700402 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400403 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400404 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700405 } catch (IOException e) {
406 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400407 }
Chris Wren92aa4232013-10-04 11:29:36 -0400408 }
409
410 /**
411 * Record the restore state for the next backup.
412 *
413 * @param newState notes about the backup state after restore.
414 */
415 @Override
416 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700417 writeJournal(newState, getCurrentStateJournal());
418 }
419
420 private Journal getCurrentStateJournal() {
421 Journal journal = new Journal();
422 journal.t = mLastBackupRestoreTime;
423 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
424 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700425 journal.backupVersion = BACKUP_VERSION;
Sunny Goyal96373642015-06-05 11:14:01 -0700426 journal.profile = mDeviceProfileData;
Sunny Goyalef728d42014-10-22 11:28:28 -0700427 return journal;
428 }
429
430 private int getAppVersion() {
431 try {
432 return mContext.getPackageManager()
433 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
434 } catch (NameNotFoundException e) {
435 return 0;
436 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400437 }
438
Adam Cohen2e6da152015-05-06 11:42:25 -0700439 private DeviceProfieData initDeviceProfileData(InvariantDeviceProfile profile) {
440 DeviceProfieData data = new DeviceProfieData();
441 data.desktopRows = profile.numRows;
442 data.desktopCols = profile.numColumns;
443 data.hotseatCount = profile.numHotseatIcons;
444 data.allappsRank = profile.hotseatAllAppsRank;
445 return data;
Sunny Goyal33d44382014-10-16 09:24:19 -0700446 }
447
448 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400449 * Write all modified favorites to the data stream.
450 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400451 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400452 * @throws IOException
453 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700454 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400455 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400456 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700457 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400458 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700459 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400460 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400461 cursor.moveToPosition(-1);
462 while(cursor.moveToNext()) {
463 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700464 final long updateTime = cursor.getLong(ID_MODIFIED);
465 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700466 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700467 final String backupKey = keyToBackupKey(key);
Sunny Goyal107ea632015-07-20 12:59:39 -0700468
469 // Favorite proto changed in v4. Backup again if the version is old.
470 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime
471 || restoredBackupVersion < 4) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700472 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500473 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700474 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400475 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400476 }
477 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400478 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400480 }
481
482 /**
483 * Read a favorite from the stream.
484 *
485 * <P>Keys arrive in any order, so screens and containers may not exist yet.
486 *
487 * @param key identifier for the row
488 * @param buffer the serialized proto from the stream, may be larger than dataSize
489 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400490 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700491 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500492 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400493 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
494 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
495
Sunny Goyalef728d42014-10-22 11:28:28 -0700496 ContentResolver cr = mContext.getContentResolver();
497 ContentValues values = unpackFavorite(buffer, dataSize);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700498 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400499 }
500
501 /**
502 * Write all modified screens to the data stream.
503 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400504 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400505 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400506 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700507 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400508 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400509 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400510 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
511 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400512 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400513 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700514 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400515 while(cursor.moveToNext()) {
516 final long id = cursor.getLong(ID_INDEX);
517 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400518 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700519 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500520 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700521 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
522 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500523 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700524 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400525 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400526 }
527 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400528 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400529 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400530 }
531
532 /**
533 * Read a screen from the stream.
534 *
535 * <P>Keys arrive in any order, so children of this screen may already exist.
536 *
537 * @param key identifier for the row
538 * @param buffer the serialized proto from the stream, may be larger than dataSize
539 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400540 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700541 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500542 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400543 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
544 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500545
Sunny Goyalef728d42014-10-22 11:28:28 -0700546 ContentResolver cr = mContext.getContentResolver();
547 ContentValues values = unpackScreen(buffer, dataSize);
548 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400549 }
550
Chris Wren22e130d2013-09-23 18:25:57 -0400551 /**
552 * Write all the static icon resources we need to render placeholders
553 * for a package that is not installed.
554 *
Chris Wren22e130d2013-09-23 18:25:57 -0400555 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400556 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700557 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400558 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400559 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400560 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700561 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700562 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400563
Kenny Guyed131872014-04-30 03:02:21 +0100564 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100565 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100566 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700567 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400568 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
569 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400570 try {
571 cursor.moveToPosition(-1);
572 while(cursor.moveToNext()) {
573 final long id = cursor.getLong(ID_INDEX);
574 final String intentDescription = cursor.getString(INTENT_INDEX);
575 try {
576 Intent intent = Intent.parseUri(intentDescription, 0);
577 ComponentName cn = intent.getComponent();
578 Key key = null;
579 String backupKey = null;
580 if (cn != null) {
581 key = getKey(Key.ICON, cn.flattenToShortString());
582 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400583 } else {
584 Log.w(TAG, "empty intent on application favorite: " + id);
585 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700586 if (mExistingKeys.contains(backupKey)) {
587 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400588
589 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700590 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400591 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700592 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
593 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
594 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100595 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100596 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700597 writeRowToBackup(key, packIcon(dpi, icon), data);
598 mKeys.add(key);
599 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400600 }
601 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700602 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400603 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400604 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400605 }
606 }
607 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500608 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400609 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500610 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400611 }
612
613 }
614 } finally {
615 cursor.close();
616 }
Chris Wren22e130d2013-09-23 18:25:57 -0400617 }
618
619 /**
620 * Read an icon from the stream.
621 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400622 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400623 *
624 * @param key identifier for the row
625 * @param buffer the serialized proto from the stream, may be larger than dataSize
626 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400627 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700628 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500629 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400630 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
631 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500632
Sunny Goyalef728d42014-10-22 11:28:28 -0700633 Resource res = unpackProto(new Resource(), buffer, dataSize);
634 if (DEBUG) {
635 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400636 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700637 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
638 if (icon == null) {
639 Log.w(TAG, "failed to unpack icon for " + key.name);
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700640 } else {
641 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
642 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
643 "" /* label */, mUserSerial, mIdp);
Sunny Goyalef728d42014-10-22 11:28:28 -0700644 }
Chris Wren22e130d2013-09-23 18:25:57 -0400645 }
646
Chris Wrenfd13c712013-09-27 15:45:19 -0400647 /**
648 * Write all the static widget resources we need to render placeholders
649 * for a package that is not installed.
650 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400651 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400652 * @throws IOException
653 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700654 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400655 // persist static widget info that hasn't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400656 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400657 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalef728d42014-10-22 11:28:28 -0700658 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400659
Sunny Goyalffe83f12014-08-14 17:39:34 -0700660 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
661 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400662 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
663 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400664 try {
665 cursor.moveToPosition(-1);
666 while(cursor.moveToNext()) {
667 final long id = cursor.getLong(ID_INDEX);
668 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
Chris Wrenfd13c712013-09-27 15:45:19 -0400669 final ComponentName provider = ComponentName.unflattenFromString(providerName);
670 Key key = null;
671 String backupKey = null;
672 if (provider != null) {
673 key = getKey(Key.WIDGET, providerName);
674 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400675 } else {
676 Log.w(TAG, "empty intent on appwidget: " + id);
677 }
Sunny Goyal107ea632015-07-20 12:59:39 -0700678
679 // Widget backup proto changed in v3. So add it again if the original backup is old.
680 if (mExistingKeys.contains(backupKey) && restoredBackupVersion >= 3) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700681 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400682
683 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700684 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400685 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700686 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
687 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
688 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Robin Lee26ace122015-03-16 19:41:43 +0000689 UserHandleCompat user = UserHandleCompat.myUserHandle();
Sunny Goyal96373642015-06-05 11:14:01 -0700690 writeRowToBackup(key, packWidget(dpi, provider, user), data);
Sunny Goyalef728d42014-10-22 11:28:28 -0700691 mKeys.add(key);
692 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400693 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700694 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400695 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400696 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400697 }
698 }
699 }
700 } finally {
701 cursor.close();
702 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400703 }
704
705 /**
706 * Read a widget from the stream.
707 *
708 * <P>Keys arrive in any order, so widgets that use this data may already exist.
709 *
710 * @param key identifier for the row
711 * @param buffer the serialized proto from the stream, may be larger than dataSize
712 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400713 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700714 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500715 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400716 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
717 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700718 Widget widget = unpackProto(new Widget(), buffer, dataSize);
719 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
720 if (widget.icon.data != null) {
721 Bitmap icon = BitmapFactory
722 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
723 if (icon == null) {
724 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500725 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800726 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700727 icon, widget.icon.dpi, widget.label, mUserSerial, mIdp);
Chris Wren5dee7af2013-12-20 17:22:11 -0500728 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400729 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700730
Sunny Goyale5bb7052015-07-27 14:36:07 -0700731 // Cache widget min sizes incase migration is required.
732 widgetSizes.add(widget.provider + "#" + widget.minSpanX + "," + widget.minSpanY);
Chris Wrenfd13c712013-09-27 15:45:19 -0400733 }
734
Chris Wren22e130d2013-09-23 18:25:57 -0400735 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400736 *
737 * <P> Keys contain their own checksum instead of using
738 * the heavy-weight CheckedMessage wrapper.
739 */
740 private Key getKey(int type, long id) {
741 Key key = new Key();
742 key.type = type;
743 key.id = id;
744 key.checksum = checkKey(key);
745 return key;
746 }
747
Chris Wren22e130d2013-09-23 18:25:57 -0400748 /** create a new key for a named object.
749 *
750 * <P> Keys contain their own checksum instead of using
751 * the heavy-weight CheckedMessage wrapper.
752 */
753 private Key getKey(int type, String name) {
754 Key key = new Key();
755 key.type = type;
756 key.name = name;
757 key.checksum = checkKey(key);
758 return key;
759 }
760
Chris Wren1ada10d2013-09-13 18:01:38 -0400761 /** keys need to be strings, serialize and encode. */
762 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400763 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400764 }
765
766 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700767 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400768 try {
769 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
770 if (key.checksum != checkKey(key)) {
771 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700772 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400773 }
774 return key;
775 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700776 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400777 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700778 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400779 }
780 }
781
782 /** Compute the checksum over the important bits of a key. */
783 private long checkKey(Key key) {
784 CRC32 checksum = new CRC32();
785 checksum.update(key.type);
786 checksum.update((int) (key.id & 0xffff));
787 checksum.update((int) ((key.id >> 32) & 0xffff));
788 if (!TextUtils.isEmpty(key.name)) {
789 checksum.update(key.name.getBytes());
790 }
791 return checksum.getValue();
792 }
793
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800794 /**
795 * @return true if its an hotseat item, that can be replaced during restore.
796 * TODO: Extend check for folders in hotseat.
797 */
798 private boolean isReplaceableHotseatItem(Favorite favorite) {
799 return favorite.container == Favorites.CONTAINER_HOTSEAT
800 && favorite.intent != null
801 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
802 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
803 }
804
Chris Wren1ada10d2013-09-13 18:01:38 -0400805 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700806 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400807 Favorite favorite = new Favorite();
808 favorite.id = c.getLong(ID_INDEX);
809 favorite.screen = c.getInt(SCREEN_INDEX);
810 favorite.container = c.getInt(CONTAINER_INDEX);
811 favorite.cellX = c.getInt(CELLX_INDEX);
812 favorite.cellY = c.getInt(CELLY_INDEX);
813 favorite.spanX = c.getInt(SPANX_INDEX);
814 favorite.spanY = c.getInt(SPANY_INDEX);
815 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
Sunny Goyal107ea632015-07-20 12:59:39 -0700816 favorite.rank = c.getInt(RANK_INDEX);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700817
Chris Wren1ada10d2013-09-13 18:01:38 -0400818 String title = c.getString(TITLE_INDEX);
819 if (!TextUtils.isEmpty(title)) {
820 favorite.title = title;
821 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100822 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800823 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100824 if (!TextUtils.isEmpty(intentDescription)) {
825 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800826 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100827 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
828 favorite.intent = intent.toUri(0);
829 } catch (URISyntaxException e) {
830 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700831 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400832 }
833 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
834 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
835 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
836 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
837 if (!TextUtils.isEmpty(appWidgetProvider)) {
838 favorite.appWidgetProvider = appWidgetProvider;
839 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700840 } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
841 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
842 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
843 if (!TextUtils.isEmpty(iconPackage)) {
844 favorite.iconPackage = iconPackage;
845 }
846 String iconResource = c.getString(ICON_RESOURCE_INDEX);
847 if (!TextUtils.isEmpty(iconResource)) {
848 favorite.iconResource = iconResource;
849 }
850 }
851
852 byte[] blob = c.getBlob(ICON_INDEX);
853 if (blob != null && blob.length > 0) {
854 favorite.icon = blob;
855 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400856 }
857
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800858 if (isReplaceableHotseatItem(favorite)) {
859 if (intent != null && intent.getComponent() != null) {
860 PackageManager pm = mContext.getPackageManager();
861 ActivityInfo activity = null;;
862 try {
863 activity = pm.getActivityInfo(intent.getComponent(), 0);
864 } catch (NameNotFoundException e) {
865 Log.e(TAG, "Target not found", e);
866 }
867 if (activity == null) {
868 return favorite;
869 }
870 for (int i = 0; i < mItemTypeMatchers.length; i++) {
871 if (mItemTypeMatchers[i] == null) {
872 mItemTypeMatchers[i] = new ItemTypeMatcher(
873 CommonAppTypeParser.getResourceForItemType(i));
874 }
875 if (mItemTypeMatchers[i].matches(activity, pm)) {
876 favorite.targetType = i;
877 break;
878 }
879 }
880 }
881 }
882
Sunny Goyalef728d42014-10-22 11:28:28 -0700883 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400884 }
885
886 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700887 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700888 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700889 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800890
Sunny Goyalc115e642015-07-20 14:23:43 -0700891 // If it is a hotseat item, move it accordingly.
892 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
893 favorite.screen += mHotseatShift;
894 }
895
Chris Wren5dee7af2013-12-20 17:22:11 -0500896 ContentValues values = new ContentValues();
897 values.put(Favorites._ID, favorite.id);
898 values.put(Favorites.SCREEN, favorite.screen);
899 values.put(Favorites.CONTAINER, favorite.container);
900 values.put(Favorites.CELLX, favorite.cellX);
901 values.put(Favorites.CELLY, favorite.cellY);
902 values.put(Favorites.SPANX, favorite.spanX);
903 values.put(Favorites.SPANY, favorite.spanY);
Sunny Goyal107ea632015-07-20 12:59:39 -0700904 values.put(Favorites.RANK, favorite.rank);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700905
906 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
907 values.put(Favorites.ICON_TYPE, favorite.iconType);
908 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
909 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
910 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
911 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500912 values.put(Favorites.ICON, favorite.icon);
913 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700914
Chris Wren5dee7af2013-12-20 17:22:11 -0500915 if (!TextUtils.isEmpty(favorite.title)) {
916 values.put(Favorites.TITLE, favorite.title);
917 } else {
918 values.put(Favorites.TITLE, "");
919 }
920 if (!TextUtils.isEmpty(favorite.intent)) {
921 values.put(Favorites.INTENT, favorite.intent);
922 }
923 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500924
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100925 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
926 long userSerialNumber =
927 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
928 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
929
Sunny Goyale5bb7052015-07-27 14:36:07 -0700930 // If we will attempt grid resize, use the original profile to validate grid size, as
931 // anything which fits in the original grid should fit in the current grid after
932 // grid migration.
933 DeviceProfieData currentProfile = migrationCompatibleProfileData == null
934 ? mDeviceProfileData : migrationCompatibleProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700935
Sunny Goyalff572272014-07-23 13:58:07 -0700936 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
937 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
938 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
939 }
940 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
941 values.put(LauncherSettings.Favorites.RESTORED,
942 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
943 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
944 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700945
946 // Verify placement
947 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
948 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
949 restoreSuccessful = false;
950 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
951 }
Sunny Goyalff572272014-07-23 13:58:07 -0700952 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800953 // Check if it is an hotseat item, that can be replaced.
954 if (isReplaceableHotseatItem(favorite)
955 && favorite.targetType != Favorite.TARGET_NONE
956 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
957 Log.e(TAG, "Added item type flag");
958 values.put(LauncherSettings.Favorites.RESTORED,
959 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
960 } else {
961 // Let LauncherModel know we've been here.
962 values.put(LauncherSettings.Favorites.RESTORED, 1);
963 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700964
965 // Verify placement
966 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
967 if ((favorite.screen >= currentProfile.hotseatCount)
968 || (favorite.screen == currentProfile.allappsRank)) {
969 restoreSuccessful = false;
970 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
971 }
972 } else {
973 if ((favorite.cellX >= currentProfile.desktopCols)
974 || (favorite.cellY >= currentProfile.desktopRows)) {
975 restoreSuccessful = false;
976 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
977 }
978 }
Sunny Goyalff572272014-07-23 13:58:07 -0700979 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500980
Chris Wren5dee7af2013-12-20 17:22:11 -0500981 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400982 }
983
984 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700985 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400986 Screen screen = new Screen();
987 screen.id = c.getLong(ID_INDEX);
988 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700989 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400990 }
991
992 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700993 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400994 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700995 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500996 ContentValues values = new ContentValues();
997 values.put(WorkspaceScreens._ID, screen.id);
998 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
999 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -04001000 }
1001
Chris Wren22e130d2013-09-23 18:25:57 -04001002 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001003 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -04001004 Resource res = new Resource();
1005 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -07001006 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -04001007 return res;
1008 }
1009
Chris Wrenfd13c712013-09-27 15:45:19 -04001010 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal96373642015-06-05 11:14:01 -07001011 private Widget packWidget(int dpi, ComponentName provider, UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08001012 final LauncherAppWidgetProviderInfo info =
Robin Lee26ace122015-03-16 19:41:43 +00001013 LauncherModel.getProviderInfo(mContext, provider, user);
Chris Wrenfd13c712013-09-27 15:45:19 -04001014 Widget widget = new Widget();
1015 widget.provider = provider.flattenToShortString();
1016 widget.label = info.label;
1017 widget.configure = info.configure != null;
1018 if (info.icon != 0) {
1019 widget.icon = new Resource();
Sunny Goyal96373642015-06-05 11:14:01 -07001020 Drawable fullResIcon = mIconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -04001021 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -07001022 widget.icon.data = Utilities.flattenBitmap(icon);
1023 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -04001024 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001025
Sunny Goyale5bb7052015-07-27 14:36:07 -07001026 Point spans = info.getMinSpans(mIdp, mContext);
1027 widget.minSpanX = spans.x;
1028 widget.minSpanY = spans.y;
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001029
Sunny Goyalef728d42014-10-22 11:28:28 -07001030 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001031 }
1032
Sunny Goyalef728d42014-10-22 11:28:28 -07001033 /**
1034 * Deserialize a proto after verifying checksum wrapper.
1035 */
1036 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001037 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001038 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1039 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1040 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001041 }
1042
Chris Wren1ada10d2013-09-13 18:01:38 -04001043 /**
1044 * Read the old journal from the input file.
1045 *
1046 * In the event of any error, just pretend we didn't have a journal,
1047 * in that case, do a full backup.
1048 *
1049 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001050 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001051 */
1052 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001053 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001054 if (oldState == null) {
1055 return journal;
1056 }
1057 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1058 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001059 int availableBytes = inStream.available();
1060 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1061 if (availableBytes < MAX_JOURNAL_SIZE) {
1062 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001063 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001064 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001065 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001066 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001067 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001068 // OMG what are you doing? This is crazy inefficient!
1069 // If we read a byte that is not ours, we will cause trouble: b/12491813
1070 // However, we don't know how many bytes to expect (oops).
1071 // So we have to step through *slowly*, watching for the end.
1072 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001073 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001074 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001075 bytesRead += result;
1076 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001077 Log.w(TAG, "unexpected end of file while reading journal.");
1078 // stop reading and see what there is to parse
1079 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001080 }
1081 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001082 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001083 availableBytes = 0;
1084 }
1085
1086 // check the buffer to see if we have a valid journal
1087 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001088 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001089 // if we are here, then we have read a valid, checksum-verified journal
1090 valid = true;
1091 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001092 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001093 } catch (InvalidProtocolBufferNanoException e) {
1094 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001095 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001096 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001097 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001098 }
Chris Wren92aa4232013-10-04 11:29:36 -04001099 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001100 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001101 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001102 }
1103 }
Chris Wren92aa4232013-10-04 11:29:36 -04001104 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001105 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001106 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001107 try {
1108 inStream.close();
1109 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001110 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001111 }
1112 }
1113 return journal;
1114 }
1115
Sunny Goyalef728d42014-10-22 11:28:28 -07001116 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1117 throws IOException {
1118 writeRowToBackup(keyToBackupKey(key), proto, data);
1119 }
1120
1121 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001122 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001123 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001124 data.writeEntityHeader(backupKey, blob.length);
1125 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001126 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001127 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001128 }
1129
Chris Wren1ada10d2013-09-13 18:01:38 -04001130 /**
1131 * Write the new journal to the output file.
1132 *
1133 * In the event of any error, just pretend we didn't have a journal,
1134 * in that case, do a full backup.
1135
1136 * @param newState the write-only file descriptor pointing to the new journal
1137 * @param journal a Journal protocol buffer
1138 */
1139 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1140 FileOutputStream outStream = null;
1141 try {
1142 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001143 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001144 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001145 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001146 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001147 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001148 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001149 }
1150 }
1151
1152 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1153 private byte[] writeCheckedBytes(MessageNano proto) {
1154 CheckedMessage wrapper = new CheckedMessage();
1155 wrapper.payload = MessageNano.toByteArray(proto);
1156 CRC32 checksum = new CRC32();
1157 checksum.update(wrapper.payload);
1158 wrapper.checksum = checksum.getValue();
1159 return MessageNano.toByteArray(wrapper);
1160 }
1161
1162 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001163 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001164 throws InvalidProtocolBufferNanoException {
1165 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001166 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001167 CRC32 checksum = new CRC32();
1168 checksum.update(wrapper.payload);
1169 if (wrapper.checksum != checksum.getValue()) {
1170 throw new InvalidProtocolBufferNanoException("checksum does not match");
1171 }
1172 return wrapper.payload;
1173 }
1174
Sunny Goyalef728d42014-10-22 11:28:28 -07001175 /**
1176 * @return true if the launcher is in a state to support backup
1177 */
Chris Wren71144262014-02-27 15:49:39 -05001178 private boolean launcherIsReady() {
1179 ContentResolver cr = mContext.getContentResolver();
1180 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1181 if (cursor == null) {
1182 // launcher data has been wiped, do nothing
1183 return false;
1184 }
1185 cursor.close();
1186
Adam Cohen2e6da152015-05-06 11:42:25 -07001187 if (LauncherAppState.getInstanceNoCreate() == null) {
Chris Wren71144262014-02-27 15:49:39 -05001188 // launcher services are unavailable, try again later
Chris Wren71144262014-02-27 15:49:39 -05001189 return false;
1190 }
1191
1192 return true;
1193 }
1194
Sunny Goyalffe83f12014-08-14 17:39:34 -07001195 private String getUserSelectionArg() {
1196 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1197 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1198 }
1199
Sunny Goyal316490e2015-06-02 09:38:28 -07001200 @Thunk class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001201
1202 private static final long serialVersionUID = 8931456637211665082L;
1203
Sunny Goyal316490e2015-06-02 09:38:28 -07001204 @Thunk InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001205 super(cause);
1206 }
1207
Sunny Goyal316490e2015-06-02 09:38:28 -07001208 @Thunk InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001209 super(reason);
1210 }
1211 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001212
Sunny Goyale5bb7052015-07-27 14:36:07 -07001213 public boolean shouldAttemptWorkspaceMigration() {
1214 return migrationCompatibleProfileData != null;
1215 }
1216
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001217 /**
1218 * A class to check if an activity can handle one of the intents from a list of
1219 * predefined intents.
1220 */
1221 private class ItemTypeMatcher {
1222
1223 private final ArrayList<Intent> mIntents;
1224
1225 ItemTypeMatcher(int xml_res) {
1226 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1227 }
1228
1229 private ArrayList<Intent> parseIntents(int xml_res) {
1230 ArrayList<Intent> intents = new ArrayList<Intent>();
1231 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1232 try {
1233 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1234 final int depth = parser.getDepth();
1235 int type;
1236 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1237 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1238 if (type != XmlPullParser.START_TAG) {
1239 continue;
1240 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1241 final String uri = DefaultLayoutParser.getAttributeValue(
1242 parser, DefaultLayoutParser.ATTR_URI);
1243 intents.add(Intent.parseUri(uri, 0));
1244 }
1245 }
1246 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1247 Log.e(TAG, "Unable to parse " + xml_res, e);
1248 } finally {
1249 parser.close();
1250 }
1251 return intents;
1252 }
1253
1254 public boolean matches(ActivityInfo activity, PackageManager pm) {
1255 for (Intent intent : mIntents) {
1256 intent.setPackage(activity.packageName);
1257 ResolveInfo info = pm.resolveActivity(intent, 0);
1258 if (info != null && (info.activityInfo.name.equals(activity.name)
1259 || info.activityInfo.name.equals(activity.targetActivity))) {
1260 return true;
1261 }
1262 }
1263 return false;
1264 }
1265 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001266}