blob: 8b9c5d96a397173a7d2abe674eb90285af3366b4 [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 Goyal33d44382014-10-16 09:24:19 -0700149 boolean restoreSuccessful;
150
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) {
244 return true;
245 }
246
247 /**
Chris Wren92aa4232013-10-04 11:29:36 -0400248 * Restore launcher configuration from the restored data stream.
Sunny Goyal33d44382014-10-16 09:24:19 -0700249 * It assumes that the keys will arrive in lexical order. So if the journal was present in the
250 * backup, it should arrive first.
Chris Wren1ada10d2013-09-13 18:01:38 -0400251 *
Chris Wren92aa4232013-10-04 11:29:36 -0400252 * @param data the key/value pair from the server
Chris Wren1ada10d2013-09-13 18:01:38 -0400253 */
254 @Override
Chris Wren92aa4232013-10-04 11:29:36 -0400255 public void restoreEntity(BackupDataInputStream data) {
Sunny Goyal33d44382014-10-16 09:24:19 -0700256 if (!restoreSuccessful) {
257 return;
258 }
259
Sunny Goyalef728d42014-10-22 11:28:28 -0700260 int dataSize = data.size();
261 if (mBuffer.length < dataSize) {
262 mBuffer = new byte[dataSize];
Chris Wren92aa4232013-10-04 11:29:36 -0400263 }
264 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700265 int bytesRead = data.read(mBuffer, 0, dataSize);
266 if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
267 String backupKey = data.getKey();
Sunny Goyal33d44382014-10-16 09:24:19 -0700268
269 if (JOURNAL_KEY.equals(backupKey)) {
270 if (VERBOSE) Log.v(TAG, "Journal entry restored");
271 if (!mKeys.isEmpty()) {
272 // We received the journal key after a restore key.
273 Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
274 restoreSuccessful = false;
275 return;
276 }
277
278 Journal journal = new Journal();
279 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
280 applyJournal(journal);
281 restoreSuccessful = isBackupCompatible(journal);
282 return;
283 }
284
285 if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
286 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
287 return;
288 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700289 Key key = backupKeyToKey(backupKey);
Chris Wren50c8f422014-01-15 16:10:39 -0500290 mKeys.add(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400291 switch (key.type) {
292 case Key.FAVORITE:
Sunny Goyalef728d42014-10-22 11:28:28 -0700293 restoreFavorite(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400294 break;
295
296 case Key.SCREEN:
Sunny Goyalef728d42014-10-22 11:28:28 -0700297 restoreScreen(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400298 break;
299
300 case Key.ICON:
Sunny Goyalef728d42014-10-22 11:28:28 -0700301 restoreIcon(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400302 break;
303
304 case Key.WIDGET:
Sunny Goyalef728d42014-10-22 11:28:28 -0700305 restoreWidget(key, mBuffer, dataSize);
Chris Wren92aa4232013-10-04 11:29:36 -0400306 break;
307
308 default:
309 Log.w(TAG, "unknown restore entity type: " + key.type);
Sunny Goyalef728d42014-10-22 11:28:28 -0700310 mKeys.remove(key);
Chris Wren92aa4232013-10-04 11:29:36 -0400311 break;
Chris Wren1ada10d2013-09-13 18:01:38 -0400312 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700313 } catch (IOException e) {
314 Log.w(TAG, "ignoring unparsable backup entry", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400315 }
Chris Wren92aa4232013-10-04 11:29:36 -0400316 }
317
318 /**
319 * Record the restore state for the next backup.
320 *
321 * @param newState notes about the backup state after restore.
322 */
323 @Override
324 public void writeNewStateDescription(ParcelFileDescriptor newState) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700325 writeJournal(newState, getCurrentStateJournal());
326 }
327
328 private Journal getCurrentStateJournal() {
329 Journal journal = new Journal();
330 journal.t = mLastBackupRestoreTime;
331 journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
332 journal.appVersion = getAppVersion();
Sunny Goyal33d44382014-10-16 09:24:19 -0700333 journal.backupVersion = BACKUP_VERSION;
334 journal.profile = getDeviceProfieData();
Sunny Goyalef728d42014-10-22 11:28:28 -0700335 return journal;
336 }
337
338 private int getAppVersion() {
339 try {
340 return mContext.getPackageManager()
341 .getPackageInfo(mContext.getPackageName(), 0).versionCode;
342 } catch (NameNotFoundException e) {
343 return 0;
344 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400345 }
346
347 /**
Sunny Goyal33d44382014-10-16 09:24:19 -0700348 * @return the current device profile information.
349 */
350 private DeviceProfieData getDeviceProfieData() {
351 LauncherAppState.setApplicationContext(mContext.getApplicationContext());
352 LauncherAppState app = LauncherAppState.getInstance();
353
354 DeviceProfile profile;
355 if (app.getDynamicGrid() == null) {
356 // Initialize the grid
357 profile = app.initDynamicGrid(mContext);
358 } else {
359 profile = app.getDynamicGrid().getDeviceProfile();
360 }
361
362 DeviceProfieData data = new DeviceProfieData();
363 data.desktopRows = profile.numRows;
364 data.desktopCols = profile.numColumns;
365 data.hotseatCount = profile.numHotseatIcons;
366 data.allappsRank = profile.hotseatAllAppsRank;
367 return data;
368 }
369
370 /**
Chris Wren1ada10d2013-09-13 18:01:38 -0400371 * Write all modified favorites to the data stream.
372 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400373 * @param data output stream for key/value pairs
Chris Wren1ada10d2013-09-13 18:01:38 -0400374 * @throws IOException
375 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700376 private void backupFavorites(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400377 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400378 ContentResolver cr = mContext.getContentResolver();
Sunny Goyalffe83f12014-08-14 17:39:34 -0700379 // Don't backup apps in other profiles for now.
Chris Wren22e130d2013-09-23 18:25:57 -0400380 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
Sunny Goyalffe83f12014-08-14 17:39:34 -0700381 getUserSelectionArg(), null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400382 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400383 cursor.moveToPosition(-1);
384 while(cursor.moveToNext()) {
385 final long id = cursor.getLong(ID_INDEX);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700386 final long updateTime = cursor.getLong(ID_MODIFIED);
387 Key key = getKey(Key.FAVORITE, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700388 mKeys.add(key);
Sunny Goyalffe83f12014-08-14 17:39:34 -0700389 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700390 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
391 writeRowToBackup(key, packFavorite(cursor), data);
Chris Wren50c8f422014-01-15 16:10:39 -0500392 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700393 if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400394 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400395 }
396 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400397 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400398 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400399 }
400
401 /**
402 * Read a favorite from the stream.
403 *
404 * <P>Keys arrive in any order, so screens and containers may not exist yet.
405 *
406 * @param key identifier for the row
407 * @param buffer the serialized proto from the stream, may be larger than dataSize
408 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400409 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700410 private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500411 if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400412 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
413 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
414
Sunny Goyalef728d42014-10-22 11:28:28 -0700415 ContentResolver cr = mContext.getContentResolver();
416 ContentValues values = unpackFavorite(buffer, dataSize);
417 cr.insert(Favorites.CONTENT_URI_NO_NOTIFICATION, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400418 }
419
420 /**
421 * Write all modified screens to the data stream.
422 *
Chris Wren1ada10d2013-09-13 18:01:38 -0400423 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400424 * @throws IOException
Chris Wren1ada10d2013-09-13 18:01:38 -0400425 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700426 private void backupScreens(BackupDataOutput data) throws IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -0400427 // persist things that have changed since the last backup
Chris Wren92aa4232013-10-04 11:29:36 -0400428 ContentResolver cr = mContext.getContentResolver();
Chris Wren22e130d2013-09-23 18:25:57 -0400429 Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
430 null, null, null);
Chris Wren1ada10d2013-09-13 18:01:38 -0400431 try {
Chris Wren22e130d2013-09-23 18:25:57 -0400432 cursor.moveToPosition(-1);
Sunny Goyalef728d42014-10-22 11:28:28 -0700433 if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
Chris Wren22e130d2013-09-23 18:25:57 -0400434 while(cursor.moveToNext()) {
435 final long id = cursor.getLong(ID_INDEX);
436 final long updateTime = cursor.getLong(ID_MODIFIED);
Chris Wren1ada10d2013-09-13 18:01:38 -0400437 Key key = getKey(Key.SCREEN, id);
Sunny Goyalef728d42014-10-22 11:28:28 -0700438 mKeys.add(key);
Chris Wren5743aa92014-01-10 18:02:06 -0500439 final String backupKey = keyToBackupKey(key);
Sunny Goyalef728d42014-10-22 11:28:28 -0700440 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
441 writeRowToBackup(key, packScreen(cursor), data);
Chris Wren5dee7af2013-12-20 17:22:11 -0500442 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700443 if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400444 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400445 }
446 } finally {
Chris Wren22e130d2013-09-23 18:25:57 -0400447 cursor.close();
Chris Wren1ada10d2013-09-13 18:01:38 -0400448 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400449 }
450
451 /**
452 * Read a screen from the stream.
453 *
454 * <P>Keys arrive in any order, so children of this screen may already exist.
455 *
456 * @param key identifier for the row
457 * @param buffer the serialized proto from the stream, may be larger than dataSize
458 * @param dataSize the size of the proto from the stream
Chris Wren1ada10d2013-09-13 18:01:38 -0400459 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700460 private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500461 if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
Chris Wren1ada10d2013-09-13 18:01:38 -0400462 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
463 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren5dee7af2013-12-20 17:22:11 -0500464
Sunny Goyalef728d42014-10-22 11:28:28 -0700465 ContentResolver cr = mContext.getContentResolver();
466 ContentValues values = unpackScreen(buffer, dataSize);
467 cr.insert(WorkspaceScreens.CONTENT_URI, values);
Chris Wren1ada10d2013-09-13 18:01:38 -0400468 }
469
Chris Wren22e130d2013-09-23 18:25:57 -0400470 /**
471 * Write all the static icon resources we need to render placeholders
472 * for a package that is not installed.
473 *
Chris Wren22e130d2013-09-23 18:25:57 -0400474 * @param data output stream for key/value pairs
Chris Wren22e130d2013-09-23 18:25:57 -0400475 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700476 private void backupIcons(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400477 // persist icons that haven't been persisted yet
Chris Wren6d0dde02014-02-10 12:16:54 -0500478 if (!initializeIconCache()) {
Chris Wren92aa4232013-10-04 11:29:36 -0400479 dataChanged(); // try again later
Chris Wrend8fe6de2013-10-04 10:42:14 -0400480 if (DEBUG) Log.d(TAG, "Launcher is not initialized, delaying icon backup");
481 return;
482 }
Chris Wren92aa4232013-10-04 11:29:36 -0400483 final ContentResolver cr = mContext.getContentResolver();
Chris Wren92aa4232013-10-04 11:29:36 -0400484 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Sunny Goyalffe83f12014-08-14 17:39:34 -0700485 final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
Sunny Goyalef728d42014-10-22 11:28:28 -0700486 int backupUpIconCount = 0;
Chris Wren22e130d2013-09-23 18:25:57 -0400487
Kenny Guyed131872014-04-30 03:02:21 +0100488 // Don't backup apps in other profiles for now.
Kenny Guyed131872014-04-30 03:02:21 +0100489 String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
Kenny Guy43ea7ac2014-05-09 16:44:18 +0100490 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
Sunny Goyalffe83f12014-08-14 17:39:34 -0700491 getUserSelectionArg();
Chris Wren22e130d2013-09-23 18:25:57 -0400492 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
493 where, null, null);
Chris Wren22e130d2013-09-23 18:25:57 -0400494 try {
495 cursor.moveToPosition(-1);
496 while(cursor.moveToNext()) {
497 final long id = cursor.getLong(ID_INDEX);
498 final String intentDescription = cursor.getString(INTENT_INDEX);
499 try {
500 Intent intent = Intent.parseUri(intentDescription, 0);
501 ComponentName cn = intent.getComponent();
502 Key key = null;
503 String backupKey = null;
504 if (cn != null) {
505 key = getKey(Key.ICON, cn.flattenToShortString());
506 backupKey = keyToBackupKey(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400507 } else {
508 Log.w(TAG, "empty intent on application favorite: " + id);
509 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700510 if (mExistingKeys.contains(backupKey)) {
511 if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400512
513 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700514 mKeys.add(key);
Chris Wren22e130d2013-09-23 18:25:57 -0400515 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700516 if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
517 if (backupUpIconCount < MAX_ICONS_PER_PASS) {
518 if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
Kenny Guyed131872014-04-30 03:02:21 +0100519 Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
Kenny Guyed131872014-04-30 03:02:21 +0100520 if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700521 writeRowToBackup(key, packIcon(dpi, icon), data);
522 mKeys.add(key);
523 backupUpIconCount ++;
Chris Wren22e130d2013-09-23 18:25:57 -0400524 }
525 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700526 if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400527 // too many icons for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400528 dataChanged();
Chris Wren22e130d2013-09-23 18:25:57 -0400529 }
530 }
531 } catch (URISyntaxException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500532 Log.e(TAG, "invalid URI on application favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400533 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500534 Log.e(TAG, "unable to save application icon for favorite: " + id);
Chris Wren22e130d2013-09-23 18:25:57 -0400535 }
536
537 }
538 } finally {
539 cursor.close();
540 }
Chris Wren22e130d2013-09-23 18:25:57 -0400541 }
542
543 /**
544 * Read an icon from the stream.
545 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400546 * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
Chris Wren22e130d2013-09-23 18:25:57 -0400547 *
548 * @param key identifier for the row
549 * @param buffer the serialized proto from the stream, may be larger than dataSize
550 * @param dataSize the size of the proto from the stream
Chris Wren22e130d2013-09-23 18:25:57 -0400551 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700552 private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500553 if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
Chris Wren22e130d2013-09-23 18:25:57 -0400554 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
555 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Chris Wren6d0dde02014-02-10 12:16:54 -0500556
Sunny Goyalef728d42014-10-22 11:28:28 -0700557 Resource res = unpackProto(new Resource(), buffer, dataSize);
558 if (DEBUG) {
559 Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
Chris Wren22e130d2013-09-23 18:25:57 -0400560 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700561 Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
562 if (icon == null) {
563 Log.w(TAG, "failed to unpack icon for " + key.name);
564 }
565 if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
566 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(key.name), icon, res.dpi);
Chris Wren22e130d2013-09-23 18:25:57 -0400567 }
568
Chris Wrenfd13c712013-09-27 15:45:19 -0400569 /**
570 * Write all the static widget resources we need to render placeholders
571 * for a package that is not installed.
572 *
Chris Wrenfd13c712013-09-27 15:45:19 -0400573 * @param data output stream for key/value pairs
Chris Wrenfd13c712013-09-27 15:45:19 -0400574 * @throws IOException
575 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700576 private void backupWidgets(BackupDataOutput data) throws IOException {
Chris Wrenfd13c712013-09-27 15:45:19 -0400577 // persist static widget info that hasn't been persisted yet
Chris Wrend8fe6de2013-10-04 10:42:14 -0400578 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
Chris Wren6d0dde02014-02-10 12:16:54 -0500579 if (appState == null || !initializeIconCache()) {
580 Log.w(TAG, "Failed to get icon cache during restore");
Chris Wrend8fe6de2013-10-04 10:42:14 -0400581 return;
582 }
Chris Wren92aa4232013-10-04 11:29:36 -0400583 final ContentResolver cr = mContext.getContentResolver();
584 final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
585 final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
Chris Wren92aa4232013-10-04 11:29:36 -0400586 final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
Chris Wrenfd13c712013-09-27 15:45:19 -0400587 final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
588 if (DEBUG) Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
Sunny Goyalef728d42014-10-22 11:28:28 -0700589 int backupWidgetCount = 0;
Chris Wrenfd13c712013-09-27 15:45:19 -0400590
Sunny Goyalffe83f12014-08-14 17:39:34 -0700591 String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
592 + getUserSelectionArg();
Chris Wrenfd13c712013-09-27 15:45:19 -0400593 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
594 where, null, null);
Chris Wrenfd13c712013-09-27 15:45:19 -0400595 try {
596 cursor.moveToPosition(-1);
597 while(cursor.moveToNext()) {
598 final long id = cursor.getLong(ID_INDEX);
599 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
600 final int spanX = cursor.getInt(SPANX_INDEX);
601 final int spanY = cursor.getInt(SPANY_INDEX);
602 final ComponentName provider = ComponentName.unflattenFromString(providerName);
603 Key key = null;
604 String backupKey = null;
605 if (provider != null) {
606 key = getKey(Key.WIDGET, providerName);
607 backupKey = keyToBackupKey(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400608 } else {
609 Log.w(TAG, "empty intent on appwidget: " + id);
610 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700611 if (mExistingKeys.contains(backupKey)) {
612 if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400613
614 // remember that we already backed this up previously
Sunny Goyalef728d42014-10-22 11:28:28 -0700615 mKeys.add(key);
Chris Wrenfd13c712013-09-27 15:45:19 -0400616 } else if (backupKey != null) {
Sunny Goyalef728d42014-10-22 11:28:28 -0700617 if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
618 if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
619 if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400620 previewLoader.setPreviewSize(spanX * profile.cellWidthPx,
621 spanY * profile.cellHeightPx, widgetSpacingLayout);
Sunny Goyalef728d42014-10-22 11:28:28 -0700622 writeRowToBackup(key, packWidget(dpi, previewLoader, mIconCache, provider), data);
623 mKeys.add(key);
624 backupWidgetCount ++;
Chris Wrenfd13c712013-09-27 15:45:19 -0400625 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700626 if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
Chris Wrenfd13c712013-09-27 15:45:19 -0400627 // too many widgets for this pass, request another.
Chris Wren92aa4232013-10-04 11:29:36 -0400628 dataChanged();
Chris Wrenfd13c712013-09-27 15:45:19 -0400629 }
630 }
631 }
632 } finally {
633 cursor.close();
634 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400635 }
636
637 /**
638 * Read a widget from the stream.
639 *
640 * <P>Keys arrive in any order, so widgets that use this data may already exist.
641 *
642 * @param key identifier for the row
643 * @param buffer the serialized proto from the stream, may be larger than dataSize
644 * @param dataSize the size of the proto from the stream
Chris Wrenfd13c712013-09-27 15:45:19 -0400645 */
Sunny Goyalef728d42014-10-22 11:28:28 -0700646 private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
Chris Wren50c8f422014-01-15 16:10:39 -0500647 if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
Chris Wrenfd13c712013-09-27 15:45:19 -0400648 if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
649 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
Sunny Goyalef728d42014-10-22 11:28:28 -0700650 Widget widget = unpackProto(new Widget(), buffer, dataSize);
651 if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
652 if (widget.icon.data != null) {
653 Bitmap icon = BitmapFactory
654 .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
655 if (icon == null) {
656 Log.w(TAG, "failed to unpack widget icon for " + key.name);
Chris Wren5dee7af2013-12-20 17:22:11 -0500657 } else {
Sunny Goyalef728d42014-10-22 11:28:28 -0700658 IconCache.preloadIcon(mContext, ComponentName.unflattenFromString(widget.provider),
659 icon, widget.icon.dpi);
Chris Wren5dee7af2013-12-20 17:22:11 -0500660 }
Chris Wrenfd13c712013-09-27 15:45:19 -0400661 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700662
663 // future site of widget table mutation
Chris Wrenfd13c712013-09-27 15:45:19 -0400664 }
665
Chris Wren22e130d2013-09-23 18:25:57 -0400666 /** create a new key, with an integer ID.
Chris Wren1ada10d2013-09-13 18:01:38 -0400667 *
668 * <P> Keys contain their own checksum instead of using
669 * the heavy-weight CheckedMessage wrapper.
670 */
671 private Key getKey(int type, long id) {
672 Key key = new Key();
673 key.type = type;
674 key.id = id;
675 key.checksum = checkKey(key);
676 return key;
677 }
678
Chris Wren22e130d2013-09-23 18:25:57 -0400679 /** create a new key for a named object.
680 *
681 * <P> Keys contain their own checksum instead of using
682 * the heavy-weight CheckedMessage wrapper.
683 */
684 private Key getKey(int type, String name) {
685 Key key = new Key();
686 key.type = type;
687 key.name = name;
688 key.checksum = checkKey(key);
689 return key;
690 }
691
Chris Wren1ada10d2013-09-13 18:01:38 -0400692 /** keys need to be strings, serialize and encode. */
693 private String keyToBackupKey(Key key) {
Chris Wren978194c2013-10-03 17:47:22 -0400694 return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
Chris Wren1ada10d2013-09-13 18:01:38 -0400695 }
696
697 /** keys need to be strings, decode and parse. */
698 private Key backupKeyToKey(String backupKey) throws KeyParsingException {
699 try {
700 Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
701 if (key.checksum != checkKey(key)) {
702 key = null;
703 throw new KeyParsingException("invalid key read from stream" + backupKey);
704 }
705 return key;
706 } catch (InvalidProtocolBufferNanoException e) {
707 throw new KeyParsingException(e);
708 } catch (IllegalArgumentException e) {
709 throw new KeyParsingException(e);
710 }
711 }
712
713 /** Compute the checksum over the important bits of a key. */
714 private long checkKey(Key key) {
715 CRC32 checksum = new CRC32();
716 checksum.update(key.type);
717 checksum.update((int) (key.id & 0xffff));
718 checksum.update((int) ((key.id >> 32) & 0xffff));
719 if (!TextUtils.isEmpty(key.name)) {
720 checksum.update(key.name.getBytes());
721 }
722 return checksum.getValue();
723 }
724
725 /** Serialize a Favorite for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700726 private Favorite packFavorite(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400727 Favorite favorite = new Favorite();
728 favorite.id = c.getLong(ID_INDEX);
729 favorite.screen = c.getInt(SCREEN_INDEX);
730 favorite.container = c.getInt(CONTAINER_INDEX);
731 favorite.cellX = c.getInt(CELLX_INDEX);
732 favorite.cellY = c.getInt(CELLY_INDEX);
733 favorite.spanX = c.getInt(SPANX_INDEX);
734 favorite.spanY = c.getInt(SPANY_INDEX);
735 favorite.iconType = c.getInt(ICON_TYPE_INDEX);
736 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
737 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
738 if (!TextUtils.isEmpty(iconPackage)) {
739 favorite.iconPackage = iconPackage;
740 }
741 String iconResource = c.getString(ICON_RESOURCE_INDEX);
742 if (!TextUtils.isEmpty(iconResource)) {
743 favorite.iconResource = iconResource;
744 }
745 }
746 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
747 byte[] blob = c.getBlob(ICON_INDEX);
748 if (blob != null && blob.length > 0) {
749 favorite.icon = blob;
750 }
751 }
752 String title = c.getString(TITLE_INDEX);
753 if (!TextUtils.isEmpty(title)) {
754 favorite.title = title;
755 }
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100756 String intentDescription = c.getString(INTENT_INDEX);
757 if (!TextUtils.isEmpty(intentDescription)) {
758 try {
759 Intent intent = Intent.parseUri(intentDescription, 0);
760 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
761 favorite.intent = intent.toUri(0);
762 } catch (URISyntaxException e) {
763 Log.e(TAG, "Invalid intent", e);
Sunny Goyalef728d42014-10-22 11:28:28 -0700764 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400765 }
766 favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
767 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
768 favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
769 String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
770 if (!TextUtils.isEmpty(appWidgetProvider)) {
771 favorite.appWidgetProvider = appWidgetProvider;
772 }
773 }
774
Sunny Goyalef728d42014-10-22 11:28:28 -0700775 return favorite;
Chris Wren1ada10d2013-09-13 18:01:38 -0400776 }
777
778 /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700779 private ContentValues unpackFavorite(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400780 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700781 Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500782 ContentValues values = new ContentValues();
783 values.put(Favorites._ID, favorite.id);
784 values.put(Favorites.SCREEN, favorite.screen);
785 values.put(Favorites.CONTAINER, favorite.container);
786 values.put(Favorites.CELLX, favorite.cellX);
787 values.put(Favorites.CELLY, favorite.cellY);
788 values.put(Favorites.SPANX, favorite.spanX);
789 values.put(Favorites.SPANY, favorite.spanY);
790 values.put(Favorites.ICON_TYPE, favorite.iconType);
791 if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
792 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
793 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
794 }
795 if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
796 values.put(Favorites.ICON, favorite.icon);
797 }
798 if (!TextUtils.isEmpty(favorite.title)) {
799 values.put(Favorites.TITLE, favorite.title);
800 } else {
801 values.put(Favorites.TITLE, "");
802 }
803 if (!TextUtils.isEmpty(favorite.intent)) {
804 values.put(Favorites.INTENT, favorite.intent);
805 }
806 values.put(Favorites.ITEM_TYPE, favorite.itemType);
Chris Wrenf4d08112014-01-16 18:13:56 -0500807
Kenny Guyf8b1dfd2014-05-13 12:59:34 +0100808 UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
809 long userSerialNumber =
810 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
811 values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
812
Sunny Goyalff572272014-07-23 13:58:07 -0700813 if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
814 if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
815 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
816 }
817 values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
818 values.put(LauncherSettings.Favorites.RESTORED,
819 LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
820 LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
821 LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
822 } else {
823 // Let LauncherModel know we've been here.
824 values.put(LauncherSettings.Favorites.RESTORED, 1);
825 }
Chris Wrenf4d08112014-01-16 18:13:56 -0500826
Chris Wren5dee7af2013-12-20 17:22:11 -0500827 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400828 }
829
830 /** Serialize a Screen for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700831 private Screen packScreen(Cursor c) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400832 Screen screen = new Screen();
833 screen.id = c.getLong(ID_INDEX);
834 screen.rank = c.getInt(SCREEN_RANK_INDEX);
Sunny Goyalef728d42014-10-22 11:28:28 -0700835 return screen;
Chris Wren1ada10d2013-09-13 18:01:38 -0400836 }
837
838 /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700839 private ContentValues unpackScreen(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -0400840 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700841 Screen screen = unpackProto(new Screen(), buffer, dataSize);
Chris Wren5dee7af2013-12-20 17:22:11 -0500842 ContentValues values = new ContentValues();
843 values.put(WorkspaceScreens._ID, screen.id);
844 values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
845 return values;
Chris Wren1ada10d2013-09-13 18:01:38 -0400846 }
847
Chris Wren22e130d2013-09-23 18:25:57 -0400848 /** Serialize an icon Resource for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700849 private Resource packIcon(int dpi, Bitmap icon) {
Chris Wren22e130d2013-09-23 18:25:57 -0400850 Resource res = new Resource();
851 res.dpi = dpi;
852 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400853 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wren22e130d2013-09-23 18:25:57 -0400854 res.data = os.toByteArray();
855 }
Chris Wren22e130d2013-09-23 18:25:57 -0400856 return res;
857 }
858
Chris Wrenfd13c712013-09-27 15:45:19 -0400859 /** Serialize a widget for persistence, including a checksum wrapper. */
Sunny Goyalef728d42014-10-22 11:28:28 -0700860 private Widget packWidget(int dpi, WidgetPreviewLoader previewLoader, IconCache iconCache,
Chris Wrenfd13c712013-09-27 15:45:19 -0400861 ComponentName provider) {
862 final AppWidgetProviderInfo info = findAppWidgetProviderInfo(provider);
863 Widget widget = new Widget();
864 widget.provider = provider.flattenToShortString();
865 widget.label = info.label;
866 widget.configure = info.configure != null;
867 if (info.icon != 0) {
868 widget.icon = new Resource();
869 Drawable fullResIcon = iconCache.getFullResIcon(provider.getPackageName(), info.icon);
Chris Wren92aa4232013-10-04 11:29:36 -0400870 Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
Chris Wrenfd13c712013-09-27 15:45:19 -0400871 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400872 if (icon.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400873 widget.icon.data = os.toByteArray();
874 widget.icon.dpi = dpi;
875 }
876 }
877 if (info.previewImage != 0) {
878 widget.preview = new Resource();
879 Bitmap preview = previewLoader.generateWidgetPreview(info, null);
880 ByteArrayOutputStream os = new ByteArrayOutputStream();
Chris Wrenb86f0762013-10-04 10:10:21 -0400881 if (preview.compress(IMAGE_FORMAT, IMAGE_COMPRESSION_QUALITY, os)) {
Chris Wrenfd13c712013-09-27 15:45:19 -0400882 widget.preview.data = os.toByteArray();
883 widget.preview.dpi = dpi;
884 }
885 }
Sunny Goyalef728d42014-10-22 11:28:28 -0700886 return widget;
Chris Wrenfd13c712013-09-27 15:45:19 -0400887 }
888
Sunny Goyalef728d42014-10-22 11:28:28 -0700889 /**
890 * Deserialize a proto after verifying checksum wrapper.
891 */
892 private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
Chris Wrenfd13c712013-09-27 15:45:19 -0400893 throws InvalidProtocolBufferNanoException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700894 MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
895 if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
896 return proto;
Chris Wrenfd13c712013-09-27 15:45:19 -0400897 }
898
Chris Wren1ada10d2013-09-13 18:01:38 -0400899 /**
900 * Read the old journal from the input file.
901 *
902 * In the event of any error, just pretend we didn't have a journal,
903 * in that case, do a full backup.
904 *
905 * @param oldState the read-0only file descriptor pointing to the old journal
Chris Wren65b6a602014-01-10 14:11:25 -0500906 * @return a Journal protocol buffer
Chris Wren1ada10d2013-09-13 18:01:38 -0400907 */
908 private Journal readJournal(ParcelFileDescriptor oldState) {
Chris Wren1ada10d2013-09-13 18:01:38 -0400909 Journal journal = new Journal();
Chris Wren92aa4232013-10-04 11:29:36 -0400910 if (oldState == null) {
911 return journal;
912 }
913 FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
914 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500915 int availableBytes = inStream.available();
916 if (DEBUG) Log.d(TAG, "available " + availableBytes);
917 if (availableBytes < MAX_JOURNAL_SIZE) {
918 byte[] buffer = new byte[availableBytes];
Chris Wren1ada10d2013-09-13 18:01:38 -0400919 int bytesRead = 0;
Chris Wren65b6a602014-01-10 14:11:25 -0500920 boolean valid = false;
Chris Wren50c8f422014-01-15 16:10:39 -0500921 InvalidProtocolBufferNanoException lastProtoException = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500922 while (availableBytes > 0) {
Chris Wren92aa4232013-10-04 11:29:36 -0400923 try {
Chris Wren65b6a602014-01-10 14:11:25 -0500924 // OMG what are you doing? This is crazy inefficient!
925 // If we read a byte that is not ours, we will cause trouble: b/12491813
926 // However, we don't know how many bytes to expect (oops).
927 // So we have to step through *slowly*, watching for the end.
928 int result = inStream.read(buffer, bytesRead, 1);
Chris Wren92aa4232013-10-04 11:29:36 -0400929 if (result > 0) {
Chris Wren65b6a602014-01-10 14:11:25 -0500930 availableBytes -= result;
Chris Wren92aa4232013-10-04 11:29:36 -0400931 bytesRead += result;
932 } else {
Chris Wren65b6a602014-01-10 14:11:25 -0500933 Log.w(TAG, "unexpected end of file while reading journal.");
934 // stop reading and see what there is to parse
935 availableBytes = 0;
Chris Wren92aa4232013-10-04 11:29:36 -0400936 }
937 } catch (IOException e) {
Chris Wren92aa4232013-10-04 11:29:36 -0400938 buffer = null;
Chris Wren65b6a602014-01-10 14:11:25 -0500939 availableBytes = 0;
940 }
941
942 // check the buffer to see if we have a valid journal
943 try {
Sunny Goyalef728d42014-10-22 11:28:28 -0700944 MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
Chris Wren65b6a602014-01-10 14:11:25 -0500945 // if we are here, then we have read a valid, checksum-verified journal
946 valid = true;
947 availableBytes = 0;
Chris Wren50c8f422014-01-15 16:10:39 -0500948 if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
Chris Wren65b6a602014-01-10 14:11:25 -0500949 } catch (InvalidProtocolBufferNanoException e) {
950 // if we don't have the whole journal yet, mergeFrom will throw. keep going.
Chris Wren50c8f422014-01-15 16:10:39 -0500951 lastProtoException = e;
Chris Wren65b6a602014-01-10 14:11:25 -0500952 journal.clear();
Chris Wren92aa4232013-10-04 11:29:36 -0400953 }
Chris Wren1ada10d2013-09-13 18:01:38 -0400954 }
Chris Wren92aa4232013-10-04 11:29:36 -0400955 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
Chris Wren65b6a602014-01-10 14:11:25 -0500956 if (!valid) {
Chris Wren50c8f422014-01-15 16:10:39 -0500957 Log.w(TAG, "could not find a valid journal", lastProtoException);
Chris Wren1ada10d2013-09-13 18:01:38 -0400958 }
959 }
Chris Wren92aa4232013-10-04 11:29:36 -0400960 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500961 Log.w(TAG, "failed to close the journal", e);
Chris Wren92aa4232013-10-04 11:29:36 -0400962 } finally {
Chris Wren1ada10d2013-09-13 18:01:38 -0400963 try {
964 inStream.close();
965 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -0500966 Log.w(TAG, "failed to close the journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -0400967 }
968 }
969 return journal;
970 }
971
Sunny Goyalef728d42014-10-22 11:28:28 -0700972 private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
973 throws IOException {
974 writeRowToBackup(keyToBackupKey(key), proto, data);
975 }
976
977 private void writeRowToBackup(String backupKey, MessageNano proto,
Chris Wren22e130d2013-09-23 18:25:57 -0400978 BackupDataOutput data) throws IOException {
Sunny Goyalef728d42014-10-22 11:28:28 -0700979 byte[] blob = writeCheckedBytes(proto);
Chris Wren22e130d2013-09-23 18:25:57 -0400980 data.writeEntityHeader(backupKey, blob.length);
981 data.writeEntityData(blob, blob.length);
Sunny Goyalef728d42014-10-22 11:28:28 -0700982 if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
Chris Wren22e130d2013-09-23 18:25:57 -0400983 }
984
Chris Wren1ada10d2013-09-13 18:01:38 -0400985 /**
986 * Write the new journal to the output file.
987 *
988 * In the event of any error, just pretend we didn't have a journal,
989 * in that case, do a full backup.
990
991 * @param newState the write-only file descriptor pointing to the new journal
992 * @param journal a Journal protocol buffer
993 */
994 private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
995 FileOutputStream outStream = null;
996 try {
997 outStream = new FileOutputStream(newState.getFileDescriptor());
Chris Wren65b6a602014-01-10 14:11:25 -0500998 final byte[] journalBytes = writeCheckedBytes(journal);
Chris Wren65b6a602014-01-10 14:11:25 -0500999 outStream.write(journalBytes);
Chris Wren1ada10d2013-09-13 18:01:38 -04001000 outStream.close();
Chris Wren50c8f422014-01-15 16:10:39 -05001001 if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
Chris Wren1ada10d2013-09-13 18:01:38 -04001002 } catch (IOException e) {
Chris Wren50c8f422014-01-15 16:10:39 -05001003 Log.w(TAG, "failed to write backup journal", e);
Chris Wren1ada10d2013-09-13 18:01:38 -04001004 }
1005 }
1006
1007 /** Wrap a proto in a CheckedMessage and compute the checksum. */
1008 private byte[] writeCheckedBytes(MessageNano proto) {
1009 CheckedMessage wrapper = new CheckedMessage();
1010 wrapper.payload = MessageNano.toByteArray(proto);
1011 CRC32 checksum = new CRC32();
1012 checksum.update(wrapper.payload);
1013 wrapper.checksum = checksum.getValue();
1014 return MessageNano.toByteArray(wrapper);
1015 }
1016
1017 /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
Sunny Goyalef728d42014-10-22 11:28:28 -07001018 private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
Chris Wren1ada10d2013-09-13 18:01:38 -04001019 throws InvalidProtocolBufferNanoException {
1020 CheckedMessage wrapper = new CheckedMessage();
Sunny Goyalef728d42014-10-22 11:28:28 -07001021 MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
Chris Wren1ada10d2013-09-13 18:01:38 -04001022 CRC32 checksum = new CRC32();
1023 checksum.update(wrapper.payload);
1024 if (wrapper.checksum != checksum.getValue()) {
1025 throw new InvalidProtocolBufferNanoException("checksum does not match");
1026 }
1027 return wrapper.payload;
1028 }
1029
Chris Wrenfd13c712013-09-27 15:45:19 -04001030 private AppWidgetProviderInfo findAppWidgetProviderInfo(ComponentName component) {
1031 if (mWidgetMap == null) {
1032 List<AppWidgetProviderInfo> widgets =
Chris Wren92aa4232013-10-04 11:29:36 -04001033 AppWidgetManager.getInstance(mContext).getInstalledProviders();
Chris Wrenfd13c712013-09-27 15:45:19 -04001034 mWidgetMap = new HashMap<ComponentName, AppWidgetProviderInfo>(widgets.size());
1035 for (AppWidgetProviderInfo info : widgets) {
1036 mWidgetMap.put(info.provider, info);
1037 }
1038 }
1039 return mWidgetMap.get(component);
1040 }
1041
Chris Wren6d0dde02014-02-10 12:16:54 -05001042
1043 private boolean initializeIconCache() {
1044 if (mIconCache != null) {
1045 return true;
1046 }
1047
1048 final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
1049 if (appState == null) {
1050 Throwable stackTrace = new Throwable();
1051 stackTrace.fillInStackTrace();
1052 Log.w(TAG, "Failed to get app state during backup/restore", stackTrace);
1053 return false;
1054 }
1055 mIconCache = appState.getIconCache();
1056 return mIconCache != null;
1057 }
1058
Chris Wren71144262014-02-27 15:49:39 -05001059
Sunny Goyalef728d42014-10-22 11:28:28 -07001060 /**
1061 * @return true if the launcher is in a state to support backup
1062 */
Chris Wren71144262014-02-27 15:49:39 -05001063 private boolean launcherIsReady() {
1064 ContentResolver cr = mContext.getContentResolver();
1065 Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
1066 if (cursor == null) {
1067 // launcher data has been wiped, do nothing
1068 return false;
1069 }
1070 cursor.close();
1071
1072 if (!initializeIconCache()) {
1073 // launcher services are unavailable, try again later
1074 dataChanged();
1075 return false;
1076 }
1077
1078 return true;
1079 }
1080
Sunny Goyalffe83f12014-08-14 17:39:34 -07001081 private String getUserSelectionArg() {
1082 return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
1083 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
1084 }
1085
Sunny Goyalef728d42014-10-22 11:28:28 -07001086 private class KeyParsingException extends IOException {
Chris Wren1ada10d2013-09-13 18:01:38 -04001087 private KeyParsingException(Throwable cause) {
1088 super(cause);
1089 }
1090
1091 public KeyParsingException(String reason) {
1092 super(reason);
1093 }
1094 }
1095}