blob: e987a9bdfa5333e2b7aa04b6624cd3bde054759b [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 Goyal2e1efb42016-03-03 16:58:55 -080053import com.android.launcher3.compat.AppWidgetManagerCompat;
Sunny Goyalef728d42014-10-22 11:28:28 -070054import com.android.launcher3.compat.UserHandleCompat;
55import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyalf862a262015-12-14 14:27:38 -080056import com.android.launcher3.model.GridSizeMigrationTask;
Sunny Goyal316490e2015-06-02 09:38:28 -070057import com.android.launcher3.util.Thunk;
Sunny Goyalef728d42014-10-22 11:28:28 -070058import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
59import com.google.protobuf.nano.MessageNano;
60
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080061import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63
Chris Wren1ada10d2013-09-13 18:01:38 -040064import java.io.FileInputStream;
65import java.io.FileOutputStream;
66import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040067import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040068import java.util.ArrayList;
Sunny Goyalc0ee6752015-01-16 14:10:32 -080069import java.util.Arrays;
Chris Wren1ada10d2013-09-13 18:01:38 -040070import java.util.HashSet;
Chris Wren1ada10d2013-09-13 18:01:38 -040071import java.util.zip.CRC32;
72
73/**
74 * Persist the launcher home state across calamities.
75 */
Chris Wren92aa4232013-10-04 11:29:36 -040076public class LauncherBackupHelper implements BackupHelper {
Chris Wren92aa4232013-10-04 11:29:36 -040077 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050078 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
79 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren1ada10d2013-09-13 18:01:38 -040080
Sunny Goyal107ea632015-07-20 12:59:39 -070081 private static final int BACKUP_VERSION = 4;
Chris Wren1ada10d2013-09-13 18:01:38 -040082 private static final int MAX_JOURNAL_SIZE = 1000000;
83
Sunny Goyal33d44382014-10-16 09:24:19 -070084 // Journal key is such that it is always smaller than any dynamically generated
85 // key (any Base64 encoded string).
86 private static final String JOURNAL_KEY = "#";
87
Chris Wrenfd13c712013-09-27 15:45:19 -040088 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040089 private static final int MAX_ICONS_PER_PASS = 10;
90
Chris Wrenfd13c712013-09-27 15:45:19 -040091 /** widgets contain previews, which are very large, dribble them out */
92 private static final int MAX_WIDGETS_PER_PASS = 5;
93
Chris Wren1ada10d2013-09-13 18:01:38 -040094 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070095 Favorites._ID, // 0
96 Favorites.MODIFIED, // 1
97 Favorites.INTENT, // 2
98 Favorites.APPWIDGET_PROVIDER, // 3
99 Favorites.APPWIDGET_ID, // 4
100 Favorites.CELLX, // 5
101 Favorites.CELLY, // 6
102 Favorites.CONTAINER, // 7
103 Favorites.ICON, // 8
104 Favorites.ICON_PACKAGE, // 9
105 Favorites.ICON_RESOURCE, // 10
Sunny Goyaleb4b7992016-04-21 14:30:18 -0700106 Favorites.ITEM_TYPE, // 11
107 Favorites.SCREEN, // 12
108 Favorites.SPANX, // 13
109 Favorites.SPANY, // 14
110 Favorites.TITLE, // 15
111 Favorites.PROFILE_ID, // 16
112 Favorites.RANK, // 17
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;
Sunny Goyaleb4b7992016-04-21 14:30:18 -0700126 private static final int ITEM_TYPE_INDEX = 11;
127 private static final int SCREEN_INDEX = 12;
128 private static final int SPANX_INDEX = 13;
129 private static final int SPANY_INDEX = 14;
130 private static final int TITLE_INDEX = 15;
131 private static final int RANK_INDEX = 17;
Chris Wren1ada10d2013-09-13 18:01:38 -0400132
133 private static final String[] SCREEN_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -0700134 WorkspaceScreens._ID, // 0
135 WorkspaceScreens.MODIFIED, // 1
136 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400137 };
138
Chris Wren22e130d2013-09-23 18:25:57 -0400139 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400140
Sunny Goyal316490e2015-06-02 09:38:28 -0700141 @Thunk final Context mContext;
Sunny Goyalef728d42014-10-22 11:28:28 -0700142 private final HashSet<String> mExistingKeys;
Sunny Goyal42de82f2014-09-26 22:09:29 -0700143 private final ArrayList<Key> mKeys;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800144 private final ItemTypeMatcher[] mItemTypeMatchers;
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800145 private final long mUserSerial;
Chris Wren1ada10d2013-09-13 18:01:38 -0400146
Sunny Goyalef728d42014-10-22 11:28:28 -0700147 private BackupManager mBackupManager;
Sunny Goyalef728d42014-10-22 11:28:28 -0700148 private byte[] mBuffer = new byte[512];
149 private long mLastBackupRestoreTime;
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800150 private boolean mBackupDataWasUpdated;
Sunny Goyalef728d42014-10-22 11:28:28 -0700151
Adam Cohen2e6da152015-05-06 11:42:25 -0700152 private IconCache mIconCache;
153 private DeviceProfieData mDeviceProfileData;
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700154 private InvariantDeviceProfile mIdp;
Adam Cohen2e6da152015-05-06 11:42:25 -0700155
Sunny Goyale5bb7052015-07-27 14:36:07 -0700156 DeviceProfieData migrationCompatibleProfileData;
157 HashSet<String> widgetSizes = new HashSet<>();
158
Sunny Goyal33d44382014-10-16 09:24:19 -0700159 boolean restoreSuccessful;
Sunny Goyal08f72612015-01-05 13:41:43 -0800160 int restoredBackupVersion = 1;
Sunny Goyal33d44382014-10-16 09:24:19 -0700161
Sunny Goyalc115e642015-07-20 14:23:43 -0700162 // When migrating from a device which different hotseat configuration, the icons are shifted
163 // to center along the new all-apps icon.
164 private int mHotseatShift = 0;
165
Sunny Goyal33d44382014-10-16 09:24:19 -0700166 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400167 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700168 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700169 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700170 restoreSuccessful = true;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800171 mItemTypeMatchers = new ItemTypeMatcher[CommonAppTypeParser.SUPPORTED_TYPE_COUNT];
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800172
173 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
174 mUserSerial = userManager.getSerialNumberForUser(UserHandleCompat.myUserHandle());
Chris Wren92aa4232013-10-04 11:29:36 -0400175 }
176
177 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700178 if (mBackupManager == null) {
179 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400180 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700181 mBackupManager.dataChanged();
182 }
183
184 private void applyJournal(Journal journal) {
185 mLastBackupRestoreTime = journal.t;
186 mExistingKeys.clear();
187 if (journal.key != null) {
188 for (Key key : journal.key) {
189 mExistingKeys.add(keyToBackupKey(key));
190 }
191 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700192 restoredBackupVersion = journal.backupVersion;
Chris Wren1ada10d2013-09-13 18:01:38 -0400193 }
194
195 /**
196 * Back up launcher data so we can restore the user's state on a new device.
197 *
198 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
199 *
200 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
201 *
202 * @param oldState notes from the last backup
203 * @param data incremental key/value pairs to persist off-device
204 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400205 */
206 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400207 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
208 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500209 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400210
211 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700212 if (!launcherIsReady()) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700213 dataChanged();
Sunny Goyalef728d42014-10-22 11:28:28 -0700214 // Perform backup later.
215 writeJournal(newState, in);
216 return;
217 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700218
Sunny Goyal96373642015-06-05 11:14:01 -0700219 if (mDeviceProfileData == null) {
220 LauncherAppState app = LauncherAppState.getInstance();
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700221 mIdp = app.getInvariantDeviceProfile();
222 mDeviceProfileData = initDeviceProfileData(mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700223 mIconCache = app.getIconCache();
224 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700225
Sunny Goyalef728d42014-10-22 11:28:28 -0700226 Log.v(TAG, "lastBackupTime = " + in.t);
227 mKeys.clear();
228 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400229
Sunny Goyalef728d42014-10-22 11:28:28 -0700230 // Record the time before performing backup so that entries edited while the backup
231 // was going on, do not get missed in next backup.
232 long newBackupTime = System.currentTimeMillis();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800233 mBackupDataWasUpdated = false;
Sunny Goyalef728d42014-10-22 11:28:28 -0700234 try {
235 backupFavorites(data);
236 backupScreens(data);
237 backupIcons(data);
238 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400239
Sunny Goyalef728d42014-10-22 11:28:28 -0700240 // Delete any key which still exist in the old backup, but is not valid anymore.
241 HashSet<String> validKeys = new HashSet<String>();
242 for (Key key : mKeys) {
243 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500244 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700245 mExistingKeys.removeAll(validKeys);
246
247 // Delete anything left in the existing keys.
248 for (String deleted: mExistingKeys) {
249 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
250 data.writeEntityHeader(deleted, -1);
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800251 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -0700252 }
253
254 mExistingKeys.clear();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800255 if (!mBackupDataWasUpdated) {
256 // Check if any metadata has changed
257 mBackupDataWasUpdated = (in.profile == null)
258 || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
Sunny Goyal96373642015-06-05 11:14:01 -0700259 DeviceProfieData.toByteArray(mDeviceProfileData))
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800260 || (in.backupVersion != BACKUP_VERSION)
261 || (in.appVersion != getAppVersion());
262 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700263
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800264 if (mBackupDataWasUpdated) {
265 mLastBackupRestoreTime = newBackupTime;
266
267 // We store the journal at two places.
268 // 1) Storing it in newState allows us to do partial backups by comparing old state
269 // 2) Storing it in backup data allows us to validate keys during restore
270 Journal state = getCurrentStateJournal();
271 writeRowToBackup(JOURNAL_KEY, state, data);
272 } else {
273 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
274 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700275 } catch (IOException e) {
276 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400277 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400278
Sunny Goyalef728d42014-10-22 11:28:28 -0700279 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400280 }
281
282 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700283 * @return true if the backup corresponding to oldstate can be successfully applied
284 * to this device.
285 */
286 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal96373642015-06-05 11:14:01 -0700287 DeviceProfieData currentProfile = mDeviceProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700288 DeviceProfieData oldProfile = oldState.profile;
289
290 if (oldProfile == null || oldProfile.desktopCols == 0) {
291 // Profile info is not valid, ignore the check.
292 return true;
293 }
294
Sunny Goyale5bb7052015-07-27 14:36:07 -0700295 boolean isHotseatCompatible = false;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700296 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
Sunny Goyale5bb7052015-07-27 14:36:07 -0700297 isHotseatCompatible = true;
Sunny Goyalc115e642015-07-20 14:23:43 -0700298 mHotseatShift = 0;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700299 }
Sunny Goyalc115e642015-07-20 14:23:43 -0700300
301 if ((currentProfile.allappsRank >= oldProfile.allappsRank)
302 && ((currentProfile.hotseatCount - currentProfile.allappsRank) >=
303 (oldProfile.hotseatCount - oldProfile.allappsRank))) {
304 // There is enough space on both sides of the hotseat.
Sunny Goyale5bb7052015-07-27 14:36:07 -0700305 isHotseatCompatible = true;
Sunny Goyalc115e642015-07-20 14:23:43 -0700306 mHotseatShift = currentProfile.allappsRank - oldProfile.allappsRank;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700307 }
308
Sunny Goyale5bb7052015-07-27 14:36:07 -0700309 if (!isHotseatCompatible) {
310 return false;
311 }
312 if ((currentProfile.desktopCols >= oldProfile.desktopCols)
313 && (currentProfile.desktopRows >= oldProfile.desktopRows)) {
314 return true;
315 }
316
Sunny Goyalf076eae2016-01-11 12:25:10 -0800317 if (GridSizeMigrationTask.ENABLED) {
318 // One time migrate the workspace when launcher starts.
Sunny Goyale5bb7052015-07-27 14:36:07 -0700319 migrationCompatibleProfileData = initDeviceProfileData(mIdp);
320 migrationCompatibleProfileData.desktopCols = oldProfile.desktopCols;
321 migrationCompatibleProfileData.desktopRows = oldProfile.desktopRows;
Sunny Goyalf076eae2016-01-11 12:25:10 -0800322 migrationCompatibleProfileData.hotseatCount = oldProfile.hotseatCount;
323 migrationCompatibleProfileData.allappsRank = oldProfile.allappsRank;
Sunny Goyale5bb7052015-07-27 14:36:07 -0700324 return true;
325 }
326 return false;
Sunny Goyal33d44382014-10-16 09:24:19 -0700327 }
328
329 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400330 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700331 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
332 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400333 *
Chris Wren92aa4232013-10-04 11:29:36 -0400334 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400335 */
336 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400337 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700338 if (!restoreSuccessful) {
339 return;
340 }
Sunny Goyal96373642015-06-05 11:14:01 -0700341
342 if (mDeviceProfileData == null) {
343 // This call does not happen on a looper thread. So LauncherAppState
344 // can't be created . Instead initialize required dependencies directly.
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700345 mIdp = new InvariantDeviceProfile(mContext);
346 mDeviceProfileData = initDeviceProfileData(mIdp);
347 mIconCache = new IconCache(mContext, mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700348 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700349
Sunny Goyalef728d42014-10-22 11:28:28 -0700350 int dataSize = data.size();
351 if (mBuffer.length < dataSize) {
352 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400353 }
354 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700355 int bytesRead = data.read(mBuffer, 0, dataSize);
356 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
357 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700358
359 if (JOURNAL_KEY.equals(backupKey)) {
360 if (VERBOSE) Log.v(TAG, "Journal entry restored");
361 if (!mKeys.isEmpty()) {
362 // We received the journal key after a restore key.
363 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
364 restoreSuccessful = false;
365 return;
366 }
367
368 Journal journal = new Journal();
369 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
370 applyJournal(journal);
371 restoreSuccessful = isBackupCompatible(journal);
372 return;
373 }
374
375 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
376 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
377 return;
378 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700379 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500380 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400381 switch (key.type) {
382 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700383 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400384 break;
385
386 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700387 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400388 break;
389
390 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700391 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400392 break;
393
394 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700395 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400396 break;
397
398 default:
399 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700400 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400401 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400402 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700403 } catch (IOException e) {
404 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400405 }
Chris Wren92aa4232013-10-04 11:29:36 -0400406 }
407
408 /**
409 * Record the restore state for the next backup.
410 *
411 * @param newState notes about the backup state after restore.
412 */
413 @Override
414 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700415 writeJournal(newState, getCurrentStateJournal());
416 }
417
418 private Journal getCurrentStateJournal() {
419 Journal journal = new Journal();
420 journal.t = mLastBackupRestoreTime;
421 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
422 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700423 journal.backupVersion = BACKUP_VERSION;
Sunny Goyal96373642015-06-05 11:14:01 -0700424 journal.profile = mDeviceProfileData;
Sunny Goyalef728d42014-10-22 11:28:28 -0700425 return journal;
426 }
427
428 private int getAppVersion() {
429 try {
430 return mContext.getPackageManager()
431 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
432 } catch (NameNotFoundException e) {
433 return 0;
434 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400435 }
436
Adam Cohen2e6da152015-05-06 11:42:25 -0700437 private DeviceProfieData initDeviceProfileData(InvariantDeviceProfile profile) {
438 DeviceProfieData data = new DeviceProfieData();
439 data.desktopRows = profile.numRows;
440 data.desktopCols = profile.numColumns;
441 data.hotseatCount = profile.numHotseatIcons;
Adam Cohen2e6da152015-05-06 11:42:25 -0700442 return data;
Sunny Goyal33d44382014-10-16 09:24:19 -0700443 }
444
445 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400446 * Write all modified favorites to the data stream.
447 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400448 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400449 * @throws IOException
450 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700451 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400452 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400453 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700454 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400455 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700456 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400457 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400458 cursor.moveToPosition(-1);
459 while(cursor.moveToNext()) {
460 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700461 final long updateTime = cursor.getLong(ID_MODIFIED);
462 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700463 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700464 final String backupKey = keyToBackupKey(key);
Sunny Goyal107ea632015-07-20 12:59:39 -0700465
466 // Favorite proto changed in v4. Backup again if the version is old.
467 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime
468 || restoredBackupVersion < 4) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700469 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500470 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700471 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400472 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400473 }
474 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400475 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400476 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400477 }
478
479 /**
480 * Read a favorite from the stream.
481 *
482 * <P>Keys arrive in any order, so screens and containers may not exist yet.
483 *
484 * @param key identifier for the row
485 * @param buffer the serialized proto from the stream, may be larger than dataSize
486 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400487 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700488 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500489 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400490 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
491 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
492
Sunny Goyalef728d42014-10-22 11:28:28 -0700493 ContentResolver cr = mContext.getContentResolver();
494 ContentValues values = unpackFavorite(buffer, dataSize);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700495 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400496 }
497
498 /**
499 * Write all modified screens to the data stream.
500 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400501 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400502 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400503 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700504 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400505 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400506 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400507 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
508 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400509 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400510 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700511 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400512 while(cursor.moveToNext()) {
513 final long id = cursor.getLong(ID_INDEX);
514 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400515 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700516 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500517 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700518 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
519 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500520 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700521 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400522 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400523 }
524 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400525 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400526 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400527 }
528
529 /**
530 * Read a screen from the stream.
531 *
532 * <P>Keys arrive in any order, so children of this screen may already exist.
533 *
534 * @param key identifier for the row
535 * @param buffer the serialized proto from the stream, may be larger than dataSize
536 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400537 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700538 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500539 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400540 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
541 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500542
Sunny Goyalef728d42014-10-22 11:28:28 -0700543 ContentResolver cr = mContext.getContentResolver();
544 ContentValues values = unpackScreen(buffer, dataSize);
545 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400546 }
547
Chris Wren22e130d2013-09-23 18:25:57 -0400548 /**
549 * Write all the static icon resources we need to render placeholders
550 * for a package that is not installed.
551 *
Chris Wren22e130d2013-09-23 18:25:57 -0400552 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400553 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700554 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400555 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400556 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400557 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700558 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700559 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400560
Kenny Guyed131872014-04-30 03:02:21 +0100561 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100562 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700563 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + " OR " +
564 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_DEEP_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700565 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400566 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
567 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400568 try {
569 cursor.moveToPosition(-1);
570 while(cursor.moveToNext()) {
571 final long id = cursor.getLong(ID_INDEX);
572 final String intentDescription = cursor.getString(INTENT_INDEX);
573 try {
574 Intent intent = Intent.parseUri(intentDescription, 0);
575 ComponentName cn = intent.getComponent();
576 Key key = null;
577 String backupKey = null;
578 if (cn != null) {
579 key = getKey(Key.ICON, cn.flattenToShortString());
580 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400581 } else {
582 Log.w(TAG, "empty intent on application favorite: " + id);
583 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700584 if (mExistingKeys.contains(backupKey)) {
585 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400586
587 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700588 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400589 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700590 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
591 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
592 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100593 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100594 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700595 writeRowToBackup(key, packIcon(dpi, icon), data);
596 mKeys.add(key);
597 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400598 }
599 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700600 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400601 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400602 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400603 }
604 }
605 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500606 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400607 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500608 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400609 }
610
611 }
612 } finally {
613 cursor.close();
614 }
Chris Wren22e130d2013-09-23 18:25:57 -0400615 }
616
617 /**
618 * Read an icon from the stream.
619 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400620 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400621 *
622 * @param key identifier for the row
623 * @param buffer the serialized proto from the stream, may be larger than dataSize
624 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400625 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700626 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500627 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400628 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
629 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500630
Sunny Goyalef728d42014-10-22 11:28:28 -0700631 Resource res = unpackProto(new Resource(), buffer, dataSize);
632 if (DEBUG) {
633 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400634 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700635 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
636 if (icon == null) {
637 Log.w(TAG, "failed to unpack icon for " + key.name);
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700638 } else {
639 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
640 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
641 "" /* label */, mUserSerial, mIdp);
Sunny Goyalef728d42014-10-22 11:28:28 -0700642 }
Chris Wren22e130d2013-09-23 18:25:57 -0400643 }
644
Chris Wrenfd13c712013-09-27 15:45:19 -0400645 /**
646 * Write all the static widget resources we need to render placeholders
647 * for a package that is not installed.
648 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400649 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400650 * @throws IOException
651 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700652 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400653 // persist static widget info that hasn't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400654 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400655 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalef728d42014-10-22 11:28:28 -0700656 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400657
Sunny Goyalffe83f12014-08-14 17:39:34 -0700658 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
659 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400660 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
661 where, null, null);
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800662 AppWidgetManagerCompat widgetManager = AppWidgetManagerCompat.getInstance(mContext);
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);
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800669
Chris Wrenfd13c712013-09-27 15:45:19 -0400670 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) {
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800688 LauncherAppWidgetProviderInfo widgetInfo = widgetManager
689 .getLauncherAppWidgetInfo(cursor.getInt(APPWIDGET_ID_INDEX));
690 if (widgetInfo != null) {
691 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
692 writeRowToBackup(key, packWidget(dpi, widgetInfo), data);
693 mKeys.add(key);
694 backupWidgetCount ++;
695 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400696 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700697 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400698 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400699 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400700 }
701 }
702 }
703 } finally {
704 cursor.close();
705 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400706 }
707
708 /**
709 * Read a widget from the stream.
710 *
711 * <P>Keys arrive in any order, so widgets that use this data may already exist.
712 *
713 * @param key identifier for the row
714 * @param buffer the serialized proto from the stream, may be larger than dataSize
715 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400716 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700717 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500718 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400719 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
720 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700721 Widget widget = unpackProto(new Widget(), buffer, dataSize);
722 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
723 if (widget.icon.data != null) {
724 Bitmap icon = BitmapFactory
725 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
726 if (icon == null) {
727 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500728 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800729 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700730 icon, widget.icon.dpi, widget.label, mUserSerial, mIdp);
Chris Wren5dee7af2013-12-20 17:22:11 -0500731 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400732 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700733
Sunny Goyale5bb7052015-07-27 14:36:07 -0700734 // Cache widget min sizes incase migration is required.
735 widgetSizes.add(widget.provider + "#" + widget.minSpanX + "," + widget.minSpanY);
Chris Wrenfd13c712013-09-27 15:45:19 -0400736 }
737
Chris Wren22e130d2013-09-23 18:25:57 -0400738 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400739 *
740 * <P> Keys contain their own checksum instead of using
741 * the heavy-weight CheckedMessage wrapper.
742 */
743 private Key getKey(int type, long id) {
744 Key key = new Key();
745 key.type = type;
746 key.id = id;
747 key.checksum = checkKey(key);
748 return key;
749 }
750
Chris Wren22e130d2013-09-23 18:25:57 -0400751 /** create a new key for a named object.
752 *
753 * <P> Keys contain their own checksum instead of using
754 * the heavy-weight CheckedMessage wrapper.
755 */
756 private Key getKey(int type, String name) {
757 Key key = new Key();
758 key.type = type;
759 key.name = name;
760 key.checksum = checkKey(key);
761 return key;
762 }
763
Chris Wren1ada10d2013-09-13 18:01:38 -0400764 /** keys need to be strings, serialize and encode. */
765 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400766 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400767 }
768
769 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700770 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400771 try {
772 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
773 if (key.checksum != checkKey(key)) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700774 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400775 }
776 return key;
Sunny Goyalb740f592015-12-17 23:22:42 -0800777 } catch (InvalidProtocolBufferNanoException | IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700778 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400779 }
780 }
781
782 /** Compute the checksum over the important bits of a key. */
783 private long checkKey(Key key) {
784 CRC32 checksum = new CRC32();
785 checksum.update(key.type);
786 checksum.update((int) (key.id & 0xffff));
787 checksum.update((int) ((key.id >> 32) & 0xffff));
788 if (!TextUtils.isEmpty(key.name)) {
789 checksum.update(key.name.getBytes());
790 }
791 return checksum.getValue();
792 }
793
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800794 /**
795 * @return true if its an hotseat item, that can be replaced during restore.
796 * TODO: Extend check for folders in hotseat.
797 */
798 private boolean isReplaceableHotseatItem(Favorite favorite) {
799 return favorite.container == Favorites.CONTAINER_HOTSEAT
800 && favorite.intent != null
801 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700802 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT
803 || favorite.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800804 }
805
Chris Wren1ada10d2013-09-13 18:01:38 -0400806 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700807 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400808 Favorite favorite = new Favorite();
809 favorite.id = c.getLong(ID_INDEX);
810 favorite.screen = c.getInt(SCREEN_INDEX);
811 favorite.container = c.getInt(CONTAINER_INDEX);
812 favorite.cellX = c.getInt(CELLX_INDEX);
813 favorite.cellY = c.getInt(CELLY_INDEX);
814 favorite.spanX = c.getInt(SPANX_INDEX);
815 favorite.spanY = c.getInt(SPANY_INDEX);
Sunny Goyal107ea632015-07-20 12:59:39 -0700816 favorite.rank = c.getInt(RANK_INDEX);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700817
Chris Wren1ada10d2013-09-13 18:01:38 -0400818 String title = c.getString(TITLE_INDEX);
819 if (!TextUtils.isEmpty(title)) {
820 favorite.title = title;
821 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100822 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800823 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100824 if (!TextUtils.isEmpty(intentDescription)) {
825 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800826 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100827 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
828 favorite.intent = intent.toUri(0);
829 } catch (URISyntaxException e) {
830 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700831 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400832 }
833 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
834 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
835 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
836 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
837 if (!TextUtils.isEmpty(appWidgetProvider)) {
838 favorite.appWidgetProvider = appWidgetProvider;
839 }
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700840 } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT
841 || favorite.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
Sunny Goyaleb4b7992016-04-21 14:30:18 -0700842 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
843 String iconResource = c.getString(ICON_RESOURCE_INDEX);
844 if (!TextUtils.isEmpty(iconPackage) && !TextUtils.isEmpty(iconResource)) {
845 favorite.iconResource = iconResource;
846 favorite.iconPackage = iconPackage;
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700847 }
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
Tony Wickhambfbf7f92016-05-19 11:19:39 -0700903 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT
904 || favorite.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT) {
Sunny Goyaleb4b7992016-04-21 14:30:18 -0700905 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
906 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
Chris Wren5dee7af2013-12-20 17:22:11 -0500907 values.put(Favorites.ICON, favorite.icon);
908 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700909
Chris Wren5dee7af2013-12-20 17:22:11 -0500910 if (!TextUtils.isEmpty(favorite.title)) {
911 values.put(Favorites.TITLE, favorite.title);
912 } else {
913 values.put(Favorites.TITLE, "");
914 }
915 if (!TextUtils.isEmpty(favorite.intent)) {
916 values.put(Favorites.INTENT, favorite.intent);
917 }
918 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500919
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100920 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
921 long userSerialNumber =
922 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
923 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
924
Sunny Goyale5bb7052015-07-27 14:36:07 -0700925 // If we will attempt grid resize, use the original profile to validate grid size, as
926 // anything which fits in the original grid should fit in the current grid after
927 // grid migration.
928 DeviceProfieData currentProfile = migrationCompatibleProfileData == null
929 ? mDeviceProfileData : migrationCompatibleProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700930
Sunny Goyalff572272014-07-23 13:58:07 -0700931 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
932 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
933 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
934 }
935 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
936 values.put(LauncherSettings.Favorites.RESTORED,
937 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
938 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
939 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700940
941 // Verify placement
942 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
943 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
944 restoreSuccessful = false;
945 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
946 }
Sunny Goyalff572272014-07-23 13:58:07 -0700947 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800948 // Check if it is an hotseat item, that can be replaced.
949 if (isReplaceableHotseatItem(favorite)
950 && favorite.targetType != Favorite.TARGET_NONE
951 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
952 Log.e(TAG, "Added item type flag");
953 values.put(LauncherSettings.Favorites.RESTORED,
954 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
955 } else {
956 // Let LauncherModel know we've been here.
957 values.put(LauncherSettings.Favorites.RESTORED, 1);
958 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700959
960 // Verify placement
961 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
962 if ((favorite.screen >= currentProfile.hotseatCount)
963 || (favorite.screen == currentProfile.allappsRank)) {
964 restoreSuccessful = false;
965 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
966 }
967 } else {
968 if ((favorite.cellX >= currentProfile.desktopCols)
969 || (favorite.cellY >= currentProfile.desktopRows)) {
970 restoreSuccessful = false;
971 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
972 }
973 }
Sunny Goyalff572272014-07-23 13:58:07 -0700974 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500975
Chris Wren5dee7af2013-12-20 17:22:11 -0500976 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400977 }
978
979 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700980 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400981 Screen screen = new Screen();
982 screen.id = c.getLong(ID_INDEX);
983 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700984 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400985 }
986
987 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700988 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400989 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700990 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500991 ContentValues values = new ContentValues();
992 values.put(WorkspaceScreens._ID, screen.id);
993 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
994 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400995 }
996
Chris Wren22e130d2013-09-23 18:25:57 -0400997 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700998 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400999 Resource res = new Resource();
1000 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -07001001 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -04001002 return res;
1003 }
1004
Chris Wrenfd13c712013-09-27 15:45:19 -04001005 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001006 private Widget packWidget(int dpi, LauncherAppWidgetProviderInfo info) {
Chris Wrenfd13c712013-09-27 15:45:19 -04001007 Widget widget = new Widget();
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001008 widget.provider = info.provider.flattenToShortString();
Chris Wrenfd13c712013-09-27 15:45:19 -04001009 widget.label = info.label;
1010 widget.configure = info.configure != null;
1011 if (info.icon != 0) {
1012 widget.icon = new Resource();
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001013 Drawable fullResIcon = mIconCache.getFullResIcon(info.provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -04001014 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -07001015 widget.icon.data = Utilities.flattenBitmap(icon);
1016 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -04001017 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001018
Sunny Goyale5bb7052015-07-27 14:36:07 -07001019 Point spans = info.getMinSpans(mIdp, mContext);
1020 widget.minSpanX = spans.x;
1021 widget.minSpanY = spans.y;
Sunny Goyalef728d42014-10-22 11:28:28 -07001022 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001023 }
1024
Sunny Goyalef728d42014-10-22 11:28:28 -07001025 /**
1026 * Deserialize a proto after verifying checksum wrapper.
1027 */
1028 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001029 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001030 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1031 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1032 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001033 }
1034
Chris Wren1ada10d2013-09-13 18:01:38 -04001035 /**
1036 * Read the old journal from the input file.
1037 *
1038 * In the event of any error, just pretend we didn't have a journal,
1039 * in that case, do a full backup.
1040 *
1041 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001042 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001043 */
1044 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001045 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001046 if (oldState == null) {
1047 return journal;
1048 }
1049 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1050 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001051 int availableBytes = inStream.available();
1052 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1053 if (availableBytes < MAX_JOURNAL_SIZE) {
1054 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001055 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001056 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001057 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001058 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001059 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001060 // OMG what are you doing? This is crazy inefficient!
1061 // If we read a byte that is not ours, we will cause trouble: b/12491813
1062 // However, we don't know how many bytes to expect (oops).
1063 // So we have to step through *slowly*, watching for the end.
1064 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001065 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001066 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001067 bytesRead += result;
1068 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001069 Log.w(TAG, "unexpected end of file while reading journal.");
1070 // stop reading and see what there is to parse
1071 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001072 }
1073 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001074 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001075 availableBytes = 0;
1076 }
1077
1078 // check the buffer to see if we have a valid journal
1079 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001080 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001081 // if we are here, then we have read a valid, checksum-verified journal
1082 valid = true;
1083 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001084 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001085 } catch (InvalidProtocolBufferNanoException e) {
1086 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001087 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001088 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001089 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001090 }
Chris Wren92aa4232013-10-04 11:29:36 -04001091 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001092 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001093 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001094 }
1095 }
Chris Wren92aa4232013-10-04 11:29:36 -04001096 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001097 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001098 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001099 try {
1100 inStream.close();
1101 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001102 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001103 }
1104 }
1105 return journal;
1106 }
1107
Sunny Goyalef728d42014-10-22 11:28:28 -07001108 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1109 throws IOException {
1110 writeRowToBackup(keyToBackupKey(key), proto, data);
1111 }
1112
1113 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001114 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001115 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001116 data.writeEntityHeader(backupKey, blob.length);
1117 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001118 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001119 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001120 }
1121
Chris Wren1ada10d2013-09-13 18:01:38 -04001122 /**
1123 * Write the new journal to the output file.
1124 *
1125 * In the event of any error, just pretend we didn't have a journal,
1126 * in that case, do a full backup.
1127
1128 * @param newState the write-only file descriptor pointing to the new journal
1129 * @param journal a Journal protocol buffer
1130 */
1131 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001132 try {
Sunny Goyalb740f592015-12-17 23:22:42 -08001133 FileOutputStream outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001134 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001135 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001136 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001137 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001138 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001139 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001140 }
1141 }
1142
1143 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1144 private byte[] writeCheckedBytes(MessageNano proto) {
1145 CheckedMessage wrapper = new CheckedMessage();
1146 wrapper.payload = MessageNano.toByteArray(proto);
1147 CRC32 checksum = new CRC32();
1148 checksum.update(wrapper.payload);
1149 wrapper.checksum = checksum.getValue();
1150 return MessageNano.toByteArray(wrapper);
1151 }
1152
1153 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001154 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001155 throws InvalidProtocolBufferNanoException {
1156 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001157 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001158 CRC32 checksum = new CRC32();
1159 checksum.update(wrapper.payload);
1160 if (wrapper.checksum != checksum.getValue()) {
1161 throw new InvalidProtocolBufferNanoException("checksum does not match");
1162 }
1163 return wrapper.payload;
1164 }
1165
Sunny Goyalef728d42014-10-22 11:28:28 -07001166 /**
1167 * @return true if the launcher is in a state to support backup
1168 */
Chris Wren71144262014-02-27 15:49:39 -05001169 private boolean launcherIsReady() {
1170 ContentResolver cr = mContext.getContentResolver();
1171 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1172 if (cursor == null) {
1173 // launcher data has been wiped, do nothing
1174 return false;
1175 }
1176 cursor.close();
1177
Adam Cohen2e6da152015-05-06 11:42:25 -07001178 if (LauncherAppState.getInstanceNoCreate() == null) {
Chris Wren71144262014-02-27 15:49:39 -05001179 // launcher services are unavailable, try again later
Chris Wren71144262014-02-27 15:49:39 -05001180 return false;
1181 }
1182
1183 return true;
1184 }
1185
Sunny Goyalffe83f12014-08-14 17:39:34 -07001186 private String getUserSelectionArg() {
1187 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1188 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1189 }
1190
Sunny Goyal316490e2015-06-02 09:38:28 -07001191 @Thunk class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001192
1193 private static final long serialVersionUID = 8931456637211665082L;
1194
Sunny Goyal316490e2015-06-02 09:38:28 -07001195 @Thunk InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001196 super(cause);
1197 }
1198
Sunny Goyal316490e2015-06-02 09:38:28 -07001199 @Thunk InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001200 super(reason);
1201 }
1202 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001203
Sunny Goyale5bb7052015-07-27 14:36:07 -07001204 public boolean shouldAttemptWorkspaceMigration() {
1205 return migrationCompatibleProfileData != null;
1206 }
1207
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001208 /**
1209 * A class to check if an activity can handle one of the intents from a list of
1210 * predefined intents.
1211 */
1212 private class ItemTypeMatcher {
1213
1214 private final ArrayList<Intent> mIntents;
1215
1216 ItemTypeMatcher(int xml_res) {
1217 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1218 }
1219
1220 private ArrayList<Intent> parseIntents(int xml_res) {
1221 ArrayList<Intent> intents = new ArrayList<Intent>();
1222 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1223 try {
1224 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1225 final int depth = parser.getDepth();
1226 int type;
1227 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1228 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1229 if (type != XmlPullParser.START_TAG) {
1230 continue;
1231 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1232 final String uri = DefaultLayoutParser.getAttributeValue(
1233 parser, DefaultLayoutParser.ATTR_URI);
1234 intents.add(Intent.parseUri(uri, 0));
1235 }
1236 }
1237 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1238 Log.e(TAG, "Unable to parse " + xml_res, e);
1239 } finally {
1240 parser.close();
1241 }
1242 return intents;
1243 }
1244
1245 public boolean matches(ActivityInfo activity, PackageManager pm) {
1246 for (Intent intent : mIntents) {
1247 intent.setPackage(activity.packageName);
1248 ResolveInfo info = pm.resolveActivity(intent, 0);
1249 if (info != null && (info.activityInfo.name.equals(activity.name)
1250 || info.activityInfo.name.equals(activity.targetActivity))) {
1251 return true;
1252 }
1253 }
1254 return false;
1255 }
1256 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001257}