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