blob: 136556b927bb5cc77026f2ab66a87de447a7056d [file] [log] [blame]
Chris Wren1ada10d2013-09-13 18:01:38 -04001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Chris Wren1ada10d2013-09-13 18:01:38 -040016package com.android.launcher3;
17
Chris Wren92aa4232013-10-04 11:29:36 -040018import android.app.backup.BackupDataInputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040019import android.app.backup.BackupDataOutput;
Chris Wren4d89e2a2013-10-09 17:03:50 -040020import android.app.backup.BackupHelper;
Chris Wren1ada10d2013-09-13 18:01:38 -040021import android.app.backup.BackupManager;
Chris Wren22e130d2013-09-23 18:25:57 -040022import android.content.ComponentName;
Chris Wren1ada10d2013-09-13 18:01:38 -040023import android.content.ContentResolver;
Chris Wren5dee7af2013-12-20 17:22:11 -050024import android.content.ContentValues;
Chris Wren1ada10d2013-09-13 18:01:38 -040025import android.content.Context;
Chris Wren22e130d2013-09-23 18:25:57 -040026import android.content.Intent;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080027import android.content.pm.ActivityInfo;
28import android.content.pm.PackageManager;
Sunny Goyalef728d42014-10-22 11:28:28 -070029import android.content.pm.PackageManager.NameNotFoundException;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080030import android.content.pm.ResolveInfo;
31import android.content.res.XmlResourceParser;
Chris Wren1ada10d2013-09-13 18:01:38 -040032import android.database.Cursor;
Chris Wren22e130d2013-09-23 18:25:57 -040033import android.graphics.Bitmap;
34import android.graphics.BitmapFactory;
Sunny Goyale5bb7052015-07-27 14:36:07 -070035import android.graphics.Point;
Chris Wrenfd13c712013-09-27 15:45:19 -040036import android.graphics.drawable.Drawable;
Chris Wren1ada10d2013-09-13 18:01:38 -040037import android.os.ParcelFileDescriptor;
Chris Wren1ada10d2013-09-13 18:01:38 -040038import android.text.TextUtils;
39import android.util.Base64;
40import android.util.Log;
41
Sunny Goyalef728d42014-10-22 11:28:28 -070042import com.android.launcher3.LauncherSettings.Favorites;
43import com.android.launcher3.LauncherSettings.WorkspaceScreens;
44import com.android.launcher3.backup.BackupProtos;
45import com.android.launcher3.backup.BackupProtos.CheckedMessage;
Sunny Goyal33d44382014-10-16 09:24:19 -070046import com.android.launcher3.backup.BackupProtos.DeviceProfieData;
Sunny Goyalef728d42014-10-22 11:28:28 -070047import com.android.launcher3.backup.BackupProtos.Favorite;
48import com.android.launcher3.backup.BackupProtos.Journal;
49import com.android.launcher3.backup.BackupProtos.Key;
50import com.android.launcher3.backup.BackupProtos.Resource;
51import com.android.launcher3.backup.BackupProtos.Screen;
52import com.android.launcher3.backup.BackupProtos.Widget;
53import com.android.launcher3.compat.UserHandleCompat;
54import com.android.launcher3.compat.UserManagerCompat;
Sunny Goyal316490e2015-06-02 09:38:28 -070055import com.android.launcher3.util.Thunk;
Sunny Goyalef728d42014-10-22 11:28:28 -070056import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
57import com.google.protobuf.nano.MessageNano;
58
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080059import org.xmlpull.v1.XmlPullParser;
60import org.xmlpull.v1.XmlPullParserException;
61
Chris Wren1ada10d2013-09-13 18:01:38 -040062import java.io.FileInputStream;
63import java.io.FileOutputStream;
64import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040065import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040066import java.util.ArrayList;
Sunny Goyalc0ee6752015-01-16 14:10:32 -080067import java.util.Arrays;
Chris Wren1ada10d2013-09-13 18:01:38 -040068import java.util.HashSet;
Chris Wren1ada10d2013-09-13 18:01:38 -040069import java.util.zip.CRC32;
70
71/**
72 * Persist the launcher home state across calamities.
73 */
Chris Wren92aa4232013-10-04 11:29:36 -040074public class LauncherBackupHelper implements BackupHelper {
Chris Wren92aa4232013-10-04 11:29:36 -040075 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050076 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
77 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren1ada10d2013-09-13 18:01:38 -040078
Sunny Goyal107ea632015-07-20 12:59:39 -070079 private static final int BACKUP_VERSION = 4;
Chris Wren1ada10d2013-09-13 18:01:38 -040080 private static final int MAX_JOURNAL_SIZE = 1000000;
81
Sunny Goyal33d44382014-10-16 09:24:19 -070082 // Journal key is such that it is always smaller than any dynamically generated
83 // key (any Base64 encoded string).
84 private static final String JOURNAL_KEY = "#";
85
Chris Wrenfd13c712013-09-27 15:45:19 -040086 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040087 private static final int MAX_ICONS_PER_PASS = 10;
88
Chris Wrenfd13c712013-09-27 15:45:19 -040089 /** widgets contain previews, which are very large, dribble them out */
90 private static final int MAX_WIDGETS_PER_PASS = 5;
91
Chris Wren1ada10d2013-09-13 18:01:38 -040092 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070093 Favorites._ID, // 0
94 Favorites.MODIFIED, // 1
95 Favorites.INTENT, // 2
96 Favorites.APPWIDGET_PROVIDER, // 3
97 Favorites.APPWIDGET_ID, // 4
98 Favorites.CELLX, // 5
99 Favorites.CELLY, // 6
100 Favorites.CONTAINER, // 7
101 Favorites.ICON, // 8
102 Favorites.ICON_PACKAGE, // 9
103 Favorites.ICON_RESOURCE, // 10
104 Favorites.ICON_TYPE, // 11
105 Favorites.ITEM_TYPE, // 12
106 Favorites.SCREEN, // 13
107 Favorites.SPANX, // 14
108 Favorites.SPANY, // 15
109 Favorites.TITLE, // 16
110 Favorites.PROFILE_ID, // 17
Sunny Goyal107ea632015-07-20 12:59:39 -0700111 Favorites.RANK, // 18
Chris Wren1ada10d2013-09-13 18:01:38 -0400112 };
113
114 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400115 private static final int ID_MODIFIED = 1;
116 private static final int INTENT_INDEX = 2;
117 private static final int APPWIDGET_PROVIDER_INDEX = 3;
118 private static final int APPWIDGET_ID_INDEX = 4;
119 private static final int CELLX_INDEX = 5;
120 private static final int CELLY_INDEX = 6;
121 private static final int CONTAINER_INDEX = 7;
122 private static final int ICON_INDEX = 8;
123 private static final int ICON_PACKAGE_INDEX = 9;
124 private static final int ICON_RESOURCE_INDEX = 10;
125 private static final int ICON_TYPE_INDEX = 11;
126 private static final int ITEM_TYPE_INDEX = 12;
127 private static final int SCREEN_INDEX = 13;
128 private static final int SPANX_INDEX = 14;
129 private static final int SPANY_INDEX = 15;
130 private static final int TITLE_INDEX = 16;
Sunny Goyal107ea632015-07-20 12:59:39 -0700131 private static final int RANK_INDEX = 18;
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
317 if ((oldProfile.desktopCols - currentProfile.desktopCols <= 1) &&
318 (oldProfile.desktopRows - currentProfile.desktopRows <= 1)) {
319 // Allow desktop migration when row and/or column count contracts by 1.
320
321 migrationCompatibleProfileData = initDeviceProfileData(mIdp);
322 migrationCompatibleProfileData.desktopCols = oldProfile.desktopCols;
323 migrationCompatibleProfileData.desktopRows = oldProfile.desktopRows;
324 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;
442 data.allappsRank = profile.hotseatAllAppsRank;
443 return data;
Sunny Goyal33d44382014-10-16 09:24:19 -0700444 }
445
446 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400447 * Write all modified favorites to the data stream.
448 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400449 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400450 * @throws IOException
451 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700452 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400453 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400454 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700455 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400456 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700457 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400458 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400459 cursor.moveToPosition(-1);
460 while(cursor.moveToNext()) {
461 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700462 final long updateTime = cursor.getLong(ID_MODIFIED);
463 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700464 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700465 final String backupKey = keyToBackupKey(key);
Sunny Goyal107ea632015-07-20 12:59:39 -0700466
467 // Favorite proto changed in v4. Backup again if the version is old.
468 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime
469 || restoredBackupVersion < 4) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700470 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500471 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700472 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400473 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400474 }
475 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400476 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400477 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400478 }
479
480 /**
481 * Read a favorite from the stream.
482 *
483 * <P>Keys arrive in any order, so screens and containers may not exist yet.
484 *
485 * @param key identifier for the row
486 * @param buffer the serialized proto from the stream, may be larger than dataSize
487 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400488 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700489 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500490 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400491 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
492 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
493
Sunny Goyalef728d42014-10-22 11:28:28 -0700494 ContentResolver cr = mContext.getContentResolver();
495 ContentValues values = unpackFavorite(buffer, dataSize);
Sunny Goyal1d4a2df2015-03-30 11:11:46 -0700496 cr.insert(Favorites.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400497 }
498
499 /**
500 * Write all modified screens to the data stream.
501 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400502 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400503 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400504 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700505 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400506 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400507 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400508 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
509 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400510 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400511 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700512 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400513 while(cursor.moveToNext()) {
514 final long id = cursor.getLong(ID_INDEX);
515 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400516 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700517 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500518 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700519 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
520 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500521 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700522 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400523 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400524 }
525 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400526 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400527 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400528 }
529
530 /**
531 * Read a screen from the stream.
532 *
533 * <P>Keys arrive in any order, so children of this screen may already exist.
534 *
535 * @param key identifier for the row
536 * @param buffer the serialized proto from the stream, may be larger than dataSize
537 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400538 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700539 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500540 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400541 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
542 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500543
Sunny Goyalef728d42014-10-22 11:28:28 -0700544 ContentResolver cr = mContext.getContentResolver();
545 ContentValues values = unpackScreen(buffer, dataSize);
546 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400547 }
548
Chris Wren22e130d2013-09-23 18:25:57 -0400549 /**
550 * Write all the static icon resources we need to render placeholders
551 * for a package that is not installed.
552 *
Chris Wren22e130d2013-09-23 18:25:57 -0400553 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400554 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700555 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400556 // persist icons that haven't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400557 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400558 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700559 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700560 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400561
Kenny Guyed131872014-04-30 03:02:21 +0100562 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100563 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100564 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700565 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400566 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
567 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400568 try {
569 cursor.moveToPosition(-1);
570 while(cursor.moveToNext()) {
571 final long id = cursor.getLong(ID_INDEX);
572 final String intentDescription = cursor.getString(INTENT_INDEX);
573 try {
574 Intent intent = Intent.parseUri(intentDescription, 0);
575 ComponentName cn = intent.getComponent();
576 Key key = null;
577 String backupKey = null;
578 if (cn != null) {
579 key = getKey(Key.ICON, cn.flattenToShortString());
580 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400581 } else {
582 Log.w(TAG, "empty intent on application favorite: " + id);
583 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700584 if (mExistingKeys.contains(backupKey)) {
585 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400586
587 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700588 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400589 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700590 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
591 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
592 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100593 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100594 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700595 writeRowToBackup(key, packIcon(dpi, icon), data);
596 mKeys.add(key);
597 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400598 }
599 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700600 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400601 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400602 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400603 }
604 }
605 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500606 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400607 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500608 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400609 }
610
611 }
612 } finally {
613 cursor.close();
614 }
Chris Wren22e130d2013-09-23 18:25:57 -0400615 }
616
617 /**
618 * Read an icon from the stream.
619 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400620 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400621 *
622 * @param key identifier for the row
623 * @param buffer the serialized proto from the stream, may be larger than dataSize
624 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400625 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700626 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500627 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400628 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
629 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500630
Sunny Goyalef728d42014-10-22 11:28:28 -0700631 Resource res = unpackProto(new Resource(), buffer, dataSize);
632 if (DEBUG) {
633 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400634 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700635 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
636 if (icon == null) {
637 Log.w(TAG, "failed to unpack icon for " + key.name);
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700638 } else {
639 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
640 mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
641 "" /* label */, mUserSerial, mIdp);
Sunny Goyalef728d42014-10-22 11:28:28 -0700642 }
Chris Wren22e130d2013-09-23 18:25:57 -0400643 }
644
Chris Wrenfd13c712013-09-27 15:45:19 -0400645 /**
646 * Write all the static widget resources we need to render placeholders
647 * for a package that is not installed.
648 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400649 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400650 * @throws IOException
651 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700652 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400653 // persist static widget info that hasn't been persisted yet
Chris Wren92aa4232013-10-04 11:29:36 -0400654 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400655 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalef728d42014-10-22 11:28:28 -0700656 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400657
Sunny Goyalffe83f12014-08-14 17:39:34 -0700658 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
659 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400660 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
661 where, null, null);
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);
668 Key key = null;
669 String backupKey = null;
670 if (provider != null) {
671 key = getKey(Key.WIDGET, providerName);
672 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400673 } else {
674 Log.w(TAG, "empty intent on appwidget: " + id);
675 }
Sunny Goyal107ea632015-07-20 12:59:39 -0700676
677 // Widget backup proto changed in v3. So add it again if the original backup is old.
678 if (mExistingKeys.contains(backupKey) && restoredBackupVersion >= 3) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700679 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400680
681 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700682 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400683 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700684 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
685 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
686 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Robin Lee26ace122015-03-16 19:41:43 +0000687 UserHandleCompat user = UserHandleCompat.myUserHandle();
Sunny Goyal96373642015-06-05 11:14:01 -0700688 writeRowToBackup(key, packWidget(dpi, provider, user), data);
Sunny Goyalef728d42014-10-22 11:28:28 -0700689 mKeys.add(key);
690 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400691 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700692 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400693 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400694 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400695 }
696 }
697 }
698 } finally {
699 cursor.close();
700 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400701 }
702
703 /**
704 * Read a widget from the stream.
705 *
706 * <P>Keys arrive in any order, so widgets that use this data may already exist.
707 *
708 * @param key identifier for the row
709 * @param buffer the serialized proto from the stream, may be larger than dataSize
710 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400711 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700712 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500713 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400714 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
715 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700716 Widget widget = unpackProto(new Widget(), buffer, dataSize);
717 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
718 if (widget.icon.data != null) {
719 Bitmap icon = BitmapFactory
720 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
721 if (icon == null) {
722 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500723 } else {
Sunny Goyal4fbc3822015-02-18 16:46:50 -0800724 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
Sunny Goyaldf6ccf82015-07-20 14:32:48 -0700725 icon, widget.icon.dpi, widget.label, mUserSerial, mIdp);
Chris Wren5dee7af2013-12-20 17:22:11 -0500726 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400727 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700728
Sunny Goyale5bb7052015-07-27 14:36:07 -0700729 // Cache widget min sizes incase migration is required.
730 widgetSizes.add(widget.provider + "#" + widget.minSpanX + "," + widget.minSpanY);
Chris Wrenfd13c712013-09-27 15:45:19 -0400731 }
732
Chris Wren22e130d2013-09-23 18:25:57 -0400733 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400734 *
735 * <P> Keys contain their own checksum instead of using
736 * the heavy-weight CheckedMessage wrapper.
737 */
738 private Key getKey(int type, long id) {
739 Key key = new Key();
740 key.type = type;
741 key.id = id;
742 key.checksum = checkKey(key);
743 return key;
744 }
745
Chris Wren22e130d2013-09-23 18:25:57 -0400746 /** create a new key for a named object.
747 *
748 * <P> Keys contain their own checksum instead of using
749 * the heavy-weight CheckedMessage wrapper.
750 */
751 private Key getKey(int type, String name) {
752 Key key = new Key();
753 key.type = type;
754 key.name = name;
755 key.checksum = checkKey(key);
756 return key;
757 }
758
Chris Wren1ada10d2013-09-13 18:01:38 -0400759 /** keys need to be strings, serialize and encode. */
760 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400761 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400762 }
763
764 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700765 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400766 try {
767 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
768 if (key.checksum != checkKey(key)) {
769 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700770 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400771 }
772 return key;
773 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700774 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400775 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700776 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400777 }
778 }
779
780 /** Compute the checksum over the important bits of a key. */
781 private long checkKey(Key key) {
782 CRC32 checksum = new CRC32();
783 checksum.update(key.type);
784 checksum.update((int) (key.id & 0xffff));
785 checksum.update((int) ((key.id >> 32) & 0xffff));
786 if (!TextUtils.isEmpty(key.name)) {
787 checksum.update(key.name.getBytes());
788 }
789 return checksum.getValue();
790 }
791
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800792 /**
793 * @return true if its an hotseat item, that can be replaced during restore.
794 * TODO: Extend check for folders in hotseat.
795 */
796 private boolean isReplaceableHotseatItem(Favorite favorite) {
797 return favorite.container == Favorites.CONTAINER_HOTSEAT
798 && favorite.intent != null
799 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
800 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
801 }
802
Chris Wren1ada10d2013-09-13 18:01:38 -0400803 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700804 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400805 Favorite favorite = new Favorite();
806 favorite.id = c.getLong(ID_INDEX);
807 favorite.screen = c.getInt(SCREEN_INDEX);
808 favorite.container = c.getInt(CONTAINER_INDEX);
809 favorite.cellX = c.getInt(CELLX_INDEX);
810 favorite.cellY = c.getInt(CELLY_INDEX);
811 favorite.spanX = c.getInt(SPANX_INDEX);
812 favorite.spanY = c.getInt(SPANY_INDEX);
813 favorite.iconType = c.getInt(ICON_TYPE_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) {
839 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
840 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
841 if (!TextUtils.isEmpty(iconPackage)) {
842 favorite.iconPackage = iconPackage;
843 }
844 String iconResource = c.getString(ICON_RESOURCE_INDEX);
845 if (!TextUtils.isEmpty(iconResource)) {
846 favorite.iconResource = iconResource;
847 }
848 }
849
850 byte[] blob = c.getBlob(ICON_INDEX);
851 if (blob != null && blob.length > 0) {
852 favorite.icon = blob;
853 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400854 }
855
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800856 if (isReplaceableHotseatItem(favorite)) {
857 if (intent != null && intent.getComponent() != null) {
858 PackageManager pm = mContext.getPackageManager();
859 ActivityInfo activity = null;;
860 try {
861 activity = pm.getActivityInfo(intent.getComponent(), 0);
862 } catch (NameNotFoundException e) {
863 Log.e(TAG, "Target not found", e);
864 }
865 if (activity == null) {
866 return favorite;
867 }
868 for (int i = 0; i < mItemTypeMatchers.length; i++) {
869 if (mItemTypeMatchers[i] == null) {
870 mItemTypeMatchers[i] = new ItemTypeMatcher(
871 CommonAppTypeParser.getResourceForItemType(i));
872 }
873 if (mItemTypeMatchers[i].matches(activity, pm)) {
874 favorite.targetType = i;
875 break;
876 }
877 }
878 }
879 }
880
Sunny Goyalef728d42014-10-22 11:28:28 -0700881 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400882 }
883
884 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700885 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700886 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700887 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800888
Sunny Goyalc115e642015-07-20 14:23:43 -0700889 // If it is a hotseat item, move it accordingly.
890 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
891 favorite.screen += mHotseatShift;
892 }
893
Chris Wren5dee7af2013-12-20 17:22:11 -0500894 ContentValues values = new ContentValues();
895 values.put(Favorites._ID, favorite.id);
896 values.put(Favorites.SCREEN, favorite.screen);
897 values.put(Favorites.CONTAINER, favorite.container);
898 values.put(Favorites.CELLX, favorite.cellX);
899 values.put(Favorites.CELLY, favorite.cellY);
900 values.put(Favorites.SPANX, favorite.spanX);
901 values.put(Favorites.SPANY, favorite.spanY);
Sunny Goyal107ea632015-07-20 12:59:39 -0700902 values.put(Favorites.RANK, favorite.rank);
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700903
904 if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
905 values.put(Favorites.ICON_TYPE, favorite.iconType);
906 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
907 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
908 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
909 }
Chris Wren5dee7af2013-12-20 17:22:11 -0500910 values.put(Favorites.ICON, favorite.icon);
911 }
Sunny Goyal4e5cc642015-06-25 16:37:44 -0700912
Chris Wren5dee7af2013-12-20 17:22:11 -0500913 if (!TextUtils.isEmpty(favorite.title)) {
914 values.put(Favorites.TITLE, favorite.title);
915 } else {
916 values.put(Favorites.TITLE, "");
917 }
918 if (!TextUtils.isEmpty(favorite.intent)) {
919 values.put(Favorites.INTENT, favorite.intent);
920 }
921 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500922
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100923 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
924 long userSerialNumber =
925 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
926 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
927
Sunny Goyale5bb7052015-07-27 14:36:07 -0700928 // If we will attempt grid resize, use the original profile to validate grid size, as
929 // anything which fits in the original grid should fit in the current grid after
930 // grid migration.
931 DeviceProfieData currentProfile = migrationCompatibleProfileData == null
932 ? mDeviceProfileData : migrationCompatibleProfileData;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700933
Sunny Goyalff572272014-07-23 13:58:07 -0700934 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
935 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
936 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
937 }
938 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
939 values.put(LauncherSettings.Favorites.RESTORED,
940 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
941 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
942 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700943
944 // Verify placement
945 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
946 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
947 restoreSuccessful = false;
948 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
949 }
Sunny Goyalff572272014-07-23 13:58:07 -0700950 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800951 // Check if it is an hotseat item, that can be replaced.
952 if (isReplaceableHotseatItem(favorite)
953 && favorite.targetType != Favorite.TARGET_NONE
954 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
955 Log.e(TAG, "Added item type flag");
956 values.put(LauncherSettings.Favorites.RESTORED,
957 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
958 } else {
959 // Let LauncherModel know we've been here.
960 values.put(LauncherSettings.Favorites.RESTORED, 1);
961 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700962
963 // Verify placement
964 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
965 if ((favorite.screen >= currentProfile.hotseatCount)
966 || (favorite.screen == currentProfile.allappsRank)) {
967 restoreSuccessful = false;
968 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
969 }
970 } else {
971 if ((favorite.cellX >= currentProfile.desktopCols)
972 || (favorite.cellY >= currentProfile.desktopRows)) {
973 restoreSuccessful = false;
974 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
975 }
976 }
Sunny Goyalff572272014-07-23 13:58:07 -0700977 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500978
Chris Wren5dee7af2013-12-20 17:22:11 -0500979 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400980 }
981
982 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700983 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400984 Screen screen = new Screen();
985 screen.id = c.getLong(ID_INDEX);
986 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700987 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400988 }
989
990 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700991 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400992 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700993 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500994 ContentValues values = new ContentValues();
995 values.put(WorkspaceScreens._ID, screen.id);
996 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
997 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400998 }
999
Chris Wren22e130d2013-09-23 18:25:57 -04001000 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001001 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -04001002 Resource res = new Resource();
1003 res.dpi = dpi;
Sunny Goyal73a22a52015-04-28 16:51:09 -07001004 res.data = Utilities.flattenBitmap(icon);
Chris Wren22e130d2013-09-23 18:25:57 -04001005 return res;
1006 }
1007
Chris Wrenfd13c712013-09-27 15:45:19 -04001008 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyal96373642015-06-05 11:14:01 -07001009 private Widget packWidget(int dpi, ComponentName provider, UserHandleCompat user) {
Adam Cohen59400422014-03-05 18:07:04 -08001010 final LauncherAppWidgetProviderInfo info =
Robin Lee26ace122015-03-16 19:41:43 +00001011 LauncherModel.getProviderInfo(mContext, provider, user);
Chris Wrenfd13c712013-09-27 15:45:19 -04001012 Widget widget = new Widget();
1013 widget.provider = provider.flattenToShortString();
1014 widget.label = info.label;
1015 widget.configure = info.configure != null;
1016 if (info.icon != 0) {
1017 widget.icon = new Resource();
Sunny Goyal96373642015-06-05 11:14:01 -07001018 Drawable fullResIcon = mIconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -04001019 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Sunny Goyal73a22a52015-04-28 16:51:09 -07001020 widget.icon.data = Utilities.flattenBitmap(icon);
1021 widget.icon.dpi = dpi;
Chris Wrenfd13c712013-09-27 15:45:19 -04001022 }
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001023
Sunny Goyale5bb7052015-07-27 14:36:07 -07001024 Point spans = info.getMinSpans(mIdp, mContext);
1025 widget.minSpanX = spans.x;
1026 widget.minSpanY = spans.y;
Sunny Goyal3a30cfe2015-07-16 17:27:43 -07001027
Sunny Goyalef728d42014-10-22 11:28:28 -07001028 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -04001029 }
1030
Sunny Goyalef728d42014-10-22 11:28:28 -07001031 /**
1032 * Deserialize a proto after verifying checksum wrapper.
1033 */
1034 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001035 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001036 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1037 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1038 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001039 }
1040
Chris Wren1ada10d2013-09-13 18:01:38 -04001041 /**
1042 * Read the old journal from the input file.
1043 *
1044 * In the event of any error, just pretend we didn't have a journal,
1045 * in that case, do a full backup.
1046 *
1047 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001048 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001049 */
1050 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001051 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001052 if (oldState == null) {
1053 return journal;
1054 }
1055 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1056 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001057 int availableBytes = inStream.available();
1058 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1059 if (availableBytes < MAX_JOURNAL_SIZE) {
1060 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001061 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001062 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001063 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001064 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001065 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001066 // OMG what are you doing? This is crazy inefficient!
1067 // If we read a byte that is not ours, we will cause trouble: b/12491813
1068 // However, we don't know how many bytes to expect (oops).
1069 // So we have to step through *slowly*, watching for the end.
1070 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001071 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001072 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001073 bytesRead += result;
1074 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001075 Log.w(TAG, "unexpected end of file while reading journal.");
1076 // stop reading and see what there is to parse
1077 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001078 }
1079 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001080 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001081 availableBytes = 0;
1082 }
1083
1084 // check the buffer to see if we have a valid journal
1085 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001086 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001087 // if we are here, then we have read a valid, checksum-verified journal
1088 valid = true;
1089 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001090 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001091 } catch (InvalidProtocolBufferNanoException e) {
1092 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001093 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001094 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001095 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001096 }
Chris Wren92aa4232013-10-04 11:29:36 -04001097 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001098 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001099 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001100 }
1101 }
Chris Wren92aa4232013-10-04 11:29:36 -04001102 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001103 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001104 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001105 try {
1106 inStream.close();
1107 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001108 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001109 }
1110 }
1111 return journal;
1112 }
1113
Sunny Goyalef728d42014-10-22 11:28:28 -07001114 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1115 throws IOException {
1116 writeRowToBackup(keyToBackupKey(key), proto, data);
1117 }
1118
1119 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001120 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001121 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001122 data.writeEntityHeader(backupKey, blob.length);
1123 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001124 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001125 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001126 }
1127
Chris Wren1ada10d2013-09-13 18:01:38 -04001128 /**
1129 * Write the new journal to the output file.
1130 *
1131 * In the event of any error, just pretend we didn't have a journal,
1132 * in that case, do a full backup.
1133
1134 * @param newState the write-only file descriptor pointing to the new journal
1135 * @param journal a Journal protocol buffer
1136 */
1137 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1138 FileOutputStream outStream = null;
1139 try {
1140 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}