Controller.java 95.4 KB
Newer Older
Michael Kolb's avatar
Michael Kolb committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * Copyright (C) 2010 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;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.SearchManager;
import android.content.ClipboardManager;
import android.content.ContentProvider;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
John Reck's avatar
John Reck committed
26
import android.content.ContentUris;
Michael Kolb's avatar
Michael Kolb committed
27 28 29 30 31 32
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
John Reck's avatar
John Reck committed
33
import android.content.res.TypedArray;
34
import android.database.ContentObserver;
Michael Kolb's avatar
Michael Kolb committed
35 36 37 38 39 40 41 42 43 44 45 46 47
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Picture;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
48
import android.preference.PreferenceActivity;
Michael Kolb's avatar
Michael Kolb committed
49 50 51 52 53
import android.provider.Browser;
import android.provider.BrowserContract;
import android.provider.BrowserContract.Images;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Intents.Insert;
Michael Kolb's avatar
Michael Kolb committed
54
import android.speech.RecognizerIntent;
Michael Kolb's avatar
Michael Kolb committed
55 56
import android.text.TextUtils;
import android.util.Log;
57
import android.util.Patterns;
Michael Kolb's avatar
Michael Kolb committed
58 59 60 61 62 63 64 65 66
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
Michael Kolb's avatar
Michael Kolb committed
67
import android.view.MotionEvent;
Michael Kolb's avatar
Michael Kolb committed
68 69 70 71 72 73 74 75 76 77
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebIconDatabase;
import android.webkit.WebSettings;
import android.webkit.WebView;
78
import android.widget.Toast;
Michael Kolb's avatar
Michael Kolb committed
79

80
import com.android.browser.IntentHandler.UrlData;
John Reck's avatar
John Reck committed
81
import com.android.browser.UI.ComboViews;
82 83
import com.android.browser.UI.DropdownChangeListener;
import com.android.browser.provider.BrowserProvider;
John Reck's avatar
John Reck committed
84
import com.android.browser.provider.BrowserProvider2.Thumbnails;
John Reck's avatar
John Reck committed
85
import com.android.browser.provider.SnapshotProvider.Snapshots;
86 87 88
import com.android.browser.search.SearchEngine;
import com.android.common.Search;

Michael Kolb's avatar
Michael Kolb committed
89 90
import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
John Reck's avatar
John Reck committed
91
import java.util.ArrayList;
Michael Kolb's avatar
Michael Kolb committed
92 93
import java.util.Calendar;
import java.util.HashMap;
Michael Kolb's avatar
Michael Kolb committed
94
import java.util.List;
John Reck's avatar
John Reck committed
95
import java.util.Map;
Michael Kolb's avatar
Michael Kolb committed
96 97 98 99 100 101 102 103

/**
 * Controller for browser
 */
public class Controller
        implements WebViewController, UiController {

    private static final String LOGTAG = "Controller";
Michael Kolb's avatar
Michael Kolb committed
104 105
    private static final String SEND_APP_ID_EXTRA =
        "android.speech.extras.SEND_APPLICATION_ID_EXTRA";
Michael Kolb's avatar
Michael Kolb committed
106
    private static final String INCOGNITO_URI = "browser:incognito";
Michael Kolb's avatar
Michael Kolb committed
107

Michael Kolb's avatar
Michael Kolb committed
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

    // public message ids
    public final static int LOAD_URL = 1001;
    public final static int STOP_LOAD = 1002;

    // Message Ids
    private static final int FOCUS_NODE_HREF = 102;
    private static final int RELEASE_WAKELOCK = 107;

    static final int UPDATE_BOOKMARK_THUMBNAIL = 108;

    private static final int OPEN_BOOKMARKS = 201;

    private static final int EMPTY_MENU = -1;

    // activity requestCode
John Reck's avatar
John Reck committed
124
    final static int COMBO_VIEW = 1;
Michael Kolb's avatar
Michael Kolb committed
125 126
    final static int PREFERENCES_PAGE = 3;
    final static int FILE_SELECTED = 4;
127 128
    final static int AUTOFILL_SETUP = 5;

Michael Kolb's avatar
Michael Kolb committed
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
    private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes

    // As the ids are dynamically created, we can't guarantee that they will
    // be in sequence, so this static array maps ids to a window number.
    final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
    { R.id.window_one_menu_id, R.id.window_two_menu_id,
      R.id.window_three_menu_id, R.id.window_four_menu_id,
      R.id.window_five_menu_id, R.id.window_six_menu_id,
      R.id.window_seven_menu_id, R.id.window_eight_menu_id };

    // "source" parameter for Google search through search key
    final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
    // "source" parameter for Google search through simplily type
    final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";

144 145 146
    // "no-crash-recovery" parameter in intetnt to suppress crash recovery
    final static String NO_CRASH_RECOVERY = "no-crash-recovery";

Michael Kolb's avatar
Michael Kolb committed
147 148 149 150 151 152 153 154 155 156 157 158 159
    private Activity mActivity;
    private UI mUi;
    private TabControl mTabControl;
    private BrowserSettings mSettings;
    private WebViewFactory mFactory;

    private WakeLock mWakeLock;

    private UrlHandler mUrlHandler;
    private UploadHandler mUploadHandler;
    private IntentHandler mIntentHandler;
    private PageDialogsHandler mPageDialogsHandler;
    private NetworkStateHandler mNetworkHandler;
160
    private NfcHandler mNfcHandler;
Michael Kolb's avatar
Michael Kolb committed
161

162 163
    private Message mAutoFillSetupMessage;

Michael Kolb's avatar
Michael Kolb committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    private boolean mShouldShowErrorConsole;

    private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;

    // FIXME, temp address onPrepareMenu performance problem.
    // When we move everything out of view, we should rewrite this.
    private int mCurrentMenuState = 0;
    private int mMenuState = R.id.MAIN_MENU;
    private int mOldMenuState = EMPTY_MENU;
    private Menu mCachedMenu;

    private boolean mMenuIsDown;

    // For select and find, we keep track of the ActionMode so that
    // finish() can be called as desired.
    private ActionMode mActionMode;

    /**
     * Only meaningful when mOptionsMenuOpen is true.  This variable keeps track
     * of whether the configuration has changed.  The first onMenuOpened call
     * after a configuration change is simply a reopening of the same menu
     * (i.e. mIconView did not change).
     */
    private boolean mConfigChanged;

    /**
     * Keeps track of whether the options menu is open. This is important in
     * determining whether to show or hide the title bar overlay
     */
    private boolean mOptionsMenuOpen;

    /**
     * Whether or not the options menu is in its bigger, popup menu form. When
     * true, we want the title bar overlay to be gone. When false, we do not.
     * Only meaningful if mOptionsMenuOpen is true.
     */
    private boolean mExtendedMenuOpen;

    private boolean mInLoad;

    private boolean mActivityPaused = true;
    private boolean mLoadStopped;

    private Handler mHandler;
208 209 210
    // Checks to see when the bookmarks database has changed, and updates the
    // Tabs' notion of whether they represent bookmarked sites.
    private ContentObserver mBookmarksObserver;
211
    private CrashRecoveryHandler mCrashRecoveryHandler;
Michael Kolb's avatar
Michael Kolb committed
212

John Reck's avatar
John Reck committed
213 214
    private boolean mSimulateActionBarOverlayMode;

Michael Kolb's avatar
Michael Kolb committed
215 216
    private boolean mBlockEvents;

John Reck's avatar
John Reck committed
217
    public Controller(Activity browser, boolean preloadCrashState) {
Michael Kolb's avatar
Michael Kolb committed
218 219 220 221
        mActivity = browser;
        mSettings = BrowserSettings.getInstance();
        mTabControl = new TabControl(this);
        mSettings.setController(this);
John Reck's avatar
John Reck committed
222
        mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this);
John Reck's avatar
John Reck committed
223 224 225
        if (preloadCrashState) {
            mCrashRecoveryHandler.preloadCrashState();
        }
Michael Kolb's avatar
Michael Kolb committed
226
        mFactory = new BrowserWebViewFactory(browser);
Michael Kolb's avatar
Michael Kolb committed
227 228 229 230

        mUrlHandler = new UrlHandler(this);
        mIntentHandler = new IntentHandler(mActivity, this);
        mPageDialogsHandler = new PageDialogsHandler(mActivity, this);
231
        mNfcHandler = new NfcHandler(mActivity, this);
Michael Kolb's avatar
Michael Kolb committed
232 233

        startHandler();
234 235 236 237 238 239 240 241 242 243 244 245
        mBookmarksObserver = new ContentObserver(mHandler) {
            @Override
            public void onChange(boolean selfChange) {
                int size = mTabControl.getTabCount();
                for (int i = 0; i < size; i++) {
                    mTabControl.getTab(i).updateBookmarkedStatus();
                }
            }

        };
        browser.getContentResolver().registerContentObserver(
                BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver);
Michael Kolb's avatar
Michael Kolb committed
246 247 248 249 250 251 252

        mNetworkHandler = new NetworkStateHandler(mActivity, this);
        // Start watching the default geolocation permissions
        mSystemAllowGeolocationOrigins =
                new SystemAllowGeolocationOrigins(mActivity.getApplicationContext());
        mSystemAllowGeolocationOrigins.start();

253
        openIconDatabase();
John Reck's avatar
John Reck committed
254
        mSimulateActionBarOverlayMode = !BrowserActivity.isTablet(mActivity);
Michael Kolb's avatar
Michael Kolb committed
255 256
    }

257
    void start(final Bundle icicle, final Intent intent) {
258 259
        boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false);
        if (icicle != null || noCrashRecovery) {
260 261 262 263 264 265 266
            doStart(icicle, intent);
        } else {
            mCrashRecoveryHandler.startRecovery(intent);
        }
    }

    void doStart(final Bundle icicle, final Intent intent) {
Michael Kolb's avatar
Michael Kolb committed
267 268 269 270 271 272 273 274 275
        // Unless the last browser usage was within 24 hours, destroy any
        // remaining incognito tabs.

        Calendar lastActiveDate = icicle != null ?
                (Calendar) icicle.getSerializable("lastActiveDate") : null;
        Calendar today = Calendar.getInstance();
        Calendar yesterday = Calendar.getInstance();
        yesterday.add(Calendar.DATE, -1);

276
        final boolean restoreIncognitoTabs = !(lastActiveDate == null
Michael Kolb's avatar
Michael Kolb committed
277
            || lastActiveDate.before(yesterday)
Michael Kolb's avatar
Michael Kolb committed
278
            || lastActiveDate.after(today));
Michael Kolb's avatar
Michael Kolb committed
279

280
        // Find out if we will restore any state and remember the tab.
Michael Kolb's avatar
Michael Kolb committed
281
        final long currentTabId =
282 283
                mTabControl.canRestoreState(icicle, restoreIncognitoTabs);

Michael Kolb's avatar
Michael Kolb committed
284
        if (currentTabId == -1) {
285 286 287
            // Not able to restore so we go ahead and clear session cookies.  We
            // must do this before trying to login the user as we don't want to
            // clear any session cookies set during login.
288
            CookieManager.getInstance().removeSessionCookie();
289 290
        }

Patrick Scott's avatar
Patrick Scott committed
291
        GoogleAccountLogin.startLoginIfNeeded(mActivity,
292 293
                new Runnable() {
                    @Override public void run() {
Michael Kolb's avatar
Michael Kolb committed
294
                        onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs);
295 296 297
                    }
                });
    }
298

Michael Kolb's avatar
Michael Kolb committed
299
    private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId,
300
            boolean restoreIncognitoTabs) {
Michael Kolb's avatar
Michael Kolb committed
301
        if (currentTabId == -1) {
John Reck's avatar
John Reck committed
302
            BackgroundHandler.execute(new PruneThumbnails(mActivity, null));
Michael Kolb's avatar
Michael Kolb committed
303 304 305 306 307
            final Bundle extra = intent.getExtras();
            // Create an initial tab.
            // If the intent is ACTION_VIEW and data is not null, the Browser is
            // invoked to view the content by another application. In this case,
            // the tab will be close when exit.
Michael Kolb's avatar
Michael Kolb committed
308
            UrlData urlData = IntentHandler.getUrlDataFromIntent(intent);
Michael Kolb's avatar
Michael Kolb committed
309 310 311 312 313 314 315 316 317
            Tab t = null;
            if (urlData.isEmpty()) {
                t = openTabToHomePage();
            } else {
                t = openTab(urlData);
            }
            if (t != null) {
                t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID));
            }
Michael Kolb's avatar
Michael Kolb committed
318 319 320 321 322 323 324
            WebView webView = t.getWebView();
            if (extra != null) {
                int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
                if (scale > 0 && scale <= 1000) {
                    webView.setInitialScale(scale);
                }
            }
John Reck's avatar
John Reck committed
325
            mUi.updateTabs(mTabControl.getTabs());
Michael Kolb's avatar
Michael Kolb committed
326
        } else {
Michael Kolb's avatar
Michael Kolb committed
327
            mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs,
328
                    mUi.needsRestoreAllTabs());
John Reck's avatar
John Reck committed
329 330 331 332 333 334 335
            List<Tab> tabs = mTabControl.getTabs();
            ArrayList<Long> restoredTabs = new ArrayList<Long>(tabs.size());
            for (Tab t : tabs) {
                restoredTabs.add(t.getId());
            }
            BackgroundHandler.execute(new PruneThumbnails(mActivity, restoredTabs));
            mUi.updateTabs(tabs);
Michael Kolb's avatar
Michael Kolb committed
336 337 338
            // TabControl.restoreState() will create a new tab even if
            // restoring the state fails.
            setActiveTab(mTabControl.getCurrentTab());
