blob: 32bea5baafd7c9b9a95fda7047ced3cdb2550b3a [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.appwidget.AppWidgetProviderInfo;
23import android.content.ComponentName;
Chris Wren1ada10d2013-09-13 18:01:38 -040024import android.content.ContentResolver;
Chris Wren5dee7af2013-12-20 17:22:11 -050025import android.content.ContentValues;
Chris Wren1ada10d2013-09-13 18:01:38 -040026import android.content.Context;
Chris Wren22e130d2013-09-23 18:25:57 -040027import android.content.Intent;
Sunny Goyalef728d42014-10-22 11:28:28 -070028import android.content.pm.PackageManager.NameNotFoundException;
Chris Wren1ada10d2013-09-13 18:01:38 -040029import android.database.Cursor;
Chris Wren22e130d2013-09-23 18:25:57 -040030import android.graphics.Bitmap;
31import android.graphics.BitmapFactory;
Chris Wrenfd13c712013-09-27 15:45:19 -040032import android.graphics.drawable.Drawable;
Chris Wren1ada10d2013-09-13 18:01:38 -040033import android.os.ParcelFileDescriptor;
Chris Wren1ada10d2013-09-13 18:01:38 -040034import android.text.TextUtils;
35import android.util.Base64;
36import android.util.Log;
37
Sunny Goyalef728d42014-10-22 11:28:28 -070038import com.android.launcher3.LauncherSettings.Favorites;
39import com.android.launcher3.LauncherSettings.WorkspaceScreens;
40import com.android.launcher3.backup.BackupProtos;
41import com.android.launcher3.backup.BackupProtos.CheckedMessage;
Sunny Goyal33d44382014-10-16 09:24:19 -070042import com.android.launcher3.backup.BackupProtos.DeviceProfieData;
Sunny Goyalef728d42014-10-22 11:28:28 -070043import com.android.launcher3.backup.BackupProtos.Favorite;
44import com.android.launcher3.backup.BackupProtos.Journal;
45import com.android.launcher3.backup.BackupProtos.Key;
46import com.android.launcher3.backup.BackupProtos.Resource;
47import com.android.launcher3.backup.BackupProtos.Screen;
48import com.android.launcher3.backup.BackupProtos.Widget;
49import com.android.launcher3.compat.UserHandleCompat;
50import com.android.launcher3.compat.UserManagerCompat;
51import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
52import com.google.protobuf.nano.MessageNano;
53
Chris Wren22e130d2013-09-23 18:25:57 -040054import java.io.ByteArrayOutputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040055import java.io.FileInputStream;
56import java.io.FileOutputStream;
57import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040058import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040059import java.util.ArrayList;
Sunny Goyalc0ee6752015-01-16 14:10:32 -080060import java.util.Arrays;
Chris Wren22e130d2013-09-23 18:25:57 -040061import java.util.HashMap;
Chris Wren1ada10d2013-09-13 18:01:38 -040062import java.util.HashSet;
Chris Wren1ada10d2013-09-13 18:01:38 -040063import java.util.zip.CRC32;
64
65/**
66 * Persist the launcher home state across calamities.
67 */
Chris Wren92aa4232013-10-04 11:29:36 -040068public class LauncherBackupHelper implements BackupHelper {
Chris Wren92aa4232013-10-04 11:29:36 -040069 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050070 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
71 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren1ada10d2013-09-13 18:01:38 -040072
Sunny Goyal33d44382014-10-16 09:24:19 -070073 private static final int BACKUP_VERSION = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -040074 private static final int MAX_JOURNAL_SIZE = 1000000;
75
Sunny Goyal33d44382014-10-16 09:24:19 -070076 // Journal key is such that it is always smaller than any dynamically generated
77 // key (any Base64 encoded string).
78 private static final String JOURNAL_KEY = "#";
79
Chris Wrenfd13c712013-09-27 15:45:19 -040080 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040081 private static final int MAX_ICONS_PER_PASS = 10;
82
Chris Wrenfd13c712013-09-27 15:45:19 -040083 /** widgets contain previews, which are very large, dribble them out */
84 private static final int MAX_WIDGETS_PER_PASS = 5;
85
Sunny Goyal33d44382014-10-16 09:24:19 -070086 private static final int IMAGE_COMPRESSION_QUALITY = 75;
Chris Wren45297f82013-10-17 15:16:48 -040087
Chris Wrenb86f0762013-10-04 10:10:21 -040088 private static final Bitmap.CompressFormat IMAGE_FORMAT =
89 android.graphics.Bitmap.CompressFormat.PNG;
90
Chris Wren1ada10d2013-09-13 18:01:38 -040091 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070092 Favorites._ID, // 0
93 Favorites.MODIFIED, // 1
94 Favorites.INTENT, // 2
95 Favorites.APPWIDGET_PROVIDER, // 3
96 Favorites.APPWIDGET_ID, // 4
97 Favorites.CELLX, // 5
98 Favorites.CELLY, // 6
99 Favorites.CONTAINER, // 7
100 Favorites.ICON, // 8
101 Favorites.ICON_PACKAGE, // 9
102 Favorites.ICON_RESOURCE, // 10
103 Favorites.ICON_TYPE, // 11
104 Favorites.ITEM_TYPE, // 12
105 Favorites.SCREEN, // 13
106 Favorites.SPANX, // 14
107 Favorites.SPANY, // 15
108 Favorites.TITLE, // 16
109 Favorites.PROFILE_ID, // 17
Chris Wren1ada10d2013-09-13 18:01:38 -0400110 };
111
112 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400113 private static final int ID_MODIFIED = 1;
114 private static final int INTENT_INDEX = 2;
115 private static final int APPWIDGET_PROVIDER_INDEX = 3;
116 private static final int APPWIDGET_ID_INDEX = 4;
117 private static final int CELLX_INDEX = 5;
118 private static final int CELLY_INDEX = 6;
119 private static final int CONTAINER_INDEX = 7;
120 private static final int ICON_INDEX = 8;
121 private static final int ICON_PACKAGE_INDEX = 9;
122 private static final int ICON_RESOURCE_INDEX = 10;
123 private static final int ICON_TYPE_INDEX = 11;
124 private static final int ITEM_TYPE_INDEX = 12;
125 private static final int SCREEN_INDEX = 13;
126 private static final int SPANX_INDEX = 14;
127 private static final int SPANY_INDEX = 15;
128 private static final int TITLE_INDEX = 16;
Chris Wren1ada10d2013-09-13 18:01:38 -0400129
130 private static final String[] SCREEN_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -0700131 WorkspaceScreens._ID, // 0
132 WorkspaceScreens.MODIFIED, // 1
133 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400134 };
135
Chris Wren22e130d2013-09-23 18:25:57 -0400136 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400137
Chris Wren92aa4232013-10-04 11:29:36 -0400138 private final Context mContext;
Sunny Goyalef728d42014-10-22 11:28:28 -0700139 private final HashSet<String> mExistingKeys;
Sunny Goyal42de82f2014-09-26 22:09:29 -0700140 private final ArrayList<Key> mKeys;
Chris Wren1ada10d2013-09-13 18:01:38 -0400141
Sunny Goyalef728d42014-10-22 11:28:28 -0700142 private IconCache mIconCache;
143 private BackupManager mBackupManager;
Sunny Goyalef728d42014-10-22 11:28:28 -0700144 private byte[] mBuffer = new byte[512];
145 private long mLastBackupRestoreTime;
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800146 private boolean mBackupDataWasUpdated;
Sunny Goyalef728d42014-10-22 11:28:28 -0700147
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700148 private DeviceProfieData mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700149 boolean restoreSuccessful;
Sunny Goyal08f72612015-01-05 13:41:43 -0800150 int restoredBackupVersion = 1;
Sunny Goyal33d44382014-10-16 09:24:19 -0700151
152 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400153 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700154 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700155 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700156 restoreSuccessful = true;
Chris Wren92aa4232013-10-04 11:29:36 -0400157 }
158
159 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700160 if (mBackupManager == null) {
161 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400162 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700163 mBackupManager.dataChanged();
164 }
165
166 private void applyJournal(Journal journal) {
167 mLastBackupRestoreTime = journal.t;
168 mExistingKeys.clear();
169 if (journal.key != null) {
170 for (Key key : journal.key) {
171 mExistingKeys.add(keyToBackupKey(key));
172 }
173 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400174 }
175
176 /**
177 * Back up launcher data so we can restore the user's state on a new device.
178 *
179 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
180 *
181 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
182 *
183 * @param oldState notes from the last backup
184 * @param data incremental key/value pairs to persist off-device
185 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400186 */
187 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400188 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
189 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500190 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400191
192 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700193 if (!launcherIsReady()) {
194 // Perform backup later.
195 writeJournal(newState, in);
196 return;
197 }
198 Log.v(TAG, "lastBackupTime = " + in.t);
199 mKeys.clear();
200 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400201
Sunny Goyalef728d42014-10-22 11:28:28 -0700202 // Record the time before performing backup so that entries edited while the backup
203 // was going on, do not get missed in next backup.
204 long newBackupTime = System.currentTimeMillis();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800205 mBackupDataWasUpdated = false;
Sunny Goyalef728d42014-10-22 11:28:28 -0700206 try {
207 backupFavorites(data);
208 backupScreens(data);
209 backupIcons(data);
210 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400211
Sunny Goyalef728d42014-10-22 11:28:28 -0700212 // Delete any key which still exist in the old backup, but is not valid anymore.
213 HashSet<String> validKeys = new HashSet<String>();
214 for (Key key : mKeys) {
215 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500216 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700217 mExistingKeys.removeAll(validKeys);
218
219 // Delete anything left in the existing keys.
220 for (String deleted: mExistingKeys) {
221 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
222 data.writeEntityHeader(deleted, -1);
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800223 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -0700224 }
225
226 mExistingKeys.clear();
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800227 if (!mBackupDataWasUpdated) {
228 // Check if any metadata has changed
229 mBackupDataWasUpdated = (in.profile == null)
230 || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
231 DeviceProfieData.toByteArray(getDeviceProfieData()))
232 || (in.backupVersion != BACKUP_VERSION)
233 || (in.appVersion != getAppVersion());
234 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700235
Sunny Goyalc0ee6752015-01-16 14:10:32 -0800236 if (mBackupDataWasUpdated) {
237 mLastBackupRestoreTime = newBackupTime;
238
239 // We store the journal at two places.
240 // 1) Storing it in newState allows us to do partial backups by comparing old state
241 // 2) Storing it in backup data allows us to validate keys during restore
242 Journal state = getCurrentStateJournal();
243 writeRowToBackup(JOURNAL_KEY, state, data);
244 } else {
245 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
246 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700247 } catch (IOException e) {
248 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400249 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400250
Sunny Goyalef728d42014-10-22 11:28:28 -0700251 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400252 }
253
254 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700255 * @return true if the backup corresponding to oldstate can be successfully applied
256 * to this device.
257 */
258 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700259 DeviceProfieData currentProfile = getDeviceProfieData();
260
261 DeviceProfieData oldProfile = oldState.profile;
262
263 if (oldProfile == null || oldProfile.desktopCols == 0) {
264 // Profile info is not valid, ignore the check.
265 return true;
266 }
267
268 boolean isHotsetCompatible = false;
269 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
270 isHotsetCompatible = true;
271 }
272 if ((currentProfile.hotseatCount >= oldProfile.hotseatCount) &&
273 (currentProfile.allappsRank == oldProfile.allappsRank)) {
274 isHotsetCompatible = true;
275 }
276
277 return isHotsetCompatible && (currentProfile.desktopCols >= oldProfile.desktopCols)
278 && (currentProfile.desktopRows >= oldProfile.desktopRows);
Sunny Goyal33d44382014-10-16 09:24:19 -0700279 }
280
281 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400282 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700283 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
284 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400285 *
Chris Wren92aa4232013-10-04 11:29:36 -0400286 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400287 */
288 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400289 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700290 if (!restoreSuccessful) {
291 return;
292 }
293
Sunny Goyalef728d42014-10-22 11:28:28 -0700294 int dataSize = data.size();
295 if (mBuffer.length < dataSize) {
296 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400297 }
298 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700299 int bytesRead = data.read(mBuffer, 0, dataSize);
300 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
301 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700302
303 if (JOURNAL_KEY.equals(backupKey)) {
304 if (VERBOSE) Log.v(TAG, "Journal entry restored");
305 if (!mKeys.isEmpty()) {
306 // We received the journal key after a restore key.
307 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
308 restoreSuccessful = false;
309 return;
310 }
311
312 Journal journal = new Journal();
313 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
314 applyJournal(journal);
315 restoreSuccessful = isBackupCompatible(journal);
Sunny Goyal08f72612015-01-05 13:41:43 -0800316 restoredBackupVersion = journal.backupVersion;
Sunny Goyal33d44382014-10-16 09:24:19 -0700317 return;
318 }
319
320 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
321 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
322 return;
323 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700324 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500325 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400326 switch (key.type) {
327 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700328 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400329 break;
330
331 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700332 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400333 break;
334
335 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700336 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400337 break;
338
339 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700340 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400341 break;
342
343 default:
344 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700345 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400346 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400347 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700348 } catch (IOException e) {
349 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400350 }
Chris Wren92aa4232013-10-04 11:29:36 -0400351 }
352
353 /**
354 * Record the restore state for the next backup.
355 *
356 * @param newState notes about the backup state after restore.
357 */
358 @Override
359 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700360 writeJournal(newState, getCurrentStateJournal());
361 }
362
363 private Journal getCurrentStateJournal() {
364 Journal journal = new Journal();
365 journal.t = mLastBackupRestoreTime;
366 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
367 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700368 journal.backupVersion = BACKUP_VERSION;
369 journal.profile = getDeviceProfieData();
Sunny Goyalef728d42014-10-22 11:28:28 -0700370 return journal;
371 }
372
373 private int getAppVersion() {
374 try {
375 return mContext.getPackageManager()
376 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
377 } catch (NameNotFoundException e) {
378 return 0;
379 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400380 }
381
382 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700383 * @return the current device profile information.
384 */
385 private DeviceProfieData getDeviceProfieData() {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700386 if (mCurrentProfile != null) {
387 return mCurrentProfile;
388 }
Chris Wrenb02e6112014-11-24 16:57:54 -0500389 final Context applicationContext = mContext.getApplicationContext();
390 DeviceProfile profile = LauncherAppState.createDynamicGrid(applicationContext, null)
391 .getDeviceProfile();
Sunny Goyal33d44382014-10-16 09:24:19 -0700392
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700393 mCurrentProfile = new DeviceProfieData();
394 mCurrentProfile.desktopRows = profile.numRows;
395 mCurrentProfile.desktopCols = profile.numColumns;
396 mCurrentProfile.hotseatCount = profile.numHotseatIcons;
397 mCurrentProfile.allappsRank = profile.hotseatAllAppsRank;
398 return mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700399 }
400
401 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400402 * Write all modified favorites to the data stream.
403 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400404 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400405 * @throws IOException
406 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700407 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400408 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400409 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700410 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400411 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700412 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400413 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400414 cursor.moveToPosition(-1);
415 while(cursor.moveToNext()) {
416 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700417 final long updateTime = cursor.getLong(ID_MODIFIED);
418 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700419 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700420 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700421 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
422 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500423 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700424 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400425 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400426 }
427 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400428 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400429 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400430 }
431
432 /**
433 * Read a favorite from the stream.
434 *
435 * <P>Keys arrive in any order, so screens and containers may not exist yet.
436 *
437 * @param key identifier for the row
438 * @param buffer the serialized proto from the stream, may be larger than dataSize
439 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400440 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700441 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500442 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400443 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
444 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
445
Sunny Goyalef728d42014-10-22 11:28:28 -0700446 ContentResolver cr = mContext.getContentResolver();
447 ContentValues values = unpackFavorite(buffer, dataSize);
448 cr.insert(Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400449 }
450
451 /**
452 * Write all modified screens to the data stream.
453 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400454 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400455 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400456 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700457 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400458 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400459 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400460 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
461 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400462 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400463 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700464 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400465 while(cursor.moveToNext()) {
466 final long id = cursor.getLong(ID_INDEX);
467 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400468 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700469 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500470 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700471 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
472 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500473 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700474 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400475 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400476 }
477 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400478 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400479 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400480 }
481
482 /**
483 * Read a screen from the stream.
484 *
485 * <P>Keys arrive in any order, so children of this screen may already exist.
486 *
487 * @param key identifier for the row
488 * @param buffer the serialized proto from the stream, may be larger than dataSize
489 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400490 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700491 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500492 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400493 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
494 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500495
Sunny Goyalef728d42014-10-22 11:28:28 -0700496 ContentResolver cr = mContext.getContentResolver();
497 ContentValues values = unpackScreen(buffer, dataSize);
498 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400499 }
500
Chris Wren22e130d2013-09-23 18:25:57 -0400501 /**
502 * Write all the static icon resources we need to render placeholders
503 * for a package that is not installed.
504 *
Chris Wren22e130d2013-09-23 18:25:57 -0400505 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400506 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700507 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400508 // persist icons that haven't been persisted yet
Chris Wren6d0dde02014-02-10 12:16:54 -0500509 if (!initializeIconCache()) {
Chris Wren92aa4232013-10-04 11:29:36 -0400510 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400511 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
512 return;
513 }
Chris Wren92aa4232013-10-04 11:29:36 -0400514 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400515 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700516 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700517 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400518
Kenny Guyed131872014-04-30 03:02:21 +0100519 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100520 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100521 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700522 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400523 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
524 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400525 try {
526 cursor.moveToPosition(-1);
527 while(cursor.moveToNext()) {
528 final long id = cursor.getLong(ID_INDEX);
529 final String intentDescription = cursor.getString(INTENT_INDEX);
530 try {
531 Intent intent = Intent.parseUri(intentDescription, 0);
532 ComponentName cn = intent.getComponent();
533 Key key = null;
534 String backupKey = null;
535 if (cn != null) {
536 key = getKey(Key.ICON, cn.flattenToShortString());
537 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400538 } else {
539 Log.w(TAG, "empty intent on application favorite: " + id);
540 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700541 if (mExistingKeys.contains(backupKey)) {
542 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400543
544 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700545 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400546 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700547 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
548 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
549 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100550 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100551 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700552 writeRowToBackup(key, packIcon(dpi, icon), data);
553 mKeys.add(key);
554 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400555 }
556 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700557 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400558 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400559 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400560 }
561 }
562 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500563 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400564 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500565 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400566 }
567
568 }
569 } finally {
570 cursor.close();
571 }
Chris Wren22e130d2013-09-23 18:25:57 -0400572 }
573
574 /**
575 * Read an icon from the stream.
576 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400577 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400578 *
579 * @param key identifier for the row
580 * @param buffer the serialized proto from the stream, may be larger than dataSize
581 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400582 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700583 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500584 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400585 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
586 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500587
Sunny Goyalef728d42014-10-22 11:28:28 -0700588 Resource res = unpackProto(new Resource(), buffer, dataSize);
589 if (DEBUG) {
590 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400591 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700592 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
593 if (icon == null) {
594 Log.w(TAG, "failed to unpack icon for " + key.name);
595 }
596 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
597 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(key.name), icon, res.dpi);
Chris Wren22e130d2013-09-23 18:25:57 -0400598 }
599
Chris Wrenfd13c712013-09-27 15:45:19 -0400600 /**
601 * Write all the static widget resources we need to render placeholders
602 * for a package that is not installed.
603 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400604 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400605 * @throws IOException
606 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700607 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400608 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400609 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
Chris Wren6d0dde02014-02-10 12:16:54 -0500610 if (appState == null || !initializeIconCache()) {
611 Log.w(TAG, "Failed to get icon cache during restore");
Chris Wrend8fe6de2013-10-04 10:42:14 -0400612 return;
613 }
Chris Wren92aa4232013-10-04 11:29:36 -0400614 final ContentResolver cr = mContext.getContentResolver();
615 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
616 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wren92aa4232013-10-04 11:29:36 -0400617 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400618 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
619 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
Sunny Goyalef728d42014-10-22 11:28:28 -0700620 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400621
Sunny Goyalffe83f12014-08-14 17:39:34 -0700622 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
623 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400624 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
625 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400626 try {
627 cursor.moveToPosition(-1);
628 while(cursor.moveToNext()) {
629 final long id = cursor.getLong(ID_INDEX);
630 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
631 final int spanX = cursor.getInt(SPANX_INDEX);
632 final int spanY = cursor.getInt(SPANY_INDEX);
633 final ComponentName provider = ComponentName.unflattenFromString(providerName);
634 Key key = null;
635 String backupKey = null;
636 if (provider != null) {
637 key = getKey(Key.WIDGET, providerName);
638 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400639 } else {
640 Log.w(TAG, "empty intent on appwidget: " + id);
641 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700642 if (mExistingKeys.contains(backupKey)) {
643 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400644
645 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700646 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400647 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700648 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
649 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
650 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400651 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
652 spanY * profile.cellHeightPx, widgetSpacingLayout);
Sunny Goyalef728d42014-10-22 11:28:28 -0700653 writeRowToBackup(key, packWidget(dpi, previewLoader, mIconCache, provider), data);
654 mKeys.add(key);
655 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400656 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700657 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400658 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400659 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400660 }
661 }
662 }
663 } finally {
664 cursor.close();
665 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400666 }
667
668 /**
669 * Read a widget from the stream.
670 *
671 * <P>Keys arrive in any order, so widgets that use this data may already exist.
672 *
673 * @param key identifier for the row
674 * @param buffer the serialized proto from the stream, may be larger than dataSize
675 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400676 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700677 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500678 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400679 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
680 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700681 Widget widget = unpackProto(new Widget(), buffer, dataSize);
682 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
683 if (widget.icon.data != null) {
684 Bitmap icon = BitmapFactory
685 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
686 if (icon == null) {
687 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500688 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700689 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(widget.provider),
690 icon, widget.icon.dpi);
Chris Wren5dee7af2013-12-20 17:22:11 -0500691 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400692 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700693
694 // future site of widget table mutation
Chris Wrenfd13c712013-09-27 15:45:19 -0400695 }
696
Chris Wren22e130d2013-09-23 18:25:57 -0400697 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400698 *
699 * <P> Keys contain their own checksum instead of using
700 * the heavy-weight CheckedMessage wrapper.
701 */
702 private Key getKey(int type, long id) {
703 Key key = new Key();
704 key.type = type;
705 key.id = id;
706 key.checksum = checkKey(key);
707 return key;
708 }
709
Chris Wren22e130d2013-09-23 18:25:57 -0400710 /** create a new key for a named object.
711 *
712 * <P> Keys contain their own checksum instead of using
713 * the heavy-weight CheckedMessage wrapper.
714 */
715 private Key getKey(int type, String name) {
716 Key key = new Key();
717 key.type = type;
718 key.name = name;
719 key.checksum = checkKey(key);
720 return key;
721 }
722
Chris Wren1ada10d2013-09-13 18:01:38 -0400723 /** keys need to be strings, serialize and encode. */
724 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400725 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400726 }
727
728 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700729 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400730 try {
731 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
732 if (key.checksum != checkKey(key)) {
733 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700734 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400735 }
736 return key;
737 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700738 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400739 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700740 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400741 }
742 }
743
744 /** Compute the checksum over the important bits of a key. */
745 private long checkKey(Key key) {
746 CRC32 checksum = new CRC32();
747 checksum.update(key.type);
748 checksum.update((int) (key.id & 0xffff));
749 checksum.update((int) ((key.id >> 32) & 0xffff));
750 if (!TextUtils.isEmpty(key.name)) {
751 checksum.update(key.name.getBytes());
752 }
753 return checksum.getValue();
754 }
755
756 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700757 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400758 Favorite favorite = new Favorite();
759 favorite.id = c.getLong(ID_INDEX);
760 favorite.screen = c.getInt(SCREEN_INDEX);
761 favorite.container = c.getInt(CONTAINER_INDEX);
762 favorite.cellX = c.getInt(CELLX_INDEX);
763 favorite.cellY = c.getInt(CELLY_INDEX);
764 favorite.spanX = c.getInt(SPANX_INDEX);
765 favorite.spanY = c.getInt(SPANY_INDEX);
766 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
767 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
768 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
769 if (!TextUtils.isEmpty(iconPackage)) {
770 favorite.iconPackage = iconPackage;
771 }
772 String iconResource = c.getString(ICON_RESOURCE_INDEX);
773 if (!TextUtils.isEmpty(iconResource)) {
774 favorite.iconResource = iconResource;
775 }
776 }
777 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
778 byte[] blob = c.getBlob(ICON_INDEX);
779 if (blob != null && blob.length > 0) {
780 favorite.icon = blob;
781 }
782 }
783 String title = c.getString(TITLE_INDEX);
784 if (!TextUtils.isEmpty(title)) {
785 favorite.title = title;
786 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100787 String intentDescription = c.getString(INTENT_INDEX);
788 if (!TextUtils.isEmpty(intentDescription)) {
789 try {
790 Intent intent = Intent.parseUri(intentDescription, 0);
791 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
792 favorite.intent = intent.toUri(0);
793 } catch (URISyntaxException e) {
794 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700795 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400796 }
797 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
798 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
799 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
800 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
801 if (!TextUtils.isEmpty(appWidgetProvider)) {
802 favorite.appWidgetProvider = appWidgetProvider;
803 }
804 }
805
Sunny Goyalef728d42014-10-22 11:28:28 -0700806 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400807 }
808
809 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700810 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700811 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700812 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500813 ContentValues values = new ContentValues();
814 values.put(Favorites._ID, favorite.id);
815 values.put(Favorites.SCREEN, favorite.screen);
816 values.put(Favorites.CONTAINER, favorite.container);
817 values.put(Favorites.CELLX, favorite.cellX);
818 values.put(Favorites.CELLY, favorite.cellY);
819 values.put(Favorites.SPANX, favorite.spanX);
820 values.put(Favorites.SPANY, favorite.spanY);
821 values.put(Favorites.ICON_TYPE, favorite.iconType);
822 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
823 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
824 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
825 }
826 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
827 values.put(Favorites.ICON, favorite.icon);
828 }
829 if (!TextUtils.isEmpty(favorite.title)) {
830 values.put(Favorites.TITLE, favorite.title);
831 } else {
832 values.put(Favorites.TITLE, "");
833 }
834 if (!TextUtils.isEmpty(favorite.intent)) {
835 values.put(Favorites.INTENT, favorite.intent);
836 }
837 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500838
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100839 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
840 long userSerialNumber =
841 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
842 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
843
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700844 DeviceProfieData currentProfile = getDeviceProfieData();
845
Sunny Goyalff572272014-07-23 13:58:07 -0700846 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
847 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
848 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
849 }
850 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
851 values.put(LauncherSettings.Favorites.RESTORED,
852 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
853 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
854 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700855
856 // Verify placement
857 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
858 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
859 restoreSuccessful = false;
860 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
861 }
Sunny Goyalff572272014-07-23 13:58:07 -0700862 } else {
863 // Let LauncherModel know we've been here.
864 values.put(LauncherSettings.Favorites.RESTORED, 1);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700865
866 // Verify placement
867 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
868 if ((favorite.screen >= currentProfile.hotseatCount)
869 || (favorite.screen == currentProfile.allappsRank)) {
870 restoreSuccessful = false;
871 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
872 }
873 } else {
874 if ((favorite.cellX >= currentProfile.desktopCols)
875 || (favorite.cellY >= currentProfile.desktopRows)) {
876 restoreSuccessful = false;
877 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
878 }
879 }
Sunny Goyalff572272014-07-23 13:58:07 -0700880 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500881
Chris Wren5dee7af2013-12-20 17:22:11 -0500882 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400883 }
884
885 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700886 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400887 Screen screen = new Screen();
888 screen.id = c.getLong(ID_INDEX);
889 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700890 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400891 }
892
893 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700894 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400895 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700896 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500897 ContentValues values = new ContentValues();
898 values.put(WorkspaceScreens._ID, screen.id);
899 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
900 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400901 }
902
Chris Wren22e130d2013-09-23 18:25:57 -0400903 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700904 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400905 Resource res = new Resource();
906 res.dpi = dpi;
907 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400908 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400909 res.data = os.toByteArray();
910 }
Chris Wren22e130d2013-09-23 18:25:57 -0400911 return res;
912 }
913
Chris Wrenfd13c712013-09-27 15:45:19 -0400914 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700915 private Widget packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
Chris Wrenfd13c712013-09-27 15:45:19 -0400916 ComponentName provider) {
Adam Cohen59400422014-03-05 18:07:04 -0800917 final LauncherAppWidgetProviderInfo info =
918 LauncherModel.getProviderInfo(mContext, provider);
Chris Wrenfd13c712013-09-27 15:45:19 -0400919 Widget widget = new Widget();
920 widget.provider = provider.flattenToShortString();
921 widget.label = info.label;
922 widget.configure = info.configure != null;
923 if (info.icon != 0) {
924 widget.icon = new Resource();
925 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400926 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400927 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400928 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400929 widget.icon.data = os.toByteArray();
930 widget.icon.dpi = dpi;
931 }
932 }
933 if (info.previewImage != 0) {
934 widget.preview = new Resource();
935 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
936 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400937 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400938 widget.preview.data = os.toByteArray();
939 widget.preview.dpi = dpi;
940 }
941 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700942 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -0400943 }
944
Sunny Goyalef728d42014-10-22 11:28:28 -0700945 /**
946 * Deserialize a proto after verifying checksum wrapper.
947 */
948 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -0400949 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700950 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
951 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
952 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -0400953 }
954
Chris Wren1ada10d2013-09-13 18:01:38 -0400955 /**
956 * Read the old journal from the input file.
957 *
958 * In the event of any error, just pretend we didn't have a journal,
959 * in that case, do a full backup.
960 *
961 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -0500962 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -0400963 */
964 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400965 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400966 if (oldState == null) {
967 return journal;
968 }
969 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
970 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500971 int availableBytes = inStream.available();
972 if (DEBUG) Log.d(TAG, "available " + availableBytes);
973 if (availableBytes < MAX_JOURNAL_SIZE) {
974 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -0400975 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -0500976 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -0500977 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500978 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -0400979 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500980 // OMG what are you doing? This is crazy inefficient!
981 // If we read a byte that is not ours, we will cause trouble: b/12491813
982 // However, we don't know how many bytes to expect (oops).
983 // So we have to step through *slowly*, watching for the end.
984 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -0400985 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -0500986 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -0400987 bytesRead += result;
988 } else {
Chris Wren65b6a602014-01-10 14:11:25 -0500989 Log.w(TAG, "unexpected end of file while reading journal.");
990 // stop reading and see what there is to parse
991 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400992 }
993 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -0400994 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500995 availableBytes = 0;
996 }
997
998 // check the buffer to see if we have a valid journal
999 try {
Sunny Goyalef728d42014-10-22 11:28:28 -07001000 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -05001001 // if we are here, then we have read a valid, checksum-verified journal
1002 valid = true;
1003 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -05001004 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -05001005 } catch (InvalidProtocolBufferNanoException e) {
1006 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -05001007 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001008 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001009 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001010 }
Chris Wren92aa4232013-10-04 11:29:36 -04001011 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001012 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001013 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001014 }
1015 }
Chris Wren92aa4232013-10-04 11:29:36 -04001016 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001017 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001018 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001019 try {
1020 inStream.close();
1021 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001022 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001023 }
1024 }
1025 return journal;
1026 }
1027
Sunny Goyalef728d42014-10-22 11:28:28 -07001028 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1029 throws IOException {
1030 writeRowToBackup(keyToBackupKey(key), proto, data);
1031 }
1032
1033 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001034 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001035 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001036 data.writeEntityHeader(backupKey, blob.length);
1037 data.writeEntityData(blob, blob.length);
Sunny Goyalc0ee6752015-01-16 14:10:32 -08001038 mBackupDataWasUpdated = true;
Sunny Goyalef728d42014-10-22 11:28:28 -07001039 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001040 }
1041
Chris Wren1ada10d2013-09-13 18:01:38 -04001042 /**
1043 * Write the new journal to the output file.
1044 *
1045 * In the event of any error, just pretend we didn't have a journal,
1046 * in that case, do a full backup.
1047
1048 * @param newState the write-only file descriptor pointing to the new journal
1049 * @param journal a Journal protocol buffer
1050 */
1051 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1052 FileOutputStream outStream = null;
1053 try {
1054 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001055 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001056 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001057 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001058 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001059 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001060 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001061 }
1062 }
1063
1064 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1065 private byte[] writeCheckedBytes(MessageNano proto) {
1066 CheckedMessage wrapper = new CheckedMessage();
1067 wrapper.payload = MessageNano.toByteArray(proto);
1068 CRC32 checksum = new CRC32();
1069 checksum.update(wrapper.payload);
1070 wrapper.checksum = checksum.getValue();
1071 return MessageNano.toByteArray(wrapper);
1072 }
1073
1074 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001075 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001076 throws InvalidProtocolBufferNanoException {
1077 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001078 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001079 CRC32 checksum = new CRC32();
1080 checksum.update(wrapper.payload);
1081 if (wrapper.checksum != checksum.getValue()) {
1082 throw new InvalidProtocolBufferNanoException("checksum does not match");
1083 }
1084 return wrapper.payload;
1085 }
1086
Chris Wren6d0dde02014-02-10 12:16:54 -05001087 private boolean initializeIconCache() {
1088 if (mIconCache != null) {
1089 return true;
1090 }
1091
1092 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
1093 if (appState == null) {
1094 Throwable stackTrace = new Throwable();
1095 stackTrace.fillInStackTrace();
1096 Log.w(TAG, "Failed to get app state during backup/restore", stackTrace);
1097 return false;
1098 }
1099 mIconCache = appState.getIconCache();
1100 return mIconCache != null;
1101 }
1102
Chris Wren71144262014-02-27 15:49:39 -05001103
Sunny Goyalef728d42014-10-22 11:28:28 -07001104 /**
1105 * @return true if the launcher is in a state to support backup
1106 */
Chris Wren71144262014-02-27 15:49:39 -05001107 private boolean launcherIsReady() {
1108 ContentResolver cr = mContext.getContentResolver();
1109 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1110 if (cursor == null) {
1111 // launcher data has been wiped, do nothing
1112 return false;
1113 }
1114 cursor.close();
1115
1116 if (!initializeIconCache()) {
1117 // launcher services are unavailable, try again later
1118 dataChanged();
1119 return false;
1120 }
1121
1122 return true;
1123 }
1124
Sunny Goyalffe83f12014-08-14 17:39:34 -07001125 private String getUserSelectionArg() {
1126 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1127 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1128 }
1129
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001130 private class InvalidBackupException extends IOException {
1131 private InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001132 super(cause);
1133 }
1134
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001135 public InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001136 super(reason);
1137 }
1138 }
1139}