blob: 509fbf8b8835164c00068e60c382db6f510b141f [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)) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700771 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400772 }
773 return key;
Sunny Goyalb740f592015-12-17 23:22:42 -0800774 } catch (InvalidProtocolBufferNanoException | IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700775 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400776 }
777 }
778
779 /** Compute the checksum over the important bits of a key. */
780 private long checkKey(Key key) {
781 CRC32 checksum = new CRC32();
782 checksum.update(key.type);
783 checksum.update((int) (key.id & 0xffff));
784 checksum.update((int) ((key.id >> 32) & 0xffff));
785 if (!TextUtils.isEmpty(key.name)) {
786 checksum.update(key.name.getBytes());
787 }
788 return checksum.getValue();
789 }
790
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800791 /**
792 * @return true if its an hotseat item, that can be replaced during restore.
793 * TODO: Extend check for folders in hotseat.
794 */
795 private boolean isReplaceableHotseatItem(Favorite favorite) {
796 return favorite.container == Favorites.CONTAINER_HOTSEAT
797 && favorite.intent != null
798 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
799 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
800 }
801
Chris Wren1ada10d2013-09-13 18:01:38 -0400802 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700803 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400804 Favorite favorite = new Favorite();
805 favorite.id = c.getLong(ID_INDEX);
806 favorite.screen = c.getInt(SCREEN_INDEX);
807 favorite.container = c.getInt(CONTAINER_INDEX);
808 favorite.cellX = c.getInt(CELLX_INDEX);
809 favorite.cellY = c.getInt(CELLY_INDEX);
810 favorite.spanX = c.getInt(SPANX_INDEX);
811 favorite.spanY = c.getInt(SPANY_INDEX);
812 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
Sunny Goyal107ea632015-07-20 12:59:39 -0700813 favorite.rank = c.getInt(RANK_INDEX);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700814
Chris Wren1ada10d2013-09-13 18:01:38 -0400815 String title = c.getString(TITLE_INDEX);
816 if (!TextUtils.isEmpty(title)) {
817 favorite.title = title;
818 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100819 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800820 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100821 if (!TextUtils.isEmpty(intentDescription)) {
822 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800823 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100824 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
825 favorite.intent = intent.toUri(0);
826 } catch (URISyntaxException e) {
827 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700828 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400829 }
830 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
831 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
832 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
833 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
834 if (!TextUtils.isEmpty(appWidgetProvider)) {
835 favorite.appWidgetProvider = appWidgetProvider;
836 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700837 } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
838 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
839 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
840 if (!TextUtils.isEmpty(iconPackage)) {
841 favorite.iconPackage = iconPackage;
842 }
843 String iconResource = c.getString(ICON_RESOURCE_INDEX);
844 if (!TextUtils.isEmpty(iconResource)) {
845 favorite.iconResource = iconResource;
846 }
847 }
848
849 byte[] blob = c.getBlob(ICON_INDEX);
850 if (blob != null && blob.length > 0) {
851 favorite.icon = blob;
852 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400853 }
854
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800855 if (isReplaceableHotseatItem(favorite)) {
856 if (intent != null && intent.getComponent() != null) {
857 PackageManager pm = mContext.getPackageManager();
858 ActivityInfo activity = null;;
859 try {
860 activity = pm.getActivityInfo(intent.getComponent(), 0);
861 } catch (NameNotFoundException e) {
862 Log.e(TAG, "Target not found", e);
863 }
864 if (activity == null) {
865 return favorite;
866 }
867 for (int i = 0; i < mItemTypeMatchers.length; i++) {
868 if (mItemTypeMatchers[i] == null) {
869 mItemTypeMatchers[i] = new ItemTypeMatcher(
870 CommonAppTypeParser.getResourceForItemType(i));
871 }
872 if (mItemTypeMatchers[i].matches(activity, pm)) {
873 favorite.targetType = i;
874 break;
875 }
876 }
877 }
878 }
879
Sunny Goyalef728d42014-10-22 11:28:28 -0700880 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400881 }
882
883 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700884 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700885 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700886 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800887
Sunny Goyalc115e642015-07-20 14:23:43 -0700888 // If it is a hotseat item, move it accordingly.
889 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
890 favorite.screen += mHotseatShift;
891 }
892
Chris Wren5dee7af2013-12-20 17:22:11 -0500893 ContentValues values = new ContentValues();
894 values.put(Favorites._ID, favorite.id);
895 values.put(Favorites.SCREEN, favorite.screen);
896 values.put(Favorites.CONTAINER, favorite.container);
897 values.put(Favorites.CELLX, favorite.cellX);
898 values.put(Favorites.CELLY, favorite.cellY);
899 values.put(Favorites.SPANX, favorite.spanX);
900 values.put(Favorites.SPANY, favorite.spanY);
Sunny Goyal107ea632015-07-20 12:59:39 -0700901 values.put(Favorites.RANK, favorite.rank);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700902
903 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
904 values.put(Favorites.ICON_TYPE, favorite.iconType);
905 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
906 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
907 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
908 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500909 values.put(Favorites.ICON, favorite.icon);
910 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700911
Chris Wren5dee7af2013-12-20 17:22:11 -0500912 if (!TextUtils.isEmpty(favorite.title)) {
913 values.put(Favorites.TITLE, favorite.title);
914 } else {
915 values.put(Favorites.TITLE, "");
916 }
917 if (!TextUtils.isEmpty(favorite.intent)) {
918 values.put(Favorites.INTENT, favorite.intent);
919 }
920 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500921
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100922 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
923 long userSerialNumber =
924 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
925 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
926
Sunny Goyale5bb7052015-07-27 14:36:07 -0700927 // If we will attempt grid resize, use the original profile to validate grid size, as
928 // anything which fits in the original grid should fit in the current grid after
929 // grid migration.
930 DeviceProfieData currentProfile = migrationCompatibleProfileData == null
931 ? mDeviceProfileData : migrationCompatibleProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700932
Sunny Goyalff572272014-07-23 13:58:07 -0700933 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
934 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
935 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
936 }
937 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
938 values.put(LauncherSettings.Favorites.RESTORED,
939 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
940 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
941 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700942
943 // Verify placement
944 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
945 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
946 restoreSuccessful = false;
947 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
948 }
Sunny Goyalff572272014-07-23 13:58:07 -0700949 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800950 // Check if it is an hotseat item, that can be replaced.
951 if (isReplaceableHotseatItem(favorite)
952 && favorite.targetType != Favorite.TARGET_NONE
953 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
954 Log.e(TAG, "Added item type flag");
955 values.put(LauncherSettings.Favorites.RESTORED,
956 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
957 } else {
958 // Let LauncherModel know we've been here.
959 values.put(LauncherSettings.Favorites.RESTORED, 1);
960 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700961
962 // Verify placement
963 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
964 if ((favorite.screen >= currentProfile.hotseatCount)
965 || (favorite.screen == currentProfile.allappsRank)) {
966 restoreSuccessful = false;
967 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
968 }
969 } else {
970 if ((favorite.cellX >= currentProfile.desktopCols)
971 || (favorite.cellY >= currentProfile.desktopRows)) {
972 restoreSuccessful = false;
973 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
974 }
975 }
Sunny Goyalff572272014-07-23 13:58:07 -0700976 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500977
Chris Wren5dee7af2013-12-20 17:22:11 -0500978 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400979 }
980
981 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700982 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400983 Screen screen = new Screen();
984 screen.id = c.getLong(ID_INDEX);
985 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700986 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400987 }
988
989 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700990 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400991 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700992 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500993 ContentValues values = new ContentValues();
994 values.put(WorkspaceScreens._ID, screen.id);
995 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
996 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400997 }
998
Chris Wren22e130d2013-09-23 18:25:57 -0400999 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001000 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -04001001 Resource res = new Resource();
1002 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -07001003 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -04001004 return res;
1005 }
1006
Chris Wrenfd13c712013-09-27 15:45:19 -04001007 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal96373642015-06-05 11:14:01 -07001008 private Widget packWidget(int dpi, ComponentName provider, UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08001009 final LauncherAppWidgetProviderInfo info =
Robin Lee26ace122015-03-16 19:41:43 +00001010 LauncherModel.getProviderInfo(mContext, provider, user);
Chris Wrenfd13c712013-09-27 15:45:19 -04001011 Widget widget = new Widget();
1012 widget.provider = provider.flattenToShortString();
1013 widget.label = info.label;
1014 widget.configure = info.configure != null;
1015 if (info.icon != 0) {
1016 widget.icon = new Resource();
Sunny Goyal96373642015-06-05 11:14:01 -07001017 Drawable fullResIcon = mIconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -04001018 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -07001019 widget.icon.data = Utilities.flattenBitmap(icon);
1020 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -04001021 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001022
Sunny Goyale5bb7052015-07-27 14:36:07 -07001023 Point spans = info.getMinSpans(mIdp, mContext);
1024 widget.minSpanX = spans.x;
1025 widget.minSpanY = spans.y;
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001026
Sunny Goyalef728d42014-10-22 11:28:28 -07001027 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001028 }
1029
Sunny Goyalef728d42014-10-22 11:28:28 -07001030 /**
1031 * Deserialize a proto after verifying checksum wrapper.
1032 */
1033 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001034 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001035 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1036 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1037 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001038 }
1039
Chris Wren1ada10d2013-09-13 18:01:38 -04001040 /**
1041 * Read the old journal from the input file.
1042 *
1043 * In the event of any error, just pretend we didn't have a journal,
1044 * in that case, do a full backup.
1045 *
1046 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001047 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001048 */
1049 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001050 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001051 if (oldState == null) {
1052 return journal;
1053 }
1054 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1055 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001056 int availableBytes = inStream.available();
1057 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1058 if (availableBytes < MAX_JOURNAL_SIZE) {
1059 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001060 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001061 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001062 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001063 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001064 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001065 // OMG what are you doing? This is crazy inefficient!
1066 // If we read a byte that is not ours, we will cause trouble: b/12491813
1067 // However, we don't know how many bytes to expect (oops).
1068 // So we have to step through *slowly*, watching for the end.
1069 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001070 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001071 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001072 bytesRead += result;
1073 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001074 Log.w(TAG, "unexpected end of file while reading journal.");
1075 // stop reading and see what there is to parse
1076 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001077 }
1078 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001079 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001080 availableBytes = 0;
1081 }
1082
1083 // check the buffer to see if we have a valid journal
1084 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001085 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001086 // if we are here, then we have read a valid, checksum-verified journal
1087 valid = true;
1088 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001089 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001090 } catch (InvalidProtocolBufferNanoException e) {
1091 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001092 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001093 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001094 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001095 }
Chris Wren92aa4232013-10-04 11:29:36 -04001096 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001097 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001098 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001099 }
1100 }
Chris Wren92aa4232013-10-04 11:29:36 -04001101 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001102 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001103 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001104 try {
1105 inStream.close();
1106 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001107 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001108 }
1109 }
1110 return journal;
1111 }
1112
Sunny Goyalef728d42014-10-22 11:28:28 -07001113 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1114 throws IOException {
1115 writeRowToBackup(keyToBackupKey(key), proto, data);
1116 }
1117
1118 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001119 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001120 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001121 data.writeEntityHeader(backupKey, blob.length);
1122 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001123 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001124 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001125 }
1126
Chris Wren1ada10d2013-09-13 18:01:38 -04001127 /**
1128 * Write the new journal to the output file.
1129 *
1130 * In the event of any error, just pretend we didn't have a journal,
1131 * in that case, do a full backup.
1132
1133 * @param newState the write-only file descriptor pointing to the new journal
1134 * @param journal a Journal protocol buffer
1135 */
1136 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001137 try {
Sunny Goyalb740f592015-12-17 23:22:42 -08001138 FileOutputStream outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001139 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001140 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001141 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001142 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001143 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001144 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001145 }
1146 }
1147
1148 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1149 private byte[] writeCheckedBytes(MessageNano proto) {
1150 CheckedMessage wrapper = new CheckedMessage();
1151 wrapper.payload = MessageNano.toByteArray(proto);
1152 CRC32 checksum = new CRC32();
1153 checksum.update(wrapper.payload);
1154 wrapper.checksum = checksum.getValue();
1155 return MessageNano.toByteArray(wrapper);
1156 }
1157
1158 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001159 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001160 throws InvalidProtocolBufferNanoException {
1161 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001162 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001163 CRC32 checksum = new CRC32();
1164 checksum.update(wrapper.payload);
1165 if (wrapper.checksum != checksum.getValue()) {
1166 throw new InvalidProtocolBufferNanoException("checksum does not match");
1167 }
1168 return wrapper.payload;
1169 }
1170
Sunny Goyalef728d42014-10-22 11:28:28 -07001171 /**
1172 * @return true if the launcher is in a state to support backup
1173 */
Chris Wren71144262014-02-27 15:49:39 -05001174 private boolean launcherIsReady() {
1175 ContentResolver cr = mContext.getContentResolver();
1176 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1177 if (cursor == null) {
1178 // launcher data has been wiped, do nothing
1179 return false;
1180 }
1181 cursor.close();
1182
Adam Cohen2e6da152015-05-06 11:42:25 -07001183 if (LauncherAppState.getInstanceNoCreate() == null) {
Chris Wren71144262014-02-27 15:49:39 -05001184 // launcher services are unavailable, try again later
Chris Wren71144262014-02-27 15:49:39 -05001185 return false;
1186 }
1187
1188 return true;
1189 }
1190
Sunny Goyalffe83f12014-08-14 17:39:34 -07001191 private String getUserSelectionArg() {
1192 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1193 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1194 }
1195
Sunny Goyal316490e2015-06-02 09:38:28 -07001196 @Thunk class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001197
1198 private static final long serialVersionUID = 8931456637211665082L;
1199
Sunny Goyal316490e2015-06-02 09:38:28 -07001200 @Thunk InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001201 super(cause);
1202 }
1203
Sunny Goyal316490e2015-06-02 09:38:28 -07001204 @Thunk InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001205 super(reason);
1206 }
1207 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001208
Sunny Goyale5bb7052015-07-27 14:36:07 -07001209 public boolean shouldAttemptWorkspaceMigration() {
1210 return migrationCompatibleProfileData != null;
1211 }
1212
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001213 /**
1214 * A class to check if an activity can handle one of the intents from a list of
1215 * predefined intents.
1216 */
1217 private class ItemTypeMatcher {
1218
1219 private final ArrayList<Intent> mIntents;
1220
1221 ItemTypeMatcher(int xml_res) {
1222 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1223 }
1224
1225 private ArrayList<Intent> parseIntents(int xml_res) {
1226 ArrayList<Intent> intents = new ArrayList<Intent>();
1227 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1228 try {
1229 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1230 final int depth = parser.getDepth();
1231 int type;
1232 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1233 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1234 if (type != XmlPullParser.START_TAG) {
1235 continue;
1236 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1237 final String uri = DefaultLayoutParser.getAttributeValue(
1238 parser, DefaultLayoutParser.ATTR_URI);
1239 intents.add(Intent.parseUri(uri, 0));
1240 }
1241 }
1242 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1243 Log.e(TAG, "Unable to parse " + xml_res, e);
1244 } finally {
1245 parser.close();
1246 }
1247 return intents;
1248 }
1249
1250 public boolean matches(ActivityInfo activity, PackageManager pm) {
1251 for (Intent intent : mIntents) {
1252 intent.setPackage(activity.packageName);
1253 ResolveInfo info = pm.resolveActivity(intent, 0);
1254 if (info != null && (info.activityInfo.name.equals(activity.name)
1255 || info.activityInfo.name.equals(activity.targetActivity))) {
1256 return true;
1257 }
1258 }
1259 return false;
1260 }
1261 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001262}