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