Configure bookmark widget

 Add a configuration step when adding the bookmark widget to
 pick what account to use

Change-Id: I2be723c411ec5b9f32d6819a5e2e65995921a252
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 440a141..2782538 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -197,6 +197,12 @@
         <receiver
             android:name=".widget.BookmarkWidgetProxy"
             android:exported="false" />
+        <activity android:name=".widget.BookmarkWidgetConfigure"
+            android:theme="@android:style/Theme.Holo.DialogWhenLarge">
+            <intent-filter>
+                <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
+            </intent-filter>
+        </activity>
 
         <!-- Makes .BrowserActivity the search target for any activity in Browser -->
         <meta-data android:name="android.app.default_searchable" android:value=".BrowserActivity" />
diff --git a/res/layout/widget_account_selection.xml b/res/layout/widget_account_selection.xml
new file mode 100644
index 0000000..5dcd210
--- /dev/null
+++ b/res/layout/widget_account_selection.xml
@@ -0,0 +1,57 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2011 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.
+-->
+
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="match_parent"
+    android:orientation="vertical">
+    <ListView
+        android:id="@android:id/list"
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:layout_weight="1"
+        android:paddingLeft="16dip"
+        android:paddingRight="16dip"
+        android:fadingEdgeLength="16dip" />
+    <LinearLayout
+        android:layout_width="match_parent"
+        android:layout_height="wrap_content"
+        android:orientation="vertical"
+        android:divider="?android:attr/dividerHorizontal"
+        android:showDividers="beginning"
+        android:dividerPadding="16dip"
+        android:background="@null">
+        <LinearLayout
+            style="?android:attr/buttonBarStyle"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:orientation="horizontal"
+            android:paddingLeft="2dip"
+            android:paddingRight="2dip"
+            android:measureWithLargestChild="true"
+            android:background="@null">
+            <Button
+                android:id="@+id/cancel"
+                style="?android:attr/buttonBarButtonStyle"
+                android:layout_weight="1"
+                android:layout_width="0dip"
+                android:layout_height="wrap_content"
+                android:text="@string/cancel" />
+        </LinearLayout>
+    </LinearLayout>
+</LinearLayout>
+
diff --git a/res/xml/bookmarkthumbnailwidget_info.xml b/res/xml/bookmarkthumbnailwidget_info.xml
index 65497cd..e98e3f7 100644
--- a/res/xml/bookmarkthumbnailwidget_info.xml
+++ b/res/xml/bookmarkthumbnailwidget_info.xml
@@ -22,5 +22,6 @@
     android:updatePeriodMillis="0"
     android:previewImage="@drawable/browser_widget_preview"
     android:initialLayout="@layout/bookmarkthumbnailwidget"
-    android:resizeMode="vertical">
+    android:resizeMode="vertical"
+    android:configure="com.android.browser.widget.BookmarkWidgetConfigure">
 </appwidget-provider>
diff --git a/src/com/android/browser/AccountsChangedReceiver.java b/src/com/android/browser/AccountsChangedReceiver.java
index a34180a..aff78ca 100644
--- a/src/com/android/browser/AccountsChangedReceiver.java
+++ b/src/com/android/browser/AccountsChangedReceiver.java
@@ -57,7 +57,6 @@
             ContentResolver.setSyncAutomatically(a, BrowserContract.AUTHORITY, false);
             ContentResolver.setIsSyncable(a, BrowserContract.AUTHORITY, 0);
         }
-        BookmarkThumbnailWidgetProvider.refreshWidgets(context, true);
     }
 
 }
diff --git a/src/com/android/browser/AddBookmarkPage.java b/src/com/android/browser/AddBookmarkPage.java
index a9e5f52..f330cd5 100644
--- a/src/com/android/browser/AddBookmarkPage.java
+++ b/src/com/android/browser/AddBookmarkPage.java
@@ -996,7 +996,7 @@
         }
     }
 
