diff --git a/Android.mk b/Android.mk index 016d151a9a..10c9f24477 100644 --- a/Android.mk +++ b/Android.mk @@ -21,7 +21,13 @@ LOCAL_MODULE_TAGS := optional LOCAL_STATIC_JAVA_LIBRARIES := android-support-v13 -LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-renderscript-files-under, src) +LOCAL_SRC_FILES := $(call all-java-files-under, src) $(call all-renderscript-files-under, src) \ + $(call all-proto-files-under, protos) + +LOCAL_PROTOC_OPTIMIZE_TYPE := nano + +LOCAL_PROTOC_FLAGS := --proto_path=$(LOCAL_PATH)/protos + LOCAL_SDK_VERSION := 17 LOCAL_PACKAGE_NAME := Launcher3 diff --git a/protos/backup.proto b/protos/backup.proto new file mode 100644 index 0000000000..3780bc5833 --- /dev/null +++ b/protos/backup.proto @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + package launcher_backup; + +option java_package = "com.android.launcher3.backup"; +option java_outer_classname = "BackupProtos"; + +message Key { + enum Type { + FAVORITE = 1; + SCREEN = 2; + IMAGE = 3; + } + required Type type = 1; + optional string name = 2; // keep this short + optional int64 id = 3; + optional int64 checksum = 4; +} + +message CheckedMessage { + required bytes payload = 1; + required int64 checksum = 2; +} + +message Journal { + required int32 app_version = 1; + required int64 t = 2; + optional int64 bytes = 3; + optional int32 rows = 4; + repeated Key key = 5; +} + +message Favorite { + required int64 id = 1; + required int32 itemType = 2; + optional string title = 3; + optional int32 container = 4; + optional int32 screen = 5; + optional int32 cellX = 6; + optional int32 cellY = 7; + optional int32 spanX = 8; + optional int32 spanY = 9; + optional int32 displayMode = 10; + optional int32 appWidgetId = 11; + optional string appWidgetProvider = 12; + optional string intent = 13; + optional string uri = 14; + optional int32 iconType = 15; + optional string iconPackage = 16; + optional string iconResource = 17; + optional bytes icon = 18; + } + +message Screen { + required int64 id = 1; + optional int32 rank = 2; + } + +message Resource { + required int32 dpi = 2; + required bytes data = 3; + } diff --git a/src/com/android/launcher3/LauncherBackupAgent.java b/src/com/android/launcher3/LauncherBackupAgent.java new file mode 100644 index 0000000000..bb15ca1848 --- /dev/null +++ b/src/com/android/launcher3/LauncherBackupAgent.java @@ -0,0 +1,655 @@ +/* + * Copyright (C) 2013 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.launcher3; + +import com.google.protobuf.nano.InvalidProtocolBufferNanoException; +import com.google.protobuf.nano.MessageNano; + +import com.android.launcher3.LauncherSettings.ChangeLogColumns; +import com.android.launcher3.LauncherSettings.Favorites; +import com.android.launcher3.LauncherSettings.WorkspaceScreens; +import com.android.launcher3.backup.BackupProtos; +import com.android.launcher3.backup.BackupProtos.CheckedMessage; +import com.android.launcher3.backup.BackupProtos.Favorite; +import com.android.launcher3.backup.BackupProtos.Journal; +import com.android.launcher3.backup.BackupProtos.Key; +import com.android.launcher3.backup.BackupProtos.Screen; + +import android.app.backup.BackupAgent; +import android.app.backup.BackupDataInput; +import android.app.backup.BackupDataOutput; +import android.app.backup.BackupManager; +import android.content.ContentResolver; +import android.content.Context; +import android.database.Cursor; +import android.os.ParcelFileDescriptor; +import android.provider.BaseColumns; +import android.text.TextUtils; +import android.util.Base64; +import android.util.Log; + +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; +import java.util.zip.CRC32; + +/** + * Persist the launcher home state across calamities. + */ +public class LauncherBackupAgent extends BackupAgent { + + private static final String TAG = "LauncherBackupAgent"; + private static final boolean DEBUG = false; + + private static final int MAX_JOURNAL_SIZE = 1000000; + + private static BackupManager sBackupManager; + + private static final String[] FAVORITE_PROJECTION = { + Favorites._ID, // 0 + Favorites.APPWIDGET_ID, // 1 + Favorites.APPWIDGET_PROVIDER, // 2 + Favorites.CELLX, // 3 + Favorites.CELLY, // 4 + Favorites.CONTAINER, // 5 + Favorites.ICON, // 6 + Favorites.ICON_PACKAGE, // 7 + Favorites.ICON_RESOURCE, // 8 + Favorites.ICON_TYPE, // 9 + Favorites.ITEM_TYPE, // 10 + Favorites.INTENT, // 11 + Favorites.SCREEN, // 12 + Favorites.SPANX, // 13 + Favorites.SPANY, // 14 + Favorites.TITLE, // 15 + }; + + private static final int ID_INDEX = 0; + private static final int APPWIDGET_ID_INDEX = 1; + private static final int APPWIDGET_PROVIDER_INDEX = 2; + private static final int CELLX_INDEX = 3; + private static final int CELLY_INDEX = 4; + private static final int CONTAINER_INDEX = 5; + private static final int ICON_INDEX = 6; + private static final int ICON_PACKAGE_INDEX = 7; + private static final int ICON_RESOURCE_INDEX = 8; + private static final int ICON_TYPE_INDEX = 9; + private static final int ITEM_TYPE_INDEX = 10; + private static final int INTENT_INDEX = 11; + private static final int SCREEN_INDEX = 12; + private static final int SPANX_INDEX = 13 ; + private static final int SPANY_INDEX = 14; + private static final int TITLE_INDEX = 15; + + private static final String[] SCREEN_PROJECTION = { + WorkspaceScreens._ID, // 0 + WorkspaceScreens.SCREEN_RANK // 1 + }; + + private static final int SCREEN_RANK_INDEX = 1; + + private static final String[] ID_ONLY_PROJECTION = { + BaseColumns._ID + }; + + + /** + * Notify the backup manager that out database is dirty. + * + *
This does not force an immediate backup. + * + * @param context application context + */ + public static void dataChanged(Context context) { + if (sBackupManager == null) { + sBackupManager = new BackupManager(context); + } + sBackupManager.dataChanged(); + } + + /** + * Back up launcher data so we can restore the user's state on a new device. + * + *
The journal is a timestamp and a list of keys that were saved as of that time. + * + *
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 onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
+ ParcelFileDescriptor newState)
+ throws IOException {
+ 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 Keys may arrive in any order.
+ *
+ * @param data the key/value pairs from the server
+ * @param versionCode the version of the app that generated the data
+ * @param newState notes for the next backup
+ * @throws IOException
+ */
+ @Override
+ public void onRestore(BackupDataInput data, int versionCode, ParcelFileDescriptor newState)
+ throws IOException {
+ Log.v(TAG, "onRestore");
+ int numRows = 0;
+ Journal out = new Journal();
+
+ ArrayList Keys arrive in any order, so screens and containers may not exist yet.
+ *
+ * @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 restoreFavorite(Key key, byte[] buffer, int dataSize, ArrayList Keys arrive in any order, so children of this screen 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 restoreScreen(Key key, byte[] buffer, int dataSize, ArrayList Keys contain their own checksum instead of using
+ * the heavy-weight CheckedMessage wrapper.
+ */
+ private Key getKey(int type, long id) {
+ Key key = new Key();
+ key.type = type;
+ key.id = id;
+ key.checksum = checkKey(key);
+ return key;
+ }
+
+ /** keys need to be strings, serialize and encode. */
+ private String keyToBackupKey(Key key) {
+ return Base64.encodeToString(Key.toByteArray(key), Base64.NO_WRAP | Base64.NO_PADDING);
+ }
+
+ /** keys need to be strings, decode and parse. */
+ private Key backupKeyToKey(String backupKey) throws KeyParsingException {
+ try {
+ Key key = Key.parseFrom(Base64.decode(backupKey, Base64.DEFAULT));
+ if (key.checksum != checkKey(key)) {
+ key = null;
+ throw new KeyParsingException("invalid key read from stream" + backupKey);
+ }
+ return key;
+ } catch (InvalidProtocolBufferNanoException e) {
+ throw new KeyParsingException(e);
+ } catch (IllegalArgumentException e) {
+ throw new KeyParsingException(e);
+ }
+ }
+
+ /** Compute the checksum over the important bits of a key. */
+ private long checkKey(Key key) {
+ CRC32 checksum = new CRC32();
+ checksum.update(key.type);
+ checksum.update((int) (key.id & 0xffff));
+ checksum.update((int) ((key.id >> 32) & 0xffff));
+ if (!TextUtils.isEmpty(key.name)) {
+ checksum.update(key.name.getBytes());
+ }
+ return checksum.getValue();
+ }
+
+ /** Serialize a Favorite for persistence, including a checksum wrapper. */
+ private byte[] packFavorite(Cursor c) {
+ Favorite favorite = new Favorite();
+ favorite.id = c.getLong(ID_INDEX);
+ favorite.screen = c.getInt(SCREEN_INDEX);
+ favorite.container = c.getInt(CONTAINER_INDEX);
+ favorite.cellX = c.getInt(CELLX_INDEX);
+ favorite.cellY = c.getInt(CELLY_INDEX);
+ favorite.spanX = c.getInt(SPANX_INDEX);
+ favorite.spanY = c.getInt(SPANY_INDEX);
+ favorite.iconType = c.getInt(ICON_TYPE_INDEX);
+ if (favorite.iconType == Favorites.ICON_TYPE_RESOURCE) {
+ String iconPackage = c.getString(ICON_PACKAGE_INDEX);
+ if (!TextUtils.isEmpty(iconPackage)) {
+ favorite.iconPackage = iconPackage;
+ }
+ String iconResource = c.getString(ICON_RESOURCE_INDEX);
+ if (!TextUtils.isEmpty(iconResource)) {
+ favorite.iconResource = iconResource;
+ }
+ }
+ if (favorite.iconType == Favorites.ICON_TYPE_BITMAP) {
+ byte[] blob = c.getBlob(ICON_INDEX);
+ if (blob != null && blob.length > 0) {
+ favorite.icon = blob;
+ }
+ }
+ String title = c.getString(TITLE_INDEX);
+ if (!TextUtils.isEmpty(title)) {
+ favorite.title = title;
+ }
+ String intent = c.getString(INTENT_INDEX);
+ if (!TextUtils.isEmpty(intent)) {
+ favorite.intent = intent;
+ }
+ favorite.itemType = c.getInt(ITEM_TYPE_INDEX);
+ if (favorite.itemType == Favorites.ITEM_TYPE_APPWIDGET) {
+ favorite.appWidgetId = c.getInt(APPWIDGET_ID_INDEX);
+ String appWidgetProvider = c.getString(APPWIDGET_PROVIDER_INDEX);
+ if (!TextUtils.isEmpty(appWidgetProvider)) {
+ favorite.appWidgetProvider = appWidgetProvider;
+ }
+ }
+
+ return writeCheckedBytes(favorite);
+ }
+
+ /** Deserialize a Favorite from persistence, after verifying checksum wrapper. */
+ private Favorite unpackFavorite(byte[] buffer, int offset, int dataSize)
+ throws InvalidProtocolBufferNanoException {
+ Favorite favorite = new Favorite();
+ MessageNano.mergeFrom(favorite, readCheckedBytes(buffer, offset, dataSize));
+ return favorite;
+ }
+
+ /** Serialize a Screen for persistence, including a checksum wrapper. */
+ private byte[] packScreen(Cursor c) {
+ Screen screen = new Screen();
+ screen.id = c.getLong(ID_INDEX);
+ screen.rank = c.getInt(SCREEN_RANK_INDEX);
+
+ return writeCheckedBytes(screen);
+ }
+
+ /** Deserialize a Screen from persistence, after verifying checksum wrapper. */
+ private Screen unpackScreen(byte[] buffer, int offset, int dataSize)
+ throws InvalidProtocolBufferNanoException {
+ Screen screen = new Screen();
+ MessageNano.mergeFrom(screen, readCheckedBytes(buffer, offset, dataSize));
+ return screen;
+ }
+
+ /**
+ * Read the old journal from the input file.
+ *
+ * In the event of any error, just pretend we didn't have a journal,
+ * in that case, do a full backup.
+ *
+ * @param oldState the read-0only file descriptor pointing to the old journal
+ * @return a Journal protocol bugffer
+ */
+ private Journal readJournal(ParcelFileDescriptor oldState) {
+ int fileSize = (int) oldState.getStatSize();
+ int remaining = fileSize;
+ byte[] buffer = null;
+ Journal journal = new Journal();
+ if (remaining < MAX_JOURNAL_SIZE) {
+ FileInputStream inStream = new FileInputStream(oldState.getFileDescriptor());
+ int offset = 0;
+
+ buffer = new byte[remaining];
+ while (remaining > 0) {
+ int bytesRead = 0;
+ try {
+ bytesRead = inStream.read(buffer, offset, remaining);
+ } catch (IOException e) {
+ Log.w(TAG, "failed to read the journal", e);
+ buffer = null;
+ remaining = 0;
+ }
+ if (bytesRead > 0) {
+ remaining -= bytesRead;
+ } else {
+ // act like there is not journal
+ Log.w(TAG, "failed to read the journal");
+ buffer = null;
+ remaining = 0;
+ }
+ }
+
+ if (buffer != null) {
+ try {
+ MessageNano.mergeFrom(journal, readCheckedBytes(buffer, 0, fileSize));
+ } catch (InvalidProtocolBufferNanoException e) {
+ Log.d(TAG, "failed to read the journal", e);
+ journal.clear();
+ }
+ }
+
+ try {
+ inStream.close();
+ } catch (IOException e) {
+ Log.d(TAG, "failed to close the journal", e);
+ }
+ }
+ return journal;
+ }
+
+ /**
+ * Write the new journal to the output file.
+ *
+ * In the event of any error, just pretend we didn't have a journal,
+ * in that case, do a full backup.
+
+ * @param newState the write-only file descriptor pointing to the new journal
+ * @param journal a Journal protocol buffer
+ */
+ private void writeJournal(ParcelFileDescriptor newState, Journal journal) {
+ FileOutputStream outStream = null;
+ try {
+ outStream = new FileOutputStream(newState.getFileDescriptor());
+ outStream.write(writeCheckedBytes(journal));
+ outStream.close();
+ } catch (IOException e) {
+ Log.d(TAG, "failed to write backup journal", e);
+ }
+ }
+
+ /** Wrap a proto in a CheckedMessage and compute the checksum. */
+ private byte[] writeCheckedBytes(MessageNano proto) {
+ CheckedMessage wrapper = new CheckedMessage();
+ wrapper.payload = MessageNano.toByteArray(proto);
+ CRC32 checksum = new CRC32();
+ checksum.update(wrapper.payload);
+ wrapper.checksum = checksum.getValue();
+ return MessageNano.toByteArray(wrapper);
+ }
+
+ /** Unwrap a proto message from a CheckedMessage, verifying the checksum. */
+ private byte[] readCheckedBytes(byte[] buffer, int offset, int dataSize)
+ throws InvalidProtocolBufferNanoException {
+ CheckedMessage wrapper = new CheckedMessage();
+ MessageNano.mergeFrom(wrapper, buffer, offset, dataSize);
+ CRC32 checksum = new CRC32();
+ checksum.update(wrapper.payload);
+ if (wrapper.checksum != checksum.getValue()) {
+ throw new InvalidProtocolBufferNanoException("checksum does not match");
+ }
+ return wrapper.payload;
+ }
+
+ private class KeyParsingException extends Throwable {
+ private KeyParsingException(Throwable cause) {
+ super(cause);
+ }
+
+ public KeyParsingException(String reason) {
+ super(reason);
+ }
+ }
+}
diff --git a/src/com/android/launcher3/LauncherProvider.java b/src/com/android/launcher3/LauncherProvider.java
index fa61b11854..471d2d2fcf 100644
--- a/src/com/android/launcher3/LauncherProvider.java
+++ b/src/com/android/launcher3/LauncherProvider.java
@@ -49,6 +49,7 @@ import android.util.AttributeSet;
import android.util.Log;
import android.util.Xml;
+import com.android.launcher3.LauncherSettings.BaseLauncherColumns;
import com.android.launcher3.LauncherSettings.Favorites;
import org.xmlpull.v1.XmlPullParser;
@@ -65,7 +66,7 @@ public class LauncherProvider extends ContentProvider {
private static final String DATABASE_NAME = "launcher.db";
- private static final int DATABASE_VERSION = 14;
+ private static final int DATABASE_VERSION = 15;
static final String OLD_AUTHORITY = "com.android.launcher2.settings";
static final String AUTHORITY = "com.android.launcher3.settings";
@@ -146,6 +147,7 @@ public class LauncherProvider extends ContentProvider {
SqlArguments args = new SqlArguments(uri);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
+ addModifiedTime(initialValues);
final long rowId = dbInsertAndCheck(mOpenHelper, db, args.table, null, initialValues);
if (rowId <= 0) return null;
@@ -164,6 +166,7 @@ public class LauncherProvider extends ContentProvider {
try {
int numValues = values.length;
for (int i = 0; i < numValues; i++) {
+ addModifiedTime(values[i]);
if (dbInsertAndCheck(mOpenHelper, db, args.table, null, values[i]) < 0) {
return 0;
}
@@ -192,6 +195,7 @@ public class LauncherProvider extends ContentProvider {
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SqlArguments args = new SqlArguments(uri, selection, selectionArgs);
+ addModifiedTime(values);
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int count = db.update(args.table, values, args.where, args.args);
if (count > 0) sendNotify(uri);
@@ -204,6 +208,13 @@ public class LauncherProvider extends ContentProvider {
if (notify == null || "true".equals(notify)) {
getContext().getContentResolver().notifyChange(uri, null);
}
+
+ // always notify the backup agent
+ LauncherBackupAgent.dataChanged(getContext());
+ }
+
+ private void addModifiedTime(ContentValues values) {
+ values.put(LauncherSettings.ChangeLogColumns.MODIFIED, System.currentTimeMillis());
}
public long generateNewItemId() {
@@ -343,7 +354,8 @@ public class LauncherProvider extends ContentProvider {
"icon BLOB," +
"uri TEXT," +
"displayMode INTEGER," +
- "appWidgetProvider TEXT" +
+ "appWidgetProvider TEXT," +
+ "modified INTEGER NOT NULL DEFAULT 0" +
");");
addWorkspacesTable(db);
@@ -384,7 +396,8 @@ public class LauncherProvider extends ContentProvider {
private void addWorkspacesTable(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_WORKSPACE_SCREENS + " (" +
LauncherSettings.WorkspaceScreens._ID + " INTEGER," +
- LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER" +
+ LauncherSettings.WorkspaceScreens.SCREEN_RANK + " INTEGER," +
+ LauncherSettings.ChangeLogColumns.MODIFIED + " INTEGER NOT NULL DEFAULT 0" +
");");
}
@@ -643,6 +656,25 @@ public class LauncherProvider extends ContentProvider {
}
}
+
+ if (version < 15) {
+ db.beginTransaction();
+ try {
+ // Insert new column for holding update timestamp
+ db.execSQL("ALTER TABLE favorites " +
+ "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
+ db.execSQL("ALTER TABLE workspaceScreens " +
+ "ADD COLUMN modified INTEGER NOT NULL DEFAULT 0;");
+ db.setTransactionSuccessful();
+ version = 15;
+ } catch (SQLException ex) {
+ // Old version remains, which means we wipe old data
+ Log.e(TAG, ex.getMessage(), ex);
+ } finally {
+ db.endTransaction();
+ }
+ }
+
if (version != DATABASE_VERSION) {
Log.w(TAG, "Destroying all old data.");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVORITES);
diff --git a/src/com/android/launcher3/LauncherSettings.java b/src/com/android/launcher3/LauncherSettings.java
index ada09e9b8c..988e5efca9 100644
--- a/src/com/android/launcher3/LauncherSettings.java
+++ b/src/com/android/launcher3/LauncherSettings.java
@@ -23,7 +23,16 @@ import android.provider.BaseColumns;
* Settings related utilities.
*/
class LauncherSettings {
- static interface BaseLauncherColumns extends BaseColumns {
+ /** Columns required on table staht will be subject to backup and restore. */
+ static interface ChangeLogColumns extends BaseColumns {
+ /**
+ * The time of the last update to this row.
+ * Type: INTEGER Type: TEXT