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