blob: cad0f2c25a49357aa27a34670807255da335047d [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
106 Favorites.ICON_TYPE, // 11
107 Favorites.ITEM_TYPE, // 12
108 Favorites.SCREEN, // 13
109 Favorites.SPANX, // 14
110 Favorites.SPANY, // 15
111 Favorites.TITLE, // 16
112 Favorites.PROFILE_ID, // 17
Sunny Goyal107ea632015-07-20 12:59:39 -0700113 Favorites.RANK, // 18
Chris Wren1ada10d2013-09-13 18:01:38 -0400114 };
115
116 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400117 private static final int ID_MODIFIED = 1;
118 private static final int INTENT_INDEX = 2;
119 private static final int APPWIDGET_PROVIDER_INDEX = 3;
120 private static final int APPWIDGET_ID_INDEX = 4;
121 private static final int CELLX_INDEX = 5;
122 private static final int CELLY_INDEX = 6;
123 private static final int CONTAINER_INDEX = 7;
124 private static final int ICON_INDEX = 8;
125 private static final int ICON_PACKAGE_INDEX = 9;
126 private static final int ICON_RESOURCE_INDEX = 10;
127 private static final int ICON_TYPE_INDEX = 11;
128 private static final int ITEM_TYPE_INDEX = 12;
129 private static final int SCREEN_INDEX = 13;
130 private static final int SPANX_INDEX = 14;
131 private static final int SPANY_INDEX = 15;
132 private static final int TITLE_INDEX = 16;
Sunny Goyal107ea632015-07-20 12:59:39 -0700133 private static final int RANK_INDEX = 18;
Chris Wren1ada10d2013-09-13 18:01:38 -0400134
135 private static final String[] SCREEN_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -0700136 WorkspaceScreens._ID, // 0
137 WorkspaceScreens.MODIFIED, // 1
138 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400139 };
140
Chris Wren22e130d2013-09-23 18:25:57 -0400141 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400142
Sunny Goyal316490e2015-06-02 09:38:28 -0700143 @Thunk final Context mContext;
Sunny Goyalef728d42014-10-22 11:28:28 -0700144 private final HashSet<String> mExistingKeys;
Sunny Goyal42de82f2014-09-26 22:09:29 -0700145 private final ArrayList<Key> mKeys;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800146 private final ItemTypeMatcher[] mItemTypeMatchers;
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800147 private final long mUserSerial;
Chris Wren1ada10d2013-09-13 18:01:38 -0400148
Sunny Goyalef728d42014-10-22 11:28:28 -0700149 private BackupManager mBackupManager;
Sunny Goyalef728d42014-10-22 11:28:28 -0700150 private byte[] mBuffer = new byte[512];
151 private long mLastBackupRestoreTime;
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800152 private boolean mBackupDataWasUpdated;
Sunny Goyalef728d42014-10-22 11:28:28 -0700153
Adam Cohen2e6da152015-05-06 11:42:25 -0700154 private IconCache mIconCache;
155 private DeviceProfieData mDeviceProfileData;
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700156 private InvariantDeviceProfile mIdp;
Adam Cohen2e6da152015-05-06 11:42:25 -0700157
Sunny Goyale5bb7052015-07-27 14:36:07 -0700158 DeviceProfieData migrationCompatibleProfileData;
159 HashSet<String> widgetSizes = new HashSet<>();
160
Sunny Goyal33d44382014-10-16 09:24:19 -0700161 boolean restoreSuccessful;
Sunny Goyal08f72612015-01-05 13:41:43 -0800162 int restoredBackupVersion = 1;
Sunny Goyal33d44382014-10-16 09:24:19 -0700163
Sunny Goyalc115e642015-07-20 14:23:43 -0700164 // When migrating from a device which different hotseat configuration, the icons are shifted
165 // to center along the new all-apps icon.
166 private int mHotseatShift = 0;
167
Sunny Goyal33d44382014-10-16 09:24:19 -0700168 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400169 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700170 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700171 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700172 restoreSuccessful = true;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800173 mItemTypeMatchers = new ItemTypeMatcher[CommonAppTypeParser.SUPPORTED_TYPE_COUNT];
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800174
175 UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
176 mUserSerial = userManager.getSerialNumberForUser(UserHandleCompat.myUserHandle());
Chris Wren92aa4232013-10-04 11:29:36 -0400177 }
178
179 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700180 if (mBackupManager == null) {
181 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400182 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700183 mBackupManager.dataChanged();
184 }
185
186 private void applyJournal(Journal journal) {
187 mLastBackupRestoreTime = journal.t;
188 mExistingKeys.clear();
189 if (journal.key != null) {
190 for (Key key : journal.key) {
191 mExistingKeys.add(keyToBackupKey(key));
192 }
193 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700194 restoredBackupVersion = journal.backupVersion;
Chris Wren1ada10d2013-09-13 18:01:38 -0400195 }
196
197 /**
198 * Back up launcher data so we can restore the user's state on a new device.
199 *
200 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
201 *
202 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
203 *
204 * @param oldState notes from the last backup
205 * @param data incremental key/value pairs to persist off-device
206 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400207 */
208 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400209 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
210 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500211 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400212
213 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700214 if (!launcherIsReady()) {
Adam Cohen2e6da152015-05-06 11:42:25 -0700215 dataChanged();
Sunny Goyalef728d42014-10-22 11:28:28 -0700216 // Perform backup later.
217 writeJournal(newState, in);
218 return;
219 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700220
Sunny Goyal96373642015-06-05 11:14:01 -0700221 if (mDeviceProfileData == null) {
222 LauncherAppState app = LauncherAppState.getInstance();
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700223 mIdp = app.getInvariantDeviceProfile();
224 mDeviceProfileData = initDeviceProfileData(mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700225 mIconCache = app.getIconCache();
226 }
Adam Cohen2e6da152015-05-06 11:42:25 -0700227
Sunny Goyalef728d42014-10-22 11:28:28 -0700228 Log.v(TAG, "lastBackupTime = " + in.t);
229 mKeys.clear();
230 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400231
Sunny Goyalef728d42014-10-22 11:28:28 -0700232 // Record the time before performing backup so that entries edited while the backup
233 // was going on, do not get missed in next backup.
234 long newBackupTime = System.currentTimeMillis();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800235 mBackupDataWasUpdated = false;
Sunny Goyalef728d42014-10-22 11:28:28 -0700236 try {
237 backupFavorites(data);
238 backupScreens(data);
239 backupIcons(data);
240 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400241
Sunny Goyalef728d42014-10-22 11:28:28 -0700242 // Delete any key which still exist in the old backup, but is not valid anymore.
243 HashSet<String> validKeys = new HashSet<String>();
244 for (Key key : mKeys) {
245 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500246 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700247 mExistingKeys.removeAll(validKeys);
248
249 // Delete anything left in the existing keys.
250 for (String deleted: mExistingKeys) {
251 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
252 data.writeEntityHeader(deleted, -1);
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800253 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -0700254 }
255
256 mExistingKeys.clear();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800257 if (!mBackupDataWasUpdated) {
258 // Check if any metadata has changed
259 mBackupDataWasUpdated = (in.profile == null)
260 || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
Sunny Goyal96373642015-06-05 11:14:01 -0700261 DeviceProfieData.toByteArray(mDeviceProfileData))
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800262 || (in.backupVersion != BACKUP_VERSION)
263 || (in.appVersion != getAppVersion());
264 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700265
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800266 if (mBackupDataWasUpdated) {
267 mLastBackupRestoreTime = newBackupTime;
268
269 // We store the journal at two places.
270 // 1) Storing it in newState allows us to do partial backups by comparing old state
271 // 2) Storing it in backup data allows us to validate keys during restore
272 Journal state = getCurrentStateJournal();
273 writeRowToBackup(JOURNAL_KEY, state, data);
274 } else {
275 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
276 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700277 } catch (IOException e) {
278 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400279 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400280
Sunny Goyalef728d42014-10-22 11:28:28 -0700281 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400282 }
283
284 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700285 * @return true if the backup corresponding to oldstate can be successfully applied
286 * to this device.
287 */
288 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal96373642015-06-05 11:14:01 -0700289 DeviceProfieData currentProfile = mDeviceProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700290 DeviceProfieData oldProfile = oldState.profile;
291
292 if (oldProfile == null || oldProfile.desktopCols == 0) {
293 // Profile info is not valid, ignore the check.
294 return true;
295 }
296
Sunny Goyale5bb7052015-07-27 14:36:07 -0700297 boolean isHotseatCompatible = false;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700298 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
Sunny Goyale5bb7052015-07-27 14:36:07 -0700299 isHotseatCompatible = true;
Sunny Goyalc115e642015-07-20 14:23:43 -0700300 mHotseatShift = 0;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700301 }
Sunny Goyalc115e642015-07-20 14:23:43 -0700302
303 if ((currentProfile.allappsRank >= oldProfile.allappsRank)
304 && ((currentProfile.hotseatCount - currentProfile.allappsRank) >=
305 (oldProfile.hotseatCount - oldProfile.allappsRank))) {
306 // There is enough space on both sides of the hotseat.
Sunny Goyale5bb7052015-07-27 14:36:07 -0700307 isHotseatCompatible = true;
Sunny Goyalc115e642015-07-20 14:23:43 -0700308 mHotseatShift = currentProfile.allappsRank - oldProfile.allappsRank;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700309 }
310
Sunny Goyale5bb7052015-07-27 14:36:07 -0700311 if (!isHotseatCompatible) {
312 return false;
313 }
314 if ((currentProfile.desktopCols >= oldProfile.desktopCols)
315 && (currentProfile.desktopRows >= oldProfile.desktopRows)) {
316 return true;
317 }
318
Sunny Goyalf076eae2016-01-11 12:25:10 -0800319 if (GridSizeMigrationTask.ENABLED) {
320 // One time migrate the workspace when launcher starts.
Sunny Goyale5bb7052015-07-27 14:36:07 -0700321 migrationCompatibleProfileData = initDeviceProfileData(mIdp);
322 migrationCompatibleProfileData.desktopCols = oldProfile.desktopCols;
323 migrationCompatibleProfileData.desktopRows = oldProfile.desktopRows;
Sunny Goyalf076eae2016-01-11 12:25:10 -0800324 migrationCompatibleProfileData.hotseatCount = oldProfile.hotseatCount;
325 migrationCompatibleProfileData.allappsRank = oldProfile.allappsRank;
Sunny Goyale5bb7052015-07-27 14:36:07 -0700326 return true;
327 }
328 return false;
Sunny Goyal33d44382014-10-16 09:24:19 -0700329 }
330
331 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400332 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700333 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
334 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400335 *
Chris Wren92aa4232013-10-04 11:29:36 -0400336 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400337 */
338 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400339 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700340 if (!restoreSuccessful) {
341 return;
342 }
Sunny Goyal96373642015-06-05 11:14:01 -0700343
344 if (mDeviceProfileData == null) {
345 // This call does not happen on a looper thread. So LauncherAppState
346 // can't be created . Instead initialize required dependencies directly.
Sunny Goyal3a30cfe2015-07-16 17:27:43 -0700347 mIdp = new InvariantDeviceProfile(mContext);
348 mDeviceProfileData = initDeviceProfileData(mIdp);
349 mIconCache = new IconCache(mContext, mIdp);
Sunny Goyal96373642015-06-05 11:14:01 -0700350 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700351
Sunny Goyalef728d42014-10-22 11:28:28 -0700352 int dataSize = data.size();
353 if (mBuffer.length < dataSize) {
354 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400355 }
356 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700357 int bytesRead = data.read(mBuffer, 0, dataSize);
358 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
359 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700360
361 if (JOURNAL_KEY.equals(backupKey)) {
362 if (VERBOSE) Log.v(TAG, "Journal entry restored");
363 if (!mKeys.isEmpty()) {
364 // We received the journal key after a restore key.
365 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
366 restoreSuccessful = false;
367 return;
368 }
369
370 Journal journal = new Journal();
371 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
372 applyJournal(journal);
373 restoreSuccessful = isBackupCompatible(journal);
374 return;
375 }
376
377 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
378 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
379 return;
380 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700381 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500382 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400383 switch (key.type) {
384 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700385 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400386 break;
387
388 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700389 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400390 break;
391
392 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700393 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400394 break;
395
396 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700397 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400398 break;
399
400 default:
401 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700402 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400403 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400404 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700405 } catch (IOException e) {
406 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400407 }
Chris Wren92aa4232013-10-04 11:29:36 -0400408 }
409
410 /**
411 * Record the restore state for the next backup.
412 *
413 * @param newState notes about the backup state after restore.
414 */
415 @Override
416 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700417 writeJournal(newState, getCurrentStateJournal());
418 }
419
420 private Journal getCurrentStateJournal() {
421 Journal journal = new Journal();
422 journal.t = mLastBackupRestoreTime;
423 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
424 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700425 journal.backupVersion = BACKUP_VERSION;
Sunny Goyal96373642015-06-05 11:14:01 -0700426 journal.profile = mDeviceProfileData;
Sunny Goyalef728d42014-10-22 11:28:28 -0700427 return journal;
428 }
429
430 private int getAppVersion() {
431 try {
432 return mContext.getPackageManager()
433 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
434 } catch (NameNotFoundException e) {
435 return 0;
436 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400437 }
438
Adam Cohen2e6da152015-05-06 11:42:25 -0700439 private DeviceProfieData initDeviceProfileData(InvariantDeviceProfile profile) {
440 DeviceProfieData data = new DeviceProfieData();
441 data.desktopRows = profile.numRows;
442 data.desktopCols = profile.numColumns;
443 data.hotseatCount = profile.numHotseatIcons;
444 data.allappsRank = profile.hotseatAllAppsRank;
445 return data;
Sunny Goyal33d44382014-10-16 09:24:19 -0700446 }
447
448 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400449 * Write all modified favorites to the data stream.
450 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400451 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400452 * @throws IOException
453 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700454 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400455 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400456 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700457 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400458 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700459 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400460 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400461 cursor.moveToPosition(-1);
462 while(cursor.moveToNext()) {
463 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700464 final long updateTime = cursor.getLong(ID_MODIFIED);
465 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700466 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700467 final String backupKey = keyToBackupKey(key);
Sunny Goyal107ea632015-07-20 12:59:39 -0700468
469 // Favorite proto changed in v4. Backup again if the version is old.
470 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime
471 || restoredBackupVersion < 4) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700472 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500473 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700474 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400475 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400476 }
477 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400478 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400480 }
481
482 /**
483 * Read a favorite from the stream.
484 *
485 * <P>Keys arrive in any order, so screens and containers may not exist yet.
486 *
487 * @param key identifier for the row
488 * @param buffer the serialized proto from the stream, may be larger than dataSize
489 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400490 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700491 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500492 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400493 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
494 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
495
Sunny Goyalef728d42014-10-22 11:28:28 -0700496 ContentResolver cr = mContext.getContentResolver();
497 ContentValues values = unpackFavorite(buffer, dataSize);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700498 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400499 }
500
501 /**
502 * Write all modified screens to the data stream.
503 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400504 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400505 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400506 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700507 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400508 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400509 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400510 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
511 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400512 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400513 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700514 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400515 while(cursor.moveToNext()) {
516 final long id = cursor.getLong(ID_INDEX);
517 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400518 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700519 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500520 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700521 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
522 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500523 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700524 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400525 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400526 }
527 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400528 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400529 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400530 }
531
532 /**
533 * Read a screen from the stream.
534 *
535 * <P>Keys arrive in any order, so children of this screen may already exist.
536 *
537 * @param key identifier for the row
538 * @param buffer the serialized proto from the stream, may be larger than dataSize
539 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400540 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700541 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500542 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400543 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
544 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500545
Sunny Goyalef728d42014-10-22 11:28:28 -0700546 ContentResolver cr = mContext.getContentResolver();
547 ContentValues values = unpackScreen(buffer, dataSize);
548 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400549 }
550
Chris Wren22e130d2013-09-23 18:25:57 -0400551 /**
552 * Write all the static icon resources we need to render placeholders
553 * for a package that is not installed.
554 *
Chris Wren22e130d2013-09-23 18:25:57 -0400555 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400556 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700557 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400558 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400559 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400560 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700561 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700562 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400563
Kenny Guyed131872014-04-30 03:02:21 +0100564 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100565 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100566 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700567 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400568 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
569 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400570 try {
571 cursor.moveToPosition(-1);
572 while(cursor.moveToNext()) {
573 final long id = cursor.getLong(ID_INDEX);
574 final String intentDescription = cursor.getString(INTENT_INDEX);
575 try {
576 Intent intent = Intent.parseUri(intentDescription, 0);
577 ComponentName cn = intent.getComponent();
578 Key key = null;
579 String backupKey = null;
580 if (cn != null) {
581 key = getKey(Key.ICON, cn.flattenToShortString());
582 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400583 } else {
584 Log.w(TAG, "empty intent on application favorite: " + id);
585 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700586 if (mExistingKeys.contains(backupKey)) {
587 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400588
589 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700590 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400591 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700592 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
593 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
594 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100595 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100596 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700597 writeRowToBackup(key, packIcon(dpi, icon), data);
598 mKeys.add(key);
599 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400600 }
601 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700602 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400603 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400604 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400605 }
606 }
607 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500608 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400609 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500610 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400611 }
612
613 }
614 } finally {
615 cursor.close();
616 }
Chris Wren22e130d2013-09-23 18:25:57 -0400617 }
618
619 /**
620 * Read an icon from the stream.
621 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400622 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400623 *
624 * @param key identifier for the row
625 * @param buffer the serialized proto from the stream, may be larger than dataSize
626 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400627 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700628 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500629 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400630 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
631 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500632
Sunny Goyalef728d42014-10-22 11:28:28 -0700633 Resource res = unpackProto(new Resource(), buffer, dataSize);
634 if (DEBUG) {
635 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400636 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700637 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
638 if (icon == null) {
639 Log.w(TAG, "failed to unpack icon for " + key.name);
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700640 } else {
641 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
642 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
643 "" /* label */, mUserSerial, mIdp);
Sunny Goyalef728d42014-10-22 11:28:28 -0700644 }
Chris Wren22e130d2013-09-23 18:25:57 -0400645 }
646
Chris Wrenfd13c712013-09-27 15:45:19 -0400647 /**
648 * Write all the static widget resources we need to render placeholders
649 * for a package that is not installed.
650 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400651 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400652 * @throws IOException
653 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700654 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400655 // persist static widget info that hasn't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400656 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400657 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalef728d42014-10-22 11:28:28 -0700658 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400659
Sunny Goyalffe83f12014-08-14 17:39:34 -0700660 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
661 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400662 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
663 where, null, null);
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800664 AppWidgetManagerCompat widgetManager = AppWidgetManagerCompat.getInstance(mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400665 try {
666 cursor.moveToPosition(-1);
667 while(cursor.moveToNext()) {
668 final long id = cursor.getLong(ID_INDEX);
669 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
Chris Wrenfd13c712013-09-27 15:45:19 -0400670 final ComponentName provider = ComponentName.unflattenFromString(providerName);
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800671
Chris Wrenfd13c712013-09-27 15:45:19 -0400672 Key key = null;
673 String backupKey = null;
674 if (provider != null) {
675 key = getKey(Key.WIDGET, providerName);
676 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400677 } else {
678 Log.w(TAG, "empty intent on appwidget: " + id);
679 }
Sunny Goyal107ea632015-07-20 12:59:39 -0700680
681 // Widget backup proto changed in v3. So add it again if the original backup is old.
682 if (mExistingKeys.contains(backupKey) && restoredBackupVersion >= 3) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700683 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400684
685 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700686 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400687 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700688 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
689 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
Sunny Goyal2e1efb42016-03-03 16:58:55 -0800690 LauncherAppWidgetProviderInfo widgetInfo = widgetManager
691 .getLauncherAppWidgetInfo(cursor.getInt(APPWIDGET_ID_INDEX));
692 if (widgetInfo != null) {
693 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
694 writeRowToBackup(key, packWidget(dpi, widgetInfo), data);
695 mKeys.add(key);
696 backupWidgetCount ++;
697 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400698 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700699 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400700 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400701 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400702 }
703 }
704 }
705 } finally {
706 cursor.close();
707 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400708 }
709
710 /**
711 * Read a widget from the stream.
712 *
713 * <P>Keys arrive in any order, so widgets that use this data may already exist.
714 *
715 * @param key identifier for the row
716 * @param buffer the serialized proto from the stream, may be larger than dataSize
717 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400718 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700719 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500720 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400721 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
722 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700723 Widget widget = unpackProto(new Widget(), buffer, dataSize);
724 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
725 if (widget.icon.data != null) {
726 Bitmap icon = BitmapFactory
727 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
728 if (icon == null) {
729 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500730 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800731 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700732 icon, widget.icon.dpi, widget.label, mUserSerial, mIdp);
Chris Wren5dee7af2013-12-20 17:22:11 -0500733 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400734 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700735
Sunny Goyale5bb7052015-07-27 14:36:07 -0700736 // Cache widget min sizes incase migration is required.
737 widgetSizes.add(widget.provider + "#" + widget.minSpanX + "," + widget.minSpanY);
Chris Wrenfd13c712013-09-27 15:45:19 -0400738 }
739
Chris Wren22e130d2013-09-23 18:25:57 -0400740 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400741 *
742 * <P> Keys contain their own checksum instead of using
743 * the heavy-weight CheckedMessage wrapper.
744 */
745 private Key getKey(int type, long id) {
746 Key key = new Key();
747 key.type = type;
748 key.id = id;
749 key.checksum = checkKey(key);
750 return key;
751 }
752
Chris Wren22e130d2013-09-23 18:25:57 -0400753 /** create a new key for a named object.
754 *
755 * <P> Keys contain their own checksum instead of using
756 * the heavy-weight CheckedMessage wrapper.
757 */
758 private Key getKey(int type, String name) {
759 Key key = new Key();
760 key.type = type;
761 key.name = name;
762 key.checksum = checkKey(key);
763 return key;
764 }
765
Chris Wren1ada10d2013-09-13 18:01:38 -0400766 /** keys need to be strings, serialize and encode. */
767 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400768 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400769 }
770
771 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700772 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400773 try {
774 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
775 if (key.checksum != checkKey(key)) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700776 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400777 }
778 return key;
Sunny Goyalb740f592015-12-17 23:22:42 -0800779 } catch (InvalidProtocolBufferNanoException | IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700780 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400781 }
782 }
783
784 /** Compute the checksum over the important bits of a key. */
785 private long checkKey(Key key) {
786 CRC32 checksum = new CRC32();
787 checksum.update(key.type);
788 checksum.update((int) (key.id & 0xffff));
789 checksum.update((int) ((key.id >> 32) & 0xffff));
790 if (!TextUtils.isEmpty(key.name)) {
791 checksum.update(key.name.getBytes());
792 }
793 return checksum.getValue();
794 }
795
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800796 /**
797 * @return true if its an hotseat item, that can be replaced during restore.
798 * TODO: Extend check for folders in hotseat.
799 */
800 private boolean isReplaceableHotseatItem(Favorite favorite) {
801 return favorite.container == Favorites.CONTAINER_HOTSEAT
802 && favorite.intent != null
803 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
804 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
805 }
806
Chris Wren1ada10d2013-09-13 18:01:38 -0400807 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700808 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400809 Favorite favorite = new Favorite();
810 favorite.id = c.getLong(ID_INDEX);
811 favorite.screen = c.getInt(SCREEN_INDEX);
812 favorite.container = c.getInt(CONTAINER_INDEX);
813 favorite.cellX = c.getInt(CELLX_INDEX);
814 favorite.cellY = c.getInt(CELLY_INDEX);
815 favorite.spanX = c.getInt(SPANX_INDEX);
816 favorite.spanY = c.getInt(SPANY_INDEX);
817 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
Sunny Goyal107ea632015-07-20 12:59:39 -0700818 favorite.rank = c.getInt(RANK_INDEX);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700819
Chris Wren1ada10d2013-09-13 18:01:38 -0400820 String title = c.getString(TITLE_INDEX);
821 if (!TextUtils.isEmpty(title)) {
822 favorite.title = title;
823 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100824 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800825 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100826 if (!TextUtils.isEmpty(intentDescription)) {
827 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800828 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100829 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
830 favorite.intent = intent.toUri(0);
831 } catch (URISyntaxException e) {
832 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700833 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400834 }
835 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
836 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
837 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
838 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
839 if (!TextUtils.isEmpty(appWidgetProvider)) {
840 favorite.appWidgetProvider = appWidgetProvider;
841 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700842 } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
843 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
844 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
845 if (!TextUtils.isEmpty(iconPackage)) {
846 favorite.iconPackage = iconPackage;
847 }
848 String iconResource = c.getString(ICON_RESOURCE_INDEX);
849 if (!TextUtils.isEmpty(iconResource)) {
850 favorite.iconResource = iconResource;
851 }
852 }
853
854 byte[] blob = c.getBlob(ICON_INDEX);
855 if (blob != null && blob.length > 0) {
856 favorite.icon = blob;
857 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400858 }
859
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800860 if (isReplaceableHotseatItem(favorite)) {
861 if (intent != null && intent.getComponent() != null) {
862 PackageManager pm = mContext.getPackageManager();
863 ActivityInfo activity = null;;
864 try {
865 activity = pm.getActivityInfo(intent.getComponent(), 0);
866 } catch (NameNotFoundException e) {
867 Log.e(TAG, "Target not found", e);
868 }
869 if (activity == null) {
870 return favorite;
871 }
872 for (int i = 0; i < mItemTypeMatchers.length; i++) {
873 if (mItemTypeMatchers[i] == null) {
874 mItemTypeMatchers[i] = new ItemTypeMatcher(
875 CommonAppTypeParser.getResourceForItemType(i));
876 }
877 if (mItemTypeMatchers[i].matches(activity, pm)) {
878 favorite.targetType = i;
879 break;
880 }
881 }
882 }
883 }
884
Sunny Goyalef728d42014-10-22 11:28:28 -0700885 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400886 }
887
888 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700889 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700890 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700891 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800892
Sunny Goyalc115e642015-07-20 14:23:43 -0700893 // If it is a hotseat item, move it accordingly.
894 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
895 favorite.screen += mHotseatShift;
896 }
897
Chris Wren5dee7af2013-12-20 17:22:11 -0500898 ContentValues values = new ContentValues();
899 values.put(Favorites._ID, favorite.id);
900 values.put(Favorites.SCREEN, favorite.screen);
901 values.put(Favorites.CONTAINER, favorite.container);
902 values.put(Favorites.CELLX, favorite.cellX);
903 values.put(Favorites.CELLY, favorite.cellY);
904 values.put(Favorites.SPANX, favorite.spanX);
905 values.put(Favorites.SPANY, favorite.spanY);
Sunny Goyal107ea632015-07-20 12:59:39 -0700906 values.put(Favorites.RANK, favorite.rank);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700907
908 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
909 values.put(Favorites.ICON_TYPE, favorite.iconType);
910 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
911 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
912 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
913 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500914 values.put(Favorites.ICON, favorite.icon);
915 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700916
Chris Wren5dee7af2013-12-20 17:22:11 -0500917 if (!TextUtils.isEmpty(favorite.title)) {
918 values.put(Favorites.TITLE, favorite.title);
919 } else {
920 values.put(Favorites.TITLE, "");
921 }
922 if (!TextUtils.isEmpty(favorite.intent)) {
923 values.put(Favorites.INTENT, favorite.intent);
924 }
925 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500926
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100927 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
928 long userSerialNumber =
929 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
930 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
931
Sunny Goyale5bb7052015-07-27 14:36:07 -0700932 // If we will attempt grid resize, use the original profile to validate grid size, as
933 // anything which fits in the original grid should fit in the current grid after
934 // grid migration.
935 DeviceProfieData currentProfile = migrationCompatibleProfileData == null
936 ? mDeviceProfileData : migrationCompatibleProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700937
Sunny Goyalff572272014-07-23 13:58:07 -0700938 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
939 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
940 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
941 }
942 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
943 values.put(LauncherSettings.Favorites.RESTORED,
944 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
945 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
946 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700947
948 // Verify placement
949 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
950 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
951 restoreSuccessful = false;
952 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
953 }
Sunny Goyalff572272014-07-23 13:58:07 -0700954 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800955 // Check if it is an hotseat item, that can be replaced.
956 if (isReplaceableHotseatItem(favorite)
957 && favorite.targetType != Favorite.TARGET_NONE
958 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
959 Log.e(TAG, "Added item type flag");
960 values.put(LauncherSettings.Favorites.RESTORED,
961 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
962 } else {
963 // Let LauncherModel know we've been here.
964 values.put(LauncherSettings.Favorites.RESTORED, 1);
965 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700966
967 // Verify placement
968 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
969 if ((favorite.screen >= currentProfile.hotseatCount)
970 || (favorite.screen == currentProfile.allappsRank)) {
971 restoreSuccessful = false;
972 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
973 }
974 } else {
975 if ((favorite.cellX >= currentProfile.desktopCols)
976 || (favorite.cellY >= currentProfile.desktopRows)) {
977 restoreSuccessful = false;
978 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
979 }
980 }
Sunny Goyalff572272014-07-23 13:58:07 -0700981 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500982
Chris Wren5dee7af2013-12-20 17:22:11 -0500983 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400984 }
985
986 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700987 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400988 Screen screen = new Screen();
989 screen.id = c.getLong(ID_INDEX);
990 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700991 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400992 }
993
994 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700995 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400996 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700997 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500998 ContentValues values = new ContentValues();
999 values.put(WorkspaceScreens._ID, screen.id);
1000 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
1001 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -04001002 }
1003
Chris Wren22e130d2013-09-23 18:25:57 -04001004 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001005 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -04001006 Resource res = new Resource();
1007 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -07001008 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -04001009 return res;
1010 }
1011
Chris Wrenfd13c712013-09-27 15:45:19 -04001012 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001013 private Widget packWidget(int dpi, LauncherAppWidgetProviderInfo info) {
Chris Wrenfd13c712013-09-27 15:45:19 -04001014 Widget widget = new Widget();
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001015 widget.provider = info.provider.flattenToShortString();
Chris Wrenfd13c712013-09-27 15:45:19 -04001016 widget.label = info.label;
1017 widget.configure = info.configure != null;
1018 if (info.icon != 0) {
1019 widget.icon = new Resource();
Sunny Goyal2e1efb42016-03-03 16:58:55 -08001020 Drawable fullResIcon = mIconCache.getFullResIcon(info.provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -04001021 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -07001022 widget.icon.data = Utilities.flattenBitmap(icon);
1023 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -04001024 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001025
Sunny Goyale5bb7052015-07-27 14:36:07 -07001026 Point spans = info.getMinSpans(mIdp, mContext);
1027 widget.minSpanX = spans.x;
1028 widget.minSpanY = spans.y;
Sunny Goyalef728d42014-10-22 11:28:28 -07001029 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001030 }
1031
Sunny Goyalef728d42014-10-22 11:28:28 -07001032 /**
1033 * Deserialize a proto after verifying checksum wrapper.
1034 */
1035 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001036 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001037 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1038 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1039 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001040 }
1041
Chris Wren1ada10d2013-09-13 18:01:38 -04001042 /**
1043 * Read the old journal from the input file.
1044 *
1045 * In the event of any error, just pretend we didn't have a journal,
1046 * in that case, do a full backup.
1047 *
1048 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001049 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001050 */
1051 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001052 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001053 if (oldState == null) {
1054 return journal;
1055 }
1056 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1057 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001058 int availableBytes = inStream.available();
1059 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1060 if (availableBytes < MAX_JOURNAL_SIZE) {
1061 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001062 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001063 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001064 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001065 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001066 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001067 // OMG what are you doing? This is crazy inefficient!
1068 // If we read a byte that is not ours, we will cause trouble: b/12491813
1069 // However, we don't know how many bytes to expect (oops).
1070 // So we have to step through *slowly*, watching for the end.
1071 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001072 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001073 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001074 bytesRead += result;
1075 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001076 Log.w(TAG, "unexpected end of file while reading journal.");
1077 // stop reading and see what there is to parse
1078 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001079 }
1080 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001081 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001082 availableBytes = 0;
1083 }
1084
1085 // check the buffer to see if we have a valid journal
1086 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001087 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001088 // if we are here, then we have read a valid, checksum-verified journal
1089 valid = true;
1090 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001091 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001092 } catch (InvalidProtocolBufferNanoException e) {
1093 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001094 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001095 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001096 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001097 }
Chris Wren92aa4232013-10-04 11:29:36 -04001098 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001099 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001100 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001101 }
1102 }
Chris Wren92aa4232013-10-04 11:29:36 -04001103 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001104 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001105 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001106 try {
1107 inStream.close();
1108 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001109 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001110 }
1111 }
1112 return journal;
1113 }
1114
Sunny Goyalef728d42014-10-22 11:28:28 -07001115 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1116 throws IOException {
1117 writeRowToBackup(keyToBackupKey(key), proto, data);
1118 }
1119
1120 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001121 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001122 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001123 data.writeEntityHeader(backupKey, blob.length);
1124 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001125 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001126 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001127 }
1128
Chris Wren1ada10d2013-09-13 18:01:38 -04001129 /**
1130 * Write the new journal to the output file.
1131 *
1132 * In the event of any error, just pretend we didn't have a journal,
1133 * in that case, do a full backup.
1134
1135 * @param newState the write-only file descriptor pointing to the new journal
1136 * @param journal a Journal protocol buffer
1137 */
1138 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001139 try {
Sunny Goyalb740f592015-12-17 23:22:42 -08001140 FileOutputStream outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001141 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001142 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001143 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001144 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001145 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001146 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001147 }
1148 }
1149
1150 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1151 private byte[] writeCheckedBytes(MessageNano proto) {
1152 CheckedMessage wrapper = new CheckedMessage();
1153 wrapper.payload = MessageNano.toByteArray(proto);
1154 CRC32 checksum = new CRC32();
1155 checksum.update(wrapper.payload);
1156 wrapper.checksum = checksum.getValue();
1157 return MessageNano.toByteArray(wrapper);
1158 }
1159
1160 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001161 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001162 throws InvalidProtocolBufferNanoException {
1163 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001164 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001165 CRC32 checksum = new CRC32();
1166 checksum.update(wrapper.payload);
1167 if (wrapper.checksum != checksum.getValue()) {
1168 throw new InvalidProtocolBufferNanoException("checksum does not match");
1169 }
1170 return wrapper.payload;
1171 }
1172
Sunny Goyalef728d42014-10-22 11:28:28 -07001173 /**
1174 * @return true if the launcher is in a state to support backup
1175 */
Chris Wren71144262014-02-27 15:49:39 -05001176 private boolean launcherIsReady() {
1177 ContentResolver cr = mContext.getContentResolver();
1178 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1179 if (cursor == null) {
1180 // launcher data has been wiped, do nothing
1181 return false;
1182 }
1183 cursor.close();
1184
Adam Cohen2e6da152015-05-06 11:42:25 -07001185 if (LauncherAppState.getInstanceNoCreate() == null) {
Chris Wren71144262014-02-27 15:49:39 -05001186 // launcher services are unavailable, try again later
Chris Wren71144262014-02-27 15:49:39 -05001187 return false;
1188 }
1189
1190 return true;
1191 }
1192
Sunny Goyalffe83f12014-08-14 17:39:34 -07001193 private String getUserSelectionArg() {
1194 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1195 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1196 }
1197
Sunny Goyal316490e2015-06-02 09:38:28 -07001198 @Thunk class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001199
1200 private static final long serialVersionUID = 8931456637211665082L;
1201
Sunny Goyal316490e2015-06-02 09:38:28 -07001202 @Thunk InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001203 super(cause);
1204 }
1205
Sunny Goyal316490e2015-06-02 09:38:28 -07001206 @Thunk InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001207 super(reason);
1208 }
1209 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001210
Sunny Goyale5bb7052015-07-27 14:36:07 -07001211 public boolean shouldAttemptWorkspaceMigration() {
1212 return migrationCompatibleProfileData != null;
1213 }
1214
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001215 /**
1216 * A class to check if an activity can handle one of the intents from a list of
1217 * predefined intents.
1218 */
1219 private class ItemTypeMatcher {
1220
1221 private final ArrayList<Intent> mIntents;
1222
1223 ItemTypeMatcher(int xml_res) {
1224 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1225 }
1226
1227 private ArrayList<Intent> parseIntents(int xml_res) {
1228 ArrayList<Intent> intents = new ArrayList<Intent>();
1229 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1230 try {
1231 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1232 final int depth = parser.getDepth();
1233 int type;
1234 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1235 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1236 if (type != XmlPullParser.START_TAG) {
1237 continue;
1238 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1239 final String uri = DefaultLayoutParser.getAttributeValue(
1240 parser, DefaultLayoutParser.ATTR_URI);
1241 intents.add(Intent.parseUri(uri, 0));
1242 }
1243 }
1244 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1245 Log.e(TAG, "Unable to parse " + xml_res, e);
1246 } finally {
1247 parser.close();
1248 }
1249 return intents;
1250 }
1251
1252 public boolean matches(ActivityInfo activity, PackageManager pm) {
1253 for (Intent intent : mIntents) {
1254 intent.setPackage(activity.packageName);
1255 ResolveInfo info = pm.resolveActivity(intent, 0);
1256 if (info != null && (info.activityInfo.name.equals(activity.name)
1257 || info.activityInfo.name.equals(activity.targetActivity))) {
1258 return true;
1259 }
1260 }
1261 return false;
1262 }
1263 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001264}