Controller.java revision ef85204bf5eab3e4fd2ca4d36e838bdaaa48f68a
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.browser; 18 19import android.app.Activity; 20import android.app.DownloadManager; 21import android.app.SearchManager; 22import android.content.ClipboardManager; 23import android.content.ContentProvider; 24import android.content.ContentProviderClient; 25import android.content.ContentResolver; 26import android.content.ContentUris; 27import android.content.ContentValues; 28import android.content.Context; 29import android.content.Intent; 30import android.content.pm.PackageManager; 31import android.content.pm.ResolveInfo; 32import android.content.res.Configuration; 33import android.database.ContentObserver; 34import android.database.Cursor; 35import android.database.sqlite.SQLiteDatabase; 36import android.graphics.Bitmap; 37import android.graphics.Canvas; 38import android.graphics.Picture; 39import android.net.Uri; 40import android.net.http.SslError; 41import android.os.AsyncTask; 42import android.os.Bundle; 43import android.os.Handler; 44import android.os.Message; 45import android.os.PowerManager; 46import android.os.PowerManager.WakeLock; 47import android.preference.PreferenceActivity; 48import android.provider.Browser; 49import android.provider.BrowserContract; 50import android.provider.BrowserContract.Images; 51import android.provider.ContactsContract; 52import android.provider.ContactsContract.Intents.Insert; 53import android.speech.RecognizerIntent; 54import android.text.TextUtils; 55import android.util.Log; 56import android.util.Patterns; 57import android.view.ActionMode; 58import android.view.ContextMenu; 59import android.view.ContextMenu.ContextMenuInfo; 60import android.view.Gravity; 61import android.view.KeyEvent; 62import android.view.Menu; 63import android.view.MenuInflater; 64import android.view.MenuItem; 65import android.view.MenuItem.OnMenuItemClickListener; 66import android.view.View; 67import android.webkit.CookieManager; 68import android.webkit.CookieSyncManager; 69import android.webkit.HttpAuthHandler; 70import android.webkit.SslErrorHandler; 71import android.webkit.ValueCallback; 72import android.webkit.WebChromeClient; 73import android.webkit.WebIconDatabase; 74import android.webkit.WebSettings; 75import android.webkit.WebView; 76import android.widget.Toast; 77 78import com.android.browser.IntentHandler.UrlData; 79import com.android.browser.UI.ComboViews; 80import com.android.browser.UI.DropdownChangeListener; 81import com.android.browser.provider.BrowserProvider; 82import com.android.browser.provider.SnapshotProvider.Snapshots; 83import com.android.browser.search.SearchEngine; 84import com.android.common.Search; 85 86import java.io.ByteArrayOutputStream; 87import java.io.File; 88import java.net.URLEncoder; 89import java.util.Calendar; 90import java.util.HashMap; 91import java.util.List; 92import java.util.Map; 93 94/** 95 * Controller for browser 96 */ 97public class Controller 98 implements WebViewController, UiController { 99 100 private static final String LOGTAG = "Controller"; 101 private static final String SEND_APP_ID_EXTRA = 102 "android.speech.extras.SEND_APPLICATION_ID_EXTRA"; 103 private static final String INCOGNITO_URI = "browser:incognito"; 104 105 106 // public message ids 107 public final static int LOAD_URL = 1001; 108 public final static int STOP_LOAD = 1002; 109 110 // Message Ids 111 private static final int FOCUS_NODE_HREF = 102; 112 private static final int RELEASE_WAKELOCK = 107; 113 114 static final int UPDATE_BOOKMARK_THUMBNAIL = 108; 115 116 private static final int OPEN_BOOKMARKS = 201; 117 118 private static final int EMPTY_MENU = -1; 119 120 // activity requestCode 121 final static int PREFERENCES_PAGE = 3; 122 final static int FILE_SELECTED = 4; 123 final static int AUTOFILL_SETUP = 5; 124 125 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes 126 127 // As the ids are dynamically created, we can't guarantee that they will 128 // be in sequence, so this static array maps ids to a window number. 129 final static private int[] WINDOW_SHORTCUT_ID_ARRAY = 130 { R.id.window_one_menu_id, R.id.window_two_menu_id, 131 R.id.window_three_menu_id, R.id.window_four_menu_id, 132 R.id.window_five_menu_id, R.id.window_six_menu_id, 133 R.id.window_seven_menu_id, R.id.window_eight_menu_id }; 134 135 // "source" parameter for Google search through search key 136 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key"; 137 // "source" parameter for Google search through simplily type 138 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type"; 139 140 // "no-crash-recovery" parameter in intetnt to suppress crash recovery 141 final static String NO_CRASH_RECOVERY = "no-crash-recovery"; 142 143 private Activity mActivity; 144 private UI mUi; 145 private TabControl mTabControl; 146 private BrowserSettings mSettings; 147 private WebViewFactory mFactory; 148 private OptionsMenuHandler mOptionsMenuHandler = null; 149 150 private WakeLock mWakeLock; 151 152 private UrlHandler mUrlHandler; 153 private UploadHandler mUploadHandler; 154 private IntentHandler mIntentHandler; 155 private PageDialogsHandler mPageDialogsHandler; 156 private NetworkStateHandler mNetworkHandler; 157 private NfcHandler mNfcHandler; 158 159 private Message mAutoFillSetupMessage; 160 161 private boolean mShouldShowErrorConsole; 162 163 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins; 164 165 // FIXME, temp address onPrepareMenu performance problem. 166 // When we move everything out of view, we should rewrite this. 167 private int mCurrentMenuState = 0; 168 private int mMenuState = R.id.MAIN_MENU; 169 private int mOldMenuState = EMPTY_MENU; 170 private Menu mCachedMenu; 171 172 private boolean mMenuIsDown; 173 174 // For select and find, we keep track of the ActionMode so that 175 // finish() can be called as desired. 176 private ActionMode mActionMode; 177 178 /** 179 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track 180 * of whether the configuration has changed. The first onMenuOpened call 181 * after a configuration change is simply a reopening of the same menu 182 * (i.e. mIconView did not change). 183 */ 184 private boolean mConfigChanged; 185 186 /** 187 * Keeps track of whether the options menu is open. This is important in 188 * determining whether to show or hide the title bar overlay 189 */ 190 private boolean mOptionsMenuOpen; 191 192 /** 193 * Whether or not the options menu is in its bigger, popup menu form. When 194 * true, we want the title bar overlay to be gone. When false, we do not. 195 * Only meaningful if mOptionsMenuOpen is true. 196 */ 197 private boolean mExtendedMenuOpen; 198 199 private boolean mInLoad; 200 201 private boolean mActivityPaused = true; 202 private boolean mLoadStopped; 203 204 private Handler mHandler; 205 // Checks to see when the bookmarks database has changed, and updates the 206 // Tabs' notion of whether they represent bookmarked sites. 207 private ContentObserver mBookmarksObserver; 208 private DataController mDataController; 209 private CrashRecoveryHandler mCrashRecoveryHandler; 210 211 private static class ClearThumbnails extends AsyncTask<File, Void, Void> { 212 @Override 213 public Void doInBackground(File... files) { 214 if (files != null) { 215 for (File f : files) { 216 if (!f.delete()) { 217 Log.e(LOGTAG, f.getPath() + " was not deleted"); 218 } 219 } 220 } 221 return null; 222 } 223 } 224 225 public Controller(Activity browser) { 226 mActivity = browser; 227 mSettings = BrowserSettings.getInstance(); 228 mDataController = DataController.getInstance(mActivity); 229 mTabControl = new TabControl(this); 230 mSettings.setController(this); 231 mCrashRecoveryHandler = CrashRecoveryHandler.initialize(this); 232 mFactory = new BrowserWebViewFactory(browser); 233 234 mUrlHandler = new UrlHandler(this); 235 mIntentHandler = new IntentHandler(mActivity, this); 236 mPageDialogsHandler = new PageDialogsHandler(mActivity, this); 237 mNfcHandler = new NfcHandler(mActivity, this); 238 239 PowerManager pm = (PowerManager) mActivity 240 .getSystemService(Context.POWER_SERVICE); 241 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); 242 243 startHandler(); 244 mBookmarksObserver = new ContentObserver(mHandler) { 245 @Override 246 public void onChange(boolean selfChange) { 247 int size = mTabControl.getTabCount(); 248 for (int i = 0; i < size; i++) { 249 mTabControl.getTab(i).updateBookmarkedStatus(); 250 } 251 } 252 253 }; 254 browser.getContentResolver().registerContentObserver( 255 BrowserContract.Bookmarks.CONTENT_URI, true, mBookmarksObserver); 256 257 mNetworkHandler = new NetworkStateHandler(mActivity, this); 258 // Start watching the default geolocation permissions 259 mSystemAllowGeolocationOrigins = 260 new SystemAllowGeolocationOrigins(mActivity.getApplicationContext()); 261 mSystemAllowGeolocationOrigins.start(); 262 263 retainIconsOnStartup(); 264 } 265 266 void start(final Bundle icicle, final Intent intent) { 267 boolean noCrashRecovery = intent.getBooleanExtra(NO_CRASH_RECOVERY, false); 268 if (icicle != null || noCrashRecovery) { 269 doStart(icicle, intent); 270 } else { 271 mCrashRecoveryHandler.startRecovery(intent); 272 } 273 } 274 275 void doStart(final Bundle icicle, final Intent intent) { 276 // Unless the last browser usage was within 24 hours, destroy any 277 // remaining incognito tabs. 278 279 Calendar lastActiveDate = icicle != null ? 280 (Calendar) icicle.getSerializable("lastActiveDate") : null; 281 Calendar today = Calendar.getInstance(); 282 Calendar yesterday = Calendar.getInstance(); 283 yesterday.add(Calendar.DATE, -1); 284 285 final boolean restoreIncognitoTabs = !(lastActiveDate == null 286 || lastActiveDate.before(yesterday) 287 || lastActiveDate.after(today)); 288 289 // Find out if we will restore any state and remember the tab. 290 final long currentTabId = 291 mTabControl.canRestoreState(icicle, restoreIncognitoTabs); 292 293 if (currentTabId == -1) { 294 // Not able to restore so we go ahead and clear session cookies. We 295 // must do this before trying to login the user as we don't want to 296 // clear any session cookies set during login. 297 CookieManager.getInstance().removeSessionCookie(); 298 } 299 300 GoogleAccountLogin.startLoginIfNeeded(mActivity, 301 new Runnable() { 302 @Override public void run() { 303 onPreloginFinished(icicle, intent, currentTabId, restoreIncognitoTabs); 304 } 305 }); 306 } 307 308 private void onPreloginFinished(Bundle icicle, Intent intent, long currentTabId, 309 boolean restoreIncognitoTabs) { 310 if (currentTabId == -1) { 311 final Bundle extra = intent.getExtras(); 312 // Create an initial tab. 313 // If the intent is ACTION_VIEW and data is not null, the Browser is 314 // invoked to view the content by another application. In this case, 315 // the tab will be close when exit. 316 UrlData urlData = IntentHandler.getUrlDataFromIntent(intent); 317 Tab t = null; 318 if (urlData.isEmpty()) { 319 t = openTabToHomePage(); 320 } else { 321 t = openTab(urlData); 322 } 323 if (t != null) { 324 t.setAppId(intent.getStringExtra(Browser.EXTRA_APPLICATION_ID)); 325 } 326 WebView webView = t.getWebView(); 327 if (extra != null) { 328 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); 329 if (scale > 0 && scale <= 1000) { 330 webView.setInitialScale(scale); 331 } 332 } 333 mUi.updateTabs(mTabControl.getTabs()); 334 } else { 335 mTabControl.restoreState(icicle, currentTabId, restoreIncognitoTabs, 336 mUi.needsRestoreAllTabs()); 337 mUi.updateTabs(mTabControl.getTabs()); 338 // TabControl.restoreState() will create a new tab even if 339 // restoring the state fails. 340 setActiveTab(mTabControl.getCurrentTab()); 341 // Handle the intent 342 mIntentHandler.onNewIntent(intent); 343 } 344 // clear up the thumbnail directory, which is no longer used; 345 // ideally this should only be run once after an upgrade from 346 // a previous version of the browser 347 new ClearThumbnails().execute(mTabControl.getThumbnailDir() 348 .listFiles()); 349 // Read JavaScript flags if it exists. 350 String jsFlags = getSettings().getJsEngineFlags(); 351 if (jsFlags.trim().length() != 0) { 352 getCurrentWebView().setJsFlags(jsFlags); 353 } 354 if (BrowserActivity.ACTION_SHOW_BOOKMARKS.equals(intent.getAction())) { 355 bookmarksOrHistoryPicker(false); 356 } 357 } 358 359 @Override 360 public WebViewFactory getWebViewFactory() { 361 return mFactory; 362 } 363 364 @Override 365 public void onSetWebView(Tab tab, WebView view) { 366 mUi.onSetWebView(tab, view); 367 } 368 369 @Override 370 public void createSubWindow(Tab tab) { 371 endActionMode(); 372 WebView mainView = tab.getWebView(); 373 WebView subView = mFactory.createWebView((mainView == null) 374 ? false 375 : mainView.isPrivateBrowsingEnabled()); 376 mUi.createSubWindow(tab, subView); 377 } 378 379 @Override 380 public Context getContext() { 381 return mActivity; 382 } 383 384 @Override 385 public Activity getActivity() { 386 return mActivity; 387 } 388 389 void setUi(UI ui) { 390 mUi = ui; 391 } 392 393 BrowserSettings getSettings() { 394 return mSettings; 395 } 396 397 IntentHandler getIntentHandler() { 398 return mIntentHandler; 399 } 400 401 @Override 402 public UI getUi() { 403 return mUi; 404 } 405 406 int getMaxTabs() { 407 return mActivity.getResources().getInteger(R.integer.max_tabs); 408 } 409 410 @Override 411 public TabControl getTabControl() { 412 return mTabControl; 413 } 414 415 @Override 416 public List<Tab> getTabs() { 417 return mTabControl.getTabs(); 418 } 419 420 // Open the icon database and retain all the icons for visited sites. 421 // This is done on a background thread so as not to stall startup. 422 private void retainIconsOnStartup() { 423 // WebIconDatabase needs to be retrieved on the UI thread so that if 424 // it has not been created successfully yet the Handler is started on the 425 // UI thread. 426 new RetainIconsOnStartupTask(WebIconDatabase.getInstance()).execute(); 427 } 428 429 private class RetainIconsOnStartupTask extends AsyncTask<Void, Void, Void> { 430 private WebIconDatabase mDb; 431 432 public RetainIconsOnStartupTask(WebIconDatabase db) { 433 mDb = db; 434 } 435 436 @Override 437 protected Void doInBackground(Void... unused) { 438 mDb.open(mActivity.getDir("icons", 0).getPath()); 439 Cursor c = null; 440 try { 441 c = Browser.getAllBookmarks(mActivity.getContentResolver()); 442 if (c.moveToFirst()) { 443 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL); 444 do { 445 String url = c.getString(urlIndex); 446 mDb.retainIconForPageUrl(url); 447 } while (c.moveToNext()); 448 } 449 } catch (IllegalStateException e) { 450 Log.e(LOGTAG, "retainIconsOnStartup", e); 451 } finally { 452 if (c != null) c.close(); 453 } 454 455 return null; 456 } 457 } 458 459 private void startHandler() { 460 mHandler = new Handler() { 461 462 @Override 463 public void handleMessage(Message msg) { 464 switch (msg.what) { 465 case OPEN_BOOKMARKS: 466 bookmarksOrHistoryPicker(false); 467 break; 468 case FOCUS_NODE_HREF: 469 { 470 String url = (String) msg.getData().get("url"); 471 String title = (String) msg.getData().get("title"); 472 String src = (String) msg.getData().get("src"); 473 if (url == "") url = src; // use image if no anchor 474 if (TextUtils.isEmpty(url)) { 475 break; 476 } 477 HashMap focusNodeMap = (HashMap) msg.obj; 478 WebView view = (WebView) focusNodeMap.get("webview"); 479 // Only apply the action if the top window did not change. 480 if (getCurrentTopWebView() != view) { 481 break; 482 } 483 switch (msg.arg1) { 484 case R.id.open_context_menu_id: 485 loadUrlFromContext(url); 486 break; 487 case R.id.view_image_context_menu_id: 488 loadUrlFromContext(src); 489 break; 490 case R.id.open_newtab_context_menu_id: 491 final Tab parent = mTabControl.getCurrentTab(); 492 openTab(url, parent, 493 !mSettings.openInBackground(), true); 494 break; 495 case R.id.copy_link_context_menu_id: 496 copy(url); 497 break; 498 case R.id.save_link_context_menu_id: 499 case R.id.download_context_menu_id: 500 DownloadHandler.onDownloadStartNoStream( 501 mActivity, url, null, null, null, 502 view.isPrivateBrowsingEnabled()); 503 break; 504 } 505 break; 506 } 507 508 case LOAD_URL: 509 loadUrlFromContext((String) msg.obj); 510 break; 511 512 case STOP_LOAD: 513 stopLoading(); 514 break; 515 516 case RELEASE_WAKELOCK: 517 if (mWakeLock.isHeld()) { 518 mWakeLock.release(); 519 // if we reach here, Browser should be still in the 520 // background loading after WAKELOCK_TIMEOUT (5-min). 521 // To avoid burning the battery, stop loading. 522 mTabControl.stopAllLoading(); 523 } 524 break; 525 526 case UPDATE_BOOKMARK_THUMBNAIL: 527 Tab tab = (Tab) msg.obj; 528 if (tab != null) { 529 updateScreenshot(tab); 530 } 531 break; 532 } 533 } 534 }; 535 536 } 537 538 @Override 539 public Tab getCurrentTab() { 540 return mTabControl.getCurrentTab(); 541 } 542 543 @Override 544 public void shareCurrentPage() { 545 shareCurrentPage(mTabControl.getCurrentTab()); 546 } 547 548 private void shareCurrentPage(Tab tab) { 549 if (tab != null) { 550 sharePage(mActivity, tab.getTitle(), 551 tab.getUrl(), tab.getFavicon(), 552 createScreenshot(tab.getWebView(), 553 getDesiredThumbnailWidth(mActivity), 554 getDesiredThumbnailHeight(mActivity))); 555 } 556 } 557 558 /** 559 * Share a page, providing the title, url, favicon, and a screenshot. Uses 560 * an {@link Intent} to launch the Activity chooser. 561 * @param c Context used to launch a new Activity. 562 * @param title Title of the page. Stored in the Intent with 563 * {@link Intent#EXTRA_SUBJECT} 564 * @param url URL of the page. Stored in the Intent with 565 * {@link Intent#EXTRA_TEXT} 566 * @param favicon Bitmap of the favicon for the page. Stored in the Intent 567 * with {@link Browser#EXTRA_SHARE_FAVICON} 568 * @param screenshot Bitmap of a screenshot of the page. Stored in the 569 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT} 570 */ 571 static final void sharePage(Context c, String title, String url, 572 Bitmap favicon, Bitmap screenshot) { 573 Intent send = new Intent(Intent.ACTION_SEND); 574 send.setType("text/plain"); 575 send.putExtra(Intent.EXTRA_TEXT, url); 576 send.putExtra(Intent.EXTRA_SUBJECT, title); 577 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon); 578 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot); 579 try { 580 c.startActivity(Intent.createChooser(send, c.getString( 581 R.string.choosertitle_sharevia))); 582 } catch(android.content.ActivityNotFoundException ex) { 583 // if no app handles it, do nothing 584 } 585 } 586 587 private void copy(CharSequence text) { 588 ClipboardManager cm = (ClipboardManager) mActivity 589 .getSystemService(Context.CLIPBOARD_SERVICE); 590 cm.setText(text); 591 } 592 593 // lifecycle 594 595 protected void onConfgurationChanged(Configuration config) { 596 mConfigChanged = true; 597 if (mPageDialogsHandler != null) { 598 mPageDialogsHandler.onConfigurationChanged(config); 599 } 600 mUi.onConfigurationChanged(config); 601 } 602 603 @Override 604 public void handleNewIntent(Intent intent) { 605 mIntentHandler.onNewIntent(intent); 606 } 607 608 protected void onPause() { 609 if (mUi.isCustomViewShowing()) { 610 hideCustomView(); 611 } 612 if (mActivityPaused) { 613 Log.e(LOGTAG, "BrowserActivity is already paused."); 614 return; 615 } 616 mActivityPaused = true; 617 Tab tab = mTabControl.getCurrentTab(); 618 if (tab != null) { 619 tab.pause(); 620 if (!pauseWebViewTimers(tab)) { 621 mWakeLock.acquire(); 622 mHandler.sendMessageDelayed(mHandler 623 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT); 624 } 625 } 626 mUi.onPause(); 627 mNetworkHandler.onPause(); 628 mNfcHandler.onPause(); 629 630 WebView.disablePlatformNotifications(); 631 mCrashRecoveryHandler.backupState(); 632 633 } 634 635 void onSaveInstanceState(Bundle outState, boolean saveImages) { 636 // the default implementation requires each view to have an id. As the 637 // browser handles the state itself and it doesn't use id for the views, 638 // don't call the default implementation. Otherwise it will trigger the 639 // warning like this, "couldn't save which view has focus because the 640 // focused view XXX has no id". 641 642 // Save all the tabs 643 mTabControl.saveState(outState, saveImages); 644 if (!outState.isEmpty()) { 645 // Save time so that we know how old incognito tabs (if any) are. 646 outState.putSerializable("lastActiveDate", Calendar.getInstance()); 647 } 648 } 649 650 void onResume() { 651 if (!mActivityPaused) { 652 Log.e(LOGTAG, "BrowserActivity is already resumed."); 653 return; 654 } 655 mActivityPaused = false; 656 Tab current = mTabControl.getCurrentTab(); 657 if (current != null) { 658 current.resume(); 659 resumeWebViewTimers(current); 660 } 661 if (mWakeLock.isHeld()) { 662 mHandler.removeMessages(RELEASE_WAKELOCK); 663 mWakeLock.release(); 664 } 665 666 mUi.onResume(); 667 mNetworkHandler.onResume(); 668 mNfcHandler.onResume(); 669 WebView.enablePlatformNotifications(); 670 } 671 672 /** 673 * resume all WebView timers using the WebView instance of the given tab 674 * @param tab guaranteed non-null 675 */ 676 private void resumeWebViewTimers(Tab tab) { 677 boolean inLoad = tab.inPageLoad(); 678 if ((!mActivityPaused && !inLoad) || (mActivityPaused && inLoad)) { 679 CookieSyncManager.getInstance().startSync(); 680 WebView w = tab.getWebView(); 681 WebViewTimersControl.getInstance().onBrowserActivityResume(w); 682 } 683 } 684 685 /** 686 * Pause all WebView timers using the WebView of the given tab 687 * @param tab 688 * @return true if the timers are paused or tab is null 689 */ 690 private boolean pauseWebViewTimers(Tab tab) { 691 if (tab == null) { 692 return true; 693 } else if (!tab.inPageLoad()) { 694 CookieSyncManager.getInstance().stopSync(); 695 WebViewTimersControl.getInstance().onBrowserActivityPause(getCurrentWebView()); 696 return true; 697 } 698 return false; 699 } 700 701 void onDestroy() { 702 if (mUploadHandler != null && !mUploadHandler.handled()) { 703 mUploadHandler.onResult(Activity.RESULT_CANCELED, null); 704 mUploadHandler = null; 705 } 706 if (mTabControl == null) return; 707 mUi.onDestroy(); 708 // Remove the current tab and sub window 709 Tab t = mTabControl.getCurrentTab(); 710 if (t != null) { 711 dismissSubWindow(t); 712 removeTab(t); 713 } 714 mActivity.getContentResolver().unregisterContentObserver(mBookmarksObserver); 715 // Destroy all the tabs 716 mTabControl.destroy(); 717 WebIconDatabase.getInstance().close(); 718 // Stop watching the default geolocation permissions 719 mSystemAllowGeolocationOrigins.stop(); 720 mSystemAllowGeolocationOrigins = null; 721 } 722 723 protected boolean isActivityPaused() { 724 return mActivityPaused; 725 } 726 727 protected void onLowMemory() { 728 mTabControl.freeMemory(); 729 } 730 731 @Override 732 public boolean shouldShowErrorConsole() { 733 return mShouldShowErrorConsole; 734 } 735 736 protected void setShouldShowErrorConsole(boolean show) { 737 if (show == mShouldShowErrorConsole) { 738 // Nothing to do. 739 return; 740 } 741 mShouldShowErrorConsole = show; 742 Tab t = mTabControl.getCurrentTab(); 743 if (t == null) { 744 // There is no current tab so we cannot toggle the error console 745 return; 746 } 747 mUi.setShouldShowErrorConsole(t, show); 748 } 749 750 @Override 751 public void stopLoading() { 752 mLoadStopped = true; 753 Tab tab = mTabControl.getCurrentTab(); 754 WebView w = getCurrentTopWebView(); 755 w.stopLoading(); 756 mUi.onPageStopped(tab); 757 } 758 759 boolean didUserStopLoading() { 760 return mLoadStopped; 761 } 762 763 // WebViewController 764 765 @Override 766 public void onPageStarted(Tab tab, WebView view, Bitmap favicon) { 767 768 // We've started to load a new page. If there was a pending message 769 // to save a screenshot then we will now take the new page and save 770 // an incorrect screenshot. Therefore, remove any pending thumbnail 771 // messages from the queue. 772 mHandler.removeMessages(Controller.UPDATE_BOOKMARK_THUMBNAIL, 773 tab); 774 775 // reset sync timer to avoid sync starts during loading a page 776 CookieSyncManager.getInstance().resetSync(); 777 778 if (!mNetworkHandler.isNetworkUp()) { 779 view.setNetworkAvailable(false); 780 } 781 782 // when BrowserActivity just starts, onPageStarted may be called before 783 // onResume as it is triggered from onCreate. Call resumeWebViewTimers 784 // to start the timer. As we won't switch tabs while an activity is in 785 // pause state, we can ensure calling resume and pause in pair. 786 if (mActivityPaused) { 787 resumeWebViewTimers(tab); 788 } 789 mLoadStopped = false; 790 if (!mNetworkHandler.isNetworkUp()) { 791 mNetworkHandler.createAndShowNetworkDialog(); 792 } 793 endActionMode(); 794 795 mUi.onTabDataChanged(tab); 796 797 String url = tab.getUrl(); 798 // update the bookmark database for favicon 799 maybeUpdateFavicon(tab, null, url, favicon); 800 801 Performance.tracePageStart(url); 802 803 // Performance probe 804 if (false) { 805 Performance.onPageStarted(); 806 } 807 808 } 809 810 @Override 811 public void onPageFinished(Tab tab) { 812 mUi.onTabDataChanged(tab); 813 if (!tab.isPrivateBrowsingEnabled() 814 && !TextUtils.isEmpty(tab.getUrl()) 815 && !tab.isSnapshot()) { 816 // Only update the bookmark screenshot if the user did not 817 // cancel the load early and there is not already 818 // a pending update for the tab. 819 if (tab.inForeground() && !didUserStopLoading() 820 || !tab.inForeground()) { 821 if (!mHandler.hasMessages(UPDATE_BOOKMARK_THUMBNAIL, tab)) { 822 mHandler.sendMessageDelayed(mHandler.obtainMessage( 823 UPDATE_BOOKMARK_THUMBNAIL, 0, 0, tab), 824 500); 825 } 826 } 827 } 828 // pause the WebView timer and release the wake lock if it is finished 829 // while BrowserActivity is in pause state. 830 if (mActivityPaused && pauseWebViewTimers(tab)) { 831 if (mWakeLock.isHeld()) { 832 mHandler.removeMessages(RELEASE_WAKELOCK); 833 mWakeLock.release(); 834 } 835 } 836 837 // Performance probe 838 if (false) { 839 Performance.onPageFinished(tab.getUrl()); 840 } 841 842 Performance.tracePageFinished(); 843 } 844 845 @Override 846 public void onProgressChanged(Tab tab) { 847 int newProgress = tab.getLoadProgress(); 848 849 if (newProgress == 100) { 850 CookieSyncManager.getInstance().sync(); 851 // onProgressChanged() may continue to be called after the main 852 // frame has finished loading, as any remaining sub frames continue 853 // to load. We'll only get called once though with newProgress as 854 // 100 when everything is loaded. (onPageFinished is called once 855 // when the main frame completes loading regardless of the state of 856 // any sub frames so calls to onProgressChanges may continue after 857 // onPageFinished has executed) 858 if (mInLoad) { 859 mInLoad = false; 860 updateInLoadMenuItems(mCachedMenu); 861 } 862 } else { 863 if (!mInLoad) { 864 // onPageFinished may have already been called but a subframe is 865 // still loading and updating the progress. Reset mInLoad and 866 // update the menu items. 867 mInLoad = true; 868 updateInLoadMenuItems(mCachedMenu); 869 } 870 } 871 mUi.onProgressChanged(tab); 872 } 873 874 @Override 875 public void onUpdatedLockIcon(Tab tab) { 876 mUi.onTabDataChanged(tab); 877 } 878 879 @Override 880 public void onReceivedTitle(Tab tab, final String title) { 881 mUi.onTabDataChanged(tab); 882 final String pageUrl = tab.getOriginalUrl(); 883 if (TextUtils.isEmpty(pageUrl) || pageUrl.length() 884 >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) { 885 return; 886 } 887 // Update the title in the history database if not in private browsing mode 888 if (!tab.isPrivateBrowsingEnabled()) { 889 mDataController.updateHistoryTitle(pageUrl, title); 890 } 891 } 892 893 @Override 894 public void onFavicon(Tab tab, WebView view, Bitmap icon) { 895 mUi.onTabDataChanged(tab); 896 maybeUpdateFavicon(tab, view.getOriginalUrl(), view.getUrl(), icon); 897 } 898 899 @Override 900 public boolean shouldOverrideUrlLoading(Tab tab, WebView view, String url) { 901 return mUrlHandler.shouldOverrideUrlLoading(tab, view, url); 902 } 903 904 @Override 905 public boolean shouldOverrideKeyEvent(KeyEvent event) { 906 if (mMenuIsDown) { 907 // only check shortcut key when MENU is held 908 return mActivity.getWindow().isShortcutKey(event.getKeyCode(), 909 event); 910 } else { 911 return false; 912 } 913 } 914 915 @Override 916 public void onUnhandledKeyEvent(KeyEvent event) { 917 if (!isActivityPaused()) { 918 if (event.getAction() == KeyEvent.ACTION_DOWN) { 919 mActivity.onKeyDown(event.getKeyCode(), event); 920 } else { 921 mActivity.onKeyUp(event.getKeyCode(), event); 922 } 923 } 924 } 925 926 @Override 927 public void doUpdateVisitedHistory(Tab tab, boolean isReload) { 928 // Don't save anything in private browsing mode 929 if (tab.isPrivateBrowsingEnabled()) return; 930 String url = tab.getOriginalUrl(); 931 932 if (TextUtils.isEmpty(url) 933 || url.regionMatches(true, 0, "about:", 0, 6)) { 934 return; 935 } 936 mDataController.updateVisitedHistory(url); 937 WebIconDatabase.getInstance().retainIconForPageUrl(url); 938 if (!mActivityPaused) { 939 // Since we clear the state in onPause, don't backup the current 940 // state if we are already paused 941 mCrashRecoveryHandler.backupState(); 942 } 943 } 944 945 @Override 946 public void getVisitedHistory(final ValueCallback<String[]> callback) { 947 AsyncTask<Void, Void, String[]> task = 948 new AsyncTask<Void, Void, String[]>() { 949 @Override 950 public String[] doInBackground(Void... unused) { 951 return Browser.getVisitedHistory(mActivity.getContentResolver()); 952 } 953 @Override 954 public void onPostExecute(String[] result) { 955 callback.onReceiveValue(result); 956 } 957 }; 958 task.execute(); 959 } 960 961 @Override 962 public void onReceivedHttpAuthRequest(Tab tab, WebView view, 963 final HttpAuthHandler handler, final String host, 964 final String realm) { 965 String username = null; 966 String password = null; 967 968 boolean reuseHttpAuthUsernamePassword 969 = handler.useHttpAuthUsernamePassword(); 970 971 if (reuseHttpAuthUsernamePassword && view != null) { 972 String[] credentials = view.getHttpAuthUsernamePassword(host, realm); 973 if (credentials != null && credentials.length == 2) { 974 username = credentials[0]; 975 password = credentials[1]; 976 } 977 } 978 979 if (username != null && password != null) { 980 handler.proceed(username, password); 981 } else { 982 if (tab.inForeground()) { 983 mPageDialogsHandler.showHttpAuthentication(tab, handler, host, realm); 984 } else { 985 handler.cancel(); 986 } 987 } 988 } 989 990 @Override 991 public void onDownloadStart(Tab tab, String url, String userAgent, 992 String contentDisposition, String mimetype, long contentLength) { 993 WebView w = tab.getWebView(); 994 DownloadHandler.onDownloadStart(mActivity, url, userAgent, 995 contentDisposition, mimetype, w.isPrivateBrowsingEnabled()); 996 if (w.copyBackForwardList().getSize() == 0) { 997 // This Tab was opened for the sole purpose of downloading a 998 // file. Remove it. 999 if (tab == mTabControl.getCurrentTab()) { 1000 // In this case, the Tab is still on top. 1001 goBackOnePageOrQuit(); 1002 } else { 1003 // In this case, it is not. 1004 closeTab(tab); 1005 } 1006 } 1007 } 1008 1009 @Override 1010 public Bitmap getDefaultVideoPoster() { 1011 return mUi.getDefaultVideoPoster(); 1012 } 1013 1014 @Override 1015 public View getVideoLoadingProgressView() { 1016 return mUi.getVideoLoadingProgressView(); 1017 } 1018 1019 @Override 1020 public void showSslCertificateOnError(WebView view, SslErrorHandler handler, 1021 SslError error) { 1022 mPageDialogsHandler.showSSLCertificateOnError(view, handler, error); 1023 } 1024 1025 @Override 1026 public void showAutoLogin(Tab tab) { 1027 assert tab.inForeground(); 1028 // Update the title bar to show the auto-login request. 1029 mUi.showAutoLogin(tab); 1030 } 1031 1032 @Override 1033 public void hideAutoLogin(Tab tab) { 1034 assert tab.inForeground(); 1035 mUi.hideAutoLogin(tab); 1036 } 1037 1038 // helper method 1039 1040 /* 1041 * Update the favorites icon if the private browsing isn't enabled and the 1042 * icon is valid. 1043 */ 1044 private void maybeUpdateFavicon(Tab tab, final String originalUrl, 1045 final String url, Bitmap favicon) { 1046 if (favicon == null) { 1047 return; 1048 } 1049 if (!tab.isPrivateBrowsingEnabled()) { 1050 Bookmarks.updateFavicon(mActivity 1051 .getContentResolver(), originalUrl, url, favicon); 1052 } 1053 } 1054 1055 @Override 1056 public void bookmarkedStatusHasChanged(Tab tab) { 1057 // TODO: Switch to using onTabDataChanged after b/3262950 is fixed 1058 mUi.bookmarkedStatusHasChanged(tab); 1059 } 1060 1061 // end WebViewController 1062 1063 protected void pageUp() { 1064 getCurrentTopWebView().pageUp(false); 1065 } 1066 1067 protected void pageDown() { 1068 getCurrentTopWebView().pageDown(false); 1069 } 1070 1071 // callback from phone title bar 1072 public void editUrl() { 1073 if (mOptionsMenuOpen) mActivity.closeOptionsMenu(); 1074 mUi.editUrl(false); 1075 } 1076 1077 public void startVoiceSearch() { 1078 Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH); 1079 intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 1080 RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); 1081 intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, 1082 mActivity.getComponentName().flattenToString()); 1083 intent.putExtra(SEND_APP_ID_EXTRA, false); 1084 intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, true); 1085 mActivity.startActivity(intent); 1086 } 1087 1088 @Override 1089 public void activateVoiceSearchMode(String title, List<String> results) { 1090 mUi.showVoiceTitleBar(title, results); 1091 } 1092 1093 public void revertVoiceSearchMode(Tab tab) { 1094 mUi.revertVoiceTitleBar(tab); 1095 } 1096 1097 public boolean supportsVoiceSearch() { 1098 SearchEngine searchEngine = getSettings().getSearchEngine(); 1099 return (searchEngine != null && searchEngine.supportsVoiceSearch()); 1100 } 1101 1102 public void showCustomView(Tab tab, View view, int requestedOrientation, 1103 WebChromeClient.CustomViewCallback callback) { 1104 if (tab.inForeground()) { 1105 if (mUi.isCustomViewShowing()) { 1106 callback.onCustomViewHidden(); 1107 return; 1108 } 1109 mUi.showCustomView(view, requestedOrientation, callback); 1110 // Save the menu state and set it to empty while the custom 1111 // view is showing. 1112 mOldMenuState = mMenuState; 1113 mMenuState = EMPTY_MENU; 1114 mActivity.invalidateOptionsMenu(); 1115 } 1116 } 1117 1118 @Override 1119 public void hideCustomView() { 1120 if (mUi.isCustomViewShowing()) { 1121 mUi.onHideCustomView(); 1122 // Reset the old menu state. 1123 mMenuState = mOldMenuState; 1124 mOldMenuState = EMPTY_MENU; 1125 mActivity.invalidateOptionsMenu(); 1126 } 1127 } 1128 1129 protected void onActivityResult(int requestCode, int resultCode, 1130 Intent intent) { 1131 if (getCurrentTopWebView() == null) return; 1132 switch (requestCode) { 1133 case PREFERENCES_PAGE: 1134 if (resultCode == Activity.RESULT_OK && intent != null) { 1135 String action = intent.getStringExtra(Intent.EXTRA_TEXT); 1136 if (PreferenceKeys.PREF_PRIVACY_CLEAR_HISTORY.equals(action)) { 1137 mTabControl.removeParentChildRelationShips(); 1138 } 1139 } 1140 break; 1141 case FILE_SELECTED: 1142 // Chose a file from the file picker. 1143 if (null == mUploadHandler) break; 1144 mUploadHandler.onResult(resultCode, intent); 1145 break; 1146 case AUTOFILL_SETUP: 1147 // Determine whether a profile was actually set up or not 1148 // and if so, send the message back to the WebTextView to 1149 // fill the form with the new profile. 1150 if (getSettings().getAutoFillProfile() != null) { 1151 mAutoFillSetupMessage.sendToTarget(); 1152 mAutoFillSetupMessage = null; 1153 } 1154 break; 1155 default: 1156 break; 1157 } 1158 getCurrentTopWebView().requestFocus(); 1159 } 1160 1161 /** 1162 * Open the Go page. 1163 * @param startWithHistory If true, open starting on the history tab. 1164 * Otherwise, start with the bookmarks tab. 1165 */ 1166 @Override 1167 public void bookmarksOrHistoryPicker(boolean startWithHistory) { 1168 if (mTabControl.getCurrentWebView() == null) { 1169 return; 1170 } 1171 // clear action mode 1172 if (isInCustomActionMode()) { 1173 endActionMode(); 1174 } 1175 Bundle extras = new Bundle(); 1176 // Disable opening in a new window if we have maxed out the windows 1177 extras.putBoolean(BrowserBookmarksPage.EXTRA_DISABLE_WINDOW, 1178 !mTabControl.canCreateNewTab()); 1179 mUi.showComboView(startWithHistory 1180 ? ComboViews.History : ComboViews.Bookmarks, extras); 1181 } 1182 1183 // combo view callbacks 1184 1185 /** 1186 * callback from ComboPage when clear history is requested 1187 */ 1188 public void onRemoveParentChildRelationships() { 1189 mTabControl.removeParentChildRelationShips(); 1190 } 1191 1192 /** 1193 * callback from ComboPage when bookmark/history selection 1194 */ 1195 @Override 1196 public void onUrlSelected(String url, boolean newTab) { 1197 removeComboView(); 1198 if (!TextUtils.isEmpty(url)) { 1199 if (newTab) { 1200 final Tab parent = mTabControl.getCurrentTab(); 1201 openTab(url, 1202 (parent != null) && parent.isPrivateBrowsingEnabled(), 1203 !mSettings.openInBackground(), 1204 true); 1205 } else { 1206 final Tab currentTab = mTabControl.getCurrentTab(); 1207 loadUrl(currentTab, url); 1208 } 1209 } 1210 } 1211 1212 /** 1213 * dismiss the ComboPage 1214 */ 1215 @Override 1216 public void removeComboView() { 1217 mUi.hideComboView(); 1218 } 1219 1220 // key handling 1221 protected void onBackKey() { 1222 if (!mUi.onBackKey()) { 1223 WebView subwindow = mTabControl.getCurrentSubWindow(); 1224 if (subwindow != null) { 1225 if (subwindow.canGoBack()) { 1226 subwindow.goBack(); 1227 } else { 1228 dismissSubWindow(mTabControl.getCurrentTab()); 1229 } 1230 } else { 1231 goBackOnePageOrQuit(); 1232 } 1233 } 1234 } 1235 1236 protected boolean onMenuKey() { 1237 return mUi.onMenuKey(); 1238 } 1239 1240 // menu handling and state 1241 // TODO: maybe put into separate handler 1242 1243 protected boolean onCreateOptionsMenu(Menu menu) { 1244 if (mOptionsMenuHandler != null) { 1245 return mOptionsMenuHandler.onCreateOptionsMenu(menu); 1246 } 1247 1248 if (mMenuState == EMPTY_MENU) { 1249 return false; 1250 } 1251 MenuInflater inflater = mActivity.getMenuInflater(); 1252 inflater.inflate(R.menu.browser, menu); 1253 updateInLoadMenuItems(menu); 1254 // hold on to the menu reference here; it is used by the page callbacks 1255 // to update the menu based on loading state 1256 mCachedMenu = menu; 1257 return true; 1258 } 1259 1260 protected void onCreateContextMenu(ContextMenu menu, View v, 1261 ContextMenuInfo menuInfo) { 1262 if (v instanceof TitleBar) { 1263 return; 1264 } 1265 if (!(v instanceof WebView)) { 1266 return; 1267 } 1268 final WebView webview = (WebView) v; 1269 WebView.HitTestResult result = webview.getHitTestResult(); 1270 if (result == null) { 1271 return; 1272 } 1273 1274 int type = result.getType(); 1275 if (type == WebView.HitTestResult.UNKNOWN_TYPE) { 1276 Log.w(LOGTAG, 1277 "We should not show context menu when nothing is touched"); 1278 return; 1279 } 1280 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) { 1281 // let TextView handles context menu 1282 return; 1283 } 1284 1285 // Note, http://b/issue?id=1106666 is requesting that 1286 // an inflated menu can be used again. This is not available 1287 // yet, so inflate each time (yuk!) 1288 MenuInflater inflater = mActivity.getMenuInflater(); 1289 inflater.inflate(R.menu.browsercontext, menu); 1290 1291 // Show the correct menu group 1292 final String extra = result.getExtra(); 1293 menu.setGroupVisible(R.id.PHONE_MENU, 1294 type == WebView.HitTestResult.PHONE_TYPE); 1295 menu.setGroupVisible(R.id.EMAIL_MENU, 1296 type == WebView.HitTestResult.EMAIL_TYPE); 1297 menu.setGroupVisible(R.id.GEO_MENU, 1298 type == WebView.HitTestResult.GEO_TYPE); 1299 menu.setGroupVisible(R.id.IMAGE_MENU, 1300 type == WebView.HitTestResult.IMAGE_TYPE 1301 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1302 menu.setGroupVisible(R.id.ANCHOR_MENU, 1303 type == WebView.HitTestResult.SRC_ANCHOR_TYPE 1304 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1305 boolean hitText = type == WebView.HitTestResult.SRC_ANCHOR_TYPE 1306 || type == WebView.HitTestResult.PHONE_TYPE 1307 || type == WebView.HitTestResult.EMAIL_TYPE 1308 || type == WebView.HitTestResult.GEO_TYPE; 1309 menu.setGroupVisible(R.id.SELECT_TEXT_MENU, hitText); 1310 if (hitText) { 1311 menu.findItem(R.id.select_text_menu_id) 1312 .setOnMenuItemClickListener(new SelectText(webview)); 1313 } 1314 // Setup custom handling depending on the type 1315 switch (type) { 1316 case WebView.HitTestResult.PHONE_TYPE: 1317 menu.setHeaderTitle(Uri.decode(extra)); 1318 menu.findItem(R.id.dial_context_menu_id).setIntent( 1319 new Intent(Intent.ACTION_VIEW, Uri 1320 .parse(WebView.SCHEME_TEL + extra))); 1321 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT); 1322 addIntent.putExtra(Insert.PHONE, Uri.decode(extra)); 1323 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); 1324 menu.findItem(R.id.add_contact_context_menu_id).setIntent( 1325 addIntent); 1326 menu.findItem(R.id.copy_phone_context_menu_id) 1327 .setOnMenuItemClickListener( 1328 new Copy(extra)); 1329 break; 1330 1331 case WebView.HitTestResult.EMAIL_TYPE: 1332 menu.setHeaderTitle(extra); 1333 menu.findItem(R.id.email_context_menu_id).setIntent( 1334 new Intent(Intent.ACTION_VIEW, Uri 1335 .parse(WebView.SCHEME_MAILTO + extra))); 1336 menu.findItem(R.id.copy_mail_context_menu_id) 1337 .setOnMenuItemClickListener( 1338 new Copy(extra)); 1339 break; 1340 1341 case WebView.HitTestResult.GEO_TYPE: 1342 menu.setHeaderTitle(extra); 1343 menu.findItem(R.id.map_context_menu_id).setIntent( 1344 new Intent(Intent.ACTION_VIEW, Uri 1345 .parse(WebView.SCHEME_GEO 1346 + URLEncoder.encode(extra)))); 1347 menu.findItem(R.id.copy_geo_context_menu_id) 1348 .setOnMenuItemClickListener( 1349 new Copy(extra)); 1350 break; 1351 1352 case WebView.HitTestResult.SRC_ANCHOR_TYPE: 1353 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: 1354 menu.setHeaderTitle(extra); 1355 // decide whether to show the open link in new tab option 1356 boolean showNewTab = mTabControl.canCreateNewTab(); 1357 MenuItem newTabItem 1358 = menu.findItem(R.id.open_newtab_context_menu_id); 1359 newTabItem.setTitle(getSettings().openInBackground() 1360 ? R.string.contextmenu_openlink_newwindow_background 1361 : R.string.contextmenu_openlink_newwindow); 1362 newTabItem.setVisible(showNewTab); 1363 if (showNewTab) { 1364 if (WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE == type) { 1365 newTabItem.setOnMenuItemClickListener( 1366 new MenuItem.OnMenuItemClickListener() { 1367 @Override 1368 public boolean onMenuItemClick(MenuItem item) { 1369 final HashMap<String, WebView> hrefMap = 1370 new HashMap<String, WebView>(); 1371 hrefMap.put("webview", webview); 1372 final Message msg = mHandler.obtainMessage( 1373 FOCUS_NODE_HREF, 1374 R.id.open_newtab_context_menu_id, 1375 0, hrefMap); 1376 webview.requestFocusNodeHref(msg); 1377 return true; 1378 } 1379 }); 1380 } else { 1381 newTabItem.setOnMenuItemClickListener( 1382 new MenuItem.OnMenuItemClickListener() { 1383 @Override 1384 public boolean onMenuItemClick(MenuItem item) { 1385 final Tab parent = mTabControl.getCurrentTab(); 1386 openTab(extra, parent, 1387 !mSettings.openInBackground(), 1388 true); 1389 return true; 1390 } 1391 }); 1392 } 1393 } 1394 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) { 1395 break; 1396 } 1397 // otherwise fall through to handle image part 1398 case WebView.HitTestResult.IMAGE_TYPE: 1399 if (type == WebView.HitTestResult.IMAGE_TYPE) { 1400 menu.setHeaderTitle(extra); 1401 } 1402 menu.findItem(R.id.view_image_context_menu_id).setIntent( 1403 new Intent(Intent.ACTION_VIEW, Uri.parse(extra))); 1404 menu.findItem(R.id.download_context_menu_id). 1405 setOnMenuItemClickListener( 1406 new Download(mActivity, extra, webview.isPrivateBrowsingEnabled())); 1407 menu.findItem(R.id.set_wallpaper_context_menu_id). 1408 setOnMenuItemClickListener(new WallpaperHandler(mActivity, 1409 extra)); 1410 break; 1411 1412 default: 1413 Log.w(LOGTAG, "We should not get here."); 1414 break; 1415 } 1416 //update the ui 1417 mUi.onContextMenuCreated(menu); 1418 } 1419 1420 /** 1421 * As the menu can be open when loading state changes 1422 * we must manually update the state of the stop/reload menu 1423 * item 1424 */ 1425 private void updateInLoadMenuItems(Menu menu) { 1426 if (menu == null) { 1427 return; 1428 } 1429 MenuItem dest = menu.findItem(R.id.stop_reload_menu_id); 1430 MenuItem src = mInLoad ? 1431 menu.findItem(R.id.stop_menu_id): 1432 menu.findItem(R.id.reload_menu_id); 1433 if (src != null) { 1434 dest.setIcon(src.getIcon()); 1435 dest.setTitle(src.getTitle()); 1436 } 1437 } 1438 1439 boolean onPrepareOptionsMenu(Menu menu) { 1440 if (mOptionsMenuHandler != null) { 1441 return mOptionsMenuHandler.onPrepareOptionsMenu(menu); 1442 } 1443 // Note: setVisible will decide whether an item is visible; while 1444 // setEnabled() will decide whether an item is enabled, which also means 1445 // whether the matching shortcut key will function. 1446 switch (mMenuState) { 1447 case EMPTY_MENU: 1448 if (mCurrentMenuState != mMenuState) { 1449 menu.setGroupVisible(R.id.MAIN_MENU, false); 1450 menu.setGroupEnabled(R.id.MAIN_MENU, false); 1451 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false); 1452 } 1453 break; 1454 default: 1455 if (mCurrentMenuState != mMenuState) { 1456 menu.setGroupVisible(R.id.MAIN_MENU, true); 1457 menu.setGroupEnabled(R.id.MAIN_MENU, true); 1458 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true); 1459 } 1460 updateMenuState(getCurrentTab(), menu); 1461 break; 1462 } 1463 mCurrentMenuState = mMenuState; 1464 return mUi.onPrepareOptionsMenu(menu); 1465 } 1466 1467 @Override 1468 public void updateMenuState(Tab tab, Menu menu) { 1469 boolean canGoBack = false; 1470 boolean canGoForward = false; 1471 boolean isHome = false; 1472 if (tab != null) { 1473 canGoBack = tab.canGoBack(); 1474 canGoForward = tab.canGoForward(); 1475 isHome = mSettings.getHomePage().equals(tab.getUrl()); 1476 } 1477 final MenuItem back = menu.findItem(R.id.back_menu_id); 1478 back.setEnabled(canGoBack); 1479 1480 final MenuItem home = menu.findItem(R.id.homepage_menu_id); 1481 home.setEnabled(!isHome); 1482 1483 final MenuItem forward = menu.findItem(R.id.forward_menu_id); 1484 forward.setEnabled(canGoForward); 1485 1486 final MenuItem source = menu.findItem(mInLoad ? R.id.stop_menu_id : R.id.reload_menu_id); 1487 final MenuItem dest = menu.findItem(R.id.stop_reload_menu_id); 1488 dest.setTitle(source.getTitle()); 1489 dest.setIcon(source.getIcon()); 1490 1491 // decide whether to show the share link option 1492 PackageManager pm = mActivity.getPackageManager(); 1493 Intent send = new Intent(Intent.ACTION_SEND); 1494 send.setType("text/plain"); 1495 ResolveInfo ri = pm.resolveActivity(send, 1496 PackageManager.MATCH_DEFAULT_ONLY); 1497 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null); 1498 1499 boolean isNavDump = mSettings.enableNavDump(); 1500 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id); 1501 nav.setVisible(isNavDump); 1502 nav.setEnabled(isNavDump); 1503 1504 boolean showDebugSettings = mSettings.isDebugEnabled(); 1505 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id); 1506 counter.setVisible(showDebugSettings); 1507 counter.setEnabled(showDebugSettings); 1508 1509 MenuItem saveSnapshot = menu.findItem(R.id.save_snapshot_menu_id); 1510 saveSnapshot.setVisible(tab != null && !tab.isSnapshot()); 1511 } 1512 1513 public boolean onOptionsItemSelected(MenuItem item) { 1514 if (mOptionsMenuHandler != null && 1515 mOptionsMenuHandler.onOptionsItemSelected(item)) { 1516 return true; 1517 } 1518 1519 if (item.getGroupId() != R.id.CONTEXT_MENU) { 1520 // menu remains active, so ensure comboview is dismissed 1521 // if main menu option is selected 1522 removeComboView(); 1523 } 1524 if (null == getCurrentTopWebView()) { 1525 return false; 1526 } 1527 if (mMenuIsDown) { 1528 // The shortcut action consumes the MENU. Even if it is still down, 1529 // it won't trigger the next shortcut action. In the case of the 1530 // shortcut action triggering a new activity, like Bookmarks, we 1531 // won't get onKeyUp for MENU. So it is important to reset it here. 1532 mMenuIsDown = false; 1533 } 1534 switch (item.getItemId()) { 1535 // -- Main menu 1536 case R.id.new_tab_menu_id: 1537 openTabToHomePage(); 1538 break; 1539 1540 case R.id.incognito_menu_id: 1541 openIncognitoTab(); 1542 break; 1543 1544 case R.id.goto_menu_id: 1545 editUrl(); 1546 break; 1547 1548 case R.id.bookmarks_menu_id: 1549 bookmarksOrHistoryPicker(false); 1550 break; 1551 1552 case R.id.add_bookmark_menu_id: 1553 bookmarkCurrentPage(false); 1554 break; 1555 1556 case R.id.stop_reload_menu_id: 1557 if (mInLoad) { 1558 stopLoading(); 1559 } else { 1560 getCurrentTopWebView().reload(); 1561 } 1562 break; 1563 1564 case R.id.back_menu_id: 1565 getCurrentTab().goBack(); 1566 break; 1567 1568 case R.id.forward_menu_id: 1569 getCurrentTab().goForward(); 1570 break; 1571 1572 case R.id.close_menu_id: 1573 // Close the subwindow if it exists. 1574 if (mTabControl.getCurrentSubWindow() != null) { 1575 dismissSubWindow(mTabControl.getCurrentTab()); 1576 break; 1577 } 1578 closeCurrentTab(); 1579 break; 1580 1581 case R.id.homepage_menu_id: 1582 Tab current = mTabControl.getCurrentTab(); 1583 loadUrl(current, mSettings.getHomePage()); 1584 break; 1585 1586 case R.id.preferences_menu_id: 1587 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class); 1588 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE, 1589 getCurrentTopWebView().getUrl()); 1590 mActivity.startActivityForResult(intent, PREFERENCES_PAGE); 1591 break; 1592 1593 case R.id.find_menu_id: 1594 getCurrentTopWebView().showFindDialog(null, true); 1595 break; 1596 1597 case R.id.save_snapshot_menu_id: 1598 final Tab source = getTabControl().getCurrentTab(); 1599 if (source == null) break; 1600 final ContentResolver cr = mActivity.getContentResolver(); 1601 final ContentValues values = source.createSnapshotValues(); 1602 if (values != null) { 1603 new AsyncTask<Tab, Void, Long>() { 1604 1605 @Override 1606 protected Long doInBackground(Tab... params) { 1607 Uri result = cr.insert(Snapshots.CONTENT_URI, values); 1608 long id = ContentUris.parseId(result); 1609 return id; 1610 } 1611 1612 @Override 1613 protected void onPostExecute(Long id) { 1614 Bundle b = new Bundle(); 1615 b.putLong(BrowserSnapshotPage.EXTRA_ANIMATE_ID, id); 1616 mUi.showComboView(ComboViews.Snapshots, b); 1617 }; 1618 }.execute(source); 1619 } else { 1620 Toast.makeText(mActivity, R.string.snapshot_failed, 1621 Toast.LENGTH_SHORT).show(); 1622 } 1623 break; 1624 1625 case R.id.page_info_menu_id: 1626 mPageDialogsHandler.showPageInfo(mTabControl.getCurrentTab(), false, null); 1627 break; 1628 1629 case R.id.classic_history_menu_id: 1630 bookmarksOrHistoryPicker(true); 1631 break; 1632 1633 case R.id.title_bar_share_page_url: 1634 case R.id.share_page_menu_id: 1635 Tab currentTab = mTabControl.getCurrentTab(); 1636 if (null == currentTab) { 1637 return false; 1638 } 1639 shareCurrentPage(currentTab); 1640 break; 1641 1642 case R.id.dump_nav_menu_id: 1643 getCurrentTopWebView().debugDump(); 1644 break; 1645 1646 case R.id.dump_counters_menu_id: 1647 getCurrentTopWebView().dumpV8Counters(); 1648 break; 1649 1650 case R.id.zoom_in_menu_id: 1651 getCurrentTopWebView().zoomIn(); 1652 break; 1653 1654 case R.id.zoom_out_menu_id: 1655 getCurrentTopWebView().zoomOut(); 1656 break; 1657 1658 case R.id.view_downloads_menu_id: 1659 viewDownloads(); 1660 break; 1661 1662 case R.id.window_one_menu_id: 1663 case R.id.window_two_menu_id: 1664 case R.id.window_three_menu_id: 1665 case R.id.window_four_menu_id: 1666 case R.id.window_five_menu_id: 1667 case R.id.window_six_menu_id: 1668 case R.id.window_seven_menu_id: 1669 case R.id.window_eight_menu_id: 1670 { 1671 int menuid = item.getItemId(); 1672 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) { 1673 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) { 1674 Tab desiredTab = mTabControl.getTab(id); 1675 if (desiredTab != null && 1676 desiredTab != mTabControl.getCurrentTab()) { 1677 switchToTab(desiredTab); 1678 } 1679 break; 1680 } 1681 } 1682 } 1683 break; 1684 1685 default: 1686 return false; 1687 } 1688 return true; 1689 } 1690 1691 public boolean onContextItemSelected(MenuItem item) { 1692 // Let the History and Bookmark fragments handle menus they created. 1693 if (item.getGroupId() == R.id.CONTEXT_MENU) { 1694 return false; 1695 } 1696 1697 int id = item.getItemId(); 1698 boolean result = true; 1699 switch (id) { 1700 // For the context menu from the title bar 1701 case R.id.title_bar_copy_page_url: 1702 Tab currentTab = mTabControl.getCurrentTab(); 1703 if (null == currentTab) { 1704 result = false; 1705 break; 1706 } 1707 WebView mainView = currentTab.getWebView(); 1708 if (null == mainView) { 1709 result = false; 1710 break; 1711 } 1712 copy(mainView.getUrl()); 1713 break; 1714 // -- Browser context menu 1715 case R.id.open_context_menu_id: 1716 case R.id.save_link_context_menu_id: 1717 case R.id.copy_link_context_menu_id: 1718 final WebView webView = getCurrentTopWebView(); 1719 if (null == webView) { 1720 result = false; 1721 break; 1722 } 1723 final HashMap<String, WebView> hrefMap = 1724 new HashMap<String, WebView>(); 1725 hrefMap.put("webview", webView); 1726 final Message msg = mHandler.obtainMessage( 1727 FOCUS_NODE_HREF, id, 0, hrefMap); 1728 webView.requestFocusNodeHref(msg); 1729 break; 1730 1731 default: 1732 // For other context menus 1733 result = onOptionsItemSelected(item); 1734 } 1735 return result; 1736 } 1737 1738 /** 1739 * support programmatically opening the context menu 1740 */ 1741 public void openContextMenu(View view) { 1742 mActivity.openContextMenu(view); 1743 } 1744 1745 /** 1746 * programmatically open the options menu 1747 */ 1748 public void openOptionsMenu() { 1749 mActivity.openOptionsMenu(); 1750 } 1751 1752 public boolean onMenuOpened(int featureId, Menu menu) { 1753 if (mOptionsMenuOpen) { 1754 if (mConfigChanged) { 1755 // We do not need to make any changes to the state of the 1756 // title bar, since the only thing that happened was a 1757 // change in orientation 1758 mConfigChanged = false; 1759 } else { 1760 if (!mExtendedMenuOpen) { 1761 mExtendedMenuOpen = true; 1762 mUi.onExtendedMenuOpened(); 1763 } else { 1764 // Switching the menu back to icon view, so show the 1765 // title bar once again. 1766 mExtendedMenuOpen = false; 1767 mUi.onExtendedMenuClosed(mInLoad); 1768 } 1769 } 1770 } else { 1771 // The options menu is closed, so open it, and show the title 1772 mOptionsMenuOpen = true; 1773 mConfigChanged = false; 1774 mExtendedMenuOpen = false; 1775 mUi.onOptionsMenuOpened(); 1776 } 1777 return true; 1778 } 1779 1780 public void onOptionsMenuClosed(Menu menu) { 1781 mOptionsMenuOpen = false; 1782 mUi.onOptionsMenuClosed(mInLoad); 1783 } 1784 1785 public void onContextMenuClosed(Menu menu) { 1786 mUi.onContextMenuClosed(menu, mInLoad); 1787 } 1788 1789 // Helper method for getting the top window. 1790 @Override 1791 public WebView getCurrentTopWebView() { 1792 return mTabControl.getCurrentTopWebView(); 1793 } 1794 1795 @Override 1796 public WebView getCurrentWebView() { 1797 return mTabControl.getCurrentWebView(); 1798 } 1799 1800 /* 1801 * This method is called as a result of the user selecting the options 1802 * menu to see the download window. It shows the download window on top of 1803 * the current window. 1804 */ 1805 void viewDownloads() { 1806 Intent intent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS); 1807 mActivity.startActivity(intent); 1808 } 1809 1810 // action mode 1811 1812 void onActionModeStarted(ActionMode mode) { 1813 mUi.onActionModeStarted(mode); 1814 mActionMode = mode; 1815 } 1816 1817 /* 1818 * True if a custom ActionMode (i.e. find or select) is in use. 1819 */ 1820 @Override 1821 public boolean isInCustomActionMode() { 1822 return mActionMode != null; 1823 } 1824 1825 /* 1826 * End the current ActionMode. 1827 */ 1828 @Override 1829 public void endActionMode() { 1830 if (mActionMode != null) { 1831 mActionMode.finish(); 1832 } 1833 } 1834 1835 /* 1836 * Called by find and select when they are finished. Replace title bars 1837 * as necessary. 1838 */ 1839 public void onActionModeFinished(ActionMode mode) { 1840 if (!isInCustomActionMode()) return; 1841 mUi.onActionModeFinished(mInLoad); 1842 mActionMode = null; 1843 } 1844 1845 boolean isInLoad() { 1846 return mInLoad; 1847 } 1848 1849 // bookmark handling 1850 1851 /** 1852 * add the current page as a bookmark to the given folder id 1853 * @param folderId use -1 for the default folder 1854 * @param canBeAnEdit If true, check to see whether the site is already 1855 * bookmarked, and if it is, edit that bookmark. If false, and 1856 * the site is already bookmarked, do not attempt to edit the 1857 * existing bookmark. 1858 */ 1859 @Override 1860 public void bookmarkCurrentPage(boolean canBeAnEdit) { 1861 Intent i = new Intent(mActivity, 1862 AddBookmarkPage.class); 1863 WebView w = getCurrentTopWebView(); 1864 i.putExtra(BrowserContract.Bookmarks.URL, w.getUrl()); 1865 i.putExtra(BrowserContract.Bookmarks.TITLE, w.getTitle()); 1866 String touchIconUrl = w.getTouchIconUrl(); 1867 if (touchIconUrl != null) { 1868 i.putExtra(AddBookmarkPage.TOUCH_ICON_URL, touchIconUrl); 1869 WebSettings settings = w.getSettings(); 1870 if (settings != null) { 1871 i.putExtra(AddBookmarkPage.USER_AGENT, 1872 settings.getUserAgentString()); 1873 } 1874 } 1875 i.putExtra(BrowserContract.Bookmarks.THUMBNAIL, 1876 createScreenshot(w, getDesiredThumbnailWidth(mActivity), 1877 getDesiredThumbnailHeight(mActivity))); 1878 i.putExtra(BrowserContract.Bookmarks.FAVICON, w.getFavicon()); 1879 if (canBeAnEdit) { 1880 i.putExtra(AddBookmarkPage.CHECK_FOR_DUPE, true); 1881 } 1882 // Put the dialog at the upper right of the screen, covering the 1883 // star on the title bar. 1884 i.putExtra("gravity", Gravity.RIGHT | Gravity.TOP); 1885 mActivity.startActivity(i); 1886 } 1887 1888 // file chooser 1889 public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { 1890 mUploadHandler = new UploadHandler(this); 1891 mUploadHandler.openFileChooser(uploadMsg, acceptType); 1892 } 1893 1894 // thumbnails 1895 1896 /** 1897 * Return the desired width for thumbnail screenshots, which are stored in 1898 * the database, and used on the bookmarks screen. 1899 * @param context Context for finding out the density of the screen. 1900 * @return desired width for thumbnail screenshot. 1901 */ 1902 static int getDesiredThumbnailWidth(Context context) { 1903 return context.getResources().getDimensionPixelOffset( 1904 R.dimen.bookmarkThumbnailWidth); 1905 } 1906 1907 /** 1908 * Return the desired height for thumbnail screenshots, which are stored in 1909 * the database, and used on the bookmarks screen. 1910 * @param context Context for finding out the density of the screen. 1911 * @return desired height for thumbnail screenshot. 1912 */ 1913 static int getDesiredThumbnailHeight(Context context) { 1914 return context.getResources().getDimensionPixelOffset( 1915 R.dimen.bookmarkThumbnailHeight); 1916 } 1917 1918 static Bitmap createScreenshot(Tab tab, int width, int height) { 1919 if ((tab != null) && (tab.getWebView() != null)) { 1920 return createScreenshot(tab.getWebView(), width, height); 1921 } 1922 return null; 1923 } 1924 1925 static Bitmap createScreenshot(WebView view, int width, int height) { 1926 // We render to a bitmap 2x the desired size so that we can then 1927 // re-scale it with filtering since canvas.scale doesn't filter 1928 // This helps reduce aliasing at the cost of being slightly blurry 1929 final int filter_scale = 2; 1930 Picture thumbnail = view.capturePicture(); 1931 if (thumbnail == null) { 1932 return null; 1933 } 1934 width *= filter_scale; 1935 height *= filter_scale; 1936 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); 1937 Canvas canvas = new Canvas(bm); 1938 // May need to tweak these values to determine what is the 1939 // best scale factor 1940 int thumbnailWidth = thumbnail.getWidth(); 1941 int thumbnailHeight = thumbnail.getHeight(); 1942 float scaleFactor = 1.0f; 1943 if (thumbnailWidth > 0 && thumbnailHeight > 0) { 1944 scaleFactor = (float) width / (float)thumbnailWidth; 1945 } else { 1946 return null; 1947 } 1948 1949 float scaleFactorY = (float) height / (float)thumbnailHeight; 1950 if (scaleFactorY > scaleFactor) { 1951 // The picture is narrower than the requested AR 1952 // Center the thumnail and crop the sides 1953 scaleFactor = scaleFactorY; 1954 float wx = (thumbnailWidth * scaleFactor) - width; 1955 canvas.translate((int) -(wx / 2), 0); 1956 } 1957 1958 canvas.scale(scaleFactor, scaleFactor); 1959 1960 thumbnail.draw(canvas); 1961 Bitmap ret = Bitmap.createScaledBitmap(bm, width / filter_scale, 1962 height / filter_scale, true); 1963 bm.recycle(); 1964 return ret; 1965 } 1966 1967 private void updateScreenshot(Tab tab) { 1968 // If this is a bookmarked site, add a screenshot to the database. 1969 // FIXME: Would like to make sure there is actually something to 1970 // draw, but the API for that (WebViewCore.pictureReady()) is not 1971 // currently accessible here. 1972 1973 WebView view = tab.getWebView(); 1974 if (view == null) { 1975 // Tab was destroyed 1976 return; 1977 } 1978 final String url = tab.getUrl(); 1979 final String originalUrl = view.getOriginalUrl(); 1980 1981 if (TextUtils.isEmpty(url)) { 1982 return; 1983 } 1984 1985 // Only update thumbnails for web urls (http(s)://), not for 1986 // about:, javascript:, data:, etc... 1987 // Unless it is a bookmarked site, then always update 1988 if (!Patterns.WEB_URL.matcher(url).matches() && !tab.isBookmarkedSite()) { 1989 return; 1990 } 1991 1992 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(mActivity), 1993 getDesiredThumbnailHeight(mActivity)); 1994 if (bm == null) { 1995 return; 1996 } 1997 1998 final ContentResolver cr = mActivity.getContentResolver(); 1999 new AsyncTask<Void, Void, Void>() { 2000 @Override 2001 protected Void doInBackground(Void... unused) { 2002 Cursor cursor = null; 2003 try { 2004 // TODO: Clean this up 2005 cursor = Bookmarks.queryCombinedForUrl(cr, originalUrl, url); 2006 if (cursor != null && cursor.moveToFirst()) { 2007 final ByteArrayOutputStream os = 2008 new ByteArrayOutputStream(); 2009 bm.compress(Bitmap.CompressFormat.PNG, 100, os); 2010 2011 ContentValues values = new ContentValues(); 2012 values.put(Images.THUMBNAIL, os.toByteArray()); 2013 2014 do { 2015 values.put(Images.URL, cursor.getString(0)); 2016 cr.update(Images.CONTENT_URI, values, null, null); 2017 } while (cursor.moveToNext()); 2018 } 2019 } catch (IllegalStateException e) { 2020 // Ignore 2021 } finally { 2022 if (cursor != null) cursor.close(); 2023 } 2024 return null; 2025 } 2026 }.execute(); 2027 } 2028 2029 private class Copy implements OnMenuItemClickListener { 2030 private CharSequence mText; 2031 2032 public boolean onMenuItemClick(MenuItem item) { 2033 copy(mText); 2034 return true; 2035 } 2036 2037 public Copy(CharSequence toCopy) { 2038 mText = toCopy; 2039 } 2040 } 2041 2042 private static class Download implements OnMenuItemClickListener { 2043 private Activity mActivity; 2044 private String mText; 2045 private boolean mPrivateBrowsing; 2046 2047 public boolean onMenuItemClick(MenuItem item) { 2048 DownloadHandler.onDownloadStartNoStream(mActivity, mText, null, 2049 null, null, mPrivateBrowsing); 2050 return true; 2051 } 2052 2053 public Download(Activity activity, String toDownload, boolean privateBrowsing) { 2054 mActivity = activity; 2055 mText = toDownload; 2056 mPrivateBrowsing = privateBrowsing; 2057 } 2058 } 2059 2060 private static class SelectText implements OnMenuItemClickListener { 2061 private WebView mWebView; 2062 2063 public boolean onMenuItemClick(MenuItem item) { 2064 if (mWebView != null) { 2065 return mWebView.selectText(); 2066 } 2067 return false; 2068 } 2069 2070 public SelectText(WebView webView) { 2071 mWebView = webView; 2072 } 2073 2074 } 2075 2076 /********************** TODO: UI stuff *****************************/ 2077 2078 // these methods have been copied, they still need to be cleaned up 2079 2080 /****************** tabs ***************************************************/ 2081 2082 // basic tab interactions: 2083 2084 // it is assumed that tabcontrol already knows about the tab 2085 protected void addTab(Tab tab) { 2086 mUi.addTab(tab); 2087 } 2088 2089 protected void removeTab(Tab tab) { 2090 mUi.removeTab(tab); 2091 mTabControl.removeTab(tab); 2092 mCrashRecoveryHandler.backupState(); 2093 } 2094 2095 @Override 2096 public void setActiveTab(Tab tab) { 2097 // monkey protection against delayed start 2098 if (tab != null) { 2099 mTabControl.setCurrentTab(tab); 2100 // the tab is guaranteed to have a webview after setCurrentTab 2101 mUi.setActiveTab(tab); 2102 } 2103 } 2104 2105 protected void closeEmptyChildTab() { 2106 Tab current = mTabControl.getCurrentTab(); 2107 if (current != null 2108 && current.getWebView().copyBackForwardList().getSize() == 0) { 2109 Tab parent = current.getParent(); 2110 if (parent != null) { 2111 switchToTab(parent); 2112 closeTab(current); 2113 } 2114 } 2115 } 2116 2117 protected void reuseTab(Tab appTab, UrlData urlData) { 2118 // Dismiss the subwindow if applicable. 2119 dismissSubWindow(appTab); 2120 // Since we might kill the WebView, remove it from the 2121 // content view first. 2122 mUi.detachTab(appTab); 2123 // Recreate the main WebView after destroying the old one. 2124 mTabControl.recreateWebView(appTab); 2125 // TODO: analyze why the remove and add are necessary 2126 mUi.attachTab(appTab); 2127 if (mTabControl.getCurrentTab() != appTab) { 2128 switchToTab(appTab); 2129 loadUrlDataIn(appTab, urlData); 2130 } else { 2131 // If the tab was the current tab, we have to attach 2132 // it to the view system again. 2133 setActiveTab(appTab); 2134 loadUrlDataIn(appTab, urlData); 2135 } 2136 } 2137 2138 // Remove the sub window if it exists. Also called by TabControl when the 2139 // user clicks the 'X' to dismiss a sub window. 2140 public void dismissSubWindow(Tab tab) { 2141 removeSubWindow(tab); 2142 // dismiss the subwindow. This will destroy the WebView. 2143 tab.dismissSubWindow(); 2144 getCurrentTopWebView().requestFocus(); 2145 } 2146 2147 @Override 2148 public void removeSubWindow(Tab t) { 2149 if (t.getSubWebView() != null) { 2150 mUi.removeSubWindow(t.getSubViewContainer()); 2151 } 2152 } 2153 2154 @Override 2155 public void attachSubWindow(Tab tab) { 2156 if (tab.getSubWebView() != null) { 2157 mUi.attachSubWindow(tab.getSubViewContainer()); 2158 getCurrentTopWebView().requestFocus(); 2159 } 2160 } 2161 2162 private Tab showPreloadedTab(final UrlData urlData) { 2163 if (!urlData.isPreloaded()) { 2164 return null; 2165 } 2166 final PreloadedTabControl tabControl = urlData.getPreloadedTab(); 2167 final String sbQuery = urlData.getSearchBoxQueryToSubmit(); 2168 if (sbQuery != null) { 2169 if (!tabControl.searchBoxSubmit(sbQuery, urlData.mUrl, urlData.mHeaders)) { 2170 // Could not submit query. Fallback to regular tab creation 2171 tabControl.destroy(); 2172 return null; 2173 } 2174 } 2175 Tab t = tabControl.getTab(); 2176 mTabControl.addPreloadedTab(t); 2177 addTab(t); 2178 setActiveTab(t); 2179 return t; 2180 } 2181 2182 // open a non inconito tab with the given url data 2183 // and set as active tab 2184 public Tab openTab(UrlData urlData) { 2185 Tab tab = showPreloadedTab(urlData); 2186 if (tab == null) { 2187 tab = createNewTab(false, true, true); 2188 if ((tab != null) && !urlData.isEmpty()) { 2189 loadUrlDataIn(tab, urlData); 2190 } 2191 } 2192 return tab; 2193 } 2194 2195 @Override 2196 public Tab openTabToHomePage() { 2197 return openTab(mSettings.getHomePage(), false, true, false); 2198 } 2199 2200 @Override 2201 public Tab openIncognitoTab() { 2202 return openTab(INCOGNITO_URI, true, true, false); 2203 } 2204 2205 @Override 2206 public Tab openTab(String url, boolean incognito, boolean setActive, 2207 boolean useCurrent) { 2208 return openTab(url, incognito, setActive, useCurrent, null); 2209 } 2210 2211 @Override 2212 public Tab openTab(String url, Tab parent, boolean setActive, 2213 boolean useCurrent) { 2214 return openTab(url, (parent != null) && parent.isPrivateBrowsingEnabled(), 2215 setActive, useCurrent, parent); 2216 } 2217 2218 public Tab openTab(String url, boolean incognito, boolean setActive, 2219 boolean useCurrent, Tab parent) { 2220 Tab tab = createNewTab(incognito, setActive, useCurrent); 2221 if (tab != null) { 2222 if (parent != null && parent != tab) { 2223 parent.addChildTab(tab); 2224 } 2225 if (url != null) { 2226 loadUrl(tab, url); 2227 } 2228 } 2229 return tab; 2230 } 2231 2232 // this method will attempt to create a new tab 2233 // incognito: private browsing tab 2234 // setActive: ste tab as current tab 2235 // useCurrent: if no new tab can be created, return current tab 2236 private Tab createNewTab(boolean incognito, boolean setActive, 2237 boolean useCurrent) { 2238 Tab tab = null; 2239 if (mTabControl.canCreateNewTab()) { 2240 tab = mTabControl.createNewTab(incognito); 2241 addTab(tab); 2242 if (setActive) { 2243 setActiveTab(tab); 2244 } 2245 } else { 2246 if (useCurrent) { 2247 tab = mTabControl.getCurrentTab(); 2248 reuseTab(tab, null); 2249 } else { 2250 mUi.showMaxTabsWarning(); 2251 } 2252 } 2253 return tab; 2254 } 2255 2256 @Override 2257 public SnapshotTab createNewSnapshotTab(long snapshotId, boolean setActive) { 2258 SnapshotTab tab = null; 2259 if (mTabControl.canCreateNewTab()) { 2260 tab = mTabControl.createSnapshotTab(snapshotId); 2261 addTab(tab); 2262 if (setActive) { 2263 setActiveTab(tab); 2264 } 2265 } else { 2266 mUi.showMaxTabsWarning(); 2267 } 2268 return tab; 2269 } 2270 2271 /** 2272 * @param tab the tab to switch to 2273 * @return boolean True if we successfully switched to a different tab. If 2274 * the indexth tab is null, or if that tab is the same as 2275 * the current one, return false. 2276 */ 2277 @Override 2278 public boolean switchToTab(Tab tab) { 2279 // hide combo view if open 2280 removeComboView(); 2281 Tab currentTab = mTabControl.getCurrentTab(); 2282 if (tab == null || tab == currentTab) { 2283 return false; 2284 } 2285 setActiveTab(tab); 2286 return true; 2287 } 2288 2289 @Override 2290 public void closeCurrentTab() { 2291 // hide combo view if open 2292 removeComboView(); 2293 if (mTabControl.getTabCount() == 1) { 2294 mActivity.finish(); 2295 return; 2296 } 2297 final Tab current = mTabControl.getCurrentTab(); 2298 final int pos = mTabControl.getCurrentPosition(); 2299 Tab newTab = current.getParent(); 2300 if (newTab == null) { 2301 newTab = mTabControl.getTab(pos + 1); 2302 if (newTab == null) { 2303 newTab = mTabControl.getTab(pos - 1); 2304 } 2305 } 2306 if (switchToTab(newTab)) { 2307 // Close window 2308 closeTab(current); 2309 } 2310 } 2311 2312 /** 2313 * Close the tab, remove its associated title bar, and adjust mTabControl's 2314 * current tab to a valid value. 2315 */ 2316 @Override 2317 public void closeTab(Tab tab) { 2318 // hide combo view if open 2319 removeComboView(); 2320 removeTab(tab); 2321 } 2322 2323 // Called when loading from context menu or LOAD_URL message 2324 protected void loadUrlFromContext(String url) { 2325 Tab tab = getCurrentTab(); 2326 WebView view = tab != null ? tab.getWebView() : null; 2327 // In case the user enters nothing. 2328 if (url != null && url.length() != 0 && tab != null && view != null) { 2329 url = UrlUtils.smartUrlFilter(url); 2330 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) { 2331 loadUrl(tab, url); 2332 } 2333 } 2334 } 2335 2336 /** 2337 * Load the URL into the given WebView and update the title bar 2338 * to reflect the new load. Call this instead of WebView.loadUrl 2339 * directly. 2340 * @param view The WebView used to load url. 2341 * @param url The URL to load. 2342 */ 2343 @Override 2344 public void loadUrl(Tab tab, String url) { 2345 loadUrl(tab, url, null); 2346 } 2347 2348 protected void loadUrl(Tab tab, String url, Map<String, String> headers) { 2349 if (tab != null) { 2350 dismissSubWindow(tab); 2351 tab.loadUrl(url, headers); 2352 } 2353 } 2354 2355 /** 2356 * Load UrlData into a Tab and update the title bar to reflect the new 2357 * load. Call this instead of UrlData.loadIn directly. 2358 * @param t The Tab used to load. 2359 * @param data The UrlData being loaded. 2360 */ 2361 protected void loadUrlDataIn(Tab t, UrlData data) { 2362 if (data != null) { 2363 if (data.mVoiceIntent != null) { 2364 t.activateVoiceSearchMode(data.mVoiceIntent); 2365 } else if (data.isPreloaded()) { 2366 // this isn't called for preloaded tabs 2367 } else { 2368 loadUrl(t, data.mUrl, data.mHeaders); 2369 } 2370 } 2371 } 2372 2373 @Override 2374 public void onUserCanceledSsl(Tab tab) { 2375 // TODO: Figure out the "right" behavior 2376 if (tab.canGoBack()) { 2377 tab.goBack(); 2378 } else { 2379 tab.loadUrl(mSettings.getHomePage(), null); 2380 } 2381 } 2382 2383 void goBackOnePageOrQuit() { 2384 Tab current = mTabControl.getCurrentTab(); 2385 if (current == null) { 2386 /* 2387 * Instead of finishing the activity, simply push this to the back 2388 * of the stack and let ActivityManager to choose the foreground 2389 * activity. As BrowserActivity is singleTask, it will be always the 2390 * root of the task. So we can use either true or false for 2391 * moveTaskToBack(). 2392 */ 2393 mActivity.moveTaskToBack(true); 2394 return; 2395 } 2396 if (current.canGoBack()) { 2397 current.goBack(); 2398 } else { 2399 // Check to see if we are closing a window that was created by 2400 // another window. If so, we switch back to that window. 2401 Tab parent = current.getParent(); 2402 if (parent != null) { 2403 switchToTab(parent); 2404 // Now we close the other tab 2405 closeTab(current); 2406 } else { 2407 /* 2408 * Instead of finishing the activity, simply push this to the back 2409 * of the stack and let ActivityManager to choose the foreground 2410 * activity. As BrowserActivity is singleTask, it will be always the 2411 * root of the task. So we can use either true or false for 2412 * moveTaskToBack(). 2413 */ 2414 mActivity.moveTaskToBack(true); 2415 } 2416 } 2417 } 2418 2419 /** 2420 * Feed the previously stored results strings to the BrowserProvider so that 2421 * the SearchDialog will show them instead of the standard searches. 2422 * @param result String to show on the editable line of the SearchDialog. 2423 */ 2424 @Override 2425 public void showVoiceSearchResults(String result) { 2426 ContentProviderClient client = mActivity.getContentResolver() 2427 .acquireContentProviderClient(Browser.BOOKMARKS_URI); 2428 ContentProvider prov = client.getLocalContentProvider(); 2429 BrowserProvider bp = (BrowserProvider) prov; 2430 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults()); 2431 client.release(); 2432 2433 Bundle bundle = createGoogleSearchSourceBundle( 2434 GOOGLE_SEARCH_SOURCE_SEARCHKEY); 2435 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true); 2436 startSearch(result, false, bundle, false); 2437 } 2438 2439 private void startSearch(String initialQuery, boolean selectInitialQuery, 2440 Bundle appSearchData, boolean globalSearch) { 2441 if (appSearchData == null) { 2442 appSearchData = createGoogleSearchSourceBundle( 2443 GOOGLE_SEARCH_SOURCE_TYPE); 2444 } 2445 2446 SearchEngine searchEngine = mSettings.getSearchEngine(); 2447 if (searchEngine != null && !searchEngine.supportsVoiceSearch()) { 2448 appSearchData.putBoolean(SearchManager.DISABLE_VOICE_SEARCH, true); 2449 } 2450 mActivity.startSearch(initialQuery, selectInitialQuery, appSearchData, 2451 globalSearch); 2452 } 2453 2454 private Bundle createGoogleSearchSourceBundle(String source) { 2455 Bundle bundle = new Bundle(); 2456 bundle.putString(Search.SOURCE, source); 2457 return bundle; 2458 } 2459 2460 /** 2461 * helper method for key handler 2462 * returns the current tab if it can't advance 2463 */ 2464 private Tab getNextTab() { 2465 return mTabControl.getTab(Math.min(mTabControl.getTabCount() - 1, 2466 mTabControl.getCurrentPosition() + 1)); 2467 } 2468 2469 /** 2470 * helper method for key handler 2471 * returns the current tab if it can't advance 2472 */ 2473 private Tab getPrevTab() { 2474 return mTabControl.getTab(Math.max(0, 2475 mTabControl.getCurrentPosition() - 1)); 2476 } 2477 2478 /** 2479 * handle key events in browser 2480 * 2481 * @param keyCode 2482 * @param event 2483 * @return true if handled, false to pass to super 2484 */ 2485 boolean onKeyDown(int keyCode, KeyEvent event) { 2486 boolean noModifiers = event.hasNoModifiers(); 2487 // Even if MENU is already held down, we need to call to super to open 2488 // the IME on long press. 2489 if (KeyEvent.KEYCODE_MENU == keyCode) { 2490 if (mOptionsMenuHandler != null) { 2491 return false; 2492 } else { 2493 event.startTracking(); 2494 return true; 2495 } 2496 } 2497 if (!noModifiers 2498 && ((KeyEvent.KEYCODE_MENU == keyCode) 2499 || (KeyEvent.KEYCODE_CTRL_LEFT == keyCode) 2500 || (KeyEvent.KEYCODE_CTRL_RIGHT == keyCode))) { 2501 mMenuIsDown = true; 2502 return false; 2503 } 2504 2505 WebView webView = getCurrentTopWebView(); 2506 Tab tab = getCurrentTab(); 2507 if (webView == null || tab == null) return false; 2508 2509 boolean ctrl = event.hasModifiers(KeyEvent.META_CTRL_ON); 2510 boolean shift = event.hasModifiers(KeyEvent.META_SHIFT_ON); 2511 2512 switch(keyCode) { 2513 case KeyEvent.KEYCODE_TAB: 2514 if (event.isCtrlPressed()) { 2515 if (event.isShiftPressed()) { 2516 // prev tab 2517 switchToTab(getPrevTab()); 2518 } else { 2519 // next tab 2520 switchToTab(getNextTab()); 2521 } 2522 return true; 2523 } 2524 break; 2525 case KeyEvent.KEYCODE_SPACE: 2526 // WebView/WebTextView handle the keys in the KeyDown. As 2527 // the Activity's shortcut keys are only handled when WebView 2528 // doesn't, have to do it in onKeyDown instead of onKeyUp. 2529 if (shift) { 2530 pageUp(); 2531 } else if (noModifiers) { 2532 pageDown(); 2533 } 2534 return true; 2535 case KeyEvent.KEYCODE_BACK: 2536 if (!noModifiers) break; 2537 event.startTracking(); 2538 return true; 2539 case KeyEvent.KEYCODE_DPAD_LEFT: 2540 if (ctrl) { 2541 tab.goBack(); 2542 return true; 2543 } 2544 break; 2545 case KeyEvent.KEYCODE_DPAD_RIGHT: 2546 if (ctrl) { 2547 tab.goForward(); 2548 return true; 2549 } 2550 break; 2551 case KeyEvent.KEYCODE_A: 2552 if (ctrl) { 2553 webView.selectAll(); 2554 return true; 2555 } 2556 break; 2557// case KeyEvent.KEYCODE_B: // menu 2558 case KeyEvent.KEYCODE_C: 2559 if (ctrl) { 2560 webView.copySelection(); 2561 return true; 2562 } 2563 break; 2564// case KeyEvent.KEYCODE_D: // menu 2565// case KeyEvent.KEYCODE_E: // in Chrome: puts '?' in URL bar 2566// case KeyEvent.KEYCODE_F: // menu 2567// case KeyEvent.KEYCODE_G: // in Chrome: finds next match 2568// case KeyEvent.KEYCODE_H: // menu 2569// case KeyEvent.KEYCODE_I: // unused 2570// case KeyEvent.KEYCODE_J: // menu 2571// case KeyEvent.KEYCODE_K: // in Chrome: puts '?' in URL bar 2572// case KeyEvent.KEYCODE_L: // menu 2573// case KeyEvent.KEYCODE_M: // unused 2574// case KeyEvent.KEYCODE_N: // in Chrome: new window 2575// case KeyEvent.KEYCODE_O: // in Chrome: open file 2576// case KeyEvent.KEYCODE_P: // in Chrome: print page 2577// case KeyEvent.KEYCODE_Q: // unused 2578// case KeyEvent.KEYCODE_R: 2579// case KeyEvent.KEYCODE_S: // in Chrome: saves page 2580 case KeyEvent.KEYCODE_T: 2581 // we can't use the ctrl/shift flags, they check for 2582 // exclusive use of a modifier 2583 if (event.isCtrlPressed()) { 2584 if (event.isShiftPressed()) { 2585 openIncognitoTab(); 2586 } else { 2587 openTabToHomePage(); 2588 } 2589 return true; 2590 } 2591 break; 2592// case KeyEvent.KEYCODE_U: // in Chrome: opens source of page 2593// case KeyEvent.KEYCODE_V: // text view intercepts to paste 2594 case KeyEvent.KEYCODE_W: // in Chrome: close tab 2595 if (ctrl) { 2596 closeCurrentTab(); 2597 return true; 2598 } 2599 break; 2600// case KeyEvent.KEYCODE_X: // text view intercepts to cut 2601// case KeyEvent.KEYCODE_Y: // unused 2602// case KeyEvent.KEYCODE_Z: // unused 2603 } 2604 // it is a regular key and webview is not null 2605 return mUi.dispatchKey(keyCode, event); 2606 } 2607 2608 boolean onKeyLongPress(int keyCode, KeyEvent event) { 2609 switch(keyCode) { 2610 case KeyEvent.KEYCODE_BACK: 2611 if (mUi.showsWeb()) { 2612 bookmarksOrHistoryPicker(true); 2613 return true; 2614 } 2615 break; 2616 } 2617 return false; 2618 } 2619 2620 boolean onKeyUp(int keyCode, KeyEvent event) { 2621 if (KeyEvent.KEYCODE_MENU == keyCode) { 2622 mMenuIsDown = false; 2623 if (event.isTracking() && !event.isCanceled()) { 2624 return onMenuKey(); 2625 } 2626 } 2627 if (!event.hasNoModifiers()) return false; 2628 switch(keyCode) { 2629 case KeyEvent.KEYCODE_BACK: 2630 if (event.isTracking() && !event.isCanceled()) { 2631 onBackKey(); 2632 return true; 2633 } 2634 break; 2635 } 2636 return false; 2637 } 2638 2639 public boolean isMenuDown() { 2640 return mMenuIsDown; 2641 } 2642 2643 public void setupAutoFill(Message message) { 2644 // Open the settings activity at the AutoFill profile fragment so that 2645 // the user can create a new profile. When they return, we will dispatch 2646 // the message so that we can autofill the form using their new profile. 2647 Intent intent = new Intent(mActivity, BrowserPreferencesPage.class); 2648 intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, 2649 AutoFillSettingsFragment.class.getName()); 2650 mAutoFillSetupMessage = message; 2651 mActivity.startActivityForResult(intent, AUTOFILL_SETUP); 2652 } 2653 2654 @Override 2655 public void registerOptionsMenuHandler(OptionsMenuHandler handler) { 2656 mOptionsMenuHandler = handler; 2657 } 2658 2659 @Override 2660 public void unregisterOptionsMenuHandler(OptionsMenuHandler handler) { 2661 if (mOptionsMenuHandler == handler) { 2662 mOptionsMenuHandler = null; 2663 } 2664 } 2665 2666 @Override 2667 public void registerDropdownChangeListener(DropdownChangeListener d) { 2668 mUi.registerDropdownChangeListener(d); 2669 } 2670 2671 public boolean onSearchRequested() { 2672 mUi.editUrl(false); 2673 return true; 2674 } 2675 2676} 2677