John Reck's avatar
John Reck committed
339 340
            // Handle the intent
            mIntentHandler.onNewIntent(intent);
Michael Kolb's avatar
Michael Kolb committed
341 342
        }
        // Read JavaScript flags if it exists.
John Reck's avatar
John Reck committed
343
        String jsFlags = getSettings().getJsEngineFlags();
Michael Kolb's avatar
Michael Kolb committed
344 345 346
        if (jsFlags.trim().length() != 0) {
            getCurrentWebView().setJsFlags(jsFlags);
        }
John Reck's avatar
John Reck committed
347 348 349
        if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) {
            bookmarksOrHistoryPicker(false);
        }
Michael Kolb's avatar
Michael Kolb committed
350 351
    }

John Reck's avatar
John Reck committed
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
    private static class PruneThumbnails implements Runnable {
        private Context mContext;
        private List<Long> mIds;

        PruneThumbnails(Context context, List<Long> preserveIds) {
            mContext = context.getApplicationContext();
            mIds = preserveIds;
        }

        @Override
        public void run() {
            ContentResolver cr = mContext.getContentResolver();
            if (mIds == null || mIds.size() == 0) {
                cr.delete(Thumbnails.CONTENT_URI, null, null);
            } else {
                int length = mIds.size();
                StringBuilder where = new StringBuilder();
                where.append(Thumbnails._ID);
                where.append(" not in (");
                for (int i = 0; i < length; i++) {
                    where.append(mIds.get(i));
                    if (i < (length - 1)) {
                        where.append(",");
                    }
                }
                where.append(")");
                cr.delete(Thumbnails.CONTENT_URI, where.toString(), null);
            }
        }

    }

Michael Kolb's avatar
Michael Kolb committed
384 385
    @Override
    public WebViewFactory getWebViewFactory() {
Michael Kolb's avatar
Michael Kolb committed
386 387 388
        return mFactory;
    }

Michael Kolb's avatar
Michael Kolb committed
389 390 391 392 393
    @Override
    public void onSetWebView(Tab tab, WebView view) {
        mUi.onSetWebView(tab, view);
    }

Michael Kolb's avatar
Michael Kolb committed
394 395 396 397 398 399 400 401 402 403
    @Override
    public void createSubWindow(Tab tab) {
        endActionMode();
        WebView mainView = tab.getWebView();
        WebView subView = mFactory.createWebView((mainView == null)
                ? false
                : mainView.isPrivateBrowsingEnabled());
        mUi.createSubWindow(tab, subView);
    }

Michael Kolb's avatar
Michael Kolb committed
404 405 406 407 408
    @Override
    public Context getContext() {
        return mActivity;
    }

Michael Kolb's avatar
Michael Kolb committed
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    @Override
    public Activity getActivity() {
        return mActivity;
    }

    void setUi(UI ui) {
        mUi = ui;
    }

    BrowserSettings getSettings() {
        return mSettings;
    }

    IntentHandler getIntentHandler() {
        return mIntentHandler;
    }

    @Override
    public UI getUi() {
        return mUi;
    }

    int getMaxTabs() {
        return mActivity.getResources().getInteger(R.integer.max_tabs);
    }

    @Override
    public TabControl getTabControl() {
        return mTabControl;
    }

Michael Kolb's avatar
Michael Kolb committed
440 441 442 443 444
    @Override
    public List<Tab> getTabs() {
        return mTabControl.getTabs();
    }

445 446 447 448 449
    // Open the icon database.
    private void openIconDatabase() {
        // We have to call getInstance on the UI thread
        final WebIconDatabase instance = WebIconDatabase.getInstance();
        BackgroundHandler.execute(new Runnable() {
450

451 452 453
            @Override
            public void run() {
                instance.open(mActivity.getDir("icons", 0).getPath());
Michael Kolb's avatar
Michael Kolb committed
454
            }
455
        });
Michael Kolb's avatar
Michael Kolb committed
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
    }

    private void startHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case OPEN_BOOKMARKS:
                        bookmarksOrHistoryPicker(false);
                        break;
                    case FOCUS_NODE_HREF:
                    {
                        String url = (String) msg.getData().get("url");
                        String title = (String) msg.getData().get("title");
471 472
                        String src = (String) msg.getData().get("src");
                        if (url == "") url = src; // use image if no anchor
Michael Kolb's avatar
Michael Kolb committed
473 474 475 476 477 478 479 480 481 482 483
                        if (TextUtils.isEmpty(url)) {
                            break;
                        }
                        HashMap focusNodeMap = (HashMap) msg.obj;
                        WebView view = (WebView) focusNodeMap.get("webview");
                        // Only apply the action if the top window did not change.
                        if (getCurrentTopWebView() != view) {
                            break;
                        }
                        switch (msg.arg1) {
                            case R.id.open_context_menu_id:
John Reck's avatar
John Reck committed
484
                                loadUrlFromContext(url);
Michael Kolb's avatar
Michael Kolb committed
485
                                break;
486
                            case R.id.view_image_context_menu_id:
John Reck's avatar
John Reck committed
487
                                loadUrlFromContext(src);
488
                                break;
489 490
                            case R.id.open_newtab_context_menu_id:
                                final Tab parent = mTabControl.getCurrentTab();
John Reck's avatar
John Reck committed
491 492
                                openTab(url, parent,
                                        !mSettings.openInBackground(), true);
493
                                break;
Michael Kolb's avatar
Michael Kolb committed
494 495 496 497 498
                            case R.id.copy_link_context_menu_id:
                                copy(url);
                                break;
                            case R.id.save_link_context_menu_id:
                            case R.id.download_context_menu_id:
499
                                DownloadHandler.onDownloadStartNoStream(
500 501
                                        mActivity, url, null, null, null,
                                        view.isPrivateBrowsingEnabled());
Michael Kolb's avatar
Michael Kolb committed
502 503 504 505 506 507
                                break;
                        }
                        break;
                    }

                    case LOAD_URL:
John Reck's avatar
John Reck committed
508
                        loadUrlFromContext((String) msg.obj);
Michael Kolb's avatar
Michael Kolb committed
509 510 511 512 513 514 515
                        break;

                    case STOP_LOAD:
                        stopLoading();
                        break;

                    case RELEASE_WAKELOCK:
John Reck's avatar
John Reck committed
516
                        if (mWakeLock != null && mWakeLock.isHeld()) {
Michael Kolb's avatar
Michael Kolb committed
517 518 519 520 521 522 523 524 525
                            mWakeLock.release();
                            // if we reach here, Browser should be still in the
                            // background loading after WAKELOCK_TIMEOUT (5-min).
                            // To avoid burning the battery, stop loading.
                            mTabControl.stopAllLoading();
                        }
                        break;

                    case UPDATE_BOOKMARK_THUMBNAIL:
526 527 528
                        Tab tab = (Tab) msg.obj;
                        if (tab != null) {
                            updateScreenshot(tab);
Michael Kolb's avatar
Michael Kolb committed
529 530 531 532 533 534 535 536
                        }
                        break;
                }
            }
        };

    }

John Reck's avatar
John Reck committed
537
    @Override
538 539 540 541
    public Tab getCurrentTab() {
        return mTabControl.getCurrentTab();
    }

542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    @Override
    public void shareCurrentPage() {
        shareCurrentPage(mTabControl.getCurrentTab());
    }

    private void shareCurrentPage(Tab tab) {
        if (tab != null) {
            sharePage(mActivity, tab.getTitle(),
                    tab.getUrl(), tab.getFavicon(),
                    createScreenshot(tab.getWebView(),
                            getDesiredThumbnailWidth(mActivity),
                            getDesiredThumbnailHeight(mActivity)));
        }
    }

Michael Kolb's avatar
Michael Kolb committed
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    /**
     * Share a page, providing the title, url, favicon, and a screenshot.  Uses
     * an {@link Intent} to launch the Activity chooser.
     * @param c Context used to launch a new Activity.
     * @param title Title of the page.  Stored in the Intent with
     *          {@link Intent#EXTRA_SUBJECT}
     * @param url URL of the page.  Stored in the Intent with
     *          {@link Intent#EXTRA_TEXT}
     * @param favicon Bitmap of the favicon for the page.  Stored in the Intent
     *          with {@link Browser#EXTRA_SHARE_FAVICON}
     * @param screenshot Bitmap of a screenshot of the page.  Stored in the
     *          Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
     */
    static final void sharePage(Context c, String title, String url,
            Bitmap favicon, Bitmap screenshot) {
        Intent send = new Intent(Intent.ACTION_SEND);
        send.setType("text/plain");
        send.putExtra(Intent.EXTRA_TEXT, url);
        send.putExtra(Intent.EXTRA_SUBJECT, title);
        send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
        send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
        try {
            c.startActivity(Intent.createChooser(send, c.getString(
                    R.string.choosertitle_sharevia)));
        } catch(android.content.ActivityNotFoundException ex) {
            // if no app handles it, do nothing
        }
    }

    private void copy(CharSequence text) {
        ClipboardManager cm = (ClipboardManager) mActivity
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setText(text);
    }

    // lifecycle

    protected void onConfgurationChanged(Configuration config) {
        mConfigChanged = true;
        if (mPageDialogsHandler != null) {
            mPageDialogsHandler.onConfigurationChanged(config);
        }
        mUi.onConfigurationChanged(config);
    }

    @Override
    public void handleNewIntent(Intent intent) {
604 605 606
        if (!mUi.isWebShowing()) {
            mUi.showWeb(false);
        }
Michael Kolb's avatar
Michael Kolb committed
607 608 609 610
        mIntentHandler.onNewIntent(intent);
    }

    protected void onPause() {
611 612 613
        if (mUi.isCustomViewShowing()) {
            hideCustomView();
        }
Michael Kolb's avatar
Michael Kolb committed
614 615 616 617 618
        if (mActivityPaused) {
            Log.e(LOGTAG, "BrowserActivity is already paused.");
            return;
        }
        mActivityPaused = true;
Michael Kolb's avatar
Michael Kolb committed
619 620 621 622
        Tab tab = mTabControl.getCurrentTab();
        if (tab != null) {
            tab.pause();
            if (!pauseWebViewTimers(tab)) {
John Reck's avatar
John Reck committed
623 624 625 626 627
                if (mWakeLock == null) {
                    PowerManager pm = (PowerManager) mActivity
                            .getSystemService(Context.POWER_SERVICE);
                    mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
                }
Michael Kolb's avatar
Michael Kolb committed
628 629 630 631
                mWakeLock.acquire();
                mHandler.sendMessageDelayed(mHandler
                        .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
            }
Michael Kolb's avatar
Michael Kolb committed
632 633 634
        }
        mUi.onPause();
        mNetworkHandler.onPause();
635
        mNfcHandler.onPause();
Michael Kolb's avatar
Michael Kolb committed
636 637

        WebView.disablePlatformNotifications();
John Reck's avatar
John Reck committed
638
        mCrashRecoveryHandler.backupState();
639

Michael Kolb's avatar
Michael Kolb committed
640 641
    }

John Reck's avatar
John Reck committed
642
    void onSaveInstanceState(Bundle outState) {
Michael Kolb's avatar
Michael Kolb committed
643 644 645 646 647 648 649
        // the default implementation requires each view to have an id. As the
        // browser handles the state itself and it doesn't use id for the views,
        // don't call the default implementation. Otherwise it will trigger the
        // warning like this, "couldn't save which view has focus because the
        // focused view XXX has no id".

        // Save all the tabs
John Reck's avatar
John Reck committed
650
        mTabControl.saveState(outState);
651 652 653 654
        if (!outState.isEmpty()) {
            // Save time so that we know how old incognito tabs (if any) are.
            outState.putSerializable("lastActiveDate", Calendar.getInstance());
        }
Michael Kolb's avatar
Michael Kolb committed
655 656 657 658 659 660 661 662
    }

    void onResume() {
        if (!mActivityPaused) {
            Log.e(LOGTAG, "BrowserActivity is already resumed.");
            return;
        }
        mActivityPaused = false;
Michael Kolb's avatar
Michael Kolb committed
663 664 665 666 667
        Tab current = mTabControl.getCurrentTab();
        if (current != null) {
            current.resume();
            resumeWebViewTimers(current);
        }
John Reck's avatar
John Reck committed
668
        releaseWakeLock();
669

Michael Kolb's avatar
Michael Kolb committed
670 671
        mUi.onResume();
        mNetworkHandler.onResume();
672
        mNfcHandler.onResume();
Michael Kolb's avatar
Michael Kolb committed
673 674 675
        WebView.enablePlatformNotifications();
    }

John Reck's avatar
John Reck committed
676 677 678 679 680 681 682
    private void releaseWakeLock() {
        if (mWakeLock != null && mWakeLock.isHeld()) {
            mHandler.removeMessages(RELEASE_WAKELOCK);
            mWakeLock.release();
        }
    }

Michael Kolb's avatar
Michael Kolb committed
683
    /**
684
     * resume all WebView timers using the WebView instance of the given tab
Michael Kolb's avatar
Michael Kolb committed
685 686 687
     * @param tab guaranteed non-null
     */
    private void resumeWebViewTimers(Tab tab) {
Michael Kolb's avatar
Michael Kolb committed
688 689 690 691
        boolean inLoad = tab.inPageLoad();
        if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) {
            CookieSyncManager.getInstance().startSync();
            WebView w = tab.getWebView();
Mathew Inwood's avatar
Mathew Inwood committed
692
            WebViewTimersControl.getInstance().onBrowserActivityResume(w);
Michael Kolb's avatar
Michael Kolb committed
693 694 695
        }
    }

