blob: bca2ffbe06353cdcc661836dae20447487991f7a [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 " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100563 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700564 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400565 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
566 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400567 try {
568 cursor.moveToPosition(-1);
569 while(cursor.moveToNext()) {
570 final long id = cursor.getLong(ID_INDEX);
571 final String intentDescription = cursor.getString(INTENT_INDEX);
572 try {
573 Intent intent = Intent.parseUri(intentDescription, 0);
574 ComponentName cn = intent.getComponent();
575 Key key = null;
576 String backupKey = null;
577 if (cn != null) {
578 key = getKey(Key.ICON, cn.flattenToShortString());
579 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400580 } else {
581 Log.w(TAG, "empty intent on application favorite: " + id);
582 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700583 if (mExistingKeys.contains(backupKey)) {
584 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400585
586 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700587 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400588 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700589 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
590 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
591 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100592 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100593 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700594 writeRowToBackup(key, packIcon(dpi, icon), data);
595 mKeys.add(key);
596 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400597 }
598 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700599 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400600 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400601 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400602 }
603 }
604 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500605 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400606 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500607 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400608 }
609
610 }
611 } finally {
612 cursor.close();
613 }
Chris Wren22e130d2013-09-23 18:25:57 -0400614 }
615
616 /**
617 * Read an icon from the stream.
618 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400619 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400620 *
621 * @param key identifier for the row
622 * @param buffer the serialized proto from the stream, may be larger than dataSize
623 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400624 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700625 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500626 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400627 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
628 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500629
Sunny Goyalef728d42014-10-22 11:28:28 -0700630 Resource res = unpackProto(new Resource(), buffer, dataSize);
631 if (DEBUG) {
632 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400633 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700634 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
635 if (icon == null) {
636 Log.w(TAG, "failed to unpack icon for " + key.name);
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700637 } else {
638 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
639 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
640 "" /* label */, mUserSerial, mIdp);
Sunny Goyalef728d42014-10-22 11:28:28 -0700641 }
Chris Wren22e130d2013-09-23 18:25:57 -0400642 }
643
Chris Wrenfd13c712013-09-27 15:45:19 -0400644 /**
645 * Write all the static widget resources we need to render placeholders
646 * for a package that is not installed.
647 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400648 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400649 * @throws IOException
650 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700651 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400652 // persist static widget info that hasn't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400653 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400654 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalef728d42014-10-22 11:28:28 -0700655 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400656
Sunny Goyalffe83f12014-08-14 17:39:34 -0700657 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
658 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400659 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
660 where, null, null);
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800661 AppWidgetManagerCompat widgetManager = AppWidgetManagerCompat.getInstance(mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400662 try {
663 cursor.moveToPosition(-1);
664 while(cursor.moveToNext()) {
665 final long id = cursor.getLong(ID_INDEX);
666 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
Chris Wrenfd13c712013-09-27 15:45:19 -0400667 final ComponentName provider = ComponentName.unflattenFromString(providerName);
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800668
Chris Wrenfd13c712013-09-27 15:45:19 -0400669 Key key = null;
670 String backupKey = null;
671 if (provider != null) {
672 key = getKey(Key.WIDGET, providerName);
673 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400674 } else {
675 Log.w(TAG, "empty intent on appwidget: " + id);
676 }
Sunny Goyal107ea632015-07-20 12:59:39 -0700677
678 // Widget backup proto changed in v3. So add it again if the original backup is old.
679 if (mExistingKeys.contains(backupKey) && restoredBackupVersion >= 3) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700680 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400681
682 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700683 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400684 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700685 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
686 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800687 LauncherAppWidgetProviderInfo widgetInfo = widgetManager
688 .getLauncherAppWidgetInfo(cursor.getInt(APPWIDGET_ID_INDEX));
689 if (widgetInfo != null) {
690 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
691 writeRowToBackup(key, packWidget(dpi, widgetInfo), data);
692 mKeys.add(key);
693 backupWidgetCount ++;
694 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400695 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700696 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400697 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400698 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400699 }
700 }
701 }
702 } finally {
703 cursor.close();
704 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400705 }
706
707 /**
708 * Read a widget from the stream.
709 *
710 * <P>Keys arrive in any order, so widgets that use this data may already exist.
711 *
712 * @param key identifier for the row
713 * @param buffer the serialized proto from the stream, may be larger than dataSize
714 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400715 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700716 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500717 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400718 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
719 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700720 Widget widget = unpackProto(new Widget(), buffer, dataSize);
721 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
722 if (widget.icon.data != null) {
723 Bitmap icon = BitmapFactory
724 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
725 if (icon == null) {
726 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500727 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800728 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700729 icon, widget.icon.dpi, widget.label, mUserSerial, mIdp);
Chris Wren5dee7af2013-12-20 17:22:11 -0500730 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400731 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700732
Sunny Goyale5bb7052015-07-27 14:36:07 -0700733 // Cache widget min sizes incase migration is required.
734 widgetSizes.add(widget.provider + "#" + widget.minSpanX + "," + widget.minSpanY);
Chris Wrenfd13c712013-09-27 15:45:19 -0400735 }
736
Chris Wren22e130d2013-09-23 18:25:57 -0400737 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400738 *
739 * <P> Keys contain their own checksum instead of using
740 * the heavy-weight CheckedMessage wrapper.
741 */
742 private Key getKey(int type, long id) {
743 Key key = new Key();
744 key.type = type;
745 key.id = id;
746 key.checksum = checkKey(key);
747 return key;
748 }
749
Chris Wren22e130d2013-09-23 18:25:57 -0400750 /** create a new key for a named object.
751 *
752 * <P> Keys contain their own checksum instead of using
753 * the heavy-weight CheckedMessage wrapper.
754 */
755 private Key getKey(int type, String name) {
756 Key key = new Key();
757 key.type = type;
758 key.name = name;
759 key.checksum = checkKey(key);
760 return key;
761 }
762
Chris Wren1ada10d2013-09-13 18:01:38 -0400763 /** keys need to be strings, serialize and encode. */
764 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400765 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400766 }
767
768 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700769 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400770 try {
771 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
772 if (key.checksum != checkKey(key)) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700773 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400774 }
775 return key;
Sunny Goyalb740f592015-12-17 23:22:42 -0800776 } catch (InvalidProtocolBufferNanoException | IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700777 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400778 }
779 }
780
781 /** Compute the checksum over the important bits of a key. */
782 private long checkKey(Key key) {
783 CRC32 checksum = new CRC32();
784 checksum.update(key.type);
785 checksum.update((int) (key.id & 0xffff));
786 checksum.update((int) ((key.id >> 32) & 0xffff));
787 if (!TextUtils.isEmpty(key.name)) {
788 checksum.update(key.name.getBytes());
789 }
790 return checksum.getValue();
791 }
792
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800793 /**
794 * @return true if its an hotseat item, that can be replaced during restore.
795 * TODO: Extend check for folders in hotseat.
796 */
797 private boolean isReplaceableHotseatItem(Favorite favorite) {
798 return favorite.container == Favorites.CONTAINER_HOTSEAT
799 && favorite.intent != null
800 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
801 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
802 }
803
Chris Wren1ada10d2013-09-13 18:01:38 -0400804 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700805 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400806 Favorite favorite = new Favorite();
807 favorite.id = c.getLong(ID_INDEX);
808 favorite.screen = c.getInt(SCREEN_INDEX);
809 favorite.container = c.getInt(CONTAINER_INDEX);
810 favorite.cellX = c.getInt(CELLX_INDEX);
811 favorite.cellY = c.getInt(CELLY_INDEX);
812 favorite.spanX = c.getInt(SPANX_INDEX);
813 favorite.spanY = c.getInt(SPANY_INDEX);
Sunny Goyal107ea632015-07-20 12:59:39 -0700814 favorite.rank = c.getInt(RANK_INDEX);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700815
Chris Wren1ada10d2013-09-13 18:01:38 -0400816 String title = c.getString(TITLE_INDEX);
817 if (!TextUtils.isEmpty(title)) {
818 favorite.title = title;
819 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100820 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800821 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100822 if (!TextUtils.isEmpty(intentDescription)) {
823 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800824 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100825 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
826 favorite.intent = intent.toUri(0);
827 } catch (URISyntaxException e) {
828 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700829 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400830 }
831 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
832 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
833 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
834 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
835 if (!TextUtils.isEmpty(appWidgetProvider)) {
836 favorite.appWidgetProvider = appWidgetProvider;
837 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700838 } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
Sunny Goyaleb4b7992016-04-21 14:30:18 -0700839 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
840 String iconResource = c.getString(ICON_RESOURCE_INDEX);
841 if (!TextUtils.isEmpty(iconPackage) && !TextUtils.isEmpty(iconResource)) {
842 favorite.iconResource = iconResource;
843 favorite.iconPackage = iconPackage;
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700844 }
845
846 byte[] blob = c.getBlob(ICON_INDEX);
847 if (blob != null && blob.length > 0) {
848 favorite.icon = blob;
849 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400850 }
851
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800852 if (isReplaceableHotseatItem(favorite)) {
853 if (intent != null && intent.getComponent() != null) {
854 PackageManager pm = mContext.getPackageManager();
855 ActivityInfo activity = null;;
856 try {
857 activity = pm.getActivityInfo(intent.getComponent(), 0);
858 } catch (NameNotFoundException e) {
859 Log.e(TAG, "Target not found", e);
860 }
861 if (activity == null) {
862 return favorite;
863 }
864 for (int i = 0; i < mItemTypeMatchers.length; i++) {
865 if (mItemTypeMatchers[i] == null) {
866 mItemTypeMatchers[i] = new ItemTypeMatcher(
867 CommonAppTypeParser.getResourceForItemType(i));
868 }
869 if (mItemTypeMatchers[i].matches(activity, pm)) {
870 favorite.targetType = i;
871 break;
872 }
873 }
874 }
875 }
876
Sunny Goyalef728d42014-10-22 11:28:28 -0700877 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400878 }
879
880 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700881 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700882 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700883 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800884
Sunny Goyalc115e642015-07-20 14:23:43 -0700885 // If it is a hotseat item, move it accordingly.
886 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
887 favorite.screen += mHotseatShift;
888 }
889
Chris Wren5dee7af2013-12-20 17:22:11 -0500890 ContentValues values = new ContentValues();
891 values.put(Favorites._ID, favorite.id);
892 values.put(Favorites.SCREEN, favorite.screen);
893 values.put(Favorites.CONTAINER, favorite.container);
894 values.put(Favorites.CELLX, favorite.cellX);
895 values.put(Favorites.CELLY, favorite.cellY);
896 values.put(Favorites.SPANX, favorite.spanX);
897 values.put(Favorites.SPANY, favorite.spanY);
Sunny Goyal107ea632015-07-20 12:59:39 -0700898 values.put(Favorites.RANK, favorite.rank);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700899
900 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
Sunny Goyaleb4b7992016-04-21 14:30:18 -0700901 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
902 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
Chris Wren5dee7af2013-12-20 17:22:11 -0500903 values.put(Favorites.ICON, favorite.icon);
904 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700905
Chris Wren5dee7af2013-12-20 17:22:11 -0500906 if (!TextUtils.isEmpty(favorite.title)) {
907 values.put(Favorites.TITLE, favorite.title);
908 } else {
909 values.put(Favorites.TITLE, "");
910 }
911 if (!TextUtils.isEmpty(favorite.intent)) {
912 values.put(Favorites.INTENT, favorite.intent);
913 }
914 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500915
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100916 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
917 long userSerialNumber =
918 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
919 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
920
Sunny Goyale5bb7052015-07-27 14:36:07 -0700921 // If we will attempt grid resize, use the original profile to validate grid size, as
922 // anything which fits in the original grid should fit in the current grid after
923 // grid migration.
924 DeviceProfieData currentProfile = migrationCompatibleProfileData == null
925 ? mDeviceProfileData : migrationCompatibleProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700926
Sunny Goyalff572272014-07-23 13:58:07 -0700927 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
928 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
929 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
930 }
931 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
932 values.put(LauncherSettings.Favorites.RESTORED,
933 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
934 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
935 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700936
937 // Verify placement
938 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
939 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
940 restoreSuccessful = false;
941 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
942 }
Sunny Goyalff572272014-07-23 13:58:07 -0700943 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800944 // Check if it is an hotseat item, that can be replaced.
945 if (isReplaceableHotseatItem(favorite)
946 && favorite.targetType != Favorite.TARGET_NONE
947 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
948 Log.e(TAG, "Added item type flag");
949 values.put(LauncherSettings.Favorites.RESTORED,
950 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
951 } else {
952 // Let LauncherModel know we've been here.
953 values.put(LauncherSettings.Favorites.RESTORED, 1);
954 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700955
956 // Verify placement
957 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
958 if ((favorite.screen >= currentProfile.hotseatCount)
959 || (favorite.screen == currentProfile.allappsRank)) {
960 restoreSuccessful = false;
961 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
962 }
963 } else {
964 if ((favorite.cellX >= currentProfile.desktopCols)
965 || (favorite.cellY >= currentProfile.desktopRows)) {
966 restoreSuccessful = false;
967 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
968 }
969 }
Sunny Goyalff572272014-07-23 13:58:07 -0700970 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500971
Chris Wren5dee7af2013-12-20 17:22:11 -0500972 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400973 }
974
975 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700976 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400977 Screen screen = new Screen();
978 screen.id = c.getLong(ID_INDEX);
979 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700980 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400981 }
982
983 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700984 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400985 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700986 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500987 ContentValues values = new ContentValues();
988 values.put(WorkspaceScreens._ID, screen.id);
989 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
990 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400991 }
992
Chris Wren22e130d2013-09-23 18:25:57 -0400993 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700994 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400995 Resource res = new Resource();
996 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -0700997 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -0400998 return res;
999 }
1000
Chris Wrenfd13c712013-09-27 15:45:19 -04001001 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001002 private Widget packWidget(int dpi, LauncherAppWidgetProviderInfo info) {
Chris Wrenfd13c712013-09-27 15:45:19 -04001003 Widget widget = new Widget();
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001004 widget.provider = info.provider.flattenToShortString();
Chris Wrenfd13c712013-09-27 15:45:19 -04001005 widget.label = info.label;
1006 widget.configure = info.configure != null;
1007 if (info.icon != 0) {
1008 widget.icon = new Resource();
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001009 Drawable fullResIcon = mIconCache.getFullResIcon(info.provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -04001010 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -07001011 widget.icon.data = Utilities.flattenBitmap(icon);
1012 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -04001013 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001014
Sunny Goyale5bb7052015-07-27 14:36:07 -07001015 Point spans = info.getMinSpans(mIdp, mContext);
1016 widget.minSpanX = spans.x;
1017 widget.minSpanY = spans.y;
Sunny Goyalef728d42014-10-22 11:28:28 -07001018 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001019 }
1020
Sunny Goyalef728d42014-10-22 11:28:28 -07001021 /**
1022 * Deserialize a proto after verifying checksum wrapper.
1023 */
1024 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001025 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001026 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1027 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1028 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001029 }
1030
Chris Wren1ada10d2013-09-13 18:01:38 -04001031 /**
1032 * Read the old journal from the input file.
1033 *
1034 * In the event of any error, just pretend we didn't have a journal,
1035 * in that case, do a full backup.
1036 *
1037 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001038 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001039 */
1040 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001041 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001042 if (oldState == null) {
1043 return journal;
1044 }
1045 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1046 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001047 int availableBytes = inStream.available();
1048 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1049 if (availableBytes < MAX_JOURNAL_SIZE) {
1050 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001051 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001052 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001053 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001054 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001055 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001056 // OMG what are you doing? This is crazy inefficient!
1057 // If we read a byte that is not ours, we will cause trouble: b/12491813
1058 // However, we don't know how many bytes to expect (oops).
1059 // So we have to step through *slowly*, watching for the end.
1060 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001061 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001062 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001063 bytesRead += result;
1064 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001065 Log.w(TAG, "unexpected end of file while reading journal.");
1066 // stop reading and see what there is to parse
1067 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001068 }
1069 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001070 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001071 availableBytes = 0;
1072 }
1073
1074 // check the buffer to see if we have a valid journal
1075 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001076 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001077 // if we are here, then we have read a valid, checksum-verified journal
1078 valid = true;
1079 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001080 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001081 } catch (InvalidProtocolBufferNanoException e) {
1082 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001083 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001084 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001085 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001086 }
Chris Wren92aa4232013-10-04 11:29:36 -04001087 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001088 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001089 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001090 }
1091 }
Chris Wren92aa4232013-10-04 11:29:36 -04001092 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001093 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001094 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001095 try {
1096 inStream.close();
1097 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001098 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001099 }
1100 }
1101 return journal;
1102 }
1103
Sunny Goyalef728d42014-10-22 11:28:28 -07001104 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1105 throws IOException {
1106 writeRowToBackup(keyToBackupKey(key), proto, data);
1107 }
1108
1109 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001110 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001111 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001112 data.writeEntityHeader(backupKey, blob.length);
1113 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001114 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001115 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001116 }
1117
Chris Wren1ada10d2013-09-13 18:01:38 -04001118 /**
1119 * Write the new journal to the output file.
1120 *
1121 * In the event of any error, just pretend we didn't have a journal,
1122 * in that case, do a full backup.
1123
1124 * @param newState the write-only file descriptor pointing to the new journal
1125 * @param journal a Journal protocol buffer
1126 */
1127 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001128 try {
Sunny Goyalb740f592015-12-17 23:22:42 -08001129 FileOutputStream outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001130 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001131 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001132 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001133 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001134 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001135 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001136 }
1137 }
1138
1139 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1140 private byte[] writeCheckedBytes(MessageNano proto) {
1141 CheckedMessage wrapper = new CheckedMessage();
1142 wrapper.payload = MessageNano.toByteArray(proto);
1143 CRC32 checksum = new CRC32();
1144 checksum.update(wrapper.payload);
1145 wrapper.checksum = checksum.getValue();
1146 return MessageNano.toByteArray(wrapper);
1147 }
1148
1149 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001150 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001151 throws InvalidProtocolBufferNanoException {
1152 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001153 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001154 CRC32 checksum = new CRC32();
1155 checksum.update(wrapper.payload);
1156 if (wrapper.checksum != checksum.getValue()) {
1157 throw new InvalidProtocolBufferNanoException("checksum does not match");
1158 }
1159 return wrapper.payload;
1160 }
1161
Sunny Goyalef728d42014-10-22 11:28:28 -07001162 /**
1163 * @return true if the launcher is in a state to support backup
1164 */
Chris Wren71144262014-02-27 15:49:39 -05001165 private boolean launcherIsReady() {
1166 ContentResolver cr = mContext.getContentResolver();
1167 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1168 if (cursor == null) {
1169 // launcher data has been wiped, do nothing
1170 return false;
1171 }
1172 cursor.close();
1173
Adam Cohen2e6da152015-05-06 11:42:25 -07001174 if (LauncherAppState.getInstanceNoCreate() == null) {
Chris Wren71144262014-02-27 15:49:39 -05001175 // launcher services are unavailable, try again later
Chris Wren71144262014-02-27 15:49:39 -05001176 return false;
1177 }
1178
1179 return true;
1180 }
1181
Sunny Goyalffe83f12014-08-14 17:39:34 -07001182 private String getUserSelectionArg() {
1183 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1184 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1185 }
1186
Sunny Goyal316490e2015-06-02 09:38:28 -07001187 @Thunk class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001188
1189 private static final long serialVersionUID = 8931456637211665082L;
1190
Sunny Goyal316490e2015-06-02 09:38:28 -07001191 @Thunk InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001192 super(cause);
1193 }
1194
Sunny Goyal316490e2015-06-02 09:38:28 -07001195 @Thunk InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001196 super(reason);
1197 }
1198 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001199
Sunny Goyale5bb7052015-07-27 14:36:07 -07001200 public boolean shouldAttemptWorkspaceMigration() {
1201 return migrationCompatibleProfileData != null;
1202 }
1203
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001204 /**
1205 * A class to check if an activity can handle one of the intents from a list of
1206 * predefined intents.
1207 */
1208 private class ItemTypeMatcher {
1209
1210 private final ArrayList<Intent> mIntents;
1211
1212 ItemTypeMatcher(int xml_res) {
1213 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1214 }
1215
1216 private ArrayList<Intent> parseIntents(int xml_res) {
1217 ArrayList<Intent> intents = new ArrayList<Intent>();
1218 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1219 try {
1220 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1221 final int depth = parser.getDepth();
1222 int type;
1223 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1224 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1225 if (type != XmlPullParser.START_TAG) {
1226 continue;
1227 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1228 final String uri = DefaultLayoutParser.getAttributeValue(
1229 parser, DefaultLayoutParser.ATTR_URI);
1230 intents.add(Intent.parseUri(uri, 0));
1231 }
1232 }
1233 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1234 Log.e(TAG, "Unable to parse " + xml_res, e);
1235 } finally {
1236 parser.close();
1237 }
1238 return intents;
1239 }
1240
1241 public boolean matches(ActivityInfo activity, PackageManager pm) {
1242 for (Intent intent : mIntents) {
1243 intent.setPackage(activity.packageName);
1244 ResolveInfo info = pm.resolveActivity(intent, 0);
1245 if (info != null && (info.activityInfo.name.equals(activity.name)
1246 || info.activityInfo.name.equals(activity.targetActivity))) {
1247 return true;
1248 }
1249 }
1250 return false;
1251 }
1252 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001253}