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