Removed extra bitmap captures

- Removed unncessary calls to capture bitmaps
- Streamlined the code

Change-Id: I4701e72dd44685dc867c121da76fd0ec0ade0be7
diff --git a/src/com/android/browser/AddBookmarkPage.java b/src/com/android/browser/AddBookmarkPage.java
index 13c3d16..884cdc4 100644
--- a/src/com/android/browser/AddBookmarkPage.java
+++ b/src/com/android/browser/AddBookmarkPage.java
@@ -829,7 +829,7 @@
             String url = bundle.getString(BrowserContract.Bookmarks.URL);
             boolean invalidateThumbnail = bundle.getBoolean(REMOVE_THUMBNAIL);
             Bitmap thumbnail = invalidateThumbnail ? null
-                    : (Bitmap) bundle.getParcelable(BrowserContract.Bookmarks.THUMBNAIL);
+                    : (Bitmap) bundle.getParcelable(BrowserContract.Bookmarks.FAVICON);
             String touchIconUrl = bundle.getString(TOUCH_ICON_URL);
 
             // Save to the bookmarks DB.
@@ -1056,9 +1056,6 @@
             if (urlUnmodified) {
                 thumbnail = (Bitmap) mMap.getParcelable(
                         BrowserContract.Bookmarks.THUMBNAIL);
-                if (thumbnail == null) {
-                    thumbnail = Controller.getAndReleaseLastBookmarkBitmapFromIntent();
-                }
                 favicon = (Bitmap) mMap.getParcelable(
                         BrowserContract.Bookmarks.FAVICON);
             } else {
diff --git a/src/com/android/browser/Bookmarks.java b/src/com/android/browser/Bookmarks.java
index 9bd84f8..dc1052f 100644
--- a/src/com/android/browser/Bookmarks.java
+++ b/src/com/android/browser/Bookmarks.java
@@ -22,6 +22,7 @@
 import android.content.Context;
 import android.content.SharedPreferences;
 import android.database.Cursor;
+import android.database.sqlite.SQLiteException;
 import android.graphics.Bitmap;
 import android.net.Uri;
 import android.os.AsyncTask;
@@ -158,15 +159,31 @@
             Combined.URL + " == ? OR " +
             Combined.URL + " == ?";
 
+    private static String eatTrailingSlash(String input) {
+        if (TextUtils.isEmpty(input)) {
+            return input;
+        }
+
+        if (input.charAt(input.length() - 1) == '/') {
+            return input.substring(0, input.length() - 1);
+        }
+
+        return input;
+    }
+
     public static Cursor queryCombinedForUrl(ContentResolver cr,
             String originalUrl, String url) {
         if (cr == null || url == null) {
             return null;
         }
 
+        url = eatTrailingSlash(url);
+
         // If originalUrl is null, just set it to url.
         if (originalUrl == null) {
             originalUrl = url;
+        } else {
+            originalUrl = eatTrailingSlash(originalUrl);
         }
 
         // Look for both the original url and the actual url. This takes in to
@@ -205,20 +222,39 @@
             protected Void doInBackground(Void... unused) {
                 final ByteArrayOutputStream os = new ByteArrayOutputStream();
                 favicon.compress(Bitmap.CompressFormat.PNG, 100, os);
+                byte[] image = os.toByteArray();
 
                 // The Images update will insert if it doesn't exist
                 ContentValues values = new ContentValues();
-                values.put(Images.FAVICON, os.toByteArray());
-                updateImages(cr, originalUrl, values);
-                updateImages(cr, url, values);
+                values.put(Images.FAVICON, image);
+                values.put(Images.THUMBNAIL, image);
+
+                updateImages(cr, removeQuery(originalUrl), values);
+                updateImages(cr, removeQuery(url), values);
+
+                Cursor cursor = null;
+                try {
+                    cursor = queryCombinedForUrl(cr, originalUrl, url);
+                    if (cursor != null && cursor.moveToFirst()) {
+                        do {
+                            updateImages(cr, cursor.getString(0), values);
+                        } while (cursor.moveToNext());
+                    }
+                } catch (IllegalStateException e) {
+                    // Ignore
+                } catch (SQLiteException s) {
+                    // Ignore
+                } finally {
+                    if (cursor != null) cursor.close();
+                }
+
                 return null;
             }
 
             private void updateImages(final ContentResolver cr,
-                    final String url, ContentValues values) {
-                String iurl = removeQuery(url);
-                if (!TextUtils.isEmpty(iurl)) {
-                    values.put(Images.URL, iurl);
+                                      final String url, ContentValues values) {
+                if (!TextUtils.isEmpty(url)) {
+                    values.put(Images.URL, url);
                     cr.update(BrowserContract.Images.CONTENT_URI, values, null, null);
                 }
             }
diff --git a/src/com/android/browser/Controller.java b/src/com/android/browser/Controller.java
index 3f5319a..652755b 100644
--- a/src/com/android/browser/Controller.java
+++ b/src/com/android/browser/Controller.java
@@ -155,8 +155,6 @@
     private static final int RELEASE_WAKELOCK = 107;
     private static final int UNKNOWN_TYPE_MSG = 109;
 
-    static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
-
     private static final int OPEN_BOOKMARKS = 201;
     private static final int OPEN_MENU = 202;
 
@@ -263,7 +261,6 @@
     private String mUpdateMyNavThumbnailUrl;
     private float mLevel = 0.0f;
     private WebView.HitTestResult mResult;
-    private static Bitmap mBookmarkBitmap;
     private PowerConnectionReceiver mLowPowerReceiver;
     private PowerConnectionReceiver mPowerChangeReceiver;
 
@@ -671,12 +668,6 @@
                         }
                         break;
 
-                    case UPDATE_BOOKMARK_THUMBNAIL:
-                        Tab tab = (Tab) msg.obj;
-                        if (tab != null) {
-                            updateScreenshot(tab);
-                        }
-                        break;
                     case OPEN_MENU:
                         if (!mOptionsMenuOpen && mActivity != null ) {
                             mActivity.openOptionsMenu();
@@ -989,12 +980,6 @@
     @Override
     public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
 
-        // We've started to load a new page. If there was a pending message
-        // to save a screenshot then we will now take the new page and save
-        // an incorrect screenshot. Therefore, remove any pending thumbnail
-        // messages from the queue.
-        mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL, tab);
-
         // reset sync timer to avoid sync starts during loading a page
         CookieSyncManager.getInstance().resetSync();
         WifiManager wifiMgr = (WifiManager) this.getContext()
@@ -1045,6 +1030,7 @@
          }
 
         tab.onPageFinished();
+        maybeUpdateFavicon(tab, tab.getOriginalUrl(), tab.getUrl(), tab.getFavicon());
 
         Performance.tracePageFinished();
     }
