2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.browser;
19 import android.app.Activity;
20 import android.app.AlertDialog;
21 import android.app.ProgressDialog;
22 import android.app.SearchManager;
23 import android.content.ActivityNotFoundException;
24 import android.content.BroadcastReceiver;
25 import android.content.ComponentName;
26 import android.content.ContentProvider;
27 import android.content.ContentProviderClient;
28 import android.content.ContentResolver;
29 import android.content.ContentUris;
30 import android.content.ContentValues;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.pm.PackageInfo;
36 import android.content.pm.PackageManager;
37 import android.content.pm.ResolveInfo;
38 import android.content.res.Configuration;
39 import android.content.res.Resources;
40 import android.database.Cursor;
41 import android.database.DatabaseUtils;
42 import android.graphics.Bitmap;
43 import android.graphics.BitmapFactory;
44 import android.graphics.Canvas;
45 import android.graphics.Picture;
46 import android.graphics.PixelFormat;
47 import android.graphics.Rect;
48 import android.graphics.drawable.Drawable;
49 import android.net.ConnectivityManager;
50 import android.net.NetworkInfo;
51 import android.net.Uri;
52 import android.net.WebAddress;
53 import android.net.http.SslCertificate;
54 import android.net.http.SslError;
55 import android.os.AsyncTask;
56 import android.os.Bundle;
57 import android.os.Debug;
58 import android.os.Environment;
59 import android.os.Handler;
60 import android.os.Message;
61 import android.os.PowerManager;
62 import android.os.Process;
63 import android.os.ServiceManager;
64 import android.os.SystemClock;
65 import android.provider.Browser;
66 import android.provider.ContactsContract;
67 import android.provider.ContactsContract.Intents.Insert;
68 import android.provider.Downloads;
69 import android.provider.MediaStore;
70 import android.speech.RecognizerResultsIntent;
71 import android.text.IClipboard;
72 import android.text.TextUtils;
73 import android.text.format.DateFormat;
74 import android.util.AttributeSet;
75 import android.util.Log;
76 import android.view.ContextMenu;
77 import android.view.Gravity;
78 import android.view.KeyEvent;
79 import android.view.LayoutInflater;
80 import android.view.Menu;
81 import android.view.MenuInflater;
82 import android.view.MenuItem;
83 import android.view.View;
84 import android.view.ViewGroup;
85 import android.view.Window;
86 import android.view.WindowManager;
87 import android.view.ContextMenu.ContextMenuInfo;
88 import android.view.MenuItem.OnMenuItemClickListener;
89 import android.webkit.CookieManager;
90 import android.webkit.CookieSyncManager;
91 import android.webkit.DownloadListener;
92 import android.webkit.HttpAuthHandler;
93 import android.webkit.PluginManager;
94 import android.webkit.SslErrorHandler;
95 import android.webkit.URLUtil;
96 import android.webkit.ValueCallback;
97 import android.webkit.WebChromeClient;
98 import android.webkit.WebHistoryItem;
99 import android.webkit.WebIconDatabase;
100 import android.webkit.WebView;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.LinearLayout;
104 import android.widget.TextView;
105 import android.widget.Toast;
106 import android.accounts.Account;
107 import android.accounts.AccountManager;
108 import android.accounts.AccountManagerFuture;
109 import android.accounts.AuthenticatorException;
110 import android.accounts.OperationCanceledException;
111 import android.accounts.AccountManagerCallback;
113 import com.android.common.Patterns;
114 import com.android.common.speech.LoggingEvents;
116 import com.google.android.gsf.GoogleLoginServiceConstants;
118 import java.io.ByteArrayOutputStream;
120 import java.io.IOException;
121 import java.io.InputStream;
122 import java.net.MalformedURLException;
124 import java.net.URISyntaxException;
126 import java.net.URLEncoder;
127 import java.text.ParseException;
128 import java.util.Date;
129 import java.util.HashMap;
130 import java.util.Iterator;
131 import java.util.Map;
132 import java.util.regex.Matcher;
133 import java.util.regex.Pattern;
135 public class BrowserActivity extends Activity
136 implements View.OnCreateContextMenuListener, DownloadListener,
137 AccountManagerCallback<Account[]> {
139 /* Define some aliases to make these debugging flags easier to refer to.
140 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
142 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
143 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
144 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
146 // These are single-character shortcuts for searching popular sources.
147 private static final int SHORTCUT_INVALID = 0;
148 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
149 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
150 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
151 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
153 private Account[] mAccountsGoogle;
154 private Account[] mAccountsPreferHosted;
156 private void startReadOfGoogleAccounts() {
157 mAccountsGoogle = null;
158 mAccountsPreferHosted = null;
160 AccountManager.get(this).getAccountsByTypeAndFeatures(
161 GoogleLoginServiceConstants.ACCOUNT_TYPE,
162 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
166 /** This implements AccountManagerCallback<Account[]> */
167 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
169 if (mAccountsGoogle == null) {
170 mAccountsGoogle = accountManagerFuture.getResult();
172 AccountManager.get(this).getAccountsByTypeAndFeatures(
173 GoogleLoginServiceConstants.ACCOUNT_TYPE,
174 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
177 mAccountsPreferHosted = accountManagerFuture.getResult();
180 } catch (OperationCanceledException e) {
182 } catch (IOException e) {
184 } catch (AuthenticatorException e) {
189 private void setupHomePage() {
190 // get the default home page
191 String homepage = mSettings.getHomePage();
193 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
196 // hostedUser == googleUser
197 // The device has only a google account
199 // hostedUser != googleUser
200 // The device has a hosted account and a google account
202 // hostedUser != null, googleUser == null
203 // The device has only a hosted account (so far)
204 String hostedUser = mAccountsPreferHosted.length == 0
206 : mAccountsPreferHosted[0].name;
207 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
209 // developers might have no accounts at all
210 if (hostedUser == null) return;
212 if (googleUser == null || !hostedUser.equals(googleUser)) {
213 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
214 homepage = homepage.replace("?", "/a/" + domain + "?");
218 mSettings.setHomePage(BrowserActivity.this, homepage);
219 resumeAfterCredentials();
222 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
224 public Void doInBackground(File... files) {
226 for (File f : files) {
228 Log.e(LOGTAG, f.getPath() + " was not deleted");
237 * This layout holds everything you see below the status bar, including the
238 * error console, the custom view container, and the webviews.
240 private FrameLayout mBrowserFrameLayout;
243 public void onCreate(Bundle icicle) {
245 Log.v(LOGTAG, this + " onStart");
247 super.onCreate(icicle);
248 // test the browser in OpenGL
249 // requestWindowFeature(Window.FEATURE_OPENGL);
251 // enable this to test the browser in 32bit
253 getWindow().setFormat(PixelFormat.RGBX_8888);
254 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
257 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
259 mResolver = getContentResolver();
261 // If this was a web search request, pass it on to the default web
262 // search provider and finish this activity.
263 if (handleWebSearchIntent(getIntent())) {
268 mSecLockIcon = Resources.getSystem().getDrawable(
269 android.R.drawable.ic_secure);
270 mMixLockIcon = Resources.getSystem().getDrawable(
271 android.R.drawable.ic_partial_secure);
273 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
274 .findViewById(com.android.internal.R.id.content);
275 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
276 .inflate(R.layout.custom_screen, null);
277 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
279 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
280 .findViewById(R.id.error_console);
281 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
282 .findViewById(R.id.fullscreen_custom_content);
283 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
284 mTitleBar = new TitleBar(this);
285 mFakeTitleBar = new TitleBar(this);
287 // Create the tab control and our initial tab
288 mTabControl = new TabControl(this);
290 // Open the icon database and retain all the bookmark urls for favicons
291 retainIconsOnStartup();
293 // Keep a settings instance handy.
294 mSettings = BrowserSettings.getInstance();
295 mSettings.setTabControl(mTabControl);
296 mSettings.loadFromDb(this);
298 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
299 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
301 /* enables registration for changes in network status from
303 mNetworkStateChangedFilter = new IntentFilter();
304 mNetworkStateChangedFilter.addAction(
305 ConnectivityManager.CONNECTIVITY_ACTION);
306 mNetworkStateIntentReceiver = new BroadcastReceiver() {
308 public void onReceive(Context context, Intent intent) {
309 if (intent.getAction().equals(
310 ConnectivityManager.CONNECTIVITY_ACTION)) {
311 boolean noConnectivity = intent.getBooleanExtra(
312 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
313 if (!noConnectivity) {
314 NetworkInfo info = intent.getParcelableExtra(
315 ConnectivityManager.EXTRA_NETWORK_INFO);
316 String typeName = info.getTypeName();
317 String subtypeName = info.getSubtypeName();
318 sendNetworkType(typeName.toLowerCase(),
319 (subtypeName != null ? subtypeName.toLowerCase() : ""));
321 onNetworkToggle(!noConnectivity);
326 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
327 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
328 filter.addDataScheme("package");
329 mPackageInstallationReceiver = new BroadcastReceiver() {
331 public void onReceive(Context context, Intent intent) {
332 final String action = intent.getAction();
333 final String packageName = intent.getData()
334 .getSchemeSpecificPart();
335 final boolean replacing = intent.getBooleanExtra(
336 Intent.EXTRA_REPLACING, false);
337 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
338 // if it is replacing, refreshPlugins() when adding
341 PackageManager pm = BrowserActivity.this.getPackageManager();
342 PackageInfo pkgInfo = null;
344 pkgInfo = pm.getPackageInfo(packageName,
345 PackageManager.GET_PERMISSIONS);
346 } catch (PackageManager.NameNotFoundException e) {
349 if (pkgInfo != null) {
350 String permissions[] = pkgInfo.requestedPermissions;
351 if (permissions == null) {
354 boolean permissionOk = false;
355 for (String permit : permissions) {
356 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
362 PluginManager.getInstance(BrowserActivity.this)
364 Intent.ACTION_PACKAGE_ADDED
370 registerReceiver(mPackageInstallationReceiver, filter);
372 if (!mTabControl.restoreState(icicle)) {
373 // clear up the thumbnail directory if we can't restore the state as
374 // none of the files in the directory are referenced any more.
375 new ClearThumbnails().execute(
376 mTabControl.getThumbnailDir().listFiles());
377 // there is no quit on Android. But if we can't restore the state,
378 // we can treat it as a new Browser, remove the old session cookies.
379 CookieManager.getInstance().removeSessionCookie();
380 final Intent intent = getIntent();
381 final Bundle extra = intent.getExtras();
382 // Create an initial tab.
383 // If the intent is ACTION_VIEW and data is not null, the Browser is
384 // invoked to view the content by another application. In this case,
385 // the tab will be close when exit.
386 UrlData urlData = getUrlDataFromIntent(intent);
388 String action = intent.getAction();
389 final Tab t = mTabControl.createNewTab(
390 (Intent.ACTION_VIEW.equals(action) &&
391 intent.getData() != null)
392 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
394 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
395 mTabControl.setCurrentTab(t);
396 attachTabToContentView(t);
397 WebView webView = t.getWebView();
399 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
400 if (scale > 0 && scale <= 1000) {
401 webView.setInitialScale(scale);
404 // If we are not restoring from an icicle, then there is a high
405 // likely hood this is the first run. So, check to see if the
406 // homepage needs to be configured and copy any plugins from our
407 // asset directory to the data partition.
408 if ((extra == null || !extra.getBoolean("testing"))
409 && !mSettings.isLoginInitialized()) {
410 startReadOfGoogleAccounts();
413 if (urlData.isEmpty()) {
414 if (mSettings.isLoginInitialized()) {
415 webView.loadUrl(mSettings.getHomePage());
417 waitForCredentials();
423 // TabControl.restoreState() will create a new tab even if
424 // restoring the state fails.
425 attachTabToContentView(mTabControl.getCurrentTab());
428 // Read JavaScript flags if it exists.
429 String jsFlags = mSettings.getJsFlags();
430 if (jsFlags.trim().length() != 0) {
431 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
436 * Feed the previously stored results strings to the BrowserProvider so that
437 * the SearchDialog will show them instead of the standard searches.
438 * @param result String to show on the editable line of the SearchDialog.
440 /* package */ void showVoiceSearchResults(String result) {
441 ContentProviderClient client = mResolver.acquireContentProviderClient(
442 Browser.BOOKMARKS_URI);
443 ContentProvider prov = client.getLocalContentProvider();
444 BrowserProvider bp = (BrowserProvider) prov;
445 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
448 startSearch(result, false,
449 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
454 protected void onNewIntent(Intent intent) {
455 Tab current = mTabControl.getCurrentTab();
456 // When a tab is closed on exit, the current tab index is set to -1.
457 // Reset before proceed as Browser requires the current tab to be set.
458 if (current == null) {
459 // Try to reset the tab in case the index was incorrect.
460 current = mTabControl.getTab(0);
461 if (current == null) {
462 // No tabs at all so just ignore this intent.
465 mTabControl.setCurrentTab(current);
466 attachTabToContentView(current);
467 resetTitleAndIcon(current.getWebView());
469 final String action = intent.getAction();
470 final int flags = intent.getFlags();
471 if (Intent.ACTION_MAIN.equals(action) ||
472 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
473 // just resume the browser
476 boolean activateVoiceSearch = RecognizerResultsIntent
477 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
478 if (Intent.ACTION_VIEW.equals(action)
479 || Intent.ACTION_SEARCH.equals(action)
480 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
481 || Intent.ACTION_WEB_SEARCH.equals(action)
482 || activateVoiceSearch) {
483 if (current.isInVoiceSearchMode()) {
484 String title = current.getVoiceDisplayTitle();
485 if (title != null && title.equals(intent.getStringExtra(
486 SearchManager.QUERY))) {
487 // The user submitted the same search as the last voice
488 // search, so do nothing.
491 if (Intent.ACTION_SEARCH.equals(action)
492 && current.voiceSearchSourceIsGoogle()) {
493 Intent logIntent = new Intent(
494 LoggingEvents.ACTION_LOG_EVENT);
495 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
496 LoggingEvents.VoiceSearch.QUERY_UPDATED);
498 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
499 intent.getDataString());
500 sendBroadcast(logIntent);
501 // Note, onPageStarted will revert the voice title bar
502 // When http://b/issue?id=2379215 is fixed, we should update
503 // the title bar here.
506 // If this was a search request (e.g. search query directly typed into the address bar),
507 // pass it on to the default web search provider.
508 if (handleWebSearchIntent(intent)) {
512 UrlData urlData = getUrlDataFromIntent(intent);
513 if (urlData.isEmpty()) {
514 urlData = new UrlData(mSettings.getHomePage());
517 final String appId = intent
518 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
519 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
520 && !getPackageName().equals(appId)
521 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
522 Tab appTab = mTabControl.getTabFromId(appId);
523 if (appTab != null) {
524 Log.i(LOGTAG, "Reusing tab for " + appId);
525 // Dismiss the subwindow if applicable.
526 dismissSubWindow(appTab);
527 // Since we might kill the WebView, remove it from the
528 // content view first.
529 removeTabFromContentView(appTab);
530 // Recreate the main WebView after destroying the old one.
531 // If the WebView has the same original url and is on that
532 // page, it can be reused.
534 mTabControl.recreateWebView(appTab, urlData.mUrl);
536 if (current != appTab) {
537 switchToTab(mTabControl.getTabIndex(appTab));
539 urlData.loadIn(appTab);
542 // If the tab was the current tab, we have to attach
543 // it to the view system again.
544 attachTabToContentView(appTab);
546 urlData.loadIn(appTab);
551 // No matching application tab, try to find a regular tab
552 // with a matching url.
553 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
554 if (appTab != null) {
555 if (current != appTab) {
556 switchToTab(mTabControl.getTabIndex(appTab));
558 // Otherwise, we are already viewing the correct tab.
560 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
561 // will be opened in a new tab unless we have reached
562 // MAX_TABS. Then the url will be opened in the current
563 // tab. If a new tab is created, it will have "true" for
565 openTabAndShow(urlData, true, appId);
569 if (!urlData.isEmpty()
570 && urlData.mUrl.startsWith("about:debug")) {
571 if ("about:debug.dom".equals(urlData.mUrl)) {
572 current.getWebView().dumpDomTree(false);
573 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
574 current.getWebView().dumpDomTree(true);
575 } else if ("about:debug.render".equals(urlData.mUrl)) {
576 current.getWebView().dumpRenderTree(false);
577 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
578 current.getWebView().dumpRenderTree(true);
579 } else if ("about:debug.display".equals(urlData.mUrl)) {
580 current.getWebView().dumpDisplayTree();
581 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
582 int index = urlData.mUrl.codePointAt(16) - '0';
583 if (index <= 0 || index > 9) {
584 current.getWebView().setDragTracker(null);
586 current.getWebView().setDragTracker(new MeshTracker(index));
589 mSettings.toggleDebugSettings();
593 // Get rid of the subwindow if it exists
594 dismissSubWindow(current);
595 urlData.loadIn(current);
600 private int parseUrlShortcut(String url) {
601 if (url == null) return SHORTCUT_INVALID;
603 // FIXME: quick search, need to be customized by setting
604 if (url.length() > 2 && url.charAt(1) == ' ') {
605 switch (url.charAt(0)) {
606 case 'g': return SHORTCUT_GOOGLE_SEARCH;
607 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
608 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
609 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
612 return SHORTCUT_INVALID;
616 * Launches the default web search activity with the query parameters if the given intent's data
617 * are identified as plain search terms and not URLs/shortcuts.
618 * @return true if the intent was handled and web search activity was launched, false if not.
620 private boolean handleWebSearchIntent(Intent intent) {
621 if (intent == null) return false;
624 final String action = intent.getAction();
625 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
629 if (Intent.ACTION_VIEW.equals(action)) {
630 Uri data = intent.getData();
631 if (data != null) url = data.toString();
632 } else if (Intent.ACTION_SEARCH.equals(action)
633 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
634 || Intent.ACTION_WEB_SEARCH.equals(action)) {
635 url = intent.getStringExtra(SearchManager.QUERY);
637 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
638 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
642 * Launches the default web search activity with the query parameters if the given url string
643 * was identified as plain search terms and not URL/shortcut.
644 * @return true if the request was handled and web search activity was launched, false if not.
646 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
647 if (inUrl == null) return false;
649 // In general, we shouldn't modify URL from Intent.
650 // But currently, we get the user-typed URL from search box as well.
651 String url = fixUrl(inUrl).trim();
653 // URLs and site specific search shortcuts are handled by the regular flow of control, so
655 if (Patterns.WEB_URL.matcher(url).matches()
656 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
657 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
661 Browser.updateVisitedHistory(mResolver, url, false);
662 Browser.addSearchUrl(mResolver, url);
664 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
665 intent.addCategory(Intent.CATEGORY_DEFAULT);
666 intent.putExtra(SearchManager.QUERY, url);
667 if (appData != null) {
668 intent.putExtra(SearchManager.APP_DATA, appData);
670 if (extraData != null) {
671 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
673 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
674 startActivity(intent);
679 private UrlData getUrlDataFromIntent(Intent intent) {
681 Map<String, String> headers = null;
682 if (intent != null) {
683 final String action = intent.getAction();
684 if (Intent.ACTION_VIEW.equals(action)) {
685 url = smartUrlFilter(intent.getData());
686 if (url != null && url.startsWith("content:")) {
687 /* Append mimetype so webview knows how to display */
688 String mimeType = intent.resolveType(getContentResolver());
689 if (mimeType != null) {
690 url += "?" + mimeType;
693 if (url != null && url.startsWith("http")) {
694 final Bundle pairs = intent
695 .getBundleExtra(Browser.EXTRA_HEADERS);
696 if (pairs != null && !pairs.isEmpty()) {
697 Iterator<String> iter = pairs.keySet().iterator();
698 headers = new HashMap<String, String>();
699 while (iter.hasNext()) {
700 String key = iter.next();
701 headers.put(key, pairs.getString(key));
705 } else if (Intent.ACTION_SEARCH.equals(action)
706 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
707 || Intent.ACTION_WEB_SEARCH.equals(action)) {
708 url = intent.getStringExtra(SearchManager.QUERY);
710 mLastEnteredUrl = url;
711 Browser.updateVisitedHistory(mResolver, url, false);
712 // In general, we shouldn't modify URL from Intent.
713 // But currently, we get the user-typed URL from search box as well.
715 url = smartUrlFilter(url);
716 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
717 if (url.contains(searchSource)) {
718 String source = null;
719 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
720 if (appData != null) {
721 source = appData.getString(SearchManager.SOURCE);
723 if (TextUtils.isEmpty(source)) {
724 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
726 url = url.replace(searchSource, "&source=android-"+source+"&");
731 return new UrlData(url, headers, intent);
733 /* package */ void showVoiceTitleBar(String title) {
734 mTitleBar.setInVoiceMode(true);
735 mFakeTitleBar.setInVoiceMode(true);
737 mTitleBar.setDisplayTitle(title);
738 mFakeTitleBar.setDisplayTitle(title);
740 /* package */ void revertVoiceTitleBar() {
741 mTitleBar.setInVoiceMode(false);
742 mFakeTitleBar.setInVoiceMode(false);
744 mTitleBar.setDisplayTitle(mTitle);
745 mFakeTitleBar.setDisplayTitle(mTitle);
747 /* package */ static String fixUrl(String inUrl) {
748 // FIXME: Converting the url to lower case
749 // duplicates functionality in smartUrlFilter().
750 // However, changing all current callers of fixUrl to
751 // call smartUrlFilter in addition may have unwanted
752 // consequences, and is deferred for now.
753 int colon = inUrl.indexOf(':');
754 boolean allLower = true;
755 for (int index = 0; index < colon; index++) {
756 char ch = inUrl.charAt(index);
757 if (!Character.isLetter(ch)) {
760 allLower &= Character.isLowerCase(ch);
761 if (index == colon - 1 && !allLower) {
762 inUrl = inUrl.substring(0, colon).toLowerCase()
763 + inUrl.substring(colon);
766 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
768 if (inUrl.startsWith("http:") ||
769 inUrl.startsWith("https:")) {
770 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
771 inUrl = inUrl.replaceFirst("/", "//");
772 } else inUrl = inUrl.replaceFirst(":", "://");
778 protected void onResume() {
781 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
784 if (!mActivityInPause) {
785 Log.e(LOGTAG, "BrowserActivity is already resumed.");
789 mTabControl.resumeCurrentTab();
790 mActivityInPause = false;
791 resumeWebViewTimers();
793 if (mWakeLock.isHeld()) {
794 mHandler.removeMessages(RELEASE_WAKELOCK);
798 if (mCredsDlg != null) {
799 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
800 // In case credential request never comes back
801 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
805 registerReceiver(mNetworkStateIntentReceiver,
806 mNetworkStateChangedFilter);
807 WebView.enablePlatformNotifications();
811 * Since the actual title bar is embedded in the WebView, and removing it
812 * would change its appearance, use a different TitleBar to show overlayed
813 * at the top of the screen, when the menu is open or the page is loading.
815 private TitleBar mFakeTitleBar;
818 * Holder for the fake title bar. It will have a foreground shadow, as well
819 * as a white background, so the fake title bar looks like the real one.
821 private ViewGroup mFakeTitleBarHolder;
824 * Layout parameters for the fake title bar within mFakeTitleBarHolder
826 private FrameLayout.LayoutParams mFakeTitleBarParams
827 = new FrameLayout.LayoutParams(
828 ViewGroup.LayoutParams.MATCH_PARENT,
829 ViewGroup.LayoutParams.WRAP_CONTENT);
831 * Keeps track of whether the options menu is open. This is important in
832 * determining whether to show or hide the title bar overlay.
834 private boolean mOptionsMenuOpen;
837 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
838 * of whether the configuration has changed. The first onMenuOpened call
839 * after a configuration change is simply a reopening of the same menu
840 * (i.e. mIconView did not change).
842 private boolean mConfigChanged;
845 * Whether or not the options menu is in its smaller, icon menu form. When
846 * true, we want the title bar overlay to be up. When false, we do not.
847 * Only meaningful if mOptionsMenuOpen is true.
849 private boolean mIconView;
852 public boolean onMenuOpened(int featureId, Menu menu) {
853 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
854 if (mOptionsMenuOpen) {
855 if (mConfigChanged) {
856 // We do not need to make any changes to the state of the
857 // title bar, since the only thing that happened was a
858 // change in orientation
859 mConfigChanged = false;
862 // Switching the menu to expanded view, so hide the
867 // Switching the menu back to icon view, so show the
868 // title bar once again.
874 // The options menu is closed, so open it, and show the title
876 mOptionsMenuOpen = true;
877 mConfigChanged = false;
885 * Special class used exclusively for the shadow drawn underneath the fake
886 * title bar. The shadow does not need to be drawn if the WebView
887 * underneath is scrolled to the top, because it will draw directly on top
888 * of the embedded shadow.
890 private static class Shadow extends View {
891 private WebView mWebView;
893 public Shadow(Context context, AttributeSet attrs) {
894 super(context, attrs);
897 public void setWebView(WebView view) {
902 public void draw(Canvas canvas) {
903 // In general onDraw is the method to override, but we care about
904 // whether or not the background gets drawn, which happens in draw()
905 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
908 // Need to invalidate so that if the scroll position changes, we
909 // still draw as appropriate.
914 private void showFakeTitleBar() {
915 final View decor = getWindow().peekDecorView();
916 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
917 && !mActivityInPause && decor != null
918 && decor.getWindowToken() != null) {
919 Rect visRect = new Rect();
920 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
922 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
927 WindowManager manager
928 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
930 // Add the title bar to the window manager so it can receive touches
931 // while the menu is up
932 WindowManager.LayoutParams params
933 = new WindowManager.LayoutParams(
934 ViewGroup.LayoutParams.MATCH_PARENT,
935 ViewGroup.LayoutParams.WRAP_CONTENT,
936 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
937 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
938 PixelFormat.TRANSLUCENT);
939 params.gravity = Gravity.TOP;
940 WebView mainView = mTabControl.getCurrentWebView();
941 boolean atTop = mainView != null && mainView.getScrollY() == 0;
942 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
943 // XXX : Without providing an offset, the fake title bar will be
944 // placed underneath the status bar. Use the global visible rect
945 // of mBrowserFrameLayout to determine the bottom of the status bar
946 params.y = visRect.top;
947 // Add a holder for the title bar. It also holds a shadow to show
948 // below the title bar.
949 if (mFakeTitleBarHolder == null) {
950 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
951 .inflate(R.layout.title_bar_bg, null);
953 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
955 shadow.setWebView(mainView);
956 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
957 manager.addView(mFakeTitleBarHolder, params);
962 public void onOptionsMenuClosed(Menu menu) {
963 mOptionsMenuOpen = false;
966 } else if (!mIconView) {
967 // The page is currently loading, and we are in expanded mode, so
968 // we were not showing the menu. Show it once again. It will be
969 // removed when the page finishes.
974 private void hideFakeTitleBar() {
975 if (mFakeTitleBar.getParent() == null) return;
976 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
977 mFakeTitleBarHolder.getLayoutParams();
978 WebView mainView = mTabControl.getCurrentWebView();
979 // Although we decided whether or not to animate based on the current
980 // scroll position, the scroll position may have changed since the
981 // fake title bar was displayed. Make sure it has the appropriate
982 // animation/lack thereof before removing.
983 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
984 ? 0 : R.style.TitleBar;
985 WindowManager manager
986 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
987 manager.updateViewLayout(mFakeTitleBarHolder, params);
988 mFakeTitleBarHolder.removeView(mFakeTitleBar);
989 manager.removeView(mFakeTitleBarHolder);
993 * Special method for the fake title bar to call when displaying its context
994 * menu, since it is in its own Window, and its parent does not show a
997 /* package */ void showTitleBarContextMenu() {
998 if (null == mTitleBar.getParent()) {
1001 openContextMenu(mTitleBar);
1005 public void onContextMenuClosed(Menu menu) {
1006 super.onContextMenuClosed(menu);
1013 * onSaveInstanceState(Bundle map)
1014 * onSaveInstanceState is called right before onStop(). The map contains
1018 protected void onSaveInstanceState(Bundle outState) {
1020 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1022 // the default implementation requires each view to have an id. As the
1023 // browser handles the state itself and it doesn't use id for the views,
1024 // don't call the default implementation. Otherwise it will trigger the
1025 // warning like this, "couldn't save which view has focus because the
1026 // focused view XXX has no id".
1028 // Save all the tabs
1029 mTabControl.saveState(outState);
1033 protected void onPause() {
1036 if (mActivityInPause) {
1037 Log.e(LOGTAG, "BrowserActivity is already paused.");
1041 mTabControl.pauseCurrentTab();
1042 mActivityInPause = true;
1043 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1044 mWakeLock.acquire();
1045 mHandler.sendMessageDelayed(mHandler
1046 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1049 // Clear the credentials toast if it is up
1050 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1051 mCredsDlg.dismiss();
1055 // FIXME: This removes the active tabs page and resets the menu to
1056 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1057 // but then we would need to save it in onSaveInstanceState and restore
1058 // it in onCreate/onRestoreInstanceState
1059 if (mActiveTabsPage != null) {
1060 removeActiveTabPage(true);
1065 // unregister network state listener
1066 unregisterReceiver(mNetworkStateIntentReceiver);
1067 WebView.disablePlatformNotifications();
1071 protected void onDestroy() {
1073 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1077 if (mUploadMessage != null) {
1078 mUploadMessage.onReceiveValue(null);
1079 mUploadMessage = null;
1082 if (mTabControl == null) return;
1084 // Remove the fake title bar if it is there
1087 // Remove the current tab and sub window
1088 Tab t = mTabControl.getCurrentTab();
1090 dismissSubWindow(t);
1091 removeTabFromContentView(t);
1093 // Destroy all the tabs
1094 mTabControl.destroy();
1095 WebIconDatabase.getInstance().close();
1097 unregisterReceiver(mPackageInstallationReceiver);
1101 public void onConfigurationChanged(Configuration newConfig) {
1102 mConfigChanged = true;
1103 super.onConfigurationChanged(newConfig);
1105 if (mPageInfoDialog != null) {
1106 mPageInfoDialog.dismiss();
1109 mPageInfoFromShowSSLCertificateOnError);
1111 if (mSSLCertificateDialog != null) {
1112 mSSLCertificateDialog.dismiss();
1114 mSSLCertificateView);
1116 if (mSSLCertificateOnErrorDialog != null) {
1117 mSSLCertificateOnErrorDialog.dismiss();
1118 showSSLCertificateOnError(
1119 mSSLCertificateOnErrorView,
1120 mSSLCertificateOnErrorHandler,
1121 mSSLCertificateOnErrorError);
1123 if (mHttpAuthenticationDialog != null) {
1124 String title = ((TextView) mHttpAuthenticationDialog
1125 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1127 String name = ((TextView) mHttpAuthenticationDialog
1128 .findViewById(R.id.username_edit)).getText().toString();
1129 String password = ((TextView) mHttpAuthenticationDialog
1130 .findViewById(R.id.password_edit)).getText().toString();
1131 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1133 mHttpAuthenticationDialog.dismiss();
1134 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1135 name, password, focusId);
1140 public void onLowMemory() {
1141 super.onLowMemory();
1142 mTabControl.freeMemory();
1145 private boolean resumeWebViewTimers() {
1146 Tab tab = mTabControl.getCurrentTab();
1147 boolean inLoad = tab.inLoad();
1148 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1149 CookieSyncManager.getInstance().startSync();
1150 WebView w = tab.getWebView();
1160 private boolean pauseWebViewTimers() {
1161 Tab tab = mTabControl.getCurrentTab();
1162 boolean inLoad = tab.inLoad();
1163 if (mActivityInPause && !inLoad) {
1164 CookieSyncManager.getInstance().stopSync();
1165 WebView w = mTabControl.getCurrentWebView();
1175 // FIXME: Do we want to call this when loading google for the first time?
1177 * This function is called when we are launching for the first time. We
1178 * are waiting for the login credentials before loading Google home
1179 * pages. This way the user will be logged in straight away.
1181 private void waitForCredentials() {
1183 mCredsDlg = new ProgressDialog(this);
1184 mCredsDlg.setIndeterminate(true);
1185 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1186 // If the user cancels the operation, then cancel the Google
1187 // Credentials request.
1188 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1191 // We set a timeout for the retrieval of credentials in onResume()
1192 // as that is when we have freed up some CPU time to get
1193 // the login credentials.
1197 * If we have received the credentials or we have timed out and we are
1198 * showing the credentials dialog, then it is time to move on.
1200 private void resumeAfterCredentials() {
1201 if (mCredsDlg == null) {
1206 if (mCredsDlg.isShowing()) {
1207 mCredsDlg.dismiss();
1211 // Clear any pending timeout
1212 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1215 WebView w = mTabControl.getCurrentWebView();
1217 w.loadUrl(mSettings.getHomePage());
1220 // Update the settings, need to do this last as it can take a moment
1221 // to persist the settings. In the mean time we could be loading
1223 mSettings.setLoginInitialized(this);
1226 // Open the icon database and retain all the icons for visited sites.
1227 private void retainIconsOnStartup() {
1228 final WebIconDatabase db = WebIconDatabase.getInstance();
1229 db.open(getDir("icons", 0).getPath());
1231 Cursor c = Browser.getAllBookmarks(mResolver);
1232 if (!c.moveToFirst()) {
1236 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1238 String url = c.getString(urlIndex);
1239 db.retainIconForPageUrl(url);
1240 } while (c.moveToNext());
1242 } catch (IllegalStateException e) {
1243 Log.e(LOGTAG, "retainIconsOnStartup", e);
1247 // Helper method for getting the top window.
1248 WebView getTopWindow() {
1249 return mTabControl.getCurrentTopWebView();
1252 TabControl getTabControl() {
1257 public boolean onCreateOptionsMenu(Menu menu) {
1258 super.onCreateOptionsMenu(menu);
1260 MenuInflater inflater = getMenuInflater();
1261 inflater.inflate(R.menu.browser, menu);
1263 updateInLoadMenuItems();
1268 * As the menu can be open when loading state changes
1269 * we must manually update the state of the stop/reload menu
1272 private void updateInLoadMenuItems() {
1273 if (mMenu == null) {
1276 MenuItem src = mInLoad ?
1277 mMenu.findItem(R.id.stop_menu_id):
1278 mMenu.findItem(R.id.reload_menu_id);
1279 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1280 dest.setIcon(src.getIcon());
1281 dest.setTitle(src.getTitle());
1285 public boolean onContextItemSelected(MenuItem item) {
1286 // chording is not an issue with context menus, but we use the same
1287 // options selector, so set mCanChord to true so we can access them.
1289 int id = item.getItemId();
1290 boolean result = true;
1292 // For the context menu from the title bar
1293 case R.id.title_bar_copy_page_url:
1294 Tab currentTab = mTabControl.getCurrentTab();
1295 if (null == currentTab) {
1299 WebView mainView = currentTab.getWebView();
1300 if (null == mainView) {
1304 copy(mainView.getUrl());
1306 // -- Browser context menu
1307 case R.id.open_context_menu_id:
1308 case R.id.open_newtab_context_menu_id:
1309 case R.id.bookmark_context_menu_id:
1310 case R.id.save_link_context_menu_id:
1311 case R.id.share_link_context_menu_id:
1312 case R.id.copy_link_context_menu_id:
1313 final WebView webView = getTopWindow();
1314 if (null == webView) {
1318 final HashMap hrefMap = new HashMap();
1319 hrefMap.put("webview", webView);
1320 final Message msg = mHandler.obtainMessage(
1321 FOCUS_NODE_HREF, id, 0, hrefMap);
1322 webView.requestFocusNodeHref(msg);
1326 // For other context menus
1327 result = onOptionsItemSelected(item);
1333 private Bundle createGoogleSearchSourceBundle(String source) {
1334 Bundle bundle = new Bundle();
1335 bundle.putString(SearchManager.SOURCE, source);
1340 * Overriding this to insert a local information bundle
1343 public boolean onSearchRequested() {
1344 if (mOptionsMenuOpen) closeOptionsMenu();
1345 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1346 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1347 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1352 public void startSearch(String initialQuery, boolean selectInitialQuery,
1353 Bundle appSearchData, boolean globalSearch) {
1354 if (appSearchData == null) {
1355 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1357 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1361 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1362 * results in changing tabs.
1363 * @param index Index of the tab to change to, as defined by
1364 * mTabControl.getTabIndex(Tab t).
1365 * @return boolean True if we successfully switched to a different tab. If
1366 * the indexth tab is null, or if that tab is the same as
1367 * the current one, return false.
1369 /* package */ boolean switchToTab(int index) {
1370 Tab tab = mTabControl.getTab(index);
1371 Tab currentTab = mTabControl.getCurrentTab();
1372 if (tab == null || tab == currentTab) {
1375 if (currentTab != null) {
1376 // currentTab may be null if it was just removed. In that case,
1377 // we do not need to remove it
1378 removeTabFromContentView(currentTab);
1380 mTabControl.setCurrentTab(tab);
1381 attachTabToContentView(tab);
1382 resetTitleIconAndProgress();
1383 updateLockIconToLatest();
1387 /* package */ Tab openTabToHomePage() {
1388 return openTabAndShow(mSettings.getHomePage(), false, null);
1391 /* package */ void closeCurrentWindow() {
1392 final Tab current = mTabControl.getCurrentTab();
1393 if (mTabControl.getTabCount() == 1) {
1394 // This is the last tab. Open a new one, with the home
1395 // page and close the current one.
1396 openTabToHomePage();
1400 final Tab parent = current.getParentTab();
1401 int indexToShow = -1;
1402 if (parent != null) {
1403 indexToShow = mTabControl.getTabIndex(parent);
1405 final int currentIndex = mTabControl.getCurrentIndex();
1406 // Try to move to the tab to the right
1407 indexToShow = currentIndex + 1;
1408 if (indexToShow > mTabControl.getTabCount() - 1) {
1409 // Try to move to the tab to the left
1410 indexToShow = currentIndex - 1;
1413 if (switchToTab(indexToShow)) {
1419 private ActiveTabsPage mActiveTabsPage;
1422 * Remove the active tabs page.
1423 * @param needToAttach If true, the active tabs page did not attach a tab
1424 * to the content view, so we need to do that here.
1426 /* package */ void removeActiveTabPage(boolean needToAttach) {
1427 mContentView.removeView(mActiveTabsPage);
1428 mActiveTabsPage = null;
1429 mMenuState = R.id.MAIN_MENU;
1431 attachTabToContentView(mTabControl.getCurrentTab());
1433 getTopWindow().requestFocus();
1437 public boolean onOptionsItemSelected(MenuItem item) {
1439 // The user has already fired a shortcut with this hold down of the
1443 if (null == getTopWindow()) {
1447 // The shortcut action consumes the MENU. Even if it is still down,
1448 // it won't trigger the next shortcut action. In the case of the
1449 // shortcut action triggering a new activity, like Bookmarks, we
1450 // won't get onKeyUp for MENU. So it is important to reset it here.
1451 mMenuIsDown = false;
1453 switch (item.getItemId()) {
1455 case R.id.new_tab_menu_id:
1456 openTabToHomePage();
1459 case R.id.goto_menu_id:
1460 onSearchRequested();
1463 case R.id.bookmarks_menu_id:
1464 bookmarksOrHistoryPicker(false);
1467 case R.id.active_tabs_menu_id:
1468 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1469 removeTabFromContentView(mTabControl.getCurrentTab());
1471 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1472 mActiveTabsPage.requestFocus();
1473 mMenuState = EMPTY_MENU;
1476 case R.id.add_bookmark_menu_id:
1477 Intent i = new Intent(BrowserActivity.this,
1478 AddBookmarkPage.class);
1479 WebView w = getTopWindow();
1480 i.putExtra("url", w.getUrl());
1481 i.putExtra("title", w.getTitle());
1482 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1483 i.putExtra("thumbnail", createScreenshot(w));
1487 case R.id.stop_reload_menu_id:
1491 getTopWindow().reload();
1495 case R.id.back_menu_id:
1496 getTopWindow().goBack();
1499 case R.id.forward_menu_id:
1500 getTopWindow().goForward();
1503 case R.id.close_menu_id:
1504 // Close the subwindow if it exists.
1505 if (mTabControl.getCurrentSubWindow() != null) {
1506 dismissSubWindow(mTabControl.getCurrentTab());
1509 closeCurrentWindow();
1512 case R.id.homepage_menu_id:
1513 Tab current = mTabControl.getCurrentTab();
1514 if (current != null) {
1515 dismissSubWindow(current);
1516 current.getWebView().loadUrl(mSettings.getHomePage());
1520 case R.id.preferences_menu_id:
1521 Intent intent = new Intent(this,
1522 BrowserPreferencesPage.class);
1523 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1524 getTopWindow().getUrl());
1525 startActivityForResult(intent, PREFERENCES_PAGE);
1528 case R.id.find_menu_id:
1529 if (null == mFindDialog) {
1530 mFindDialog = new FindDialog(this);
1532 mFindDialog.setWebView(getTopWindow());
1534 mMenuState = EMPTY_MENU;
1537 case R.id.select_text_id:
1538 getTopWindow().emulateShiftHeld();
1540 case R.id.page_info_menu_id:
1541 showPageInfo(mTabControl.getCurrentTab(), false);
1544 case R.id.classic_history_menu_id:
1545 bookmarksOrHistoryPicker(true);
1548 case R.id.title_bar_share_page_url:
1549 case R.id.share_page_menu_id:
1550 Tab currentTab = mTabControl.getCurrentTab();
1551 if (null == currentTab) {
1555 currentTab.populatePickerData();
1556 sharePage(this, currentTab.getTitle(),
1557 currentTab.getUrl(), currentTab.getFavicon(),
1558 createScreenshot(currentTab.getWebView()));
1561 case R.id.dump_nav_menu_id:
1562 getTopWindow().debugDump();
1565 case R.id.dump_counters_menu_id:
1566 getTopWindow().dumpV8Counters();
1569 case R.id.zoom_in_menu_id:
1570 getTopWindow().zoomIn();
1573 case R.id.zoom_out_menu_id:
1574 getTopWindow().zoomOut();
1577 case R.id.view_downloads_menu_id:
1578 viewDownloads(null);
1581 case R.id.window_one_menu_id:
1582 case R.id.window_two_menu_id:
1583 case R.id.window_three_menu_id:
1584 case R.id.window_four_menu_id:
1585 case R.id.window_five_menu_id:
1586 case R.id.window_six_menu_id:
1587 case R.id.window_seven_menu_id:
1588 case R.id.window_eight_menu_id:
1590 int menuid = item.getItemId();
1591 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1592 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1593 Tab desiredTab = mTabControl.getTab(id);
1594 if (desiredTab != null &&
1595 desiredTab != mTabControl.getCurrentTab()) {
1605 if (!super.onOptionsItemSelected(item)) {
1608 // Otherwise fall through.
1614 public void closeFind() {
1615 mMenuState = R.id.MAIN_MENU;
1619 public boolean onPrepareOptionsMenu(Menu menu) {
1620 // This happens when the user begins to hold down the menu key, so
1621 // allow them to chord to get a shortcut.
1623 // Note: setVisible will decide whether an item is visible; while
1624 // setEnabled() will decide whether an item is enabled, which also means
1625 // whether the matching shortcut key will function.
1626 super.onPrepareOptionsMenu(menu);
1627 switch (mMenuState) {
1629 if (mCurrentMenuState != mMenuState) {
1630 menu.setGroupVisible(R.id.MAIN_MENU, false);
1631 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1632 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1636 if (mCurrentMenuState != mMenuState) {
1637 menu.setGroupVisible(R.id.MAIN_MENU, true);
1638 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1639 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1641 final WebView w = getTopWindow();
1642 boolean canGoBack = false;
1643 boolean canGoForward = false;
1644 boolean isHome = false;
1646 canGoBack = w.canGoBack();
1647 canGoForward = w.canGoForward();
1648 isHome = mSettings.getHomePage().equals(w.getUrl());
1650 final MenuItem back = menu.findItem(R.id.back_menu_id);
1651 back.setEnabled(canGoBack);
1653 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1654 home.setEnabled(!isHome);
1656 menu.findItem(R.id.forward_menu_id)
1657 .setEnabled(canGoForward);
1659 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1660 mTabControl.canCreateNewTab());
1662 // decide whether to show the share link option
1663 PackageManager pm = getPackageManager();
1664 Intent send = new Intent(Intent.ACTION_SEND);
1665 send.setType("text/plain");
1666 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1667 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1669 boolean isNavDump = mSettings.isNavDump();
1670 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1671 nav.setVisible(isNavDump);
1672 nav.setEnabled(isNavDump);
1674 boolean showDebugSettings = mSettings.showDebugSettings();
1675 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1676 counter.setVisible(showDebugSettings);
1677 counter.setEnabled(showDebugSettings);
1681 mCurrentMenuState = mMenuState;
1686 public void onCreateContextMenu(ContextMenu menu, View v,
1687 ContextMenuInfo menuInfo) {
1688 WebView webview = (WebView) v;
1689 WebView.HitTestResult result = webview.getHitTestResult();
1690 if (result == null) {
1694 int type = result.getType();
1695 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1697 "We should not show context menu when nothing is touched");
1700 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1701 // let TextView handles context menu
1705 // Note, http://b/issue?id=1106666 is requesting that
1706 // an inflated menu can be used again. This is not available
1707 // yet, so inflate each time (yuk!)
1708 MenuInflater inflater = getMenuInflater();
1709 inflater.inflate(R.menu.browsercontext, menu);
1711 // Show the correct menu group
1712 String extra = result.getExtra();
1713 menu.setGroupVisible(R.id.PHONE_MENU,
1714 type == WebView.HitTestResult.PHONE_TYPE);
1715 menu.setGroupVisible(R.id.EMAIL_MENU,
1716 type == WebView.HitTestResult.EMAIL_TYPE);
1717 menu.setGroupVisible(R.id.GEO_MENU,
1718 type == WebView.HitTestResult.GEO_TYPE);
1719 menu.setGroupVisible(R.id.IMAGE_MENU,
1720 type == WebView.HitTestResult.IMAGE_TYPE
1721 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1722 menu.setGroupVisible(R.id.ANCHOR_MENU,
1723 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1724 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1726 // Setup custom handling depending on the type
1728 case WebView.HitTestResult.PHONE_TYPE:
1729 menu.setHeaderTitle(Uri.decode(extra));
1730 menu.findItem(R.id.dial_context_menu_id).setIntent(
1731 new Intent(Intent.ACTION_VIEW, Uri
1732 .parse(WebView.SCHEME_TEL + extra)));
1733 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1734 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1735 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1736 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1738 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1742 case WebView.HitTestResult.EMAIL_TYPE:
1743 menu.setHeaderTitle(extra);
1744 menu.findItem(R.id.email_context_menu_id).setIntent(
1745 new Intent(Intent.ACTION_VIEW, Uri
1746 .parse(WebView.SCHEME_MAILTO + extra)));
1747 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1751 case WebView.HitTestResult.GEO_TYPE:
1752 menu.setHeaderTitle(extra);
1753 menu.findItem(R.id.map_context_menu_id).setIntent(
1754 new Intent(Intent.ACTION_VIEW, Uri
1755 .parse(WebView.SCHEME_GEO
1756 + URLEncoder.encode(extra))));
1757 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1761 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1762 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1763 TextView titleView = (TextView) LayoutInflater.from(this)
1764 .inflate(android.R.layout.browser_link_context_header,
1766 titleView.setText(extra);
1767 menu.setHeaderView(titleView);
1768 // decide whether to show the open link in new tab option
1769 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1770 mTabControl.canCreateNewTab());
1771 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1772 Bookmarks.urlHasAcceptableScheme(extra));
1773 PackageManager pm = getPackageManager();
1774 Intent send = new Intent(Intent.ACTION_SEND);
1775 send.setType("text/plain");
1776 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1777 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1778 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1781 // otherwise fall through to handle image part
1782 case WebView.HitTestResult.IMAGE_TYPE:
1783 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1784 menu.setHeaderTitle(extra);
1786 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1787 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1788 menu.findItem(R.id.download_context_menu_id).
1789 setOnMenuItemClickListener(new Download(extra));
1790 menu.findItem(R.id.set_wallpaper_context_menu_id).
1791 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1795 Log.w(LOGTAG, "We should not get here.");
1801 // Attach the given tab to the content view.
1802 // this should only be called for the current tab.
1803 private void attachTabToContentView(Tab t) {
1804 // Attach the container that contains the main WebView and any other UI
1805 // associated with the tab.
1806 t.attachTabToContentView(mContentView);
1808 if (mShouldShowErrorConsole) {
1809 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1810 if (errorConsole.numberOfErrors() == 0) {
1811 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1813 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1816 mErrorConsoleContainer.addView(errorConsole,
1817 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1818 ViewGroup.LayoutParams.WRAP_CONTENT));
1821 WebView view = t.getWebView();
1822 view.setEmbeddedTitleBar(mTitleBar);
1823 if (t.isInVoiceSearchMode()) {
1824 showVoiceTitleBar(t.getVoiceDisplayTitle());
1826 revertVoiceTitleBar();
1828 // Request focus on the top window.
1829 t.getTopWindow().requestFocus();
1832 // Attach a sub window to the main WebView of the given tab.
1833 void attachSubWindow(Tab t) {
1834 t.attachSubWindow(mContentView);
1835 getTopWindow().requestFocus();
1838 // Remove the given tab from the content view.
1839 private void removeTabFromContentView(Tab t) {
1840 // Remove the container that contains the main WebView.
1841 t.removeTabFromContentView(mContentView);
1843 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1844 if (errorConsole != null) {
1845 mErrorConsoleContainer.removeView(errorConsole);
1848 WebView view = t.getWebView();
1850 view.setEmbeddedTitleBar(null);
1854 // Remove the sub window if it exists. Also called by TabControl when the
1855 // user clicks the 'X' to dismiss a sub window.
1856 /* package */ void dismissSubWindow(Tab t) {
1857 t.removeSubWindow(mContentView);
1858 // dismiss the subwindow. This will destroy the WebView.
1859 t.dismissSubWindow();
1860 getTopWindow().requestFocus();
1863 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1864 // that accepts url as string.
1865 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1866 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1869 // This method does a ton of stuff. It will attempt to create a new tab
1870 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1871 // url isn't null, it will load the given url.
1872 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1874 final Tab currentTab = mTabControl.getCurrentTab();
1875 if (mTabControl.canCreateNewTab()) {
1876 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1878 WebView webview = tab.getWebView();
1879 // If the last tab was removed from the active tabs page, currentTab
1881 if (currentTab != null) {
1882 removeTabFromContentView(currentTab);
1884 // We must set the new tab as the current tab to reflect the old
1885 // animation behavior.
1886 mTabControl.setCurrentTab(tab);
1887 attachTabToContentView(tab);
1888 if (!urlData.isEmpty()) {
1889 urlData.loadIn(tab);
1893 // Get rid of the subwindow if it exists
1894 dismissSubWindow(currentTab);
1895 if (!urlData.isEmpty()) {
1896 // Load the given url.
1897 urlData.loadIn(currentTab);
1903 private Tab openTab(String url) {
1904 if (mSettings.openInBackground()) {
1905 Tab t = mTabControl.createNewTab();
1907 WebView view = t.getWebView();
1912 return openTabAndShow(url, false, null);
1916 private class Copy implements OnMenuItemClickListener {
1917 private CharSequence mText;
1919 public boolean onMenuItemClick(MenuItem item) {
1924 public Copy(CharSequence toCopy) {
1929 private class Download implements OnMenuItemClickListener {
1930 private String mText;
1932 public boolean onMenuItemClick(MenuItem item) {
1933 onDownloadStartNoStream(mText, null, null, null, -1);
1937 public Download(String toDownload) {
1942 private class SetAsWallpaper extends Thread implements
1943 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1945 private ProgressDialog mWallpaperProgress;
1946 private boolean mCanceled = false;
1948 public SetAsWallpaper(String url) {
1950 mUrl = new URL(url);
1951 } catch (MalformedURLException e) {
1956 public void onCancel(DialogInterface dialog) {
1960 public boolean onMenuItemClick(MenuItem item) {
1962 // The user may have tried to set a image with a large file size as their
1963 // background so it may take a few moments to perform the operation. Display
1964 // a progress spinner while it is working.
1965 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1966 mWallpaperProgress.setIndeterminate(true);
1967 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1968 mWallpaperProgress.setCancelable(true);
1969 mWallpaperProgress.setOnCancelListener(this);
1970 mWallpaperProgress.show();
1977 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1979 // TODO: This will cause the resource to be downloaded again, when we
1980 // should in most cases be able to grab it from the cache. To fix this
1981 // we should query WebCore to see if we can access a cached version and
1982 // instead open an input stream on that. This pattern could also be used
1983 // in the download manager where the same problem exists.
1984 InputStream inputstream = mUrl.openStream();
1985 if (inputstream != null) {
1986 setWallpaper(inputstream);
1988 } catch (IOException e) {
1989 Log.e(LOGTAG, "Unable to set new wallpaper");
1990 // Act as though the user canceled the operation so we try to
1991 // restore the old wallpaper.
1996 // Restore the old wallpaper if the user cancelled whilst we were setting
1997 // the new wallpaper.
1998 int width = oldWallpaper.getIntrinsicWidth();
1999 int height = oldWallpaper.getIntrinsicHeight();
2000 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2001 Canvas canvas = new Canvas(bm);
2002 oldWallpaper.setBounds(0, 0, width, height);
2003 oldWallpaper.draw(canvas);
2006 } catch (IOException e) {
2007 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2012 if (mWallpaperProgress.isShowing()) {
2013 mWallpaperProgress.dismiss();
2018 private void copy(CharSequence text) {
2020 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2022 clip.setClipboardText(text);
2024 } catch (android.os.RemoteException e) {
2025 Log.e(LOGTAG, "Copy failed", e);
2030 * Resets the browser title-view to whatever it must be
2031 * (for example, if we had a loading error)
2032 * When we have a new page, we call resetTitle, when we
2033 * have to reset the titlebar to whatever it used to be
2034 * (for example, if the user chose to stop loading), we
2035 * call resetTitleAndRevertLockIcon.
2037 /* package */ void resetTitleAndRevertLockIcon() {
2038 mTabControl.getCurrentTab().revertLockIcon();
2039 updateLockIconToLatest();
2040 resetTitleIconAndProgress();
2044 * Reset the title, favicon, and progress.
2046 private void resetTitleIconAndProgress() {
2047 WebView current = mTabControl.getCurrentWebView();
2048 if (current == null) {
2051 resetTitleAndIcon(current);
2052 int progress = current.getProgress();
2053 current.getWebChromeClient().onProgressChanged(current, progress);
2056 // Reset the title and the icon based on the given item.
2057 private void resetTitleAndIcon(WebView view) {
2058 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2060 setUrlTitle(item.getUrl(), item.getTitle());
2061 setFavicon(item.getFavicon());
2063 setUrlTitle(null, null);
2069 * Sets a title composed of the URL and the title string.
2070 * @param url The URL of the site being loaded.
2071 * @param title The title of the site being loaded.
2073 void setUrlTitle(String url, String title) {
2077 // If we are in voice search mode, the title has already been set.
2078 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2079 mTitleBar.setDisplayTitle(url);
2080 mFakeTitleBar.setDisplayTitle(url);
2084 * @param url The URL to build a title version of the URL from.
2085 * @return The title version of the URL or null if fails.
2086 * The title version of the URL can be either the URL hostname,
2087 * or the hostname with an "https://" prefix (for secure URLs),
2088 * or an empty string if, for example, the URL in question is a
2089 * file:// URL with no hostname.
2091 /* package */ static String buildTitleUrl(String url) {
2092 String titleUrl = null;
2096 // parse the url string
2097 URL urlObj = new URL(url);
2098 if (urlObj != null) {
2101 String protocol = urlObj.getProtocol();
2102 String host = urlObj.getHost();
2104 if (host != null && 0 < host.length()) {
2106 if (protocol != null) {
2107 // if a secure site, add an "https://" prefix!
2108 if (protocol.equalsIgnoreCase("https")) {
2109 titleUrl = protocol + "://" + host;
2114 } catch (MalformedURLException e) {}
2120 // Set the favicon in the title bar.
2121 void setFavicon(Bitmap icon) {
2122 mTitleBar.setFavicon(icon);
2123 mFakeTitleBar.setFavicon(icon);
2127 * Close the tab, remove its associated title bar, and adjust mTabControl's
2128 * current tab to a valid value.
2130 /* package */ void closeTab(Tab t) {
2131 int currentIndex = mTabControl.getCurrentIndex();
2132 int removeIndex = mTabControl.getTabIndex(t);
2133 mTabControl.removeTab(t);
2134 if (currentIndex >= removeIndex && currentIndex != 0) {
2137 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2138 resetTitleIconAndProgress();
2141 private void goBackOnePageOrQuit() {
2142 Tab current = mTabControl.getCurrentTab();
2143 if (current == null) {
2145 * Instead of finishing the activity, simply push this to the back
2146 * of the stack and let ActivityManager to choose the foreground
2147 * activity. As BrowserActivity is singleTask, it will be always the
2148 * root of the task. So we can use either true or false for
2151 moveTaskToBack(true);
2154 WebView w = current.getWebView();
2155 if (w.canGoBack()) {
2158 // Check to see if we are closing a window that was created by
2159 // another window. If so, we switch back to that window.
2160 Tab parent = current.getParentTab();
2161 if (parent != null) {
2162 switchToTab(mTabControl.getTabIndex(parent));
2163 // Now we close the other tab
2166 if (current.closeOnExit()) {
2167 // force the tab's inLoad() to be false as we are going to
2168 // either finish the activity or remove the tab. This will
2169 // ensure pauseWebViewTimers() taking action.
2170 mTabControl.getCurrentTab().clearInLoad();
2171 if (mTabControl.getTabCount() == 1) {
2175 // call pauseWebViewTimers() now, we won't be able to call
2176 // it in onPause() as the WebView won't be valid.
2177 // Temporarily change mActivityInPause to be true as
2178 // pauseWebViewTimers() will do nothing if mActivityInPause
2180 boolean savedState = mActivityInPause;
2182 Log.e(LOGTAG, "BrowserActivity is already paused "
2183 + "while handing goBackOnePageOrQuit.");
2185 mActivityInPause = true;
2186 pauseWebViewTimers();
2187 mActivityInPause = savedState;
2188 removeTabFromContentView(current);
2189 mTabControl.removeTab(current);
2192 * Instead of finishing the activity, simply push this to the back
2193 * of the stack and let ActivityManager to choose the foreground
2194 * activity. As BrowserActivity is singleTask, it will be always the
2195 * root of the task. So we can use either true or false for
2198 moveTaskToBack(true);
2203 boolean isMenuDown() {
2208 public boolean onKeyDown(int keyCode, KeyEvent event) {
2209 // Even if MENU is already held down, we need to call to super to open
2210 // the IME on long press.
2211 if (KeyEvent.KEYCODE_MENU == keyCode) {
2213 return super.onKeyDown(keyCode, event);
2215 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2216 // still down, we don't want to trigger the search. Pretend to consume
2217 // the key and do nothing.
2218 if (mMenuIsDown) return true;
2221 case KeyEvent.KEYCODE_SPACE:
2222 // WebView/WebTextView handle the keys in the KeyDown. As
2223 // the Activity's shortcut keys are only handled when WebView
2224 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2225 if (event.isShiftPressed()) {
2226 getTopWindow().pageUp(false);
2228 getTopWindow().pageDown(false);
2231 case KeyEvent.KEYCODE_BACK:
2232 if (event.getRepeatCount() == 0) {
2233 event.startTracking();
2235 } else if (mCustomView == null && mActiveTabsPage == null
2236 && event.isLongPress()) {
2237 bookmarksOrHistoryPicker(true);
2242 return super.onKeyDown(keyCode, event);
2246 public boolean onKeyUp(int keyCode, KeyEvent event) {
2248 case KeyEvent.KEYCODE_MENU:
2249 mMenuIsDown = false;
2251 case KeyEvent.KEYCODE_BACK:
2252 if (event.isTracking() && !event.isCanceled()) {
2253 if (mCustomView != null) {
2254 // if a custom view is showing, hide it
2255 mTabControl.getCurrentWebView().getWebChromeClient()
2256 .onHideCustomView();
2257 } else if (mActiveTabsPage != null) {
2258 // if tab page is showing, hide it
2259 removeActiveTabPage(true);
2261 WebView subwindow = mTabControl.getCurrentSubWindow();
2262 if (subwindow != null) {
2263 if (subwindow.canGoBack()) {
2266 dismissSubWindow(mTabControl.getCurrentTab());
2269 goBackOnePageOrQuit();
2276 return super.onKeyUp(keyCode, event);
2279 /* package */ void stopLoading() {
2280 mDidStopLoad = true;
2281 resetTitleAndRevertLockIcon();
2282 WebView w = getTopWindow();
2284 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2285 // same logic here. But for subwindow case, should we call into the main
2286 // WebView's onPageFinished as we never call its onPageStarted and if
2287 // the page finishes itself, we don't call onPageFinished.
2288 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2293 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2297 boolean didUserStopLoading() {
2298 return mDidStopLoad;
2301 private void cancelStopToast() {
2302 if (mStopToast != null) {
2303 mStopToast.cancel();
2308 // called by a UI or non-UI thread to post the message
2309 public void postMessage(int what, int arg1, int arg2, Object obj,
2311 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2315 // called by a UI or non-UI thread to remove the message
2316 void removeMessages(int what, Object object) {
2317 mHandler.removeMessages(what, object);
2320 // public message ids
2321 public final static int LOAD_URL = 1001;
2322 public final static int STOP_LOAD = 1002;
2325 private static final int FOCUS_NODE_HREF = 102;
2326 private static final int CANCEL_CREDS_REQUEST = 103;
2327 private static final int RELEASE_WAKELOCK = 107;
2329 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2331 // Private handler for handling javascript and saving passwords
2332 private Handler mHandler = new Handler() {
2334 public void handleMessage(Message msg) {
2336 case FOCUS_NODE_HREF:
2338 String url = (String) msg.getData().get("url");
2339 String title = (String) msg.getData().get("title");
2340 if (url == null || url.length() == 0) {
2343 HashMap focusNodeMap = (HashMap) msg.obj;
2344 WebView view = (WebView) focusNodeMap.get("webview");
2345 // Only apply the action if the top window did not change.
2346 if (getTopWindow() != view) {
2350 case R.id.open_context_menu_id:
2351 case R.id.view_image_context_menu_id:
2352 loadURL(getTopWindow(), url);
2354 case R.id.open_newtab_context_menu_id:
2355 final Tab parent = mTabControl.getCurrentTab();
2356 final Tab newTab = openTab(url);
2357 if (newTab != parent) {
2358 parent.addChildTab(newTab);
2361 case R.id.bookmark_context_menu_id:
2362 Intent intent = new Intent(BrowserActivity.this,
2363 AddBookmarkPage.class);
2364 intent.putExtra("url", url);
2365 intent.putExtra("title", title);
2366 startActivity(intent);
2368 case R.id.share_link_context_menu_id:
2369 // See if this site has been visited before
2370 StringBuilder sb = new StringBuilder(
2371 Browser.BookmarkColumns.URL + " = ");
2372 DatabaseUtils.appendEscapedSQLString(sb, url);
2373 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2374 Browser.HISTORY_PROJECTION,
2378 if (c.moveToFirst()) {
2379 // The site has been visited before, so grab the
2380 // info from the database.
2381 Bitmap favicon = null;
2382 Bitmap thumbnail = null;
2383 String linkTitle = c.getString(Browser.
2384 HISTORY_PROJECTION_TITLE_INDEX);
2385 byte[] data = c.getBlob(Browser.
2386 HISTORY_PROJECTION_FAVICON_INDEX);
2388 favicon = BitmapFactory.decodeByteArray(
2389 data, 0, data.length);
2391 data = c.getBlob(Browser.
2392 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2394 thumbnail = BitmapFactory.decodeByteArray(
2395 data, 0, data.length);
2397 sharePage(BrowserActivity.this,
2398 linkTitle, url, favicon, thumbnail);
2400 Browser.sendString(BrowserActivity.this, url,
2402 R.string.choosertitle_sharevia));
2405 case R.id.copy_link_context_menu_id:
2408 case R.id.save_link_context_menu_id:
2409 case R.id.download_context_menu_id:
2410 onDownloadStartNoStream(url, null, null, null, -1);
2417 loadURL(getTopWindow(), (String) msg.obj);
2424 case CANCEL_CREDS_REQUEST:
2425 resumeAfterCredentials();
2428 case RELEASE_WAKELOCK:
2429 if (mWakeLock.isHeld()) {
2430 mWakeLock.release();
2431 // if we reach here, Browser should be still in the
2432 // background loading after WAKELOCK_TIMEOUT (5-min).
2433 // To avoid burning the battery, stop loading.
2434 mTabControl.stopAllLoading();
2438 case UPDATE_BOOKMARK_THUMBNAIL:
2439 WebView view = (WebView) msg.obj;
2441 updateScreenshot(view);
2449 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2450 * an {@link Intent} to launch the Activity chooser.
2451 * @param c Context used to launch a new Activity.
2452 * @param title Title of the page. Stored in the Intent with
2453 * {@link Browser#EXTRA_SHARE_TITLE}
2454 * @param url URL of the page. Stored in the Intent with
2455 * {@link Intent#EXTRA_TEXT}
2456 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2457 * with {@link Browser#EXTRA_SHARE_FAVICON}
2458 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2459 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2461 public static final void sharePage(Context c, String title, String url,
2462 Bitmap favicon, Bitmap screenshot) {
2463 Intent send = new Intent(Intent.ACTION_SEND);
2464 send.setType("text/plain");
2465 send.putExtra(Intent.EXTRA_TEXT, url);
2466 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2467 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2468 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2470 c.startActivity(Intent.createChooser(send, c.getString(
2471 R.string.choosertitle_sharevia)));
2472 } catch(android.content.ActivityNotFoundException ex) {
2473 // if no app handles it, do nothing
2477 private void updateScreenshot(WebView view) {
2478 // If this is a bookmarked site, add a screenshot to the database.
2479 // FIXME: When should we update? Every time?
2480 // FIXME: Would like to make sure there is actually something to
2481 // draw, but the API for that (WebViewCore.pictureReady()) is not
2482 // currently accessible here.
2484 ContentResolver cr = getContentResolver();
2485 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2486 cr, view.getOriginalUrl(), view.getUrl(), true);
2488 boolean succeed = c.moveToFirst();
2489 ContentValues values = null;
2491 if (values == null) {
2492 final ByteArrayOutputStream os
2493 = new ByteArrayOutputStream();
2494 Bitmap bm = createScreenshot(view);
2499 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2500 values = new ContentValues();
2501 values.put(Browser.BookmarkColumns.THUMBNAIL,
2504 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2505 c.getInt(0)), values, null, null);
2506 succeed = c.moveToNext();
2513 * Values for the size of the thumbnail created when taking a screenshot.
2514 * Lazily initialized. Instead of using these directly, use
2515 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2517 private static int THUMBNAIL_WIDTH = 0;
2518 private static int THUMBNAIL_HEIGHT = 0;
2521 * Return the desired width for thumbnail screenshots, which are stored in
2522 * the database, and used on the bookmarks screen.
2523 * @param context Context for finding out the density of the screen.
2524 * @return int desired width for thumbnail screenshot.
2526 /* package */ static int getDesiredThumbnailWidth(Context context) {
2527 if (THUMBNAIL_WIDTH == 0) {
2528 float density = context.getResources().getDisplayMetrics().density;
2529 THUMBNAIL_WIDTH = (int) (90 * density);
2530 THUMBNAIL_HEIGHT = (int) (80 * density);
2532 return THUMBNAIL_WIDTH;
2536 * Return the desired height for thumbnail screenshots, which are stored in
2537 * the database, and used on the bookmarks screen.
2538 * @param context Context for finding out the density of the screen.
2539 * @return int desired height for thumbnail screenshot.
2541 /* package */ static int getDesiredThumbnailHeight(Context context) {
2542 // To ensure that they are both initialized.
2543 getDesiredThumbnailWidth(context);
2544 return THUMBNAIL_HEIGHT;
2547 private Bitmap createScreenshot(WebView view) {
2548 Picture thumbnail = view.capturePicture();
2549 if (thumbnail == null) {
2552 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2553 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2554 Canvas canvas = new Canvas(bm);
2555 // May need to tweak these values to determine what is the
2556 // best scale factor
2557 int thumbnailWidth = thumbnail.getWidth();
2558 int thumbnailHeight = thumbnail.getHeight();
2559 float scaleFactorX = 1.0f;
2560 float scaleFactorY = 1.0f;
2561 if (thumbnailWidth > 0) {
2562 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2563 (float)thumbnailWidth;
2568 if (view.getWidth() > view.getHeight() &&
2569 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2570 // If the device is in landscape and the page is shorter
2571 // than the height of the view, stretch the thumbnail to fill the
2573 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2574 (float)thumbnailHeight;
2576 // In the portrait case, this looks nice.
2577 scaleFactorY = scaleFactorX;
2580 canvas.scale(scaleFactorX, scaleFactorY);
2582 thumbnail.draw(canvas);
2586 // -------------------------------------------------------------------------
2587 // Helper function for WebViewClient.
2588 //-------------------------------------------------------------------------
2590 // Use in overrideUrlLoading
2591 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2592 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2593 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2594 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2596 void onPageStarted(WebView view, String url, Bitmap favicon) {
2597 // when BrowserActivity just starts, onPageStarted may be called before
2598 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2599 // to start the timer. As we won't switch tabs while an activity is in
2600 // pause state, we can ensure calling resume and pause in pair.
2601 if (mActivityInPause) resumeWebViewTimers();
2604 setUrlTitle(url, null);
2605 setFavicon(favicon);
2606 // Keep this initial progress in sync with initialProgressValue (* 100)
2607 // in ProgressTracker.cpp
2608 // Show some progress so that the user knows the page is beginning to
2610 onProgressChanged(view, 10);
2611 mDidStopLoad = false;
2612 if (!mIsNetworkUp) createAndShowNetworkDialog();
2614 if (mSettings.isTracing()) {
2617 WebAddress uri = new WebAddress(url);
2619 } catch (android.net.ParseException ex) {
2622 host = host.replace('.', '_');
2625 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2628 // Performance probe
2630 mStart = SystemClock.uptimeMillis();
2631 mProcessStart = Process.getElapsedCpuTime();
2632 long[] sysCpu = new long[7];
2633 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2635 mUserStart = sysCpu[0] + sysCpu[1];
2636 mSystemStart = sysCpu[2];
2637 mIdleStart = sysCpu[3];
2638 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2640 mUiStart = SystemClock.currentThreadTimeMillis();
2644 void onPageFinished(WebView view, String url) {
2645 // Reset the title and icon in case we stopped a provisional load.
2646 resetTitleAndIcon(view);
2647 // Update the lock icon image only once we are done loading
2648 updateLockIconToLatest();
2649 // pause the WebView timer and release the wake lock if it is finished
2650 // while BrowserActivity is in pause state.
2651 if (mActivityInPause && pauseWebViewTimers()) {
2652 if (mWakeLock.isHeld()) {
2653 mHandler.removeMessages(RELEASE_WAKELOCK);
2654 mWakeLock.release();
2658 // Performance probe
2660 long[] sysCpu = new long[7];
2661 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2663 String uiInfo = "UI thread used "
2664 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2667 Log.d(LOGTAG, uiInfo);
2669 //The string that gets written to the log
2670 String performanceString = "It took total "
2671 + (SystemClock.uptimeMillis() - mStart)
2672 + " ms clock time to load the page."
2673 + "\nbrowser process used "
2674 + (Process.getElapsedCpuTime() - mProcessStart)
2675 + " ms, user processes used "
2676 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2677 + " ms, kernel used "
2678 + (sysCpu[2] - mSystemStart) * 10
2679 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2680 + " ms and irq took "
2681 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2682 * 10 + " ms, " + uiInfo;
2684 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2687 // strip the url to maintain consistency
2688 String newUrl = new String(url);
2689 if (newUrl.startsWith("http://www.")) {
2690 newUrl = newUrl.substring(11);
2691 } else if (newUrl.startsWith("http://")) {
2692 newUrl = newUrl.substring(7);
2693 } else if (newUrl.startsWith("https://www.")) {
2694 newUrl = newUrl.substring(12);
2695 } else if (newUrl.startsWith("https://")) {
2696 newUrl = newUrl.substring(8);
2699 Log.d(LOGTAG, newUrl + " loaded");
2707 Debug.stopMethodTracing();
2711 boolean shouldOverrideUrlLoading(WebView view, String url) {
2712 if (url.startsWith(SCHEME_WTAI)) {
2713 // wtai://wp/mc;number
2714 // number=string(phone-number)
2715 if (url.startsWith(SCHEME_WTAI_MC)) {
2716 Intent intent = new Intent(Intent.ACTION_VIEW,
2717 Uri.parse(WebView.SCHEME_TEL +
2718 url.substring(SCHEME_WTAI_MC.length())));
2719 startActivity(intent);
2722 // wtai://wp/sd;dtmf
2723 // dtmf=string(dialstring)
2724 if (url.startsWith(SCHEME_WTAI_SD)) {
2725 // TODO: only send when there is active voice connection
2728 // wtai://wp/ap;number;name
2729 // number=string(phone-number)
2731 if (url.startsWith(SCHEME_WTAI_AP)) {
2737 // The "about:" schemes are internal to the browser; don't want these to
2738 // be dispatched to other apps.
2739 if (url.startsWith("about:")) {
2744 // perform generic parsing of the URI to turn it into an Intent.
2746 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2747 } catch (URISyntaxException ex) {
2748 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2752 // check whether the intent can be resolved. If not, we will see
2753 // whether we can download it from the Market.
2754 if (getPackageManager().resolveActivity(intent, 0) == null) {
2755 String packagename = intent.getPackage();
2756 if (packagename != null) {
2757 intent = new Intent(Intent.ACTION_VIEW, Uri
2758 .parse("market://search?q=pname:" + packagename));
2759 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2760 startActivity(intent);
2767 // sanitize the Intent, ensuring web pages can not bypass browser
2768 // security (only access to BROWSABLE activities).
2769 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2770 intent.setComponent(null);
2772 if (startActivityIfNeeded(intent, -1)) {
2775 } catch (ActivityNotFoundException ex) {
2776 // ignore the error. If no application can handle the URL,
2777 // eg about:blank, assume the browser can handle it.
2788 // -------------------------------------------------------------------------
2789 // Helper function for WebChromeClient
2790 // -------------------------------------------------------------------------
2792 void onProgressChanged(WebView view, int newProgress) {
2793 mTitleBar.setProgress(newProgress);
2794 mFakeTitleBar.setProgress(newProgress);
2796 if (newProgress == 100) {
2797 // onProgressChanged() may continue to be called after the main
2798 // frame has finished loading, as any remaining sub frames continue
2799 // to load. We'll only get called once though with newProgress as
2800 // 100 when everything is loaded. (onPageFinished is called once
2801 // when the main frame completes loading regardless of the state of
2802 // any sub frames so calls to onProgressChanges may continue after
2803 // onPageFinished has executed)
2806 updateInLoadMenuItems();
2807 // If the options menu is open, leave the title bar
2808 if (!mOptionsMenuOpen || !mIconView) {
2812 } else if (!mInLoad) {
2813 // onPageFinished may have already been called but a subframe is
2814 // still loading and updating the progress. Reset mInLoad and update
2817 updateInLoadMenuItems();
2818 if (!mOptionsMenuOpen || mIconView) {
2819 // This page has begun to load, so show the title bar
2825 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2826 // if a view already exists then immediately terminate the new one
2827 if (mCustomView != null) {
2828 callback.onCustomViewHidden();
2832 // Add the custom view to its container.
2833 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2835 mCustomViewCallback = callback;
2836 // Save the menu state and set it to empty while the custom
2838 mOldMenuState = mMenuState;
2839 mMenuState = EMPTY_MENU;
2840 // Hide the content view.
2841 mContentView.setVisibility(View.GONE);
2842 // Finally show the custom view container.
2843 setStatusBarVisibility(false);
2844 mCustomViewContainer.setVisibility(View.VISIBLE);
2845 mCustomViewContainer.bringToFront();
2848 void onHideCustomView() {
2849 if (mCustomView == null)
2852 // Hide the custom view.
2853 mCustomView.setVisibility(View.GONE);
2854 // Remove the custom view from its container.
2855 mCustomViewContainer.removeView(mCustomView);
2857 // Reset the old menu state.
2858 mMenuState = mOldMenuState;
2859 mOldMenuState = EMPTY_MENU;
2860 mCustomViewContainer.setVisibility(View.GONE);
2861 mCustomViewCallback.onCustomViewHidden();
2862 // Show the content view.
2863 setStatusBarVisibility(true);
2864 mContentView.setVisibility(View.VISIBLE);
2867 Bitmap getDefaultVideoPoster() {
2868 if (mDefaultVideoPoster == null) {
2869 mDefaultVideoPoster = BitmapFactory.decodeResource(
2870 getResources(), R.drawable.default_video_poster);
2872 return mDefaultVideoPoster;
2875 View getVideoLoadingProgressView() {
2876 if (mVideoProgressView == null) {
2877 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2878 mVideoProgressView = inflater.inflate(
2879 R.layout.video_loading_progress, null);
2881 return mVideoProgressView;
2885 * The Object used to inform the WebView of the file to upload.
2887 private ValueCallback<Uri> mUploadMessage;
2889 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2890 if (mUploadMessage != null) return;
2891 mUploadMessage = uploadMsg;
2892 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2893 i.addCategory(Intent.CATEGORY_OPENABLE);
2895 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2896 getString(R.string.choose_upload)), FILE_SELECTED);
2899 // -------------------------------------------------------------------------
2900 // Implement functions for DownloadListener
2901 // -------------------------------------------------------------------------
2904 * Notify the host application a download should be done, or that
2905 * the data should be streamed if a streaming viewer is available.
2906 * @param url The full url to the content that should be downloaded
2907 * @param contentDisposition Content-disposition http header, if
2909 * @param mimetype The mimetype of the content reported by the server
2910 * @param contentLength The file size reported by the server
2912 public void onDownloadStart(String url, String userAgent,
2913 String contentDisposition, String mimetype, long contentLength) {
2914 // if we're dealing wih A/V content that's not explicitly marked
2915 // for download, check if it's streamable.
2916 if (contentDisposition == null
2917 || !contentDisposition.regionMatches(
2918 true, 0, "attachment", 0, 10)) {
2919 // query the package manager to see if there's a registered handler
2921 Intent intent = new Intent(Intent.ACTION_VIEW);
2922 intent.setDataAndType(Uri.parse(url), mimetype);
2923 ResolveInfo info = getPackageManager().resolveActivity(intent,
2924 PackageManager.MATCH_DEFAULT_ONLY);
2926 ComponentName myName = getComponentName();
2927 // If we resolved to ourselves, we don't want to attempt to
2928 // load the url only to try and download it again.
2929 if (!myName.getPackageName().equals(
2930 info.activityInfo.packageName)
2931 || !myName.getClassName().equals(
2932 info.activityInfo.name)) {
2933 // someone (other than us) knows how to handle this mime
2934 // type with this scheme, don't download.
2936 startActivity(intent);
2938 } catch (ActivityNotFoundException ex) {
2940 Log.d(LOGTAG, "activity not found for " + mimetype
2941 + " over " + Uri.parse(url).getScheme(),
2944 // Best behavior is to fall back to a download in this
2950 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2954 * Notify the host application a download should be done, even if there
2955 * is a streaming viewer available for thise type.
2956 * @param url The full url to the content that should be downloaded
2957 * @param contentDisposition Content-disposition http header, if
2959 * @param mimetype The mimetype of the content reported by the server
2960 * @param contentLength The file size reported by the server
2962 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2963 String contentDisposition, String mimetype, long contentLength) {
2965 String filename = URLUtil.guessFileName(url,
2966 contentDisposition, mimetype);
2968 // Check to see if we have an SDCard
2969 String status = Environment.getExternalStorageState();
2970 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2974 // Check to see if the SDCard is busy, same as the music app
2975 if (status.equals(Environment.MEDIA_SHARED)) {
2976 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2977 title = R.string.download_sdcard_busy_dlg_title;
2979 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2980 title = R.string.download_no_sdcard_dlg_title;
2983 new AlertDialog.Builder(this)
2985 .setIcon(android.R.drawable.ic_dialog_alert)
2987 .setPositiveButton(R.string.ok, null)
2992 // java.net.URI is a lot stricter than KURL so we have to undo
2993 // KURL's percent-encoding and redo the encoding using java.net.URI.
2996 // Undo the percent-encoding that KURL may have done.
2997 String newUrl = new String(URLUtil.decode(url.getBytes()));
2998 // Parse the url into pieces
2999 WebAddress w = new WebAddress(newUrl);
3001 String query = null;
3002 String path = w.mPath;
3003 // Break the path into path, query, and fragment
3004 if (path.length() > 0) {
3005 // Strip the fragment
3006 int idx = path.lastIndexOf('#');
3008 frag = path.substring(idx + 1);
3009 path = path.substring(0, idx);
3011 idx = path.lastIndexOf('?');
3013 query = path.substring(idx + 1);
3014 path = path.substring(0, idx);
3017 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3019 } catch (Exception e) {
3020 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3024 // XXX: Have to use the old url since the cookies were stored using the
3025 // old percent-encoded url.
3026 String cookies = CookieManager.getInstance().getCookie(url);
3028 ContentValues values = new ContentValues();
3029 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3030 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3031 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3032 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
3034 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
3035 BrowserDownloadPage.class.getCanonicalName());
3036 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3037 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3038 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3039 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3040 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
3041 if (contentLength > 0) {
3042 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
3044 if (mimetype == null) {
3045 // We must have long pressed on a link or image to download it. We
3046 // are not sure of the mimetype in this case, so do a head request
3047 new FetchUrlMimeType(this).execute(values);
3049 final Uri contentUri =
3050 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
3055 // -------------------------------------------------------------------------
3058 * Resets the lock icon. This method is called when we start a new load and
3059 * know the url to be loaded.
3061 private void resetLockIcon(String url) {
3062 // Save the lock-icon state (we revert to it if the load gets cancelled)
3063 mTabControl.getCurrentTab().resetLockIcon(url);
3064 updateLockIconImage(LOCK_ICON_UNSECURE);
3068 * Update the lock icon to correspond to our latest state.
3070 private void updateLockIconToLatest() {
3071 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
3075 * Updates the lock-icon image in the title-bar.
3077 private void updateLockIconImage(int lockIconType) {
3079 if (lockIconType == LOCK_ICON_SECURE) {
3081 } else if (lockIconType == LOCK_ICON_MIXED) {
3084 mTitleBar.setLock(d);
3085 mFakeTitleBar.setLock(d);
3089 * Displays a page-info dialog.
3090 * @param tab The tab to show info about
3091 * @param fromShowSSLCertificateOnError The flag that indicates whether
3092 * this dialog was opened from the SSL-certificate-on-error dialog or
3093 * not. This is important, since we need to know whether to return to
3094 * the parent dialog or simply dismiss.
3096 private void showPageInfo(final Tab tab,
3097 final boolean fromShowSSLCertificateOnError) {
3098 final LayoutInflater factory = LayoutInflater
3101 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3103 final WebView view = tab.getWebView();
3106 String title = null;
3110 title = tab.getTitle();
3111 } else if (view == mTabControl.getCurrentWebView()) {
3112 // Use the cached title and url if this is the current WebView
3116 url = view.getUrl();
3117 title = view.getTitle();
3123 if (title == null) {
3127 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3128 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3130 mPageInfoView = tab;
3131 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3133 AlertDialog.Builder alertDialogBuilder =
3134 new AlertDialog.Builder(this)
3135 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3136 .setView(pageInfoView)
3139 new DialogInterface.OnClickListener() {
3140 public void onClick(DialogInterface dialog,
3142 mPageInfoDialog = null;
3143 mPageInfoView = null;
3145 // if we came here from the SSL error dialog
3146 if (fromShowSSLCertificateOnError) {
3147 // go back to the SSL error dialog
3148 showSSLCertificateOnError(
3149 mSSLCertificateOnErrorView,
3150 mSSLCertificateOnErrorHandler,
3151 mSSLCertificateOnErrorError);
3155 .setOnCancelListener(
3156 new DialogInterface.OnCancelListener() {
3157 public void onCancel(DialogInterface dialog) {
3158 mPageInfoDialog = null;
3159 mPageInfoView = null;
3161 // if we came here from the SSL error dialog
3162 if (fromShowSSLCertificateOnError) {
3163 // go back to the SSL error dialog
3164 showSSLCertificateOnError(
3165 mSSLCertificateOnErrorView,
3166 mSSLCertificateOnErrorHandler,
3167 mSSLCertificateOnErrorError);
3172 // if we have a main top-level page SSL certificate set or a certificate
3174 if (fromShowSSLCertificateOnError ||
3175 (view != null && view.getCertificate() != null)) {
3176 // add a 'View Certificate' button
3177 alertDialogBuilder.setNeutralButton(
3178 R.string.view_certificate,
3179 new DialogInterface.OnClickListener() {
3180 public void onClick(DialogInterface dialog,
3182 mPageInfoDialog = null;
3183 mPageInfoView = null;
3185 // if we came here from the SSL error dialog
3186 if (fromShowSSLCertificateOnError) {
3187 // go back to the SSL error dialog
3188 showSSLCertificateOnError(
3189 mSSLCertificateOnErrorView,
3190 mSSLCertificateOnErrorHandler,
3191 mSSLCertificateOnErrorError);
3193 // otherwise, display the top-most certificate from
3195 if (view.getCertificate() != null) {
3196 showSSLCertificate(tab);
3203 mPageInfoDialog = alertDialogBuilder.show();
3207 * Displays the main top-level page SSL certificate dialog
3208 * (accessible from the Page-Info dialog).
3209 * @param tab The tab to show certificate for.
3211 private void showSSLCertificate(final Tab tab) {
3212 final View certificateView =
3213 inflateCertificateView(tab.getWebView().getCertificate());
3214 if (certificateView == null) {
3218 LayoutInflater factory = LayoutInflater.from(this);
3220 final LinearLayout placeholder =
3221 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3223 LinearLayout ll = (LinearLayout) factory.inflate(
3224 R.layout.ssl_success, placeholder);
3225 ((TextView)ll.findViewById(R.id.success))
3226 .setText(R.string.ssl_certificate_is_valid);
3228 mSSLCertificateView = tab;
3229 mSSLCertificateDialog =
3230 new AlertDialog.Builder(this)
3231 .setTitle(R.string.ssl_certificate).setIcon(
3232 R.drawable.ic_dialog_browser_certificate_secure)
3233 .setView(certificateView)
3234 .setPositiveButton(R.string.ok,
3235 new DialogInterface.OnClickListener() {
3236 public void onClick(DialogInterface dialog,
3238 mSSLCertificateDialog = null;
3239 mSSLCertificateView = null;
3241 showPageInfo(tab, false);
3244 .setOnCancelListener(
3245 new DialogInterface.OnCancelListener() {
3246 public void onCancel(DialogInterface dialog) {
3247 mSSLCertificateDialog = null;
3248 mSSLCertificateView = null;
3250 showPageInfo(tab, false);
3257 * Displays the SSL error certificate dialog.
3258 * @param view The target web-view.
3259 * @param handler The SSL error handler responsible for cancelling the
3260 * connection that resulted in an SSL error or proceeding per user request.
3261 * @param error The SSL error object.
3263 void showSSLCertificateOnError(
3264 final WebView view, final SslErrorHandler handler, final SslError error) {
3266 final View certificateView =
3267 inflateCertificateView(error.getCertificate());
3268 if (certificateView == null) {
3272 LayoutInflater factory = LayoutInflater.from(this);
3274 final LinearLayout placeholder =
3275 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3277 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3278 LinearLayout ll = (LinearLayout)factory
3279 .inflate(R.layout.ssl_warning, placeholder);
3280 ((TextView)ll.findViewById(R.id.warning))
3281 .setText(R.string.ssl_untrusted);
3284 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3285 LinearLayout ll = (LinearLayout)factory
3286 .inflate(R.layout.ssl_warning, placeholder);
3287 ((TextView)ll.findViewById(R.id.warning))
3288 .setText(R.string.ssl_mismatch);
3291 if (error.hasError(SslError.SSL_EXPIRED)) {
3292 LinearLayout ll = (LinearLayout)factory
3293 .inflate(R.layout.ssl_warning, placeholder);
3294 ((TextView)ll.findViewById(R.id.warning))
3295 .setText(R.string.ssl_expired);
3298 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3299 LinearLayout ll = (LinearLayout)factory
3300 .inflate(R.layout.ssl_warning, placeholder);
3301 ((TextView)ll.findViewById(R.id.warning))
3302 .setText(R.string.ssl_not_yet_valid);
3305 mSSLCertificateOnErrorHandler = handler;
3306 mSSLCertificateOnErrorView = view;
3307 mSSLCertificateOnErrorError = error;
3308 mSSLCertificateOnErrorDialog =
3309 new AlertDialog.Builder(this)
3310 .setTitle(R.string.ssl_certificate).setIcon(
3311 R.drawable.ic_dialog_browser_certificate_partially_secure)
3312 .setView(certificateView)
3313 .setPositiveButton(R.string.ok,
3314 new DialogInterface.OnClickListener() {
3315 public void onClick(DialogInterface dialog,
3317 mSSLCertificateOnErrorDialog = null;
3318 mSSLCertificateOnErrorView = null;
3319 mSSLCertificateOnErrorHandler = null;
3320 mSSLCertificateOnErrorError = null;
3322 view.getWebViewClient().onReceivedSslError(
3323 view, handler, error);
3326 .setNeutralButton(R.string.page_info_view,
3327 new DialogInterface.OnClickListener() {
3328 public void onClick(DialogInterface dialog,
3330 mSSLCertificateOnErrorDialog = null;
3332 // do not clear the dialog state: we will
3333 // need to show the dialog again once the
3334 // user is done exploring the page-info details
3336 showPageInfo(mTabControl.getTabFromView(view),
3340 .setOnCancelListener(
3341 new DialogInterface.OnCancelListener() {
3342 public void onCancel(DialogInterface dialog) {
3343 mSSLCertificateOnErrorDialog = null;
3344 mSSLCertificateOnErrorView = null;
3345 mSSLCertificateOnErrorHandler = null;
3346 mSSLCertificateOnErrorError = null;
3348 view.getWebViewClient().onReceivedSslError(
3349 view, handler, error);
3356 * Inflates the SSL certificate view (helper method).
3357 * @param certificate The SSL certificate.
3358 * @return The resultant certificate view with issued-to, issued-by,
3359 * issued-on, expires-on, and possibly other fields set.
3360 * If the input certificate is null, returns null.
3362 private View inflateCertificateView(SslCertificate certificate) {
3363 if (certificate == null) {
3367 LayoutInflater factory = LayoutInflater.from(this);
3369 View certificateView = factory.inflate(
3370 R.layout.ssl_certificate, null);
3373 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3374 if (issuedTo != null) {
3375 ((TextView) certificateView.findViewById(R.id.to_common))
3376 .setText(issuedTo.getCName());
3377 ((TextView) certificateView.findViewById(R.id.to_org))
3378 .setText(issuedTo.getOName());
3379 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3380 .setText(issuedTo.getUName());
3384 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3385 if (issuedBy != null) {
3386 ((TextView) certificateView.findViewById(R.id.by_common))
3387 .setText(issuedBy.getCName());
3388 ((TextView) certificateView.findViewById(R.id.by_org))
3389 .setText(issuedBy.getOName());
3390 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3391 .setText(issuedBy.getUName());
3395 String issuedOn = reformatCertificateDate(
3396 certificate.getValidNotBefore());
3397 ((TextView) certificateView.findViewById(R.id.issued_on))
3401 String expiresOn = reformatCertificateDate(
3402 certificate.getValidNotAfter());
3403 ((TextView) certificateView.findViewById(R.id.expires_on))
3404 .setText(expiresOn);
3406 return certificateView;
3410 * Re-formats the certificate date (Date.toString()) string to
3411 * a properly localized date string.
3412 * @return Properly localized version of the certificate date string and
3413 * the original certificate date string if fails to localize.
3414 * If the original string is null, returns an empty string "".
3416 private String reformatCertificateDate(String certificateDate) {
3417 String reformattedDate = null;
3419 if (certificateDate != null) {
3422 date = java.text.DateFormat.getInstance().parse(certificateDate);
3423 } catch (ParseException e) {
3429 DateFormat.getDateFormat(this).format(date);
3433 return reformattedDate != null ? reformattedDate :
3434 (certificateDate != null ? certificateDate : "");
3438 * Displays an http-authentication dialog.
3440 void showHttpAuthentication(final HttpAuthHandler handler,
3441 final String host, final String realm, final String title,
3442 final String name, final String password, int focusId) {
3443 LayoutInflater factory = LayoutInflater.from(this);
3444 final View v = factory
3445 .inflate(R.layout.http_authentication, null);
3447 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3449 if (password != null) {
3450 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3453 String titleText = title;
3454 if (titleText == null) {
3455 titleText = getText(R.string.sign_in_to).toString().replace(
3456 "%s1", host).replace("%s2", realm);
3459 mHttpAuthHandler = handler;
3460 AlertDialog dialog = new AlertDialog.Builder(this)
3461 .setTitle(titleText)
3462 .setIcon(android.R.drawable.ic_dialog_alert)
3464 .setPositiveButton(R.string.action,
3465 new DialogInterface.OnClickListener() {
3466 public void onClick(DialogInterface dialog,
3468 String nm = ((EditText) v
3469 .findViewById(R.id.username_edit))
3470 .getText().toString();
3471 String pw = ((EditText) v
3472 .findViewById(R.id.password_edit))
3473 .getText().toString();
3474 BrowserActivity.this.setHttpAuthUsernamePassword
3475 (host, realm, nm, pw);
3476 handler.proceed(nm, pw);
3477 mHttpAuthenticationDialog = null;
3478 mHttpAuthHandler = null;
3480 .setNegativeButton(R.string.cancel,
3481 new DialogInterface.OnClickListener() {
3482 public void onClick(DialogInterface dialog,
3485 BrowserActivity.this.resetTitleAndRevertLockIcon();
3486 mHttpAuthenticationDialog = null;
3487 mHttpAuthHandler = null;
3489 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3490 public void onCancel(DialogInterface dialog) {
3492 BrowserActivity.this.resetTitleAndRevertLockIcon();
3493 mHttpAuthenticationDialog = null;
3494 mHttpAuthHandler = null;
3497 // Make the IME appear when the dialog is displayed if applicable.
3498 dialog.getWindow().setSoftInputMode(
3499 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3502 dialog.findViewById(focusId).requestFocus();
3504 v.findViewById(R.id.username_edit).requestFocus();
3506 mHttpAuthenticationDialog = dialog;
3509 public int getProgress() {
3510 WebView w = mTabControl.getCurrentWebView();
3512 return w.getProgress();
3519 * Set HTTP authentication password.
3521 * @param host The host for the password
3522 * @param realm The realm for the password
3523 * @param username The username for the password. If it is null, it means
3524 * password can't be saved.
3525 * @param password The password
3527 public void setHttpAuthUsernamePassword(String host, String realm,
3530 WebView w = mTabControl.getCurrentWebView();
3532 w.setHttpAuthUsernamePassword(host, realm, username, password);
3537 * connectivity manager says net has come or gone... inform the user
3538 * @param up true if net has come up, false if net has gone down
3540 public void onNetworkToggle(boolean up) {
3541 if (up == mIsNetworkUp) {
3544 mIsNetworkUp = true;
3545 if (mAlertDialog != null) {
3546 mAlertDialog.cancel();
3547 mAlertDialog = null;
3550 mIsNetworkUp = false;
3552 createAndShowNetworkDialog();
3555 WebView w = mTabControl.getCurrentWebView();
3557 w.setNetworkAvailable(up);
3561 boolean isNetworkUp() {
3562 return mIsNetworkUp;
3565 // This method shows the network dialog alerting the user that the net is
3566 // down. It will only show the dialog if mAlertDialog is null.
3567 private void createAndShowNetworkDialog() {
3568 if (mAlertDialog == null) {
3569 mAlertDialog = new AlertDialog.Builder(this)
3570 .setTitle(R.string.loadSuspendedTitle)
3571 .setMessage(R.string.loadSuspended)
3572 .setPositiveButton(R.string.ok, null)
3578 protected void onActivityResult(int requestCode, int resultCode,
3580 if (getTopWindow() == null) return;
3582 switch (requestCode) {
3584 if (resultCode == RESULT_OK && intent != null) {
3585 String data = intent.getAction();
3586 Bundle extras = intent.getExtras();
3587 if (extras != null && extras.getBoolean("new_window", false)) {
3590 final Tab currentTab =
3591 mTabControl.getCurrentTab();
3592 dismissSubWindow(currentTab);
3593 if (data != null && data.length() != 0) {
3594 getTopWindow().loadUrl(data);
3598 // Deliberately fall through to PREFERENCES_PAGE, since the
3599 // same extra may be attached to the COMBO_PAGE
3600 case PREFERENCES_PAGE:
3601 if (resultCode == RESULT_OK && intent != null) {
3602 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3603 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3604 mTabControl.removeParentChildRelationShips();
3608 // Choose a file from the file picker.
3610 if (null == mUploadMessage) break;
3611 Uri result = intent == null || resultCode != RESULT_OK ? null
3613 mUploadMessage.onReceiveValue(result);
3614 mUploadMessage = null;
3619 getTopWindow().requestFocus();
3623 * This method is called as a result of the user selecting the options
3624 * menu to see the download window. It shows the download window on top of
3625 * the current window.
3627 private void viewDownloads(Uri downloadRecord) {
3628 Intent intent = new Intent(this,
3629 BrowserDownloadPage.class);
3630 intent.setData(downloadRecord);
3631 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3637 * @param startWithHistory If true, open starting on the history tab.
3638 * Otherwise, start with the bookmarks tab.
3640 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3641 WebView current = mTabControl.getCurrentWebView();
3642 if (current == null) {
3645 Intent intent = new Intent(this,
3646 CombinedBookmarkHistoryActivity.class);
3647 String title = current.getTitle();
3648 String url = current.getUrl();
3649 Bitmap thumbnail = createScreenshot(current);
3651 // Just in case the user opens bookmarks before a page finishes loading
3652 // so the current history item, and therefore the page, is null.
3654 url = mLastEnteredUrl;
3657 url = mSettings.getHomePage();
3660 // In case the web page has not yet received its associated title.
3661 if (title == null) {
3664 intent.putExtra("title", title);
3665 intent.putExtra("url", url);
3666 intent.putExtra("thumbnail", thumbnail);
3667 // Disable opening in a new window if we have maxed out the windows
3668 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3669 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3670 if (startWithHistory) {
3671 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3672 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3674 startActivityForResult(intent, COMBO_PAGE);
3677 // Called when loading from context menu or LOAD_URL message
3678 private void loadURL(WebView view, String url) {
3679 // In case the user enters nothing.
3680 if (url != null && url.length() != 0 && view != null) {
3681 url = smartUrlFilter(url);
3682 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3688 private String smartUrlFilter(Uri inUri) {
3689 if (inUri != null) {
3690 return smartUrlFilter(inUri.toString());
3695 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3696 "(?i)" + // switch on case insensitive matching
3697 "(" + // begin group for schema
3698 "(?:http|https|file):\\/\\/" +
3699 "|(?:inline|data|about|content|javascript):" +
3704 * Attempts to determine whether user input is a URL or search
3705 * terms. Anything with a space is passed to search.
3707 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3708 * "Http://" converts to "http://"
3710 * @return Original or modified URL
3713 String smartUrlFilter(String url) {
3715 String inUrl = url.trim();
3716 boolean hasSpace = inUrl.indexOf(' ') != -1;
3718 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3719 if (matcher.matches()) {
3720 // force scheme to lowercase
3721 String scheme = matcher.group(1);
3722 String lcScheme = scheme.toLowerCase();
3723 if (!lcScheme.equals(scheme)) {
3724 inUrl = lcScheme + matcher.group(2);
3727 inUrl = inUrl.replace(" ", "%20");
3732 // FIXME: Is this the correct place to add to searches?
3733 // what if someone else calls this function?
3734 int shortcut = parseUrlShortcut(inUrl);
3735 if (shortcut != SHORTCUT_INVALID) {
3736 Browser.addSearchUrl(mResolver, inUrl);
3737 String query = inUrl.substring(2);
3739 case SHORTCUT_GOOGLE_SEARCH:
3740 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3741 case SHORTCUT_WIKIPEDIA_SEARCH:
3742 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3743 case SHORTCUT_DICTIONARY_SEARCH:
3744 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3745 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3746 // FIXME: we need location in this case
3747 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3751 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3752 return URLUtil.guessUrl(inUrl);
3756 Browser.addSearchUrl(mResolver, inUrl);
3757 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3760 /* package */ void setShouldShowErrorConsole(boolean flag) {
3761 if (flag == mShouldShowErrorConsole) {
3766 mShouldShowErrorConsole = flag;
3768 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3769 .getErrorConsole(true);
3772 // Setting the show state of the console will cause it's the layout to be inflated.
3773 if (errorConsole.numberOfErrors() > 0) {
3774 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3776 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3779 // Now we can add it to the main view.
3780 mErrorConsoleContainer.addView(errorConsole,
3781 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3782 ViewGroup.LayoutParams.WRAP_CONTENT));
3784 mErrorConsoleContainer.removeView(errorConsole);
3789 boolean shouldShowErrorConsole() {
3790 return mShouldShowErrorConsole;
3793 private void setStatusBarVisibility(boolean visible) {
3794 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3795 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3799 private void sendNetworkType(String type, String subtype) {
3800 WebView w = mTabControl.getCurrentWebView();
3802 w.setNetworkType(type, subtype);
3806 final static int LOCK_ICON_UNSECURE = 0;
3807 final static int LOCK_ICON_SECURE = 1;
3808 final static int LOCK_ICON_MIXED = 2;
3810 private BrowserSettings mSettings;
3811 private TabControl mTabControl;
3812 private ContentResolver mResolver;
3813 private FrameLayout mContentView;
3814 private View mCustomView;
3815 private FrameLayout mCustomViewContainer;
3816 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3818 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3819 // view, we should rewrite this.
3820 private int mCurrentMenuState = 0;
3821 private int mMenuState = R.id.MAIN_MENU;
3822 private int mOldMenuState = EMPTY_MENU;
3823 private static final int EMPTY_MENU = -1;
3826 private FindDialog mFindDialog;
3827 // Used to prevent chording to result in firing two shortcuts immediately
3828 // one after another. Fixes bug 1211714.
3831 private boolean mInLoad;
3832 private boolean mIsNetworkUp;
3833 private boolean mDidStopLoad;
3835 private boolean mActivityInPause = true;
3837 private boolean mMenuIsDown;
3839 private static boolean mInTrace;
3841 // Performance probe
3842 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3843 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3844 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3845 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3846 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3847 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3848 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3849 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3850 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3853 private long mStart;
3854 private long mProcessStart;
3855 private long mUserStart;
3856 private long mSystemStart;
3857 private long mIdleStart;
3858 private long mIrqStart;
3860 private long mUiStart;
3862 private Drawable mMixLockIcon;
3863 private Drawable mSecLockIcon;
3865 /* hold a ref so we can auto-cancel if necessary */
3866 private AlertDialog mAlertDialog;
3868 // Wait for credentials before loading google.com
3869 private ProgressDialog mCredsDlg;
3871 // The up-to-date URL and title (these can be different from those stored
3872 // in WebView, since it takes some time for the information in WebView to
3874 private String mUrl;
3875 private String mTitle;
3877 // As PageInfo has different style for landscape / portrait, we have
3878 // to re-open it when configuration changed
3879 private AlertDialog mPageInfoDialog;
3880 private Tab mPageInfoView;
3881 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3882 // dialog, we should not just dismiss it, but should get back to the
3883 // SSL-certificate-on-error dialog. This flag is used to store this state
3884 private boolean mPageInfoFromShowSSLCertificateOnError;
3886 // as SSLCertificateOnError has different style for landscape / portrait,
3887 // we have to re-open it when configuration changed
3888 private AlertDialog mSSLCertificateOnErrorDialog;
3889 private WebView mSSLCertificateOnErrorView;
3890 private SslErrorHandler mSSLCertificateOnErrorHandler;
3891 private SslError mSSLCertificateOnErrorError;
3893 // as SSLCertificate has different style for landscape / portrait, we
3894 // have to re-open it when configuration changed
3895 private AlertDialog mSSLCertificateDialog;
3896 private Tab mSSLCertificateView;
3898 // as HttpAuthentication has different style for landscape / portrait, we
3899 // have to re-open it when configuration changed
3900 private AlertDialog mHttpAuthenticationDialog;
3901 private HttpAuthHandler mHttpAuthHandler;
3903 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3904 new FrameLayout.LayoutParams(
3905 ViewGroup.LayoutParams.MATCH_PARENT,
3906 ViewGroup.LayoutParams.MATCH_PARENT);
3907 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3908 new FrameLayout.LayoutParams(
3909 ViewGroup.LayoutParams.MATCH_PARENT,
3910 ViewGroup.LayoutParams.MATCH_PARENT,
3913 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3915 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3916 // Dictionary search
3917 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3918 // Google Mobile Local search
3919 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3921 final static String QUERY_PLACE_HOLDER = "%s";
3923 // "source" parameter for Google search through search key
3924 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3925 // "source" parameter for Google search through goto menu
3926 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3927 // "source" parameter for Google search through simplily type
3928 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3929 // "source" parameter for Google search suggested by the browser
3930 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3931 // "source" parameter for Google search from unknown source
3932 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3934 private final static String LOGTAG = "browser";
3936 private String mLastEnteredUrl;
3938 private PowerManager.WakeLock mWakeLock;
3939 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3941 private Toast mStopToast;
3943 private TitleBar mTitleBar;
3945 private LinearLayout mErrorConsoleContainer = null;
3946 private boolean mShouldShowErrorConsole = false;
3948 // As the ids are dynamically created, we can't guarantee that they will
3949 // be in sequence, so this static array maps ids to a window number.
3950 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3951 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3952 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3953 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3955 // monitor platform changes
3956 private IntentFilter mNetworkStateChangedFilter;
3957 private BroadcastReceiver mNetworkStateIntentReceiver;
3959 private BroadcastReceiver mPackageInstallationReceiver;
3961 // activity requestCode
3962 final static int COMBO_PAGE = 1;
3963 final static int DOWNLOAD_PAGE = 2;
3964 final static int PREFERENCES_PAGE = 3;
3965 final static int FILE_SELECTED = 4;
3967 // the default <video> poster
3968 private Bitmap mDefaultVideoPoster;
3969 // the video progress view
3970 private View mVideoProgressView;
3973 * A UrlData class to abstract how the content will be set to WebView.
3974 * This base class uses loadUrl to show the content.
3976 private static class UrlData {
3978 final Map<String, String> mHeaders;
3979 final Intent mVoiceIntent;
3981 UrlData(String url) {
3983 this.mHeaders = null;
3984 this.mVoiceIntent = null;
3987 UrlData(String url, Map<String, String> headers, Intent intent) {
3989 this.mHeaders = headers;
3990 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3991 .equals(intent.getAction())) {
3992 this.mVoiceIntent = intent;
3994 this.mVoiceIntent = null;
3999 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
4002 public void loadIn(Tab t) {
4003 if (mVoiceIntent != null) {
4004 t.activateVoiceSearchMode(mVoiceIntent);
4006 t.getWebView().loadUrl(mUrl, mHeaders);
4011 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);