Search in sources :

Example 1 with Key

use of com.android.launcher3.backup.BackupProtos.Key in project Launcher3 by chislon.

the class LauncherBackupHelper method backupWidgets.

/**
     * Write all the static widget resources we need to render placeholders
     * for a package that is not installed.
     *
     * @param in notes from last backup
     * @param data output stream for key/value pairs
     * @param out notes about this backup
     * @param keys keys to mark as clean in the notes for next backup
     * @throws IOException
     */
private void backupWidgets(Journal in, BackupDataOutput data, Journal out, ArrayList<Key> keys) throws IOException {
    // persist static widget info that hasn't been persisted yet
    final LauncherAppState appState = LauncherAppState.getInstanceNoCreate();
    if (appState == null) {
        // try again later
        dataChanged();
        if (DEBUG)
            Log.d(TAG, "Launcher is not initialized, delaying widget backup");
        return;
    }
    final ContentResolver cr = mContext.getContentResolver();
    final WidgetPreviewLoader previewLoader = new WidgetPreviewLoader(mContext);
    final PagedViewCellLayout widgetSpacingLayout = new PagedViewCellLayout(mContext);
    final IconCache iconCache = appState.getIconCache();
    final int dpi = mContext.getResources().getDisplayMetrics().densityDpi;
    final DeviceProfile profile = appState.getDynamicGrid().getDeviceProfile();
    if (DEBUG)
        Log.d(TAG, "cellWidthPx: " + profile.cellWidthPx);
    // read the old ID set
    Set<String> savedIds = getSavedIdsByType(Key.WIDGET, in);
    if (DEBUG)
        Log.d(TAG, "widgets savedIds.size()=" + savedIds.size());
    int startRows = out.rows;
    if (DEBUG)
        Log.d(TAG, "starting here: " + startRows);
    String where = Favorites.ITEM_TYPE + "=" + Favorites.ITEM_TYPE_APPWIDGET;
    Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, where, null, null);
    Set<String> currentIds = new HashSet<String>(cursor.getCount());
    try {
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
            final long id = cursor.getLong(ID_INDEX);
            final String providerName = cursor.getString(APPWIDGET_PROVIDER_INDEX);
            final int spanX = cursor.getInt(SPANX_INDEX);
            final int spanY = cursor.getInt(SPANY_INDEX);
            final ComponentName provider = ComponentName.unflattenFromString(providerName);
            Key key = null;
            String backupKey = null;
            if (provider != null) {
                key = getKey(Key.WIDGET, providerName);
                backupKey = keyToBackupKey(key);
                currentIds.add(backupKey);
            } else {
                Log.w(TAG, "empty intent on appwidget: " + id);
            }
            if (savedIds.contains(backupKey)) {
                if (DEBUG)
                    Log.d(TAG, "already saved widget " + backupKey);
                // remember that we already backed this up previously
                keys.add(key);
            } else if (backupKey != null) {
                if (DEBUG)
                    Log.d(TAG, "I can count this high: " + out.rows);
                if ((out.rows - startRows) < MAX_WIDGETS_PER_PASS) {
                    if (DEBUG)
                        Log.d(TAG, "saving widget " + backupKey);
                    previewLoader.setPreviewSize(spanX * profile.cellWidthPx, spanY * profile.cellHeightPx, widgetSpacingLayout);
                    byte[] blob = packWidget(dpi, previewLoader, iconCache, provider);
                    keys.add(key);
                    writeRowToBackup(key, blob, out, data);
                } else {
                    if (DEBUG)
                        Log.d(TAG, "scheduling another run for widget " + backupKey);
                    // too many widgets for this pass, request another.
                    dataChanged();
                }
            }
        }
    } finally {
        cursor.close();
    }
    if (DEBUG)
        Log.d(TAG, "widget currentIds.size()=" + currentIds.size());
    // these IDs must have been deleted
    savedIds.removeAll(currentIds);
    out.rows += removeDeletedKeysFromBackup(savedIds, data);
}
Also used : Cursor(android.database.Cursor) ContentResolver(android.content.ContentResolver) ComponentName(android.content.ComponentName) Key(com.android.launcher3.backup.BackupProtos.Key) HashSet(java.util.HashSet)

