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