Michael Kolb's avatar
Michael Kolb committed
696 697 698 699 700 701 702 703 704
    /**
     * Pause all WebView timers using the WebView of the given tab
     * @param tab
     * @return true if the timers are paused or tab is null
     */
    private boolean pauseWebViewTimers(Tab tab) {
        if (tab == null) {
            return true;
        } else if (!tab.inPageLoad()) {
Michael Kolb's avatar
Michael Kolb committed
705
            CookieSyncManager.getInstance().stopSync();
Mathew Inwood's avatar
Mathew Inwood committed
706
            WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView());
Michael Kolb's avatar
Michael Kolb committed
707 708
            return true;
        }
Michael Kolb's avatar
Michael Kolb committed
709
        return false;
Michael Kolb's avatar
Michael Kolb committed
710 711 712
    }

    void onDestroy() {
John Reck's avatar
John Reck committed
713
        if (mUploadHandler != null && !mUploadHandler.handled()) {
Michael Kolb's avatar
Michael Kolb committed
714 715 716 717 718 719 720 721 722 723 724
            mUploadHandler.onResult(Activity.RESULT_CANCELED, null);
            mUploadHandler = null;
        }
        if (mTabControl == null) return;
        mUi.onDestroy();
        // Remove the current tab and sub window
        Tab t = mTabControl.getCurrentTab();
        if (t != null) {
            dismissSubWindow(t);
            removeTab(t);
        }
725
        mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver);
Michael Kolb's avatar
Michael Kolb committed
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
        // Destroy all the tabs
        mTabControl.destroy();
        WebIconDatabase.getInstance().close();
        // Stop watching the default geolocation permissions
        mSystemAllowGeolocationOrigins.stop();
        mSystemAllowGeolocationOrigins = null;
    }

    protected boolean isActivityPaused() {
        return mActivityPaused;
    }

    protected void onLowMemory() {
        mTabControl.freeMemory();
    }

    @Override
    public boolean shouldShowErrorConsole() {
        return mShouldShowErrorConsole;
    }

    protected void setShouldShowErrorConsole(boolean show) {
        if (show == mShouldShowErrorConsole) {
            // Nothing to do.
            return;
        }
        mShouldShowErrorConsole = show;
        Tab t = mTabControl.getCurrentTab();
        if (t == null) {
            // There is no current tab so we cannot toggle the error console
            return;
        }
        mUi.setShouldShowErrorConsole(t, show);
    }

    @Override
    public void stopLoading() {
        mLoadStopped = true;
        Tab tab = mTabControl.getCurrentTab();
        WebView w = getCurrentTopWebView();
        w.stopLoading();
        mUi.onPageStopped(tab);
    }

    boolean didUserStopLoading() {
        return mLoadStopped;
    }

    // WebViewController

    @Override
777
    public void onPageStarted(Tab tab, WebView view, Bitmap favicon) {
Michael Kolb's avatar
Michael Kolb committed
778 779 780 781 782 783

        // 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,
784
                tab);
Michael Kolb's avatar
Michael Kolb committed
785 786 787 788 789 790 791 792 793 794 795 796 797

        // reset sync timer to avoid sync starts during loading a page
        CookieSyncManager.getInstance().resetSync();

        if (!mNetworkHandler.isNetworkUp()) {
            view.setNetworkAvailable(false);
        }

        // when BrowserActivity just starts, onPageStarted may be called before
        // onResume as it is triggered from onCreate. Call resumeWebViewTimers
        // to start the timer. As we won't switch tabs while an activity is in
        // pause state, we can ensure calling resume and pause in pair.
        if (mActivityPaused) {
Michael Kolb's avatar
Michael Kolb committed
798
            resumeWebViewTimers(tab);
Michael Kolb's avatar
Michael Kolb committed
799 800 801 802 803 804 805
        }
        mLoadStopped = false;
        if (!mNetworkHandler.isNetworkUp()) {
            mNetworkHandler.createAndShowNetworkDialog();
        }
        endActionMode();

John Reck's avatar
John Reck committed
806
        mUi.onTabDataChanged(tab);
Michael Kolb's avatar
Michael Kolb committed
807

808
        String url = tab.getUrl();
Michael Kolb's avatar
Michael Kolb committed
809 810 811 812 813 814 815 816 817 818 819 820 821
        // update the bookmark database for favicon
        maybeUpdateFavicon(tab, null, url, favicon);

        Performance.tracePageStart(url);

        // Performance probe
        if (false) {
            Performance.onPageStarted();
        }

    }

    @Override
822
    public void onPageFinished(Tab tab) {
John Reck's avatar
John Reck committed
823
        mUi.onTabDataChanged(tab);
824
        if (!tab.isPrivateBrowsingEnabled()
John Reck's avatar
John Reck committed
825 826
                && !TextUtils.isEmpty(tab.getUrl())
                && !tab.isSnapshot()) {
John Reck's avatar
John Reck committed
827 828 829
            // 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.
Michael Kolb's avatar
Michael Kolb committed
830 831
            if (tab.inForeground() && !didUserStopLoading()
                    || !tab.inForeground()) {
John Reck's avatar
John Reck committed
832 833 834 835 836
                if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) {
                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
                            UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab),
                            500);
                }
Michael Kolb's avatar
Michael Kolb committed
837 838 839 840
            }
        }
        // pause the WebView timer and release the wake lock if it is finished
        // while BrowserActivity is in pause state.
Michael Kolb's avatar
Michael Kolb committed
841
        if (mActivityPaused && pauseWebViewTimers(tab)) {
John Reck's avatar
John Reck committed
842
            releaseWakeLock();
Michael Kolb's avatar
Michael Kolb committed
843
        }
844

Michael Kolb's avatar
Michael Kolb committed
845 846
        // Performance probe
        if (false) {
847
            Performance.onPageFinished(tab.getUrl());
Michael Kolb's avatar
Michael Kolb committed
848 849 850 851 852 853
         }

        Performance.tracePageFinished();
    }

    @Override
John Reck's avatar
John Reck committed
854 855
    public void onProgressChanged(Tab tab) {
        int newProgress = tab.getLoadProgress();
Michael Kolb's avatar
Michael Kolb committed
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878

        if (newProgress == 100) {
            CookieSyncManager.getInstance().sync();
            // onProgressChanged() may continue to be called after the main
            // frame has finished loading, as any remaining sub frames continue
            // to load. We'll only get called once though with newProgress as
            // 100 when everything is loaded. (onPageFinished is called once
            // when the main frame completes loading regardless of the state of
            // any sub frames so calls to onProgressChanges may continue after
            // onPageFinished has executed)
            if (mInLoad) {
                mInLoad = false;
                updateInLoadMenuItems(mCachedMenu);
            }
        } else {
            if (!mInLoad) {
                // onPageFinished may have already been called but a subframe is
                // still loading and updating the progress. Reset mInLoad and
                // update the menu items.
                mInLoad = true;
                updateInLoadMenuItems(mCachedMenu);
            }
        }
John Reck's avatar
John Reck committed
879 880 881 882 883 884
        mUi.onProgressChanged(tab);
    }

    @Override
    public void onUpdatedLockIcon(Tab tab) {
        mUi.onTabDataChanged(tab);
Michael Kolb's avatar
Michael Kolb committed
885 886 887 888
    }

    @Override
    public void onReceivedTitle(Tab tab, final String title) {
John Reck's avatar
John Reck committed
889
        mUi.onTabDataChanged(tab);
890
        final String pageUrl = tab.getOriginalUrl();
891
        if (TextUtils.isEmpty(pageUrl) || pageUrl.length()
Michael Kolb's avatar
Michael Kolb committed
892 893 894 895 896
                >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
            return;
        }
        // Update the title in the history database if not in private browsing mode
        if (!tab.isPrivateBrowsingEnabled()) {
John Reck's avatar
John Reck committed
897
            DataController.getInstance(mActivity).updateHistoryTitle(pageUrl, title);
Michael Kolb's avatar
Michael Kolb committed
898 899 900 901 902
        }
    }

    @Override
    public void onFavicon(Tab tab, WebView view, Bitmap icon) {
John Reck's avatar
John Reck committed
903
        mUi.onTabDataChanged(tab);
Michael Kolb's avatar
Michael Kolb committed
904 905 906 907
        maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon);
    }

    @Override
908 909
    public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) {
        return mUrlHandler.shouldOverrideUrlLoading(tab, view, url);
Michael Kolb's avatar
Michael Kolb committed
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
    }

    @Override
    public boolean shouldOverrideKeyEvent(KeyEvent event) {
        if (mMenuIsDown) {
            // only check shortcut key when MENU is held
            return mActivity.getWindow().isShortcutKey(event.getKeyCode(),
                    event);
        } else {
            return false;
        }
    }

    @Override
    public void onUnhandledKeyEvent(KeyEvent event) {
        if (!isActivityPaused()) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                mActivity.onKeyDown(event.getKeyCode(), event);
            } else {
                mActivity.onKeyUp(event.getKeyCode(), event);
            }
        }
    }

    @Override
935
    public void doUpdateVisitedHistory(Tab tab, boolean isReload) {
Michael Kolb's avatar
Michael Kolb committed
936 937
        // Don't save anything in private browsing mode
        if (tab.isPrivateBrowsingEnabled()) return;
938
        String url = tab.getOriginalUrl();
Michael Kolb's avatar
Michael Kolb committed
939

940 941
        if (TextUtils.isEmpty(url)
                || url.regionMatches(true, 0, "about:", 0, 6)) {
Michael Kolb's avatar
Michael Kolb committed
942 943
            return;
        }
John Reck's avatar
John Reck committed
944
        DataController.getInstance(mActivity).updateVisitedHistory(url);
945 946 947 948 949
        if (!mActivityPaused) {
            // Since we clear the state in onPause, don't backup the current
            // state if we are already paused
            mCrashRecoveryHandler.backupState();
        }
Michael Kolb's avatar
Michael Kolb committed
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
    }

    @Override
    public void getVisitedHistory(final ValueCallback<String[]> callback) {
        AsyncTask<Void, Void, String[]> task =
                new AsyncTask<Void, Void, String[]>() {
            @Override
            public String[] doInBackground(Void... unused) {
                return Browser.getVisitedHistory(mActivity.getContentResolver());
            }
            @Override
            public void onPostExecute(String[] result) {
                callback.onReceiveValue(result);
            }
        };
        task.execute();
    }

    @Override
    public void onReceivedHttpAuthRequest(Tab tab, WebView view,
            final HttpAuthHandler handler, final String host,
            final String realm) {
        String username = null;
        String password = null;

        boolean reuseHttpAuthUsernamePassword
                = handler.useHttpAuthUsernamePassword();

        if (reuseHttpAuthUsernamePassword && view != null) {
            String[] credentials = view.getHttpAuthUsernamePassword(host, realm);
            if (credentials != null && credentials.length == 2) {
                username = credentials[0];
                password = credentials[1];
            }
        }

        if (username != null && password != null) {
            handler.proceed(username, password);
        } else {
989
            if (tab.inForeground() && !handler.suppressDialog()) {
Michael Kolb's avatar
Michael Kolb committed
990 991 992 993 994 995 996 997 998 999
                mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm);
            } else {
                handler.cancel();
            }
        }
    }

    @Override
    public void onDownloadStart(Tab tab, String url, String userAgent,
            String contentDisposition, String mimetype, long contentLength) {
1000
        WebView w = tab.getWebView();
1001
        DownloadHandler.onDownloadStart(mActivity, url, userAgent,
1002 1003
                contentDisposition, mimetype, w.isPrivateBrowsingEnabled());
        if (w.copyBackForwardList().getSize() == 0) {
Michael Kolb's avatar
Michael Kolb committed
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
            // This Tab was opened for the sole purpose of downloading a
            // file. Remove it.
            if (tab == mTabControl.getCurrentTab()) {
                // In this case, the Tab is still on top.
                goBackOnePageOrQuit();
            } else {
                // In this case, it is not.
                closeTab(tab);
            }
        }
    }

    @Override
    public Bitmap getDefaultVideoPoster() {
        return mUi.getDefaultVideoPoster();
    }

    @Override
    public View getVideoLoadingProgressView() {
        return mUi.getVideoLoadingProgressView();
    }

    @Override
    public void showSslCertificateOnError(WebView view, SslErrorHandler handler,
            SslError error) {
        mPageDialogsHandler.showSSLCertificateOnError(view, handler, error);
    }

Patrick Scott's avatar
Patrick Scott committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    @Override
    public void showAutoLogin(Tab tab) {
        assert tab.inForeground();
        // Update the title bar to show the auto-login request.
        mUi.showAutoLogin(tab);
    }

    @Override
    public void hideAutoLogin(Tab tab) {
        assert tab.inForeground();
        mUi.hideAutoLogin(tab);
    }

Michael Kolb's avatar
Michael Kolb committed
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
    // helper method

    /*
     * Update the favorites icon if the private browsing isn't enabled and the
     * icon is valid.
     */
    private void maybeUpdateFavicon(Tab tab, final String originalUrl,
            final String url, Bitmap favicon) {
        if (favicon == null) {
            return;
        }
        if (!tab.isPrivateBrowsingEnabled()) {
            Bookmarks.updateFavicon(mActivity
                    .getContentResolver(), originalUrl, url, favicon);
        }
    }

1062 1063
    @Override
    public void bookmarkedStatusHasChanged(Tab tab) {
1064
        // TODO: Switch to using onTabDataChanged after b/3262950 is fixed
1065 1066 1067
        mUi.bookmarkedStatusHasChanged(tab);
    }