@@ -1075,22 +1061,6 @@
                 // finished while BrowserActivity is in pause state.
                 releaseWakeLock();
             }
-            if (!tab.isPrivateBrowsingEnabled()
-                    && !TextUtils.isEmpty(tab.getUrl())
-                    && !tab.isSnapshot()) {
-                // Only update the bookmark screenshot if the user did not
-                // cancel the load early and there is not already
-                // a pending update for the tab.
-                if (tab.shouldUpdateThumbnail() &&
-                        (tab.inForeground() && !didUserStopLoading()
-                        || !tab.inForeground())) {
-                    if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
-                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
-                                UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
-                                1500);
-                    }
-                }
-            }
         } else {
             if (!tab.inPageLoad()) {
                 // onPageFinished may have already been called but a subframe is
@@ -2377,36 +2347,18 @@
         BrowserPreferencesPage.startPreferencesForResult(mActivity, getCurrentTopWebView().getUrl(), PREFERENCES_PAGE);
     }
 
-    // This function is specifically used from AddBookmark Activity.
-    // The bookmark activity clears the bitmap after retrieving it.
-    // The function usage elsewhere will result in breaking bookmark
-    // functionality.
-    public static Bitmap getAndReleaseLastBookmarkBitmapFromIntent() {
-        Bitmap bitmap = mBookmarkBitmap;
-        mBookmarkBitmap = null;
-        return bitmap;
-    }
-
     @Override
     public void bookmarkCurrentPage() {
         if(EditBookmarksRestriction.getInstance().isEnabled()) {
-            Toast.makeText(getContext(), R.string.mdm_managed_alert, Toast.LENGTH_SHORT).show();
+            Toast.makeText(getContext(), R.string.mdm_managed_alert,
+                    Toast.LENGTH_SHORT).show();
         }
         else {
             WebView w = getCurrentTopWebView();
             if (w == null)
                 return;
             final Intent i = createBookmarkCurrentPageIntent(false);
-            createScreenshotAsync(
-                    w, getDesiredThumbnailWidth(mActivity),
-                    getDesiredThumbnailHeight(mActivity),
-                    new ValueCallback<Bitmap>() {
-                        @Override
-                        public void onReceiveValue(Bitmap bitmap) {
-                            mBookmarkBitmap = bitmap;
-                            mActivity.startActivity(i);
-                        }
-                    });
+            mActivity.startActivity(i);
         }
     }
 
@@ -2711,116 +2663,6 @@
                 }});
     }
 