Example 2 with Key

use of com.android.launcher3.backup.BackupProtos.Key in project Launcher3 by chislon.

the class LauncherBackupHelper method restoreIcon.

/**
     * Read an icon from the stream.
     *
     * <P>Keys arrive in any order, so shortcuts that use this icon may already exist.
     *
     * @param key identifier for the row
     * @param buffer the serialized proto from the stream, may be larger than dataSize
     * @param dataSize the size of the proto from the stream
     * @param keys keys to mark as clean in the notes for next backup
     */
private void restoreIcon(Key key, byte[] buffer, int dataSize, ArrayList<Key> keys) {
    Log.v(TAG, "unpacking icon " + key.id);
    if (DEBUG)
        Log.d(TAG, "read (" + buffer.length + "): " + Base64.encodeToString(buffer, 0, dataSize, Base64.NO_WRAP));
    try {
        Resource res = unpackIcon(buffer, 0, dataSize);
        if (DEBUG)
            Log.d(TAG, "unpacked " + res.dpi);
        if (DEBUG)
            Log.d(TAG, "read " + Base64.encodeToString(res.data, 0, res.data.length, Base64.NO_WRAP));
        Bitmap icon = BitmapFactory.decodeByteArray(res.data, 0, res.data.length);
        if (icon == null) {
            Log.w(TAG, "failed to unpack icon for " + key.name);
        }
    } catch (InvalidProtocolBufferNanoException e) {
        Log.w(TAG, "failed to decode proto", e);
    }
}
Also used : Bitmap(android.graphics.Bitmap) Resource(com.android.launcher3.backup.BackupProtos.Resource) InvalidProtocolBufferNanoException(com.google.protobuf.nano.InvalidProtocolBufferNanoException)

Example 3 with Key

use of com.android.launcher3.backup.BackupProtos.Key in project Launcher3 by chislon.

the class DecoderRing method main.