Michael Kolb's avatar
Michael Kolb committed
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    // end WebViewController

    protected void pageUp() {
        getCurrentTopWebView().pageUp(false);
    }

    protected void pageDown() {
        getCurrentTopWebView().pageDown(false);
    }

    // callback from phone title bar
    public void editUrl() {
        if (mOptionsMenuOpen) mActivity.closeOptionsMenu();
Michael Kolb's avatar
Michael Kolb committed
1081
        mUi.editUrl(false);
Michael Kolb's avatar
Michael Kolb committed
1082 1083
    }

Michael Kolb's avatar
Michael Kolb committed
1084 1085 1086 1087 1088 1089 1090
    public void startVoiceSearch() {
        Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                mActivity.getComponentName().flattenToString());
        intent.putExtra(SEND_APP_ID_EXTRA, false);
Michael Kolb's avatar
Michael Kolb committed
1091
        intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true);
Michael Kolb's avatar
Michael Kolb committed
1092 1093 1094
        mActivity.startActivity(intent);
    }

Michael Kolb's avatar
Michael Kolb committed
1095 1096 1097
    @Override
    public void activateVoiceSearchMode(String title, List<String> results) {
        mUi.showVoiceTitleBar(title, results);
Michael Kolb's avatar
Michael Kolb committed
1098 1099 1100 1101 1102 1103
    }

    public void revertVoiceSearchMode(Tab tab) {
        mUi.revertVoiceTitleBar(tab);
    }

Michael Kolb's avatar
Michael Kolb committed
1104
    public boolean supportsVoiceSearch() {
John Reck's avatar
John Reck committed
1105
        SearchEngine searchEngine = getSettings().getSearchEngine();
Michael Kolb's avatar
Michael Kolb committed
1106 1107 1108
        return (searchEngine != null && searchEngine.supportsVoiceSearch());
    }

1109
    public void showCustomView(Tab tab, View view, int requestedOrientation,
Michael Kolb's avatar
Michael Kolb committed
1110 1111 1112 1113 1114 1115
            WebChromeClient.CustomViewCallback callback) {
        if (tab.inForeground()) {
            if (mUi.isCustomViewShowing()) {
                callback.onCustomViewHidden();
                return;
            }
1116
            mUi.showCustomView(view, requestedOrientation, callback);
Michael Kolb's avatar
Michael Kolb committed
1117 1118 1119 1120
            // Save the menu state and set it to empty while the custom
            // view is showing.
            mOldMenuState = mMenuState;
            mMenuState = EMPTY_MENU;
1121
            mActivity.invalidateOptionsMenu();
Michael Kolb's avatar
Michael Kolb committed
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
        }
    }

    @Override
    public void hideCustomView() {
        if (mUi.isCustomViewShowing()) {
            mUi.onHideCustomView();
            // Reset the old menu state.
            mMenuState = mOldMenuState;
            mOldMenuState = EMPTY_MENU;
1132
            mActivity.invalidateOptionsMenu();
Michael Kolb's avatar
Michael Kolb committed
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
        }
    }

    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        if (getCurrentTopWebView() == null) return;
        switch (requestCode) {
            case PREFERENCES_PAGE:
                if (resultCode == Activity.RESULT_OK && intent != null) {
                    String action = intent.getStringExtra(Intent.EXTRA_TEXT);
John Reck's avatar
John Reck committed
1143
                    if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) {
Michael Kolb's avatar
Michael Kolb committed
1144 1145 1146 1147 1148
                        mTabControl.removeParentChildRelationShips();
                    }
                }
                break;
            case FILE_SELECTED:
1149
                // Chose a file from the file picker.
John Reck's avatar
John Reck committed
1150
                if (null == mUploadHandler) break;
Michael Kolb's avatar
Michael Kolb committed
1151 1152
                mUploadHandler.onResult(resultCode, intent);
                break;
1153 1154 1155 1156 1157 1158 1159 1160 1161
            case AUTOFILL_SETUP:
                // Determine whether a profile was actually set up or not
                // and if so, send the message back to the WebTextView to
                // fill the form with the new profile.
                if (getSettings().getAutoFillProfile() != null) {
                    mAutoFillSetupMessage.sendToTarget();
                    mAutoFillSetupMessage = null;
                }
                break;
John Reck's avatar
John Reck committed
1162 1163 1164 1165
            case COMBO_VIEW:
                if (intent == null || resultCode != Activity.RESULT_OK) {
                    break;
                }
1166
                mUi.showWeb(false);
John Reck's avatar
John Reck committed
1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
                if (Intent.ACTION_VIEW.equals(intent.getAction())) {
                    Tab t = getCurrentTab();
                    Uri uri = intent.getData();
                    loadUrl(t, uri.toString());
                } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_ALL)) {
                    String[] urls = intent.getStringArrayExtra(
                            ComboViewActivity.EXTRA_OPEN_ALL);
                    Tab parent = getCurrentTab();
                    for (String url : urls) {
                        parent = openTab(url, parent,
                                !mSettings.openInBackground(), true);
                    }
                } else if (intent.hasExtra(ComboViewActivity.EXTRA_OPEN_SNAPSHOT)) {
                    long id = intent.getLongExtra(
                            ComboViewActivity.EXTRA_OPEN_SNAPSHOT, -1);
                    if (id >= 0) {
                        createNewSnapshotTab(id, true);
                    }
                }
                break;
Michael Kolb's avatar
Michael Kolb committed
1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
            default:
                break;
        }
        getCurrentTopWebView().requestFocus();
    }

    /**
     * Open the Go page.
     * @param startWithHistory If true, open starting on the history tab.
     *                         Otherwise, start with the bookmarks tab.
     */
    @Override
    public void bookmarksOrHistoryPicker(boolean startWithHistory) {
        if (mTabControl.getCurrentWebView() == null) {
            return;
        }
1203 1204 1205 1206
        // clear action mode
        if (isInCustomActionMode()) {
            endActionMode();
        }
Michael Kolb's avatar
Michael Kolb committed
1207 1208 1209 1210
        Bundle extras = new Bundle();
        // Disable opening in a new window if we have maxed out the windows
        extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW,
                !mTabControl.canCreateNewTab());
John Reck's avatar
John Reck committed
1211 1212
        mUi.showComboView(startWithHistory
                ? ComboViews.History : ComboViews.Bookmarks, extras);
Michael Kolb's avatar
Michael Kolb committed
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    }

    // combo view callbacks

    /**
     * callback from ComboPage when clear history is requested
     */
    public void onRemoveParentChildRelationships() {
        mTabControl.removeParentChildRelationShips();
    }

    // key handling
    protected void onBackKey() {
        if (!mUi.onBackKey()) {
            WebView subwindow = mTabControl.getCurrentSubWindow();
            if (subwindow != null) {
                if (subwindow.canGoBack()) {
                    subwindow.goBack();
                } else {
                    dismissSubWindow(mTabControl.getCurrentTab());
                }
            } else {
                goBackOnePageOrQuit();
            }
        }
    }

1240 1241
    protected boolean onMenuKey() {
        return mUi.onMenuKey();
1242 1243
    }

Michael Kolb's avatar
Michael Kolb committed
1244 1245 1246 1247
    // menu handling and state
    // TODO: maybe put into separate handler

    protected boolean onCreateOptionsMenu(Menu menu) {
1248 1249 1250
        if (mMenuState == EMPTY_MENU) {
            return false;
        }
Michael Kolb's avatar
Michael Kolb committed
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
        MenuInflater inflater = mActivity.getMenuInflater();
        inflater.inflate(R.menu.browser, menu);
        updateInLoadMenuItems(menu);
        // hold on to the menu reference here; it is used by the page callbacks
        // to update the menu based on loading state
        mCachedMenu = menu;
        return true;
    }

    protected void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
John Reck's avatar
John Reck committed
1262
        if (v instanceof TitleBar) {
Michael Kolb's avatar
Michael Kolb committed
1263 1264 1265 1266 1267
            return;
        }
        if (!(v instanceof WebView)) {
            return;
        }
1268
        final WebView webview = (WebView) v;
Michael Kolb's avatar
Michael Kolb committed
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        WebView.HitTestResult result = webview.getHitTestResult();
        if (result == null) {
            return;
        }

        int type = result.getType();
        if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
            Log.w(LOGTAG,
                    "We should not show context menu when nothing is touched");
            return;
        }
        if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
            // let TextView handles context menu
            return;
        }

        // Note, http://b/issue?id=1106666 is requesting that
        // an inflated menu can be used again. This is not available
        // yet, so inflate each time (yuk!)
        MenuInflater inflater = mActivity.getMenuInflater();
        inflater.inflate(R.menu.browsercontext, menu);

        // Show the correct menu group
        final String extra = result.getExtra();
        menu.setGroupVisible(R.id.PHONE_MENU,
                type == WebView.HitTestResult.PHONE_TYPE);
        menu.setGroupVisible(R.id.EMAIL_MENU,
                type == WebView.HitTestResult.EMAIL_TYPE);
        menu.setGroupVisible(R.id.GEO_MENU,
                type == WebView.HitTestResult.GEO_TYPE);
        menu.setGroupVisible(R.id.IMAGE_MENU,
                type == WebView.HitTestResult.IMAGE_TYPE
                || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
        menu.setGroupVisible(R.id.ANCHOR_MENU,
                type == WebView.HitTestResult.SRC_ANCHOR_TYPE
                || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
Cary Clark's avatar
Cary Clark committed
1305 1306 1307 1308 1309 1310 1311 1312 1313
        boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE
                || type == WebView.HitTestResult.PHONE_TYPE
                || type == WebView.HitTestResult.EMAIL_TYPE
                || type == WebView.HitTestResult.GEO_TYPE;
        menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText);
        if (hitText) {
            menu.findItem(R.id.select_text_menu_id)
                    .setOnMenuItemClickListener(new SelectText(webview));
        }
Michael Kolb's avatar
Michael Kolb committed
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
        // Setup custom handling depending on the type
        switch (type) {
            case WebView.HitTestResult.PHONE_TYPE:
                menu.setHeaderTitle(Uri.decode(extra));
                menu.findItem(R.id.dial_context_menu_id).setIntent(
                        new Intent(Intent.ACTION_VIEW, Uri
                                .parse(WebView.SCHEME_TEL + extra)));
                Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
                addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
                addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
                menu.findItem(R.id.add_contact_context_menu_id).setIntent(
                        addIntent);
                menu.findItem(R.id.copy_phone_context_menu_id)
                        .setOnMenuItemClickListener(
                        new Copy(extra));
                break;

            case WebView.HitTestResult.EMAIL_TYPE:
                menu.setHeaderTitle(extra);
                menu.findItem(R.id.email_context_menu_id).setIntent(
                        new Intent(Intent.ACTION_VIEW, Uri
                                .parse(WebView.SCHEME_MAILTO + extra)));
                menu.findItem(R.id.copy_mail_context_menu_id)
                        .setOnMenuItemClickListener(
                        new Copy(extra));
                break;

            case WebView.HitTestResult.GEO_TYPE:
                menu.setHeaderTitle(extra);
                menu.findItem(R.id.map_context_menu_id).setIntent(
                        new Intent(Intent.ACTION_VIEW, Uri
                                .parse(WebView.SCHEME_GEO
                                        + URLEncoder.encode(extra))));
                menu.findItem(R.id.copy_geo_context_menu_id)
                        .setOnMenuItemClickListener(
                        new Copy(extra));
                break;

            case WebView.HitTestResult.SRC_ANCHOR_TYPE:
            case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
Michael Kolb's avatar
Michael Kolb committed
1354
                menu.setHeaderTitle(extra);
Michael Kolb's avatar
Michael Kolb committed
1355 1356 1357 1358
                // decide whether to show the open link in new tab option
                boolean showNewTab = mTabControl.canCreateNewTab();
                MenuItem newTabItem
                        = menu.findItem(R.id.open_newtab_context_menu_id);
John Reck's avatar
John Reck committed
1359
                newTabItem.setTitle(getSettings().openInBackground()
Michael Kolb's avatar
Michael Kolb committed
1360 1361
                        ? R.string.contextmenu_openlink_newwindow_background
                        : R.string.contextmenu_openlink_newwindow);
Michael Kolb's avatar
Michael Kolb committed
1362 1363
                newTabItem.setVisible(showNewTab);
                if (showNewTab) {
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
                    if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) {
                        newTabItem.setOnMenuItemClickListener(
                                new MenuItem.OnMenuItemClickListener() {
                                    @Override
                                    public boolean onMenuItemClick(MenuItem item) {
                                        final HashMap<String, WebView> hrefMap =
                                                new HashMap<String, WebView>();
                                        hrefMap.put("webview", webview);
                                        final Message msg = mHandler.obtainMessage(
                                                FOCUS_NODE_HREF,
                                                R.id.open_newtab_context_menu_id,
                                                0, hrefMap);
                                        webview.requestFocusNodeHref(msg);
                                        return true;
Michael Kolb's avatar
Michael Kolb committed
1378
                                    }
1379 1380 1381 1382 1383 1384 1385
                                });
                    } else {
                        newTabItem.setOnMenuItemClickListener(
                                new MenuItem.OnMenuItemClickListener() {
                                    @Override
                                    public boolean onMenuItemClick(MenuItem item) {
                                        final Tab parent = mTabControl.getCurrentTab();
John Reck's avatar
John Reck committed
1386 1387 1388
                                        openTab(extra, parent,
                                                !mSettings.openInBackground(),
                                                true);
1389 1390 1391 1392
                                        return true;
                                    }
                                });
                    }
Michael Kolb's avatar
Michael Kolb committed
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
                }
                if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
                    break;
                }
                // otherwise fall through to handle image part
            case WebView.HitTestResult.IMAGE_TYPE:
                if (type == WebView.HitTestResult.IMAGE_TYPE) {
                    menu.setHeaderTitle(extra);
                }
                menu.findItem(R.id.view_image_context_menu_id).setIntent(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
                menu.findItem(R.id.download_context_menu_id).
1405 1406
                        setOnMenuItemClickListener(
                                new Download(mActivity, extra, webview.isPrivateBrowsingEnabled()));
1407 1408 1409
                menu.findItem(R.id.set_wallpaper_context_menu_id).
                        setOnMenuItemClickListener(new WallpaperHandler(mActivity,
                                extra));
Michael Kolb's avatar
Michael Kolb committed
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
                break;

            default:
                Log.w(LOGTAG, "We should not get here.");
                break;
        }
        //update the ui
        mUi.onContextMenuCreated(menu);
    }

    /**
     * As the menu can be open when loading state changes
     * we must manually update the state of the stop/reload menu
     * item
     */
    private void updateInLoadMenuItems(Menu menu) {
        if (menu == null) {
            return;
        }
        MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
        MenuItem src = mInLoad ?
                menu.findItem(R.id.stop_menu_id):
                menu.findItem(R.id.reload_menu_id);
        if (src != null) {
            dest.setIcon(src.getIcon());
            dest.setTitle(src.getTitle());
        }
    }

