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