blob: 05d729e78a3096afd5cd3c3b22e44ff0b66827b7 [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;
Sunny Goyala6164c52016-01-06 14:47:13 -080044import com.android.launcher3.backup.nano.BackupProtos;
45import com.android.launcher3.backup.nano.BackupProtos.CheckedMessage;
46import com.android.launcher3.backup.nano.BackupProtos.DeviceProfieData;
47import com.android.launcher3.backup.nano.BackupProtos.Favorite;
48import com.android.launcher3.backup.nano.BackupProtos.Journal;
49import com.android.launcher3.backup.nano.BackupProtos.Key;
50import com.android.launcher3.backup.nano.BackupProtos.Resource;
51import com.android.launcher3.backup.nano.BackupProtos.Screen;
52import com.android.launcher3.backup.nano.BackupProtos.Widget;
Sunny Goyalef728d42014-10-22 11:28:28 -070053import com.android.launcher3.compat.UserHandleCompat;
54import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyalf862a262015-12-14 14:27:38 -080055import com.android.launcher3.model.GridSizeMigrationTask;
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 Goyalf076eae2016-01-11 12:25:10 -0800318 if (GridSizeMigrationTask.ENABLED) {
319 // One time migrate the workspace when launcher starts.
Sunny Goyale5bb7052015-07-27 14:36:07 -0700320 migrationCompatibleProfileData = initDeviceProfileData(mIdp);
321 migrationCompatibleProfileData.desktopCols = oldProfile.desktopCols;
322 migrationCompatibleProfileData.desktopRows = oldProfile.desktopRows;
Sunny Goyalf076eae2016-01-11 12:25:10 -0800323 migrationCompatibleProfileData.hotseatCount = oldProfile.hotseatCount;
324 migrationCompatibleProfileData.allappsRank = oldProfile.allappsRank;
Sunny Goyale5bb7052015-07-27 14:36:07 -0700325 return true;
326 }
327 return false;
Sunny Goyal33d44382014-10-16 09:24:19 -0700328 }
329
330 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400331 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700332 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
333 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400334 *
Chris Wren92aa4232013-10-04 11:29:36 -0400335 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400336 */
337 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400338 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700339 if (!restoreSuccessful) {
340 return;
341 }
Sunny Goyal96373642015-06-05 11:14:01 -0700342
343 if (mDeviceProfileData == null) {
344 // This call does not happen on a looper thread. So LauncherAppState
345 // can't be created . Instead initialize required dependencies directly.
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700346 mIdp = new InvariantDeviceProfile(mContext);
347 mDeviceProfileData = initDeviceProfileData(mIdp);
348 mIconCache = new IconCache(mContext, mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700349 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700350
Sunny Goyalef728d42014-10-22 11:28:28 -0700351 int dataSize = data.size();
352 if (mBuffer.length < dataSize) {
353 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400354 }
355 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700356 int bytesRead = data.read(mBuffer, 0, dataSize);
357 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
358 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700359
360 if (JOURNAL_KEY.equals(backupKey)) {
361 if (VERBOSE) Log.v(TAG, "Journal entry restored");
362 if (!mKeys.isEmpty()) {
363 // We received the journal key after a restore key.
364 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
365 restoreSuccessful = false;
366 return;
367 }
368
369 Journal journal = new Journal();
370 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
371 applyJournal(journal);
372 restoreSuccessful = isBackupCompatible(journal);
373 return;
374 }
375
376 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
377 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
378 return;
379 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700380 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500381 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400382 switch (key.type) {
383 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700384 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400385 break;
386
387 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700388 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400389 break;
390
391 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700392 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400393 break;
394
395 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700396 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400397 break;
398
399 default:
400 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700401 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400402 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400403 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700404 } catch (IOException e) {
405 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400406 }
Chris Wren92aa4232013-10-04 11:29:36 -0400407 }
408
409 /**
410 * Record the restore state for the next backup.
411 *
412 * @param newState notes about the backup state after restore.
413 */
414 @Override
415 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700416 writeJournal(newState, getCurrentStateJournal());
417 }
418
419 private Journal getCurrentStateJournal() {
420 Journal journal = new Journal();
421 journal.t = mLastBackupRestoreTime;
422 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
423 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700424 journal.backupVersion = BACKUP_VERSION;
Sunny Goyal96373642015-06-05 11:14:01 -0700425 journal.profile = mDeviceProfileData;
Sunny Goyalef728d42014-10-22 11:28:28 -0700426 return journal;
427 }
428
429 private int getAppVersion() {
430 try {
431 return mContext.getPackageManager()
432 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
433 } catch (NameNotFoundException e) {
434 return 0;
435 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400436 }
437
Adam Cohen2e6da152015-05-06 11:42:25 -0700438 private DeviceProfieData initDeviceProfileData(InvariantDeviceProfile profile) {
439 DeviceProfieData data = new DeviceProfieData();
440 data.desktopRows = profile.numRows;
441 data.desktopCols = profile.numColumns;
442 data.hotseatCount = profile.numHotseatIcons;
443 data.allappsRank = profile.hotseatAllAppsRank;
444 return data;
Sunny Goyal33d44382014-10-16 09:24:19 -0700445 }
446
447 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400448 * Write all modified favorites to the data stream.
449 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400450 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400451 * @throws IOException
452 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700453 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400454 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400455 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700456 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400457 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700458 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400459 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400460 cursor.moveToPosition(-1);
461 while(cursor.moveToNext()) {
462 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700463 final long updateTime = cursor.getLong(ID_MODIFIED);
464 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700465 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700466 final String backupKey = keyToBackupKey(key);
Sunny Goyal107ea632015-07-20 12:59:39 -0700467
468 // Favorite proto changed in v4. Backup again if the version is old.
469 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime
470 || restoredBackupVersion < 4) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700471 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500472 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700473 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400474 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400475 }
476 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400477 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400478 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 }
480
481 /**
482 * Read a favorite from the stream.
483 *
484 * <P>Keys arrive in any order, so screens and containers may not exist yet.
485 *
486 * @param key identifier for the row
487 * @param buffer the serialized proto from the stream, may be larger than dataSize
488 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400489 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700490 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500491 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400492 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
493 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
494
Sunny Goyalef728d42014-10-22 11:28:28 -0700495 ContentResolver cr = mContext.getContentResolver();
496 ContentValues values = unpackFavorite(buffer, dataSize);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700497 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400498 }
499
500 /**
501 * Write all modified screens to the data stream.
502 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400503 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400504 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400505 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700506 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400507 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400508 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400509 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
510 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400511 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400512 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700513 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400514 while(cursor.moveToNext()) {
515 final long id = cursor.getLong(ID_INDEX);
516 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400517 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700518 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500519 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700520 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
521 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500522 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700523 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400524 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400525 }
526 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400527 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400528 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400529 }
530
531 /**
532 * Read a screen from the stream.
533 *
534 * <P>Keys arrive in any order, so children of this screen may already exist.
535 *
536 * @param key identifier for the row
537 * @param buffer the serialized proto from the stream, may be larger than dataSize
538 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400539 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700540 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500541 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400542 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
543 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500544
Sunny Goyalef728d42014-10-22 11:28:28 -0700545 ContentResolver cr = mContext.getContentResolver();
546 ContentValues values = unpackScreen(buffer, dataSize);
547 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400548 }
549
Chris Wren22e130d2013-09-23 18:25:57 -0400550 /**
551 * Write all the static icon resources we need to render placeholders
552 * for a package that is not installed.
553 *
Chris Wren22e130d2013-09-23 18:25:57 -0400554 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400555 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700556 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400557 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400558 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400559 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700560 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700561 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400562
Kenny Guyed131872014-04-30 03:02:21 +0100563 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100564 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100565 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700566 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400567 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
568 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400569 try {
570 cursor.moveToPosition(-1);
571 while(cursor.moveToNext()) {
572 final long id = cursor.getLong(ID_INDEX);
573 final String intentDescription = cursor.getString(INTENT_INDEX);
574 try {
575 Intent intent = Intent.parseUri(intentDescription, 0);
576 ComponentName cn = intent.getComponent();
577 Key key = null;
578 String backupKey = null;
579 if (cn != null) {
580 key = getKey(Key.ICON, cn.flattenToShortString());
581 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400582 } else {
583 Log.w(TAG, "empty intent on application favorite: " + id);
584 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700585 if (mExistingKeys.contains(backupKey)) {
586 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400587
588 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700589 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400590 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700591 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
592 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
593 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100594 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100595 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700596 writeRowToBackup(key, packIcon(dpi, icon), data);
597 mKeys.add(key);
598 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400599 }
600 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700601 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400602 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400603 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400604 }
605 }
606 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500607 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400608 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500609 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400610 }
611
612 }
613 } finally {
614 cursor.close();
615 }
Chris Wren22e130d2013-09-23 18:25:57 -0400616 }
617
618 /**
619 * Read an icon from the stream.
620 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400621 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400622 *
623 * @param key identifier for the row
624 * @param buffer the serialized proto from the stream, may be larger than dataSize
625 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400626 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700627 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500628 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400629 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
630 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500631
Sunny Goyalef728d42014-10-22 11:28:28 -0700632 Resource res = unpackProto(new Resource(), buffer, dataSize);
633 if (DEBUG) {
634 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400635 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700636 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
637 if (icon == null) {
638 Log.w(TAG, "failed to unpack icon for " + key.name);
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700639 } else {
640 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
641 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
642 "" /* label */, mUserSerial, mIdp);
Sunny Goyalef728d42014-10-22 11:28:28 -0700643 }
Chris Wren22e130d2013-09-23 18:25:57 -0400644 }
645
Chris Wrenfd13c712013-09-27 15:45:19 -0400646 /**
647 * Write all the static widget resources we need to render placeholders
648 * for a package that is not installed.
649 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400650 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400651 * @throws IOException
652 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700653 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400654 // persist static widget info that hasn't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400655 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400656 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalef728d42014-10-22 11:28:28 -0700657 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400658
Sunny Goyalffe83f12014-08-14 17:39:34 -0700659 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
660 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400661 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
662 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400663 try {
664 cursor.moveToPosition(-1);
665 while(cursor.moveToNext()) {
666 final long id = cursor.getLong(ID_INDEX);
667 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
Chris Wrenfd13c712013-09-27 15:45:19 -0400668 final ComponentName provider = ComponentName.unflattenFromString(providerName);
669 Key key = null;
670 String backupKey = null;
671 if (provider != null) {
672 key = getKey(Key.WIDGET, providerName);
673 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400674 } else {
675 Log.w(TAG, "empty intent on appwidget: " + id);
676 }
Sunny Goyal107ea632015-07-20 12:59:39 -0700677
678 // Widget backup proto changed in v3. So add it again if the original backup is old.
679 if (mExistingKeys.contains(backupKey) && restoredBackupVersion >= 3) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700680 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400681
682 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700683 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400684 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700685 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
686 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
687 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Robin Lee26ace122015-03-16 19:41:43 +0000688 UserHandleCompat user = UserHandleCompat.myUserHandle();
Sunny Goyal96373642015-06-05 11:14:01 -0700689 writeRowToBackup(key, packWidget(dpi, provider, user), data);
Sunny Goyalef728d42014-10-22 11:28:28 -0700690 mKeys.add(key);
691 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400692 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700693 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400694 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400695 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400696 }
697 }
698 }
699 } finally {
700 cursor.close();
701 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400702 }
703
704 /**
705 * Read a widget from the stream.
706 *
707 * <P>Keys arrive in any order, so widgets that use this data may already exist.
708 *
709 * @param key identifier for the row
710 * @param buffer the serialized proto from the stream, may be larger than dataSize
711 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400712 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700713 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500714 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400715 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
716 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700717 Widget widget = unpackProto(new Widget(), buffer, dataSize);
718 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
719 if (widget.icon.data != null) {
720 Bitmap icon = BitmapFactory
721 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
722 if (icon == null) {
723 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500724 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800725 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700726 icon, widget.icon.dpi, widget.label, mUserSerial, mIdp);
Chris Wren5dee7af2013-12-20 17:22:11 -0500727 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400728 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700729
Sunny Goyale5bb7052015-07-27 14:36:07 -0700730 // Cache widget min sizes incase migration is required.
731 widgetSizes.add(widget.provider + "#" + widget.minSpanX + "," + widget.minSpanY);
Chris Wrenfd13c712013-09-27 15:45:19 -0400732 }
733
Chris Wren22e130d2013-09-23 18:25:57 -0400734 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400735 *
736 * <P> Keys contain their own checksum instead of using
737 * the heavy-weight CheckedMessage wrapper.
738 */
739 private Key getKey(int type, long id) {
740 Key key = new Key();
741 key.type = type;
742 key.id = id;
743 key.checksum = checkKey(key);
744 return key;
745 }
746
Chris Wren22e130d2013-09-23 18:25:57 -0400747 /** create a new key for a named object.
748 *
749 * <P> Keys contain their own checksum instead of using
750 * the heavy-weight CheckedMessage wrapper.
751 */
752 private Key getKey(int type, String name) {
753 Key key = new Key();
754 key.type = type;
755 key.name = name;
756 key.checksum = checkKey(key);
757 return key;
758 }
759
Chris Wren1ada10d2013-09-13 18:01:38 -0400760 /** keys need to be strings, serialize and encode. */
761 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400762 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400763 }
764
765 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700766 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400767 try {
768 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
769 if (key.checksum != checkKey(key)) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700770 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400771 }
772 return key;
Sunny Goyalb740f592015-12-17 23:22:42 -0800773 } catch (InvalidProtocolBufferNanoException | IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700774 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400775 }
776 }
777
778 /** Compute the checksum over the important bits of a key. */
779 private long checkKey(Key key) {
780 CRC32 checksum = new CRC32();
781 checksum.update(key.type);
782 checksum.update((int) (key.id & 0xffff));
783 checksum.update((int) ((key.id >> 32) & 0xffff));
784 if (!TextUtils.isEmpty(key.name)) {
785 checksum.update(key.name.getBytes());
786 }
787 return checksum.getValue();
788 }
789
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800790 /**
791 * @return true if its an hotseat item, that can be replaced during restore.
792 * TODO: Extend check for folders in hotseat.
793 */
794 private boolean isReplaceableHotseatItem(Favorite favorite) {
795 return favorite.container == Favorites.CONTAINER_HOTSEAT
796 && favorite.intent != null
797 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
798 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
799 }
800
Chris Wren1ada10d2013-09-13 18:01:38 -0400801 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700802 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400803 Favorite favorite = new Favorite();
804 favorite.id = c.getLong(ID_INDEX);
805 favorite.screen = c.getInt(SCREEN_INDEX);
806 favorite.container = c.getInt(CONTAINER_INDEX);
807 favorite.cellX = c.getInt(CELLX_INDEX);
808 favorite.cellY = c.getInt(CELLY_INDEX);
809 favorite.spanX = c.getInt(SPANX_INDEX);
810 favorite.spanY = c.getInt(SPANY_INDEX);
811 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
Sunny Goyal107ea632015-07-20 12:59:39 -0700812 favorite.rank = c.getInt(RANK_INDEX);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700813
Chris Wren1ada10d2013-09-13 18:01:38 -0400814 String title = c.getString(TITLE_INDEX);
815 if (!TextUtils.isEmpty(title)) {
816 favorite.title = title;
817 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100818 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800819 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100820 if (!TextUtils.isEmpty(intentDescription)) {
821 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800822 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100823 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
824 favorite.intent = intent.toUri(0);
825 } catch (URISyntaxException e) {
826 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700827 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400828 }
829 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
830 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
831 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
832 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
833 if (!TextUtils.isEmpty(appWidgetProvider)) {
834 favorite.appWidgetProvider = appWidgetProvider;
835 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700836 } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
837 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
838 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
839 if (!TextUtils.isEmpty(iconPackage)) {
840 favorite.iconPackage = iconPackage;
841 }
842 String iconResource = c.getString(ICON_RESOURCE_INDEX);
843 if (!TextUtils.isEmpty(iconResource)) {
844 favorite.iconResource = iconResource;
845 }
846 }
847
848 byte[] blob = c.getBlob(ICON_INDEX);
849 if (blob != null && blob.length > 0) {
850 favorite.icon = blob;
851 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400852 }
853
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800854 if (isReplaceableHotseatItem(favorite)) {
855 if (intent != null && intent.getComponent() != null) {
856 PackageManager pm = mContext.getPackageManager();
857 ActivityInfo activity = null;;
858 try {
859 activity = pm.getActivityInfo(intent.getComponent(), 0);
860 } catch (NameNotFoundException e) {
861 Log.e(TAG, "Target not found", e);
862 }
863 if (activity == null) {
864 return favorite;
865 }
866 for (int i = 0; i < mItemTypeMatchers.length; i++) {
867 if (mItemTypeMatchers[i] == null) {
868 mItemTypeMatchers[i] = new ItemTypeMatcher(
869 CommonAppTypeParser.getResourceForItemType(i));
870 }
871 if (mItemTypeMatchers[i].matches(activity, pm)) {
872 favorite.targetType = i;
873 break;
874 }
875 }
876 }
877 }
878
Sunny Goyalef728d42014-10-22 11:28:28 -0700879 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400880 }
881
882 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700883 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700884 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700885 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800886
Sunny Goyalc115e642015-07-20 14:23:43 -0700887 // If it is a hotseat item, move it accordingly.
888 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
889 favorite.screen += mHotseatShift;
890 }
891
Chris Wren5dee7af2013-12-20 17:22:11 -0500892 ContentValues values = new ContentValues();
893 values.put(Favorites._ID, favorite.id);
894 values.put(Favorites.SCREEN, favorite.screen);
895 values.put(Favorites.CONTAINER, favorite.container);
896 values.put(Favorites.CELLX, favorite.cellX);
897 values.put(Favorites.CELLY, favorite.cellY);
898 values.put(Favorites.SPANX, favorite.spanX);
899 values.put(Favorites.SPANY, favorite.spanY);
Sunny Goyal107ea632015-07-20 12:59:39 -0700900 values.put(Favorites.RANK, favorite.rank);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700901
902 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
903 values.put(Favorites.ICON_TYPE, favorite.iconType);
904 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
905 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
906 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
907 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500908 values.put(Favorites.ICON, favorite.icon);
909 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700910
Chris Wren5dee7af2013-12-20 17:22:11 -0500911 if (!TextUtils.isEmpty(favorite.title)) {
912 values.put(Favorites.TITLE, favorite.title);
913 } else {
914 values.put(Favorites.TITLE, "");
915 }
916 if (!TextUtils.isEmpty(favorite.intent)) {
917 values.put(Favorites.INTENT, favorite.intent);
918 }
919 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500920
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100921 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
922 long userSerialNumber =
923 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
924 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
925
Sunny Goyale5bb7052015-07-27 14:36:07 -0700926 // If we will attempt grid resize, use the original profile to validate grid size, as
927 // anything which fits in the original grid should fit in the current grid after
928 // grid migration.
929 DeviceProfieData currentProfile = migrationCompatibleProfileData == null
930 ? mDeviceProfileData : migrationCompatibleProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700931
Sunny Goyalff572272014-07-23 13:58:07 -0700932 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
933 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
934 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
935 }
936 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
937 values.put(LauncherSettings.Favorites.RESTORED,
938 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
939 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
940 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700941
942 // Verify placement
943 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
944 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
945 restoreSuccessful = false;
946 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
947 }
Sunny Goyalff572272014-07-23 13:58:07 -0700948 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800949 // Check if it is an hotseat item, that can be replaced.
950 if (isReplaceableHotseatItem(favorite)
951 && favorite.targetType != Favorite.TARGET_NONE
952 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
953 Log.e(TAG, "Added item type flag");
954 values.put(LauncherSettings.Favorites.RESTORED,
955 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
956 } else {
957 // Let LauncherModel know we've been here.
958 values.put(LauncherSettings.Favorites.RESTORED, 1);
959 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700960
961 // Verify placement
962 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
963 if ((favorite.screen >= currentProfile.hotseatCount)
964 || (favorite.screen == currentProfile.allappsRank)) {
965 restoreSuccessful = false;
966 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
967 }
968 } else {
969 if ((favorite.cellX >= currentProfile.desktopCols)
970 || (favorite.cellY >= currentProfile.desktopRows)) {
971 restoreSuccessful = false;
972 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
973 }
974 }
Sunny Goyalff572272014-07-23 13:58:07 -0700975 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500976
Chris Wren5dee7af2013-12-20 17:22:11 -0500977 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400978 }
979
980 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700981 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400982 Screen screen = new Screen();
983 screen.id = c.getLong(ID_INDEX);
984 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700985 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400986 }
987
988 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700989 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400990 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700991 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500992 ContentValues values = new ContentValues();
993 values.put(WorkspaceScreens._ID, screen.id);
994 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
995 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400996 }
997
Chris Wren22e130d2013-09-23 18:25:57 -0400998 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700999 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -04001000 Resource res = new Resource();
1001 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -07001002 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -04001003 return res;
1004 }
1005
Chris Wrenfd13c712013-09-27 15:45:19 -04001006 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal96373642015-06-05 11:14:01 -07001007 private Widget packWidget(int dpi, ComponentName provider, UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08001008 final LauncherAppWidgetProviderInfo info =
Robin Lee26ace122015-03-16 19:41:43 +00001009 LauncherModel.getProviderInfo(mContext, provider, user);
Chris Wrenfd13c712013-09-27 15:45:19 -04001010 Widget widget = new Widget();
1011 widget.provider = provider.flattenToShortString();
1012 widget.label = info.label;
1013 widget.configure = info.configure != null;
1014 if (info.icon != 0) {
1015 widget.icon = new Resource();
Sunny Goyal96373642015-06-05 11:14:01 -07001016 Drawable fullResIcon = mIconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -04001017 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -07001018 widget.icon.data = Utilities.flattenBitmap(icon);
1019 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -04001020 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001021
Sunny Goyale5bb7052015-07-27 14:36:07 -07001022 Point spans = info.getMinSpans(mIdp, mContext);
1023 widget.minSpanX = spans.x;
1024 widget.minSpanY = spans.y;
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001025
Sunny Goyalef728d42014-10-22 11:28:28 -07001026 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001027 }
1028
Sunny Goyalef728d42014-10-22 11:28:28 -07001029 /**
1030 * Deserialize a proto after verifying checksum wrapper.
1031 */
1032 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001033 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001034 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1035 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1036 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001037 }
1038
Chris Wren1ada10d2013-09-13 18:01:38 -04001039 /**
1040 * Read the old journal from the input file.
1041 *
1042 * In the event of any error, just pretend we didn't have a journal,
1043 * in that case, do a full backup.
1044 *
1045 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001046 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001047 */
1048 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001049 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001050 if (oldState == null) {
1051 return journal;
1052 }
1053 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1054 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001055 int availableBytes = inStream.available();
1056 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1057 if (availableBytes < MAX_JOURNAL_SIZE) {
1058 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001059 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001060 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001061 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001062 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001063 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001064 // OMG what are you doing? This is crazy inefficient!
1065 // If we read a byte that is not ours, we will cause trouble: b/12491813
1066 // However, we don't know how many bytes to expect (oops).
1067 // So we have to step through *slowly*, watching for the end.
1068 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001069 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001070 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001071 bytesRead += result;
1072 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001073 Log.w(TAG, "unexpected end of file while reading journal.");
1074 // stop reading and see what there is to parse
1075 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001076 }
1077 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001078 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001079 availableBytes = 0;
1080 }
1081
1082 // check the buffer to see if we have a valid journal
1083 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001084 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001085 // if we are here, then we have read a valid, checksum-verified journal
1086 valid = true;
1087 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001088 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001089 } catch (InvalidProtocolBufferNanoException e) {
1090 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001091 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001092 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001093 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001094 }
Chris Wren92aa4232013-10-04 11:29:36 -04001095 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001096 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001097 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001098 }
1099 }
Chris Wren92aa4232013-10-04 11:29:36 -04001100 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001101 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001102 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001103 try {
1104 inStream.close();
1105 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001106 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001107 }
1108 }
1109 return journal;
1110 }
1111
Sunny Goyalef728d42014-10-22 11:28:28 -07001112 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1113 throws IOException {
1114 writeRowToBackup(keyToBackupKey(key), proto, data);
1115 }
1116
1117 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001118 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001119 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001120 data.writeEntityHeader(backupKey, blob.length);
1121 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001122 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001123 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001124 }
1125
Chris Wren1ada10d2013-09-13 18:01:38 -04001126 /**
1127 * Write the new journal to the output file.
1128 *
1129 * In the event of any error, just pretend we didn't have a journal,
1130 * in that case, do a full backup.
1131
1132 * @param newState the write-only file descriptor pointing to the new journal
1133 * @param journal a Journal protocol buffer
1134 */
1135 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001136 try {
Sunny Goyalb740f592015-12-17 23:22:42 -08001137 FileOutputStream outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001138 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001139 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001140 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001141 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001142 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001143 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001144 }
1145 }
1146
1147 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1148 private byte[] writeCheckedBytes(MessageNano proto) {
1149 CheckedMessage wrapper = new CheckedMessage();
1150 wrapper.payload = MessageNano.toByteArray(proto);
1151 CRC32 checksum = new CRC32();
1152 checksum.update(wrapper.payload);
1153 wrapper.checksum = checksum.getValue();
1154 return MessageNano.toByteArray(wrapper);
1155 }
1156
1157 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001158 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001159 throws InvalidProtocolBufferNanoException {
1160 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001161 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001162 CRC32 checksum = new CRC32();
1163 checksum.update(wrapper.payload);
1164 if (wrapper.checksum != checksum.getValue()) {
1165 throw new InvalidProtocolBufferNanoException("checksum does not match");
1166 }
1167 return wrapper.payload;
1168 }
1169
Sunny Goyalef728d42014-10-22 11:28:28 -07001170 /**
1171 * @return true if the launcher is in a state to support backup
1172 */
Chris Wren71144262014-02-27 15:49:39 -05001173 private boolean launcherIsReady() {
1174 ContentResolver cr = mContext.getContentResolver();
1175 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1176 if (cursor == null) {
1177 // launcher data has been wiped, do nothing
1178 return false;
1179 }
1180 cursor.close();
1181
Adam Cohen2e6da152015-05-06 11:42:25 -07001182 if (LauncherAppState.getInstanceNoCreate() == null) {
Chris Wren71144262014-02-27 15:49:39 -05001183 // launcher services are unavailable, try again later
Chris Wren71144262014-02-27 15:49:39 -05001184 return false;
1185 }
1186
1187 return true;
1188 }
1189
Sunny Goyalffe83f12014-08-14 17:39:34 -07001190 private String getUserSelectionArg() {
1191 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1192 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1193 }
1194
Sunny Goyal316490e2015-06-02 09:38:28 -07001195 @Thunk class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001196
1197 private static final long serialVersionUID = 8931456637211665082L;
1198
Sunny Goyal316490e2015-06-02 09:38:28 -07001199 @Thunk InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001200 super(cause);
1201 }
1202
Sunny Goyal316490e2015-06-02 09:38:28 -07001203 @Thunk InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001204 super(reason);
1205 }
1206 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001207
Sunny Goyale5bb7052015-07-27 14:36:07 -07001208 public boolean shouldAttemptWorkspaceMigration() {
1209 return migrationCompatibleProfileData != null;
1210 }
1211
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001212 /**
1213 * A class to check if an activity can handle one of the intents from a list of
1214 * predefined intents.
1215 */
1216 private class ItemTypeMatcher {
1217
1218 private final ArrayList<Intent> mIntents;
1219
1220 ItemTypeMatcher(int xml_res) {
1221 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1222 }
1223
1224 private ArrayList<Intent> parseIntents(int xml_res) {
1225 ArrayList<Intent> intents = new ArrayList<Intent>();
1226 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1227 try {
1228 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1229 final int depth = parser.getDepth();
1230 int type;
1231 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1232 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1233 if (type != XmlPullParser.START_TAG) {
1234 continue;
1235 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1236 final String uri = DefaultLayoutParser.getAttributeValue(
1237 parser, DefaultLayoutParser.ATTR_URI);
1238 intents.add(Intent.parseUri(uri, 0));
1239 }
1240 }
1241 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1242 Log.e(TAG, "Unable to parse " + xml_res, e);
1243 } finally {
1244 parser.close();
1245 }
1246 return intents;
1247 }
1248
1249 public boolean matches(ActivityInfo activity, PackageManager pm) {
1250 for (Intent intent : mIntents) {
1251 intent.setPackage(activity.packageName);
1252 ResolveInfo info = pm.resolveActivity(intent, 0);
1253 if (info != null && (info.activityInfo.name.equals(activity.name)
1254 || info.activityInfo.name.equals(activity.targetActivity))) {
1255 return true;
1256 }
1257 }
1258 return false;
1259 }
1260 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001261}