John Reck's avatar
John Reck committed
1439
    boolean onPrepareOptionsMenu(Menu menu) {
Michael Kolb's avatar
Michael Kolb committed
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
        // Note: setVisible will decide whether an item is visible; while
        // setEnabled() will decide whether an item is enabled, which also means
        // whether the matching shortcut key will function.
        switch (mMenuState) {
            case EMPTY_MENU:
                if (mCurrentMenuState != mMenuState) {
                    menu.setGroupVisible(R.id.MAIN_MENU, false);
                    menu.setGroupEnabled(R.id.MAIN_MENU, false);
                    menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
                }
                break;
            default:
                if (mCurrentMenuState != mMenuState) {
                    menu.setGroupVisible(R.id.MAIN_MENU, true);
                    menu.setGroupEnabled(R.id.MAIN_MENU, true);
                    menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
                }
Michael Kolb's avatar
Michael Kolb committed
1457
                updateMenuState(getCurrentTab(), menu);
Michael Kolb's avatar
Michael Kolb committed
1458 1459 1460
                break;
        }
        mCurrentMenuState = mMenuState;
Michael Kolb's avatar
Michael Kolb committed
1461
        return mUi.onPrepareOptionsMenu(menu);
Michael Kolb's avatar
Michael Kolb committed
1462 1463
    }

Michael Kolb's avatar
Michael Kolb committed
1464 1465 1466 1467 1468
    @Override
    public void updateMenuState(Tab tab, Menu menu) {
        boolean canGoBack = false;
        boolean canGoForward = false;
        boolean isHome = false;
John Reck's avatar
John Reck committed
1469
        boolean isDesktopUa = false;
Michael Kolb's avatar
Michael Kolb committed
1470 1471 1472 1473
        if (tab != null) {
            canGoBack = tab.canGoBack();
            canGoForward = tab.canGoForward();
            isHome = mSettings.getHomePage().equals(tab.getUrl());
John Reck's avatar
John Reck committed
1474
            isDesktopUa = mSettings.hasDesktopUseragent(tab.getWebView());
Michael Kolb's avatar
Michael Kolb committed
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486
        }
        final MenuItem back = menu.findItem(R.id.back_menu_id);
        back.setEnabled(canGoBack);

        final MenuItem home = menu.findItem(R.id.homepage_menu_id);
        home.setEnabled(!isHome);

        final MenuItem forward = menu.findItem(R.id.forward_menu_id);
        forward.setEnabled(canGoForward);

        final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id);
        final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id);
Michael Kolb's avatar
Michael Kolb committed
1487 1488 1489 1490
        if (source != null && dest != null) {
            dest.setTitle(source.getTitle());
            dest.setIcon(source.getIcon());
        }
Michael Kolb's avatar
Michael Kolb committed
1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508

        // decide whether to show the share link option
        PackageManager pm = mActivity.getPackageManager();
        Intent send = new Intent(Intent.ACTION_SEND);
        send.setType("text/plain");
        ResolveInfo ri = pm.resolveActivity(send,
                PackageManager.MATCH_DEFAULT_ONLY);
        menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);

        boolean isNavDump = mSettings.enableNavDump();
        final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
        nav.setVisible(isNavDump);
        nav.setEnabled(isNavDump);

        boolean showDebugSettings = mSettings.isDebugEnabled();
        final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
        counter.setVisible(showDebugSettings);
        counter.setEnabled(showDebugSettings);
John Reck's avatar
John Reck committed
1509 1510
        final MenuItem uaSwitcher = menu.findItem(R.id.ua_desktop_menu_id);
        uaSwitcher.setChecked(isDesktopUa);
Michael Kolb's avatar
Michael Kolb committed
1511

Michael Kolb's avatar
Michael Kolb committed
1512
        mUi.updateMenuState(tab, menu);
Michael Kolb's avatar
Michael Kolb committed
1513 1514
    }

Michael Kolb's avatar
Michael Kolb committed
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525
    public boolean onOptionsItemSelected(MenuItem item) {
        if (null == getCurrentTopWebView()) {
            return false;
        }
        if (mMenuIsDown) {
            // The shortcut action consumes the MENU. Even if it is still down,
            // it won't trigger the next shortcut action. In the case of the
            // shortcut action triggering a new activity, like Bookmarks, we
            // won't get onKeyUp for MENU. So it is important to reset it here.
            mMenuIsDown = false;
        }
Michael Kolb's avatar
Michael Kolb committed
1526 1527 1528 1529
        if (mUi.onOptionsItemSelected(item)) {
            // ui callback handled it
            return true;
        }
Michael Kolb's avatar
Michael Kolb committed
1530 1531 1532 1533 1534 1535 1536
        switch (item.getItemId()) {
            // -- Main menu
            case R.id.new_tab_menu_id:
                openTabToHomePage();
                break;

            case R.id.incognito_menu_id:
Michael Kolb's avatar
Michael Kolb committed
1537
                openIncognitoTab();
Michael Kolb's avatar
Michael Kolb committed
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
                break;

            case R.id.goto_menu_id:
                editUrl();
                break;

            case R.id.bookmarks_menu_id:
                bookmarksOrHistoryPicker(false);
                break;

            case R.id.add_bookmark_menu_id:
John Reck's avatar
John Reck committed
1549
                mActivity.startActivity(createBookmarkCurrentPageIntent(false));
Michael Kolb's avatar
Michael Kolb committed
1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
                break;

            case R.id.stop_reload_menu_id:
                if (mInLoad) {
                    stopLoading();
                } else {
                    getCurrentTopWebView().reload();
                }
                break;

            case R.id.back_menu_id:
John Reck's avatar
John Reck committed
1561
                getCurrentTab().goBack();
Michael Kolb's avatar
Michael Kolb committed
1562 1563 1564
                break;

            case R.id.forward_menu_id:
John Reck's avatar
John Reck committed
1565
                getCurrentTab().goForward();
Michael Kolb's avatar
Michael Kolb committed
1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
                break;

            case R.id.close_menu_id:
                // Close the subwindow if it exists.
                if (mTabControl.getCurrentSubWindow() != null) {
                    dismissSubWindow(mTabControl.getCurrentTab());
                    break;
                }
                closeCurrentTab();
                break;

            case R.id.homepage_menu_id:
                Tab current = mTabControl.getCurrentTab();
John Reck's avatar
John Reck committed
1579
                loadUrl(current, mSettings.getHomePage());
Michael Kolb's avatar
Michael Kolb committed
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589
                break;

            case R.id.preferences_menu_id:
                Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
                intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
                        getCurrentTopWebView().getUrl());
                mActivity.startActivityForResult(intent, PREFERENCES_PAGE);
                break;

            case R.id.find_menu_id:
1590
                getCurrentTopWebView().showFindDialog(null, true);
Michael Kolb's avatar
Michael Kolb committed
1591 1592
                break;

John Reck's avatar
John Reck committed
1593 1594
            case R.id.save_snapshot_menu_id:
                final Tab source = getTabControl().getCurrentTab();
John Reck's avatar
John Reck committed
1595
                if (source == null) break;
John Reck's avatar
John Reck committed
1596 1597
                final ContentResolver cr = mActivity.getContentResolver();
                final ContentValues values = source.createSnapshotValues();
John Reck's avatar
John Reck committed
1598 1599 1600 1601 1602 1603 1604 1605
                if (values != null) {
                    new AsyncTask<Tab, Void, Long>() {

                        @Override
                        protected Long doInBackground(Tab... params) {
                            Uri result = cr.insert(Snapshots.CONTENT_URI, values);
                            long id = ContentUris.parseId(result);
                            return id;
John Reck's avatar
John Reck committed
1606
                        }
John Reck's avatar
John Reck committed
1607

John Reck's avatar
John Reck committed
1608 1609 1610 1611 1612 1613 1614 1615 1616
                        @Override
                        protected void onPostExecute(Long id) {
                            Bundle b = new Bundle();
                            b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id);
                            mUi.showComboView(ComboViews.Snapshots, b);
                        };
                    }.execute(source);
                } else {
                    Toast.makeText(mActivity, R.string.snapshot_failed,
1617 1618 1619 1620
                            Toast.LENGTH_SHORT).show();
                }
                break;

Michael Kolb's avatar
Michael Kolb committed
1621
            case R.id.page_info_menu_id:
1622
                mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null);
Michael Kolb's avatar
Michael Kolb committed
1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633
                break;

            case R.id.classic_history_menu_id:
                bookmarksOrHistoryPicker(true);
                break;

            case R.id.share_page_menu_id:
                Tab currentTab = mTabControl.getCurrentTab();
                if (null == currentTab) {
                    return false;
                }
1634
                shareCurrentPage(currentTab);
Michael Kolb's avatar
Michael Kolb committed
1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
                break;

            case R.id.dump_nav_menu_id:
                getCurrentTopWebView().debugDump();
                break;

            case R.id.dump_counters_menu_id:
                getCurrentTopWebView().dumpV8Counters();
                break;

            case R.id.zoom_in_menu_id:
                getCurrentTopWebView().zoomIn();
                break;

            case R.id.zoom_out_menu_id:
                getCurrentTopWebView().zoomOut();
                break;

            case R.id.view_downloads_menu_id:
                viewDownloads();
                break;

John Reck's avatar
John Reck committed
1657 1658 1659 1660 1661 1662
            case R.id.ua_desktop_menu_id:
                WebView web = getCurrentWebView();
                mSettings.toggleDesktopUseragent(web);
                web.loadUrl(web.getOriginalUrl());
                break;

Michael Kolb's avatar
Michael Kolb committed
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
            case R.id.window_one_menu_id:
            case R.id.window_two_menu_id:
            case R.id.window_three_menu_id:
            case R.id.window_four_menu_id:
            case R.id.window_five_menu_id:
            case R.id.window_six_menu_id:
            case R.id.window_seven_menu_id:
            case R.id.window_eight_menu_id:
                {
                    int menuid = item.getItemId();
                    for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
                        if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
                            Tab desiredTab = mTabControl.getTab(id);
                            if (desiredTab != null &&
                                    desiredTab != mTabControl.getCurrentTab()) {
Michael Kolb's avatar
Michael Kolb committed
1678
                                switchToTab(desiredTab);
Michael Kolb's avatar
Michael Kolb committed
1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
                            }
                            break;
                        }
                    }
                }
                break;

            default:
                return false;
        }
        return true;
    }

    public boolean onContextItemSelected(MenuItem item) {
1693 1694 1695 1696 1697
        // Let the History and Bookmark fragments handle menus they created.
        if (item.getGroupId() == R.id.CONTEXT_MENU) {
            return false;
        }

Michael Kolb's avatar
Michael Kolb committed
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796
        int id = item.getItemId();
        boolean result = true;
        switch (id) {
            // -- Browser context menu
            case R.id.open_context_menu_id:
            case R.id.save_link_context_menu_id:
            case R.id.copy_link_context_menu_id:
                final WebView webView = getCurrentTopWebView();
                if (null == webView) {
                    result = false;
                    break;
                }
                final HashMap<String, WebView> hrefMap =
                        new HashMap<String, WebView>();
                hrefMap.put("webview", webView);
                final Message msg = mHandler.obtainMessage(
                        FOCUS_NODE_HREF, id, 0, hrefMap);
                webView.requestFocusNodeHref(msg);
                break;

            default:
                // For other context menus
                result = onOptionsItemSelected(item);
        }
        return result;
    }

    /**
     * support programmatically opening the context menu
     */
    public void openContextMenu(View view) {
        mActivity.openContextMenu(view);
    }

    /**
     * programmatically open the options menu
     */
    public void openOptionsMenu() {
        mActivity.openOptionsMenu();
    }

    public boolean onMenuOpened(int featureId, Menu menu) {
        if (mOptionsMenuOpen) {
            if (mConfigChanged) {
                // We do not need to make any changes to the state of the
                // title bar, since the only thing that happened was a
                // change in orientation
                mConfigChanged = false;
            } else {
                if (!mExtendedMenuOpen) {
                    mExtendedMenuOpen = true;
                    mUi.onExtendedMenuOpened();
                } else {
                    // Switching the menu back to icon view, so show the
                    // title bar once again.
                    mExtendedMenuOpen = false;
                    mUi.onExtendedMenuClosed(mInLoad);
                }
            }
        } else {
            // The options menu is closed, so open it, and show the title
            mOptionsMenuOpen = true;
            mConfigChanged = false;
            mExtendedMenuOpen = false;
            mUi.onOptionsMenuOpened();
        }
        return true;
    }

    public void onOptionsMenuClosed(Menu menu) {
        mOptionsMenuOpen = false;
        mUi.onOptionsMenuClosed(mInLoad);
    }

    public void onContextMenuClosed(Menu menu) {
        mUi.onContextMenuClosed(menu, mInLoad);
    }

    // Helper method for getting the top window.
    @Override
    public WebView getCurrentTopWebView() {
        return mTabControl.getCurrentTopWebView();
    }

    @Override
    public WebView getCurrentWebView() {
        return mTabControl.getCurrentWebView();
    }

    /*
     * This method is called as a result of the user selecting the options
     * menu to see the download window. It shows the download window on top of
     * the current window.
     */
    void viewDownloads() {
        Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
        mActivity.startActivity(intent);
    }

