blob: 7f3a7985e1660d7a2f1143b5f8ded92eaf91f88e [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.AppWidgetManager;
23import android.appwidget.AppWidgetProviderInfo;
24import android.content.ComponentName;
Chris Wren1ada10d2013-09-13 18:01:38 -040025import android.content.ContentResolver;
Chris Wren5dee7af2013-12-20 17:22:11 -050026import android.content.ContentValues;
Chris Wren1ada10d2013-09-13 18:01:38 -040027import android.content.Context;
Chris Wren22e130d2013-09-23 18:25:57 -040028import android.content.Intent;
Sunny Goyalef728d42014-10-22 11:28:28 -070029import android.content.pm.PackageManager.NameNotFoundException;
Chris Wren1ada10d2013-09-13 18:01:38 -040030import android.database.Cursor;
Chris Wren22e130d2013-09-23 18:25:57 -040031import android.graphics.Bitmap;
32import android.graphics.BitmapFactory;
Chris Wrenfd13c712013-09-27 15:45:19 -040033import android.graphics.drawable.Drawable;
Chris Wren1ada10d2013-09-13 18:01:38 -040034import android.os.ParcelFileDescriptor;
Chris Wren1ada10d2013-09-13 18:01:38 -040035import android.text.TextUtils;
36import android.util.Base64;
37import android.util.Log;
38
Sunny Goyalef728d42014-10-22 11:28:28 -070039import com.android.launcher3.LauncherSettings.Favorites;
40import com.android.launcher3.LauncherSettings.WorkspaceScreens;
41import com.android.launcher3.backup.BackupProtos;
42import com.android.launcher3.backup.BackupProtos.CheckedMessage;
Sunny Goyal33d44382014-10-16 09:24:19 -070043import com.android.launcher3.backup.BackupProtos.DeviceProfieData;
Sunny Goyalef728d42014-10-22 11:28:28 -070044import com.android.launcher3.backup.BackupProtos.Favorite;
45import com.android.launcher3.backup.BackupProtos.Journal;
46import com.android.launcher3.backup.BackupProtos.Key;
47import com.android.launcher3.backup.BackupProtos.Resource;
48import com.android.launcher3.backup.BackupProtos.Screen;
49import com.android.launcher3.backup.BackupProtos.Widget;
50import com.android.launcher3.compat.UserHandleCompat;
51import com.android.launcher3.compat.UserManagerCompat;
52import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
53import com.google.protobuf.nano.MessageNano;
54
Chris Wren22e130d2013-09-23 18:25:57 -040055import java.io.ByteArrayOutputStream;
Chris Wren1ada10d2013-09-13 18:01:38 -040056import java.io.FileInputStream;
57import java.io.FileOutputStream;
58import java.io.IOException;
Chris Wren22e130d2013-09-23 18:25:57 -040059import java.net.URISyntaxException;
Chris Wren1ada10d2013-09-13 18:01:38 -040060import java.util.ArrayList;
Chris Wren22e130d2013-09-23 18:25:57 -040061import java.util.HashMap;
Chris Wren1ada10d2013-09-13 18:01:38 -040062import java.util.HashSet;
Chris Wren22e130d2013-09-23 18:25:57 -040063import java.util.List;
Chris Wren1ada10d2013-09-13 18:01:38 -040064import java.util.zip.CRC32;
65
66/**
67 * Persist the launcher home state across calamities.
68 */
Chris Wren92aa4232013-10-04 11:29:36 -040069public class LauncherBackupHelper implements BackupHelper {
Chris Wren92aa4232013-10-04 11:29:36 -040070 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050071 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
72 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren1ada10d2013-09-13 18:01:38 -040073
Sunny Goyal33d44382014-10-16 09:24:19 -070074 private static final int BACKUP_VERSION = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -040075 private static final int MAX_JOURNAL_SIZE = 1000000;
76
Sunny Goyal33d44382014-10-16 09:24:19 -070077 // Journal key is such that it is always smaller than any dynamically generated
78 // key (any Base64 encoded string).
79 private static final String JOURNAL_KEY = "#";
80
Chris Wrenfd13c712013-09-27 15:45:19 -040081 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040082 private static final int MAX_ICONS_PER_PASS = 10;
83
Chris Wrenfd13c712013-09-27 15:45:19 -040084 /** widgets contain previews, which are very large, dribble them out */
85 private static final int MAX_WIDGETS_PER_PASS = 5;
86
Sunny Goyal33d44382014-10-16 09:24:19 -070087 private static final int IMAGE_COMPRESSION_QUALITY = 75;
Chris Wren45297f82013-10-17 15:16:48 -040088
Chris Wrenb86f0762013-10-04 10:10:21 -040089 private static final Bitmap.CompressFormat IMAGE_FORMAT =
90 android.graphics.Bitmap.CompressFormat.PNG;
91
Chris Wren1ada10d2013-09-13 18:01:38 -040092 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070093 Favorites._ID, // 0
94 Favorites.MODIFIED, // 1
95 Favorites.INTENT, // 2
96 Favorites.APPWIDGET_PROVIDER, // 3
97 Favorites.APPWIDGET_ID, // 4
98 Favorites.CELLX, // 5
99 Favorites.CELLY, // 6
100 Favorites.CONTAINER, // 7
101 Favorites.ICON, // 8
102 Favorites.ICON_PACKAGE, // 9
103 Favorites.ICON_RESOURCE, // 10
104 Favorites.ICON_TYPE, // 11
105 Favorites.ITEM_TYPE, // 12
106 Favorites.SCREEN, // 13
107 Favorites.SPANX, // 14
108 Favorites.SPANY, // 15
109 Favorites.TITLE, // 16
110 Favorites.PROFILE_ID, // 17
Chris Wren1ada10d2013-09-13 18:01:38 -0400111 };
112
113 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400114 private static final int ID_MODIFIED = 1;
115 private static final int INTENT_INDEX = 2;
116 private static final int APPWIDGET_PROVIDER_INDEX = 3;
117 private static final int APPWIDGET_ID_INDEX = 4;
118 private static final int CELLX_INDEX = 5;
119 private static final int CELLY_INDEX = 6;
120 private static final int CONTAINER_INDEX = 7;
121 private static final int ICON_INDEX = 8;
122 private static final int ICON_PACKAGE_INDEX = 9;
123 private static final int ICON_RESOURCE_INDEX = 10;
124 private static final int ICON_TYPE_INDEX = 11;
125 private static final int ITEM_TYPE_INDEX = 12;
126 private static final int SCREEN_INDEX = 13;
127 private static final int SPANX_INDEX = 14;
128 private static final int SPANY_INDEX = 15;
129 private static final int TITLE_INDEX = 16;
Chris Wren1ada10d2013-09-13 18:01:38 -0400130
131 private static final String[] SCREEN_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -0700132 WorkspaceScreens._ID, // 0
133 WorkspaceScreens.MODIFIED, // 1
134 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400135 };
136
Chris Wren22e130d2013-09-23 18:25:57 -0400137 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400138
Chris Wren92aa4232013-10-04 11:29:36 -0400139 private final Context mContext;
Sunny Goyalef728d42014-10-22 11:28:28 -0700140 private final HashSet<String> mExistingKeys;
Sunny Goyal42de82f2014-09-26 22:09:29 -0700141 private final ArrayList<Key> mKeys;
Chris Wren1ada10d2013-09-13 18:01:38 -0400142
Sunny Goyalef728d42014-10-22 11:28:28 -0700143 private IconCache mIconCache;
144 private BackupManager mBackupManager;
145 private HashMap<ComponentName, AppWidgetProviderInfo> mWidgetMap;
146 private byte[] mBuffer = new byte[512];
147 private long mLastBackupRestoreTime;
148
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700149 private DeviceProfieData mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700150 boolean restoreSuccessful;
151
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();
Chris Wren1ada10d2013-09-13 18:01:38 -0400205
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);
223 }
224
225 mExistingKeys.clear();
226 mLastBackupRestoreTime = newBackupTime;
Sunny Goyal33d44382014-10-16 09:24:19 -0700227
228 // We store the journal at two places.
229 // 1) Storing it in newState allows us to do partial backups by comparing old state
230 // 2) Storing it in backup data allows us to validate keys during restore
231 Journal state = getCurrentStateJournal();
232 writeRowToBackup(JOURNAL_KEY, state, data);
Sunny Goyalef728d42014-10-22 11:28:28 -0700233 } catch (IOException e) {
234 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400235 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400236
Sunny Goyalef728d42014-10-22 11:28:28 -0700237 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400238 }
239
240 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700241 * @return true if the backup corresponding to oldstate can be successfully applied
242 * to this device.
243 */
244 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700245 DeviceProfieData currentProfile = getDeviceProfieData();
246
247 DeviceProfieData oldProfile = oldState.profile;
248
249 if (oldProfile == null || oldProfile.desktopCols == 0) {
250 // Profile info is not valid, ignore the check.
251 return true;
252 }
253
254 boolean isHotsetCompatible = false;
255 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
256 isHotsetCompatible = true;
257 }
258 if ((currentProfile.hotseatCount >= oldProfile.hotseatCount) &&
259 (currentProfile.allappsRank == oldProfile.allappsRank)) {
260 isHotsetCompatible = true;
261 }
262
263 return isHotsetCompatible && (currentProfile.desktopCols >= oldProfile.desktopCols)
264 && (currentProfile.desktopRows >= oldProfile.desktopRows);
Sunny Goyal33d44382014-10-16 09:24:19 -0700265 }
266
267 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400268 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700269 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
270 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400271 *
Chris Wren92aa4232013-10-04 11:29:36 -0400272 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400273 */
274 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400275 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700276 if (!restoreSuccessful) {
277 return;
278 }
279
Sunny Goyalef728d42014-10-22 11:28:28 -0700280 int dataSize = data.size();
281 if (mBuffer.length < dataSize) {
282 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400283 }
284 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700285 int bytesRead = data.read(mBuffer, 0, dataSize);
286 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
287 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700288
289 if (JOURNAL_KEY.equals(backupKey)) {
290 if (VERBOSE) Log.v(TAG, "Journal entry restored");
291 if (!mKeys.isEmpty()) {
292 // We received the journal key after a restore key.
293 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
294 restoreSuccessful = false;
295 return;
296 }
297
298 Journal journal = new Journal();
299 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
300 applyJournal(journal);
301 restoreSuccessful = isBackupCompatible(journal);
302 return;
303 }
304
305 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
306 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
307 return;
308 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700309 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500310 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400311 switch (key.type) {
312 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700313 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400314 break;
315
316 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700317 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400318 break;
319
320 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700321 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400322 break;
323
324 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700325 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400326 break;
327
328 default:
329 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700330 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400331 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400332 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700333 } catch (IOException e) {
334 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400335 }
Chris Wren92aa4232013-10-04 11:29:36 -0400336 }
337
338 /**
339 * Record the restore state for the next backup.
340 *
341 * @param newState notes about the backup state after restore.
342 */
343 @Override
344 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700345 writeJournal(newState, getCurrentStateJournal());
346 }
347
348 private Journal getCurrentStateJournal() {
349 Journal journal = new Journal();
350 journal.t = mLastBackupRestoreTime;
351 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
352 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700353 journal.backupVersion = BACKUP_VERSION;
354 journal.profile = getDeviceProfieData();
Sunny Goyalef728d42014-10-22 11:28:28 -0700355 return journal;
356 }
357
358 private int getAppVersion() {
359 try {
360 return mContext.getPackageManager()
361 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
362 } catch (NameNotFoundException e) {
363 return 0;
364 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400365 }
366
367 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700368 * @return the current device profile information.
369 */
370 private DeviceProfieData getDeviceProfieData() {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700371 if (mCurrentProfile != null) {
372 return mCurrentProfile;
373 }
Sunny Goyal33d44382014-10-16 09:24:19 -0700374 LauncherAppState.setApplicationContext(mContext.getApplicationContext());
375 LauncherAppState app = LauncherAppState.getInstance();
376
377 DeviceProfile profile;
378 if (app.getDynamicGrid() == null) {
379 // Initialize the grid
380 profile = app.initDynamicGrid(mContext);
381 } else {
382 profile = app.getDynamicGrid().getDeviceProfile();
383 }
384
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700385 mCurrentProfile = new DeviceProfieData();
386 mCurrentProfile.desktopRows = profile.numRows;
387 mCurrentProfile.desktopCols = profile.numColumns;
388 mCurrentProfile.hotseatCount = profile.numHotseatIcons;
389 mCurrentProfile.allappsRank = profile.hotseatAllAppsRank;
390 return mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700391 }
392
393 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400394 * Write all modified favorites to the data stream.
395 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400396 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400397 * @throws IOException
398 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700399 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400400 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400401 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700402 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400403 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700404 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400405 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400406 cursor.moveToPosition(-1);
407 while(cursor.moveToNext()) {
408 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700409 final long updateTime = cursor.getLong(ID_MODIFIED);
410 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700411 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700412 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700413 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
414 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500415 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700416 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400417 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400418 }
419 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400420 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400421 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400422 }
423
424 /**
425 * Read a favorite from the stream.
426 *
427 * <P>Keys arrive in any order, so screens and containers may not exist yet.
428 *
429 * @param key identifier for the row
430 * @param buffer the serialized proto from the stream, may be larger than dataSize
431 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400432 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700433 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500434 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400435 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
436 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
437
Sunny Goyalef728d42014-10-22 11:28:28 -0700438 ContentResolver cr = mContext.getContentResolver();
439 ContentValues values = unpackFavorite(buffer, dataSize);
440 cr.insert(Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400441 }
442
443 /**
444 * Write all modified screens to the data stream.
445 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400446 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400447 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400448 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700449 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400450 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400451 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400452 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
453 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400454 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400455 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700456 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400457 while(cursor.moveToNext()) {
458 final long id = cursor.getLong(ID_INDEX);
459 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400460 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700461 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500462 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700463 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
464 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500465 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700466 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400467 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400468 }
469 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400470 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400471 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400472 }
473
474 /**
475 * Read a screen from the stream.
476 *
477 * <P>Keys arrive in any order, so children of this screen may already exist.
478 *
479 * @param key identifier for the row
480 * @param buffer the serialized proto from the stream, may be larger than dataSize
481 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400482 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700483 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500484 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400485 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
486 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500487
Sunny Goyalef728d42014-10-22 11:28:28 -0700488 ContentResolver cr = mContext.getContentResolver();
489 ContentValues values = unpackScreen(buffer, dataSize);
490 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400491 }
492
Chris Wren22e130d2013-09-23 18:25:57 -0400493 /**
494 * Write all the static icon resources we need to render placeholders
495 * for a package that is not installed.
496 *
Chris Wren22e130d2013-09-23 18:25:57 -0400497 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400498 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700499 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400500 // persist icons that haven't been persisted yet
Chris Wren6d0dde02014-02-10 12:16:54 -0500501 if (!initializeIconCache()) {
Chris Wren92aa4232013-10-04 11:29:36 -0400502 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400503 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
504 return;
505 }
Chris Wren92aa4232013-10-04 11:29:36 -0400506 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400507 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700508 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700509 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400510
Kenny Guyed131872014-04-30 03:02:21 +0100511 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100512 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100513 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700514 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400515 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
516 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400517 try {
518 cursor.moveToPosition(-1);
519 while(cursor.moveToNext()) {
520 final long id = cursor.getLong(ID_INDEX);
521 final String intentDescription = cursor.getString(INTENT_INDEX);
522 try {
523 Intent intent = Intent.parseUri(intentDescription, 0);
524 ComponentName cn = intent.getComponent();
525 Key key = null;
526 String backupKey = null;
527 if (cn != null) {
528 key = getKey(Key.ICON, cn.flattenToShortString());
529 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400530 } else {
531 Log.w(TAG, "empty intent on application favorite: " + id);
532 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700533 if (mExistingKeys.contains(backupKey)) {
534 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400535
536 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700537 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400538 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700539 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
540 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
541 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100542 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100543 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700544 writeRowToBackup(key, packIcon(dpi, icon), data);
545 mKeys.add(key);
546 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400547 }
548 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700549 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400550 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400551 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400552 }
553 }
554 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500555 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400556 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500557 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400558 }
559
560 }
561 } finally {
562 cursor.close();
563 }
Chris Wren22e130d2013-09-23 18:25:57 -0400564 }
565
566 /**
567 * Read an icon from the stream.
568 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400569 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400570 *
571 * @param key identifier for the row
572 * @param buffer the serialized proto from the stream, may be larger than dataSize
573 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400574 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700575 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500576 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400577 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
578 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500579
Sunny Goyalef728d42014-10-22 11:28:28 -0700580 Resource res = unpackProto(new Resource(), buffer, dataSize);
581 if (DEBUG) {
582 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400583 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700584 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
585 if (icon == null) {
586 Log.w(TAG, "failed to unpack icon for " + key.name);
587 }
588 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
589 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(key.name), icon, res.dpi);
Chris Wren22e130d2013-09-23 18:25:57 -0400590 }
591
Chris Wrenfd13c712013-09-27 15:45:19 -0400592 /**
593 * Write all the static widget resources we need to render placeholders
594 * for a package that is not installed.
595 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400596 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400597 * @throws IOException
598 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700599 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400600 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400601 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
Chris Wren6d0dde02014-02-10 12:16:54 -0500602 if (appState == null || !initializeIconCache()) {
603 Log.w(TAG, "Failed to get icon cache during restore");
Chris Wrend8fe6de2013-10-04 10:42:14 -0400604 return;
605 }
Chris Wren92aa4232013-10-04 11:29:36 -0400606 final ContentResolver cr = mContext.getContentResolver();
607 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
608 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wren92aa4232013-10-04 11:29:36 -0400609 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400610 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
611 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
Sunny Goyalef728d42014-10-22 11:28:28 -0700612 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400613
Sunny Goyalffe83f12014-08-14 17:39:34 -0700614 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
615 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400616 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
617 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400618 try {
619 cursor.moveToPosition(-1);
620 while(cursor.moveToNext()) {
621 final long id = cursor.getLong(ID_INDEX);
622 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
623 final int spanX = cursor.getInt(SPANX_INDEX);
624 final int spanY = cursor.getInt(SPANY_INDEX);
625 final ComponentName provider = ComponentName.unflattenFromString(providerName);
626 Key key = null;
627 String backupKey = null;
628 if (provider != null) {
629 key = getKey(Key.WIDGET, providerName);
630 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400631 } else {
632 Log.w(TAG, "empty intent on appwidget: " + id);
633 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700634 if (mExistingKeys.contains(backupKey)) {
635 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400636
637 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700638 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400639 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700640 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
641 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
642 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400643 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
644 spanY * profile.cellHeightPx, widgetSpacingLayout);
Sunny Goyalef728d42014-10-22 11:28:28 -0700645 writeRowToBackup(key, packWidget(dpi, previewLoader, mIconCache, provider), data);
646 mKeys.add(key);
647 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400648 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700649 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400650 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400651 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400652 }
653 }
654 }
655 } finally {
656 cursor.close();
657 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400658 }
659
660 /**
661 * Read a widget from the stream.
662 *
663 * <P>Keys arrive in any order, so widgets that use this data may already exist.
664 *
665 * @param key identifier for the row
666 * @param buffer the serialized proto from the stream, may be larger than dataSize
667 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400668 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700669 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500670 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400671 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
672 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700673 Widget widget = unpackProto(new Widget(), buffer, dataSize);
674 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
675 if (widget.icon.data != null) {
676 Bitmap icon = BitmapFactory
677 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
678 if (icon == null) {
679 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500680 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700681 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(widget.provider),
682 icon, widget.icon.dpi);
Chris Wren5dee7af2013-12-20 17:22:11 -0500683 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400684 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700685
686 // future site of widget table mutation
Chris Wrenfd13c712013-09-27 15:45:19 -0400687 }
688
Chris Wren22e130d2013-09-23 18:25:57 -0400689 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400690 *
691 * <P> Keys contain their own checksum instead of using
692 * the heavy-weight CheckedMessage wrapper.
693 */
694 private Key getKey(int type, long id) {
695 Key key = new Key();
696 key.type = type;
697 key.id = id;
698 key.checksum = checkKey(key);
699 return key;
700 }
701
Chris Wren22e130d2013-09-23 18:25:57 -0400702 /** create a new key for a named object.
703 *
704 * <P> Keys contain their own checksum instead of using
705 * the heavy-weight CheckedMessage wrapper.
706 */
707 private Key getKey(int type, String name) {
708 Key key = new Key();
709 key.type = type;
710 key.name = name;
711 key.checksum = checkKey(key);
712 return key;
713 }
714
Chris Wren1ada10d2013-09-13 18:01:38 -0400715 /** keys need to be strings, serialize and encode. */
716 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400717 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400718 }
719
720 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700721 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400722 try {
723 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
724 if (key.checksum != checkKey(key)) {
725 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700726 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400727 }
728 return key;
729 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700730 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400731 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700732 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400733 }
734 }
735
736 /** Compute the checksum over the important bits of a key. */
737 private long checkKey(Key key) {
738 CRC32 checksum = new CRC32();
739 checksum.update(key.type);
740 checksum.update((int) (key.id & 0xffff));
741 checksum.update((int) ((key.id >> 32) & 0xffff));
742 if (!TextUtils.isEmpty(key.name)) {
743 checksum.update(key.name.getBytes());
744 }
745 return checksum.getValue();
746 }
747
748 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700749 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400750 Favorite favorite = new Favorite();
751 favorite.id = c.getLong(ID_INDEX);
752 favorite.screen = c.getInt(SCREEN_INDEX);
753 favorite.container = c.getInt(CONTAINER_INDEX);
754 favorite.cellX = c.getInt(CELLX_INDEX);
755 favorite.cellY = c.getInt(CELLY_INDEX);
756 favorite.spanX = c.getInt(SPANX_INDEX);
757 favorite.spanY = c.getInt(SPANY_INDEX);
758 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
759 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
760 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
761 if (!TextUtils.isEmpty(iconPackage)) {
762 favorite.iconPackage = iconPackage;
763 }
764 String iconResource = c.getString(ICON_RESOURCE_INDEX);
765 if (!TextUtils.isEmpty(iconResource)) {
766 favorite.iconResource = iconResource;
767 }
768 }
769 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
770 byte[] blob = c.getBlob(ICON_INDEX);
771 if (blob != null && blob.length > 0) {
772 favorite.icon = blob;
773 }
774 }
775 String title = c.getString(TITLE_INDEX);
776 if (!TextUtils.isEmpty(title)) {
777 favorite.title = title;
778 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100779 String intentDescription = c.getString(INTENT_INDEX);
780 if (!TextUtils.isEmpty(intentDescription)) {
781 try {
782 Intent intent = Intent.parseUri(intentDescription, 0);
783 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
784 favorite.intent = intent.toUri(0);
785 } catch (URISyntaxException e) {
786 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700787 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400788 }
789 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
790 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
791 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
792 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
793 if (!TextUtils.isEmpty(appWidgetProvider)) {
794 favorite.appWidgetProvider = appWidgetProvider;
795 }
796 }
797
Sunny Goyalef728d42014-10-22 11:28:28 -0700798 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400799 }
800
801 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700802 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700803 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700804 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500805 ContentValues values = new ContentValues();
806 values.put(Favorites._ID, favorite.id);
807 values.put(Favorites.SCREEN, favorite.screen);
808 values.put(Favorites.CONTAINER, favorite.container);
809 values.put(Favorites.CELLX, favorite.cellX);
810 values.put(Favorites.CELLY, favorite.cellY);
811 values.put(Favorites.SPANX, favorite.spanX);
812 values.put(Favorites.SPANY, favorite.spanY);
813 values.put(Favorites.ICON_TYPE, favorite.iconType);
814 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
815 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
816 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
817 }
818 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
819 values.put(Favorites.ICON, favorite.icon);
820 }
821 if (!TextUtils.isEmpty(favorite.title)) {
822 values.put(Favorites.TITLE, favorite.title);
823 } else {
824 values.put(Favorites.TITLE, "");
825 }
826 if (!TextUtils.isEmpty(favorite.intent)) {
827 values.put(Favorites.INTENT, favorite.intent);
828 }
829 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500830
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100831 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
832 long userSerialNumber =
833 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
834 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
835
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700836 DeviceProfieData currentProfile = getDeviceProfieData();
837
Sunny Goyalff572272014-07-23 13:58:07 -0700838 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
839 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
840 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
841 }
842 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
843 values.put(LauncherSettings.Favorites.RESTORED,
844 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
845 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
846 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700847
848 // Verify placement
849 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
850 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
851 restoreSuccessful = false;
852 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
853 }
Sunny Goyalff572272014-07-23 13:58:07 -0700854 } else {
855 // Let LauncherModel know we've been here.
856 values.put(LauncherSettings.Favorites.RESTORED, 1);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700857
858 // Verify placement
859 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
860 if ((favorite.screen >= currentProfile.hotseatCount)
861 || (favorite.screen == currentProfile.allappsRank)) {
862 restoreSuccessful = false;
863 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
864 }
865 } else {
866 if ((favorite.cellX >= currentProfile.desktopCols)
867 || (favorite.cellY >= currentProfile.desktopRows)) {
868 restoreSuccessful = false;
869 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
870 }
871 }
Sunny Goyalff572272014-07-23 13:58:07 -0700872 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500873
Chris Wren5dee7af2013-12-20 17:22:11 -0500874 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400875 }
876
877 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700878 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400879 Screen screen = new Screen();
880 screen.id = c.getLong(ID_INDEX);
881 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700882 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400883 }
884
885 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700886 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400887 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700888 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500889 ContentValues values = new ContentValues();
890 values.put(WorkspaceScreens._ID, screen.id);
891 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
892 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400893 }
894
Chris Wren22e130d2013-09-23 18:25:57 -0400895 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700896 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400897 Resource res = new Resource();
898 res.dpi = dpi;
899 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400900 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400901 res.data = os.toByteArray();
902 }
Chris Wren22e130d2013-09-23 18:25:57 -0400903 return res;
904 }
905
Chris Wrenfd13c712013-09-27 15:45:19 -0400906 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700907 private Widget packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
Chris Wrenfd13c712013-09-27 15:45:19 -0400908 ComponentName provider) {
Adam Cohen59400422014-03-05 18:07:04 -0800909 final LauncherAppWidgetProviderInfo info =
910 LauncherModel.getProviderInfo(mContext, provider);
Chris Wrenfd13c712013-09-27 15:45:19 -0400911 Widget widget = new Widget();
912 widget.provider = provider.flattenToShortString();
913 widget.label = info.label;
914 widget.configure = info.configure != null;
915 if (info.icon != 0) {
916 widget.icon = new Resource();
917 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400918 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400919 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400920 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400921 widget.icon.data = os.toByteArray();
922 widget.icon.dpi = dpi;
923 }
924 }
925 if (info.previewImage != 0) {
926 widget.preview = new Resource();
927 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
928 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400929 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400930 widget.preview.data = os.toByteArray();
931 widget.preview.dpi = dpi;
932 }
933 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700934 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -0400935 }
936
Sunny Goyalef728d42014-10-22 11:28:28 -0700937 /**
938 * Deserialize a proto after verifying checksum wrapper.
939 */
940 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -0400941 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700942 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
943 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
944 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -0400945 }
946
Chris Wren1ada10d2013-09-13 18:01:38 -0400947 /**
948 * Read the old journal from the input file.
949 *
950 * In the event of any error, just pretend we didn't have a journal,
951 * in that case, do a full backup.
952 *
953 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -0500954 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -0400955 */
956 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400957 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400958 if (oldState == null) {
959 return journal;
960 }
961 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
962 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500963 int availableBytes = inStream.available();
964 if (DEBUG) Log.d(TAG, "available " + availableBytes);
965 if (availableBytes < MAX_JOURNAL_SIZE) {
966 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -0400967 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -0500968 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -0500969 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500970 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -0400971 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500972 // OMG what are you doing? This is crazy inefficient!
973 // If we read a byte that is not ours, we will cause trouble: b/12491813
974 // However, we don't know how many bytes to expect (oops).
975 // So we have to step through *slowly*, watching for the end.
976 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -0400977 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -0500978 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -0400979 bytesRead += result;
980 } else {
Chris Wren65b6a602014-01-10 14:11:25 -0500981 Log.w(TAG, "unexpected end of file while reading journal.");
982 // stop reading and see what there is to parse
983 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400984 }
985 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -0400986 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500987 availableBytes = 0;
988 }
989
990 // check the buffer to see if we have a valid journal
991 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700992 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -0500993 // if we are here, then we have read a valid, checksum-verified journal
994 valid = true;
995 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -0500996 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -0500997 } catch (InvalidProtocolBufferNanoException e) {
998 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -0500999 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -05001000 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -04001001 }
Chris Wren1ada10d2013-09-13 18:01:38 -04001002 }
Chris Wren92aa4232013-10-04 11:29:36 -04001003 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -05001004 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -05001005 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -04001006 }
1007 }
Chris Wren92aa4232013-10-04 11:29:36 -04001008 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001009 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001010 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001011 try {
1012 inStream.close();
1013 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001014 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001015 }
1016 }
1017 return journal;
1018 }
1019
Sunny Goyalef728d42014-10-22 11:28:28 -07001020 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1021 throws IOException {
1022 writeRowToBackup(keyToBackupKey(key), proto, data);
1023 }
1024
1025 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001026 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001027 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001028 data.writeEntityHeader(backupKey, blob.length);
1029 data.writeEntityData(blob, blob.length);
Sunny Goyalef728d42014-10-22 11:28:28 -07001030 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001031 }
1032
Chris Wren1ada10d2013-09-13 18:01:38 -04001033 /**
1034 * Write the new journal to the output file.
1035 *
1036 * In the event of any error, just pretend we didn't have a journal,
1037 * in that case, do a full backup.
1038
1039 * @param newState the write-only file descriptor pointing to the new journal
1040 * @param journal a Journal protocol buffer
1041 */
1042 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1043 FileOutputStream outStream = null;
1044 try {
1045 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001046 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001047 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001048 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001049 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001050 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001051 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001052 }
1053 }
1054
1055 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1056 private byte[] writeCheckedBytes(MessageNano proto) {
1057 CheckedMessage wrapper = new CheckedMessage();
1058 wrapper.payload = MessageNano.toByteArray(proto);
1059 CRC32 checksum = new CRC32();
1060 checksum.update(wrapper.payload);
1061 wrapper.checksum = checksum.getValue();
1062 return MessageNano.toByteArray(wrapper);
1063 }
1064
1065 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001066 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001067 throws InvalidProtocolBufferNanoException {
1068 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001069 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001070 CRC32 checksum = new CRC32();
1071 checksum.update(wrapper.payload);
1072 if (wrapper.checksum != checksum.getValue()) {
1073 throw new InvalidProtocolBufferNanoException("checksum does not match");
1074 }
1075 return wrapper.payload;
1076 }
1077
Chris Wren6d0dde02014-02-10 12:16:54 -05001078 private boolean initializeIconCache() {
1079 if (mIconCache != null) {
1080 return true;
1081 }
1082
1083 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
1084 if (appState == null) {
1085 Throwable stackTrace = new Throwable();
1086 stackTrace.fillInStackTrace();
1087 Log.w(TAG, "Failed to get app state during backup/restore", stackTrace);
1088 return false;
1089 }
1090 mIconCache = appState.getIconCache();
1091 return mIconCache != null;
1092 }
1093
Chris Wren71144262014-02-27 15:49:39 -05001094
Sunny Goyalef728d42014-10-22 11:28:28 -07001095 /**
1096 * @return true if the launcher is in a state to support backup
1097 */
Chris Wren71144262014-02-27 15:49:39 -05001098 private boolean launcherIsReady() {
1099 ContentResolver cr = mContext.getContentResolver();
1100 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1101 if (cursor == null) {
1102 // launcher data has been wiped, do nothing
1103 return false;
1104 }
1105 cursor.close();
1106
1107 if (!initializeIconCache()) {
1108 // launcher services are unavailable, try again later
1109 dataChanged();
1110 return false;
1111 }
1112
1113 return true;
1114 }
1115
Sunny Goyalffe83f12014-08-14 17:39:34 -07001116 private String getUserSelectionArg() {
1117 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1118 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1119 }
1120
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001121 private class InvalidBackupException extends IOException {
1122 private InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001123 super(cause);
1124 }
1125
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001126 public InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001127 super(reason);
1128 }
1129 }
1130}