public static void main(String[] args) throws Exception {
    File source = null;
    Class type = Key.class;
    int skip = 0;
    for (int i = 0; i < args.length; i++) {
        if ("-k".equals(args[i])) {
            type = Key.class;
        } else if ("-f".equals(args[i])) {
            type = Favorite.class;
        } else if ("-j".equals(args[i])) {
            type = Journal.class;
        } else if ("-i".equals(args[i])) {
            type = Resource.class;
        } else if ("-s".equals(args[i])) {
            type = Screen.class;
        } else if ("-w".equals(args[i])) {
            type = Widget.class;
        } else if ("-S".equals(args[i])) {
            if ((i + 1) < args.length) {
                skip = Integer.valueOf(args[++i]);
            } else {
                usage(args);
            }
        } else if (args[i] != null && !args[i].startsWith("-")) {
            source = new File(args[i]);
        } else {
            System.err.println("Unsupported flag: " + args[i]);
            usage(args);
        }
    }
    // read in the bytes
    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    BufferedInputStream input = null;
    if (source == null) {
        input = new BufferedInputStream(System.in);
    } else {
        try {
            input = new BufferedInputStream(new FileInputStream(source));
        } catch (FileNotFoundException e) {
            System.err.println("failed to open file: " + source + ", " + e);
            System.exit(1);
        }
    }
    byte[] buffer = new byte[1024];
    try {
        while (input.available() > 0) {
            int n = input.read(buffer);
            int offset = 0;
            if (skip > 0) {
                offset = Math.min(skip, n);
                n -= offset;
                skip -= offset;
            }
            if (n > 0) {
                byteStream.write(buffer, offset, n);
            }
        }
    } catch (IOException e) {
        System.err.println("failed to read input: " + e);
        System.exit(1);
    }
    System.err.println("read this many bytes: " + byteStream.size());
    MessageNano proto = null;
    if (type == Key.class) {
        Key key = new Key();
        try {
            key = Key.parseFrom(byteStream.toByteArray());
        } catch (InvalidProtocolBufferNanoException e) {
            System.err.println("failed to parse proto: " + e);
            System.exit(1);
        }
        // keys are self-checked
        if (key.checksum != checkKey(key)) {
            System.err.println("key ckecksum failed");
            System.exit(1);
        }
        proto = key;
    } else {
        // other types are wrapped in a checksum message
        CheckedMessage wrapper = new CheckedMessage();
        try {
            MessageNano.mergeFrom(wrapper, byteStream.toByteArray());
        } catch (InvalidProtocolBufferNanoException e) {
            System.err.println("failed to parse wrapper: " + e);
            System.exit(1);
        }
        CRC32 checksum = new CRC32();
        checksum.update(wrapper.payload);
        if (wrapper.checksum != checksum.getValue()) {
            System.err.println("wrapper ckecksum failed");
            System.exit(1);
        }
        // decode the actual message
        proto = (MessageNano) type.newInstance();
        try {
            MessageNano.mergeFrom(proto, wrapper.payload);
        } catch (InvalidProtocolBufferNanoException e) {
            System.err.println("failed to parse proto: " + e);
            System.exit(1);
        }
    }
    // Generic string output
    System.out.println(proto.toString());
    // save off the icon bits in a file for inspection
    if (proto instanceof Resource) {
        Resource icon = (Resource) proto;
        final String path = "icon.webp";
        FileOutputStream iconFile = new FileOutputStream(path);
        iconFile.write(icon.data);
        iconFile.close();
        System.err.println("wrote " + path);
    }
    // save off the widget icon and preview bits in files for inspection
    if (proto instanceof Widget) {
        Widget widget = (Widget) proto;
        if (widget.icon != null) {
            final String path = "widget_icon.webp";
            FileOutputStream iconFile = new FileOutputStream(path);
            iconFile.write(widget.icon.data);
            iconFile.close();
            System.err.println("wrote " + path);
        }
        if (widget.preview != null) {
            final String path = "widget_preview.webp";
            FileOutputStream iconFile = new FileOutputStream(path);
            iconFile.write(widget.preview.data);
            iconFile.close();
            System.err.println("wrote " + path);
        }
    }
    // success
    System.exit(0);
}
Also used : Favorite(com.android.launcher3.backup.BackupProtos.Favorite) CRC32(java.util.zip.CRC32) MessageNano(com.google.protobuf.nano.MessageNano) Resource(com.android.launcher3.backup.BackupProtos.Resource) Widget(com.android.launcher3.backup.BackupProtos.Widget) FileNotFoundException(java.io.FileNotFoundException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) InvalidProtocolBufferNanoException(com.google.protobuf.nano.InvalidProtocolBufferNanoException) FileInputStream(java.io.FileInputStream) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) CheckedMessage(com.android.launcher3.backup.BackupProtos.CheckedMessage) File(java.io.File) Key(com.android.launcher3.backup.BackupProtos.Key)

Example 4 with Key

use of com.android.launcher3.backup.BackupProtos.Key in project Launcher3 by chislon.

the class LauncherBackupHelper method performBackup.

/**
     * Back up launcher data so we can restore the user's state on a new device.
     *
     * <P>The journal is a timestamp and a list of keys that were saved as of that time.
     *
     * <P>Keys may come back in any order, so each key/value is one complete row of the database.
     *
     * @param oldState notes from the last backup
     * @param data incremental key/value pairs to persist off-device
     * @param newState notes for the next backup
     * @throws IOException
     */