John Reck's avatar
John Reck committed
1797 1798 1799 1800 1801 1802 1803 1804
    int getActionModeHeight() {
        TypedArray actionBarSizeTypedArray = mActivity.obtainStyledAttributes(
                    new int[] { android.R.attr.actionBarSize });
        int size = (int) actionBarSizeTypedArray.getDimension(0, 0f);
        actionBarSizeTypedArray.recycle();
        return size;
    }

Michael Kolb's avatar
Michael Kolb committed
1805 1806 1807 1808 1809
    // action mode

    void onActionModeStarted(ActionMode mode) {
        mUi.onActionModeStarted(mode);
        mActionMode = mode;
Michael Kolb's avatar
Michael Kolb committed
1810
        if (mSimulateActionBarOverlayMode && !mUi.isEditingUrl()) {
John Reck's avatar
John Reck committed
1811 1812 1813 1814 1815 1816 1817 1818
            WebView web = getCurrentWebView();
            // Simulate overlay mode by scrolling the webview the amount it will be
            // pushed down. Actual overlay mode doesn't work for us as otherwise
            // the CAB will, well, overlay the content, which breaks things like
            // find on page.
            int scrollBy = getActionModeHeight();
            web.scrollBy(0, scrollBy);
        }
Michael Kolb's avatar
Michael Kolb committed
1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846
    }

    /*
     * True if a custom ActionMode (i.e. find or select) is in use.
     */
    @Override
    public boolean isInCustomActionMode() {
        return mActionMode != null;
    }

    /*
     * End the current ActionMode.
     */
    @Override
    public void endActionMode() {
        if (mActionMode != null) {
            mActionMode.finish();
        }
    }

    /*
     * Called by find and select when they are finished.  Replace title bars
     * as necessary.
     */
    public void onActionModeFinished(ActionMode mode) {
        if (!isInCustomActionMode()) return;
        mUi.onActionModeFinished(mInLoad);
        mActionMode = null;
John Reck's avatar
John Reck committed
1847 1848 1849 1850 1851
        if (mSimulateActionBarOverlayMode) {
            WebView web = getCurrentWebView();
            int scrollBy = getActionModeHeight();
            web.scrollBy(0, -scrollBy);
        }
Michael Kolb's avatar
Michael Kolb committed
1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862
    }

    boolean isInLoad() {
        return mInLoad;
    }

    // bookmark handling

    /**
     * add the current page as a bookmark to the given folder id
     * @param folderId use -1 for the default folder
John Reck's avatar
John Reck committed
1863
     * @param editExisting If true, check to see whether the site is already
1864 1865 1866
     *          bookmarked, and if it is, edit that bookmark.  If false, and
     *          the site is already bookmarked, do not attempt to edit the
     *          existing bookmark.
Michael Kolb's avatar
Michael Kolb committed
1867 1868
     */
    @Override
John Reck's avatar
John Reck committed
1869
    public Intent createBookmarkCurrentPageIntent(boolean editExisting) {
Michael Kolb's avatar
Michael Kolb committed
1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887
        Intent i = new Intent(mActivity,
                AddBookmarkPage.class);
        WebView w = getCurrentTopWebView();
        i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl());
        i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle());
        String touchIconUrl = w.getTouchIconUrl();
        if (touchIconUrl != null) {
            i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl);
            WebSettings settings = w.getSettings();
            if (settings != null) {
                i.putExtra(AddBookmarkPage.USER_AGENT,
                        settings.getUserAgentString());
            }
        }
        i.putExtra(BrowserContract.Bookmarks.THUMBNAIL,
                createScreenshot(w, getDesiredThumbnailWidth(mActivity),
                getDesiredThumbnailHeight(mActivity)));
        i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon());
John Reck's avatar
John Reck committed
1888
        if (editExisting) {
1889 1890
            i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true);
        }
Michael Kolb's avatar
Michael Kolb committed
1891 1892 1893
        // Put the dialog at the upper right of the screen, covering the
        // star on the title bar.
        i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP);
John Reck's avatar
John Reck committed
1894
        return i;
Michael Kolb's avatar
Michael Kolb committed
1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
    }

    // file chooser
    public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadHandler = new UploadHandler(this);
        mUploadHandler.openFileChooser(uploadMsg, acceptType);
    }

    // thumbnails

    /**
     * Return the desired width for thumbnail screenshots, which are stored in
     * the database, and used on the bookmarks screen.
     * @param context Context for finding out the density of the screen.
     * @return desired width for thumbnail screenshot.
     */
    static int getDesiredThumbnailWidth(Context context) {
        return context.getResources().getDimensionPixelOffset(
                R.dimen.bookmarkThumbnailWidth);
    }

    /**
     * Return the desired height for thumbnail screenshots, which are stored in
     * the database, and used on the bookmarks screen.
     * @param context Context for finding out the density of the screen.
     * @return desired height for thumbnail screenshot.
     */
    static int getDesiredThumbnailHeight(Context context) {
        return context.getResources().getDimensionPixelOffset(
                R.dimen.bookmarkThumbnailHeight);
    }

John Reck's avatar
John Reck committed
1927
    static Bitmap createScreenshot(WebView view, int width, int height) {
John Reck's avatar
John Reck committed
1928 1929 1930 1931
        // We render to a bitmap 2x the desired size so that we can then
        // re-scale it with filtering since canvas.scale doesn't filter
        // This helps reduce aliasing at the cost of being slightly blurry
        final int filter_scale = 2;
Michael Kolb's avatar
Michael Kolb committed
1932 1933 1934 1935
        Picture thumbnail = view.capturePicture();
        if (thumbnail == null) {
            return null;
        }
John Reck's avatar
John Reck committed
1936 1937
        width *= filter_scale;
        height *= filter_scale;
Michael Kolb's avatar
Michael Kolb committed
1938 1939 1940 1941 1942 1943
        Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bm);
        // May need to tweak these values to determine what is the
        // best scale factor
        int thumbnailWidth = thumbnail.getWidth();
        int thumbnailHeight = thumbnail.getHeight();
1944
        float scaleFactor = 1.0f;
Michael Kolb's avatar
Michael Kolb committed
1945
        if (thumbnailWidth > 0 && thumbnailHeight > 0) {
1946
            scaleFactor = (float) width / (float)thumbnailWidth;
Michael Kolb's avatar
Michael Kolb committed
1947 1948 1949
        } else {
            return null;
        }
1950

Michael Kolb's avatar
Michael Kolb committed
1951 1952 1953 1954 1955
        float scaleFactorY = (float) height / (float)thumbnailHeight;
        if (scaleFactorY > scaleFactor) {
            // The picture is narrower than the requested AR
            // Center the thumnail and crop the sides
            scaleFactor = scaleFactorY;
1956 1957
            float wx = (thumbnailWidth * scaleFactor) - width;
            canvas.translate((int) -(wx / 2), 0);
Michael Kolb's avatar
Michael Kolb committed
1958 1959
        }

1960
        canvas.scale(scaleFactor, scaleFactor);
Michael Kolb's avatar
Michael Kolb committed
1961 1962

        thumbnail.draw(canvas);
John Reck's avatar
John Reck committed
1963 1964
        Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale,
                height / filter_scale, true);
1965
        canvas.setBitmap(null);
John Reck's avatar
John Reck committed
1966 1967
        bm.recycle();
        return ret;
Michael Kolb's avatar
Michael Kolb committed
1968 1969
    }

1970
    private void updateScreenshot(Tab tab) {
Michael Kolb's avatar
Michael Kolb committed
1971 1972 1973 1974 1975
        // 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.

1976
        WebView view = tab.getWebView();
John Reck's avatar
John Reck committed
1977 1978 1979 1980
        if (view == null) {
            // Tab was destroyed
            return;
        }
1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994
        final String url = tab.getUrl();
        final String originalUrl = view.getOriginalUrl();

        if (TextUtils.isEmpty(url)) {
            return;
        }

        // 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;
        }

Michael Kolb's avatar
Michael Kolb committed
1995 1996 1997 1998 1999 2000 2001
        final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity),
                getDesiredThumbnailHeight(mActivity));
        if (bm == null) {
            return;
        }

        final ContentResolver cr = mActivity.getContentResolver();
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... unused) {
                Cursor cursor = null;
                try {
                    // TODO: Clean this up
                    cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url);
                    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 {
2018
                            values.put(Images.URL, cursor.getString(0));
2019 2020
                            cr.update(Images.CONTENT_URI, values, null, null);
                        } while (cursor.moveToNext());
Michael Kolb's avatar
Michael Kolb committed
2021
                    }
2022 2023 2024 2025
                } catch (IllegalStateException e) {
                    // Ignore
                } finally {
                    if (cursor != null) cursor.close();
Michael Kolb's avatar
Michael Kolb committed
2026
                }
2027 2028 2029
                return null;
            }
        }.execute();
Michael Kolb's avatar
Michael Kolb committed
2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044
    }

    private class Copy implements OnMenuItemClickListener {
        private CharSequence mText;

        public boolean onMenuItemClick(MenuItem item) {
            copy(mText);
            return true;
        }

        public Copy(CharSequence toCopy) {
            mText = toCopy;
        }
    }

2045 2046
    private static class Download implements OnMenuItemClickListener {
        private Activity mActivity;
Michael Kolb's avatar
Michael Kolb committed
2047
        private String mText;
2048
        private boolean mPrivateBrowsing;
Michael Kolb's avatar
Michael Kolb committed
2049 2050

        public boolean onMenuItemClick(MenuItem item) {
2051
            DownloadHandler.onDownloadStartNoStream(mActivity, mText, null,
2052
                    null, null, mPrivateBrowsing);
Michael Kolb's avatar
Michael Kolb committed
2053 2054 2055
            return true;
        }

2056
        public Download(Activity activity, String toDownload, boolean privateBrowsing) {
2057
            mActivity = activity;
Michael Kolb's avatar
Michael Kolb committed
2058
            mText = toDownload;
2059
            mPrivateBrowsing = privateBrowsing;
Michael Kolb's avatar
Michael Kolb committed
2060 2061 2062
        }
    }

Cary Clark's avatar
Cary Clark committed
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
    private static class SelectText implements OnMenuItemClickListener {
        private WebView mWebView;

        public boolean onMenuItemClick(MenuItem item) {
            if (mWebView != null) {
                return mWebView.selectText();
            }
            return false;
        }

        public SelectText(WebView webView) {
            mWebView = webView;
        }

    }

Michael Kolb's avatar
Michael Kolb committed
2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
    /********************** TODO: UI stuff *****************************/

    // these methods have been copied, they still need to be cleaned up

    /****************** tabs ***************************************************/

    // basic tab interactions:

    // it is assumed that tabcontrol already knows about the tab
    protected void addTab(Tab tab) {
        mUi.addTab(tab);
    }

    protected void removeTab(Tab tab) {
        mUi.removeTab(tab);
        mTabControl.removeTab(tab);
John Reck's avatar
John Reck committed
2095
        mCrashRecoveryHandler.backupState();
Michael Kolb's avatar
Michael Kolb committed
2096 2097
    }

Michael Kolb's avatar
Michael Kolb committed
2098 2099
    @Override
    public void setActiveTab(Tab tab) {
Michael Kolb's avatar
Michael Kolb committed
2100 2101 2102 2103 2104 2105
        // monkey protection against delayed start
        if (tab != null) {
            mTabControl.setCurrentTab(tab);
            // the tab is guaranteed to have a webview after setCurrentTab
            mUi.setActiveTab(tab);
        }
Michael Kolb's avatar
Michael Kolb committed
2106 2107 2108 2109 2110 2111
    }

    protected void closeEmptyChildTab() {
        Tab current = mTabControl.getCurrentTab();
        if (current != null
                && current.getWebView().copyBackForwardList().getSize() == 0) {
Michael Kolb's avatar
Michael Kolb committed
2112
            Tab parent = current.getParent();
Michael Kolb's avatar
Michael Kolb committed
2113
            if (parent != null) {
Michael Kolb's avatar
Michael Kolb committed
2114
                switchToTab(parent);
Michael Kolb's avatar
Michael Kolb committed
2115 2116 2117 2118 2119
                closeTab(current);
            }
        }
    }