-    static class AccountsLoader extends CursorLoader {
+    public static class AccountsLoader extends CursorLoader {
 
         static final String[] PROJECTION = new String[] {
             Accounts.ACCOUNT_NAME,
@@ -1015,11 +1015,11 @@
 
     }
 
-    static class BookmarkAccount {
+    public static class BookmarkAccount {
 
         private String mLabel;
         String accountName, accountType;
-        long rootFolderId;
+        public long rootFolderId;
 
         public BookmarkAccount(Context context, Cursor cursor) {
             accountName = cursor.getString(
diff --git a/src/com/android/browser/preferences/GeneralPreferencesFragment.java b/src/com/android/browser/preferences/GeneralPreferencesFragment.java
index 879b95d..0a12311 100644
--- a/src/com/android/browser/preferences/GeneralPreferencesFragment.java
+++ b/src/com/android/browser/preferences/GeneralPreferencesFragment.java
@@ -113,7 +113,6 @@
             if (BrowserBookmarksPage.PREF_ACCOUNT_NAME.equals(key)
                     || BrowserBookmarksPage.PREF_ACCOUNT_TYPE.equals(key)) {
                 refreshUi();
-                BookmarkThumbnailWidgetProvider.refreshWidgets(getActivity(), true);
             }
         }
 
diff --git a/src/com/android/browser/widget/BookmarkThumbnailWidgetProvider.java b/src/com/android/browser/widget/BookmarkThumbnailWidgetProvider.java
index 48d7123..f3d2675 100644
--- a/src/com/android/browser/widget/BookmarkThumbnailWidgetProvider.java
+++ b/src/com/android/browser/widget/BookmarkThumbnailWidgetProvider.java
@@ -16,9 +16,6 @@
 
 package com.android.browser.widget;
 
-import com.android.browser.BrowserActivity;
-import com.android.browser.R;
-
 import android.app.PendingIntent;
 import android.appwidget.AppWidgetManager;
 import android.appwidget.AppWidgetProvider;
@@ -28,6 +25,9 @@
 import android.net.Uri;
 import android.widget.RemoteViews;
 
+import com.android.browser.BrowserActivity;
+import com.android.browser.R;
+
 /**
  * Widget that shows a preview of the user's bookmarks.
  */
@@ -91,7 +91,7 @@
             RemoteViews views = new RemoteViews(context.getPackageName(),
                     R.layout.bookmarkthumbnailwidget);
             views.setOnClickPendingIntent(R.id.app_shortcut, launchBrowser);
-            views.setRemoteAdapter(appWidgetId, R.id.bookmarks_list, updateIntent);
+            views.setRemoteAdapter(R.id.bookmarks_list, updateIntent);
             appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.bookmarks_list);
             Intent ic = new Intent(context, BookmarkWidgetProxy.class);
             views.setPendingIntentTemplate(R.id.bookmarks_list,
@@ -110,27 +110,9 @@
     }
 
     public static void refreshWidgets(Context context) {
-        refreshWidgets(context, false);
+        context.sendBroadcast(new Intent(
+                BookmarkThumbnailWidgetProvider.ACTION_BOOKMARK_APPWIDGET_UPDATE,
+                null, context, BookmarkThumbnailWidgetProvider.class));
     }
 
-    public static void refreshWidgets(Context context, boolean zeroState) {
-        if (zeroState) {
-            final Context appContext = context.getApplicationContext();
-            new Thread() {
-                @Override
-                public void run() {
-                    AppWidgetManager wm = AppWidgetManager.getInstance(appContext);
-                    int[] ids = wm.getAppWidgetIds(getComponentName(appContext));
-                    for (int id : ids) {
-                        BookmarkThumbnailWidgetService.clearWidgetState(appContext, id);
-                    }
-                    refreshWidgets(appContext, false);
-                }
-            }.start();
-        } else {
-            context.sendBroadcast(new Intent(
-                    BookmarkThumbnailWidgetProvider.ACTION_BOOKMARK_APPWIDGET_UPDATE,
-                    null, context, BookmarkThumbnailWidgetProvider.class));
-        }
-    }
 }
diff --git a/src/com/android/browser/widget/BookmarkThumbnailWidgetService.java b/src/com/android/browser/widget/BookmarkThumbnailWidgetService.java
index 675cdd9..7d174ee 100644
--- a/src/com/android/browser/widget/BookmarkThumbnailWidgetService.java
+++ b/src/com/android/browser/widget/BookmarkThumbnailWidgetService.java
@@ -16,10 +16,6 @@
 
 package com.android.browser.widget;
 
-import com.android.browser.BookmarkUtils;
-import com.android.browser.BrowserActivity;
-import com.android.browser.R;
-
 import android.appwidget.AppWidgetManager;
 import android.content.ContentUris;
 import android.content.Context;
@@ -40,9 +36,12 @@
 import android.widget.RemoteViews;
 import android.widget.RemoteViewsService;
 
+import com.android.browser.BrowserActivity;
+import com.android.browser.R;
+import com.android.browser.provider.BrowserProvider2;
+
 import java.io.File;
 import java.io.FilenameFilter;
-import java.util.Arrays;
 import java.util.HashSet;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -110,11 +109,11 @@
         }
     }
 
-    static void clearWidgetState(Context context, int widgetId) {
+    static void setupWidgetState(Context context, int widgetId, long rootFolder) {
         SharedPreferences pref = getWidgetState(context, widgetId);
         pref.edit()
-            .remove(STATE_CURRENT_FOLDER)
-            .remove(STATE_ROOT_FOLDER)
+            .putLong(STATE_CURRENT_FOLDER, rootFolder)
+            .putLong(STATE_ROOT_FOLDER, rootFolder)
             .commit();
     }
 
@@ -311,8 +310,8 @@
             long token = Binder.clearCallingIdentity();
             syncState();
             if (mRootFolder < 0 || mCurrentFolder < 0) {
-                // Our state has been zero'd, reset (account change most likely)
-                mRootFolder = getRootFolder();
+                // This shouldn't happen, but JIC default to the local account
+                mRootFolder = BrowserProvider2.FIXED_ID_ROOT;
                 mCurrentFolder = mRootFolder;
                 saveState();
             }
@@ -327,27 +326,12 @@
             }
         }
 
