blob: 4faa8ace8ea45e4bf307342125b3a28497f30009 [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;
Chris Wren22e130d2013-09-23 18:25:57 -040060import java.util.HashMap;
Chris Wren1ada10d2013-09-13 18:01:38 -040061import java.util.HashSet;
Chris Wren1ada10d2013-09-13 18:01:38 -040062import java.util.zip.CRC32;
63
64/**
65 * Persist the launcher home state across calamities.
66 */
Chris Wren92aa4232013-10-04 11:29:36 -040067public class LauncherBackupHelper implements BackupHelper {
Chris Wren92aa4232013-10-04 11:29:36 -040068 private static final String TAG = "LauncherBackupHelper";
Chris Wren50c8f422014-01-15 16:10:39 -050069 private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
70 private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
Chris Wren1ada10d2013-09-13 18:01:38 -040071
Sunny Goyal33d44382014-10-16 09:24:19 -070072 private static final int BACKUP_VERSION = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -040073 private static final int MAX_JOURNAL_SIZE = 1000000;
74
Sunny Goyal33d44382014-10-16 09:24:19 -070075 // Journal key is such that it is always smaller than any dynamically generated
76 // key (any Base64 encoded string).
77 private static final String JOURNAL_KEY = "#";
78
Chris Wrenfd13c712013-09-27 15:45:19 -040079 /** icons are large, dribble them out */
Chris Wren22e130d2013-09-23 18:25:57 -040080 private static final int MAX_ICONS_PER_PASS = 10;
81
Chris Wrenfd13c712013-09-27 15:45:19 -040082 /** widgets contain previews, which are very large, dribble them out */
83 private static final int MAX_WIDGETS_PER_PASS = 5;
84
Sunny Goyal33d44382014-10-16 09:24:19 -070085 private static final int IMAGE_COMPRESSION_QUALITY = 75;
Chris Wren45297f82013-10-17 15:16:48 -040086
Chris Wrenb86f0762013-10-04 10:10:21 -040087 private static final Bitmap.CompressFormat IMAGE_FORMAT =
88 android.graphics.Bitmap.CompressFormat.PNG;
89
Chris Wren1ada10d2013-09-13 18:01:38 -040090 private static final String[] FAVORITE_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -070091 Favorites._ID, // 0
92 Favorites.MODIFIED, // 1
93 Favorites.INTENT, // 2
94 Favorites.APPWIDGET_PROVIDER, // 3
95 Favorites.APPWIDGET_ID, // 4
96 Favorites.CELLX, // 5
97 Favorites.CELLY, // 6
98 Favorites.CONTAINER, // 7
99 Favorites.ICON, // 8
100 Favorites.ICON_PACKAGE, // 9
101 Favorites.ICON_RESOURCE, // 10
102 Favorites.ICON_TYPE, // 11
103 Favorites.ITEM_TYPE, // 12
104 Favorites.SCREEN, // 13
105 Favorites.SPANX, // 14
106 Favorites.SPANY, // 15
107 Favorites.TITLE, // 16
108 Favorites.PROFILE_ID, // 17
Chris Wren1ada10d2013-09-13 18:01:38 -0400109 };
110
111 private static final int ID_INDEX = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400112 private static final int ID_MODIFIED = 1;
113 private static final int INTENT_INDEX = 2;
114 private static final int APPWIDGET_PROVIDER_INDEX = 3;
115 private static final int APPWIDGET_ID_INDEX = 4;
116 private static final int CELLX_INDEX = 5;
117 private static final int CELLY_INDEX = 6;
118 private static final int CONTAINER_INDEX = 7;
119 private static final int ICON_INDEX = 8;
120 private static final int ICON_PACKAGE_INDEX = 9;
121 private static final int ICON_RESOURCE_INDEX = 10;
122 private static final int ICON_TYPE_INDEX = 11;
123 private static final int ITEM_TYPE_INDEX = 12;
124 private static final int SCREEN_INDEX = 13;
125 private static final int SPANX_INDEX = 14;
126 private static final int SPANY_INDEX = 15;
127 private static final int TITLE_INDEX = 16;
Chris Wren1ada10d2013-09-13 18:01:38 -0400128
129 private static final String[] SCREEN_PROJECTION = {
Sunny Goyalef728d42014-10-22 11:28:28 -0700130 WorkspaceScreens._ID, // 0
131 WorkspaceScreens.MODIFIED, // 1
132 WorkspaceScreens.SCREEN_RANK // 2
Chris Wren1ada10d2013-09-13 18:01:38 -0400133 };
134
Chris Wren22e130d2013-09-23 18:25:57 -0400135 private static final int SCREEN_RANK_INDEX = 2;
Chris Wren1ada10d2013-09-13 18:01:38 -0400136
Chris Wren92aa4232013-10-04 11:29:36 -0400137 private final Context mContext;
Sunny Goyalef728d42014-10-22 11:28:28 -0700138 private final HashSet<String> mExistingKeys;
Sunny Goyal42de82f2014-09-26 22:09:29 -0700139 private final ArrayList<Key> mKeys;
Chris Wren1ada10d2013-09-13 18:01:38 -0400140
Sunny Goyalef728d42014-10-22 11:28:28 -0700141 private IconCache mIconCache;
142 private BackupManager mBackupManager;
143 private HashMap<ComponentName, AppWidgetProviderInfo> mWidgetMap;
144 private byte[] mBuffer = new byte[512];
145 private long mLastBackupRestoreTime;
146
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700147 private DeviceProfieData mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700148 boolean restoreSuccessful;
Sunny Goyal08f72612015-01-05 13:41:43 -0800149 int restoredBackupVersion = 1;
Sunny Goyal33d44382014-10-16 09:24:19 -0700150
151 public LauncherBackupHelper(Context context) {
Chris Wren92aa4232013-10-04 11:29:36 -0400152 mContext = context;
Sunny Goyalef728d42014-10-22 11:28:28 -0700153 mExistingKeys = new HashSet<String>();
Sunny Goyal42de82f2014-09-26 22:09:29 -0700154 mKeys = new ArrayList<Key>();
Sunny Goyal33d44382014-10-16 09:24:19 -0700155 restoreSuccessful = true;
Chris Wren92aa4232013-10-04 11:29:36 -0400156 }
157
158 private void dataChanged() {
Sunny Goyalef728d42014-10-22 11:28:28 -0700159 if (mBackupManager == null) {
160 mBackupManager = new BackupManager(mContext);
Chris Wren1ada10d2013-09-13 18:01:38 -0400161 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700162 mBackupManager.dataChanged();
163 }
164
165 private void applyJournal(Journal journal) {
166 mLastBackupRestoreTime = journal.t;
167 mExistingKeys.clear();
168 if (journal.key != null) {
169 for (Key key : journal.key) {
170 mExistingKeys.add(keyToBackupKey(key));
171 }
172 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400173 }
174
175 /**
176 * Back up launcher data so we can restore the user's state on a new device.
177 *
178 * <P>The journal is a timestamp and a list of keys that were saved as of that time.
179 *
180 * <P>Keys may come back in any order, so each key/value is one complete row of the database.
181 *
182 * @param oldState notes from the last backup
183 * @param data incremental key/value pairs to persist off-device
184 * @param newState notes for the next backup
Chris Wren1ada10d2013-09-13 18:01:38 -0400185 */
186 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400187 public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
188 ParcelFileDescriptor newState) {
Chris Wren50c8f422014-01-15 16:10:39 -0500189 if (VERBOSE) Log.v(TAG, "onBackup");
Chris Wren1ada10d2013-09-13 18:01:38 -0400190
191 Journal in = readJournal(oldState);
Sunny Goyalef728d42014-10-22 11:28:28 -0700192 if (!launcherIsReady()) {
193 // Perform backup later.
194 writeJournal(newState, in);
195 return;
196 }
197 Log.v(TAG, "lastBackupTime = " + in.t);
198 mKeys.clear();
199 applyJournal(in);
Chris Wren1ada10d2013-09-13 18:01:38 -0400200
Sunny Goyalef728d42014-10-22 11:28:28 -0700201 // Record the time before performing backup so that entries edited while the backup
202 // was going on, do not get missed in next backup.
203 long newBackupTime = System.currentTimeMillis();
Chris Wren1ada10d2013-09-13 18:01:38 -0400204
Sunny Goyalef728d42014-10-22 11:28:28 -0700205 try {
206 backupFavorites(data);
207 backupScreens(data);
208 backupIcons(data);
209 backupWidgets(data);
Chris Wren1ada10d2013-09-13 18:01:38 -0400210
Sunny Goyalef728d42014-10-22 11:28:28 -0700211 // Delete any key which still exist in the old backup, but is not valid anymore.
212 HashSet<String> validKeys = new HashSet<String>();
213 for (Key key : mKeys) {
214 validKeys.add(keyToBackupKey(key));
Chris Wren71144262014-02-27 15:49:39 -0500215 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700216 mExistingKeys.removeAll(validKeys);
217
218 // Delete anything left in the existing keys.
219 for (String deleted: mExistingKeys) {
220 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
221 data.writeEntityHeader(deleted, -1);
222 }
223
224 mExistingKeys.clear();
225 mLastBackupRestoreTime = newBackupTime;
Sunny Goyal33d44382014-10-16 09:24:19 -0700226
227 // We store the journal at two places.
228 // 1) Storing it in newState allows us to do partial backups by comparing old state
229 // 2) Storing it in backup data allows us to validate keys during restore
230 Journal state = getCurrentStateJournal();
231 writeRowToBackup(JOURNAL_KEY, state, data);
Sunny Goyalef728d42014-10-22 11:28:28 -0700232 } catch (IOException e) {
233 Log.e(TAG, "launcher backup has failed", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400234 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400235
Sunny Goyalef728d42014-10-22 11:28:28 -0700236 writeNewStateDescription(newState);
Chris Wren1ada10d2013-09-13 18:01:38 -0400237 }
238
239 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700240 * @return true if the backup corresponding to oldstate can be successfully applied
241 * to this device.
242 */
243 private boolean isBackupCompatible(Journal oldState) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700244 DeviceProfieData currentProfile = getDeviceProfieData();
245
246 DeviceProfieData oldProfile = oldState.profile;
247
248 if (oldProfile == null || oldProfile.desktopCols == 0) {
249 // Profile info is not valid, ignore the check.
250 return true;
251 }
252
253 boolean isHotsetCompatible = false;
254 if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
255 isHotsetCompatible = true;
256 }
257 if ((currentProfile.hotseatCount >= oldProfile.hotseatCount) &&
258 (currentProfile.allappsRank == oldProfile.allappsRank)) {
259 isHotsetCompatible = true;
260 }
261
262 return isHotsetCompatible && (currentProfile.desktopCols >= oldProfile.desktopCols)
263 && (currentProfile.desktopRows >= oldProfile.desktopRows);
Sunny Goyal33d44382014-10-16 09:24:19 -0700264 }
265
266 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400267 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700268 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
269 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400270 *
Chris Wren92aa4232013-10-04 11:29:36 -0400271 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400272 */
273 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400274 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700275 if (!restoreSuccessful) {
276 return;
277 }
278
Sunny Goyalef728d42014-10-22 11:28:28 -0700279 int dataSize = data.size();
280 if (mBuffer.length < dataSize) {
281 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400282 }
283 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700284 int bytesRead = data.read(mBuffer, 0, dataSize);
285 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
286 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700287
288 if (JOURNAL_KEY.equals(backupKey)) {
289 if (VERBOSE) Log.v(TAG, "Journal entry restored");
290 if (!mKeys.isEmpty()) {
291 // We received the journal key after a restore key.
292 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
293 restoreSuccessful = false;
294 return;
295 }
296
297 Journal journal = new Journal();
298 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
299 applyJournal(journal);
300 restoreSuccessful = isBackupCompatible(journal);
Sunny Goyal08f72612015-01-05 13:41:43 -0800301 restoredBackupVersion = journal.backupVersion;
Sunny Goyal33d44382014-10-16 09:24:19 -0700302 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 }
Chris Wrenb02e6112014-11-24 16:57:54 -0500374 final Context applicationContext = mContext.getApplicationContext();
375 DeviceProfile profile = LauncherAppState.createDynamicGrid(applicationContext, null)
376 .getDeviceProfile();
Sunny Goyal33d44382014-10-16 09:24:19 -0700377
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700378 mCurrentProfile = new DeviceProfieData();
379 mCurrentProfile.desktopRows = profile.numRows;
380 mCurrentProfile.desktopCols = profile.numColumns;
381 mCurrentProfile.hotseatCount = profile.numHotseatIcons;
382 mCurrentProfile.allappsRank = profile.hotseatAllAppsRank;
383 return mCurrentProfile;
Sunny Goyal33d44382014-10-16 09:24:19 -0700384 }
385
386 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400387 * Write all modified favorites to the data stream.
388 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400389 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400390 * @throws IOException
391 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700392 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400393 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400394 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700395 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400396 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700397 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400398 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400399 cursor.moveToPosition(-1);
400 while(cursor.moveToNext()) {
401 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700402 final long updateTime = cursor.getLong(ID_MODIFIED);
403 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700404 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700405 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700406 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
407 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500408 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700409 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400410 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400411 }
412 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400413 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400414 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400415 }
416
417 /**
418 * Read a favorite from the stream.
419 *
420 * <P>Keys arrive in any order, so screens and containers may not exist yet.
421 *
422 * @param key identifier for the row
423 * @param buffer the serialized proto from the stream, may be larger than dataSize
424 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400425 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700426 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500427 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400428 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
429 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
430
Sunny Goyalef728d42014-10-22 11:28:28 -0700431 ContentResolver cr = mContext.getContentResolver();
432 ContentValues values = unpackFavorite(buffer, dataSize);
433 cr.insert(Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400434 }
435
436 /**
437 * Write all modified screens to the data stream.
438 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400439 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400440 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400441 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700442 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400443 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400444 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400445 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
446 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400447 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400448 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700449 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400450 while(cursor.moveToNext()) {
451 final long id = cursor.getLong(ID_INDEX);
452 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400453 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700454 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500455 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700456 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
457 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500458 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700459 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400460 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400461 }
462 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400463 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400464 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400465 }
466
467 /**
468 * Read a screen from the stream.
469 *
470 * <P>Keys arrive in any order, so children of this screen may already exist.
471 *
472 * @param key identifier for the row
473 * @param buffer the serialized proto from the stream, may be larger than dataSize
474 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400475 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700476 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500477 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400478 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
479 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500480
Sunny Goyalef728d42014-10-22 11:28:28 -0700481 ContentResolver cr = mContext.getContentResolver();
482 ContentValues values = unpackScreen(buffer, dataSize);
483 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400484 }
485
Chris Wren22e130d2013-09-23 18:25:57 -0400486 /**
487 * Write all the static icon resources we need to render placeholders
488 * for a package that is not installed.
489 *
Chris Wren22e130d2013-09-23 18:25:57 -0400490 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400491 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700492 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400493 // persist icons that haven't been persisted yet
Chris Wren6d0dde02014-02-10 12:16:54 -0500494 if (!initializeIconCache()) {
Chris Wren92aa4232013-10-04 11:29:36 -0400495 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400496 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
497 return;
498 }
Chris Wren92aa4232013-10-04 11:29:36 -0400499 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400500 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700501 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700502 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400503
Kenny Guyed131872014-04-30 03:02:21 +0100504 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100505 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100506 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700507 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400508 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
509 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400510 try {
511 cursor.moveToPosition(-1);
512 while(cursor.moveToNext()) {
513 final long id = cursor.getLong(ID_INDEX);
514 final String intentDescription = cursor.getString(INTENT_INDEX);
515 try {
516 Intent intent = Intent.parseUri(intentDescription, 0);
517 ComponentName cn = intent.getComponent();
518 Key key = null;
519 String backupKey = null;
520 if (cn != null) {
521 key = getKey(Key.ICON, cn.flattenToShortString());
522 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400523 } else {
524 Log.w(TAG, "empty intent on application favorite: " + id);
525 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700526 if (mExistingKeys.contains(backupKey)) {
527 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400528
529 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700530 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400531 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700532 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
533 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
534 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100535 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100536 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700537 writeRowToBackup(key, packIcon(dpi, icon), data);
538 mKeys.add(key);
539 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400540 }
541 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700542 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400543 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400544 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400545 }
546 }
547 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500548 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400549 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500550 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400551 }
552
553 }
554 } finally {
555 cursor.close();
556 }
Chris Wren22e130d2013-09-23 18:25:57 -0400557 }
558
559 /**
560 * Read an icon from the stream.
561 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400562 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400563 *
564 * @param key identifier for the row
565 * @param buffer the serialized proto from the stream, may be larger than dataSize
566 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400567 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700568 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500569 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400570 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
571 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500572
Sunny Goyalef728d42014-10-22 11:28:28 -0700573 Resource res = unpackProto(new Resource(), buffer, dataSize);
574 if (DEBUG) {
575 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400576 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700577 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
578 if (icon == null) {
579 Log.w(TAG, "failed to unpack icon for " + key.name);
580 }
581 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
582 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(key.name), icon, res.dpi);
Chris Wren22e130d2013-09-23 18:25:57 -0400583 }
584
Chris Wrenfd13c712013-09-27 15:45:19 -0400585 /**
586 * Write all the static widget resources we need to render placeholders
587 * for a package that is not installed.
588 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400589 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400590 * @throws IOException
591 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700592 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400593 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400594 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
Chris Wren6d0dde02014-02-10 12:16:54 -0500595 if (appState == null || !initializeIconCache()) {
596 Log.w(TAG, "Failed to get icon cache during restore");
Chris Wrend8fe6de2013-10-04 10:42:14 -0400597 return;
598 }
Chris Wren92aa4232013-10-04 11:29:36 -0400599 final ContentResolver cr = mContext.getContentResolver();
600 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
601 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wren92aa4232013-10-04 11:29:36 -0400602 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400603 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
604 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
Sunny Goyalef728d42014-10-22 11:28:28 -0700605 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400606
Sunny Goyalffe83f12014-08-14 17:39:34 -0700607 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
608 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400609 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
610 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400611 try {
612 cursor.moveToPosition(-1);
613 while(cursor.moveToNext()) {
614 final long id = cursor.getLong(ID_INDEX);
615 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
616 final int spanX = cursor.getInt(SPANX_INDEX);
617 final int spanY = cursor.getInt(SPANY_INDEX);
618 final ComponentName provider = ComponentName.unflattenFromString(providerName);
619 Key key = null;
620 String backupKey = null;
621 if (provider != null) {
622 key = getKey(Key.WIDGET, providerName);
623 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400624 } else {
625 Log.w(TAG, "empty intent on appwidget: " + id);
626 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700627 if (mExistingKeys.contains(backupKey)) {
628 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400629
630 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700631 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400632 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700633 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
634 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
635 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400636 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
637 spanY * profile.cellHeightPx, widgetSpacingLayout);
Sunny Goyalef728d42014-10-22 11:28:28 -0700638 writeRowToBackup(key, packWidget(dpi, previewLoader, mIconCache, provider), data);
639 mKeys.add(key);
640 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400641 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700642 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400643 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400644 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400645 }
646 }
647 }
648 } finally {
649 cursor.close();
650 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400651 }
652
653 /**
654 * Read a widget from the stream.
655 *
656 * <P>Keys arrive in any order, so widgets that use this data may already exist.
657 *
658 * @param key identifier for the row
659 * @param buffer the serialized proto from the stream, may be larger than dataSize
660 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400661 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700662 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500663 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400664 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
665 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700666 Widget widget = unpackProto(new Widget(), buffer, dataSize);
667 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
668 if (widget.icon.data != null) {
669 Bitmap icon = BitmapFactory
670 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
671 if (icon == null) {
672 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500673 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700674 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(widget.provider),
675 icon, widget.icon.dpi);
Chris Wren5dee7af2013-12-20 17:22:11 -0500676 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400677 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700678
679 // future site of widget table mutation
Chris Wrenfd13c712013-09-27 15:45:19 -0400680 }
681
Chris Wren22e130d2013-09-23 18:25:57 -0400682 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400683 *
684 * <P> Keys contain their own checksum instead of using
685 * the heavy-weight CheckedMessage wrapper.
686 */
687 private Key getKey(int type, long id) {
688 Key key = new Key();
689 key.type = type;
690 key.id = id;
691 key.checksum = checkKey(key);
692 return key;
693 }
694
Chris Wren22e130d2013-09-23 18:25:57 -0400695 /** create a new key for a named object.
696 *
697 * <P> Keys contain their own checksum instead of using
698 * the heavy-weight CheckedMessage wrapper.
699 */
700 private Key getKey(int type, String name) {
701 Key key = new Key();
702 key.type = type;
703 key.name = name;
704 key.checksum = checkKey(key);
705 return key;
706 }
707
Chris Wren1ada10d2013-09-13 18:01:38 -0400708 /** keys need to be strings, serialize and encode. */
709 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400710 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400711 }
712
713 /** keys need to be strings, decode and parse. */
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700714 private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400715 try {
716 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
717 if (key.checksum != checkKey(key)) {
718 key = null;
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700719 throw new InvalidBackupException("invalid key read from stream" + backupKey);
Chris Wren1ada10d2013-09-13 18:01:38 -0400720 }
721 return key;
722 } catch (InvalidProtocolBufferNanoException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700723 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400724 } catch (IllegalArgumentException e) {
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700725 throw new InvalidBackupException(e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400726 }
727 }
728
729 /** Compute the checksum over the important bits of a key. */
730 private long checkKey(Key key) {
731 CRC32 checksum = new CRC32();
732 checksum.update(key.type);
733 checksum.update((int) (key.id & 0xffff));
734 checksum.update((int) ((key.id >> 32) & 0xffff));
735 if (!TextUtils.isEmpty(key.name)) {
736 checksum.update(key.name.getBytes());
737 }
738 return checksum.getValue();
739 }
740
741 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700742 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400743 Favorite favorite = new Favorite();
744 favorite.id = c.getLong(ID_INDEX);
745 favorite.screen = c.getInt(SCREEN_INDEX);
746 favorite.container = c.getInt(CONTAINER_INDEX);
747 favorite.cellX = c.getInt(CELLX_INDEX);
748 favorite.cellY = c.getInt(CELLY_INDEX);
749 favorite.spanX = c.getInt(SPANX_INDEX);
750 favorite.spanY = c.getInt(SPANY_INDEX);
751 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
752 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
753 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
754 if (!TextUtils.isEmpty(iconPackage)) {
755 favorite.iconPackage = iconPackage;
756 }
757 String iconResource = c.getString(ICON_RESOURCE_INDEX);
758 if (!TextUtils.isEmpty(iconResource)) {
759 favorite.iconResource = iconResource;
760 }
761 }
762 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
763 byte[] blob = c.getBlob(ICON_INDEX);
764 if (blob != null && blob.length > 0) {
765 favorite.icon = blob;
766 }
767 }
768 String title = c.getString(TITLE_INDEX);
769 if (!TextUtils.isEmpty(title)) {
770 favorite.title = title;
771 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100772 String intentDescription = c.getString(INTENT_INDEX);
773 if (!TextUtils.isEmpty(intentDescription)) {
774 try {
775 Intent intent = Intent.parseUri(intentDescription, 0);
776 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
777 favorite.intent = intent.toUri(0);
778 } catch (URISyntaxException e) {
779 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700780 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400781 }
782 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
783 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
784 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
785 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
786 if (!TextUtils.isEmpty(appWidgetProvider)) {
787 favorite.appWidgetProvider = appWidgetProvider;
788 }
789 }
790
Sunny Goyalef728d42014-10-22 11:28:28 -0700791 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400792 }
793
794 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700795 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700796 throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700797 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500798 ContentValues values = new ContentValues();
799 values.put(Favorites._ID, favorite.id);
800 values.put(Favorites.SCREEN, favorite.screen);
801 values.put(Favorites.CONTAINER, favorite.container);
802 values.put(Favorites.CELLX, favorite.cellX);
803 values.put(Favorites.CELLY, favorite.cellY);
804 values.put(Favorites.SPANX, favorite.spanX);
805 values.put(Favorites.SPANY, favorite.spanY);
806 values.put(Favorites.ICON_TYPE, favorite.iconType);
807 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
808 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
809 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
810 }
811 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
812 values.put(Favorites.ICON, favorite.icon);
813 }
814 if (!TextUtils.isEmpty(favorite.title)) {
815 values.put(Favorites.TITLE, favorite.title);
816 } else {
817 values.put(Favorites.TITLE, "");
818 }
819 if (!TextUtils.isEmpty(favorite.intent)) {
820 values.put(Favorites.INTENT, favorite.intent);
821 }
822 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500823
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100824 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
825 long userSerialNumber =
826 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
827 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
828
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700829 DeviceProfieData currentProfile = getDeviceProfieData();
830
Sunny Goyalff572272014-07-23 13:58:07 -0700831 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
832 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
833 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
834 }
835 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
836 values.put(LauncherSettings.Favorites.RESTORED,
837 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
838 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
839 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700840
841 // Verify placement
842 if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
843 || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
844 restoreSuccessful = false;
845 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
846 }
Sunny Goyalff572272014-07-23 13:58:07 -0700847 } else {
848 // Let LauncherModel know we've been here.
849 values.put(LauncherSettings.Favorites.RESTORED, 1);
Sunny Goyal5fd733d2014-10-29 10:51:54 -0700850
851 // Verify placement
852 if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
853 if ((favorite.screen >= currentProfile.hotseatCount)
854 || (favorite.screen == currentProfile.allappsRank)) {
855 restoreSuccessful = false;
856 throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
857 }
858 } else {
859 if ((favorite.cellX >= currentProfile.desktopCols)
860 || (favorite.cellY >= currentProfile.desktopRows)) {
861 restoreSuccessful = false;
862 throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
863 }
864 }
Sunny Goyalff572272014-07-23 13:58:07 -0700865 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500866
Chris Wren5dee7af2013-12-20 17:22:11 -0500867 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400868 }
869
870 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700871 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400872 Screen screen = new Screen();
873 screen.id = c.getLong(ID_INDEX);
874 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700875 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400876 }
877
878 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700879 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400880 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700881 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500882 ContentValues values = new ContentValues();
883 values.put(WorkspaceScreens._ID, screen.id);
884 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
885 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400886 }
887
Chris Wren22e130d2013-09-23 18:25:57 -0400888 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700889 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400890 Resource res = new Resource();
891 res.dpi = dpi;
892 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400893 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400894 res.data = os.toByteArray();
895 }
Chris Wren22e130d2013-09-23 18:25:57 -0400896 return res;
897 }
898
Chris Wrenfd13c712013-09-27 15:45:19 -0400899 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700900 private Widget packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
Chris Wrenfd13c712013-09-27 15:45:19 -0400901 ComponentName provider) {
Adam Cohen59400422014-03-05 18:07:04 -0800902 final LauncherAppWidgetProviderInfo info =
903 LauncherModel.getProviderInfo(mContext, provider);
Chris Wrenfd13c712013-09-27 15:45:19 -0400904 Widget widget = new Widget();
905 widget.provider = provider.flattenToShortString();
906 widget.label = info.label;
907 widget.configure = info.configure != null;
908 if (info.icon != 0) {
909 widget.icon = new Resource();
910 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400911 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400912 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400913 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400914 widget.icon.data = os.toByteArray();
915 widget.icon.dpi = dpi;
916 }
917 }
918 if (info.previewImage != 0) {
919 widget.preview = new Resource();
920 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
921 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400922 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400923 widget.preview.data = os.toByteArray();
924 widget.preview.dpi = dpi;
925 }
926 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700927 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -0400928 }
929
Sunny Goyalef728d42014-10-22 11:28:28 -0700930 /**
931 * Deserialize a proto after verifying checksum wrapper.
932 */
933 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -0400934 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700935 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
936 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
937 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -0400938 }
939
Chris Wren1ada10d2013-09-13 18:01:38 -0400940 /**
941 * Read the old journal from the input file.
942 *
943 * In the event of any error, just pretend we didn't have a journal,
944 * in that case, do a full backup.
945 *
946 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -0500947 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -0400948 */
949 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400950 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400951 if (oldState == null) {
952 return journal;
953 }
954 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
955 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500956 int availableBytes = inStream.available();
957 if (DEBUG) Log.d(TAG, "available " + availableBytes);
958 if (availableBytes < MAX_JOURNAL_SIZE) {
959 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -0400960 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -0500961 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -0500962 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500963 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -0400964 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500965 // OMG what are you doing? This is crazy inefficient!
966 // If we read a byte that is not ours, we will cause trouble: b/12491813
967 // However, we don't know how many bytes to expect (oops).
968 // So we have to step through *slowly*, watching for the end.
969 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -0400970 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -0500971 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -0400972 bytesRead += result;
973 } else {
Chris Wren65b6a602014-01-10 14:11:25 -0500974 Log.w(TAG, "unexpected end of file while reading journal.");
975 // stop reading and see what there is to parse
976 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400977 }
978 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -0400979 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500980 availableBytes = 0;
981 }
982
983 // check the buffer to see if we have a valid journal
984 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700985 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -0500986 // if we are here, then we have read a valid, checksum-verified journal
987 valid = true;
988 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -0500989 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -0500990 } catch (InvalidProtocolBufferNanoException e) {
991 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -0500992 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -0500993 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -0400994 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400995 }
Chris Wren92aa4232013-10-04 11:29:36 -0400996 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -0500997 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -0500998 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -0400999 }
1000 }
Chris Wren92aa4232013-10-04 11:29:36 -04001001 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001002 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -04001003 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -04001004 try {
1005 inStream.close();
1006 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001007 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001008 }
1009 }
1010 return journal;
1011 }
1012
Sunny Goyalef728d42014-10-22 11:28:28 -07001013 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
1014 throws IOException {
1015 writeRowToBackup(keyToBackupKey(key), proto, data);
1016 }
1017
1018 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -04001019 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -07001020 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -04001021 data.writeEntityHeader(backupKey, blob.length);
1022 data.writeEntityData(blob, blob.length);
Sunny Goyalef728d42014-10-22 11:28:28 -07001023 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -04001024 }
1025
Chris Wren1ada10d2013-09-13 18:01:38 -04001026 /**
1027 * Write the new journal to the output file.
1028 *
1029 * In the event of any error, just pretend we didn't have a journal,
1030 * in that case, do a full backup.
1031
1032 * @param newState the write-only file descriptor pointing to the new journal
1033 * @param journal a Journal protocol buffer
1034 */
1035 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
1036 FileOutputStream outStream = null;
1037 try {
1038 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -05001039 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -05001040 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001041 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001042 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001043 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001044 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001045 }
1046 }
1047
1048 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1049 private byte[] writeCheckedBytes(MessageNano proto) {
1050 CheckedMessage wrapper = new CheckedMessage();
1051 wrapper.payload = MessageNano.toByteArray(proto);
1052 CRC32 checksum = new CRC32();
1053 checksum.update(wrapper.payload);
1054 wrapper.checksum = checksum.getValue();
1055 return MessageNano.toByteArray(wrapper);
1056 }
1057
1058 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001059 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001060 throws InvalidProtocolBufferNanoException {
1061 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001062 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001063 CRC32 checksum = new CRC32();
1064 checksum.update(wrapper.payload);
1065 if (wrapper.checksum != checksum.getValue()) {
1066 throw new InvalidProtocolBufferNanoException("checksum does not match");
1067 }
1068 return wrapper.payload;
1069 }
1070
Chris Wren6d0dde02014-02-10 12:16:54 -05001071 private boolean initializeIconCache() {
1072 if (mIconCache != null) {
1073 return true;
1074 }
1075
1076 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
1077 if (appState == null) {
1078 Throwable stackTrace = new Throwable();
1079 stackTrace.fillInStackTrace();
1080 Log.w(TAG, "Failed to get app state during backup/restore", stackTrace);
1081 return false;
1082 }
1083 mIconCache = appState.getIconCache();
1084 return mIconCache != null;
1085 }
1086
Chris Wren71144262014-02-27 15:49:39 -05001087
Sunny Goyalef728d42014-10-22 11:28:28 -07001088 /**
1089 * @return true if the launcher is in a state to support backup
1090 */
Chris Wren71144262014-02-27 15:49:39 -05001091 private boolean launcherIsReady() {
1092 ContentResolver cr = mContext.getContentResolver();
1093 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1094 if (cursor == null) {
1095 // launcher data has been wiped, do nothing
1096 return false;
1097 }
1098 cursor.close();
1099
1100 if (!initializeIconCache()) {
1101 // launcher services are unavailable, try again later
1102 dataChanged();
1103 return false;
1104 }
1105
1106 return true;
1107 }
1108
Sunny Goyalffe83f12014-08-14 17:39:34 -07001109 private String getUserSelectionArg() {
1110 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1111 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1112 }
1113
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001114 private class InvalidBackupException extends IOException {
1115 private InvalidBackupException(Throwable cause) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001116 super(cause);
1117 }
1118
Sunny Goyal5fd733d2014-10-29 10:51:54 -07001119 public InvalidBackupException(String reason) {
Chris Wren1ada10d2013-09-13 18:01:38 -04001120 super(reason);
1121 }
1122 }
1123}