John Reck's avatar
John Reck committed
2120
    protected void reuseTab(Tab appTab, UrlData urlData) {
Michael Kolb's avatar
Michael Kolb committed
2121 2122 2123 2124 2125 2126
        // Dismiss the subwindow if applicable.
        dismissSubWindow(appTab);
        // Since we might kill the WebView, remove it from the
        // content view first.
        mUi.detachTab(appTab);
        // Recreate the main WebView after destroying the old one.
John Reck's avatar
John Reck committed
2127
        mTabControl.recreateWebView(appTab);
Michael Kolb's avatar
Michael Kolb committed
2128 2129 2130
        // TODO: analyze why the remove and add are necessary
        mUi.attachTab(appTab);
        if (mTabControl.getCurrentTab() != appTab) {
Michael Kolb's avatar
Michael Kolb committed
2131
            switchToTab(appTab);
John Reck's avatar
John Reck committed
2132
            loadUrlDataIn(appTab, urlData);
Michael Kolb's avatar
Michael Kolb committed
2133 2134 2135 2136
        } else {
            // If the tab was the current tab, we have to attach
            // it to the view system again.
            setActiveTab(appTab);
John Reck's avatar
John Reck committed
2137
            loadUrlDataIn(appTab, urlData);
Michael Kolb's avatar
Michael Kolb committed
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
        }
    }

    // Remove the sub window if it exists. Also called by TabControl when the
    // user clicks the 'X' to dismiss a sub window.
    public void dismissSubWindow(Tab tab) {
        removeSubWindow(tab);
        // dismiss the subwindow. This will destroy the WebView.
        tab.dismissSubWindow();
        getCurrentTopWebView().requestFocus();
    }

    @Override
    public void removeSubWindow(Tab t) {
        if (t.getSubWebView() != null) {
            mUi.removeSubWindow(t.getSubViewContainer());
        }
    }

    @Override
    public void attachSubWindow(Tab tab) {
        if (tab.getSubWebView() != null) {
            mUi.attachSubWindow(tab.getSubViewContainer());
            getCurrentTopWebView().requestFocus();
        }
    }

2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
    private Tab showPreloadedTab(final UrlData urlData) {
        if (!urlData.isPreloaded()) {
            return null;
        }
        final PreloadedTabControl tabControl = urlData.getPreloadedTab();
        final String sbQuery = urlData.getSearchBoxQueryToSubmit();
        if (sbQuery != null) {
            if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) {
                // Could not submit query. Fallback to regular tab creation
                tabControl.destroy();
                return null;
            }
        }
2178 2179 2180 2181 2182 2183 2184
        // check tab count and make room for new tab
        if (!mTabControl.canCreateNewTab()) {
            Tab leastUsed = mTabControl.getLeastUsedTab(getCurrentTab());
            if (leastUsed != null) {
                closeTab(leastUsed);
            }
        }
2185 2186 2187 2188 2189 2190 2191
        Tab t = tabControl.getTab();
        mTabControl.addPreloadedTab(t);
        addTab(t);
        setActiveTab(t);
        return t;
    }

Michael Kolb's avatar
Michael Kolb committed
2192 2193 2194
    // open a non inconito tab with the given url data
    // and set as active tab
    public Tab openTab(UrlData urlData) {
2195 2196 2197
        Tab tab = showPreloadedTab(urlData);
        if (tab == null) {
            tab = createNewTab(false, true, true);
Michael Kolb's avatar
Michael Kolb committed
2198 2199 2200
            if ((tab != null) && !urlData.isEmpty()) {
                loadUrlDataIn(tab, urlData);
            }
2201
        }
2202
        return tab;
Michael Kolb's avatar
Michael Kolb committed
2203 2204
    }

Michael Kolb's avatar
Michael Kolb committed
2205 2206 2207
    @Override
    public Tab openTabToHomePage() {
        return openTab(mSettings.getHomePage(), false, true, false);
Michael Kolb's avatar
Michael Kolb committed
2208 2209
    }

Michael Kolb's avatar
Michael Kolb committed
2210 2211 2212 2213 2214
    @Override
    public Tab openIncognitoTab() {
        return openTab(INCOGNITO_URI, true, true, false);
    }

Michael Kolb's avatar
Michael Kolb committed
2215
    @Override
Michael Kolb's avatar
Michael Kolb committed
2216 2217
    public Tab openTab(String url, boolean incognito, boolean setActive,
            boolean useCurrent) {
John Reck's avatar
John Reck committed
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
        return openTab(url, incognito, setActive, useCurrent, null);
    }

    @Override
    public Tab openTab(String url, Tab parent, boolean setActive,
            boolean useCurrent) {
        return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(),
                setActive, useCurrent, parent);
    }

    public Tab openTab(String url, boolean incognito, boolean setActive,
            boolean useCurrent, Tab parent) {
Michael Kolb's avatar
Michael Kolb committed
2230 2231
        Tab tab = createNewTab(incognito, setActive, useCurrent);
        if (tab != null) {
John Reck's avatar
John Reck committed
2232 2233 2234
            if (parent != null && parent != tab) {
                parent.addChildTab(tab);
            }
Michael Kolb's avatar
Michael Kolb committed
2235
            if (url != null) {
John Reck's avatar
John Reck committed
2236
                loadUrl(tab, url);
Michael Kolb's avatar
Michael Kolb committed
2237
            }
Michael Kolb's avatar
Michael Kolb committed
2238
        }
Michael Kolb's avatar
Michael Kolb committed
2239
        return tab;
Michael Kolb's avatar
Michael Kolb committed
2240 2241
    }

Michael Kolb's avatar
Michael Kolb committed
2242 2243 2244 2245 2246 2247 2248
    // this method will attempt to create a new tab
    // incognito: private browsing tab
    // setActive: ste tab as current tab
    // useCurrent: if no new tab can be created, return current tab
    private Tab createNewTab(boolean incognito, boolean setActive,
            boolean useCurrent) {
        Tab tab = null;
Michael Kolb's avatar
Michael Kolb committed
2249
        if (mTabControl.canCreateNewTab()) {
Michael Kolb's avatar
Michael Kolb committed
2250
            tab = mTabControl.createNewTab(incognito);
Michael Kolb's avatar
Michael Kolb committed
2251
            addTab(tab);
Michael Kolb's avatar
Michael Kolb committed
2252 2253 2254
            if (setActive) {
                setActiveTab(tab);
            }
2255
        } else {
Michael Kolb's avatar
Michael Kolb committed
2256 2257
            if (useCurrent) {
                tab = mTabControl.getCurrentTab();
John Reck's avatar
John Reck committed
2258
                reuseTab(tab, null);
Michael Kolb's avatar
Michael Kolb committed
2259 2260 2261
            } else {
                mUi.showMaxTabsWarning();
            }
Michael Kolb's avatar
Michael Kolb committed
2262
        }
Michael Kolb's avatar
Michael Kolb committed
2263
        return tab;
Michael Kolb's avatar
Michael Kolb committed
2264 2265
    }

John Reck's avatar
John Reck committed
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276
    @Override
    public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) {
        SnapshotTab tab = null;
        if (mTabControl.canCreateNewTab()) {
            tab = mTabControl.createSnapshotTab(snapshotId);
            addTab(tab);
            if (setActive) {
                setActiveTab(tab);
            }
        } else {
            mUi.showMaxTabsWarning();
John Reck's avatar
John Reck committed
2277 2278 2279 2280
        }
        return tab;
    }

Michael Kolb's avatar
Michael Kolb committed
2281
    /**
Michael Kolb's avatar
Michael Kolb committed
2282
     * @param tab the tab to switch to
Michael Kolb's avatar
Michael Kolb committed
2283 2284 2285 2286 2287
     * @return boolean True if we successfully switched to a different tab.  If
     *                 the indexth tab is null, or if that tab is the same as
     *                 the current one, return false.
     */
    @Override
Michael Kolb's avatar
Michael Kolb committed
2288
    public boolean switchToTab(Tab tab) {
Michael Kolb's avatar
Michael Kolb committed
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299
        Tab currentTab = mTabControl.getCurrentTab();
        if (tab == null || tab == currentTab) {
            return false;
        }
        setActiveTab(tab);
        return true;
    }

    @Override
    public void closeCurrentTab() {
        if (mTabControl.getTabCount() == 1) {
John Reck's avatar
John Reck committed
2300
            mCrashRecoveryHandler.clearState();
Michael Kolb's avatar
Michael Kolb committed
2301
            mTabControl.removeTab(getCurrentTab());
2302
            mActivity.finish();
Michael Kolb's avatar
Michael Kolb committed
2303 2304
            return;
        }
Michael Kolb's avatar
Michael Kolb committed
2305 2306 2307 2308 2309 2310 2311
        final Tab current = mTabControl.getCurrentTab();
        final int pos = mTabControl.getCurrentPosition();
        Tab newTab = current.getParent();
        if (newTab == null) {
            newTab = mTabControl.getTab(pos + 1);
            if (newTab == null) {
                newTab = mTabControl.getTab(pos - 1);
Michael Kolb's avatar
Michael Kolb committed
2312 2313
            }
        }
Michael Kolb's avatar
Michael Kolb committed
2314
        if (switchToTab(newTab)) {
Michael Kolb's avatar
Michael Kolb committed
2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
            // Close window
            closeTab(current);
        }
    }

    /**
     * Close the tab, remove its associated title bar, and adjust mTabControl's
     * current tab to a valid value.
     */
    @Override
    public void closeTab(Tab tab) {
Michael Kolb's avatar
Michael Kolb committed
2326
        removeTab(tab);
Michael Kolb's avatar
Michael Kolb committed
2327 2328 2329
    }

    // Called when loading from context menu or LOAD_URL message
John Reck's avatar
John Reck committed
2330 2331 2332
    protected void loadUrlFromContext(String url) {
        Tab tab = getCurrentTab();
        WebView view = tab != null ? tab.getWebView() : null;
Michael Kolb's avatar
Michael Kolb committed
2333
        // In case the user enters nothing.
John Reck's avatar
John Reck committed
2334
        if (url != null && url.length() != 0 && tab != null && view != null) {
Michael Kolb's avatar
Michael Kolb committed
2335 2336
            url = UrlUtils.smartUrlFilter(url);
            if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
John Reck's avatar
John Reck committed
2337
                loadUrl(tab, url);
Michael Kolb's avatar
Michael Kolb committed
2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348
            }
        }
    }

    /**
     * Load the URL into the given WebView and update the title bar
     * to reflect the new load.  Call this instead of WebView.loadUrl
     * directly.
     * @param view The WebView used to load url.
     * @param url The URL to load.
     */
John Reck's avatar
John Reck committed
2349 2350
    @Override
    public void loadUrl(Tab tab, String url) {
John Reck's avatar
John Reck committed
2351 2352 2353 2354 2355 2356 2357 2358
        loadUrl(tab, url, null);
    }

    protected void loadUrl(Tab tab, String url, Map<String, String> headers) {
        if (tab != null) {
            dismissSubWindow(tab);
            tab.loadUrl(url, headers);
        }
Michael Kolb's avatar
Michael Kolb committed
2359 2360 2361 2362 2363 2364 2365 2366 2367
    }

    /**
     * Load UrlData into a Tab and update the title bar to reflect the new
     * load.  Call this instead of UrlData.loadIn directly.
     * @param t The Tab used to load.
     * @param data The UrlData being loaded.
     */
    protected void loadUrlDataIn(Tab t, UrlData data) {
John Reck's avatar
John Reck committed
2368 2369 2370
        if (data != null) {
            if (data.mVoiceIntent != null) {
                t.activateVoiceSearchMode(data.mVoiceIntent);
Michael Kolb's avatar
Michael Kolb committed
2371 2372
            } else if (data.isPreloaded()) {
                // this isn't called for preloaded tabs
John Reck's avatar
John Reck committed
2373 2374 2375 2376
            } else {
                loadUrl(t, data.mUrl, data.mHeaders);
            }
        }
Michael Kolb's avatar
Michael Kolb committed
2377 2378
    }

John Reck's avatar
John Reck committed
2379 2380 2381
    @Override
    public void onUserCanceledSsl(Tab tab) {
        // TODO: Figure out the "right" behavior
John Reck's avatar
John Reck committed
2382 2383
        if (tab.canGoBack()) {
            tab.goBack();
John Reck's avatar
John Reck committed
2384
        } else {
John Reck's avatar
John Reck committed
2385
            tab.loadUrl(mSettings.getHomePage(), null);
John Reck's avatar
John Reck committed
2386
        }
Michael Kolb's avatar
Michael Kolb committed
2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401
    }

    void goBackOnePageOrQuit() {
        Tab current = mTabControl.getCurrentTab();
        if (current == null) {
            /*
             * Instead of finishing the activity, simply push this to the back
             * of the stack and let ActivityManager to choose the foreground
             * activity. As BrowserActivity is singleTask, it will be always the
             * root of the task. So we can use either true or false for
             * moveTaskToBack().
             */
            mActivity.moveTaskToBack(true);
            return;
        }
John Reck's avatar
John Reck committed
2402 2403
        if (current.canGoBack()) {
            current.goBack();
Michael Kolb's avatar
Michael Kolb committed
2404 2405 2406
        } else {
            // Check to see if we are closing a window that was created by
            // another window. If so, we switch back to that window.
Michael Kolb's avatar
Michael Kolb committed
2407
            Tab parent = current.getParent();
Michael Kolb's avatar
Michael Kolb committed
2408
            if (parent != null) {
Michael Kolb's avatar
Michael Kolb committed
2409
                switchToTab(parent);
Michael Kolb's avatar
Michael Kolb committed
2410 2411 2412
                // Now we close the other tab
                closeTab(current);
            } else {
Michael Kolb's avatar
Michael Kolb committed
2413 2414 2415
                if ((current.getAppId() != null) || current.closeOnBack()) {
                    closeCurrentTab();
                }
Michael Kolb's avatar
Michael Kolb committed
2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468
                /*
                 * Instead of finishing the activity, simply push this to the back
                 * of the stack and let ActivityManager to choose the foreground
                 * activity. As BrowserActivity is singleTask, it will be always the
                 * root of the task. So we can use either true or false for
                 * moveTaskToBack().
                 */
                mActivity.moveTaskToBack(true);
            }
        }
    }

    /**
     * Feed the previously stored results strings to the BrowserProvider so that
     * the SearchDialog will show them instead of the standard searches.
     * @param result String to show on the editable line of the SearchDialog.
     */
    @Override
    public void showVoiceSearchResults(String result) {
        ContentProviderClient client = mActivity.getContentResolver()
                .acquireContentProviderClient(Browser.BOOKMARKS_URI);
        ContentProvider prov = client.getLocalContentProvider();
        BrowserProvider bp = (BrowserProvider) prov;
        bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
        client.release();

        Bundle bundle = createGoogleSearchSourceBundle(
                GOOGLE_SEARCH_SOURCE_SEARCHKEY);
        bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
        startSearch(result, false, bundle, false);
    }

    private void startSearch(String initialQuery, boolean selectInitialQuery,
            Bundle appSearchData, boolean globalSearch) {
        if (appSearchData == null) {
            appSearchData = createGoogleSearchSourceBundle(
                    GOOGLE_SEARCH_SOURCE_TYPE);
        }

        SearchEngine searchEngine = mSettings.getSearchEngine();
        if (searchEngine != null && !searchEngine.supportsVoiceSearch()) {
            appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true);
        }
        mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData,
                globalSearch);
    }

    private Bundle createGoogleSearchSourceBundle(String source) {
        Bundle bundle = new Bundle();
        bundle.putString(Search.SOURCE, source);
        return bundle;
    }

