blob: 353bf3f0010f8ab854967d7f776d069a2ede504d [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;
Chris Wrenfd13c712013-09-27 15:45:19 -040035import android.graphics.drawable.Drawable;
Chris Wren1ada10d2013-09-13 18:01:38 -040036import android.os.ParcelFileDescriptor;
Chris Wren1ada10d2013-09-13 18:01:38 -040037import android.text.TextUtils;
38import android.util.Base64;
39import android.util.Log;
40
Sunny Goyalef728d42014-10-22 11:28:28 -070041import com.android.launcher3.LauncherSettings.Favorites;
42import com.android.launcher3.LauncherSettings.WorkspaceScreens;
43import com.android.launcher3.backup.BackupProtos;
44import com.android.launcher3.backup.BackupProtos.CheckedMessage;
Sunny Goyal33d44382014-10-16 09:24:19 -070045import com.android.launcher3.backup.BackupProtos.DeviceProfieData;
Sunny Goyalef728d42014-10-22 11:28:28 -070046import com.android.launcher3.backup.BackupProtos.Favorite;
47import com.android.launcher3.backup.BackupProtos.Journal;
48import com.android.launcher3.backup.BackupProtos.Key;
49import com.android.launcher3.backup.BackupProtos.Resource;
50import com.android.launcher3.backup.BackupProtos.Screen;
51import com.android.launcher3.backup.BackupProtos.Widget;
52import com.android.launcher3.compat.UserHandleCompat;
53import com.android.launcher3.compat.UserManagerCompat;
54import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
55import com.google.protobuf.nano.MessageNano;
56
Sunny Goyalbb3b02f2015-01-15 12:00:14 -080057import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59
Chris Wren22e130d2013-09-23 18:25:57 -040060import java.io.ByteArrayOutputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040061import java.io.FileInputStream;
62import java.io.FileOutputStream;
63import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040064import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040065import java.util.ArrayList;
Sunny Goyalc0ee6752015-01-16 14:10:32 -080066import java.util.Arrays;
Chris Wren1ada10d2013-09-13 18:01:38 -040067import java.util.HashSet;
Chris Wren1ada10d2013-09-13 18:01:38 -040068import java.util.zip.CRC32;
69
70/**
71 * Persist the launcher home state across calamities.
72 */
Chris Wren92aa4232013-10-04 11:29:36 -040073public class LauncherBackupHelper implements BackupHelper {
Chris Wren92aa4232013-10-04 11:29:36 -040074 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050075 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
76 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren1ada10d2013-09-13 18:01:38 -040077
Sunny Goyal33d44382014-10-16 09:24:19 -070078 private static final int BACKUP_VERSION = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -040079 private static final int MAX_JOURNAL_SIZE = 1000000;
80
Sunny Goyal33d44382014-10-16 09:24:19 -070081 // Journal key is such that it is always smaller than any dynamically generated
82 // key (any Base64 encoded string).
83 private static final String JOURNAL_KEY = "#";
84
Chris Wrenfd13c712013-09-27 15:45:19 -040085 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040086 private static final int MAX_ICONS_PER_PASS = 10;
87
Chris Wrenfd13c712013-09-27 15:45:19 -040088 /** widgets contain previews, which are very large, dribble them out */
89 private static final int MAX_WIDGETS_PER_PASS = 5;
90
Sunny Goyal33d44382014-10-16 09:24:19 -070091 private static final int IMAGE_COMPRESSION_QUALITY = 75;
Chris Wren45297f82013-10-17 15:16:48 -040092
Chris Wrenb86f0762013-10-04 10:10:21 -040093 private static final Bitmap.CompressFormat IMAGE_FORMAT =
94 android.graphics.Bitmap.CompressFormat.PNG;
95
Chris Wren1ada10d2013-09-13 18:01:38 -040096 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070097 Favorites._ID, // 0
98 Favorites.MODIFIED, // 1
99 Favorites.INTENT, // 2
100 Favorites.APPWIDGET_PROVIDER, // 3
101 Favorites.APPWIDGET_ID, // 4
102 Favorites.CELLX, // 5
103 Favorites.CELLY, // 6
104 Favorites.CONTAINER, // 7
105 Favorites.ICON, // 8
106 Favorites.ICON_PACKAGE, // 9
107 Favorites.ICON_RESOURCE, // 10
108 Favorites.ICON_TYPE, // 11
109 Favorites.ITEM_TYPE, // 12
110 Favorites.SCREEN, // 13
111 Favorites.SPANX, // 14
112 Favorites.SPANY, // 15
113 Favorites.TITLE, // 16
114 Favorites.PROFILE_ID, // 17
Chris Wren1ada10d2013-09-13 18:01:38 -0400115 };
116
117 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400118 private static final int ID_MODIFIED = 1;
119 private static final int INTENT_INDEX = 2;
120 private static final int APPWIDGET_PROVIDER_INDEX = 3;
121 private static final int APPWIDGET_ID_INDEX = 4;
122 private static final int CELLX_INDEX = 5;
123 private static final int CELLY_INDEX = 6;
124 private static final int CONTAINER_INDEX = 7;
125 private static final int ICON_INDEX = 8;
126 private static final int ICON_PACKAGE_INDEX = 9;
127 private static final int ICON_RESOURCE_INDEX = 10;
128 private static final int ICON_TYPE_INDEX = 11;
129 private static final int ITEM_TYPE_INDEX = 12;
130 private static final int SCREEN_INDEX = 13;
131 private static final int SPANX_INDEX = 14;
132 private static final int SPANY_INDEX = 15;
133 private static final int TITLE_INDEX = 16;
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
Chris Wren92aa4232013-10-04 11:29:36 -0400143 private 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;
Chris Wren1ada10d2013-09-13 18:01:38 -0400147
Sunny Goyalef728d42014-10-22 11:28:28 -0700148 private IconCache mIconCache;
149 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
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700154 private DeviceProfieData mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700155 boolean restoreSuccessful;
Sunny Goyal08f72612015-01-05 13:41:43 -0800156 int restoredBackupVersion = 1;
Sunny Goyal33d44382014-10-16 09:24:19 -0700157
158 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400159 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700160 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700161 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700162 restoreSuccessful = true;
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800163 mItemTypeMatchers = new ItemTypeMatcher[CommonAppTypeParser.SUPPORTED_TYPE_COUNT];
Chris Wren92aa4232013-10-04 11:29:36 -0400164 }
165
166 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700167 if (mBackupManager == null) {
168 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400169 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700170 mBackupManager.dataChanged();
171 }
172
173 private void applyJournal(Journal journal) {
174 mLastBackupRestoreTime = journal.t;
175 mExistingKeys.clear();
176 if (journal.key != null) {
177 for (Key key : journal.key) {
178 mExistingKeys.add(keyToBackupKey(key));
179 }
180 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400181 }
182
183 /**
184 * Back up launcher data so we can restore the user's state on a new device.
185 *
186 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
187 *
188 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
189 *
190 * @param oldState notes from the last backup
191 * @param data incremental key/value pairs to persist off-device
192 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400193 */
194 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400195 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
196 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500197 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400198
199 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700200 if (!launcherIsReady()) {
201 // Perform backup later.
202 writeJournal(newState, in);
203 return;
204 }
205 Log.v(TAG, "lastBackupTime = " + in.t);
206 mKeys.clear();
207 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400208
Sunny Goyalef728d42014-10-22 11:28:28 -0700209 // Record the time before performing backup so that entries edited while the backup
210 // was going on, do not get missed in next backup.
211 long newBackupTime = System.currentTimeMillis();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800212 mBackupDataWasUpdated = false;
Sunny Goyalef728d42014-10-22 11:28:28 -0700213 try {
214 backupFavorites(data);
215 backupScreens(data);
216 backupIcons(data);
217 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400218
Sunny Goyalef728d42014-10-22 11:28:28 -0700219 // Delete any key which still exist in the old backup, but is not valid anymore.
220 HashSet<String> validKeys = new HashSet<String>();
221 for (Key key : mKeys) {
222 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500223 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700224 mExistingKeys.removeAll(validKeys);
225
226 // Delete anything left in the existing keys.
227 for (String deleted: mExistingKeys) {
228 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
229 data.writeEntityHeader(deleted, -1);
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800230 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -0700231 }
232
233 mExistingKeys.clear();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800234 if (!mBackupDataWasUpdated) {
235 // Check if any metadata has changed
236 mBackupDataWasUpdated = (in.profile == null)
237 || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
238 DeviceProfieData.toByteArray(getDeviceProfieData()))
239 || (in.backupVersion != BACKUP_VERSION)
240 || (in.appVersion != getAppVersion());
241 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700242
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800243 if (mBackupDataWasUpdated) {
244 mLastBackupRestoreTime = newBackupTime;
245
246 // We store the journal at two places.
247 // 1) Storing it in newState allows us to do partial backups by comparing old state
248 // 2) Storing it in backup data allows us to validate keys during restore
249 Journal state = getCurrentStateJournal();
250 writeRowToBackup(JOURNAL_KEY, state, data);
251 } else {
252 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
253 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700254 } catch (IOException e) {
255 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400256 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400257
Sunny Goyalef728d42014-10-22 11:28:28 -0700258 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400259 }
260
261 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700262 * @return true if the backup corresponding to oldstate can be successfully applied
263 * to this device.
264 */
265 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700266 DeviceProfieData currentProfile = getDeviceProfieData();
267
268 DeviceProfieData oldProfile = oldState.profile;
269
270 if (oldProfile == null || oldProfile.desktopCols == 0) {
271 // Profile info is not valid, ignore the check.
272 return true;
273 }
274
275 boolean isHotsetCompatible = false;
276 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
277 isHotsetCompatible = true;
278 }
279 if ((currentProfile.hotseatCount >= oldProfile.hotseatCount) &&
280 (currentProfile.allappsRank == oldProfile.allappsRank)) {
281 isHotsetCompatible = true;
282 }
283
284 return isHotsetCompatible && (currentProfile.desktopCols >= oldProfile.desktopCols)
285 && (currentProfile.desktopRows >= oldProfile.desktopRows);
Sunny Goyal33d44382014-10-16 09:24:19 -0700286 }
287
288 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400289 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700290 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
291 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400292 *
Chris Wren92aa4232013-10-04 11:29:36 -0400293 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400294 */
295 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400296 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700297 if (!restoreSuccessful) {
298 return;
299 }
300
Sunny Goyalef728d42014-10-22 11:28:28 -0700301 int dataSize = data.size();
302 if (mBuffer.length < dataSize) {
303 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400304 }
305 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700306 int bytesRead = data.read(mBuffer, 0, dataSize);
307 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
308 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700309
310 if (JOURNAL_KEY.equals(backupKey)) {
311 if (VERBOSE) Log.v(TAG, "Journal entry restored");
312 if (!mKeys.isEmpty()) {
313 // We received the journal key after a restore key.
314 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
315 restoreSuccessful = false;
316 return;
317 }
318
319 Journal journal = new Journal();
320 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
321 applyJournal(journal);
322 restoreSuccessful = isBackupCompatible(journal);
Sunny Goyal08f72612015-01-05 13:41:43 -0800323 restoredBackupVersion = journal.backupVersion;
Sunny Goyal33d44382014-10-16 09:24:19 -0700324 return;
325 }
326
327 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
328 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
329 return;
330 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700331 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500332 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400333 switch (key.type) {
334 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700335 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400336 break;
337
338 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700339 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400340 break;
341
342 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700343 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400344 break;
345
346 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700347 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400348 break;
349
350 default:
351 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700352 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400353 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400354 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700355 } catch (IOException e) {
356 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400357 }
Chris Wren92aa4232013-10-04 11:29:36 -0400358 }
359
360 /**
361 * Record the restore state for the next backup.
362 *
363 * @param newState notes about the backup state after restore.
364 */
365 @Override
366 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700367 writeJournal(newState, getCurrentStateJournal());
368 }
369
370 private Journal getCurrentStateJournal() {
371 Journal journal = new Journal();
372 journal.t = mLastBackupRestoreTime;
373 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
374 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700375 journal.backupVersion = BACKUP_VERSION;
376 journal.profile = getDeviceProfieData();
Sunny Goyalef728d42014-10-22 11:28:28 -0700377 return journal;
378 }
379
380 private int getAppVersion() {
381 try {
382 return mContext.getPackageManager()
383 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
384 } catch (NameNotFoundException e) {
385 return 0;
386 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400387 }
388
389 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700390 * @return the current device profile information.
391 */
392 private DeviceProfieData getDeviceProfieData() {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700393 if (mCurrentProfile != null) {
394 return mCurrentProfile;
395 }
Chris Wrenb02e6112014-11-24 16:57:54 -0500396 final Context applicationContext = mContext.getApplicationContext();
397 DeviceProfile profile = LauncherAppState.createDynamicGrid(applicationContext, null)
398 .getDeviceProfile();
Sunny Goyal33d44382014-10-16 09:24:19 -0700399
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700400 mCurrentProfile = new DeviceProfieData();
401 mCurrentProfile.desktopRows = profile.numRows;
402 mCurrentProfile.desktopCols = profile.numColumns;
403 mCurrentProfile.hotseatCount = profile.numHotseatIcons;
404 mCurrentProfile.allappsRank = profile.hotseatAllAppsRank;
405 return mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700406 }
407
408 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400409 * Write all modified favorites to the data stream.
410 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400411 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400412 * @throws IOException
413 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700414 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400415 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400416 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700417 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400418 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700419 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400420 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400421 cursor.moveToPosition(-1);
422 while(cursor.moveToNext()) {
423 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700424 final long updateTime = cursor.getLong(ID_MODIFIED);
425 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700426 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700427 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700428 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
429 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500430 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700431 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400432 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400433 }
434 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400435 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400436 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400437 }
438
439 /**
440 * Read a favorite from the stream.
441 *
442 * <P>Keys arrive in any order, so screens and containers may not exist yet.
443 *
444 * @param key identifier for the row
445 * @param buffer the serialized proto from the stream, may be larger than dataSize
446 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400447 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700448 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500449 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400450 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
451 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
452
Sunny Goyalef728d42014-10-22 11:28:28 -0700453 ContentResolver cr = mContext.getContentResolver();
454 ContentValues values = unpackFavorite(buffer, dataSize);
455 cr.insert(Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400456 }
457
458 /**
459 * Write all modified screens to the data stream.
460 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400461 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400462 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400463 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700464 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400465 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400466 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400467 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
468 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400469 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400470 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700471 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400472 while(cursor.moveToNext()) {
473 final long id = cursor.getLong(ID_INDEX);
474 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400475 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700476 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500477 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700478 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
479 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500480 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700481 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400482 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400483 }
484 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400485 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400486 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400487 }
488
489 /**
490 * Read a screen from the stream.
491 *
492 * <P>Keys arrive in any order, so children of this screen may already exist.
493 *
494 * @param key identifier for the row
495 * @param buffer the serialized proto from the stream, may be larger than dataSize
496 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400497 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700498 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500499 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400500 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
501 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500502
Sunny Goyalef728d42014-10-22 11:28:28 -0700503 ContentResolver cr = mContext.getContentResolver();
504 ContentValues values = unpackScreen(buffer, dataSize);
505 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400506 }
507
Chris Wren22e130d2013-09-23 18:25:57 -0400508 /**
509 * Write all the static icon resources we need to render placeholders
510 * for a package that is not installed.
511 *
Chris Wren22e130d2013-09-23 18:25:57 -0400512 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400513 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700514 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400515 // persist icons that haven't been persisted yet
Chris Wren6d0dde02014-02-10 12:16:54 -0500516 if (!initializeIconCache()) {
Chris Wren92aa4232013-10-04 11:29:36 -0400517 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400518 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
519 return;
520 }
Chris Wren92aa4232013-10-04 11:29:36 -0400521 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400522 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700523 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700524 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400525
Kenny Guyed131872014-04-30 03:02:21 +0100526 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100527 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100528 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700529 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400530 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
531 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400532 try {
533 cursor.moveToPosition(-1);
534 while(cursor.moveToNext()) {
535 final long id = cursor.getLong(ID_INDEX);
536 final String intentDescription = cursor.getString(INTENT_INDEX);
537 try {
538 Intent intent = Intent.parseUri(intentDescription, 0);
539 ComponentName cn = intent.getComponent();
540 Key key = null;
541 String backupKey = null;
542 if (cn != null) {
543 key = getKey(Key.ICON, cn.flattenToShortString());
544 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400545 } else {
546 Log.w(TAG, "empty intent on application favorite: " + id);
547 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700548 if (mExistingKeys.contains(backupKey)) {
549 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400550
551 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700552 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400553 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700554 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
555 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
556 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100557 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100558 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700559 writeRowToBackup(key, packIcon(dpi, icon), data);
560 mKeys.add(key);
561 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400562 }
563 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700564 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400565 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400566 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400567 }
568 }
569 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500570 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400571 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500572 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400573 }
574
575 }
576 } finally {
577 cursor.close();
578 }
Chris Wren22e130d2013-09-23 18:25:57 -0400579 }
580
581 /**
582 * Read an icon from the stream.
583 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400584 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400585 *
586 * @param key identifier for the row
587 * @param buffer the serialized proto from the stream, may be larger than dataSize
588 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400589 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700590 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500591 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400592 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
593 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500594
Sunny Goyalef728d42014-10-22 11:28:28 -0700595 Resource res = unpackProto(new Resource(), buffer, dataSize);
596 if (DEBUG) {
597 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400598 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700599 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
600 if (icon == null) {
601 Log.w(TAG, "failed to unpack icon for " + key.name);
602 }
603 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
604 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(key.name), icon, res.dpi);
Chris Wren22e130d2013-09-23 18:25:57 -0400605 }
606
Chris Wrenfd13c712013-09-27 15:45:19 -0400607 /**
608 * Write all the static widget resources we need to render placeholders
609 * for a package that is not installed.
610 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400611 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400612 * @throws IOException
613 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700614 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400615 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400616 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
Chris Wren6d0dde02014-02-10 12:16:54 -0500617 if (appState == null || !initializeIconCache()) {
618 Log.w(TAG, "Failed to get icon cache during restore");
Chris Wrend8fe6de2013-10-04 10:42:14 -0400619 return;
620 }
Chris Wren92aa4232013-10-04 11:29:36 -0400621 final ContentResolver cr = mContext.getContentResolver();
622 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
623 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wren92aa4232013-10-04 11:29:36 -0400624 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400625 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
626 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
Sunny Goyalef728d42014-10-22 11:28:28 -0700627 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400628
Sunny Goyalffe83f12014-08-14 17:39:34 -0700629 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
630 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400631 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
632 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400633 try {
634 cursor.moveToPosition(-1);
635 while(cursor.moveToNext()) {
636 final long id = cursor.getLong(ID_INDEX);
637 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
638 final int spanX = cursor.getInt(SPANX_INDEX);
639 final int spanY = cursor.getInt(SPANY_INDEX);
640 final ComponentName provider = ComponentName.unflattenFromString(providerName);
641 Key key = null;
642 String backupKey = null;
643 if (provider != null) {
644 key = getKey(Key.WIDGET, providerName);
645 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400646 } else {
647 Log.w(TAG, "empty intent on appwidget: " + id);
648 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700649 if (mExistingKeys.contains(backupKey)) {
650 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400651
652 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700653 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400654 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700655 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
656 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
657 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400658 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
659 spanY * profile.cellHeightPx, widgetSpacingLayout);
Sunny Goyalef728d42014-10-22 11:28:28 -0700660 writeRowToBackup(key, packWidget(dpi, previewLoader, mIconCache, provider), data);
661 mKeys.add(key);
662 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400663 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700664 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400665 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400666 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400667 }
668 }
669 }
670 } finally {
671 cursor.close();
672 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400673 }
674
675 /**
676 * Read a widget from the stream.
677 *
678 * <P>Keys arrive in any order, so widgets that use this data may already exist.
679 *
680 * @param key identifier for the row
681 * @param buffer the serialized proto from the stream, may be larger than dataSize
682 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400683 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700684 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500685 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400686 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
687 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700688 Widget widget = unpackProto(new Widget(), buffer, dataSize);
689 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
690 if (widget.icon.data != null) {
691 Bitmap icon = BitmapFactory
692 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
693 if (icon == null) {
694 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500695 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700696 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(widget.provider),
697 icon, widget.icon.dpi);
Chris Wren5dee7af2013-12-20 17:22:11 -0500698 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400699 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700700
701 // future site of widget table mutation
Chris Wrenfd13c712013-09-27 15:45:19 -0400702 }
703
Chris Wren22e130d2013-09-23 18:25:57 -0400704 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400705 *
706 * <P> Keys contain their own checksum instead of using
707 * the heavy-weight CheckedMessage wrapper.
708 */
709 private Key getKey(int type, long id) {
710 Key key = new Key();
711 key.type = type;
712 key.id = id;
713 key.checksum = checkKey(key);
714 return key;
715 }
716
Chris Wren22e130d2013-09-23 18:25:57 -0400717 /** create a new key for a named object.
718 *
719 * <P> Keys contain their own checksum instead of using
720 * the heavy-weight CheckedMessage wrapper.
721 */
722 private Key getKey(int type, String name) {
723 Key key = new Key();
724 key.type = type;
725 key.name = name;
726 key.checksum = checkKey(key);
727 return key;
728 }
729
Chris Wren1ada10d2013-09-13 18:01:38 -0400730 /** keys need to be strings, serialize and encode. */
731 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400732 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400733 }
734
735 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700736 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400737 try {
738 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
739 if (key.checksum != checkKey(key)) {
740 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700741 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400742 }
743 return key;
744 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700745 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400746 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700747 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400748 }
749 }
750
751 /** Compute the checksum over the important bits of a key. */
752 private long checkKey(Key key) {
753 CRC32 checksum = new CRC32();
754 checksum.update(key.type);
755 checksum.update((int) (key.id & 0xffff));
756 checksum.update((int) ((key.id >> 32) & 0xffff));
757 if (!TextUtils.isEmpty(key.name)) {
758 checksum.update(key.name.getBytes());
759 }
760 return checksum.getValue();
761 }
762
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800763 /**
764 * @return true if its an hotseat item, that can be replaced during restore.
765 * TODO: Extend check for folders in hotseat.
766 */
767 private boolean isReplaceableHotseatItem(Favorite favorite) {
768 return favorite.container == Favorites.CONTAINER_HOTSEAT
769 && favorite.intent != null
770 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
771 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
772 }
773
Chris Wren1ada10d2013-09-13 18:01:38 -0400774 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700775 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400776 Favorite favorite = new Favorite();
777 favorite.id = c.getLong(ID_INDEX);
778 favorite.screen = c.getInt(SCREEN_INDEX);
779 favorite.container = c.getInt(CONTAINER_INDEX);
780 favorite.cellX = c.getInt(CELLX_INDEX);
781 favorite.cellY = c.getInt(CELLY_INDEX);
782 favorite.spanX = c.getInt(SPANX_INDEX);
783 favorite.spanY = c.getInt(SPANY_INDEX);
784 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
785 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
786 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
787 if (!TextUtils.isEmpty(iconPackage)) {
788 favorite.iconPackage = iconPackage;
789 }
790 String iconResource = c.getString(ICON_RESOURCE_INDEX);
791 if (!TextUtils.isEmpty(iconResource)) {
792 favorite.iconResource = iconResource;
793 }
794 }
795 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
796 byte[] blob = c.getBlob(ICON_INDEX);
797 if (blob != null && blob.length > 0) {
798 favorite.icon = blob;
799 }
800 }
801 String title = c.getString(TITLE_INDEX);
802 if (!TextUtils.isEmpty(title)) {
803 favorite.title = title;
804 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100805 String intentDescription = c.getString(INTENT_INDEX);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800806 Intent intent = null;
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100807 if (!TextUtils.isEmpty(intentDescription)) {
808 try {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800809 intent = Intent.parseUri(intentDescription, 0);
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100810 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
811 favorite.intent = intent.toUri(0);
812 } catch (URISyntaxException e) {
813 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700814 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400815 }
816 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
817 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
818 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
819 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
820 if (!TextUtils.isEmpty(appWidgetProvider)) {
821 favorite.appWidgetProvider = appWidgetProvider;
822 }
823 }
824
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800825 if (isReplaceableHotseatItem(favorite)) {
826 if (intent != null && intent.getComponent() != null) {
827 PackageManager pm = mContext.getPackageManager();
828 ActivityInfo activity = null;;
829 try {
830 activity = pm.getActivityInfo(intent.getComponent(), 0);
831 } catch (NameNotFoundException e) {
832 Log.e(TAG, "Target not found", e);
833 }
834 if (activity == null) {
835 return favorite;
836 }
837 for (int i = 0; i < mItemTypeMatchers.length; i++) {
838 if (mItemTypeMatchers[i] == null) {
839 mItemTypeMatchers[i] = new ItemTypeMatcher(
840 CommonAppTypeParser.getResourceForItemType(i));
841 }
842 if (mItemTypeMatchers[i].matches(activity, pm)) {
843 favorite.targetType = i;
844 break;
845 }
846 }
847 }
848 }
849
Sunny Goyalef728d42014-10-22 11:28:28 -0700850 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400851 }
852
853 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700854 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700855 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700856 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800857
Chris Wren5dee7af2013-12-20 17:22:11 -0500858 ContentValues values = new ContentValues();
859 values.put(Favorites._ID, favorite.id);
860 values.put(Favorites.SCREEN, favorite.screen);
861 values.put(Favorites.CONTAINER, favorite.container);
862 values.put(Favorites.CELLX, favorite.cellX);
863 values.put(Favorites.CELLY, favorite.cellY);
864 values.put(Favorites.SPANX, favorite.spanX);
865 values.put(Favorites.SPANY, favorite.spanY);
866 values.put(Favorites.ICON_TYPE, favorite.iconType);
867 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
868 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
869 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
870 }
871 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
872 values.put(Favorites.ICON, favorite.icon);
873 }
874 if (!TextUtils.isEmpty(favorite.title)) {
875 values.put(Favorites.TITLE, favorite.title);
876 } else {
877 values.put(Favorites.TITLE, "");
878 }
879 if (!TextUtils.isEmpty(favorite.intent)) {
880 values.put(Favorites.INTENT, favorite.intent);
881 }
882 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500883
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100884 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
885 long userSerialNumber =
886 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
887 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
888
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700889 DeviceProfieData currentProfile = getDeviceProfieData();
890
Sunny Goyalff572272014-07-23 13:58:07 -0700891 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
892 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
893 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
894 }
895 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
896 values.put(LauncherSettings.Favorites.RESTORED,
897 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
898 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
899 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700900
901 // Verify placement
902 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
903 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
904 restoreSuccessful = false;
905 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
906 }
Sunny Goyalff572272014-07-23 13:58:07 -0700907 } else {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -0800908 // Check if it is an hotseat item, that can be replaced.
909 if (isReplaceableHotseatItem(favorite)
910 && favorite.targetType != Favorite.TARGET_NONE
911 && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
912 Log.e(TAG, "Added item type flag");
913 values.put(LauncherSettings.Favorites.RESTORED,
914 1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
915 } else {
916 // Let LauncherModel know we've been here.
917 values.put(LauncherSettings.Favorites.RESTORED, 1);
918 }
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700919
920 // Verify placement
921 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
922 if ((favorite.screen >= currentProfile.hotseatCount)
923 || (favorite.screen == currentProfile.allappsRank)) {
924 restoreSuccessful = false;
925 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
926 }
927 } else {
928 if ((favorite.cellX >= currentProfile.desktopCols)
929 || (favorite.cellY >= currentProfile.desktopRows)) {
930 restoreSuccessful = false;
931 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
932 }
933 }
Sunny Goyalff572272014-07-23 13:58:07 -0700934 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500935
Chris Wren5dee7af2013-12-20 17:22:11 -0500936 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400937 }
938
939 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700940 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400941 Screen screen = new Screen();
942 screen.id = c.getLong(ID_INDEX);
943 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700944 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400945 }
946
947 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700948 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400949 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700950 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500951 ContentValues values = new ContentValues();
952 values.put(WorkspaceScreens._ID, screen.id);
953 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
954 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400955 }
956
Chris Wren22e130d2013-09-23 18:25:57 -0400957 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700958 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400959 Resource res = new Resource();
960 res.dpi = dpi;
961 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400962 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400963 res.data = os.toByteArray();
964 }
Chris Wren22e130d2013-09-23 18:25:57 -0400965 return res;
966 }
967
Chris Wrenfd13c712013-09-27 15:45:19 -0400968 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700969 private Widget packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
Chris Wrenfd13c712013-09-27 15:45:19 -0400970 ComponentName provider) {
Adam Cohen59400422014-03-05 18:07:04 -0800971 final LauncherAppWidgetProviderInfo info =
972 LauncherModel.getProviderInfo(mContext, provider);
Chris Wrenfd13c712013-09-27 15:45:19 -0400973 Widget widget = new Widget();
974 widget.provider = provider.flattenToShortString();
975 widget.label = info.label;
976 widget.configure = info.configure != null;
977 if (info.icon != 0) {
978 widget.icon = new Resource();
979 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400980 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400981 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400982 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400983 widget.icon.data = os.toByteArray();
984 widget.icon.dpi = dpi;
985 }
986 }
987 if (info.previewImage != 0) {
988 widget.preview = new Resource();
989 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
990 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400991 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400992 widget.preview.data = os.toByteArray();
993 widget.preview.dpi = dpi;
994 }
995 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700996 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -0400997 }
998
Sunny Goyalef728d42014-10-22 11:28:28 -0700999 /**
1000 * Deserialize a proto after verifying checksum wrapper.
1001 */
1002 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -04001003 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001004 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
1005 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
1006 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -04001007 }
1008
Chris Wren1ada10d2013-09-13 18:01:38 -04001009 /**
1010 * Read the old journal from the input file.
1011 *
1012 * In the event of any error, just pretend we didn't have a journal,
1013 * in that case, do a full backup.
1014 *
1015 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -05001016 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -04001017 */
1018 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001019 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -04001020 if (oldState == null) {
1021 return journal;
1022 }
1023 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
1024 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001025 int availableBytes = inStream.available();
1026 if (DEBUG) Log.d(TAG, "available " + availableBytes);
1027 if (availableBytes < MAX_JOURNAL_SIZE) {
1028 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -04001029 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -05001030 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -05001031 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001032 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -04001033 try {
Chris Wren65b6a602014-01-10 14:11:25 -05001034 // OMG what are you doing? This is crazy inefficient!
1035 // If we read a byte that is not ours, we will cause trouble: b/12491813
1036 // However, we don't know how many bytes to expect (oops).
1037 // So we have to step through *slowly*, watching for the end.
1038 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -04001039 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -05001040 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -04001041 bytesRead += result;
1042 } else {
Chris Wren65b6a602014-01-10 14:11:25 -05001043 Log.w(TAG, "unexpected end of file while reading journal.");
1044 // stop reading and see what there is to parse
1045 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -04001046 }
1047 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -04001048 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -05001049 availableBytes = 0;
1050 }
1051
1052 // check the buffer to see if we have a valid journal
1053 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001054 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001055 // if we are here, then we have read a valid, checksum-verified journal
1056 valid = true;
1057 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001058 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001059 } catch (InvalidProtocolBufferNanoException e) {
1060 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001061 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001062 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001063 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001064 }
Chris Wren92aa4232013-10-04 11:29:36 -04001065 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001066 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001067 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001068 }
1069 }
Chris Wren92aa4232013-10-04 11:29:36 -04001070 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001071 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001072 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001073 try {
1074 inStream.close();
1075 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001076 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001077 }
1078 }
1079 return journal;
1080 }
1081
Sunny Goyalef728d42014-10-22 11:28:28 -07001082 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1083 throws IOException {
1084 writeRowToBackup(keyToBackupKey(key), proto, data);
1085 }
1086
1087 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001088 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001089 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001090 data.writeEntityHeader(backupKey, blob.length);
1091 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001092 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001093 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001094 }
1095
Chris Wren1ada10d2013-09-13 18:01:38 -04001096 /**
1097 * Write the new journal to the output file.
1098 *
1099 * In the event of any error, just pretend we didn't have a journal,
1100 * in that case, do a full backup.
1101
1102 * @param newState the write-only file descriptor pointing to the new journal
1103 * @param journal a Journal protocol buffer
1104 */
1105 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1106 FileOutputStream outStream = null;
1107 try {
1108 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001109 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001110 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001111 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001112 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001113 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001114 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001115 }
1116 }
1117
1118 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1119 private byte[] writeCheckedBytes(MessageNano proto) {
1120 CheckedMessage wrapper = new CheckedMessage();
1121 wrapper.payload = MessageNano.toByteArray(proto);
1122 CRC32 checksum = new CRC32();
1123 checksum.update(wrapper.payload);
1124 wrapper.checksum = checksum.getValue();
1125 return MessageNano.toByteArray(wrapper);
1126 }
1127
1128 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001129 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001130 throws InvalidProtocolBufferNanoException {
1131 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001132 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001133 CRC32 checksum = new CRC32();
1134 checksum.update(wrapper.payload);
1135 if (wrapper.checksum != checksum.getValue()) {
1136 throw new InvalidProtocolBufferNanoException("checksum does not match");
1137 }
1138 return wrapper.payload;
1139 }
1140
Chris Wren6d0dde02014-02-10 12:16:54 -05001141 private boolean initializeIconCache() {
1142 if (mIconCache != null) {
1143 return true;
1144 }
1145
1146 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
1147 if (appState == null) {
1148 Throwable stackTrace = new Throwable();
1149 stackTrace.fillInStackTrace();
1150 Log.w(TAG, "Failed to get app state during backup/restore", stackTrace);
1151 return false;
1152 }
1153 mIconCache = appState.getIconCache();
1154 return mIconCache != null;
1155 }
1156
Chris Wren71144262014-02-27 15:49:39 -05001157
Sunny Goyalef728d42014-10-22 11:28:28 -07001158 /**
1159 * @return true if the launcher is in a state to support backup
1160 */
Chris Wren71144262014-02-27 15:49:39 -05001161 private boolean launcherIsReady() {
1162 ContentResolver cr = mContext.getContentResolver();
1163 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1164 if (cursor == null) {
1165 // launcher data has been wiped, do nothing
1166 return false;
1167 }
1168 cursor.close();
1169
1170 if (!initializeIconCache()) {
1171 // launcher services are unavailable, try again later
1172 dataChanged();
1173 return false;
1174 }
1175
1176 return true;
1177 }
1178
Sunny Goyalffe83f12014-08-14 17:39:34 -07001179 private String getUserSelectionArg() {
1180 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1181 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1182 }
1183
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001184 private class InvalidBackupException extends IOException {
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001185
1186 private static final long serialVersionUID = 8931456637211665082L;
1187
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001188 private InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001189 super(cause);
1190 }
1191
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001192 public InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001193 super(reason);
1194 }
1195 }
Sunny Goyalbb3b02f2015-01-15 12:00:14 -08001196
1197 /**
1198 * A class to check if an activity can handle one of the intents from a list of
1199 * predefined intents.
1200 */
1201 private class ItemTypeMatcher {
1202
1203 private final ArrayList<Intent> mIntents;
1204
1205 ItemTypeMatcher(int xml_res) {
1206 mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
1207 }
1208
1209 private ArrayList<Intent> parseIntents(int xml_res) {
1210 ArrayList<Intent> intents = new ArrayList<Intent>();
1211 XmlResourceParser parser = mContext.getResources().getXml(xml_res);
1212 try {
1213 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
1214 final int depth = parser.getDepth();
1215 int type;
1216 while (((type = parser.next()) != XmlPullParser.END_TAG ||
1217 parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
1218 if (type != XmlPullParser.START_TAG) {
1219 continue;
1220 } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
1221 final String uri = DefaultLayoutParser.getAttributeValue(
1222 parser, DefaultLayoutParser.ATTR_URI);
1223 intents.add(Intent.parseUri(uri, 0));
1224 }
1225 }
1226 } catch (URISyntaxException | XmlPullParserException | IOException e) {
1227 Log.e(TAG, "Unable to parse " + xml_res, e);
1228 } finally {
1229 parser.close();
1230 }
1231 return intents;
1232 }
1233
1234 public boolean matches(ActivityInfo activity, PackageManager pm) {
1235 for (Intent intent : mIntents) {
1236 intent.setPackage(activity.packageName);
1237 ResolveInfo info = pm.resolveActivity(intent, 0);
1238 if (info != null && (info.activityInfo.name.equals(activity.name)
1239 || info.activityInfo.name.equals(activity.targetActivity))) {
1240 return true;
1241 }
1242 }
1243 return false;
1244 }
1245 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001246}