@Override
public void performBackup(ParcelFileDescriptor oldState, BackupDataOutput data, ParcelFileDescriptor newState) {
    Log.v(TAG, "onBackup");
    Journal in = readJournal(oldState);
    Journal out = new Journal();
    long lastBackupTime = in.t;
    out.t = System.currentTimeMillis();
    out.rows = 0;
    out.bytes = 0;
    Log.v(TAG, "lastBackupTime=" + lastBackupTime);
    ArrayList<Key> keys = new ArrayList<Key>();
    try {
        backupFavorites(in, data, out, keys);
        backupScreens(in, data, out, keys);
        backupIcons(in, data, out, keys);
        backupWidgets(in, data, out, keys);
    } catch (IOException e) {
        Log.e(TAG, "launcher backup has failed", e);
    }
    out.key = keys.toArray(BackupProtos.Key.emptyArray());
    writeJournal(newState, out);
    Log.v(TAG, "onBackup: wrote " + out.bytes + "b in " + out.rows + " rows.");
}
Also used : ArrayList(java.util.ArrayList) Journal(com.android.launcher3.backup.BackupProtos.Journal) IOException(java.io.IOException) Key(com.android.launcher3.backup.BackupProtos.Key)

Example 5 with Key

use of com.android.launcher3.backup.BackupProtos.Key in project Launcher3 by chislon.

the class LauncherBackupHelper method backupFavorites.

/**
     * Write all modified favorites to the data stream.
     *
     *
     * @param in notes from last backup
     * @param data output stream for key/value pairs
     * @param out notes about this backup
     * @param keys keys to mark as clean in the notes for next backup
     * @throws IOException
     */
private void backupFavorites(Journal in, BackupDataOutput data, Journal out, ArrayList<Key> keys) throws IOException {
    // read the old ID set
    Set<String> savedIds = getSavedIdsByType(Key.FAVORITE, in);
    if (DEBUG)
        Log.d(TAG, "favorite savedIds.size()=" + savedIds.size());
    // persist things that have changed since the last backup
    ContentResolver cr = mContext.getContentResolver();
    Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
    Set<String> currentIds = new HashSet<String>(cursor.getCount());
    try {
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
            final long id = cursor.getLong(ID_INDEX);
            final long updateTime = cursor.getLong(ID_MODIFIED);
            Key key = getKey(Key.FAVORITE, id);
            keys.add(key);
            currentIds.add(keyToBackupKey(key));
            if (updateTime > in.t) {
                byte[] blob = packFavorite(cursor);
                writeRowToBackup(key, blob, out, data);
            }
        }
    } finally {
        cursor.close();
    }
    if (DEBUG)
        Log.d(TAG, "favorite currentIds.size()=" + currentIds.size());
    // these IDs must have been deleted
    savedIds.removeAll(currentIds);
    out.rows += removeDeletedKeysFromBackup(savedIds, data);
}
Also used : Cursor(android.database.Cursor) Key(com.android.launcher3.backup.BackupProtos.Key) ContentResolver(android.content.ContentResolver) HashSet(java.util.HashSet)

Aggregations

Key (com.android.launcher3.backup.BackupProtos.Key)9 ContentResolver (android.content.ContentResolver)4 Cursor (android.database.Cursor)4 IOException (java.io.IOException)4 HashSet (java.util.HashSet)4 ComponentName (android.content.ComponentName)2 Bitmap (android.graphics.Bitmap)2 Resource (com.android.launcher3.backup.BackupProtos.Resource)2 InvalidProtocolBufferNanoException (com.google.protobuf.nano.InvalidProtocolBufferNanoException)2 Intent (android.content.Intent)1 CheckedMessage (com.android.launcher3.backup.BackupProtos.CheckedMessage)1 Favorite (com.android.launcher3.backup.BackupProtos.Favorite)1 Journal (com.android.launcher3.backup.BackupProtos.Journal)1 Widget (com.android.launcher3.backup.BackupProtos.Widget)1 MessageNano (com.google.protobuf.nano.MessageNano)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1