-        long getRootFolder() {
-            Uri uri = Uri.withAppendedPath(
-                    BrowserContract.Bookmarks.CONTENT_URI_DEFAULT_FOLDER, "id");
-            uri = BookmarkUtils.addAccountInfo(mContext, uri.buildUpon()).build();
-            Cursor c = mContext.getContentResolver().query(
-                    uri, null, null, null, null);
-            try {
-                c.moveToFirst();
-                return c.getLong(0);
-            } finally {
-                c.close();
-            }
-        }
-
         void loadBookmarks() {
             resetBookmarks();
 
             Uri uri = ContentUris.withAppendedId(
                     BrowserContract.Bookmarks.CONTENT_URI_DEFAULT_FOLDER,
                     mCurrentFolder);
-            uri = BookmarkUtils.addAccountInfo(mContext, uri.buildUpon()).build();
             mBookmarks = mContext.getContentResolver().query(uri, PROJECTION,
                     null, null, null);
             if (mCurrentFolder != mRootFolder) {
diff --git a/src/com/android/browser/widget/BookmarkWidgetConfigure.java b/src/com/android/browser/widget/BookmarkWidgetConfigure.java
new file mode 100644
index 0000000..4231f37
--- /dev/null
+++ b/src/com/android/browser/widget/BookmarkWidgetConfigure.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2011 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.browser.widget;
+
+import android.app.ListActivity;
+import android.app.LoaderManager.LoaderCallbacks;
+import android.appwidget.AppWidgetManager;
+import android.content.Intent;
+import android.content.Loader;
+import android.database.Cursor;
+import android.os.Bundle;
+import android.view.View;
+import android.view.View.OnClickListener;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+
+import com.android.browser.AddBookmarkPage.AccountsLoader;
+import com.android.browser.AddBookmarkPage.BookmarkAccount;
+import com.android.browser.R;
+import com.android.browser.provider.BrowserProvider2;
+
+public class BookmarkWidgetConfigure extends ListActivity
+        implements OnClickListener, LoaderCallbacks<Cursor> {
+
+    static final int LOADER_ACCOUNTS = 1;
+
+    private ArrayAdapter<BookmarkAccount> mAccountAdapter;
+    private int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        setResult(RESULT_CANCELED);
+        setVisible(false);
+        setContentView(R.layout.widget_account_selection);
+        findViewById(R.id.cancel).setOnClickListener(this);
+        mAccountAdapter = new ArrayAdapter<BookmarkAccount>(this,
+                android.R.layout.simple_list_item_1);
+        setListAdapter(mAccountAdapter);
+        Intent intent = getIntent();
+        Bundle extras = intent.getExtras();
+        if (extras != null) {
+            mAppWidgetId = extras.getInt(
+                    AppWidgetManager.EXTRA_APPWIDGET_ID,
+                    AppWidgetManager.INVALID_APPWIDGET_ID);
+        }
+        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
+            finish();
+        } else {
+            getLoaderManager().initLoader(LOADER_ACCOUNTS, null, this);
+        }
+    }
+
+    @Override
+    public void onClick(View v) {
+        finish();
+    }
+
+    @Override
+    protected void onListItemClick(ListView l, View v, int position, long id) {
+        BookmarkAccount account = mAccountAdapter.getItem(position);
+        pickAccount(account.rootFolderId);
+    }
+
+    @Override
+    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
+        return new AccountsLoader(this);
+    }
+
+    void pickAccount(long rootId) {
+        BookmarkThumbnailWidgetService.setupWidgetState(this, mAppWidgetId, rootId);
+        Intent result = new Intent();
+        result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
+        setResult(RESULT_OK, result);
+        finish();
+    }
+
+    @Override
+    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
+        if (cursor == null || cursor.getCount() <= 1) {
+            // We always have the local account, so if count == 1 it must
+            // be the local account
+            pickAccount(BrowserProvider2.FIXED_ID_ROOT);
+        } else {
+            mAccountAdapter.clear();
+            while (cursor.moveToNext()) {
+                mAccountAdapter.add(new BookmarkAccount(this, cursor));
+            }
+            setVisible(true);
+        }
+        getLoaderManager().destroyLoader(LOADER_ACCOUNTS);
+    }
+
+    @Override
+    public void onLoaderReset(Loader<Cursor> loader) {
+        // Don't care
+    }
+
+}