Home | History | Annotate | Download | only in launcher3
      1 /*
      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  */
     16 package com.android.launcher3;
     17 
     18 import android.app.backup.BackupDataInputStream;
     19 import android.app.backup.BackupDataOutput;
     20 import android.app.backup.BackupHelper;
     21 import android.app.backup.BackupManager;
     22 import android.content.ComponentName;
     23 import android.content.ContentResolver;
     24 import android.content.ContentValues;
     25 import android.content.Context;
     26 import android.content.Intent;
     27 import android.content.pm.ActivityInfo;
     28 import android.content.pm.PackageManager;
     29 import android.content.pm.PackageManager.NameNotFoundException;
     30 import android.content.pm.ResolveInfo;
     31 import android.content.res.XmlResourceParser;
     32 import android.database.Cursor;
     33 import android.graphics.Bitmap;
     34 import android.graphics.BitmapFactory;
     35 import android.graphics.drawable.Drawable;
     36 import android.os.ParcelFileDescriptor;
     37 import android.text.TextUtils;
     38 import android.util.Base64;
     39 import android.util.Log;
     40 
     41 import com.android.launcher3.LauncherSettings.Favorites;
     42 import com.android.launcher3.LauncherSettings.WorkspaceScreens;
     43 import com.android.launcher3.backup.BackupProtos;
     44 import com.android.launcher3.backup.BackupProtos.CheckedMessage;
     45 import com.android.launcher3.backup.BackupProtos.DeviceProfieData;
     46 import com.android.launcher3.backup.BackupProtos.Favorite;
     47 import com.android.launcher3.backup.BackupProtos.Journal;
     48 import com.android.launcher3.backup.BackupProtos.Key;
     49 import com.android.launcher3.backup.BackupProtos.Resource;
     50 import com.android.launcher3.backup.BackupProtos.Screen;
     51 import com.android.launcher3.backup.BackupProtos.Widget;
     52 import com.android.launcher3.compat.UserHandleCompat;
     53 import com.android.launcher3.compat.UserManagerCompat;
     54 import com.android.launcher3.util.Thunk;
     55 import com.google.protobuf.nano.InvalidProtocolBufferNanoException;
     56 import com.google.protobuf.nano.MessageNano;
     57 
     58 import org.xmlpull.v1.XmlPullParser;
     59 import org.xmlpull.v1.XmlPullParserException;
     60 
     61 import java.io.FileInputStream;
     62 import java.io.FileOutputStream;
     63 import java.io.IOException;
     64 import java.net.URISyntaxException;
     65 import java.util.ArrayList;
     66 import java.util.Arrays;
     67 import java.util.HashSet;
     68 import java.util.zip.CRC32;
     69 
     70 /**
     71  * Persist the launcher home state across calamities.
     72  */
     73 public class LauncherBackupHelper implements BackupHelper {
     74     private static final String TAG = "LauncherBackupHelper";
     75     private static final boolean VERBOSE = LauncherBackupAgentHelper.VERBOSE;
     76     private static final boolean DEBUG = LauncherBackupAgentHelper.DEBUG;
     77 
     78     private static final int BACKUP_VERSION = 3;
     79     private static final int MAX_JOURNAL_SIZE = 1000000;
     80 
     81     // Journal key is such that it is always smaller than any dynamically generated
     82     // key (any Base64 encoded string).
     83     private static final String JOURNAL_KEY = "#";
     84 
     85     /** icons are large, dribble them out */
     86     private static final int MAX_ICONS_PER_PASS = 10;
     87 
     88     /** widgets contain previews, which are very large, dribble them out */
     89     private static final int MAX_WIDGETS_PER_PASS = 5;
     90 
     91     private static final String[] FAVORITE_PROJECTION = {
     92         Favorites._ID,                     // 0
     93         Favorites.MODIFIED,                // 1
     94         Favorites.INTENT,                  // 2
     95         Favorites.APPWIDGET_PROVIDER,      // 3
     96         Favorites.APPWIDGET_ID,            // 4
     97         Favorites.CELLX,                   // 5
     98         Favorites.CELLY,                   // 6
     99         Favorites.CONTAINER,               // 7
    100         Favorites.ICON,                    // 8
    101         Favorites.ICON_PACKAGE,            // 9
    102         Favorites.ICON_RESOURCE,           // 10
    103         Favorites.ICON_TYPE,               // 11
    104         Favorites.ITEM_TYPE,               // 12
    105         Favorites.SCREEN,                  // 13
    106         Favorites.SPANX,                   // 14
    107         Favorites.SPANY,                   // 15
    108         Favorites.TITLE,                   // 16
    109         Favorites.PROFILE_ID,              // 17
    110     };
    111 
    112     private static final int ID_INDEX = 0;
    113     private static final int ID_MODIFIED = 1;
    114     private static final int INTENT_INDEX = 2;
    115     private static final int APPWIDGET_PROVIDER_INDEX = 3;
    116     private static final int APPWIDGET_ID_INDEX = 4;
    117     private static final int CELLX_INDEX = 5;
    118     private static final int CELLY_INDEX = 6;
    119     private static final int CONTAINER_INDEX = 7;
    120     private static final int ICON_INDEX = 8;
    121     private static final int ICON_PACKAGE_INDEX = 9;
    122     private static final int ICON_RESOURCE_INDEX = 10;
    123     private static final int ICON_TYPE_INDEX = 11;
    124     private static final int ITEM_TYPE_INDEX = 12;
    125     private static final int SCREEN_INDEX = 13;
    126     private static final int SPANX_INDEX = 14;
    127     private static final int SPANY_INDEX = 15;
    128     private static final int TITLE_INDEX = 16;
    129 
    130     private static final String[] SCREEN_PROJECTION = {
    131         WorkspaceScreens._ID,              // 0
    132         WorkspaceScreens.MODIFIED,         // 1
    133         WorkspaceScreens.SCREEN_RANK       // 2
    134     };
    135 
    136     private static final int SCREEN_RANK_INDEX = 2;
    137 
    138     @Thunk final Context mContext;
    139     private final HashSet<String> mExistingKeys;
    140     private final ArrayList<Key> mKeys;
    141     private final ItemTypeMatcher[] mItemTypeMatchers;
    142     private final long mUserSerial;
    143 
    144     private BackupManager mBackupManager;
    145     private byte[] mBuffer = new byte[512];
    146     private long mLastBackupRestoreTime;
    147     private boolean mBackupDataWasUpdated;
    148 
    149     private IconCache mIconCache;
    150     private DeviceProfieData mDeviceProfileData;
    151     private InvariantDeviceProfile mIdp;
    152 
    153     boolean restoreSuccessful;
    154     int restoredBackupVersion = 1;
    155 
    156     public LauncherBackupHelper(Context context) {
    157         mContext = context;
    158         mExistingKeys = new HashSet<String>();
    159         mKeys = new ArrayList<Key>();
    160         restoreSuccessful = true;
    161         mItemTypeMatchers = new ItemTypeMatcher[CommonAppTypeParser.SUPPORTED_TYPE_COUNT];
    162 
    163         UserManagerCompat userManager = UserManagerCompat.getInstance(mContext);
    164         mUserSerial = userManager.getSerialNumberForUser(UserHandleCompat.myUserHandle());
    165     }
    166 
    167     private void dataChanged() {
    168         if (mBackupManager == null) {
    169             mBackupManager = new BackupManager(mContext);
    170         }
    171         mBackupManager.dataChanged();
    172     }
    173 
    174     private void applyJournal(Journal journal) {
    175         mLastBackupRestoreTime = journal.t;
    176         mExistingKeys.clear();
    177         if (journal.key != null) {
    178             for (Key key : journal.key) {
    179                 mExistingKeys.add(keyToBackupKey(key));
    180             }
    181         }
    182         restoredBackupVersion = journal.backupVersion;
    183     }
    184 
    185     /**
    186      * Back up launcher data so we can restore the user's state on a new device.
    187      *
    188      * <P>The journal is a timestamp and a list of keys that were saved as of that time.
    189      *
    190      * <P>Keys may come back in any order, so each key/value is one complete row of the database.
    191      *
    192      * @param oldState notes from the last backup
    193      * @param data incremental key/value pairs to persist off-device
    194      * @param newState notes for the next backup
    195      */
    196     @Override
    197     public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
    198             ParcelFileDescriptor newState) {
    199         if (VERBOSE) Log.v(TAG, "onBackup");
    200 
    201         Journal in = readJournal(oldState);
    202         if (!launcherIsReady()) {
    203             dataChanged();
    204             // Perform backup later.
    205             writeJournal(newState, in);
    206             return;
    207         }
    208 
    209         if (mDeviceProfileData == null) {
    210             LauncherAppState app = LauncherAppState.getInstance();
    211             mIdp = app.getInvariantDeviceProfile();
    212             mDeviceProfileData = initDeviceProfileData(mIdp);
    213             mIconCache = app.getIconCache();
    214         }
    215 
    216         Log.v(TAG, "lastBackupTime = " + in.t);
    217         mKeys.clear();
    218         applyJournal(in);
    219 
    220         // Record the time before performing backup so that entries edited while the backup
    221         // was going on, do not get missed in next backup.
    222         long newBackupTime = System.currentTimeMillis();
    223         mBackupDataWasUpdated = false;
    224         try {
    225             backupFavorites(data);
    226             backupScreens(data);
    227             backupIcons(data);
    228             backupWidgets(data);
    229 
    230             // Delete any key which still exist in the old backup, but is not valid anymore.
    231             HashSet<String> validKeys = new HashSet<String>();
    232             for (Key key : mKeys) {
    233                 validKeys.add(keyToBackupKey(key));
    234             }
    235             mExistingKeys.removeAll(validKeys);
    236 
    237             // Delete anything left in the existing keys.
    238             for (String deleted: mExistingKeys) {
    239                 if (VERBOSE) Log.v(TAG, "dropping deleted item " + deleted);
    240                 data.writeEntityHeader(deleted, -1);
    241                 mBackupDataWasUpdated = true;
    242             }
    243 
    244             mExistingKeys.clear();
    245             if (!mBackupDataWasUpdated) {
    246                 // Check if any metadata has changed
    247                 mBackupDataWasUpdated = (in.profile == null)
    248                         || !Arrays.equals(DeviceProfieData.toByteArray(in.profile),
    249                             DeviceProfieData.toByteArray(mDeviceProfileData))
    250                         || (in.backupVersion != BACKUP_VERSION)
    251                         || (in.appVersion != getAppVersion());
    252             }
    253 
    254             if (mBackupDataWasUpdated) {
    255                 mLastBackupRestoreTime = newBackupTime;
    256 
    257                 // We store the journal at two places.
    258                 //   1) Storing it in newState allows us to do partial backups by comparing old state
    259                 //   2) Storing it in backup data allows us to validate keys during restore
    260                 Journal state = getCurrentStateJournal();
    261                 writeRowToBackup(JOURNAL_KEY, state, data);
    262             } else {
    263                 if (DEBUG) Log.d(TAG, "Nothing was written during backup");
    264             }
    265         } catch (IOException e) {
    266             Log.e(TAG, "launcher backup has failed", e);
    267         }
    268 
    269         writeNewStateDescription(newState);
    270     }
    271 
    272     /**
    273      * @return true if the backup corresponding to oldstate can be successfully applied
    274      * to this device.
    275      */
    276     private boolean isBackupCompatible(Journal oldState) {
    277         DeviceProfieData currentProfile = mDeviceProfileData;
    278         DeviceProfieData oldProfile = oldState.profile;
    279 
    280         if (oldProfile == null || oldProfile.desktopCols == 0) {
    281             // Profile info is not valid, ignore the check.
    282             return true;
    283         }
    284 
    285         boolean isHotsetCompatible = false;
    286         if (currentProfile.allappsRank >= oldProfile.hotseatCount) {
    287             isHotsetCompatible = true;
    288         }
    289         if ((currentProfile.hotseatCount >= oldProfile.hotseatCount) &&
    290                 (currentProfile.allappsRank == oldProfile.allappsRank)) {
    291             isHotsetCompatible = true;
    292         }
    293 
    294         return isHotsetCompatible && (currentProfile.desktopCols >= oldProfile.desktopCols)
    295                 && (currentProfile.desktopRows >= oldProfile.desktopRows);
    296     }
    297 
    298     /**
    299      * Restore launcher configuration from the restored data stream.
    300      * It assumes that the keys will arrive in lexical order. So if the journal was present in the
    301      * backup, it should arrive first.
    302      *
    303      * @param data the key/value pair from the server
    304      */
    305     @Override
    306     public void restoreEntity(BackupDataInputStream data) {
    307         if (!restoreSuccessful) {
    308             return;
    309         }
    310 
    311         if (mDeviceProfileData == null) {
    312             // This call does not happen on a looper thread. So LauncherAppState
    313             // can't be created . Instead initialize required dependencies directly.
    314             mIdp = new InvariantDeviceProfile(mContext);
    315             mDeviceProfileData = initDeviceProfileData(mIdp);
    316             mIconCache = new IconCache(mContext, mIdp);
    317         }
    318 
    319         int dataSize = data.size();
    320         if (mBuffer.length < dataSize) {
    321             mBuffer = new byte[dataSize];
    322         }
    323         try {
    324             int bytesRead = data.read(mBuffer, 0, dataSize);
    325             if (DEBUG) Log.d(TAG, "read " + bytesRead + " of " + dataSize + " available");
    326             String backupKey = data.getKey();
    327 
    328             if (JOURNAL_KEY.equals(backupKey)) {
    329                 if (VERBOSE) Log.v(TAG, "Journal entry restored");
    330                 if (!mKeys.isEmpty()) {
    331                     // We received the journal key after a restore key.
    332                     Log.wtf(TAG, keyToBackupKey(mKeys.get(0)) + " received after " + JOURNAL_KEY);
    333                     restoreSuccessful = false;
    334                     return;
    335                 }
    336 
    337                 Journal journal = new Journal();
    338                 MessageNano.mergeFrom(journal, readCheckedBytes(mBuffer, dataSize));
    339                 applyJournal(journal);
    340                 restoreSuccessful = isBackupCompatible(journal);
    341                 return;
    342             }
    343 
    344             if (!mExistingKeys.isEmpty() && !mExistingKeys.contains(backupKey)) {
    345                 if (DEBUG) Log.e(TAG, "Ignoring key not present in the backup state " + backupKey);
    346                 return;
    347             }
    348             Key key = backupKeyToKey(backupKey);
    349             mKeys.add(key);
    350             switch (key.type) {
    351                 case Key.FAVORITE:
    352                     restoreFavorite(key, mBuffer, dataSize);
    353                     break;
    354 
    355                 case Key.SCREEN:
    356                     restoreScreen(key, mBuffer, dataSize);
    357                     break;
    358 
    359                 case Key.ICON:
    360                     restoreIcon(key, mBuffer, dataSize);
    361                     break;
    362 
    363                 case Key.WIDGET:
    364                     restoreWidget(key, mBuffer, dataSize);
    365                     break;
    366 
    367                 default:
    368                     Log.w(TAG, "unknown restore entity type: " + key.type);
    369                     mKeys.remove(key);
    370                     break;
    371             }
    372         } catch (IOException e) {
    373             Log.w(TAG, "ignoring unparsable backup entry", e);
    374         }
    375     }
    376 
    377     /**
    378      * Record the restore state for the next backup.
    379      *
    380      * @param newState notes about the backup state after restore.
    381      */
    382     @Override
    383     public void writeNewStateDescription(ParcelFileDescriptor newState) {
    384         writeJournal(newState, getCurrentStateJournal());
    385     }
    386 
    387     private Journal getCurrentStateJournal() {
    388         Journal journal = new Journal();
    389         journal.t = mLastBackupRestoreTime;
    390         journal.key = mKeys.toArray(new BackupProtos.Key[mKeys.size()]);
    391         journal.appVersion = getAppVersion();
    392         journal.backupVersion = BACKUP_VERSION;
    393         journal.profile = mDeviceProfileData;
    394         return journal;
    395     }
    396 
    397     private int getAppVersion() {
    398         try {
    399             return mContext.getPackageManager()
    400                     .getPackageInfo(mContext.getPackageName(), 0).versionCode;
    401         } catch (NameNotFoundException e) {
    402             return 0;
    403         }
    404     }
    405 
    406     private DeviceProfieData initDeviceProfileData(InvariantDeviceProfile profile) {
    407         DeviceProfieData data = new DeviceProfieData();
    408         data.desktopRows = profile.numRows;
    409         data.desktopCols = profile.numColumns;
    410         data.hotseatCount = profile.numHotseatIcons;
    411         data.allappsRank = profile.hotseatAllAppsRank;
    412         return data;
    413     }
    414 
    415     /**
    416      * Write all modified favorites to the data stream.
    417      *
    418      * @param data output stream for key/value pairs
    419      * @throws IOException
    420      */
    421     private void backupFavorites(BackupDataOutput data) throws IOException {
    422         // persist things that have changed since the last backup
    423         ContentResolver cr = mContext.getContentResolver();
    424         // Don't backup apps in other profiles for now.
    425         Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
    426                 getUserSelectionArg(), null, null);
    427         try {
    428             cursor.moveToPosition(-1);
    429             while(cursor.moveToNext()) {
    430                 final long id = cursor.getLong(ID_INDEX);
    431                 final long updateTime = cursor.getLong(ID_MODIFIED);
    432                 Key key = getKey(Key.FAVORITE, id);
    433                 mKeys.add(key);
    434                 final String backupKey = keyToBackupKey(key);
    435                 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
    436                     writeRowToBackup(key, packFavorite(cursor), data);
    437                 } else {
    438                     if (DEBUG) Log.d(TAG, "favorite already backup up: " + id);
    439                 }
    440             }
    441         } finally {
    442             cursor.close();
    443         }
    444     }
    445 
    446     /**
    447      * Read a favorite from the stream.
    448      *
    449      * <P>Keys arrive in any order, so screens and containers may not exist yet.
    450      *
    451      * @param key identifier for the row
    452      * @param buffer the serialized proto from the stream, may be larger than dataSize
    453      * @param dataSize the size of the proto from the stream
    454      */
    455     private void restoreFavorite(Key key, byte[] buffer, int dataSize) throws IOException {
    456         if (VERBOSE) Log.v(TAG, "unpacking favorite " + key.id);
    457         if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
    458                 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
    459 
    460         ContentResolver cr = mContext.getContentResolver();
    461         ContentValues values = unpackFavorite(buffer, dataSize);
    462         cr.insert(Favorites.CONTENT_URI, values);
    463     }
    464 
    465     /**
    466      * Write all modified screens to the data stream.
    467      *
    468      * @param data output stream for key/value pairs
    469      * @throws IOException
    470      */
    471     private void backupScreens(BackupDataOutput data) throws IOException {
    472         // persist things that have changed since the last backup
    473         ContentResolver cr = mContext.getContentResolver();
    474         Cursor cursor = cr.query(WorkspaceScreens.CONTENT_URI, SCREEN_PROJECTION,
    475                 null, null, null);
    476         try {
    477             cursor.moveToPosition(-1);
    478             if (DEBUG) Log.d(TAG, "dumping screens after: " + mLastBackupRestoreTime);
    479             while(cursor.moveToNext()) {
    480                 final long id = cursor.getLong(ID_INDEX);
    481                 final long updateTime = cursor.getLong(ID_MODIFIED);
    482                 Key key = getKey(Key.SCREEN, id);
    483                 mKeys.add(key);
    484                 final String backupKey = keyToBackupKey(key);
    485                 if (!mExistingKeys.contains(backupKey) || updateTime >= mLastBackupRestoreTime) {
    486                     writeRowToBackup(key, packScreen(cursor), data);
    487                 } else {
    488                     if (VERBOSE) Log.v(TAG, "screen already backup up " + id);
    489                 }
    490             }
    491         } finally {
    492             cursor.close();
    493         }
    494     }
    495 
    496     /**
    497      * Read a screen from the stream.
    498      *
    499      * <P>Keys arrive in any order, so children of this screen may already exist.
    500      *
    501      * @param key identifier for the row
    502      * @param buffer the serialized proto from the stream, may be larger than dataSize
    503      * @param dataSize the size of the proto from the stream
    504      */
    505     private void restoreScreen(Key key, byte[] buffer, int dataSize) throws IOException {
    506         if (VERBOSE) Log.v(TAG, "unpacking screen " + key.id);
    507         if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
    508                 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
    509 
    510         ContentResolver cr = mContext.getContentResolver();
    511         ContentValues values = unpackScreen(buffer, dataSize);
    512         cr.insert(WorkspaceScreens.CONTENT_URI, values);
    513     }
    514 
    515     /**
    516      * Write all the static icon resources we need to render placeholders
    517      * for a package that is not installed.
    518      *
    519      * @param data output stream for key/value pairs
    520      */
    521     private void backupIcons(BackupDataOutput data) throws IOException {
    522         // persist icons that haven't been persisted yet
    523         final ContentResolver cr = mContext.getContentResolver();
    524         final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
    525         final UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
    526         int backupUpIconCount = 0;
    527 
    528         // Don't backup apps in other profiles for now.
    529         String where = "(" + Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPLICATION + " OR " +
    530                 Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_SHORTCUT + ") AND " +
    531                 getUserSelectionArg();
    532         Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
    533                 where, null, null);
    534         try {
    535             cursor.moveToPosition(-1);
    536             while(cursor.moveToNext()) {
    537                 final long id = cursor.getLong(ID_INDEX);
    538                 final String intentDescription = cursor.getString(INTENT_INDEX);
    539                 try {
    540                     Intent intent = Intent.parseUri(intentDescription, 0);
    541                     ComponentName cn = intent.getComponent();
    542                     Key key = null;
    543                     String backupKey = null;
    544                     if (cn != null) {
    545                         key = getKey(Key.ICON, cn.flattenToShortString());
    546                         backupKey = keyToBackupKey(key);
    547                     } else {
    548                         Log.w(TAG, "empty intent on application favorite: " + id);
    549                     }
    550                     if (mExistingKeys.contains(backupKey)) {
    551                         if (DEBUG) Log.d(TAG, "already saved icon " + backupKey);
    552 
    553                         // remember that we already backed this up previously
    554                         mKeys.add(key);
    555                     } else if (backupKey != null) {
    556                         if (DEBUG) Log.d(TAG, "I can count this high: " + backupUpIconCount);
    557                         if (backupUpIconCount < MAX_ICONS_PER_PASS) {
    558                             if (DEBUG) Log.d(TAG, "saving icon " + backupKey);
    559                             Bitmap icon = mIconCache.getIcon(intent, myUserHandle);
    560                             if (icon != null && !mIconCache.isDefaultIcon(icon, myUserHandle)) {
    561                                 writeRowToBackup(key, packIcon(dpi, icon), data);
    562                                 mKeys.add(key);
    563                                 backupUpIconCount ++;
    564                             }
    565                         } else {
    566                             if (VERBOSE) Log.v(TAG, "deferring icon backup " + backupKey);
    567                             // too many icons for this pass, request another.
    568                             dataChanged();
    569                         }
    570                     }
    571                 } catch (URISyntaxException e) {
    572                     Log.e(TAG, "invalid URI on application favorite: " + id);
    573                 } catch (IOException e) {
    574                     Log.e(TAG, "unable to save application icon for favorite: " + id);
    575                 }
    576 
    577             }
    578         } finally {
    579             cursor.close();
    580         }
    581     }
    582 
    583     /**
    584      * Read an icon from the stream.
    585      *
    586      * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
    587      *
    588      * @param key identifier for the row
    589      * @param buffer the serialized proto from the stream, may be larger than dataSize
    590      * @param dataSize the size of the proto from the stream
    591      */
    592     private void restoreIcon(Key key, byte[] buffer, int dataSize) throws IOException {
    593         if (VERBOSE) Log.v(TAG, "unpacking icon " + key.id);
    594         if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
    595                 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
    596 
    597         Resource res = unpackProto(new Resource(), buffer, dataSize);
    598         if (DEBUG) {
    599             Log.d(TAG, "unpacked " + res.dpi + " dpi icon");
    600         }
    601         Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
    602         if (icon == null) {
    603             Log.w(TAG, "failed to unpack icon for " + key.name);
    604         }
    605         if (VERBOSE) Log.v(TAG, "saving restored icon as: " + key.name);
    606         mIconCache.preloadIcon(ComponentName.unflattenFromString(key.name), icon, res.dpi,
    607                 "" /* label */, mUserSerial);
    608     }
    609 
    610     /**
    611      * Write all the static widget resources we need to render placeholders
    612      * for a package that is not installed.
    613      *
    614      * @param data output stream for key/value pairs
    615      * @throws IOException
    616      */
    617     private void backupWidgets(BackupDataOutput data) throws IOException {
    618         // persist static widget info that hasn't been persisted yet
    619         final ContentResolver cr = mContext.getContentResolver();
    620         final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
    621         int backupWidgetCount = 0;
    622 
    623         String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET + " AND "
    624                 + getUserSelectionArg();
    625         Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION,
    626                 where, null, null);
    627         try {
    628             cursor.moveToPosition(-1);
    629             while(cursor.moveToNext()) {
    630                 final long id = cursor.getLong(ID_INDEX);
    631                 final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
    632                 final ComponentName provider = ComponentName.unflattenFromString(providerName);
    633                 Key key = null;
    634                 String backupKey = null;
    635                 if (provider != null) {
    636                     key = getKey(Key.WIDGET, providerName);
    637                     backupKey = keyToBackupKey(key);
    638                 } else {
    639                     Log.w(TAG, "empty intent on appwidget: " + id);
    640                 }
    641                 if (mExistingKeys.contains(backupKey) && restoredBackupVersion >= BACKUP_VERSION) {
    642                     if (DEBUG) Log.d(TAG, "already saved widget " + backupKey);
    643 
    644                     // remember that we already backed this up previously
    645                     mKeys.add(key);
    646                 } else if (backupKey != null) {
    647                     if (DEBUG) Log.d(TAG, "I can count this high: " + backupWidgetCount);
    648                     if (backupWidgetCount < MAX_WIDGETS_PER_PASS) {
    649                         if (DEBUG) Log.d(TAG, "saving widget " + backupKey);
    650                         UserHandleCompat user = UserHandleCompat.myUserHandle();
    651                         writeRowToBackup(key, packWidget(dpi, provider, user), data);
    652                         mKeys.add(key);
    653                         backupWidgetCount ++;
    654                     } else {
    655                         if (VERBOSE) Log.v(TAG, "deferring widget backup " + backupKey);
    656                         // too many widgets for this pass, request another.
    657                         dataChanged();
    658                     }
    659                 }
    660             }
    661         } finally {
    662             cursor.close();
    663         }
    664     }
    665 
    666     /**
    667      * Read a widget from the stream.
    668      *
    669      * <P>Keys arrive in any order, so widgets that use this data may already exist.
    670      *
    671      * @param key identifier for the row
    672      * @param buffer the serialized proto from the stream, may be larger than dataSize
    673      * @param dataSize the size of the proto from the stream
    674      */
    675     private void restoreWidget(Key key, byte[] buffer, int dataSize) throws IOException {
    676         if (VERBOSE) Log.v(TAG, "unpacking widget " + key.id);
    677         if (DEBUG) Log.d(TAG, "read (" + buffer.length + "): " +
    678                 Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
    679         Widget widget = unpackProto(new Widget(), buffer, dataSize);
    680         if (DEBUG) Log.d(TAG, "unpacked " + widget.provider);
    681         if (widget.icon.data != null)  {
    682             Bitmap icon = BitmapFactory
    683                     .decodeByteArray(widget.icon.data, 0, widget.icon.data.length);
    684             if (icon == null) {
    685                 Log.w(TAG, "failed to unpack widget icon for " + key.name);
    686             } else {
    687                 mIconCache.preloadIcon(ComponentName.unflattenFromString(widget.provider),
    688                         icon, widget.icon.dpi, widget.label, mUserSerial);
    689             }
    690         }
    691 
    692         // future site of widget table mutation
    693     }
    694 
    695     /** create a new key, with an integer ID.
    696      *
    697      * <P> Keys contain their own checksum instead of using
    698      * the heavy-weight CheckedMessage wrapper.
    699      */
    700     private Key getKey(int type, long id) {
    701         Key key = new Key();
    702         key.type = type;
    703         key.id = id;
    704         key.checksum = checkKey(key);
    705         return key;
    706     }
    707 
    708     /** create a new key for a named object.
    709      *
    710      * <P> Keys contain their own checksum instead of using
    711      * the heavy-weight CheckedMessage wrapper.
    712      */
    713     private Key getKey(int type, String name) {
    714         Key key = new Key();
    715         key.type = type;
    716         key.name = name;
    717         key.checksum = checkKey(key);
    718         return key;
    719     }
    720 
    721     /** keys need to be strings, serialize and encode. */
    722     private String keyToBackupKey(Key key) {
    723         return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP);
    724     }
    725 
    726     /** keys need to be strings, decode and parse. */
    727     private Key backupKeyToKey(String backupKey) throws InvalidBackupException {
    728         try {
    729             Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
    730             if (key.checksum != checkKey(key)) {
    731                 key = null;
    732                 throw new InvalidBackupException("invalid key read from stream" + backupKey);
    733             }
    734             return key;
    735         } catch (InvalidProtocolBufferNanoException e) {
    736             throw new InvalidBackupException(e);
    737         } catch (IllegalArgumentException e) {
    738             throw new InvalidBackupException(e);
    739         }
    740     }
    741 
    742     /** Compute the checksum over the important bits of a key. */
    743     private long checkKey(Key key) {
    744         CRC32 checksum = new CRC32();
    745         checksum.update(key.type);
    746         checksum.update((int) (key.id & 0xffff));
    747         checksum.update((int) ((key.id >> 32) & 0xffff));
    748         if (!TextUtils.isEmpty(key.name)) {
    749             checksum.update(key.name.getBytes());
    750         }
    751         return checksum.getValue();
    752     }
    753 
    754     /**
    755      * @return true if its an hotseat item, that can be replaced during restore.
    756      * TODO: Extend check for folders in hotseat.
    757      */
    758     private boolean isReplaceableHotseatItem(Favorite favorite) {
    759         return favorite.container == Favorites.CONTAINER_HOTSEAT
    760                 && favorite.intent != null
    761                 && (favorite.itemType == Favorites.ITEM_TYPE_APPLICATION
    762                 || favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT);
    763     }
    764 
    765     /** Serialize a Favorite for persistence, including a checksum wrapper. */
    766     private Favorite packFavorite(Cursor c) {
    767         Favorite favorite = new Favorite();
    768         favorite.id = c.getLong(ID_INDEX);
    769         favorite.screen = c.getInt(SCREEN_INDEX);
    770         favorite.container = c.getInt(CONTAINER_INDEX);
    771         favorite.cellX = c.getInt(CELLX_INDEX);
    772         favorite.cellY = c.getInt(CELLY_INDEX);
    773         favorite.spanX = c.getInt(SPANX_INDEX);
    774         favorite.spanY = c.getInt(SPANY_INDEX);
    775         favorite.iconType = c.getInt(ICON_TYPE_INDEX);
    776 
    777         String title = c.getString(TITLE_INDEX);
    778         if (!TextUtils.isEmpty(title)) {
    779             favorite.title = title;
    780         }
    781         String intentDescription = c.getString(INTENT_INDEX);
    782         Intent intent = null;
    783         if (!TextUtils.isEmpty(intentDescription)) {
    784             try {
    785                 intent = Intent.parseUri(intentDescription, 0);
    786                 intent.removeExtra(ItemInfo.EXTRA_PROFILE);
    787                 favorite.intent = intent.toUri(0);
    788             } catch (URISyntaxException e) {
    789                 Log.e(TAG, "Invalid intent", e);
    790             }
    791         }
    792         favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
    793         if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
    794             favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
    795             String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
    796             if (!TextUtils.isEmpty(appWidgetProvider)) {
    797                 favorite.appWidgetProvider = appWidgetProvider;
    798             }
    799         } else if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
    800             if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
    801                 String iconPackage = c.getString(ICON_PACKAGE_INDEX);
    802                 if (!TextUtils.isEmpty(iconPackage)) {
    803                     favorite.iconPackage = iconPackage;
    804                 }
    805                 String iconResource = c.getString(ICON_RESOURCE_INDEX);
    806                 if (!TextUtils.isEmpty(iconResource)) {
    807                     favorite.iconResource = iconResource;
    808                 }
    809             }
    810 
    811             byte[] blob = c.getBlob(ICON_INDEX);
    812             if (blob != null && blob.length > 0) {
    813                 favorite.icon = blob;
    814             }
    815         }
    816 
    817         if (isReplaceableHotseatItem(favorite)) {
    818             if (intent != null && intent.getComponent() != null) {
    819                 PackageManager pm = mContext.getPackageManager();
    820                 ActivityInfo activity = null;;
    821                 try {
    822                     activity = pm.getActivityInfo(intent.getComponent(), 0);
    823                 } catch (NameNotFoundException e) {
    824                     Log.e(TAG, "Target not found", e);
    825                 }
    826                 if (activity == null) {
    827                     return favorite;
    828                 }
    829                 for (int i = 0; i < mItemTypeMatchers.length; i++) {
    830                     if (mItemTypeMatchers[i] == null) {
    831                         mItemTypeMatchers[i] = new ItemTypeMatcher(
    832                                 CommonAppTypeParser.getResourceForItemType(i));
    833                     }
    834                     if (mItemTypeMatchers[i].matches(activity, pm)) {
    835                         favorite.targetType = i;
    836                         break;
    837                     }
    838                 }
    839             }
    840         }
    841 
    842         return favorite;
    843     }
    844 
    845     /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
    846     private ContentValues unpackFavorite(byte[] buffer, int dataSize)
    847             throws IOException {
    848         Favorite favorite = unpackProto(new Favorite(), buffer, dataSize);
    849 
    850         ContentValues values = new ContentValues();
    851         values.put(Favorites._ID, favorite.id);
    852         values.put(Favorites.SCREEN, favorite.screen);
    853         values.put(Favorites.CONTAINER, favorite.container);
    854         values.put(Favorites.CELLX, favorite.cellX);
    855         values.put(Favorites.CELLY, favorite.cellY);
    856         values.put(Favorites.SPANX, favorite.spanX);
    857         values.put(Favorites.SPANY, favorite.spanY);
    858 
    859         if (favorite.itemType == Favorites.ITEM_TYPE_SHORTCUT) {
    860             values.put(Favorites.ICON_TYPE, favorite.iconType);
    861             if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
    862                 values.put(Favorites.ICON_PACKAGE, favorite.iconPackage);
    863                 values.put(Favorites.ICON_RESOURCE, favorite.iconResource);
    864             }
    865             values.put(Favorites.ICON, favorite.icon);
    866         }
    867 
    868         if (!TextUtils.isEmpty(favorite.title)) {
    869             values.put(Favorites.TITLE, favorite.title);
    870         } else {
    871             values.put(Favorites.TITLE, "");
    872         }
    873         if (!TextUtils.isEmpty(favorite.intent)) {
    874             values.put(Favorites.INTENT, favorite.intent);
    875         }
    876         values.put(Favorites.ITEM_TYPE, favorite.itemType);
    877 
    878         UserHandleCompat myUserHandle = UserHandleCompat.myUserHandle();
    879         long userSerialNumber =
    880                 UserManagerCompat.getInstance(mContext).getSerialNumberForUser(myUserHandle);
    881         values.put(LauncherSettings.Favorites.PROFILE_ID, userSerialNumber);
    882 
    883         DeviceProfieData currentProfile = mDeviceProfileData;
    884 
    885         if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
    886             if (!TextUtils.isEmpty(favorite.appWidgetProvider)) {
    887                 values.put(Favorites.APPWIDGET_PROVIDER, favorite.appWidgetProvider);
    888             }
    889             values.put(Favorites.APPWIDGET_ID, favorite.appWidgetId);
    890             values.put(LauncherSettings.Favorites.RESTORED,
    891                     LauncherAppWidgetInfo.FLAG_ID_NOT_VALID |
    892                     LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY |
    893                     LauncherAppWidgetInfo.FLAG_UI_NOT_READY);
    894 
    895             // Verify placement
    896             if (((favorite.cellX + favorite.spanX) > currentProfile.desktopCols)
    897                     || ((favorite.cellY + favorite.spanY) > currentProfile.desktopRows)) {
    898                 restoreSuccessful = false;
    899                 throw new InvalidBackupException("Widget not in screen bounds, aborting restore");
    900             }
    901         } else {
    902             // Check if it is an hotseat item, that can be replaced.
    903             if (isReplaceableHotseatItem(favorite)
    904                     && favorite.targetType != Favorite.TARGET_NONE
    905                     && favorite.targetType < CommonAppTypeParser.SUPPORTED_TYPE_COUNT) {
    906                 Log.e(TAG, "Added item type flag");
    907                 values.put(LauncherSettings.Favorites.RESTORED,
    908                         1 | CommonAppTypeParser.encodeItemTypeToFlag(favorite.targetType));
    909             } else {
    910                 // Let LauncherModel know we've been here.
    911                 values.put(LauncherSettings.Favorites.RESTORED, 1);
    912             }
    913 
    914             // Verify placement
    915             if (favorite.container == Favorites.CONTAINER_HOTSEAT) {
    916                 if ((favorite.screen >= currentProfile.hotseatCount)
    917                         || (favorite.screen == currentProfile.allappsRank)) {
    918                     restoreSuccessful = false;
    919                     throw new InvalidBackupException("Item not in hotseat bounds, aborting restore");
    920                 }
    921             } else {
    922                 if ((favorite.cellX >= currentProfile.desktopCols)
    923                         || (favorite.cellY >= currentProfile.desktopRows)) {
    924                     restoreSuccessful = false;
    925                     throw new InvalidBackupException("Item not in desktop bounds, aborting restore");
    926                 }
    927             }
    928         }
    929 
    930         return values;
    931     }
    932 
    933     /** Serialize a Screen for persistence, including a checksum wrapper. */
    934     private Screen packScreen(Cursor c) {
    935         Screen screen = new Screen();
    936         screen.id = c.getLong(ID_INDEX);
    937         screen.rank = c.getInt(SCREEN_RANK_INDEX);
    938         return screen;
    939     }
    940 
    941     /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
    942     private ContentValues unpackScreen(byte[] buffer, int dataSize)
    943             throws InvalidProtocolBufferNanoException {
    944         Screen screen = unpackProto(new Screen(), buffer, dataSize);
    945         ContentValues values = new ContentValues();
    946         values.put(WorkspaceScreens._ID, screen.id);
    947         values.put(WorkspaceScreens.SCREEN_RANK, screen.rank);
    948         return values;
    949     }
    950 
    951     /** Serialize an icon Resource for persistence, including a checksum wrapper. */
    952     private Resource packIcon(int dpi, Bitmap icon) {
    953         Resource res = new Resource();
    954         res.dpi = dpi;
    955         res.data = Utilities.flattenBitmap(icon);
    956         return res;
    957     }
    958 
    959     /** Serialize a widget for persistence, including a checksum wrapper. */
    960     private Widget packWidget(int dpi, ComponentName provider, UserHandleCompat user) {
    961         final LauncherAppWidgetProviderInfo info =
    962                 LauncherModel.getProviderInfo(mContext, provider, user);
    963         Widget widget = new Widget();
    964         widget.provider = provider.flattenToShortString();
    965         widget.label = info.label;
    966         widget.configure = info.configure != null;
    967         if (info.icon != 0) {
    968             widget.icon = new Resource();
    969             Drawable fullResIcon = mIconCache.getFullResIcon(provider.getPackageName(), info.icon);
    970             Bitmap icon = Utilities.createIconBitmap(fullResIcon, mContext);
    971             widget.icon.data = Utilities.flattenBitmap(icon);
    972             widget.icon.dpi = dpi;
    973         }
    974 
    975         // Calculate the spans corresponding to any one of the orientations as it should not change
    976         // based on orientation.
    977         int[] minSpans = CellLayout.rectToCell(
    978                 mIdp.portraitProfile, mContext, info.minResizeWidth, info.minResizeHeight, null);
    979         widget.minSpanX = (info.resizeMode & LauncherAppWidgetProviderInfo.RESIZE_HORIZONTAL) != 0
    980                 ? minSpans[0] : -1;
    981         widget.minSpanY = (info.resizeMode & LauncherAppWidgetProviderInfo.RESIZE_VERTICAL) != 0
    982                 ? minSpans[1] : -1;
    983 
    984         return widget;
    985     }
    986 
    987     /**
    988      * Deserialize a proto after verifying checksum wrapper.
    989      */
    990     private <T extends MessageNano> T unpackProto(T proto, byte[] buffer, int dataSize)
    991             throws InvalidProtocolBufferNanoException {
    992         MessageNano.mergeFrom(proto, readCheckedBytes(buffer, dataSize));
    993         if (DEBUG) Log.d(TAG, "unpacked proto " + proto);
    994         return proto;
    995     }
    996 
    997     /**
    998      * Read the old journal from the input file.
    999      *
   1000      * In the event of any error, just pretend we didn't have a journal,
   1001      * in that case, do a full backup.
   1002      *
   1003      * @param oldState the read-0only file descriptor pointing to the old journal
   1004      * @return a Journal protocol buffer
   1005      */
   1006     private Journal readJournal(ParcelFileDescriptor oldState) {
   1007         Journal journal = new Journal();
   1008         if (oldState == null) {
   1009             return journal;
   1010         }
   1011         FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
   1012         try {
   1013             int availableBytes = inStream.available();
   1014             if (DEBUG) Log.d(TAG, "available " + availableBytes);
   1015             if (availableBytes < MAX_JOURNAL_SIZE) {
   1016                 byte[] buffer = new byte[availableBytes];
   1017                 int bytesRead = 0;
   1018                 boolean valid = false;
   1019                 InvalidProtocolBufferNanoException lastProtoException = null;
   1020                 while (availableBytes > 0) {
   1021                     try {
   1022                         // OMG what are you doing? This is crazy inefficient!
   1023                         // If we read a byte that is not ours, we will cause trouble: b/12491813
   1024                         // However, we don't know how many bytes to expect (oops).
   1025                         // So we have to step through *slowly*, watching for the end.
   1026                         int result = inStream.read(buffer, bytesRead, 1);
   1027                         if (result > 0) {
   1028                             availableBytes -= result;
   1029                             bytesRead += result;
   1030                         } else {
   1031                             Log.w(TAG, "unexpected end of file while reading journal.");
   1032                             // stop reading and see what there is to parse
   1033                             availableBytes = 0;
   1034                         }
   1035                     } catch (IOException e) {
   1036                         buffer = null;
   1037                         availableBytes = 0;
   1038                     }
   1039 
   1040                     // check the buffer to see if we have a valid journal
   1041                     try {
   1042                         MessageNano.mergeFrom(journal, readCheckedBytes(buffer, bytesRead));
   1043                         // if we are here, then we have read a valid, checksum-verified journal
   1044                         valid = true;
   1045                         availableBytes = 0;
   1046                         if (VERBOSE) Log.v(TAG, "read " + bytesRead + " bytes of journal");
   1047                     } catch (InvalidProtocolBufferNanoException e) {
   1048                         // if we don't have the whole journal yet, mergeFrom will throw. keep going.
   1049                         lastProtoException = e;
   1050                         journal.clear();
   1051                     }
   1052                 }
   1053                 if (DEBUG) Log.d(TAG, "journal bytes read: " + bytesRead);
   1054                 if (!valid) {
   1055                     Log.w(TAG, "could not find a valid journal", lastProtoException);
   1056                 }
   1057             }
   1058         } catch (IOException e) {
   1059             Log.w(TAG, "failed to close the journal", e);
   1060         } finally {
   1061             try {
   1062                 inStream.close();
   1063             } catch (IOException e) {
   1064                 Log.w(TAG, "failed to close the journal", e);
   1065             }
   1066         }
   1067         return journal;
   1068     }
   1069 
   1070     private void writeRowToBackup(Key key, MessageNano proto, BackupDataOutput data)
   1071             throws IOException {
   1072         writeRowToBackup(keyToBackupKey(key), proto, data);
   1073     }
   1074 
   1075     private void writeRowToBackup(String backupKey, MessageNano proto,
   1076             BackupDataOutput data) throws IOException {
   1077         byte[] blob = writeCheckedBytes(proto);
   1078         data.writeEntityHeader(backupKey, blob.length);
   1079         data.writeEntityData(blob, blob.length);
   1080         mBackupDataWasUpdated = true;
   1081         if (VERBOSE) Log.v(TAG, "Writing New entry " + backupKey);
   1082     }
   1083 
   1084     /**
   1085      * Write the new journal to the output file.
   1086      *
   1087      * In the event of any error, just pretend we didn't have a journal,
   1088      * in that case, do a full backup.
   1089 
   1090      * @param newState the write-only file descriptor pointing to the new journal
   1091      * @param journal a Journal protocol buffer
   1092      */
   1093     private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
   1094         FileOutputStream outStream = null;
   1095         try {
   1096             outStream = new FileOutputStream(newState.getFileDescriptor());
   1097             final byte[] journalBytes = writeCheckedBytes(journal);
   1098             outStream.write(journalBytes);
   1099             outStream.close();
   1100             if (VERBOSE) Log.v(TAG, "wrote " + journalBytes.length + " bytes of journal");
   1101         } catch (IOException e) {
   1102             Log.w(TAG, "failed to write backup journal", e);
   1103         }
   1104     }
   1105 
   1106     /** Wrap a proto in a CheckedMessage and compute the checksum. */
   1107     private byte[] writeCheckedBytes(MessageNano proto) {
   1108         CheckedMessage wrapper = new CheckedMessage();
   1109         wrapper.payload = MessageNano.toByteArray(proto);
   1110         CRC32 checksum = new CRC32();
   1111         checksum.update(wrapper.payload);
   1112         wrapper.checksum = checksum.getValue();
   1113         return MessageNano.toByteArray(wrapper);
   1114     }
   1115 
   1116     /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
   1117     private static byte[] readCheckedBytes(byte[] buffer, int dataSize)
   1118             throws InvalidProtocolBufferNanoException {
   1119         CheckedMessage wrapper = new CheckedMessage();
   1120         MessageNano.mergeFrom(wrapper, buffer, 0, dataSize);
   1121         CRC32 checksum = new CRC32();
   1122         checksum.update(wrapper.payload);
   1123         if (wrapper.checksum != checksum.getValue()) {
   1124             throw new InvalidProtocolBufferNanoException("checksum does not match");
   1125         }
   1126         return wrapper.payload;
   1127     }
   1128 
   1129     /**
   1130      * @return true if the launcher is in a state to support backup
   1131      */
   1132     private boolean launcherIsReady() {
   1133         ContentResolver cr = mContext.getContentResolver();
   1134         Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
   1135         if (cursor == null) {
   1136             // launcher data has been wiped, do nothing
   1137             return false;
   1138         }
   1139         cursor.close();
   1140 
   1141         if (LauncherAppState.getInstanceNoCreate() == null) {
   1142             // launcher services are unavailable, try again later
   1143             return false;
   1144         }
   1145 
   1146         return true;
   1147     }
   1148 
   1149     private String getUserSelectionArg() {
   1150         return Favorites.PROFILE_ID + '=' + UserManagerCompat.getInstance(mContext)
   1151                 .getSerialNumberForUser(UserHandleCompat.myUserHandle());
   1152     }
   1153 
   1154     @Thunk class InvalidBackupException extends IOException {
   1155 
   1156         private static final long serialVersionUID = 8931456637211665082L;
   1157 
   1158         @Thunk InvalidBackupException(Throwable cause) {
   1159             super(cause);
   1160         }
   1161 
   1162         @Thunk InvalidBackupException(String reason) {
   1163             super(reason);
   1164         }
   1165     }
   1166 
   1167     /**
   1168      * A class to check if an activity can handle one of the intents from a list of
   1169      * predefined intents.
   1170      */
   1171     private class ItemTypeMatcher {
   1172 
   1173         private final ArrayList<Intent> mIntents;
   1174 
   1175         ItemTypeMatcher(int xml_res) {
   1176             mIntents = xml_res == 0 ? new ArrayList<Intent>() : parseIntents(xml_res);
   1177         }
   1178 
   1179         private ArrayList<Intent> parseIntents(int xml_res) {
   1180             ArrayList<Intent> intents = new ArrayList<Intent>();
   1181             XmlResourceParser parser = mContext.getResources().getXml(xml_res);
   1182             try {
   1183                 DefaultLayoutParser.beginDocument(parser, DefaultLayoutParser.TAG_RESOLVE);
   1184                 final int depth = parser.getDepth();
   1185                 int type;
   1186                 while (((type = parser.next()) != XmlPullParser.END_TAG ||
   1187                         parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
   1188                     if (type != XmlPullParser.START_TAG) {
   1189                         continue;
   1190                     } else if (DefaultLayoutParser.TAG_FAVORITE.equals(parser.getName())) {
   1191                         final String uri = DefaultLayoutParser.getAttributeValue(
   1192                                 parser, DefaultLayoutParser.ATTR_URI);
   1193                         intents.add(Intent.parseUri(uri, 0));
   1194                     }
   1195                 }
   1196             } catch (URISyntaxException | XmlPullParserException | IOException e) {
   1197                 Log.e(TAG, "Unable to parse " + xml_res, e);
   1198             } finally {
   1199                 parser.close();
   1200             }
   1201             return intents;
   1202         }
   1203 
   1204         public boolean matches(ActivityInfo activity, PackageManager pm) {
   1205             for (Intent intent : mIntents) {
   1206                 intent.setPackage(activity.packageName);
   1207                 ResolveInfo info = pm.resolveActivity(intent, 0);
   1208                 if (info != null && (info.activityInfo.name.equals(activity.name)
   1209                         || info.activityInfo.name.equals(activity.targetActivity))) {
   1210                     return true;
   1211                 }
   1212             }
   1213             return false;
   1214         }
   1215     }
   1216 }
   1217