Michael Kolb's avatar
Michael Kolb committed
2469 2470 2471 2472
    /**
     * helper method for key handler
     * returns the current tab if it can't advance
     */
Michael Kolb's avatar
Michael Kolb committed
2473 2474 2475
    private Tab getNextTab() {
        return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1,
                mTabControl.getCurrentPosition() + 1));
Michael Kolb's avatar
Michael Kolb committed
2476 2477 2478 2479 2480 2481
    }

    /**
     * helper method for key handler
     * returns the current tab if it can't advance
     */
Michael Kolb's avatar
Michael Kolb committed
2482 2483 2484
    private Tab getPrevTab() {
        return  mTabControl.getTab(Math.max(0,
                mTabControl.getCurrentPosition() - 1));
Michael Kolb's avatar
Michael Kolb committed
2485 2486
    }

Michael Kolb's avatar
Michael Kolb committed
2487 2488 2489 2490 2491 2492 2493 2494
    /**
     * handle key events in browser
     *
     * @param keyCode
     * @param event
     * @return true if handled, false to pass to super
     */
    boolean onKeyDown(int keyCode, KeyEvent event) {
Cary Clark's avatar
Cary Clark committed
2495
        boolean noModifiers = event.hasNoModifiers();
Michael Kolb's avatar
Michael Kolb committed
2496 2497
        // Even if MENU is already held down, we need to call to super to open
        // the IME on long press.
Michael Kolb's avatar
Michael Kolb committed
2498 2499 2500 2501
        if (!noModifiers
                && ((KeyEvent.KEYCODE_MENU == keyCode)
                        || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode)
                        || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) {
Michael Kolb's avatar
Michael Kolb committed
2502 2503 2504 2505
            mMenuIsDown = true;
            return false;
        }

Cary Clark's avatar
Cary Clark committed
2506
        WebView webView = getCurrentTopWebView();
John Reck's avatar
John Reck committed
2507 2508
        Tab tab = getCurrentTab();
        if (webView == null || tab == null) return false;
Cary Clark's avatar
Cary Clark committed
2509

Cary Clark's avatar
Cary Clark committed
2510 2511
        boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON);
        boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON);
Cary Clark's avatar
Cary Clark committed
2512

Michael Kolb's avatar
Michael Kolb committed
2513
        switch(keyCode) {
Michael Kolb's avatar
Michael Kolb committed
2514 2515 2516 2517
            case KeyEvent.KEYCODE_TAB:
                if (event.isCtrlPressed()) {
                    if (event.isShiftPressed()) {
                        // prev tab
Michael Kolb's avatar
Michael Kolb committed
2518
                        switchToTab(getPrevTab());
Michael Kolb's avatar
Michael Kolb committed
2519 2520
                    } else {
                        // next tab
Michael Kolb's avatar
Michael Kolb committed
2521
                        switchToTab(getNextTab());
Michael Kolb's avatar
Michael Kolb committed
2522 2523 2524 2525
                    }
                    return true;
                }
                break;
Michael Kolb's avatar
Michael Kolb committed
2526 2527 2528 2529
            case KeyEvent.KEYCODE_SPACE:
                // WebView/WebTextView handle the keys in the KeyDown. As
                // the Activity's shortcut keys are only handled when WebView
                // doesn't, have to do it in onKeyDown instead of onKeyUp.
Cary Clark's avatar
Cary Clark committed
2530
                if (shift) {
Michael Kolb's avatar
Michael Kolb committed
2531
                    pageUp();
Cary Clark's avatar
Cary Clark committed
2532
                } else if (noModifiers) {
Michael Kolb's avatar
Michael Kolb committed
2533 2534 2535 2536
                    pageDown();
                }
                return true;
            case KeyEvent.KEYCODE_BACK:
Cary Clark's avatar
Cary Clark committed
2537
                if (!noModifiers) break;
John Reck's avatar
John Reck committed
2538 2539
                event.startTracking();
                return true;
Michael Kolb's avatar
Michael Kolb committed
2540 2541 2542 2543
            case KeyEvent.KEYCODE_FORWARD:
                if (!noModifiers) break;
                tab.goForward();
                return true;
Cary Clark's avatar
Cary Clark committed
2544 2545
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (ctrl) {
John Reck's avatar
John Reck committed
2546
                    tab.goBack();
Cary Clark's avatar
Cary Clark committed
2547 2548 2549 2550 2551
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (ctrl) {
John Reck's avatar
John Reck committed
2552
                    tab.goForward();
Cary Clark's avatar
Cary Clark committed
2553 2554 2555 2556 2557 2558 2559 2560 2561
                    return true;
                }
                break;
            case KeyEvent.KEYCODE_A:
                if (ctrl) {
                    webView.selectAll();
                    return true;
                }
                break;
Michael Kolb's avatar
Michael Kolb committed
2562
//          case KeyEvent.KEYCODE_B:    // menu
Cary Clark's avatar
Cary Clark committed
2563 2564 2565 2566 2567 2568
            case KeyEvent.KEYCODE_C:
                if (ctrl) {
                    webView.copySelection();
                    return true;
                }
                break;
Michael Kolb's avatar
Michael Kolb committed
2569
//          case KeyEvent.KEYCODE_D:    // menu
Cary Clark's avatar
Cary Clark committed
2570
//          case KeyEvent.KEYCODE_E:    // in Chrome: puts '?' in URL bar
Michael Kolb's avatar
Michael Kolb committed
2571
//          case KeyEvent.KEYCODE_F:    // menu
Cary Clark's avatar
Cary Clark committed
2572
//          case KeyEvent.KEYCODE_G:    // in Chrome: finds next match
Michael Kolb's avatar
Michael Kolb committed
2573
//          case KeyEvent.KEYCODE_H:    // menu
Cary Clark's avatar
Cary Clark committed
2574
//          case KeyEvent.KEYCODE_I:    // unused
Michael Kolb's avatar
Michael Kolb committed
2575
//          case KeyEvent.KEYCODE_J:    // menu
Cary Clark's avatar
Cary Clark committed
2576
//          case KeyEvent.KEYCODE_K:    // in Chrome: puts '?' in URL bar
Michael Kolb's avatar
Michael Kolb committed
2577
//          case KeyEvent.KEYCODE_L:    // menu
Cary Clark's avatar
Cary Clark committed
2578 2579 2580 2581 2582
//          case KeyEvent.KEYCODE_M:    // unused
//          case KeyEvent.KEYCODE_N:    // in Chrome: new window
//          case KeyEvent.KEYCODE_O:    // in Chrome: open file
//          case KeyEvent.KEYCODE_P:    // in Chrome: print page
//          case KeyEvent.KEYCODE_Q:    // unused
Michael Kolb's avatar
Michael Kolb committed
2583
//          case KeyEvent.KEYCODE_R:
Cary Clark's avatar
Cary Clark committed
2584 2585
//          case KeyEvent.KEYCODE_S:    // in Chrome: saves page
            case KeyEvent.KEYCODE_T:
Michael Kolb's avatar
Michael Kolb committed
2586 2587 2588
                // we can't use the ctrl/shift flags, they check for
                // exclusive use of a modifier
                if (event.isCtrlPressed()) {
Cary Clark's avatar
Cary Clark committed
2589
                    if (event.isShiftPressed()) {
Michael Kolb's avatar
Michael Kolb committed
2590
                        openIncognitoTab();
Cary Clark's avatar
Cary Clark committed
2591 2592 2593 2594 2595 2596 2597 2598
                    } else {
                        openTabToHomePage();
                    }
                    return true;
                }
                break;
//          case KeyEvent.KEYCODE_U:    // in Chrome: opens source of page
//          case KeyEvent.KEYCODE_V:    // text view intercepts to paste
Michael Kolb's avatar
Michael Kolb committed
2599
//          case KeyEvent.KEYCODE_W:    // menu
Cary Clark's avatar
Cary Clark committed
2600 2601 2602
//          case KeyEvent.KEYCODE_X:    // text view intercepts to cut
//          case KeyEvent.KEYCODE_Y:    // unused
//          case KeyEvent.KEYCODE_Z:    // unused
Michael Kolb's avatar
Michael Kolb committed
2603
        }
Michael Kolb's avatar
Michael Kolb committed
2604 2605
        // it is a regular key and webview is not null
         return mUi.dispatchKey(keyCode, event);
Michael Kolb's avatar
Michael Kolb committed
2606 2607
    }

John Reck's avatar
John Reck committed
2608 2609 2610
    boolean onKeyLongPress(int keyCode, KeyEvent event) {
        switch(keyCode) {
        case KeyEvent.KEYCODE_BACK:
2611
            if (mUi.isWebShowing()) {
John Reck's avatar
John Reck committed
2612 2613 2614 2615 2616 2617 2618 2619
                bookmarksOrHistoryPicker(true);
                return true;
            }
            break;
        }
        return false;
    }

Michael Kolb's avatar
Michael Kolb committed
2620
    boolean onKeyUp(int keyCode, KeyEvent event) {
2621 2622 2623
        if (KeyEvent.KEYCODE_MENU == keyCode) {
            mMenuIsDown = false;
            if (event.isTracking() && !event.isCanceled()) {
2624
                return onMenuKey();
2625 2626
            }
        }
Cary Clark's avatar
Cary Clark committed
2627
        if (!event.hasNoModifiers()) return false;
Michael Kolb's avatar
Michael Kolb committed
2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
        switch(keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (event.isTracking() && !event.isCanceled()) {
                    onBackKey();
                    return true;
                }
                break;
        }
        return false;
    }

    public boolean isMenuDown() {
        return mMenuIsDown;
    }

2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
    public void setupAutoFill(Message message) {
        // Open the settings activity at the AutoFill profile fragment so that
        // the user can create a new profile. When they return, we will dispatch
        // the message so that we can autofill the form using their new profile.
        Intent intent = new Intent(mActivity, BrowserPreferencesPage.class);
        intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT,
                AutoFillSettingsFragment.class.getName());
        mAutoFillSetupMessage = message;
        mActivity.startActivityForResult(intent, AUTOFILL_SETUP);
    }
John Reck's avatar
John Reck committed
2653

2654 2655 2656 2657
    @Override
    public void registerDropdownChangeListener(DropdownChangeListener d) {
        mUi.registerDropdownChangeListener(d);
    }
Michael Kolb's avatar
Michael Kolb committed
2658 2659 2660 2661 2662 2663

    public boolean onSearchRequested() {
        mUi.editUrl(false);
        return true;
    }

John Reck's avatar
John Reck committed
2664 2665 2666 2667 2668
    @Override
    public boolean shouldCaptureThumbnails() {
        return mUi.shouldCaptureThumbnails();
    }

Michael Kolb's avatar
Michael Kolb committed
2669 2670 2671 2672 2673 2674
    @Override
    public void setBlockEvents(boolean block) {
        mBlockEvents = block;
    }

    public boolean dispatchKeyEvent(KeyEvent event) {
Michael Kolb's avatar
Michael Kolb committed
2675
        return mBlockEvents || hasNoActiveTab();
Michael Kolb's avatar
Michael Kolb committed
2676 2677 2678
    }

    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
Michael Kolb's avatar
Michael Kolb committed
2679
        return mBlockEvents || hasNoActiveTab();
Michael Kolb's avatar
Michael Kolb committed
2680 2681 2682
    }

    public boolean dispatchTouchEvent(MotionEvent ev) {
Michael Kolb's avatar
Michael Kolb committed
2683
        return mBlockEvents || hasNoActiveTab();
Michael Kolb's avatar
Michael Kolb committed
2684 2685 2686
    }

    public boolean dispatchTrackballEvent(MotionEvent ev) {
Michael Kolb's avatar
Michael Kolb committed
2687
        return mBlockEvents || hasNoActiveTab();
Michael Kolb's avatar
Michael Kolb committed
2688 2689 2690
    }

    public boolean dispatchGenericMotionEvent(MotionEvent ev) {
Michael Kolb's avatar
Michael Kolb committed
2691 2692 2693 2694 2695 2696 2697 2698 2699 2700
        return mBlockEvents || hasNoActiveTab();
    }

    private boolean hasNoActiveTab() {
        Tab tab = getCurrentTab();
        if (tab == null) {
            Log.w(LOGTAG, "Received event with no active tab. Tab count: "
                    + mTabControl.getTabCount());
        }
        return tab == null;
Michael Kolb's avatar
Michael Kolb committed
2701 2702
    }

Michael Kolb's avatar
Michael Kolb committed
2703
}