-    private void updateScreenshot(final Tab tab) {
-        createScreenshotAsync(
-            tab.getWebView(),
-            getDesiredThumbnailWidth(mActivity),
-            getDesiredThumbnailHeight(mActivity),
-            new ValueCallback<Bitmap>() {
-                @Override
-                public void onReceiveValue(Bitmap bitmap) {
-                   updateScreenshot(tab, bitmap);
-                }
-            });
-    }
-
-    private void updateScreenshot(Tab tab, final Bitmap bm) {
-        // If this is a bookmarked site, add a screenshot to the database.
-        // FIXME: Would like to make sure there is actually something to
-        // draw, but the API for that (WebViewCore.pictureReady()) is not
-        // currently accessible here.
-
-        WebView view = tab.getWebView();
-        if (view == null) {
-            // Tab was destroyed
-            return;
-        }
-        final String url = tab.getUrl();
-        final String originalUrl = view.getOriginalUrl();
-        final String thumbnailUrl = mUpdateMyNavThumbnailUrl;
-        if (TextUtils.isEmpty(url)) {
-            return;
-        }
-
-        //update My Navigation Thumbnails
-        if (bm != null) {
-            updateMyNavigationThumbnail(url, bm);
-        }
-        // Only update thumbnails for web urls (http(s)://), not for
-        // about:, javascript:, data:, etc...
-        // Unless it is a bookmarked site, then always update
-        if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) {
-            return;
-        }
-
-        if (url != null && mUpdateMyNavThumbnailUrl != null
-                && Patterns.WEB_URL.matcher(url).matches()
-                && Patterns.WEB_URL.matcher(mUpdateMyNavThumbnailUrl).matches()) {
-            String urlHost = (new WebAddress(url)).getHost();
-            String bookmarkHost = (new WebAddress(mUpdateMyNavThumbnailUrl)).getHost();
-            if (urlHost == null || urlHost.length() == 0 || bookmarkHost == null
-                    || bookmarkHost.length() == 0) {
-                return;
-            }
-            String urlDomain = urlHost.substring(urlHost.indexOf('.'), urlHost.length());
-            String bookmarkDomain = bookmarkHost.substring(bookmarkHost.indexOf('.'),
-                    bookmarkHost.length());
-            Log.d(LOGTAG, "addressUrl domain is  " + urlDomain);
-            Log.d(LOGTAG, "bookmarkUrl domain is " + bookmarkDomain);
-            if (!bookmarkDomain.equals(urlDomain)) {
-                return;
-            }
-        }
-        if (bm == null) {
-            if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
-                mHandler.sendMessageDelayed(mHandler.obtainMessage(
-                     UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
-                     500);
-            }
-            return;
-        }
-
-        final ContentResolver cr = mActivity.getContentResolver();
-        new AsyncTask<Void, Void, Void>() {
-            @Override
-            protected Void doInBackground(Void... unused) {
-                Cursor cursor = null;
-                try {
-                    // TODO: Clean this up
-                    cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl,
-                            mUpdateMyNavThumbnail ? ((thumbnailUrl != null) ? thumbnailUrl : url)
-                                    : url);
-                    if (mUpdateMyNavThumbnail) {
-                        mUpdateMyNavThumbnail = false;
-                        mUpdateMyNavThumbnailUrl = null;
-                    }
-                    if (cursor != null && cursor.moveToFirst()) {
-                        final ByteArrayOutputStream os =
-                                new ByteArrayOutputStream();
-                        bm.compress(Bitmap.CompressFormat.PNG, 100, os);
-
-                        ContentValues values = new ContentValues();
-                        values.put(Images.THUMBNAIL, os.toByteArray());
-
-                        do {
-                            values.put(Images.URL, cursor.getString(0));
-                            cr.update(Images.CONTENT_URI, values, null, null);
-                        } while (cursor.moveToNext());
-                    }
-                } catch (IllegalStateException e) {
-                    // Ignore
-                } catch (SQLiteException s) {
-                    // Added for possible error when user tries to remove the same bookmark
-                    // that is being updated with a screen shot
-                    Log.w(LOGTAG, "Error when running updateScreenshot ", s);
-                } finally {
-                    if (cursor != null) cursor.close();
-                }
-                return null;
-            }
-        }.execute();
-    }
-
     private class Copy implements OnMenuItemClickListener {
         private CharSequence mText;
 
diff --git a/src/com/android/browser/Tab.java b/src/com/android/browser/Tab.java
index 64be289..01876a4 100644
--- a/src/com/android/browser/Tab.java
+++ b/src/com/android/browser/Tab.java
@@ -1228,11 +1228,11 @@
             }
         };
 
