BrowserActivity.java revision 43610292590fe3e2f8d0ddba1adf9e5557c0f401
1/* 2 * Copyright (C) 2006 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.ActionBar; 20import android.app.Activity; 21import android.app.AlertDialog; 22import android.app.ProgressDialog; 23import android.app.SearchManager; 24import android.content.ActivityNotFoundException; 25import android.content.BroadcastReceiver; 26import android.content.ClipboardManager; 27import android.content.ComponentName; 28import android.content.ContentProvider; 29import android.content.ContentProviderClient; 30import android.content.ContentResolver; 31import android.content.ContentUris; 32import android.content.ContentValues; 33import android.content.Context; 34import android.content.DialogInterface; 35import android.content.Intent; 36import android.content.IntentFilter; 37import android.content.pm.PackageInfo; 38import android.content.pm.PackageManager; 39import android.content.pm.ResolveInfo; 40import android.content.res.Configuration; 41import android.content.res.Resources; 42import android.database.Cursor; 43import android.graphics.Bitmap; 44import android.graphics.BitmapFactory; 45import android.graphics.Canvas; 46import android.graphics.Picture; 47import android.graphics.PixelFormat; 48import android.graphics.drawable.Drawable; 49import android.net.ConnectivityManager; 50import android.net.NetworkInfo; 51import android.net.Uri; 52import android.net.WebAddress; 53import android.net.http.SslCertificate; 54import android.net.http.SslError; 55import android.os.AsyncTask; 56import android.os.Bundle; 57import android.os.Debug; 58import android.os.Environment; 59import android.os.Handler; 60import android.os.Message; 61import android.os.PowerManager; 62import android.os.Process; 63import android.os.SystemClock; 64import android.provider.Browser; 65import android.provider.BrowserContract; 66import android.provider.ContactsContract; 67import android.provider.ContactsContract.Intents.Insert; 68import android.provider.Downloads; 69import android.provider.MediaStore; 70import android.speech.RecognizerResultsIntent; 71import android.text.TextUtils; 72import android.text.format.DateFormat; 73import android.util.Log; 74import android.util.Patterns; 75import android.view.ActionMode; 76import android.view.ContextMenu; 77import android.view.ContextMenu.ContextMenuInfo; 78import android.view.Gravity; 79import android.view.KeyEvent; 80import android.view.LayoutInflater; 81import android.view.Menu; 82import android.view.MenuInflater; 83import android.view.MenuItem; 84import android.view.MenuItem.OnMenuItemClickListener; 85import android.view.View; 86import android.view.ViewGroup; 87import android.view.Window; 88import android.view.WindowManager; 89import android.view.accessibility.AccessibilityManager; 90import android.webkit.CookieManager; 91import android.webkit.CookieSyncManager; 92import android.webkit.DownloadListener; 93import android.webkit.HttpAuthHandler; 94import android.webkit.PluginManager; 95import android.webkit.SslErrorHandler; 96import android.webkit.URLUtil; 97import android.webkit.ValueCallback; 98import android.webkit.WebChromeClient; 99import android.webkit.WebHistoryItem; 100import android.webkit.WebIconDatabase; 101import android.webkit.WebView; 102import android.widget.EditText; 103import android.widget.FrameLayout; 104import android.widget.LinearLayout; 105import android.widget.TextView; 106import android.widget.Toast; 107 108import com.android.browser.ScrollWebView.ScrollListener; 109import com.android.common.Search; 110import com.android.common.speech.LoggingEvents; 111 112import java.io.ByteArrayOutputStream; 113import java.io.File; 114import java.io.IOException; 115import java.io.InputStream; 116import java.net.MalformedURLException; 117import java.net.URISyntaxException; 118import java.net.URL; 119import java.net.URLEncoder; 120import java.util.Date; 121import java.util.HashMap; 122import java.util.HashSet; 123import java.util.Iterator; 124import java.util.List; 125import java.util.Map; 126import java.util.Set; 127import java.util.Vector; 128import java.util.regex.Matcher; 129import java.util.regex.Pattern; 130 131public class BrowserActivity extends Activity 132 implements View.OnCreateContextMenuListener, DownloadListener { 133 134 /* Define some aliases to make these debugging flags easier to refer to. 135 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG". 136 */ 137 private final static boolean DEBUG = com.android.browser.Browser.DEBUG; 138 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED; 139 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED; 140 141 // These are single-character shortcuts for searching popular sources. 142 private static final int SHORTCUT_INVALID = 0; 143 private static final int SHORTCUT_GOOGLE_SEARCH = 1; 144 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2; 145 private static final int SHORTCUT_DICTIONARY_SEARCH = 3; 146 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4; 147 148 private static class ClearThumbnails extends AsyncTask<File, Void, Void> { 149 @Override 150 public Void doInBackground(File... files) { 151 if (files != null) { 152 for (File f : files) { 153 if (!f.delete()) { 154 Log.e(LOGTAG, f.getPath() + " was not deleted"); 155 } 156 } 157 } 158 return null; 159 } 160 } 161 162 /** 163 * This layout holds everything you see below the status bar, including the 164 * error console, the custom view container, and the webviews. 165 */ 166 private FrameLayout mBrowserFrameLayout; 167 168 private boolean mXLargeScreenSize; 169 170 private Boolean mIsProviderPresent = null; 171 private Uri mRlzUri = null; 172 173 @Override 174 public void onCreate(Bundle icicle) { 175 if (LOGV_ENABLED) { 176 Log.v(LOGTAG, this + " onStart"); 177 } 178 super.onCreate(icicle); 179 // test the browser in OpenGL 180 // requestWindowFeature(Window.FEATURE_OPENGL); 181 182 // enable this to test the browser in 32bit 183 if (false) { 184 getWindow().setFormat(PixelFormat.RGBX_8888); 185 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888); 186 } 187 188 if (AccessibilityManager.getInstance(this).isEnabled()) { 189 setDefaultKeyMode(DEFAULT_KEYS_DISABLE); 190 } else { 191 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); 192 } 193 194 mResolver = getContentResolver(); 195 196 // If this was a web search request, pass it on to the default web 197 // search provider and finish this activity. 198 if (handleWebSearchIntent(getIntent())) { 199 finish(); 200 return; 201 } 202 203 mSecLockIcon = Resources.getSystem().getDrawable( 204 android.R.drawable.ic_secure); 205 mMixLockIcon = Resources.getSystem().getDrawable( 206 android.R.drawable.ic_partial_secure); 207 208 // Create the tab control and our initial tab 209 mTabControl = new TabControl(this); 210 211 mXLargeScreenSize = (getResources().getConfiguration().screenLayout 212 & Configuration.SCREENLAYOUT_SIZE_MASK) 213 == Configuration.SCREENLAYOUT_SIZE_XLARGE; 214 215 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView() 216 .findViewById(com.android.internal.R.id.content); 217 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this) 218 .inflate(R.layout.custom_screen, null); 219 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById( 220 R.id.main_content); 221 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout 222 .findViewById(R.id.error_console); 223 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout 224 .findViewById(R.id.fullscreen_custom_content); 225 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS); 226 227 if (mXLargeScreenSize) { 228 mTitleBar = new TitleBarXLarge(this); 229 mTitleBar.setProgress(100); 230 mFakeTitleBar = new TitleBarXLarge(this); 231 ActionBar actionBar = getActionBar(); 232 mTabBar = new TabBar(this, mTabControl, (TitleBarXLarge) mFakeTitleBar); 233 actionBar.setCustomNavigationMode(mTabBar); 234 } else { 235 mTitleBar = new TitleBar(this); 236 // mTitleBar will be always be shown in the fully loaded mode on 237 // phone 238 mTitleBar.setProgress(100); 239 mFakeTitleBar = new TitleBar(this); 240 } 241 242 // Open the icon database and retain all the bookmark urls for favicons 243 retainIconsOnStartup(); 244 245 // Keep a settings instance handy. 246 mSettings = BrowserSettings.getInstance(); 247 mSettings.setTabControl(mTabControl); 248 249 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); 250 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser"); 251 252 // Find out if the network is currently up. 253 ConnectivityManager cm = (ConnectivityManager) getSystemService( 254 Context.CONNECTIVITY_SERVICE); 255 NetworkInfo info = cm.getActiveNetworkInfo(); 256 if (info != null) { 257 mIsNetworkUp = info.isAvailable(); 258 } 259 260 /* enables registration for changes in network status from 261 http stack */ 262 mNetworkStateChangedFilter = new IntentFilter(); 263 mNetworkStateChangedFilter.addAction( 264 ConnectivityManager.CONNECTIVITY_ACTION); 265 mNetworkStateIntentReceiver = new BroadcastReceiver() { 266 @Override 267 public void onReceive(Context context, Intent intent) { 268 if (intent.getAction().equals( 269 ConnectivityManager.CONNECTIVITY_ACTION)) { 270 271 NetworkInfo info = intent.getParcelableExtra( 272 ConnectivityManager.EXTRA_NETWORK_INFO); 273 String typeName = info.getTypeName(); 274 String subtypeName = info.getSubtypeName(); 275 sendNetworkType(typeName.toLowerCase(), 276 (subtypeName != null ? subtypeName.toLowerCase() : "")); 277 278 onNetworkToggle(info.isAvailable()); 279 } 280 } 281 }; 282 283 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED); 284 filter.addAction(Intent.ACTION_PACKAGE_REMOVED); 285 filter.addDataScheme("package"); 286 mPackageInstallationReceiver = new BroadcastReceiver() { 287 @Override 288 public void onReceive(Context context, Intent intent) { 289 final String action = intent.getAction(); 290 final String packageName = intent.getData() 291 .getSchemeSpecificPart(); 292 final boolean replacing = intent.getBooleanExtra( 293 Intent.EXTRA_REPLACING, false); 294 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) { 295 // if it is replacing, refreshPlugins() when adding 296 return; 297 } 298 299 if (sGoogleApps.contains(packageName)) { 300 BrowserActivity.this.packageChanged(packageName, 301 Intent.ACTION_PACKAGE_ADDED.equals(action)); 302 } 303 304 PackageManager pm = BrowserActivity.this.getPackageManager(); 305 PackageInfo pkgInfo = null; 306 try { 307 pkgInfo = pm.getPackageInfo(packageName, 308 PackageManager.GET_PERMISSIONS); 309 } catch (PackageManager.NameNotFoundException e) { 310 return; 311 } 312 if (pkgInfo != null) { 313 String permissions[] = pkgInfo.requestedPermissions; 314 if (permissions == null) { 315 return; 316 } 317 boolean permissionOk = false; 318 for (String permit : permissions) { 319 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) { 320 permissionOk = true; 321 break; 322 } 323 } 324 if (permissionOk) { 325 PluginManager.getInstance(BrowserActivity.this) 326 .refreshPlugins(true); 327 } 328 } 329 } 330 }; 331 registerReceiver(mPackageInstallationReceiver, filter); 332 333 if (!mTabControl.restoreState(icicle)) { 334 // clear up the thumbnail directory if we can't restore the state as 335 // none of the files in the directory are referenced any more. 336 new ClearThumbnails().execute( 337 mTabControl.getThumbnailDir().listFiles()); 338 // there is no quit on Android. But if we can't restore the state, 339 // we can treat it as a new Browser, remove the old session cookies. 340 CookieManager.getInstance().removeSessionCookie(); 341 final Intent intent = getIntent(); 342 final Bundle extra = intent.getExtras(); 343 // Create an initial tab. 344 // If the intent is ACTION_VIEW and data is not null, the Browser is 345 // invoked to view the content by another application. In this case, 346 // the tab will be close when exit. 347 UrlData urlData = getUrlDataFromIntent(intent); 348 349 String action = intent.getAction(); 350 final Tab t = mTabControl.createNewTab( 351 (Intent.ACTION_VIEW.equals(action) && 352 intent.getData() != null) 353 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS 354 .equals(action), 355 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), 356 urlData.mUrl, false); 357 mTabControl.setCurrentTab(t); 358 attachTabToContentView(t); 359 WebView webView = t.getWebView(); 360 if (extra != null) { 361 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0); 362 if (scale > 0 && scale <= 1000) { 363 webView.setInitialScale(scale); 364 } 365 } 366 367 if (urlData.isEmpty()) { 368 loadUrl(webView, mSettings.getHomePage()); 369 } else { 370 loadUrlDataIn(t, urlData); 371 } 372 } else { 373 // TabControl.restoreState() will create a new tab even if 374 // restoring the state fails. 375 attachTabToContentView(mTabControl.getCurrentTab()); 376 } 377 378 // Delete old thumbnails to save space 379 File dir = mTabControl.getThumbnailDir(); 380 if (dir.exists()) { 381 for (String child : dir.list()) { 382 File f = new File(dir, child); 383 f.delete(); 384 } 385 } 386 387 // Read JavaScript flags if it exists. 388 String jsFlags = mSettings.getJsFlags(); 389 if (jsFlags.trim().length() != 0) { 390 mTabControl.getCurrentWebView().setJsFlags(jsFlags); 391 } 392 // Work out which packages are installed on the system. 393 getInstalledPackages(); 394 395 // Start watching the default geolocation permissions 396 mSystemAllowGeolocationOrigins 397 = new SystemAllowGeolocationOrigins(getApplicationContext()); 398 mSystemAllowGeolocationOrigins.start(); 399 } 400 401 ScrollListener getScrollListener() { 402 return mTabBar; 403 } 404 405 /** 406 * Feed the previously stored results strings to the BrowserProvider so that 407 * the SearchDialog will show them instead of the standard searches. 408 * @param result String to show on the editable line of the SearchDialog. 409 */ 410 /* package */ void showVoiceSearchResults(String result) { 411 ContentProviderClient client = mResolver.acquireContentProviderClient( 412 Browser.BOOKMARKS_URI); 413 ContentProvider prov = client.getLocalContentProvider(); 414 BrowserProvider bp = (BrowserProvider) prov; 415 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults()); 416 client.release(); 417 418 Bundle bundle = createGoogleSearchSourceBundle( 419 GOOGLE_SEARCH_SOURCE_SEARCHKEY); 420 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true); 421 startSearch(result, false, bundle, false); 422 } 423 424 @Override 425 protected void onNewIntent(Intent intent) { 426 Tab current = mTabControl.getCurrentTab(); 427 // When a tab is closed on exit, the current tab index is set to -1. 428 // Reset before proceed as Browser requires the current tab to be set. 429 if (current == null) { 430 // Try to reset the tab in case the index was incorrect. 431 current = mTabControl.getTab(0); 432 if (current == null) { 433 // No tabs at all so just ignore this intent. 434 return; 435 } 436 mTabControl.setCurrentTab(current); 437 attachTabToContentView(current); 438 resetTitleAndIcon(current.getWebView()); 439 } 440 final String action = intent.getAction(); 441 final int flags = intent.getFlags(); 442 if (Intent.ACTION_MAIN.equals(action) || 443 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) { 444 // just resume the browser 445 return; 446 } 447 // In case the SearchDialog is open. 448 ((SearchManager) getSystemService(Context.SEARCH_SERVICE)) 449 .stopSearch(); 450 boolean activateVoiceSearch = RecognizerResultsIntent 451 .ACTION_VOICE_SEARCH_RESULTS.equals(action); 452 if (Intent.ACTION_VIEW.equals(action) 453 || Intent.ACTION_SEARCH.equals(action) 454 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) 455 || Intent.ACTION_WEB_SEARCH.equals(action) 456 || activateVoiceSearch) { 457 if (current.isInVoiceSearchMode()) { 458 String title = current.getVoiceDisplayTitle(); 459 if (title != null && title.equals(intent.getStringExtra( 460 SearchManager.QUERY))) { 461 // The user submitted the same search as the last voice 462 // search, so do nothing. 463 return; 464 } 465 if (Intent.ACTION_SEARCH.equals(action) 466 && current.voiceSearchSourceIsGoogle()) { 467 Intent logIntent = new Intent( 468 LoggingEvents.ACTION_LOG_EVENT); 469 logIntent.putExtra(LoggingEvents.EXTRA_EVENT, 470 LoggingEvents.VoiceSearch.QUERY_UPDATED); 471 logIntent.putExtra( 472 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE, 473 intent.getDataString()); 474 sendBroadcast(logIntent); 475 // Note, onPageStarted will revert the voice title bar 476 // When http://b/issue?id=2379215 is fixed, we should update 477 // the title bar here. 478 } 479 } 480 // If this was a search request (e.g. search query directly typed into the address bar), 481 // pass it on to the default web search provider. 482 if (handleWebSearchIntent(intent)) { 483 return; 484 } 485 486 UrlData urlData = getUrlDataFromIntent(intent); 487 if (urlData.isEmpty()) { 488 urlData = new UrlData(mSettings.getHomePage()); 489 } 490 491 final String appId = intent 492 .getStringExtra(Browser.EXTRA_APPLICATION_ID); 493 if ((Intent.ACTION_VIEW.equals(action) 494 // If a voice search has no appId, it means that it came 495 // from the browser. In that case, reuse the current tab. 496 || (activateVoiceSearch && appId != null)) 497 && !getPackageName().equals(appId) 498 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) { 499 Tab appTab = mTabControl.getTabFromId(appId); 500 if (appTab != null) { 501 Log.i(LOGTAG, "Reusing tab for " + appId); 502 // Dismiss the subwindow if applicable. 503 dismissSubWindow(appTab); 504 // Since we might kill the WebView, remove it from the 505 // content view first. 506 removeTabFromContentView(appTab); 507 // Recreate the main WebView after destroying the old one. 508 // If the WebView has the same original url and is on that 509 // page, it can be reused. 510 boolean needsLoad = 511 mTabControl.recreateWebView(appTab, urlData); 512 513 if (current != appTab) { 514 switchToTab(mTabControl.getTabIndex(appTab)); 515 if (needsLoad) { 516 loadUrlDataIn(appTab, urlData); 517 } 518 } else { 519 // If the tab was the current tab, we have to attach 520 // it to the view system again. 521 attachTabToContentView(appTab); 522 if (needsLoad) { 523 loadUrlDataIn(appTab, urlData); 524 } 525 } 526 return; 527 } else { 528 // No matching application tab, try to find a regular tab 529 // with a matching url. 530 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl); 531 if (appTab != null) { 532 if (current != appTab) { 533 switchToTab(mTabControl.getTabIndex(appTab)); 534 } 535 // Otherwise, we are already viewing the correct tab. 536 } else { 537 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url 538 // will be opened in a new tab unless we have reached 539 // MAX_TABS. Then the url will be opened in the current 540 // tab. If a new tab is created, it will have "true" for 541 // exit on close. 542 openTabAndShow(urlData, true, appId); 543 } 544 } 545 } else { 546 if (!urlData.isEmpty() 547 && urlData.mUrl.startsWith("about:debug")) { 548 if ("about:debug.dom".equals(urlData.mUrl)) { 549 current.getWebView().dumpDomTree(false); 550 } else if ("about:debug.dom.file".equals(urlData.mUrl)) { 551 current.getWebView().dumpDomTree(true); 552 } else if ("about:debug.render".equals(urlData.mUrl)) { 553 current.getWebView().dumpRenderTree(false); 554 } else if ("about:debug.render.file".equals(urlData.mUrl)) { 555 current.getWebView().dumpRenderTree(true); 556 } else if ("about:debug.display".equals(urlData.mUrl)) { 557 current.getWebView().dumpDisplayTree(); 558 } else if (urlData.mUrl.startsWith("about:debug.drag")) { 559 int index = urlData.mUrl.codePointAt(16) - '0'; 560 if (index <= 0 || index > 9) { 561 current.getWebView().setDragTracker(null); 562 } else { 563 current.getWebView().setDragTracker(new MeshTracker(index)); 564 } 565 } else { 566 mSettings.toggleDebugSettings(); 567 } 568 return; 569 } 570 // Get rid of the subwindow if it exists 571 dismissSubWindow(current); 572 // If the current Tab is being used as an application tab, 573 // remove the association, since the new Intent means that it is 574 // no longer associated with that application. 575 current.setAppId(null); 576 loadUrlDataIn(current, urlData); 577 } 578 } 579 } 580 581 private int parseUrlShortcut(String url) { 582 if (url == null) return SHORTCUT_INVALID; 583 584 // FIXME: quick search, need to be customized by setting 585 if (url.length() > 2 && url.charAt(1) == ' ') { 586 switch (url.charAt(0)) { 587 case 'g': return SHORTCUT_GOOGLE_SEARCH; 588 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH; 589 case 'd': return SHORTCUT_DICTIONARY_SEARCH; 590 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH; 591 } 592 } 593 return SHORTCUT_INVALID; 594 } 595 596 /** 597 * Launches the default web search activity with the query parameters if the given intent's data 598 * are identified as plain search terms and not URLs/shortcuts. 599 * @return true if the intent was handled and web search activity was launched, false if not. 600 */ 601 private boolean handleWebSearchIntent(Intent intent) { 602 if (intent == null) return false; 603 604 String url = null; 605 final String action = intent.getAction(); 606 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals( 607 action)) { 608 return false; 609 } 610 if (Intent.ACTION_VIEW.equals(action)) { 611 Uri data = intent.getData(); 612 if (data != null) url = data.toString(); 613 } else if (Intent.ACTION_SEARCH.equals(action) 614 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) 615 || Intent.ACTION_WEB_SEARCH.equals(action)) { 616 url = intent.getStringExtra(SearchManager.QUERY); 617 } 618 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA), 619 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); 620 } 621 622 /** 623 * Launches the default web search activity with the query parameters if the given url string 624 * was identified as plain search terms and not URL/shortcut. 625 * @return true if the request was handled and web search activity was launched, false if not. 626 */ 627 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) { 628 if (inUrl == null) return false; 629 630 // In general, we shouldn't modify URL from Intent. 631 // But currently, we get the user-typed URL from search box as well. 632 String url = fixUrl(inUrl).trim(); 633 634 // URLs and site specific search shortcuts are handled by the regular flow of control, so 635 // return early. 636 if (Patterns.WEB_URL.matcher(url).matches() 637 || ACCEPTED_URI_SCHEMA.matcher(url).matches() 638 || parseUrlShortcut(url) != SHORTCUT_INVALID) { 639 return false; 640 } 641 642 final ContentResolver cr = mResolver; 643 final String newUrl = url; 644 if (mTabControl == null || !mTabControl.getCurrentWebView().isPrivateBrowsingEnabled()) { 645 new AsyncTask<Void, Void, Void>() { 646 @Override 647 protected Void doInBackground(Void... unused) { 648 Browser.updateVisitedHistory(cr, newUrl, false); 649 Browser.addSearchUrl(cr, newUrl); 650 return null; 651 } 652 }.execute(); 653 } 654 655 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH); 656 intent.addCategory(Intent.CATEGORY_DEFAULT); 657 intent.putExtra(SearchManager.QUERY, url); 658 if (appData != null) { 659 intent.putExtra(SearchManager.APP_DATA, appData); 660 } 661 if (extraData != null) { 662 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData); 663 } 664 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName()); 665 startActivity(intent); 666 667 return true; 668 } 669 670 private UrlData getUrlDataFromIntent(Intent intent) { 671 String url = ""; 672 Map<String, String> headers = null; 673 if (intent != null) { 674 final String action = intent.getAction(); 675 if (Intent.ACTION_VIEW.equals(action)) { 676 url = smartUrlFilter(intent.getData()); 677 if (url != null && url.startsWith("content:")) { 678 /* Append mimetype so webview knows how to display */ 679 String mimeType = intent.resolveType(getContentResolver()); 680 if (mimeType != null) { 681 url += "?" + mimeType; 682 } 683 } 684 if (url != null && url.startsWith("http")) { 685 final Bundle pairs = intent 686 .getBundleExtra(Browser.EXTRA_HEADERS); 687 if (pairs != null && !pairs.isEmpty()) { 688 Iterator<String> iter = pairs.keySet().iterator(); 689 headers = new HashMap<String, String>(); 690 while (iter.hasNext()) { 691 String key = iter.next(); 692 headers.put(key, pairs.getString(key)); 693 } 694 } 695 } 696 } else if (Intent.ACTION_SEARCH.equals(action) 697 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action) 698 || Intent.ACTION_WEB_SEARCH.equals(action)) { 699 url = intent.getStringExtra(SearchManager.QUERY); 700 if (url != null) { 701 mLastEnteredUrl = url; 702 // In general, we shouldn't modify URL from Intent. 703 // But currently, we get the user-typed URL from search box as well. 704 url = fixUrl(url); 705 url = smartUrlFilter(url); 706 final ContentResolver cr = mResolver; 707 final String newUrl = url; 708 new AsyncTask<Void, Void, Void>() { 709 @Override 710 protected Void doInBackground(Void... unused) { 711 Browser.updateVisitedHistory(cr, newUrl, false); 712 return null; 713 } 714 }.execute(); 715 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&"; 716 if (url.contains(searchSource)) { 717 String source = null; 718 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); 719 if (appData != null) { 720 source = appData.getString(Search.SOURCE); 721 } 722 if (TextUtils.isEmpty(source)) { 723 source = GOOGLE_SEARCH_SOURCE_UNKNOWN; 724 } 725 url = url.replace(searchSource, "&source=android-"+source+"&"); 726 } 727 } 728 } 729 } 730 return new UrlData(url, headers, intent); 731 } 732 /* package */ void showVoiceTitleBar(String title) { 733 mTitleBar.setInVoiceMode(true); 734 mTitleBar.setDisplayTitle(title); 735 mFakeTitleBar.setInVoiceMode(true); 736 mFakeTitleBar.setDisplayTitle(title); 737 } 738 /* package */ void revertVoiceTitleBar() { 739 mTitleBar.setInVoiceMode(false); 740 mTitleBar.setDisplayTitle(mUrl); 741 mFakeTitleBar.setInVoiceMode(false); 742 mFakeTitleBar.setDisplayTitle(mUrl); 743 } 744 /* package */ static String fixUrl(String inUrl) { 745 // FIXME: Converting the url to lower case 746 // duplicates functionality in smartUrlFilter(). 747 // However, changing all current callers of fixUrl to 748 // call smartUrlFilter in addition may have unwanted 749 // consequences, and is deferred for now. 750 int colon = inUrl.indexOf(':'); 751 boolean allLower = true; 752 for (int index = 0; index < colon; index++) { 753 char ch = inUrl.charAt(index); 754 if (!Character.isLetter(ch)) { 755 break; 756 } 757 allLower &= Character.isLowerCase(ch); 758 if (index == colon - 1 && !allLower) { 759 inUrl = inUrl.substring(0, colon).toLowerCase() 760 + inUrl.substring(colon); 761 } 762 } 763 if (inUrl.startsWith("http://") || inUrl.startsWith("https://")) 764 return inUrl; 765 if (inUrl.startsWith("http:") || 766 inUrl.startsWith("https:")) { 767 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) { 768 inUrl = inUrl.replaceFirst("/", "//"); 769 } else inUrl = inUrl.replaceFirst(":", "://"); 770 } 771 return inUrl; 772 } 773 774 @Override 775 protected void onResume() { 776 super.onResume(); 777 if (LOGV_ENABLED) { 778 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this); 779 } 780 781 if (!mActivityInPause) { 782 Log.e(LOGTAG, "BrowserActivity is already resumed."); 783 return; 784 } 785 786 mTabControl.resumeCurrentTab(); 787 mActivityInPause = false; 788 resumeWebViewTimers(); 789 790 if (mWakeLock.isHeld()) { 791 mHandler.removeMessages(RELEASE_WAKELOCK); 792 mWakeLock.release(); 793 } 794 795 registerReceiver(mNetworkStateIntentReceiver, 796 mNetworkStateChangedFilter); 797 WebView.enablePlatformNotifications(); 798 } 799 800 /** 801 * Since the actual title bar is embedded in the WebView, and removing it 802 * would change its appearance, use a different TitleBar to show overlayed 803 * at the top of the screen, when the menu is open or the page is loading. 804 */ 805 private TitleBarBase mFakeTitleBar; 806 807 /** 808 * Keeps track of whether the options menu is open. This is important in 809 * determining whether to show or hide the title bar overlay. 810 */ 811 private boolean mOptionsMenuOpen; 812 813 /** 814 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track 815 * of whether the configuration has changed. The first onMenuOpened call 816 * after a configuration change is simply a reopening of the same menu 817 * (i.e. mIconView did not change). 818 */ 819 private boolean mConfigChanged; 820 821 /** 822 * Whether or not the options menu is in its smaller, icon menu form. When 823 * true, we want the title bar overlay to be up. When false, we do not. 824 * Only meaningful if mOptionsMenuOpen is true. 825 */ 826 private boolean mIconView; 827 828 @Override 829 public boolean onMenuOpened(int featureId, Menu menu) { 830 if (Window.FEATURE_OPTIONS_PANEL == featureId) { 831 if (mOptionsMenuOpen) { 832 if (mConfigChanged) { 833 // We do not need to make any changes to the state of the 834 // title bar, since the only thing that happened was a 835 // change in orientation 836 mConfigChanged = false; 837 } else { 838 if (mIconView) { 839 // Switching the menu to expanded view, so hide the 840 // title bar. 841 hideFakeTitleBar(); 842 mIconView = false; 843 } else { 844 // Switching the menu back to icon view, so show the 845 // title bar once again. 846 showFakeTitleBar(); 847 mIconView = true; 848 } 849 } 850 } else { 851 // The options menu is closed, so open it, and show the title 852 showFakeTitleBar(); 853 mOptionsMenuOpen = true; 854 mConfigChanged = false; 855 mIconView = true; 856 } 857 } 858 return true; 859 } 860 861 void showFakeTitleBar() { 862 if (!isFakeTitleBarShowing() && mActiveTabsPage == null && !mActivityInPause) { 863 WebView mainView = mTabControl.getCurrentWebView(); 864 // if there is no current WebView, don't show the faked title bar; 865 if (mainView == null) { 866 return; 867 } 868 // Do not need to check for null, since the current tab will have 869 // at least a main WebView, or we would have returned above. 870 if (isInCustomActionMode()) { 871 // Do not show the fake title bar, while a custom ActionMode 872 // (i.e. find or select) is showing. 873 return; 874 } 875 if (mXLargeScreenSize) { 876 mContentView.addView(mFakeTitleBar); 877 mTabBar.onShowTitleBar(); 878 } else { 879 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); 880 881 // Add the title bar to the window manager so it can receive 882 // touches 883 // while the menu is up 884 WindowManager.LayoutParams params = 885 new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 886 ViewGroup.LayoutParams.WRAP_CONTENT, 887 WindowManager.LayoutParams.TYPE_APPLICATION, 888 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, 889 PixelFormat.TRANSLUCENT); 890 params.gravity = Gravity.TOP; 891 boolean atTop = mainView.getScrollY() == 0; 892 params.windowAnimations = atTop ? 0 : R.style.TitleBar; 893 manager.addView(mFakeTitleBar, params); 894 } 895 } 896 } 897 898 @Override 899 public void onOptionsMenuClosed(Menu menu) { 900 mOptionsMenuOpen = false; 901 if (!mInLoad) { 902 hideFakeTitleBar(); 903 } else if (!mIconView) { 904 // The page is currently loading, and we are in expanded mode, so 905 // we were not showing the menu. Show it once again. It will be 906 // removed when the page finishes. 907 showFakeTitleBar(); 908 } 909 } 910 911 void stopScrolling() { 912 ((ScrollWebView) mTabControl.getCurrentWebView()).stopScroll(); 913 } 914 915 void hideFakeTitleBar() { 916 if (!isFakeTitleBarShowing()) return; 917 if (mXLargeScreenSize) { 918 mContentView.removeView(mFakeTitleBar); 919 mTabBar.onHideTitleBar(); 920 } else { 921 WindowManager.LayoutParams params = 922 (WindowManager.LayoutParams) mFakeTitleBar.getLayoutParams(); 923 WebView mainView = mTabControl.getCurrentWebView(); 924 // Although we decided whether or not to animate based on the 925 // current 926 // scroll position, the scroll position may have changed since the 927 // fake title bar was displayed. Make sure it has the appropriate 928 // animation/lack thereof before removing. 929 params.windowAnimations = 930 mainView != null && mainView.getScrollY() == 0 ? 0 : R.style.TitleBar; 931 WindowManager manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); 932 manager.updateViewLayout(mFakeTitleBar, params); 933 manager.removeView(mFakeTitleBar); 934 } 935 } 936 937 boolean isFakeTitleBarShowing() { 938 return (mFakeTitleBar.getParent() != null); 939 } 940 941 /** 942 * Special method for the fake title bar to call when displaying its context 943 * menu, since it is in its own Window, and its parent does not show a 944 * context menu. 945 */ 946 /* package */ void showTitleBarContextMenu() { 947 if (null == mTitleBar.getParent()) { 948 return; 949 } 950 openContextMenu(mTitleBar); 951 } 952 953 @Override 954 public void onContextMenuClosed(Menu menu) { 955 super.onContextMenuClosed(menu); 956 if (mInLoad) { 957 showFakeTitleBar(); 958 } 959 } 960 961 /** 962 * onSaveInstanceState(Bundle map) 963 * onSaveInstanceState is called right before onStop(). The map contains 964 * the saved state. 965 */ 966 @Override 967 protected void onSaveInstanceState(Bundle outState) { 968 if (LOGV_ENABLED) { 969 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this); 970 } 971 // the default implementation requires each view to have an id. As the 972 // browser handles the state itself and it doesn't use id for the views, 973 // don't call the default implementation. Otherwise it will trigger the 974 // warning like this, "couldn't save which view has focus because the 975 // focused view XXX has no id". 976 977 // Save all the tabs 978 mTabControl.saveState(outState); 979 } 980 981 @Override 982 protected void onPause() { 983 super.onPause(); 984 985 if (mActivityInPause) { 986 Log.e(LOGTAG, "BrowserActivity is already paused."); 987 return; 988 } 989 990 mTabControl.pauseCurrentTab(); 991 mActivityInPause = true; 992 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) { 993 mWakeLock.acquire(); 994 mHandler.sendMessageDelayed(mHandler 995 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT); 996 } 997 998 // FIXME: This removes the active tabs page and resets the menu to 999 // MAIN_MENU. A better solution might be to do this work in onNewIntent 1000 // but then we would need to save it in onSaveInstanceState and restore 1001 // it in onCreate/onRestoreInstanceState 1002 if (mActiveTabsPage != null) { 1003 removeActiveTabPage(true); 1004 } 1005 1006 cancelStopToast(); 1007 1008 // unregister network state listener 1009 unregisterReceiver(mNetworkStateIntentReceiver); 1010 WebView.disablePlatformNotifications(); 1011 } 1012 1013 @Override 1014 protected void onDestroy() { 1015 if (LOGV_ENABLED) { 1016 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this); 1017 } 1018 super.onDestroy(); 1019 1020 if (mUploadMessage != null) { 1021 mUploadMessage.onReceiveValue(null); 1022 mUploadMessage = null; 1023 } 1024 1025 if (mTabControl == null) return; 1026 1027 // Remove the fake title bar if it is there 1028 hideFakeTitleBar(); 1029 1030 // Remove the current tab and sub window 1031 Tab t = mTabControl.getCurrentTab(); 1032 if (t != null) { 1033 dismissSubWindow(t); 1034 removeTabFromContentView(t); 1035 } 1036 // Destroy all the tabs 1037 mTabControl.destroy(); 1038 WebIconDatabase.getInstance().close(); 1039 1040 unregisterReceiver(mPackageInstallationReceiver); 1041 1042 // Stop watching the default geolocation permissions 1043 mSystemAllowGeolocationOrigins.stop(); 1044 mSystemAllowGeolocationOrigins = null; 1045 } 1046 1047 @Override 1048 public void onConfigurationChanged(Configuration newConfig) { 1049 mConfigChanged = true; 1050 super.onConfigurationChanged(newConfig); 1051 1052 if (mPageInfoDialog != null) { 1053 mPageInfoDialog.dismiss(); 1054 showPageInfo( 1055 mPageInfoView, 1056 mPageInfoFromShowSSLCertificateOnError); 1057 } 1058 if (mSSLCertificateDialog != null) { 1059 mSSLCertificateDialog.dismiss(); 1060 showSSLCertificate( 1061 mSSLCertificateView); 1062 } 1063 if (mSSLCertificateOnErrorDialog != null) { 1064 mSSLCertificateOnErrorDialog.dismiss(); 1065 showSSLCertificateOnError( 1066 mSSLCertificateOnErrorView, 1067 mSSLCertificateOnErrorHandler, 1068 mSSLCertificateOnErrorError); 1069 } 1070 if (mHttpAuthenticationDialog != null) { 1071 String title = ((TextView) mHttpAuthenticationDialog 1072 .findViewById(com.android.internal.R.id.alertTitle)).getText() 1073 .toString(); 1074 String name = ((TextView) mHttpAuthenticationDialog 1075 .findViewById(R.id.username_edit)).getText().toString(); 1076 String password = ((TextView) mHttpAuthenticationDialog 1077 .findViewById(R.id.password_edit)).getText().toString(); 1078 int focusId = mHttpAuthenticationDialog.getCurrentFocus() 1079 .getId(); 1080 mHttpAuthenticationDialog.dismiss(); 1081 showHttpAuthentication(mHttpAuthHandler, null, null, title, 1082 name, password, focusId); 1083 } 1084 } 1085 1086 @Override 1087 public void onLowMemory() { 1088 super.onLowMemory(); 1089 mTabControl.freeMemory(); 1090 } 1091 1092 private void resumeWebViewTimers() { 1093 Tab tab = mTabControl.getCurrentTab(); 1094 if (tab == null) return; // monkey can trigger this 1095 boolean inLoad = tab.inLoad(); 1096 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) { 1097 CookieSyncManager.getInstance().startSync(); 1098 WebView w = tab.getWebView(); 1099 if (w != null) { 1100 w.resumeTimers(); 1101 } 1102 } 1103 } 1104 1105 private boolean pauseWebViewTimers() { 1106 Tab tab = mTabControl.getCurrentTab(); 1107 boolean inLoad = tab.inLoad(); 1108 if (mActivityInPause && !inLoad) { 1109 CookieSyncManager.getInstance().stopSync(); 1110 WebView w = mTabControl.getCurrentWebView(); 1111 if (w != null) { 1112 w.pauseTimers(); 1113 } 1114 return true; 1115 } else { 1116 return false; 1117 } 1118 } 1119 1120 // Open the icon database and retain all the icons for visited sites. 1121 private void retainIconsOnStartup() { 1122 final WebIconDatabase db = WebIconDatabase.getInstance(); 1123 db.open(getDir("icons", 0).getPath()); 1124 Cursor c = null; 1125 try { 1126 c = Browser.getAllBookmarks(mResolver); 1127 if (c.moveToFirst()) { 1128 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL); 1129 do { 1130 String url = c.getString(urlIndex); 1131 db.retainIconForPageUrl(url); 1132 } while (c.moveToNext()); 1133 } 1134 } catch (IllegalStateException e) { 1135 Log.e(LOGTAG, "retainIconsOnStartup", e); 1136 } finally { 1137 if (c!= null) c.close(); 1138 } 1139 } 1140 1141 // Helper method for getting the top window. 1142 WebView getTopWindow() { 1143 return mTabControl.getCurrentTopWebView(); 1144 } 1145 1146 TabControl getTabControl() { 1147 return mTabControl; 1148 } 1149 1150 @Override 1151 public boolean onCreateOptionsMenu(Menu menu) { 1152 super.onCreateOptionsMenu(menu); 1153 1154 MenuInflater inflater = getMenuInflater(); 1155 inflater.inflate(R.menu.browser, menu); 1156 mMenu = menu; 1157 updateInLoadMenuItems(); 1158 return true; 1159 } 1160 1161 /** 1162 * As the menu can be open when loading state changes 1163 * we must manually update the state of the stop/reload menu 1164 * item 1165 */ 1166 private void updateInLoadMenuItems() { 1167 if (mMenu == null) { 1168 return; 1169 } 1170 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id); 1171 MenuItem src = mInLoad ? 1172 mMenu.findItem(R.id.stop_menu_id): 1173 mMenu.findItem(R.id.reload_menu_id); 1174 if (src != null) { 1175 dest.setIcon(src.getIcon()); 1176 dest.setTitle(src.getTitle()); 1177 } 1178 } 1179 1180 @Override 1181 public boolean onContextItemSelected(MenuItem item) { 1182 // chording is not an issue with context menus, but we use the same 1183 // options selector, so set mCanChord to true so we can access them. 1184 mCanChord = true; 1185 int id = item.getItemId(); 1186 boolean result = true; 1187 switch (id) { 1188 // For the context menu from the title bar 1189 case R.id.title_bar_copy_page_url: 1190 Tab currentTab = mTabControl.getCurrentTab(); 1191 if (null == currentTab) { 1192 result = false; 1193 break; 1194 } 1195 WebView mainView = currentTab.getWebView(); 1196 if (null == mainView) { 1197 result = false; 1198 break; 1199 } 1200 copy(mainView.getUrl()); 1201 break; 1202 // -- Browser context menu 1203 case R.id.open_context_menu_id: 1204 case R.id.bookmark_context_menu_id: 1205 case R.id.save_link_context_menu_id: 1206 case R.id.share_link_context_menu_id: 1207 case R.id.copy_link_context_menu_id: 1208 final WebView webView = getTopWindow(); 1209 if (null == webView) { 1210 result = false; 1211 break; 1212 } 1213 final HashMap hrefMap = new HashMap(); 1214 hrefMap.put("webview", webView); 1215 final Message msg = mHandler.obtainMessage( 1216 FOCUS_NODE_HREF, id, 0, hrefMap); 1217 webView.requestFocusNodeHref(msg); 1218 break; 1219 1220 default: 1221 // For other context menus 1222 result = onOptionsItemSelected(item); 1223 } 1224 mCanChord = false; 1225 return result; 1226 } 1227 1228 private Bundle createGoogleSearchSourceBundle(String source) { 1229 Bundle bundle = new Bundle(); 1230 bundle.putString(Search.SOURCE, source); 1231 return bundle; 1232 } 1233 1234 /* package */ void editUrl() { 1235 if (mOptionsMenuOpen) closeOptionsMenu(); 1236 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl(); 1237 startSearch(mSettings.getHomePage().equals(url) ? null : url, true, 1238 null, false); 1239 } 1240 1241 /** 1242 * Overriding this to insert a local information bundle 1243 */ 1244 @Override 1245 public void startSearch(String initialQuery, boolean selectInitialQuery, 1246 Bundle appSearchData, boolean globalSearch) { 1247 if (appSearchData == null) { 1248 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE); 1249 } 1250 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch); 1251 } 1252 1253 /** 1254 * Switch tabs. Called by the TitleBarSet when sliding the title bar 1255 * results in changing tabs. 1256 * @param index Index of the tab to change to, as defined by 1257 * mTabControl.getTabIndex(Tab t). 1258 * @return boolean True if we successfully switched to a different tab. If 1259 * the indexth tab is null, or if that tab is the same as 1260 * the current one, return false. 1261 */ 1262 /* package */ boolean switchToTab(int index) { 1263 Tab tab = mTabControl.getTab(index); 1264 Tab currentTab = mTabControl.getCurrentTab(); 1265 if (tab == null || tab == currentTab) { 1266 return false; 1267 } 1268 if (currentTab != null) { 1269 // currentTab may be null if it was just removed. In that case, 1270 // we do not need to remove it 1271 removeTabFromContentView(currentTab); 1272 } 1273 mTabControl.setCurrentTab(tab); 1274 attachTabToContentView(tab); 1275 resetTitleIconAndProgress(); 1276 updateLockIconToLatest(); 1277 return true; 1278 } 1279 1280 /* package */ Tab openTabToHomePage() { 1281 return openTabAndShow(mSettings.getHomePage(), false, null); 1282 } 1283 1284 /* package */ void closeCurrentWindow() { 1285 final Tab current = mTabControl.getCurrentTab(); 1286 if (mTabControl.getTabCount() == 1) { 1287 // This is the last tab. Open a new one, with the home 1288 // page and close the current one. 1289 openTabToHomePage(); 1290 closeTab(current); 1291 return; 1292 } 1293 final Tab parent = current.getParentTab(); 1294 int indexToShow = -1; 1295 if (parent != null) { 1296 indexToShow = mTabControl.getTabIndex(parent); 1297 } else { 1298 final int currentIndex = mTabControl.getCurrentIndex(); 1299 // Try to move to the tab to the right 1300 indexToShow = currentIndex + 1; 1301 if (indexToShow > mTabControl.getTabCount() - 1) { 1302 // Try to move to the tab to the left 1303 indexToShow = currentIndex - 1; 1304 } 1305 } 1306 if (switchToTab(indexToShow)) { 1307 // Close window 1308 closeTab(current); 1309 } 1310 } 1311 1312 private ActiveTabsPage mActiveTabsPage; 1313 1314 /** 1315 * Remove the active tabs page. 1316 * @param needToAttach If true, the active tabs page did not attach a tab 1317 * to the content view, so we need to do that here. 1318 */ 1319 /* package */ void removeActiveTabPage(boolean needToAttach) { 1320 mContentView.removeView(mActiveTabsPage); 1321 mTitleBar.setVisibility(View.VISIBLE); 1322 mActiveTabsPage = null; 1323 mMenuState = R.id.MAIN_MENU; 1324 if (needToAttach) { 1325 attachTabToContentView(mTabControl.getCurrentTab()); 1326 } 1327 getTopWindow().requestFocus(); 1328 } 1329 1330 @Override 1331 public ActionMode onStartActionMode(ActionMode.Callback callback) { 1332 ActionMode mode = super.onStartActionMode(callback); 1333 if (callback instanceof FindActionModeCallback 1334 || callback instanceof SelectActionModeCallback) { 1335 // For find and select, hide extra title bars. They will 1336 // be replaced in onEndActionMode. 1337 Tab tab = mTabControl.getCurrentTab(); 1338 if (tab.getSubWebView() == null) { 1339 // If the find or select is being performed on the main webview, 1340 // remove the embedded title bar. 1341 WebView mainView = tab.getWebView(); 1342 if (mainView != null) { 1343 mainView.setEmbeddedTitleBar(null); 1344 } 1345 } 1346 hideFakeTitleBar(); 1347 mActionMode = mode; 1348 } else { 1349 // Do not store other ActionModes, since we are unable to determine 1350 // when they finish. 1351 mActionMode = null; 1352 } 1353 return mode; 1354 } 1355 1356 @Override 1357 public boolean onOptionsItemSelected(MenuItem item) { 1358 // check the action bar button before mCanChord check, as the prepare call 1359 // doesn't come for action bar buttons 1360 if (item.getItemId() == R.id.newtab) { 1361 bookmarksOrHistoryPicker(false, true); 1362 return true; 1363 } 1364 if (!mCanChord) { 1365 // The user has already fired a shortcut with this hold down of the 1366 // menu key. 1367 return false; 1368 } 1369 if (null == getTopWindow()) { 1370 return false; 1371 } 1372 if (mMenuIsDown) { 1373 // The shortcut action consumes the MENU. Even if it is still down, 1374 // it won't trigger the next shortcut action. In the case of the 1375 // shortcut action triggering a new activity, like Bookmarks, we 1376 // won't get onKeyUp for MENU. So it is important to reset it here. 1377 mMenuIsDown = false; 1378 } 1379 switch (item.getItemId()) { 1380 // -- Main menu 1381 case R.id.new_tab_menu_id: 1382 openTabToHomePage(); 1383 break; 1384 1385 case R.id.incognito_menu_id: 1386 openIncognitoTab(); 1387 break; 1388 1389 case R.id.goto_menu_id: 1390 editUrl(); 1391 break; 1392 1393 case R.id.bookmarks_menu_id: 1394 bookmarksOrHistoryPicker(false, false); 1395 break; 1396 1397 case R.id.active_tabs_menu_id: 1398 mActiveTabsPage = new ActiveTabsPage(this, mTabControl); 1399 removeTabFromContentView(mTabControl.getCurrentTab()); 1400 mTitleBar.setVisibility(View.GONE); 1401 hideFakeTitleBar(); 1402 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS); 1403 mActiveTabsPage.requestFocus(); 1404 mMenuState = EMPTY_MENU; 1405 break; 1406 1407 case R.id.add_bookmark_menu_id: 1408 bookmarkCurrentPage(); 1409 break; 1410 1411 case R.id.stop_reload_menu_id: 1412 if (mInLoad) { 1413 stopLoading(); 1414 } else { 1415 getTopWindow().reload(); 1416 } 1417 break; 1418 1419 case R.id.back_menu_id: 1420 getTopWindow().goBack(); 1421 break; 1422 1423 case R.id.forward_menu_id: 1424 getTopWindow().goForward(); 1425 break; 1426 1427 case R.id.close_menu_id: 1428 // Close the subwindow if it exists. 1429 if (mTabControl.getCurrentSubWindow() != null) { 1430 dismissSubWindow(mTabControl.getCurrentTab()); 1431 break; 1432 } 1433 closeCurrentWindow(); 1434 break; 1435 1436 case R.id.homepage_menu_id: 1437 Tab current = mTabControl.getCurrentTab(); 1438 if (current != null) { 1439 dismissSubWindow(current); 1440 loadUrl(current.getWebView(), mSettings.getHomePage()); 1441 } 1442 break; 1443 1444 case R.id.preferences_menu_id: 1445 Intent intent = new Intent(this, 1446 BrowserPreferencesPage.class); 1447 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE, 1448 getTopWindow().getUrl()); 1449 startActivityForResult(intent, PREFERENCES_PAGE); 1450 break; 1451 1452 case R.id.find_menu_id: 1453 showFindDialog(null); 1454 break; 1455 1456 case R.id.save_webarchive_menu_id: 1457 if (LOGD_ENABLED) { 1458 Log.d(LOGTAG, "Save as Web Archive"); 1459 } 1460 String directory = getExternalFilesDir(null).getAbsolutePath() + File.separator; 1461 getTopWindow().saveWebArchive(directory, true, new ValueCallback<String>() { 1462 @Override 1463 public void onReceiveValue(String value) { 1464 if (value != null) { 1465 Toast.makeText(BrowserActivity.this, R.string.webarchive_saved, Toast.LENGTH_SHORT).show(); 1466 } else { 1467 Toast.makeText(BrowserActivity.this, R.string.webarchive_failed, Toast.LENGTH_SHORT).show(); 1468 } 1469 } 1470 }); 1471 break; 1472 1473 case R.id.page_info_menu_id: 1474 showPageInfo(mTabControl.getCurrentTab(), false); 1475 break; 1476 1477 case R.id.classic_history_menu_id: 1478 bookmarksOrHistoryPicker(true, false); 1479 break; 1480 1481 case R.id.title_bar_share_page_url: 1482 case R.id.share_page_menu_id: 1483 Tab currentTab = mTabControl.getCurrentTab(); 1484 if (null == currentTab) { 1485 mCanChord = false; 1486 return false; 1487 } 1488 currentTab.populatePickerData(); 1489 sharePage(this, currentTab.getTitle(), 1490 currentTab.getUrl(), currentTab.getFavicon(), 1491 createScreenshot(currentTab.getWebView(), getDesiredThumbnailWidth(this), 1492 getDesiredThumbnailHeight(this))); 1493 break; 1494 1495 case R.id.dump_nav_menu_id: 1496 getTopWindow().debugDump(); 1497 break; 1498 1499 case R.id.dump_counters_menu_id: 1500 getTopWindow().dumpV8Counters(); 1501 break; 1502 1503 case R.id.zoom_in_menu_id: 1504 getTopWindow().zoomIn(); 1505 break; 1506 1507 case R.id.zoom_out_menu_id: 1508 getTopWindow().zoomOut(); 1509 break; 1510 1511 case R.id.view_downloads_menu_id: 1512 viewDownloads(null); 1513 break; 1514 1515 case R.id.window_one_menu_id: 1516 case R.id.window_two_menu_id: 1517 case R.id.window_three_menu_id: 1518 case R.id.window_four_menu_id: 1519 case R.id.window_five_menu_id: 1520 case R.id.window_six_menu_id: 1521 case R.id.window_seven_menu_id: 1522 case R.id.window_eight_menu_id: 1523 { 1524 int menuid = item.getItemId(); 1525 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) { 1526 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) { 1527 Tab desiredTab = mTabControl.getTab(id); 1528 if (desiredTab != null && 1529 desiredTab != mTabControl.getCurrentTab()) { 1530 switchToTab(id); 1531 } 1532 break; 1533 } 1534 } 1535 } 1536 break; 1537 1538 default: 1539 if (!super.onOptionsItemSelected(item)) { 1540 return false; 1541 } 1542 // Otherwise fall through. 1543 } 1544 mCanChord = false; 1545 return true; 1546 } 1547 1548 /* package */ void bookmarkCurrentPage() { 1549 Intent i = new Intent(BrowserActivity.this, 1550 AddBookmarkPage.class); 1551 WebView w = getTopWindow(); 1552 i.putExtra("url", w.getUrl()); 1553 i.putExtra("title", w.getTitle()); 1554 i.putExtra("touch_icon_url", w.getTouchIconUrl()); 1555 i.putExtra("thumbnail", createScreenshot(w, getDesiredThumbnailWidth(this), 1556 getDesiredThumbnailHeight(this))); 1557 i.putExtra("url_editable", false); 1558 startActivity(i); 1559 } 1560 1561 /* 1562 * True if a custom ActionMode (i.e. find or select) is in use. 1563 */ 1564 private boolean isInCustomActionMode() { 1565 return mActionMode != null; 1566 } 1567 1568 /* 1569 * End the current ActionMode. Only works for find and select. 1570 */ 1571 void endActionMode() { 1572 if (mActionMode != null) { 1573 mActionMode.finish(); 1574 } 1575 } 1576 1577 /* 1578 * Called by find and select when they are finished. Replace title bars 1579 * as necessary. 1580 */ 1581 public void onEndActionMode() { 1582 if (!isInCustomActionMode()) return; 1583 // If the Find was being performed in the main WebView, replace the 1584 // embedded title bar. 1585 Tab currentTab = mTabControl.getCurrentTab(); 1586 if (currentTab.getSubWebView() == null) { 1587 WebView mainView = currentTab.getWebView(); 1588 if (mainView != null) { 1589 mainView.setEmbeddedTitleBar(mTitleBar); 1590 } 1591 } 1592 if (mInLoad) { 1593 // The title bar was hidden, because otherwise it would cover up the 1594 // find or select dialog. Now that the dialog has been removed, 1595 // show the fake title bar once again. 1596 showFakeTitleBar(); 1597 } 1598 mActionMode = null; 1599 } 1600 1601 private FindActionModeCallback mFindCallback; 1602 private SelectActionModeCallback mSelectCallback; 1603 1604 // For select and find, we keep track of the ActionMode so that 1605 // finish() can be called as desired. 1606 private ActionMode mActionMode; 1607 1608 /* 1609 * Open the find ActionMode. 1610 * @param text If non null, will be placed in find to be searched for. 1611 */ 1612 public void showFindDialog(String text) { 1613 if (null == mFindCallback) { 1614 mFindCallback = new FindActionModeCallback(this); 1615 } 1616 WebView webView = getTopWindow(); 1617 webView.setFindIsUp(true); 1618 mFindCallback.setWebView(webView); 1619 startActionMode(mFindCallback); 1620 if (text != null) mFindCallback.setText(text); 1621 } 1622 1623 /* 1624 * Show the select ActionMode. 1625 */ 1626 public void showSelectDialog() { 1627 if (null == mSelectCallback) { 1628 mSelectCallback = new SelectActionModeCallback(this); 1629 } 1630 WebView webView = getTopWindow(); 1631 webView.setUpSelect(); 1632 mSelectCallback.setWebView(webView); 1633 startActionMode(mSelectCallback); 1634 } 1635 1636 @Override 1637 public boolean onPrepareOptionsMenu(Menu menu) { 1638 // This happens when the user begins to hold down the menu key, so 1639 // allow them to chord to get a shortcut. 1640 mCanChord = true; 1641 // Note: setVisible will decide whether an item is visible; while 1642 // setEnabled() will decide whether an item is enabled, which also means 1643 // whether the matching shortcut key will function. 1644 super.onPrepareOptionsMenu(menu); 1645 switch (mMenuState) { 1646 case EMPTY_MENU: 1647 if (mCurrentMenuState != mMenuState) { 1648 menu.setGroupVisible(R.id.MAIN_MENU, false); 1649 menu.setGroupEnabled(R.id.MAIN_MENU, false); 1650 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false); 1651 } 1652 break; 1653 default: 1654 if (mCurrentMenuState != mMenuState) { 1655 menu.setGroupVisible(R.id.MAIN_MENU, true); 1656 menu.setGroupEnabled(R.id.MAIN_MENU, true); 1657 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true); 1658 } 1659 final WebView w = getTopWindow(); 1660 boolean canGoBack = false; 1661 boolean canGoForward = false; 1662 boolean isHome = false; 1663 if (w != null) { 1664 canGoBack = w.canGoBack(); 1665 canGoForward = w.canGoForward(); 1666 isHome = mSettings.getHomePage().equals(w.getUrl()); 1667 } 1668 final MenuItem back = menu.findItem(R.id.back_menu_id); 1669 back.setEnabled(canGoBack); 1670 1671 final MenuItem home = menu.findItem(R.id.homepage_menu_id); 1672 home.setEnabled(!isHome); 1673 1674 final MenuItem forward = menu.findItem(R.id.forward_menu_id); 1675 forward.setEnabled(canGoForward); 1676 1677 if (!mXLargeScreenSize) { 1678 final MenuItem newtab = menu.findItem(R.id.new_tab_menu_id); 1679 newtab.setEnabled(mTabControl.canCreateNewTab()); 1680 } 1681 1682 // decide whether to show the share link option 1683 PackageManager pm = getPackageManager(); 1684 Intent send = new Intent(Intent.ACTION_SEND); 1685 send.setType("text/plain"); 1686 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); 1687 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null); 1688 1689 boolean isNavDump = mSettings.isNavDump(); 1690 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id); 1691 nav.setVisible(isNavDump); 1692 nav.setEnabled(isNavDump); 1693 1694 boolean showDebugSettings = mSettings.showDebugSettings(); 1695 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id); 1696 counter.setVisible(showDebugSettings); 1697 counter.setEnabled(showDebugSettings); 1698 1699 break; 1700 } 1701 mCurrentMenuState = mMenuState; 1702 return true; 1703 } 1704 1705 @Override 1706 public void onCreateContextMenu(ContextMenu menu, View v, 1707 ContextMenuInfo menuInfo) { 1708 if (v instanceof TitleBarBase) { 1709 return; 1710 } 1711 WebView webview = (WebView) v; 1712 WebView.HitTestResult result = webview.getHitTestResult(); 1713 if (result == null) { 1714 return; 1715 } 1716 1717 int type = result.getType(); 1718 if (type == WebView.HitTestResult.UNKNOWN_TYPE) { 1719 Log.w(LOGTAG, 1720 "We should not show context menu when nothing is touched"); 1721 return; 1722 } 1723 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) { 1724 // let TextView handles context menu 1725 return; 1726 } 1727 1728 // Note, http://b/issue?id=1106666 is requesting that 1729 // an inflated menu can be used again. This is not available 1730 // yet, so inflate each time (yuk!) 1731 MenuInflater inflater = getMenuInflater(); 1732 inflater.inflate(R.menu.browsercontext, menu); 1733 1734 // Show the correct menu group 1735 final String extra = result.getExtra(); 1736 menu.setGroupVisible(R.id.PHONE_MENU, 1737 type == WebView.HitTestResult.PHONE_TYPE); 1738 menu.setGroupVisible(R.id.EMAIL_MENU, 1739 type == WebView.HitTestResult.EMAIL_TYPE); 1740 menu.setGroupVisible(R.id.GEO_MENU, 1741 type == WebView.HitTestResult.GEO_TYPE); 1742 menu.setGroupVisible(R.id.IMAGE_MENU, 1743 type == WebView.HitTestResult.IMAGE_TYPE 1744 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1745 menu.setGroupVisible(R.id.ANCHOR_MENU, 1746 type == WebView.HitTestResult.SRC_ANCHOR_TYPE 1747 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE); 1748 1749 // Setup custom handling depending on the type 1750 switch (type) { 1751 case WebView.HitTestResult.PHONE_TYPE: 1752 menu.setHeaderTitle(Uri.decode(extra)); 1753 menu.findItem(R.id.dial_context_menu_id).setIntent( 1754 new Intent(Intent.ACTION_VIEW, Uri 1755 .parse(WebView.SCHEME_TEL + extra))); 1756 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT); 1757 addIntent.putExtra(Insert.PHONE, Uri.decode(extra)); 1758 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE); 1759 menu.findItem(R.id.add_contact_context_menu_id).setIntent( 1760 addIntent); 1761 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener( 1762 new Copy(extra)); 1763 break; 1764 1765 case WebView.HitTestResult.EMAIL_TYPE: 1766 menu.setHeaderTitle(extra); 1767 menu.findItem(R.id.email_context_menu_id).setIntent( 1768 new Intent(Intent.ACTION_VIEW, Uri 1769 .parse(WebView.SCHEME_MAILTO + extra))); 1770 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener( 1771 new Copy(extra)); 1772 break; 1773 1774 case WebView.HitTestResult.GEO_TYPE: 1775 menu.setHeaderTitle(extra); 1776 menu.findItem(R.id.map_context_menu_id).setIntent( 1777 new Intent(Intent.ACTION_VIEW, Uri 1778 .parse(WebView.SCHEME_GEO 1779 + URLEncoder.encode(extra)))); 1780 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener( 1781 new Copy(extra)); 1782 break; 1783 1784 case WebView.HitTestResult.SRC_ANCHOR_TYPE: 1785 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE: 1786 TextView titleView = (TextView) LayoutInflater.from(this) 1787 .inflate(android.R.layout.browser_link_context_header, 1788 null); 1789 titleView.setText(extra); 1790 menu.setHeaderView(titleView); 1791 // decide whether to show the open link in new tab option 1792 boolean showNewTab = mTabControl.canCreateNewTab(); 1793 MenuItem newTabItem 1794 = menu.findItem(R.id.open_newtab_context_menu_id); 1795 newTabItem.setVisible(showNewTab); 1796 if (showNewTab) { 1797 newTabItem.setOnMenuItemClickListener( 1798 new MenuItem.OnMenuItemClickListener() { 1799 public boolean onMenuItemClick(MenuItem item) { 1800 final Tab parent = mTabControl.getCurrentTab(); 1801 final Tab newTab = openTab(extra, false); 1802 if (newTab != parent) { 1803 parent.addChildTab(newTab); 1804 } 1805 return true; 1806 } 1807 }); 1808 } 1809 menu.findItem(R.id.bookmark_context_menu_id).setVisible( 1810 Bookmarks.urlHasAcceptableScheme(extra)); 1811 PackageManager pm = getPackageManager(); 1812 Intent send = new Intent(Intent.ACTION_SEND); 1813 send.setType("text/plain"); 1814 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY); 1815 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null); 1816 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) { 1817 break; 1818 } 1819 // otherwise fall through to handle image part 1820 case WebView.HitTestResult.IMAGE_TYPE: 1821 if (type == WebView.HitTestResult.IMAGE_TYPE) { 1822 menu.setHeaderTitle(extra); 1823 } 1824 menu.findItem(R.id.view_image_context_menu_id).setIntent( 1825 new Intent(Intent.ACTION_VIEW, Uri.parse(extra))); 1826 menu.findItem(R.id.download_context_menu_id). 1827 setOnMenuItemClickListener(new Download(extra)); 1828 menu.findItem(R.id.set_wallpaper_context_menu_id). 1829 setOnMenuItemClickListener(new SetAsWallpaper(extra)); 1830 break; 1831 1832 default: 1833 Log.w(LOGTAG, "We should not get here."); 1834 break; 1835 } 1836 hideFakeTitleBar(); 1837 } 1838 1839 // Attach the given tab to the content view. 1840 // this should only be called for the current tab. 1841 private void attachTabToContentView(Tab t) { 1842 // Attach the container that contains the main WebView and any other UI 1843 // associated with the tab. 1844 t.attachTabToContentView(mContentView); 1845 1846 if (mShouldShowErrorConsole) { 1847 ErrorConsoleView errorConsole = t.getErrorConsole(true); 1848 if (errorConsole.numberOfErrors() == 0) { 1849 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); 1850 } else { 1851 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); 1852 } 1853 1854 mErrorConsoleContainer.addView(errorConsole, 1855 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1856 ViewGroup.LayoutParams.WRAP_CONTENT)); 1857 } 1858 1859 WebView view = t.getWebView(); 1860 view.setEmbeddedTitleBar(mTitleBar); 1861 if (t.isInVoiceSearchMode()) { 1862 showVoiceTitleBar(t.getVoiceDisplayTitle()); 1863 } else { 1864 revertVoiceTitleBar(); 1865 } 1866 // Request focus on the top window. 1867 t.getTopWindow().requestFocus(); 1868 if (mTabControl.getTabChangeListener() != null) { 1869 mTabControl.getTabChangeListener().onCurrentTab(t); 1870 } 1871 } 1872 1873 // Attach a sub window to the main WebView of the given tab. 1874 void attachSubWindow(Tab t) { 1875 t.attachSubWindow(mContentView); 1876 getTopWindow().requestFocus(); 1877 } 1878 1879 // Remove the given tab from the content view. 1880 private void removeTabFromContentView(Tab t) { 1881 // Remove the container that contains the main WebView. 1882 t.removeTabFromContentView(mContentView); 1883 1884 ErrorConsoleView errorConsole = t.getErrorConsole(false); 1885 if (errorConsole != null) { 1886 mErrorConsoleContainer.removeView(errorConsole); 1887 } 1888 1889 WebView view = t.getWebView(); 1890 if (view != null) { 1891 view.setEmbeddedTitleBar(null); 1892 } 1893 } 1894 1895 // Remove the sub window if it exists. Also called by TabControl when the 1896 // user clicks the 'X' to dismiss a sub window. 1897 /* package */ void dismissSubWindow(Tab t) { 1898 t.removeSubWindow(mContentView); 1899 // dismiss the subwindow. This will destroy the WebView. 1900 t.dismissSubWindow(); 1901 getTopWindow().requestFocus(); 1902 } 1903 1904 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)} 1905 // that accepts url as string. 1906 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) { 1907 return openTabAndShow(new UrlData(url), closeOnExit, appId); 1908 } 1909 1910 // This method does a ton of stuff. It will attempt to create a new tab 1911 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If 1912 // url isn't null, it will load the given url. 1913 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit, 1914 String appId) { 1915 final Tab currentTab = mTabControl.getCurrentTab(); 1916 if (mTabControl.canCreateNewTab()) { 1917 final Tab tab = mTabControl.createNewTab(closeOnExit, appId, 1918 urlData.mUrl, false); 1919 WebView webview = tab.getWebView(); 1920 // If the last tab was removed from the active tabs page, currentTab 1921 // will be null. 1922 if (currentTab != null) { 1923 removeTabFromContentView(currentTab); 1924 } 1925 // We must set the new tab as the current tab to reflect the old 1926 // animation behavior. 1927 mTabControl.setCurrentTab(tab); 1928 attachTabToContentView(tab); 1929 if (!urlData.isEmpty()) { 1930 loadUrlDataIn(tab, urlData); 1931 } 1932 return tab; 1933 } else { 1934 // Get rid of the subwindow if it exists 1935 dismissSubWindow(currentTab); 1936 if (!urlData.isEmpty()) { 1937 // Load the given url. 1938 loadUrlDataIn(currentTab, urlData); 1939 } 1940 return currentTab; 1941 } 1942 } 1943 1944 private Tab openTab(String url, boolean forceForeground) { 1945 if (mSettings.openInBackground() && !forceForeground) { 1946 Tab t = mTabControl.createNewTab(); 1947 if (t != null) { 1948 WebView view = t.getWebView(); 1949 loadUrl(view, url); 1950 } 1951 return t; 1952 } else { 1953 return openTabAndShow(url, false, null); 1954 } 1955 } 1956 1957 /* package */ Tab openIncognitoTab() { 1958 if (mTabControl.canCreateNewTab()) { 1959 Tab currentTab = mTabControl.getCurrentTab(); 1960 Tab tab = mTabControl.createNewTab(false, null, null, true); 1961 if (currentTab != null) { 1962 removeTabFromContentView(currentTab); 1963 } 1964 mTabControl.setCurrentTab(tab); 1965 attachTabToContentView(tab); 1966 return tab; 1967 } 1968 return null; 1969 } 1970 1971 private class Copy implements OnMenuItemClickListener { 1972 private CharSequence mText; 1973 1974 public boolean onMenuItemClick(MenuItem item) { 1975 copy(mText); 1976 return true; 1977 } 1978 1979 public Copy(CharSequence toCopy) { 1980 mText = toCopy; 1981 } 1982 } 1983 1984 private class Download implements OnMenuItemClickListener { 1985 private String mText; 1986 1987 public boolean onMenuItemClick(MenuItem item) { 1988 onDownloadStartNoStream(mText, null, null, null, -1); 1989 return true; 1990 } 1991 1992 public Download(String toDownload) { 1993 mText = toDownload; 1994 } 1995 } 1996 1997 private class SetAsWallpaper extends Thread implements 1998 OnMenuItemClickListener, DialogInterface.OnCancelListener { 1999 private URL mUrl; 2000 private ProgressDialog mWallpaperProgress; 2001 private boolean mCanceled = false; 2002 2003 public SetAsWallpaper(String url) { 2004 try { 2005 mUrl = new URL(url); 2006 } catch (MalformedURLException e) { 2007 mUrl = null; 2008 } 2009 } 2010 2011 public void onCancel(DialogInterface dialog) { 2012 mCanceled = true; 2013 } 2014 2015 public boolean onMenuItemClick(MenuItem item) { 2016 if (mUrl != null) { 2017 // The user may have tried to set a image with a large file size as their 2018 // background so it may take a few moments to perform the operation. Display 2019 // a progress spinner while it is working. 2020 mWallpaperProgress = new ProgressDialog(BrowserActivity.this); 2021 mWallpaperProgress.setIndeterminate(true); 2022 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper)); 2023 mWallpaperProgress.setCancelable(true); 2024 mWallpaperProgress.setOnCancelListener(this); 2025 mWallpaperProgress.show(); 2026 start(); 2027 } 2028 return true; 2029 } 2030 2031 @Override 2032 public void run() { 2033 Drawable oldWallpaper = BrowserActivity.this.getWallpaper(); 2034 try { 2035 // TODO: This will cause the resource to be downloaded again, when we 2036 // should in most cases be able to grab it from the cache. To fix this 2037 // we should query WebCore to see if we can access a cached version and 2038 // instead open an input stream on that. This pattern could also be used 2039 // in the download manager where the same problem exists. 2040 InputStream inputstream = mUrl.openStream(); 2041 if (inputstream != null) { 2042 setWallpaper(inputstream); 2043 } 2044 } catch (IOException e) { 2045 Log.e(LOGTAG, "Unable to set new wallpaper"); 2046 // Act as though the user canceled the operation so we try to 2047 // restore the old wallpaper. 2048 mCanceled = true; 2049 } 2050 2051 if (mCanceled) { 2052 // Restore the old wallpaper if the user cancelled whilst we were setting 2053 // the new wallpaper. 2054 int width = oldWallpaper.getIntrinsicWidth(); 2055 int height = oldWallpaper.getIntrinsicHeight(); 2056 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); 2057 Canvas canvas = new Canvas(bm); 2058 oldWallpaper.setBounds(0, 0, width, height); 2059 oldWallpaper.draw(canvas); 2060 try { 2061 setWallpaper(bm); 2062 } catch (IOException e) { 2063 Log.e(LOGTAG, "Unable to restore old wallpaper."); 2064 } 2065 mCanceled = false; 2066 } 2067 2068 if (mWallpaperProgress.isShowing()) { 2069 mWallpaperProgress.dismiss(); 2070 } 2071 } 2072 } 2073 2074 private void copy(CharSequence text) { 2075 ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); 2076 cm.setText(text); 2077 } 2078 2079 /** 2080 * Resets the browser title-view to whatever it must be 2081 * (for example, if we had a loading error) 2082 * When we have a new page, we call resetTitle, when we 2083 * have to reset the titlebar to whatever it used to be 2084 * (for example, if the user chose to stop loading), we 2085 * call resetTitleAndRevertLockIcon. 2086 */ 2087 /* package */ void resetTitleAndRevertLockIcon() { 2088 mTabControl.getCurrentTab().revertLockIcon(); 2089 updateLockIconToLatest(); 2090 resetTitleIconAndProgress(); 2091 } 2092 2093 /** 2094 * Reset the title, favicon, and progress. 2095 */ 2096 private void resetTitleIconAndProgress() { 2097 WebView current = mTabControl.getCurrentWebView(); 2098 if (current == null) { 2099 return; 2100 } 2101 resetTitleAndIcon(current); 2102 int progress = current.getProgress(); 2103 current.getWebChromeClient().onProgressChanged(current, progress); 2104 } 2105 2106 // Reset the title and the icon based on the given item. 2107 private void resetTitleAndIcon(WebView view) { 2108 WebHistoryItem item = view.copyBackForwardList().getCurrentItem(); 2109 if (item != null) { 2110 setUrlTitle(item.getUrl(), item.getTitle()); 2111 setFavicon(item.getFavicon()); 2112 } else { 2113 setUrlTitle(null, null); 2114 setFavicon(null); 2115 } 2116 } 2117 2118 /** 2119 * Sets a title composed of the URL and the title string. 2120 * @param url The URL of the site being loaded. 2121 * @param title The title of the site being loaded. 2122 */ 2123 void setUrlTitle(String url, String title) { 2124 mUrl = url; 2125 mTitle = title; 2126 2127 // If we are in voice search mode, the title has already been set. 2128 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return; 2129 mTitleBar.setDisplayTitle(url); 2130 mFakeTitleBar.setDisplayTitle(url); 2131 } 2132 2133 /** 2134 * @param url The URL to build a title version of the URL from. 2135 * @return The title version of the URL or null if fails. 2136 * The title version of the URL can be either the URL hostname, 2137 * or the hostname with an "https://" prefix (for secure URLs), 2138 * or an empty string if, for example, the URL in question is a 2139 * file:// URL with no hostname. 2140 */ 2141 /* package */ static String buildTitleUrl(String url) { 2142 String titleUrl = null; 2143 2144 if (url != null) { 2145 try { 2146 // parse the url string 2147 URL urlObj = new URL(url); 2148 if (urlObj != null) { 2149 titleUrl = ""; 2150 2151 String protocol = urlObj.getProtocol(); 2152 String host = urlObj.getHost(); 2153 2154 if (host != null && 0 < host.length()) { 2155 titleUrl = host; 2156 if (protocol != null) { 2157 // if a secure site, add an "https://" prefix! 2158 if (protocol.equalsIgnoreCase("https")) { 2159 titleUrl = protocol + "://" + host; 2160 } 2161 } 2162 } 2163 } 2164 } catch (MalformedURLException e) {} 2165 } 2166 2167 return titleUrl; 2168 } 2169 2170 // Set the favicon in the title bar. 2171 void setFavicon(Bitmap icon) { 2172 mTitleBar.setFavicon(icon); 2173 mFakeTitleBar.setFavicon(icon); 2174 } 2175 2176 /** 2177 * Close the tab, remove its associated title bar, and adjust mTabControl's 2178 * current tab to a valid value. 2179 */ 2180 /* package */ void closeTab(Tab t) { 2181 int currentIndex = mTabControl.getCurrentIndex(); 2182 int removeIndex = mTabControl.getTabIndex(t); 2183 mTabControl.removeTab(t); 2184 if (currentIndex >= removeIndex && currentIndex != 0) { 2185 currentIndex--; 2186 } 2187 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex)); 2188 resetTitleIconAndProgress(); 2189 updateLockIconToLatest(); 2190 } 2191 2192 /* package */ void goBackOnePageOrQuit() { 2193 Tab current = mTabControl.getCurrentTab(); 2194 if (current == null) { 2195 /* 2196 * Instead of finishing the activity, simply push this to the back 2197 * of the stack and let ActivityManager to choose the foreground 2198 * activity. As BrowserActivity is singleTask, it will be always the 2199 * root of the task. So we can use either true or false for 2200 * moveTaskToBack(). 2201 */ 2202 moveTaskToBack(true); 2203 return; 2204 } 2205 WebView w = current.getWebView(); 2206 if (w.canGoBack()) { 2207 w.goBack(); 2208 } else { 2209 // Check to see if we are closing a window that was created by 2210 // another window. If so, we switch back to that window. 2211 Tab parent = current.getParentTab(); 2212 if (parent != null) { 2213 switchToTab(mTabControl.getTabIndex(parent)); 2214 // Now we close the other tab 2215 closeTab(current); 2216 } else { 2217 if (current.closeOnExit()) { 2218 // force the tab's inLoad() to be false as we are going to 2219 // either finish the activity or remove the tab. This will 2220 // ensure pauseWebViewTimers() taking action. 2221 mTabControl.getCurrentTab().clearInLoad(); 2222 if (mTabControl.getTabCount() == 1) { 2223 finish(); 2224 return; 2225 } 2226 // call pauseWebViewTimers() now, we won't be able to call 2227 // it in onPause() as the WebView won't be valid. 2228 // Temporarily change mActivityInPause to be true as 2229 // pauseWebViewTimers() will do nothing if mActivityInPause 2230 // is false. 2231 boolean savedState = mActivityInPause; 2232 if (savedState) { 2233 Log.e(LOGTAG, "BrowserActivity is already paused " 2234 + "while handing goBackOnePageOrQuit."); 2235 } 2236 mActivityInPause = true; 2237 pauseWebViewTimers(); 2238 mActivityInPause = savedState; 2239 removeTabFromContentView(current); 2240 mTabControl.removeTab(current); 2241 } 2242 /* 2243 * Instead of finishing the activity, simply push this to the back 2244 * of the stack and let ActivityManager to choose the foreground 2245 * activity. As BrowserActivity is singleTask, it will be always the 2246 * root of the task. So we can use either true or false for 2247 * moveTaskToBack(). 2248 */ 2249 moveTaskToBack(true); 2250 } 2251 } 2252 } 2253 2254 boolean isMenuDown() { 2255 return mMenuIsDown; 2256 } 2257 2258 @Override 2259 public boolean onKeyDown(int keyCode, KeyEvent event) { 2260 // Even if MENU is already held down, we need to call to super to open 2261 // the IME on long press. 2262 if (KeyEvent.KEYCODE_MENU == keyCode) { 2263 mMenuIsDown = true; 2264 return super.onKeyDown(keyCode, event); 2265 } 2266 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is 2267 // still down, we don't want to trigger the search. Pretend to consume 2268 // the key and do nothing. 2269 if (mMenuIsDown) return true; 2270 2271 switch(keyCode) { 2272 case KeyEvent.KEYCODE_SPACE: 2273 // WebView/WebTextView handle the keys in the KeyDown. As 2274 // the Activity's shortcut keys are only handled when WebView 2275 // doesn't, have to do it in onKeyDown instead of onKeyUp. 2276 if (event.isShiftPressed()) { 2277 getTopWindow().pageUp(false); 2278 } else { 2279 getTopWindow().pageDown(false); 2280 } 2281 return true; 2282 case KeyEvent.KEYCODE_BACK: 2283 if (event.getRepeatCount() == 0) { 2284 event.startTracking(); 2285 return true; 2286 } else if (mCustomView == null && mActiveTabsPage == null 2287 && event.isLongPress()) { 2288 bookmarksOrHistoryPicker(true, false); 2289 return true; 2290 } 2291 break; 2292 } 2293 return super.onKeyDown(keyCode, event); 2294 } 2295 2296 @Override 2297 public boolean onKeyUp(int keyCode, KeyEvent event) { 2298 switch(keyCode) { 2299 case KeyEvent.KEYCODE_MENU: 2300 mMenuIsDown = false; 2301 break; 2302 case KeyEvent.KEYCODE_BACK: 2303 if (event.isTracking() && !event.isCanceled()) { 2304 if (mCustomView != null) { 2305 // if a custom view is showing, hide it 2306 mTabControl.getCurrentWebView().getWebChromeClient() 2307 .onHideCustomView(); 2308 } else if (mActiveTabsPage != null) { 2309 // if tab page is showing, hide it 2310 removeActiveTabPage(true); 2311 } else { 2312 WebView subwindow = mTabControl.getCurrentSubWindow(); 2313 if (subwindow != null) { 2314 if (subwindow.canGoBack()) { 2315 subwindow.goBack(); 2316 } else { 2317 dismissSubWindow(mTabControl.getCurrentTab()); 2318 } 2319 } else { 2320 goBackOnePageOrQuit(); 2321 } 2322 } 2323 return true; 2324 } 2325 break; 2326 } 2327 return super.onKeyUp(keyCode, event); 2328 } 2329 2330 /* package */ void stopLoading() { 2331 mDidStopLoad = true; 2332 resetTitleAndRevertLockIcon(); 2333 WebView w = getTopWindow(); 2334 w.stopLoading(); 2335 // FIXME: before refactor, it is using mWebViewClient. So I keep the 2336 // same logic here. But for subwindow case, should we call into the main 2337 // WebView's onPageFinished as we never call its onPageStarted and if 2338 // the page finishes itself, we don't call onPageFinished. 2339 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w, 2340 w.getUrl()); 2341 2342 cancelStopToast(); 2343 mStopToast = Toast 2344 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT); 2345 mStopToast.show(); 2346 } 2347 2348 boolean didUserStopLoading() { 2349 return mDidStopLoad; 2350 } 2351 2352 private void cancelStopToast() { 2353 if (mStopToast != null) { 2354 mStopToast.cancel(); 2355 mStopToast = null; 2356 } 2357 } 2358 2359 // called by a UI or non-UI thread to post the message 2360 public void postMessage(int what, int arg1, int arg2, Object obj, 2361 long delayMillis) { 2362 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2, 2363 obj), delayMillis); 2364 } 2365 2366 // called by a UI or non-UI thread to remove the message 2367 void removeMessages(int what, Object object) { 2368 mHandler.removeMessages(what, object); 2369 } 2370 2371 // public message ids 2372 public final static int LOAD_URL = 1001; 2373 public final static int STOP_LOAD = 1002; 2374 2375 // Message Ids 2376 private static final int FOCUS_NODE_HREF = 102; 2377 private static final int RELEASE_WAKELOCK = 107; 2378 2379 static final int UPDATE_BOOKMARK_THUMBNAIL = 108; 2380 2381 private static final int TOUCH_ICON_DOWNLOADED = 109; 2382 2383 // Private handler for handling javascript and saving passwords 2384 private Handler mHandler = new Handler() { 2385 2386 @Override 2387 public void handleMessage(Message msg) { 2388 switch (msg.what) { 2389 case FOCUS_NODE_HREF: 2390 { 2391 String url = (String) msg.getData().get("url"); 2392 String title = (String) msg.getData().get("title"); 2393 if (url == null || url.length() == 0) { 2394 break; 2395 } 2396 HashMap focusNodeMap = (HashMap) msg.obj; 2397 WebView view = (WebView) focusNodeMap.get("webview"); 2398 // Only apply the action if the top window did not change. 2399 if (getTopWindow() != view) { 2400 break; 2401 } 2402 switch (msg.arg1) { 2403 case R.id.open_context_menu_id: 2404 case R.id.view_image_context_menu_id: 2405 loadUrlFromContext(getTopWindow(), url); 2406 break; 2407 case R.id.bookmark_context_menu_id: 2408 Intent intent = new Intent(BrowserActivity.this, 2409 AddBookmarkPage.class); 2410 intent.putExtra("url", url); 2411 intent.putExtra("title", title); 2412 startActivity(intent); 2413 break; 2414 case R.id.share_link_context_menu_id: 2415 sharePage(BrowserActivity.this, title, url, null, 2416 null); 2417 break; 2418 case R.id.copy_link_context_menu_id: 2419 copy(url); 2420 break; 2421 case R.id.save_link_context_menu_id: 2422 case R.id.download_context_menu_id: 2423 onDownloadStartNoStream(url, null, null, null, -1); 2424 break; 2425 } 2426 break; 2427 } 2428 2429 case LOAD_URL: 2430 loadUrlFromContext(getTopWindow(), (String) msg.obj); 2431 break; 2432 2433 case STOP_LOAD: 2434 stopLoading(); 2435 break; 2436 2437 case RELEASE_WAKELOCK: 2438 if (mWakeLock.isHeld()) { 2439 mWakeLock.release(); 2440 // if we reach here, Browser should be still in the 2441 // background loading after WAKELOCK_TIMEOUT (5-min). 2442 // To avoid burning the battery, stop loading. 2443 mTabControl.stopAllLoading(); 2444 } 2445 break; 2446 2447 case UPDATE_BOOKMARK_THUMBNAIL: 2448 WebView view = (WebView) msg.obj; 2449 if (view != null) { 2450 updateScreenshot(view); 2451 } 2452 break; 2453 2454 case TOUCH_ICON_DOWNLOADED: 2455 Bundle b = msg.getData(); 2456 showSaveToHomescreenDialog(b.getString("url"), 2457 b.getString("title"), 2458 (Bitmap) b.getParcelable("touchIcon"), 2459 (Bitmap) b.getParcelable("favicon")); 2460 break; 2461 } 2462 } 2463 }; 2464 2465 /** 2466 * Share a page, providing the title, url, favicon, and a screenshot. Uses 2467 * an {@link Intent} to launch the Activity chooser. 2468 * @param c Context used to launch a new Activity. 2469 * @param title Title of the page. Stored in the Intent with 2470 * {@link Intent#EXTRA_SUBJECT} 2471 * @param url URL of the page. Stored in the Intent with 2472 * {@link Intent#EXTRA_TEXT} 2473 * @param favicon Bitmap of the favicon for the page. Stored in the Intent 2474 * with {@link Browser#EXTRA_SHARE_FAVICON} 2475 * @param screenshot Bitmap of a screenshot of the page. Stored in the 2476 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT} 2477 */ 2478 public static final void sharePage(Context c, String title, String url, 2479 Bitmap favicon, Bitmap screenshot) { 2480 Intent send = new Intent(Intent.ACTION_SEND); 2481 send.setType("text/plain"); 2482 send.putExtra(Intent.EXTRA_TEXT, url); 2483 send.putExtra(Intent.EXTRA_SUBJECT, title); 2484 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon); 2485 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot); 2486 try { 2487 c.startActivity(Intent.createChooser(send, c.getString( 2488 R.string.choosertitle_sharevia))); 2489 } catch(android.content.ActivityNotFoundException ex) { 2490 // if no app handles it, do nothing 2491 } 2492 } 2493 2494 private void updateScreenshot(WebView view) { 2495 // If this is a bookmarked site, add a screenshot to the database. 2496 // FIXME: When should we update? Every time? 2497 // FIXME: Would like to make sure there is actually something to 2498 // draw, but the API for that (WebViewCore.pictureReady()) is not 2499 // currently accessible here. 2500 2501 final Bitmap bm = createScreenshot(view, getDesiredThumbnailWidth(this), 2502 getDesiredThumbnailHeight(this)); 2503 if (bm == null) { 2504 return; 2505 } 2506 2507 final ContentResolver cr = getContentResolver(); 2508 final String url = view.getUrl(); 2509 final String originalUrl = view.getOriginalUrl(); 2510 2511 new AsyncTask<Void, Void, Void>() { 2512 @Override 2513 protected Void doInBackground(Void... unused) { 2514 Cursor c = null; 2515 try { 2516 c = Bookmarks.queryBookmarksForUrl( 2517 cr, originalUrl, url); 2518 if (c != null) { 2519 if (c.moveToFirst()) { 2520 ContentValues values = new ContentValues(); 2521 final ByteArrayOutputStream os 2522 = new ByteArrayOutputStream(); 2523 bm.compress(Bitmap.CompressFormat.PNG, 100, os); 2524 values.put(BrowserContract.Bookmarks.THUMBNAIL, 2525 os.toByteArray()); 2526 do { 2527 cr.update(ContentUris.withAppendedId( 2528 BrowserContract.Bookmarks.CONTENT_URI, c.getLong(0)), 2529 values, null, null); 2530 } while (c.moveToNext()); 2531 } 2532 } 2533 } catch (IllegalStateException e) { 2534 // Ignore 2535 } finally { 2536 if (c != null) c.close(); 2537 } 2538 return null; 2539 } 2540 }.execute(); 2541 } 2542 2543 /** 2544 * Values for the size of the thumbnail created when taking a screenshot. 2545 * Lazily initialized. Instead of using these directly, use 2546 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight(). 2547 */ 2548 private static int THUMBNAIL_WIDTH = 0; 2549 private static int THUMBNAIL_HEIGHT = 0; 2550 2551 /** 2552 * Return the desired width for thumbnail screenshots, which are stored in 2553 * the database, and used on the bookmarks screen. 2554 * @param context Context for finding out the density of the screen. 2555 * @return int desired width for thumbnail screenshot. 2556 */ 2557 /* package */ static int getDesiredThumbnailWidth(Context context) { 2558 if (THUMBNAIL_WIDTH == 0) { 2559 float density = context.getResources().getDisplayMetrics().density; 2560 THUMBNAIL_WIDTH = (int) (90 * density); 2561 THUMBNAIL_HEIGHT = (int) (80 * density); 2562 } 2563 return THUMBNAIL_WIDTH; 2564 } 2565 2566 /** 2567 * Return the desired height for thumbnail screenshots, which are stored in 2568 * the database, and used on the bookmarks screen. 2569 * @param context Context for finding out the density of the screen. 2570 * @return int desired height for thumbnail screenshot. 2571 */ 2572 /* package */ static int getDesiredThumbnailHeight(Context context) { 2573 // To ensure that they are both initialized. 2574 getDesiredThumbnailWidth(context); 2575 return THUMBNAIL_HEIGHT; 2576 } 2577 2578 private Bitmap createScreenshot(WebView view, int width, int height) { 2579 Picture thumbnail = view.capturePicture(); 2580 if (thumbnail == null) { 2581 return null; 2582 } 2583 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); 2584 Canvas canvas = new Canvas(bm); 2585 // May need to tweak these values to determine what is the 2586 // best scale factor 2587 int thumbnailWidth = thumbnail.getWidth(); 2588 int thumbnailHeight = thumbnail.getHeight(); 2589 float scaleFactorX = 1.0f; 2590 float scaleFactorY = 1.0f; 2591 if (thumbnailWidth > 0) { 2592 scaleFactorX = (float) width / (float)thumbnailWidth; 2593 } else { 2594 return null; 2595 } 2596 2597 if (view.getWidth() > view.getHeight() && 2598 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) { 2599 // If the device is in landscape and the page is shorter 2600 // than the height of the view, stretch the thumbnail to fill the 2601 // space. 2602 scaleFactorY = (float) height / (float)thumbnailHeight; 2603 } else { 2604 // In the portrait case, this looks nice. 2605 scaleFactorY = scaleFactorX; 2606 } 2607 2608 canvas.scale(scaleFactorX, scaleFactorY); 2609 2610 thumbnail.draw(canvas); 2611 return bm; 2612 } 2613 2614 // ------------------------------------------------------------------------- 2615 // Helper function for WebViewClient. 2616 //------------------------------------------------------------------------- 2617 2618 // Use in overrideUrlLoading 2619 /* package */ final static String SCHEME_WTAI = "wtai://wp/"; 2620 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;"; 2621 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;"; 2622 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;"; 2623 2624 // Keep this initial progress in sync with initialProgressValue (* 100) 2625 // in ProgressTracker.cpp 2626 private final static int INITIAL_PROGRESS = 10; 2627 2628 void onPageStarted(WebView view, String url, Bitmap favicon) { 2629 // when BrowserActivity just starts, onPageStarted may be called before 2630 // onResume as it is triggered from onCreate. Call resumeWebViewTimers 2631 // to start the timer. As we won't switch tabs while an activity is in 2632 // pause state, we can ensure calling resume and pause in pair. 2633 if (mActivityInPause) resumeWebViewTimers(); 2634 2635 resetLockIcon(url); 2636 setUrlTitle(url, null); 2637 setFavicon(favicon); 2638 // Show some progress so that the user knows the page is beginning to 2639 // load 2640 onProgressChanged(view, INITIAL_PROGRESS); 2641 mDidStopLoad = false; 2642 if (!mIsNetworkUp) createAndShowNetworkDialog(); 2643 endActionMode(); 2644 if (mSettings.isTracing()) { 2645 String host; 2646 try { 2647 WebAddress uri = new WebAddress(url); 2648 host = uri.mHost; 2649 } catch (android.net.ParseException ex) { 2650 host = "browser"; 2651 } 2652 host = host.replace('.', '_'); 2653 host += ".trace"; 2654 mInTrace = true; 2655 Debug.startMethodTracing(host, 20 * 1024 * 1024); 2656 } 2657 2658 // Performance probe 2659 if (false) { 2660 mStart = SystemClock.uptimeMillis(); 2661 mProcessStart = Process.getElapsedCpuTime(); 2662 long[] sysCpu = new long[7]; 2663 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, 2664 sysCpu, null)) { 2665 mUserStart = sysCpu[0] + sysCpu[1]; 2666 mSystemStart = sysCpu[2]; 2667 mIdleStart = sysCpu[3]; 2668 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6]; 2669 } 2670 mUiStart = SystemClock.currentThreadTimeMillis(); 2671 } 2672 } 2673 2674 void onPageFinished(WebView view, String url) { 2675 // Reset the title and icon in case we stopped a provisional load. 2676 resetTitleAndIcon(view); 2677 // Update the lock icon image only once we are done loading 2678 updateLockIconToLatest(); 2679 // pause the WebView timer and release the wake lock if it is finished 2680 // while BrowserActivity is in pause state. 2681 if (mActivityInPause && pauseWebViewTimers()) { 2682 if (mWakeLock.isHeld()) { 2683 mHandler.removeMessages(RELEASE_WAKELOCK); 2684 mWakeLock.release(); 2685 } 2686 } 2687 2688 // Performance probe 2689 if (false) { 2690 long[] sysCpu = new long[7]; 2691 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null, 2692 sysCpu, null)) { 2693 String uiInfo = "UI thread used " 2694 + (SystemClock.currentThreadTimeMillis() - mUiStart) 2695 + " ms"; 2696 if (LOGD_ENABLED) { 2697 Log.d(LOGTAG, uiInfo); 2698 } 2699 //The string that gets written to the log 2700 String performanceString = "It took total " 2701 + (SystemClock.uptimeMillis() - mStart) 2702 + " ms clock time to load the page." 2703 + "\nbrowser process used " 2704 + (Process.getElapsedCpuTime() - mProcessStart) 2705 + " ms, user processes used " 2706 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10 2707 + " ms, kernel used " 2708 + (sysCpu[2] - mSystemStart) * 10 2709 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10 2710 + " ms and irq took " 2711 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart) 2712 * 10 + " ms, " + uiInfo; 2713 if (LOGD_ENABLED) { 2714 Log.d(LOGTAG, performanceString + "\nWebpage: " + url); 2715 } 2716 if (url != null) { 2717 // strip the url to maintain consistency 2718 String newUrl = new String(url); 2719 if (newUrl.startsWith("http://www.")) { 2720 newUrl = newUrl.substring(11); 2721 } else if (newUrl.startsWith("http://")) { 2722 newUrl = newUrl.substring(7); 2723 } else if (newUrl.startsWith("https://www.")) { 2724 newUrl = newUrl.substring(12); 2725 } else if (newUrl.startsWith("https://")) { 2726 newUrl = newUrl.substring(8); 2727 } 2728 if (LOGD_ENABLED) { 2729 Log.d(LOGTAG, newUrl + " loaded"); 2730 } 2731 } 2732 } 2733 } 2734 2735 if (mInTrace) { 2736 mInTrace = false; 2737 Debug.stopMethodTracing(); 2738 } 2739 } 2740 2741 private void closeEmptyChildTab() { 2742 Tab current = mTabControl.getCurrentTab(); 2743 if (current != null 2744 && current.getWebView().copyBackForwardList().getSize() == 0) { 2745 Tab parent = current.getParentTab(); 2746 if (parent != null) { 2747 switchToTab(mTabControl.getTabIndex(parent)); 2748 closeTab(current); 2749 } 2750 } 2751 } 2752 2753 boolean shouldOverrideUrlLoading(WebView view, String url) { 2754 if (url.startsWith(SCHEME_WTAI)) { 2755 // wtai://wp/mc;number 2756 // number=string(phone-number) 2757 if (url.startsWith(SCHEME_WTAI_MC)) { 2758 Intent intent = new Intent(Intent.ACTION_VIEW, 2759 Uri.parse(WebView.SCHEME_TEL + 2760 url.substring(SCHEME_WTAI_MC.length()))); 2761 startActivity(intent); 2762 // before leaving BrowserActivity, close the empty child tab. 2763 // If a new tab is created through JavaScript open to load this 2764 // url, we would like to close it as we will load this url in a 2765 // different Activity. 2766 closeEmptyChildTab(); 2767 return true; 2768 } 2769 // wtai://wp/sd;dtmf 2770 // dtmf=string(dialstring) 2771 if (url.startsWith(SCHEME_WTAI_SD)) { 2772 // TODO: only send when there is active voice connection 2773 return false; 2774 } 2775 // wtai://wp/ap;number;name 2776 // number=string(phone-number) 2777 // name=string 2778 if (url.startsWith(SCHEME_WTAI_AP)) { 2779 // TODO 2780 return false; 2781 } 2782 } 2783 2784 // The "about:" schemes are internal to the browser; don't want these to 2785 // be dispatched to other apps. 2786 if (url.startsWith("about:")) { 2787 return false; 2788 } 2789 2790 // If this is a Google search, attempt to add an RLZ string (if one isn't already present). 2791 if (rlzProviderPresent()) { 2792 Uri siteUri = Uri.parse(url); 2793 if (needsRlzString(siteUri)) { 2794 String rlz = null; 2795 Cursor cur = null; 2796 try { 2797 cur = getContentResolver().query(getRlzUri(), null, null, null, null); 2798 if (cur != null && cur.moveToFirst() && !cur.isNull(0)) { 2799 url = siteUri.buildUpon() 2800 .appendQueryParameter("rlz", cur.getString(0)) 2801 .build().toString(); 2802 } 2803 } finally { 2804 if (cur != null) { 2805 cur.close(); 2806 } 2807 } 2808 loadUrl(view, url); 2809 return true; 2810 } 2811 } 2812 2813 Intent intent; 2814 // perform generic parsing of the URI to turn it into an Intent. 2815 try { 2816 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME); 2817 } catch (URISyntaxException ex) { 2818 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage()); 2819 return false; 2820 } 2821 2822 // check whether the intent can be resolved. If not, we will see 2823 // whether we can download it from the Market. 2824 if (getPackageManager().resolveActivity(intent, 0) == null) { 2825 String packagename = intent.getPackage(); 2826 if (packagename != null) { 2827 intent = new Intent(Intent.ACTION_VIEW, Uri 2828 .parse("market://search?q=pname:" + packagename)); 2829 intent.addCategory(Intent.CATEGORY_BROWSABLE); 2830 startActivity(intent); 2831 // before leaving BrowserActivity, close the empty child tab. 2832 // If a new tab is created through JavaScript open to load this 2833 // url, we would like to close it as we will load this url in a 2834 // different Activity. 2835 closeEmptyChildTab(); 2836 return true; 2837 } else { 2838 return false; 2839 } 2840 } 2841 2842 // sanitize the Intent, ensuring web pages can not bypass browser 2843 // security (only access to BROWSABLE activities). 2844 intent.addCategory(Intent.CATEGORY_BROWSABLE); 2845 intent.setComponent(null); 2846 try { 2847 if (startActivityIfNeeded(intent, -1)) { 2848 // before leaving BrowserActivity, close the empty child tab. 2849 // If a new tab is created through JavaScript open to load this 2850 // url, we would like to close it as we will load this url in a 2851 // different Activity. 2852 closeEmptyChildTab(); 2853 return true; 2854 } 2855 } catch (ActivityNotFoundException ex) { 2856 // ignore the error. If no application can handle the URL, 2857 // eg about:blank, assume the browser can handle it. 2858 } 2859 2860 if (mMenuIsDown) { 2861 openTab(url, false); 2862 closeOptionsMenu(); 2863 return true; 2864 } 2865 return false; 2866 } 2867 2868 // Determine whether the RLZ provider is present on the system. 2869 private boolean rlzProviderPresent() { 2870 if (mIsProviderPresent == null) { 2871 PackageManager pm = getPackageManager(); 2872 mIsProviderPresent = pm.resolveContentProvider(BrowserSettings.RLZ_PROVIDER, 0) != null; 2873 } 2874 return mIsProviderPresent; 2875 } 2876 2877 // Retrieve the RLZ access point string and cache the URI used to retrieve RLZ values. 2878 private Uri getRlzUri() { 2879 if (mRlzUri == null) { 2880 String ap = getResources().getString(R.string.rlz_access_point); 2881 mRlzUri = Uri.withAppendedPath(BrowserSettings.RLZ_PROVIDER_URI, ap); 2882 } 2883 return mRlzUri; 2884 } 2885 2886 // Determine if this URI appears to be for a Google search and does not have an RLZ parameter. 2887 // Taken largely from Chrome source, src/chrome/browser/google_url_tracker.cc 2888 private static boolean needsRlzString(Uri uri) { 2889 if ((uri.getQueryParameter("q") != null) && (uri.getQueryParameter("rlz") == null)) { 2890 String host = uri.getHost(); 2891 if (host == null) { 2892 return false; 2893 } 2894 String[] hostComponents = host.split("\\."); 2895 2896 if (hostComponents.length < 2) { 2897 return false; 2898 } 2899 int googleComponent = hostComponents.length - 2; 2900 String component = hostComponents[googleComponent]; 2901 if (!"google".equals(component)) { 2902 if (hostComponents.length < 3 || 2903 (!"co".equals(component) && !"com".equals(component))) { 2904 return false; 2905 } 2906 googleComponent = hostComponents.length - 3; 2907 if (!"google".equals(hostComponents[googleComponent])) { 2908 return false; 2909 } 2910 } 2911 2912 // Google corp network handling. 2913 if (googleComponent > 0 && "corp".equals(hostComponents[googleComponent - 1])) { 2914 return false; 2915 } 2916 2917 return true; 2918 } 2919 return false; 2920 } 2921 2922 // ------------------------------------------------------------------------- 2923 // Helper function for WebChromeClient 2924 // ------------------------------------------------------------------------- 2925 2926 void onProgressChanged(WebView view, int newProgress) { 2927 2928 // On the phone, the fake title bar will always cover up the 2929 // regular title bar (or the regular one is offscreen), so only the 2930 // fake title bar needs to change its progress 2931 mFakeTitleBar.setProgress(newProgress); 2932 2933 if (newProgress == 100) { 2934 // onProgressChanged() may continue to be called after the main 2935 // frame has finished loading, as any remaining sub frames continue 2936 // to load. We'll only get called once though with newProgress as 2937 // 100 when everything is loaded. (onPageFinished is called once 2938 // when the main frame completes loading regardless of the state of 2939 // any sub frames so calls to onProgressChanges may continue after 2940 // onPageFinished has executed) 2941 if (mInLoad) { 2942 mInLoad = false; 2943 updateInLoadMenuItems(); 2944 // If the options menu is open, leave the title bar 2945 if (!mOptionsMenuOpen || !mIconView) { 2946 hideFakeTitleBar(); 2947 } 2948 } 2949 } else { 2950 if (!mInLoad) { 2951 // onPageFinished may have already been called but a subframe is 2952 // still loading and updating the progress. Reset mInLoad and 2953 // update the menu items. 2954 mInLoad = true; 2955 updateInLoadMenuItems(); 2956 } 2957 // When the page first begins to load, the Activity may still be 2958 // paused, in which case showFakeTitleBar will do nothing. Call 2959 // again as the page continues to load so that it will be shown. 2960 // (Calling it will the fake title bar is already showing will also 2961 // do nothing. 2962 if (!mOptionsMenuOpen || mIconView) { 2963 // This page has begun to load, so show the title bar 2964 showFakeTitleBar(); 2965 } 2966 } 2967 } 2968 2969 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) { 2970 // if a view already exists then immediately terminate the new one 2971 if (mCustomView != null) { 2972 callback.onCustomViewHidden(); 2973 return; 2974 } 2975 2976 // Add the custom view to its container. 2977 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER); 2978 mCustomView = view; 2979 mCustomViewCallback = callback; 2980 // Save the menu state and set it to empty while the custom 2981 // view is showing. 2982 mOldMenuState = mMenuState; 2983 mMenuState = EMPTY_MENU; 2984 // Hide the content view. 2985 mContentView.setVisibility(View.GONE); 2986 // Finally show the custom view container. 2987 setStatusBarVisibility(false); 2988 mCustomViewContainer.setVisibility(View.VISIBLE); 2989 mCustomViewContainer.bringToFront(); 2990 } 2991 2992 void onHideCustomView() { 2993 if (mCustomView == null) 2994 return; 2995 2996 // Hide the custom view. 2997 mCustomView.setVisibility(View.GONE); 2998 // Remove the custom view from its container. 2999 mCustomViewContainer.removeView(mCustomView); 3000 mCustomView = null; 3001 // Reset the old menu state. 3002 mMenuState = mOldMenuState; 3003 mOldMenuState = EMPTY_MENU; 3004 mCustomViewContainer.setVisibility(View.GONE); 3005 mCustomViewCallback.onCustomViewHidden(); 3006 // Show the content view. 3007 setStatusBarVisibility(true); 3008 mContentView.setVisibility(View.VISIBLE); 3009 } 3010 3011 Bitmap getDefaultVideoPoster() { 3012 if (mDefaultVideoPoster == null) { 3013 mDefaultVideoPoster = BitmapFactory.decodeResource( 3014 getResources(), R.drawable.default_video_poster); 3015 } 3016 return mDefaultVideoPoster; 3017 } 3018 3019 View getVideoLoadingProgressView() { 3020 if (mVideoProgressView == null) { 3021 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this); 3022 mVideoProgressView = inflater.inflate( 3023 R.layout.video_loading_progress, null); 3024 } 3025 return mVideoProgressView; 3026 } 3027 3028 /* 3029 * The Object used to inform the WebView of the file to upload. 3030 */ 3031 private ValueCallback<Uri> mUploadMessage; 3032 private String mCameraFilePath; 3033 3034 void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { 3035 3036 final String imageMimeType = "image/*"; 3037 final String videoMimeType = "video/*"; 3038 final String audioMimeType = "audio/*"; 3039 final String mediaSourceKey = "capture"; 3040 final String mediaSourceValueCamera = "camera"; 3041 final String mediaSourceValueFileSystem = "filesystem"; 3042 final String mediaSourceValueCamcorder = "camcorder"; 3043 final String mediaSourceValueMicrophone = "microphone"; 3044 3045 // media source can be 'filesystem' or 'camera' or 'camcorder' or 'microphone'. 3046 String mediaSource = ""; 3047 3048 // We add the camera intent if there was no accept type (or '*/*' or 'image/*'). 3049 boolean addCameraIntent = true; 3050 // We add the camcorder intent if there was no accept type (or '*/*' or 'video/*'). 3051 boolean addCamcorderIntent = true; 3052 3053 if (mUploadMessage != null) { 3054 // Already a file picker operation in progress. 3055 return; 3056 } 3057 3058 mUploadMessage = uploadMsg; 3059 3060 // Parse the accept type. 3061 String params[] = acceptType.split(";"); 3062 String mimeType = params[0]; 3063 3064 for (String p : params) { 3065 String[] keyValue = p.split("="); 3066 if (keyValue.length == 2) { 3067 // Process key=value parameters. 3068 if (mediaSourceKey.equals(keyValue[0])) { 3069 mediaSource = keyValue[1]; 3070 } 3071 } 3072 } 3073 3074 // This intent will display the standard OPENABLE file picker. 3075 Intent i = new Intent(Intent.ACTION_GET_CONTENT); 3076 i.addCategory(Intent.CATEGORY_OPENABLE); 3077 3078 // Create an intent to add to the standard file picker that will 3079 // capture an image from the camera. We'll combine this intent with 3080 // the standard OPENABLE picker unless the web developer specifically 3081 // requested the camera or gallery be opened by passing a parameter 3082 // in the accept type. 3083 Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 3084 File externalDataDir = Environment.getExternalStoragePublicDirectory( 3085 Environment.DIRECTORY_DCIM); 3086 File cameraDataDir = new File(externalDataDir.getAbsolutePath() + 3087 File.separator + "browser-photos"); 3088 cameraDataDir.mkdirs(); 3089 mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator + 3090 System.currentTimeMillis() + ".jpg"; 3091 cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath))); 3092 3093 Intent camcorderIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); 3094 3095 Intent soundRecIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION); 3096 3097 if (mimeType.equals(imageMimeType)) { 3098 i.setType(imageMimeType); 3099 addCamcorderIntent = false; 3100 if (mediaSource.equals(mediaSourceValueCamera)) { 3101 // Specified 'image/*' and requested the camera, so go ahead and launch the camera 3102 // directly. 3103 BrowserActivity.this.startActivityForResult(cameraIntent, FILE_SELECTED); 3104 return; 3105 } else if (mediaSource.equals(mediaSourceValueFileSystem)) { 3106 // Specified filesytem as the source, so don't want to consider the camera. 3107 addCameraIntent = false; 3108 } 3109 } else if (mimeType.equals(videoMimeType)) { 3110 i.setType(videoMimeType); 3111 addCameraIntent = false; 3112 // The camcorder saves it's own file and returns it to us in the intent, so 3113 // we don't need to generate one here. 3114 mCameraFilePath = null; 3115 3116 if (mediaSource.equals(mediaSourceValueCamcorder)) { 3117 // Specified 'video/*' and requested the camcorder, so go ahead and launch the 3118 // camcorder directly. 3119 BrowserActivity.this.startActivityForResult(camcorderIntent, FILE_SELECTED); 3120 return; 3121 } else if (mediaSource.equals(mediaSourceValueFileSystem)) { 3122 // Specified filesystem as the source, so don't want to consider the camcorder. 3123 addCamcorderIntent = false; 3124 } 3125 } else if (mimeType.equals(audioMimeType)) { 3126 i.setType(audioMimeType); 3127 addCameraIntent = false; 3128 addCamcorderIntent = false; 3129 if (mediaSource.equals(mediaSourceValueMicrophone)) { 3130 // Specified 'audio/*' and requested microphone, so go ahead and launch the sound 3131 // recorder. 3132 BrowserActivity.this.startActivityForResult(soundRecIntent, FILE_SELECTED); 3133 return; 3134 } 3135 // On a default system, there is no single option to open an audio "gallery". Both the 3136 // sound recorder and music browser respond to the OPENABLE/audio/* intent unlike the 3137 // image/* and video/* OPENABLE intents where the image / video gallery are the only 3138 // respondants (and so the user is not prompted by default). 3139 } else { 3140 i.setType("*/*"); 3141 } 3142 3143 // Combine the chooser and the extra choices (like camera or camcorder) 3144 Intent chooser = new Intent(Intent.ACTION_CHOOSER); 3145 chooser.putExtra(Intent.EXTRA_INTENT, i); 3146 3147 Vector<Intent> extraInitialIntents = new Vector<Intent>(0); 3148 3149 if (addCameraIntent) { 3150 extraInitialIntents.add(cameraIntent); 3151 } 3152 3153 if (addCamcorderIntent) { 3154 extraInitialIntents.add(camcorderIntent); 3155 } 3156 3157 if (extraInitialIntents.size() > 0) { 3158 Intent[] extraIntents = new Intent[extraInitialIntents.size()]; 3159 chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraInitialIntents.toArray(extraIntents)); 3160 } 3161 3162 chooser.putExtra(Intent.EXTRA_TITLE, getString(R.string.choose_upload)); 3163 BrowserActivity.this.startActivityForResult(chooser, FILE_SELECTED); 3164 } 3165 3166 // ------------------------------------------------------------------------- 3167 // Implement functions for DownloadListener 3168 // ------------------------------------------------------------------------- 3169 3170 /** 3171 * Notify the host application a download should be done, or that 3172 * the data should be streamed if a streaming viewer is available. 3173 * @param url The full url to the content that should be downloaded 3174 * @param contentDisposition Content-disposition http header, if 3175 * present. 3176 * @param mimetype The mimetype of the content reported by the server 3177 * @param contentLength The file size reported by the server 3178 */ 3179 public void onDownloadStart(String url, String userAgent, 3180 String contentDisposition, String mimetype, long contentLength) { 3181 // if we're dealing wih A/V content that's not explicitly marked 3182 // for download, check if it's streamable. 3183 if (contentDisposition == null 3184 || !contentDisposition.regionMatches( 3185 true, 0, "attachment", 0, 10)) { 3186 // query the package manager to see if there's a registered handler 3187 // that matches. 3188 Intent intent = new Intent(Intent.ACTION_VIEW); 3189 intent.setDataAndType(Uri.parse(url), mimetype); 3190 ResolveInfo info = getPackageManager().resolveActivity(intent, 3191 PackageManager.MATCH_DEFAULT_ONLY); 3192 if (info != null) { 3193 ComponentName myName = getComponentName(); 3194 // If we resolved to ourselves, we don't want to attempt to 3195 // load the url only to try and download it again. 3196 if (!myName.getPackageName().equals( 3197 info.activityInfo.packageName) 3198 || !myName.getClassName().equals( 3199 info.activityInfo.name)) { 3200 // someone (other than us) knows how to handle this mime 3201 // type with this scheme, don't download. 3202 try { 3203 startActivity(intent); 3204 return; 3205 } catch (ActivityNotFoundException ex) { 3206 if (LOGD_ENABLED) { 3207 Log.d(LOGTAG, "activity not found for " + mimetype 3208 + " over " + Uri.parse(url).getScheme(), 3209 ex); 3210 } 3211 // Best behavior is to fall back to a download in this 3212 // case 3213 } 3214 } 3215 } 3216 } 3217 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength); 3218 } 3219 3220 // This is to work around the fact that java.net.URI throws Exceptions 3221 // instead of just encoding URL's properly 3222 // Helper method for onDownloadStartNoStream 3223 private static String encodePath(String path) { 3224 char[] chars = path.toCharArray(); 3225 3226 boolean needed = false; 3227 for (char c : chars) { 3228 if (c == '[' || c == ']') { 3229 needed = true; 3230 break; 3231 } 3232 } 3233 if (needed == false) { 3234 return path; 3235 } 3236 3237 StringBuilder sb = new StringBuilder(""); 3238 for (char c : chars) { 3239 if (c == '[' || c == ']') { 3240 sb.append('%'); 3241 sb.append(Integer.toHexString(c)); 3242 } else { 3243 sb.append(c); 3244 } 3245 } 3246 3247 return sb.toString(); 3248 } 3249 3250 /** 3251 * Notify the host application a download should be done, even if there 3252 * is a streaming viewer available for thise type. 3253 * @param url The full url to the content that should be downloaded 3254 * @param contentDisposition Content-disposition http header, if 3255 * present. 3256 * @param mimetype The mimetype of the content reported by the server 3257 * @param contentLength The file size reported by the server 3258 */ 3259 /*package */ void onDownloadStartNoStream(String url, String userAgent, 3260 String contentDisposition, String mimetype, long contentLength) { 3261 3262 String filename = URLUtil.guessFileName(url, 3263 contentDisposition, mimetype); 3264 3265 // Check to see if we have an SDCard 3266 String status = Environment.getExternalStorageState(); 3267 if (!status.equals(Environment.MEDIA_MOUNTED)) { 3268 int title; 3269 String msg; 3270 3271 // Check to see if the SDCard is busy, same as the music app 3272 if (status.equals(Environment.MEDIA_SHARED)) { 3273 msg = getString(R.string.download_sdcard_busy_dlg_msg); 3274 title = R.string.download_sdcard_busy_dlg_title; 3275 } else { 3276 msg = getString(R.string.download_no_sdcard_dlg_msg, filename); 3277 title = R.string.download_no_sdcard_dlg_title; 3278 } 3279 3280 new AlertDialog.Builder(this) 3281 .setTitle(title) 3282 .setIcon(android.R.drawable.ic_dialog_alert) 3283 .setMessage(msg) 3284 .setPositiveButton(R.string.ok, null) 3285 .show(); 3286 return; 3287 } 3288 3289 // java.net.URI is a lot stricter than KURL so we have to encode some 3290 // extra characters. Fix for b 2538060 and b 1634719 3291 WebAddress webAddress; 3292 try { 3293 webAddress = new WebAddress(url); 3294 webAddress.mPath = encodePath(webAddress.mPath); 3295 } catch (Exception e) { 3296 // This only happens for very bad urls, we want to chatch the 3297 // exception here 3298 Log.e(LOGTAG, "Exception trying to parse url:" + url); 3299 return; 3300 } 3301 3302 // XXX: Have to use the old url since the cookies were stored using the 3303 // old percent-encoded url. 3304 String cookies = CookieManager.getInstance().getCookie(url); 3305 3306 ContentValues values = new ContentValues(); 3307 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString()); 3308 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies); 3309 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent); 3310 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE, 3311 getPackageName()); 3312 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS, 3313 OpenDownloadReceiver.class.getCanonicalName()); 3314 values.put(Downloads.Impl.COLUMN_VISIBILITY, 3315 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 3316 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype); 3317 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename); 3318 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost); 3319 if (contentLength > 0) { 3320 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength); 3321 } 3322 if (mimetype == null) { 3323 // We must have long pressed on a link or image to download it. We 3324 // are not sure of the mimetype in this case, so do a head request 3325 new FetchUrlMimeType(this).execute(values); 3326 } else { 3327 final Uri contentUri = 3328 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values); 3329 } 3330 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT) 3331 .show(); 3332 } 3333 3334 // ------------------------------------------------------------------------- 3335 3336 /** 3337 * Resets the lock icon. This method is called when we start a new load and 3338 * know the url to be loaded. 3339 */ 3340 private void resetLockIcon(String url) { 3341 // Save the lock-icon state (we revert to it if the load gets cancelled) 3342 mTabControl.getCurrentTab().resetLockIcon(url); 3343 updateLockIconImage(LOCK_ICON_UNSECURE); 3344 } 3345 3346 /** 3347 * Update the lock icon to correspond to our latest state. 3348 */ 3349 private void updateLockIconToLatest() { 3350 Tab t = mTabControl.getCurrentTab(); 3351 if (t != null) { 3352 updateLockIconImage(t.getLockIconType()); 3353 } 3354 } 3355 3356 /** 3357 * Updates the lock-icon image in the title-bar. 3358 */ 3359 private void updateLockIconImage(int lockIconType) { 3360 Drawable d = null; 3361 if (lockIconType == LOCK_ICON_SECURE) { 3362 d = mSecLockIcon; 3363 } else if (lockIconType == LOCK_ICON_MIXED) { 3364 d = mMixLockIcon; 3365 } 3366 mTitleBar.setLock(d); 3367 mFakeTitleBar.setLock(d); 3368 } 3369 3370 /** 3371 * Displays a page-info dialog. 3372 * @param tab The tab to show info about 3373 * @param fromShowSSLCertificateOnError The flag that indicates whether 3374 * this dialog was opened from the SSL-certificate-on-error dialog or 3375 * not. This is important, since we need to know whether to return to 3376 * the parent dialog or simply dismiss. 3377 */ 3378 private void showPageInfo(final Tab tab, 3379 final boolean fromShowSSLCertificateOnError) { 3380 final LayoutInflater factory = LayoutInflater 3381 .from(this); 3382 3383 final View pageInfoView = factory.inflate(R.layout.page_info, null); 3384 3385 final WebView view = tab.getWebView(); 3386 3387 String url = null; 3388 String title = null; 3389 3390 if (view == null) { 3391 url = tab.getUrl(); 3392 title = tab.getTitle(); 3393 } else if (view == mTabControl.getCurrentWebView()) { 3394 // Use the cached title and url if this is the current WebView 3395 url = mUrl; 3396 title = mTitle; 3397 } else { 3398 url = view.getUrl(); 3399 title = view.getTitle(); 3400 } 3401 3402 if (url == null) { 3403 url = ""; 3404 } 3405 if (title == null) { 3406 title = ""; 3407 } 3408 3409 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url); 3410 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title); 3411 3412 mPageInfoView = tab; 3413 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError; 3414 3415 AlertDialog.Builder alertDialogBuilder = 3416 new AlertDialog.Builder(this) 3417 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info) 3418 .setView(pageInfoView) 3419 .setPositiveButton( 3420 R.string.ok, 3421 new DialogInterface.OnClickListener() { 3422 public void onClick(DialogInterface dialog, 3423 int whichButton) { 3424 mPageInfoDialog = null; 3425 mPageInfoView = null; 3426 3427 // if we came here from the SSL error dialog 3428 if (fromShowSSLCertificateOnError) { 3429 // go back to the SSL error dialog 3430 showSSLCertificateOnError( 3431 mSSLCertificateOnErrorView, 3432 mSSLCertificateOnErrorHandler, 3433 mSSLCertificateOnErrorError); 3434 } 3435 } 3436 }) 3437 .setOnCancelListener( 3438 new DialogInterface.OnCancelListener() { 3439 public void onCancel(DialogInterface dialog) { 3440 mPageInfoDialog = null; 3441 mPageInfoView = null; 3442 3443 // if we came here from the SSL error dialog 3444 if (fromShowSSLCertificateOnError) { 3445 // go back to the SSL error dialog 3446 showSSLCertificateOnError( 3447 mSSLCertificateOnErrorView, 3448 mSSLCertificateOnErrorHandler, 3449 mSSLCertificateOnErrorError); 3450 } 3451 } 3452 }); 3453 3454 // if we have a main top-level page SSL certificate set or a certificate 3455 // error 3456 if (fromShowSSLCertificateOnError || 3457 (view != null && view.getCertificate() != null)) { 3458 // add a 'View Certificate' button 3459 alertDialogBuilder.setNeutralButton( 3460 R.string.view_certificate, 3461 new DialogInterface.OnClickListener() { 3462 public void onClick(DialogInterface dialog, 3463 int whichButton) { 3464 mPageInfoDialog = null; 3465 mPageInfoView = null; 3466 3467 // if we came here from the SSL error dialog 3468 if (fromShowSSLCertificateOnError) { 3469 // go back to the SSL error dialog 3470 showSSLCertificateOnError( 3471 mSSLCertificateOnErrorView, 3472 mSSLCertificateOnErrorHandler, 3473 mSSLCertificateOnErrorError); 3474 } else { 3475 // otherwise, display the top-most certificate from 3476 // the chain 3477 if (view.getCertificate() != null) { 3478 showSSLCertificate(tab); 3479 } 3480 } 3481 } 3482 }); 3483 } 3484 3485 mPageInfoDialog = alertDialogBuilder.show(); 3486 } 3487 3488 /** 3489 * Displays the main top-level page SSL certificate dialog 3490 * (accessible from the Page-Info dialog). 3491 * @param tab The tab to show certificate for. 3492 */ 3493 private void showSSLCertificate(final Tab tab) { 3494 final View certificateView = 3495 inflateCertificateView(tab.getWebView().getCertificate()); 3496 if (certificateView == null) { 3497 return; 3498 } 3499 3500 LayoutInflater factory = LayoutInflater.from(this); 3501 3502 final LinearLayout placeholder = 3503 (LinearLayout)certificateView.findViewById(R.id.placeholder); 3504 3505 LinearLayout ll = (LinearLayout) factory.inflate( 3506 R.layout.ssl_success, placeholder); 3507 ((TextView)ll.findViewById(R.id.success)) 3508 .setText(R.string.ssl_certificate_is_valid); 3509 3510 mSSLCertificateView = tab; 3511 mSSLCertificateDialog = 3512 new AlertDialog.Builder(this) 3513 .setTitle(R.string.ssl_certificate).setIcon( 3514 R.drawable.ic_dialog_browser_certificate_secure) 3515 .setView(certificateView) 3516 .setPositiveButton(R.string.ok, 3517 new DialogInterface.OnClickListener() { 3518 public void onClick(DialogInterface dialog, 3519 int whichButton) { 3520 mSSLCertificateDialog = null; 3521 mSSLCertificateView = null; 3522 3523 showPageInfo(tab, false); 3524 } 3525 }) 3526 .setOnCancelListener( 3527 new DialogInterface.OnCancelListener() { 3528 public void onCancel(DialogInterface dialog) { 3529 mSSLCertificateDialog = null; 3530 mSSLCertificateView = null; 3531 3532 showPageInfo(tab, false); 3533 } 3534 }) 3535 .show(); 3536 } 3537 3538 /** 3539 * Displays the SSL error certificate dialog. 3540 * @param view The target web-view. 3541 * @param handler The SSL error handler responsible for cancelling the 3542 * connection that resulted in an SSL error or proceeding per user request. 3543 * @param error The SSL error object. 3544 */ 3545 void showSSLCertificateOnError( 3546 final WebView view, final SslErrorHandler handler, final SslError error) { 3547 3548 final View certificateView = 3549 inflateCertificateView(error.getCertificate()); 3550 if (certificateView == null) { 3551 return; 3552 } 3553 3554 LayoutInflater factory = LayoutInflater.from(this); 3555 3556 final LinearLayout placeholder = 3557 (LinearLayout)certificateView.findViewById(R.id.placeholder); 3558 3559 if (error.hasError(SslError.SSL_UNTRUSTED)) { 3560 LinearLayout ll = (LinearLayout)factory 3561 .inflate(R.layout.ssl_warning, placeholder); 3562 ((TextView)ll.findViewById(R.id.warning)) 3563 .setText(R.string.ssl_untrusted); 3564 } 3565 3566 if (error.hasError(SslError.SSL_IDMISMATCH)) { 3567 LinearLayout ll = (LinearLayout)factory 3568 .inflate(R.layout.ssl_warning, placeholder); 3569 ((TextView)ll.findViewById(R.id.warning)) 3570 .setText(R.string.ssl_mismatch); 3571 } 3572 3573 if (error.hasError(SslError.SSL_EXPIRED)) { 3574 LinearLayout ll = (LinearLayout)factory 3575 .inflate(R.layout.ssl_warning, placeholder); 3576 ((TextView)ll.findViewById(R.id.warning)) 3577 .setText(R.string.ssl_expired); 3578 } 3579 3580 if (error.hasError(SslError.SSL_NOTYETVALID)) { 3581 LinearLayout ll = (LinearLayout)factory 3582 .inflate(R.layout.ssl_warning, placeholder); 3583 ((TextView)ll.findViewById(R.id.warning)) 3584 .setText(R.string.ssl_not_yet_valid); 3585 } 3586 3587 mSSLCertificateOnErrorHandler = handler; 3588 mSSLCertificateOnErrorView = view; 3589 mSSLCertificateOnErrorError = error; 3590 mSSLCertificateOnErrorDialog = 3591 new AlertDialog.Builder(this) 3592 .setTitle(R.string.ssl_certificate).setIcon( 3593 R.drawable.ic_dialog_browser_certificate_partially_secure) 3594 .setView(certificateView) 3595 .setPositiveButton(R.string.ok, 3596 new DialogInterface.OnClickListener() { 3597 public void onClick(DialogInterface dialog, 3598 int whichButton) { 3599 mSSLCertificateOnErrorDialog = null; 3600 mSSLCertificateOnErrorView = null; 3601 mSSLCertificateOnErrorHandler = null; 3602 mSSLCertificateOnErrorError = null; 3603 3604 view.getWebViewClient().onReceivedSslError( 3605 view, handler, error); 3606 } 3607 }) 3608 .setNeutralButton(R.string.page_info_view, 3609 new DialogInterface.OnClickListener() { 3610 public void onClick(DialogInterface dialog, 3611 int whichButton) { 3612 mSSLCertificateOnErrorDialog = null; 3613 3614 // do not clear the dialog state: we will 3615 // need to show the dialog again once the 3616 // user is done exploring the page-info details 3617 3618 showPageInfo(mTabControl.getTabFromView(view), 3619 true); 3620 } 3621 }) 3622 .setOnCancelListener( 3623 new DialogInterface.OnCancelListener() { 3624 public void onCancel(DialogInterface dialog) { 3625 mSSLCertificateOnErrorDialog = null; 3626 mSSLCertificateOnErrorView = null; 3627 mSSLCertificateOnErrorHandler = null; 3628 mSSLCertificateOnErrorError = null; 3629 3630 view.getWebViewClient().onReceivedSslError( 3631 view, handler, error); 3632 } 3633 }) 3634 .show(); 3635 } 3636 3637 /** 3638 * Inflates the SSL certificate view (helper method). 3639 * @param certificate The SSL certificate. 3640 * @return The resultant certificate view with issued-to, issued-by, 3641 * issued-on, expires-on, and possibly other fields set. 3642 * If the input certificate is null, returns null. 3643 */ 3644 private View inflateCertificateView(SslCertificate certificate) { 3645 if (certificate == null) { 3646 return null; 3647 } 3648 3649 LayoutInflater factory = LayoutInflater.from(this); 3650 3651 View certificateView = factory.inflate( 3652 R.layout.ssl_certificate, null); 3653 3654 // issued to: 3655 SslCertificate.DName issuedTo = certificate.getIssuedTo(); 3656 if (issuedTo != null) { 3657 ((TextView) certificateView.findViewById(R.id.to_common)) 3658 .setText(issuedTo.getCName()); 3659 ((TextView) certificateView.findViewById(R.id.to_org)) 3660 .setText(issuedTo.getOName()); 3661 ((TextView) certificateView.findViewById(R.id.to_org_unit)) 3662 .setText(issuedTo.getUName()); 3663 } 3664 3665 // issued by: 3666 SslCertificate.DName issuedBy = certificate.getIssuedBy(); 3667 if (issuedBy != null) { 3668 ((TextView) certificateView.findViewById(R.id.by_common)) 3669 .setText(issuedBy.getCName()); 3670 ((TextView) certificateView.findViewById(R.id.by_org)) 3671 .setText(issuedBy.getOName()); 3672 ((TextView) certificateView.findViewById(R.id.by_org_unit)) 3673 .setText(issuedBy.getUName()); 3674 } 3675 3676 // issued on: 3677 String issuedOn = formatCertificateDate( 3678 certificate.getValidNotBeforeDate()); 3679 ((TextView) certificateView.findViewById(R.id.issued_on)) 3680 .setText(issuedOn); 3681 3682 // expires on: 3683 String expiresOn = formatCertificateDate( 3684 certificate.getValidNotAfterDate()); 3685 ((TextView) certificateView.findViewById(R.id.expires_on)) 3686 .setText(expiresOn); 3687 3688 return certificateView; 3689 } 3690 3691 /** 3692 * Formats the certificate date to a properly localized date string. 3693 * @return Properly localized version of the certificate date string and 3694 * the "" if it fails to localize. 3695 */ 3696 private String formatCertificateDate(Date certificateDate) { 3697 if (certificateDate == null) { 3698 return ""; 3699 } 3700 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate); 3701 if (formattedDate == null) { 3702 return ""; 3703 } 3704 return formattedDate; 3705 } 3706 3707 /** 3708 * Displays an http-authentication dialog. 3709 */ 3710 void showHttpAuthentication(final HttpAuthHandler handler, 3711 final String host, final String realm, final String title, 3712 final String name, final String password, int focusId) { 3713 LayoutInflater factory = LayoutInflater.from(this); 3714 final View v = factory 3715 .inflate(R.layout.http_authentication, null); 3716 if (name != null) { 3717 ((EditText) v.findViewById(R.id.username_edit)).setText(name); 3718 } 3719 if (password != null) { 3720 ((EditText) v.findViewById(R.id.password_edit)).setText(password); 3721 } 3722 3723 String titleText = title; 3724 if (titleText == null) { 3725 titleText = getText(R.string.sign_in_to).toString().replace( 3726 "%s1", host).replace("%s2", realm); 3727 } 3728 3729 mHttpAuthHandler = handler; 3730 AlertDialog dialog = new AlertDialog.Builder(this) 3731 .setTitle(titleText) 3732 .setIcon(android.R.drawable.ic_dialog_alert) 3733 .setView(v) 3734 .setPositiveButton(R.string.action, 3735 new DialogInterface.OnClickListener() { 3736 public void onClick(DialogInterface dialog, 3737 int whichButton) { 3738 String nm = ((EditText) v 3739 .findViewById(R.id.username_edit)) 3740 .getText().toString(); 3741 String pw = ((EditText) v 3742 .findViewById(R.id.password_edit)) 3743 .getText().toString(); 3744 BrowserActivity.this.setHttpAuthUsernamePassword 3745 (host, realm, nm, pw); 3746 handler.proceed(nm, pw); 3747 mHttpAuthenticationDialog = null; 3748 mHttpAuthHandler = null; 3749 }}) 3750 .setNegativeButton(R.string.cancel, 3751 new DialogInterface.OnClickListener() { 3752 public void onClick(DialogInterface dialog, 3753 int whichButton) { 3754 handler.cancel(); 3755 BrowserActivity.this.resetTitleAndRevertLockIcon(); 3756 mHttpAuthenticationDialog = null; 3757 mHttpAuthHandler = null; 3758 }}) 3759 .setOnCancelListener(new DialogInterface.OnCancelListener() { 3760 public void onCancel(DialogInterface dialog) { 3761 handler.cancel(); 3762 BrowserActivity.this.resetTitleAndRevertLockIcon(); 3763 mHttpAuthenticationDialog = null; 3764 mHttpAuthHandler = null; 3765 }}) 3766 .create(); 3767 // Make the IME appear when the dialog is displayed if applicable. 3768 dialog.getWindow().setSoftInputMode( 3769 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); 3770 dialog.show(); 3771 if (focusId != 0) { 3772 dialog.findViewById(focusId).requestFocus(); 3773 } else { 3774 v.findViewById(R.id.username_edit).requestFocus(); 3775 } 3776 mHttpAuthenticationDialog = dialog; 3777 } 3778 3779 public int getProgress() { 3780 WebView w = mTabControl.getCurrentWebView(); 3781 if (w != null) { 3782 return w.getProgress(); 3783 } else { 3784 return 100; 3785 } 3786 } 3787 3788 /** 3789 * Set HTTP authentication password. 3790 * 3791 * @param host The host for the password 3792 * @param realm The realm for the password 3793 * @param username The username for the password. If it is null, it means 3794 * password can't be saved. 3795 * @param password The password 3796 */ 3797 public void setHttpAuthUsernamePassword(String host, String realm, 3798 String username, 3799 String password) { 3800 WebView w = getTopWindow(); 3801 if (w != null) { 3802 w.setHttpAuthUsernamePassword(host, realm, username, password); 3803 } 3804 } 3805 3806 /** 3807 * connectivity manager says net has come or gone... inform the user 3808 * @param up true if net has come up, false if net has gone down 3809 */ 3810 public void onNetworkToggle(boolean up) { 3811 if (up == mIsNetworkUp) { 3812 return; 3813 } else if (up) { 3814 mIsNetworkUp = true; 3815 if (mAlertDialog != null) { 3816 mAlertDialog.cancel(); 3817 mAlertDialog = null; 3818 } 3819 } else { 3820 mIsNetworkUp = false; 3821 if (mInLoad) { 3822 createAndShowNetworkDialog(); 3823 } 3824 } 3825 WebView w = mTabControl.getCurrentWebView(); 3826 if (w != null) { 3827 w.setNetworkAvailable(up); 3828 } 3829 } 3830 3831 boolean isNetworkUp() { 3832 return mIsNetworkUp; 3833 } 3834 3835 // This method shows the network dialog alerting the user that the net is 3836 // down. It will only show the dialog if mAlertDialog is null. 3837 private void createAndShowNetworkDialog() { 3838 if (mAlertDialog == null) { 3839 mAlertDialog = new AlertDialog.Builder(this) 3840 .setTitle(R.string.loadSuspendedTitle) 3841 .setMessage(R.string.loadSuspended) 3842 .setPositiveButton(R.string.ok, null) 3843 .show(); 3844 } 3845 } 3846 3847 @Override 3848 protected void onActivityResult(int requestCode, int resultCode, 3849 Intent intent) { 3850 if (getTopWindow() == null) return; 3851 3852 switch (requestCode) { 3853 case COMBO_PAGE: 3854 if (resultCode == RESULT_OK && intent != null) { 3855 String data = intent.getAction(); 3856 Bundle extras = intent.getExtras(); 3857 if (extras != null && extras.getBoolean("new_window", false)) { 3858 openTab(data, false); 3859 } else if ((extras != null) && 3860 extras.getBoolean(CombinedBookmarkHistoryActivity.NEWTAB_MODE)) { 3861 openTab(data, true); 3862 } else { 3863 final Tab currentTab = mTabControl.getCurrentTab(); 3864 dismissSubWindow(currentTab); 3865 if (data != null && data.length() != 0) { 3866 loadUrl(getTopWindow(), data); 3867 } 3868 } 3869 } 3870 // Deliberately fall through to PREFERENCES_PAGE, since the 3871 // same extra may be attached to the COMBO_PAGE 3872 case PREFERENCES_PAGE: 3873 if (resultCode == RESULT_OK && intent != null) { 3874 String action = intent.getStringExtra(Intent.EXTRA_TEXT); 3875 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) { 3876 mTabControl.removeParentChildRelationShips(); 3877 } 3878 } 3879 break; 3880 // Choose a file from the file picker. 3881 case FILE_SELECTED: 3882 if (null == mUploadMessage) break; 3883 Uri result = intent == null || resultCode != RESULT_OK ? null 3884 : intent.getData(); 3885 3886 // As we ask the camera to save the result of the user taking 3887 // a picture, the camera application does not return anything other 3888 // than RESULT_OK. So we need to check whether the file we expected 3889 // was written to disk in the in the case that we 3890 // did not get an intent returned but did get a RESULT_OK. If it was, 3891 // we assume that this result has came back from the camera. 3892 if (result == null && intent == null && resultCode == RESULT_OK) { 3893 File cameraFile = new File(mCameraFilePath); 3894 if (cameraFile.exists()) { 3895 result = Uri.fromFile(cameraFile); 3896 // Broadcast to the media scanner that we have a new photo 3897 // so it will be added into the gallery for the user. 3898 sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result)); 3899 } 3900 } 3901 mUploadMessage.onReceiveValue(result); 3902 mUploadMessage = null; 3903 mCameraFilePath = null; 3904 break; 3905 default: 3906 break; 3907 } 3908 getTopWindow().requestFocus(); 3909 } 3910 3911 /* 3912 * This method is called as a result of the user selecting the options 3913 * menu to see the download window. It shows the download window on top of 3914 * the current window. 3915 */ 3916 private void viewDownloads(Uri downloadRecord) { 3917 Intent intent = new Intent(this, 3918 BrowserDownloadPage.class); 3919 intent.setData(downloadRecord); 3920 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE); 3921 3922 } 3923 3924 /* package*/ void promptAddOrInstallBookmark() { 3925 final Tab current = mTabControl.getCurrentTab(); 3926 Resources resources = getResources(); 3927 CharSequence[] choices = { 3928 resources.getString(R.string.save_to_bookmarks), 3929 resources.getString(R.string.create_shortcut_bookmark) 3930 }; 3931 3932 AlertDialog.Builder builder = new AlertDialog.Builder(this); 3933 builder.setTitle(R.string.add_new_bookmark); 3934 builder.setItems(choices, new DialogInterface.OnClickListener() { 3935 public void onClick(DialogInterface dialog, int item) { 3936 if (item == 0) { 3937 bookmarkCurrentPage(); 3938 } else if (item == 1) { 3939 current.populatePickerData(); 3940 String touchIconUrl = mTabControl.getCurrentWebView().getTouchIconUrl(); 3941 if (touchIconUrl != null) { 3942 // Download the touch icon for this site then save it to the 3943 // homescreen. 3944 Bundle b = new Bundle(); 3945 b.putString("url", current.getUrl()); 3946 b.putString("title", current.getTitle()); 3947 b.putParcelable("favicon", current.getFavicon()); 3948 Message msg = mHandler.obtainMessage(TOUCH_ICON_DOWNLOADED); 3949 msg.setData(b); 3950 new DownloadTouchIcon(BrowserActivity.this, msg, 3951 mTabControl.getCurrentWebView().getSettings() 3952 .getUserAgentString()).execute(touchIconUrl); 3953 } else { 3954 // add to homescreen, can do it immediately as there is no touch 3955 // icon. 3956 showSaveToHomescreenDialog(current.getUrl(), current.getTitle(), 3957 null, current.getFavicon()); 3958 } 3959 } 3960 } 3961 }); 3962 builder.create().show(); 3963 } 3964 3965 /** 3966 * Open the Go page. 3967 * @param startWithHistory If true, open starting on the history tab. 3968 * Otherwise, start with the bookmarks tab. 3969 */ 3970 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory, boolean newTabMode) { 3971 WebView current = mTabControl.getCurrentWebView(); 3972 if (current == null) { 3973 return; 3974 } 3975 Intent intent = new Intent(this, 3976 CombinedBookmarkHistoryActivity.class); 3977 String title = current.getTitle(); 3978 String url = current.getUrl(); 3979 Bitmap thumbnail = createScreenshot(current, getDesiredThumbnailWidth(this), 3980 getDesiredThumbnailHeight(this)); 3981 3982 // Just in case the user opens bookmarks before a page finishes loading 3983 // so the current history item, and therefore the page, is null. 3984 if (null == url) { 3985 url = mLastEnteredUrl; 3986 // This can happen. 3987 if (null == url) { 3988 url = mSettings.getHomePage(); 3989 } 3990 } 3991 // In case the web page has not yet received its associated title. 3992 if (title == null) { 3993 title = url; 3994 } 3995 intent.putExtra("title", title); 3996 intent.putExtra("url", url); 3997 intent.putExtra("thumbnail", thumbnail); 3998 // Disable opening in a new window if we have maxed out the windows 3999 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab()); 4000 intent.putExtra("touch_icon_url", current.getTouchIconUrl()); 4001 if (startWithHistory) { 4002 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_FRAGMENT, 4003 CombinedBookmarkHistoryActivity.FRAGMENT_ID_HISTORY); 4004 } 4005 if (newTabMode) { 4006 intent.putExtra(CombinedBookmarkHistoryActivity.NEWTAB_MODE, true); 4007 } 4008 startActivityForResult(intent, COMBO_PAGE); 4009 } 4010 4011 private void showSaveToHomescreenDialog(String url, String title, Bitmap touchIcon, 4012 Bitmap favicon) { 4013 Intent intent = new Intent(this, SaveToHomescreenDialog.class); 4014 4015 // Just in case the user tries to save before a page finishes loading 4016 // so the current history item, and therefore the page, is null. 4017 if (null == url) { 4018 url = mLastEnteredUrl; 4019 // This can happen. 4020 if (null == url) { 4021 url = mSettings.getHomePage(); 4022 } 4023 } 4024 4025 // In case the web page has not yet received its associated title. 4026 if (title == null) { 4027 title = url; 4028 } 4029 4030 intent.putExtra("title", title); 4031 intent.putExtra("url", url); 4032 intent.putExtra("favicon", favicon); 4033 intent.putExtra("touchIcon", touchIcon); 4034 startActivity(intent); 4035 } 4036 4037 4038 // Called when loading from context menu or LOAD_URL message 4039 private void loadUrlFromContext(WebView view, String url) { 4040 // In case the user enters nothing. 4041 if (url != null && url.length() != 0 && view != null) { 4042 url = smartUrlFilter(url); 4043 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) { 4044 loadUrl(view, url); 4045 } 4046 } 4047 } 4048 4049 /** 4050 * Load the URL into the given WebView and update the title bar 4051 * to reflect the new load. Call this instead of WebView.loadUrl 4052 * directly. 4053 * @param view The WebView used to load url. 4054 * @param url The URL to load. 4055 */ 4056 private void loadUrl(WebView view, String url) { 4057 updateTitleBarForNewLoad(view, url); 4058 view.loadUrl(url); 4059 } 4060 4061 /** 4062 * Load UrlData into a Tab and update the title bar to reflect the new 4063 * load. Call this instead of UrlData.loadIn directly. 4064 * @param t The Tab used to load. 4065 * @param data The UrlData being loaded. 4066 */ 4067 private void loadUrlDataIn(Tab t, UrlData data) { 4068 updateTitleBarForNewLoad(t.getWebView(), data.mUrl); 4069 data.loadIn(t); 4070 } 4071 4072 /** 4073 * If the WebView is the top window, update the title bar to reflect 4074 * loading the new URL. i.e. set its text, clear the favicon (which 4075 * will be set once the page begins loading), and set the progress to 4076 * INITIAL_PROGRESS to show that the page has begun to load. Called 4077 * by loadUrl and loadUrlDataIn. 4078 * @param view The WebView that is starting a load. 4079 * @param url The URL that is being loaded. 4080 */ 4081 private void updateTitleBarForNewLoad(WebView view, String url) { 4082 if (view == getTopWindow()) { 4083 setUrlTitle(url, null); 4084 setFavicon(null); 4085 onProgressChanged(view, INITIAL_PROGRESS); 4086 } 4087 } 4088 4089 private String smartUrlFilter(Uri inUri) { 4090 if (inUri != null) { 4091 return smartUrlFilter(inUri.toString()); 4092 } 4093 return null; 4094 } 4095 4096 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile( 4097 "(?i)" + // switch on case insensitive matching 4098 "(" + // begin group for schema 4099 "(?:http|https|file):\\/\\/" + 4100 "|(?:inline|data|about|content|javascript):" + 4101 ")" + 4102 "(.*)" ); 4103 4104 /** 4105 * Attempts to determine whether user input is a URL or search 4106 * terms. Anything with a space is passed to search. 4107 * 4108 * Converts to lowercase any mistakenly uppercased schema (i.e., 4109 * "Http://" converts to "http://" 4110 * 4111 * @return Original or modified URL 4112 * 4113 */ 4114 String smartUrlFilter(String url) { 4115 4116 String inUrl = url.trim(); 4117 boolean hasSpace = inUrl.indexOf(' ') != -1; 4118 4119 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl); 4120 if (matcher.matches()) { 4121 // force scheme to lowercase 4122 String scheme = matcher.group(1); 4123 String lcScheme = scheme.toLowerCase(); 4124 if (!lcScheme.equals(scheme)) { 4125 inUrl = lcScheme + matcher.group(2); 4126 } 4127 if (hasSpace) { 4128 inUrl = inUrl.replace(" ", "%20"); 4129 } 4130 return inUrl; 4131 } 4132 if (hasSpace) { 4133 // FIXME: Is this the correct place to add to searches? 4134 // what if someone else calls this function? 4135 int shortcut = parseUrlShortcut(inUrl); 4136 if (shortcut != SHORTCUT_INVALID) { 4137 Browser.addSearchUrl(mResolver, inUrl); 4138 String query = inUrl.substring(2); 4139 switch (shortcut) { 4140 case SHORTCUT_GOOGLE_SEARCH: 4141 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER); 4142 case SHORTCUT_WIKIPEDIA_SEARCH: 4143 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER); 4144 case SHORTCUT_DICTIONARY_SEARCH: 4145 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER); 4146 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH: 4147 // FIXME: we need location in this case 4148 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER); 4149 } 4150 } 4151 } else { 4152 if (Patterns.WEB_URL.matcher(inUrl).matches()) { 4153 return URLUtil.guessUrl(inUrl); 4154 } 4155 } 4156 4157 Browser.addSearchUrl(mResolver, inUrl); 4158 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER); 4159 } 4160 4161 /* package */ void setShouldShowErrorConsole(boolean flag) { 4162 if (flag == mShouldShowErrorConsole) { 4163 // Nothing to do. 4164 return; 4165 } 4166 4167 mShouldShowErrorConsole = flag; 4168 4169 ErrorConsoleView errorConsole = mTabControl.getCurrentTab() 4170 .getErrorConsole(true); 4171 4172 if (flag) { 4173 // Setting the show state of the console will cause it's the layout to be inflated. 4174 if (errorConsole.numberOfErrors() > 0) { 4175 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED); 4176 } else { 4177 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE); 4178 } 4179 4180 // Now we can add it to the main view. 4181 mErrorConsoleContainer.addView(errorConsole, 4182 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 4183 ViewGroup.LayoutParams.WRAP_CONTENT)); 4184 } else { 4185 mErrorConsoleContainer.removeView(errorConsole); 4186 } 4187 4188 } 4189 4190 boolean shouldShowErrorConsole() { 4191 return mShouldShowErrorConsole; 4192 } 4193 4194 private void setStatusBarVisibility(boolean visible) { 4195 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN; 4196 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN); 4197 } 4198 4199 4200 private void sendNetworkType(String type, String subtype) { 4201 WebView w = mTabControl.getCurrentWebView(); 4202 if (w != null) { 4203 w.setNetworkType(type, subtype); 4204 } 4205 } 4206 4207 private void packageChanged(String packageName, boolean wasAdded) { 4208 WebView w = mTabControl.getCurrentWebView(); 4209 if (w == null) { 4210 return; 4211 } 4212 4213 if (wasAdded) { 4214 w.addPackageName(packageName); 4215 } else { 4216 w.removePackageName(packageName); 4217 } 4218 } 4219 4220 private void addPackageNames(Set<String> packageNames) { 4221 WebView w = mTabControl.getCurrentWebView(); 4222 if (w == null) { 4223 return; 4224 } 4225 4226 w.addPackageNames(packageNames); 4227 } 4228 4229 private void getInstalledPackages() { 4230 AsyncTask<Void, Void, Set<String> > task = 4231 new AsyncTask<Void, Void, Set<String> >() { 4232 @Override 4233 protected Set<String> doInBackground(Void... unused) { 4234 Set<String> installedPackages = new HashSet<String>(); 4235 PackageManager pm = BrowserActivity.this.getPackageManager(); 4236 if (pm != null) { 4237 List<PackageInfo> packages = pm.getInstalledPackages(0); 4238 for (PackageInfo p : packages) { 4239 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) { 4240 installedPackages.add(p.packageName); 4241 } 4242 } 4243 } 4244 4245 return installedPackages; 4246 } 4247 4248 // Executes on the UI thread 4249 @Override 4250 protected void onPostExecute(Set<String> installedPackages) { 4251 addPackageNames(installedPackages); 4252 } 4253 }; 4254 task.execute(); 4255 } 4256 4257 final static int LOCK_ICON_UNSECURE = 0; 4258 final static int LOCK_ICON_SECURE = 1; 4259 final static int LOCK_ICON_MIXED = 2; 4260 4261 private BrowserSettings mSettings; 4262 private TabControl mTabControl; 4263 private ContentResolver mResolver; 4264 private FrameLayout mContentView; 4265 private View mCustomView; 4266 private FrameLayout mCustomViewContainer; 4267 private WebChromeClient.CustomViewCallback mCustomViewCallback; 4268 4269 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of 4270 // view, we should rewrite this. 4271 private int mCurrentMenuState = 0; 4272 private int mMenuState = R.id.MAIN_MENU; 4273 private int mOldMenuState = EMPTY_MENU; 4274 private static final int EMPTY_MENU = -1; 4275 private Menu mMenu; 4276 4277 // Used to prevent chording to result in firing two shortcuts immediately 4278 // one after another. Fixes bug 1211714. 4279 boolean mCanChord; 4280 4281 private boolean mInLoad; 4282 private boolean mIsNetworkUp; 4283 private boolean mDidStopLoad; 4284 4285 /* package */ boolean mActivityInPause = true; 4286 4287 private boolean mMenuIsDown; 4288 4289 private static boolean mInTrace; 4290 4291 // Performance probe 4292 private static final int[] SYSTEM_CPU_FORMAT = new int[] { 4293 Process.PROC_SPACE_TERM | Process.PROC_COMBINE, 4294 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time 4295 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time 4296 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time 4297 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time 4298 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time 4299 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time 4300 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time 4301 }; 4302 4303 private long mStart; 4304 private long mProcessStart; 4305 private long mUserStart; 4306 private long mSystemStart; 4307 private long mIdleStart; 4308 private long mIrqStart; 4309 4310 private long mUiStart; 4311 4312 private Drawable mMixLockIcon; 4313 private Drawable mSecLockIcon; 4314 4315 /* hold a ref so we can auto-cancel if necessary */ 4316 private AlertDialog mAlertDialog; 4317 4318 // The up-to-date URL and title (these can be different from those stored 4319 // in WebView, since it takes some time for the information in WebView to 4320 // get updated) 4321 private String mUrl; 4322 private String mTitle; 4323 4324 // As PageInfo has different style for landscape / portrait, we have 4325 // to re-open it when configuration changed 4326 private AlertDialog mPageInfoDialog; 4327 private Tab mPageInfoView; 4328 // If the Page-Info dialog is launched from the SSL-certificate-on-error 4329 // dialog, we should not just dismiss it, but should get back to the 4330 // SSL-certificate-on-error dialog. This flag is used to store this state 4331 private boolean mPageInfoFromShowSSLCertificateOnError; 4332 4333 // as SSLCertificateOnError has different style for landscape / portrait, 4334 // we have to re-open it when configuration changed 4335 private AlertDialog mSSLCertificateOnErrorDialog; 4336 private WebView mSSLCertificateOnErrorView; 4337 private SslErrorHandler mSSLCertificateOnErrorHandler; 4338 private SslError mSSLCertificateOnErrorError; 4339 4340 // as SSLCertificate has different style for landscape / portrait, we 4341 // have to re-open it when configuration changed 4342 private AlertDialog mSSLCertificateDialog; 4343 private Tab mSSLCertificateView; 4344 4345 // as HttpAuthentication has different style for landscape / portrait, we 4346 // have to re-open it when configuration changed 4347 private AlertDialog mHttpAuthenticationDialog; 4348 private HttpAuthHandler mHttpAuthHandler; 4349 4350 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS = 4351 new FrameLayout.LayoutParams( 4352 ViewGroup.LayoutParams.MATCH_PARENT, 4353 ViewGroup.LayoutParams.MATCH_PARENT); 4354 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER = 4355 new FrameLayout.LayoutParams( 4356 ViewGroup.LayoutParams.MATCH_PARENT, 4357 ViewGroup.LayoutParams.MATCH_PARENT, 4358 Gravity.CENTER); 4359 // Google search 4360 final static String QuickSearch_G = "http://www.google.com/m?q=%s"; 4361 // Wikipedia search 4362 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go"; 4363 // Dictionary search 4364 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s"; 4365 // Google Mobile Local search 4366 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view"; 4367 4368 final static String QUERY_PLACE_HOLDER = "%s"; 4369 4370 // "source" parameter for Google search through search key 4371 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key"; 4372 // "source" parameter for Google search through goto menu 4373 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto"; 4374 // "source" parameter for Google search through simplily type 4375 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type"; 4376 // "source" parameter for Google search suggested by the browser 4377 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest"; 4378 // "source" parameter for Google search from unknown source 4379 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown"; 4380 4381 private final static String LOGTAG = "browser"; 4382 4383 private String mLastEnteredUrl; 4384 4385 private PowerManager.WakeLock mWakeLock; 4386 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes 4387 4388 private Toast mStopToast; 4389 4390 private TitleBarBase mTitleBar; 4391 private TabBar mTabBar; 4392 4393 private LinearLayout mErrorConsoleContainer = null; 4394 private boolean mShouldShowErrorConsole = false; 4395 4396 // As the ids are dynamically created, we can't guarantee that they will 4397 // be in sequence, so this static array maps ids to a window number. 4398 final static private int[] WINDOW_SHORTCUT_ID_ARRAY = 4399 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id, 4400 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id, 4401 R.id.window_seven_menu_id, R.id.window_eight_menu_id }; 4402 4403 // monitor platform changes 4404 private IntentFilter mNetworkStateChangedFilter; 4405 private BroadcastReceiver mNetworkStateIntentReceiver; 4406 4407 private BroadcastReceiver mPackageInstallationReceiver; 4408 4409 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins; 4410 4411 // activity requestCode 4412 final static int COMBO_PAGE = 1; 4413 final static int DOWNLOAD_PAGE = 2; 4414 final static int PREFERENCES_PAGE = 3; 4415 final static int FILE_SELECTED = 4; 4416 4417 // the default <video> poster 4418 private Bitmap mDefaultVideoPoster; 4419 // the video progress view 4420 private View mVideoProgressView; 4421 4422 // The Google packages we monitor for the navigator.isApplicationInstalled() 4423 // API. Add as needed. 4424 private static Set<String> sGoogleApps; 4425 static { 4426 sGoogleApps = new HashSet<String>(); 4427 sGoogleApps.add("com.google.android.youtube"); 4428 } 4429 4430 /** 4431 * A UrlData class to abstract how the content will be set to WebView. 4432 * This base class uses loadUrl to show the content. 4433 */ 4434 /* package */ static class UrlData { 4435 final String mUrl; 4436 final Map<String, String> mHeaders; 4437 final Intent mVoiceIntent; 4438 4439 UrlData(String url) { 4440 this.mUrl = url; 4441 this.mHeaders = null; 4442 this.mVoiceIntent = null; 4443 } 4444 4445 UrlData(String url, Map<String, String> headers, Intent intent) { 4446 this.mUrl = url; 4447 this.mHeaders = headers; 4448 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS 4449 .equals(intent.getAction())) { 4450 this.mVoiceIntent = intent; 4451 } else { 4452 this.mVoiceIntent = null; 4453 } 4454 } 4455 4456 boolean isEmpty() { 4457 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0); 4458 } 4459 4460 /** 4461 * Load this UrlData into the given Tab. Use loadUrlDataIn to update 4462 * the title bar as well. 4463 */ 4464 public void loadIn(Tab t) { 4465 if (mVoiceIntent != null) { 4466 t.activateVoiceSearchMode(mVoiceIntent); 4467 } else { 4468 t.getWebView().loadUrl(mUrl, mHeaders); 4469 } 4470 } 4471 }; 4472 4473 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null); 4474} 4475