-        mCaptureWidth = mContext.getResources().getDimensionPixelSize(
-                R.dimen.tab_thumbnail_width);
-        mCaptureHeight = mContext.getResources().getDimensionPixelSize(
-                R.dimen.tab_thumbnail_height);
-        updateShouldCaptureThumbnails();
+        mCaptureWidth = mContext.getResources().getDimensionPixelSize(R.dimen.tab_thumbnail_width);
+        mCaptureHeight =mContext.getResources().getDimensionPixelSize(R.dimen.tab_thumbnail_height);
+
+        initCaptureBitmap();
+
         restoreState(state);
         if (getId() == -1) {
             mId = TabControl.getNextId();
@@ -1254,8 +1254,9 @@
         mTabHistoryUpdateObservable = new Observable();
     }
 
-    public boolean shouldUpdateThumbnail() {
-        return mUpdateThumbnail;
+    private void initCaptureBitmap() {
+        mCapture = Bitmap.createBitmap(mCaptureWidth, mCaptureHeight, Bitmap.Config.RGB_565);
+        mCapture.eraseColor(Color.WHITE);
     }
 
     /**
@@ -1267,15 +1268,15 @@
         mId = TabControl.getNextId();
     }
 
-    public void updateShouldCaptureThumbnails() {
+    public void setController(WebViewController ctl) {
+        mWebViewController = ctl;
+
         if (mWebViewController.shouldCaptureThumbnails()) {
             synchronized (Tab.this) {
                 if (mCapture == null) {
-                    mCapture = Bitmap.createBitmap(mCaptureWidth, mCaptureHeight,
-                            Bitmap.Config.RGB_565);
-                    mCapture.eraseColor(Color.WHITE);
-                    if (mInForeground) {
-                        postCapture();
+                    initCaptureBitmap();
+                    if (mInForeground && !mHandler.hasMessages(MSG_CAPTURE)) {
+                        mHandler.sendEmptyMessageDelayed(MSG_CAPTURE, CAPTURE_DELAY);
                     }
                 }
             }
@@ -1287,11 +1288,6 @@
         }
     }
 
-    public void setController(WebViewController ctl) {
-        mWebViewController = ctl;
-        updateShouldCaptureThumbnails();
-    }
-
     public long getId() {
         return mId;
     }
@@ -1979,82 +1975,63 @@
         mDisableOverrideUrlLoading = true;
     }
 
-    protected void capture() {
-        boolean returnEmptyCapture = false;
-        if (mMainView == null || mCapture == null || !mMainView.isReady())
-            returnEmptyCapture = true;
-        if (mMainView.getContentWidth() <= 0 || mMainView.getContentHeight() <= 0) {
-             returnEmptyCapture = true;
-        }
-
-        if (returnEmptyCapture || !mFirstVisualPixelPainted || mMainView.isShowingCrashView()) {
-            mCapture = Bitmap.createBitmap(
-                    mCaptureWidth,
-                    mCaptureHeight,
-                    Bitmap.Config.RGB_565);
-            mCapture.eraseColor(Color.WHITE);
-
-            mHandler.removeMessages(MSG_CAPTURE);
-
-            TabControl tc = mWebViewController.getTabControl();
-            if (tc != null) {
-                OnThumbnailUpdatedListener updateListener
-                        = tc.getOnThumbnailUpdatedListener();
-                if (updateListener != null) {
-                    updateListener.onThumbnailUpdated(this);
-                }
-            }
-            return;
-        }
-
-        mMainView
-            .getContentBitmapAsync(
-                 (float) mCaptureWidth / mMainView.getWidth(),
-                 new Rect(),
-                 new ValueCallback<Bitmap>() {
-                     @Override
-                     public void onReceiveValue(Bitmap bitmap) {
-                         onCaptureCallback(bitmap);
-                     }});
-    }
-
-    private void onCaptureCallback(Bitmap bitmap) {
-        if (mCapture == null || bitmap == null)
-            return;
-
-        Canvas c = new Canvas(mCapture);
-        mCapture.eraseColor(Color.WHITE);
-        c.drawBitmap(bitmap, 0, 0, null);
-
-        // manually anti-alias the edges for the tilt
-        c.drawRect(0, 0, 1, mCapture.getHeight(), sAlphaPaint);
-        c.drawRect(mCapture.getWidth() - 1, 0, mCapture.getWidth(),
-                mCapture.getHeight(), sAlphaPaint);
-        c.drawRect(0, 0, mCapture.getWidth(), 1, sAlphaPaint);
-        c.drawRect(0, mCapture.getHeight() - 1, mCapture.getWidth(),
-                mCapture.getHeight(), sAlphaPaint);
-        c.setBitmap(null);
+    private void thumbnailUpdated() {
         mHandler.removeMessages(MSG_CAPTURE);
-        persistThumbnail();
+
         TabControl tc = mWebViewController.getTabControl();
         if (tc != null) {
-            OnThumbnailUpdatedListener updateListener
-                    = tc.getOnThumbnailUpdatedListener();
+            OnThumbnailUpdatedListener updateListener = tc.getOnThumbnailUpdatedListener();
             if (updateListener != null) {
                 updateListener.onThumbnailUpdated(this);
             }
         }
     }
 
-    @Override
-    public void onNewPicture(WebView view, Picture picture) {
-        postCapture();
+    protected void capture() {
+        if (mMainView == null || mCapture == null || !mMainView.isReady() ||
+                mMainView.getContentWidth() <= 0 || mMainView.getContentHeight() <= 0 ||
+                !mFirstVisualPixelPainted || mMainView.isShowingCrashView()) {
+
+            initCaptureBitmap();
+            thumbnailUpdated();
+            return;
+        }
+
+        mMainView.getContentBitmapAsync((float) mCaptureWidth / mMainView.getWidth(), new Rect(),
+            new ValueCallback<Bitmap>() {
+                @Override
+                public void onReceiveValue(Bitmap bitmap) {
+                    if (mCapture == null) {
+                        initCaptureBitmap();
+                    }
+
+                    if (bitmap == null) {
+                        thumbnailUpdated();
+                        return;
+                    }
+
+                    Canvas c = new Canvas(mCapture);
+                    mCapture.eraseColor(Color.WHITE);
+                    c.drawBitmap(bitmap, 0, 0, null);
+
+                    // manually anti-alias the edges for the tilt
+                    c.drawRect(0, 0, 1, mCapture.getHeight(), sAlphaPaint);
+                    c.drawRect(mCapture.getWidth() - 1, 0, mCapture.getWidth(),
+                            mCapture.getHeight(), sAlphaPaint);
+                    c.drawRect(0, 0, mCapture.getWidth(), 1, sAlphaPaint);
+                    c.drawRect(0, mCapture.getHeight() - 1, mCapture.getWidth(),
+                            mCapture.getHeight(), sAlphaPaint);
+                    c.setBitmap(null);
+
+                    persistThumbnail();
+                    thumbnailUpdated();
+                }
+            }
+        );
     }
 
-    private void postCapture() {
-        if (!mHandler.hasMessages(MSG_CAPTURE)) {
-            mHandler.sendEmptyMessageDelayed(MSG_CAPTURE, CAPTURE_DELAY);
-        }
+    @Override
+    public void onNewPicture(WebView view, Picture picture) {
     }
 
     public boolean canGoBack() {