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.ContentResolver;
27 import android.content.ContentUris;
28 import android.content.ContentValues;
29 import android.content.Context;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.pm.PackageInfo;
34 import android.content.pm.PackageManager;
35 import android.content.pm.ResolveInfo;
36 import android.content.res.Configuration;
37 import android.content.res.Resources;
38 import android.database.Cursor;
39 import android.database.DatabaseUtils;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Canvas;
43 import android.graphics.Picture;
44 import android.graphics.PixelFormat;
45 import android.graphics.Rect;
46 import android.graphics.drawable.Drawable;
47 import android.net.ConnectivityManager;
48 import android.net.NetworkInfo;
49 import android.net.Uri;
50 import android.net.WebAddress;
51 import android.net.http.SslCertificate;
52 import android.net.http.SslError;
53 import android.os.AsyncTask;
54 import android.os.Bundle;
55 import android.os.Debug;
56 import android.os.Environment;
57 import android.os.Handler;
58 import android.os.Message;
59 import android.os.PowerManager;
60 import android.os.Process;
61 import android.os.ServiceManager;
62 import android.os.SystemClock;
63 import android.provider.Browser;
64 import android.provider.ContactsContract;
65 import android.provider.ContactsContract.Intents.Insert;
66 import android.provider.Downloads;
67 import android.provider.MediaStore;
68 import android.text.IClipboard;
69 import android.text.TextUtils;
70 import android.text.format.DateFormat;
71 import android.util.AttributeSet;
72 import android.util.Log;
73 import android.view.ContextMenu;
74 import android.view.Gravity;
75 import android.view.KeyEvent;
76 import android.view.LayoutInflater;
77 import android.view.Menu;
78 import android.view.MenuInflater;
79 import android.view.MenuItem;
80 import android.view.View;
81 import android.view.ViewGroup;
82 import android.view.Window;
83 import android.view.WindowManager;
84 import android.view.ContextMenu.ContextMenuInfo;
85 import android.view.MenuItem.OnMenuItemClickListener;
86 import android.webkit.CookieManager;
87 import android.webkit.CookieSyncManager;
88 import android.webkit.DownloadListener;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.PluginManager;
91 import android.webkit.SslErrorHandler;
92 import android.webkit.URLUtil;
93 import android.webkit.ValueCallback;
94 import android.webkit.WebChromeClient;
95 import android.webkit.WebHistoryItem;
96 import android.webkit.WebIconDatabase;
97 import android.webkit.WebView;
98 import android.widget.EditText;
99 import android.widget.FrameLayout;
100 import android.widget.LinearLayout;
101 import android.widget.TextView;
102 import android.widget.Toast;
103 import android.accounts.Account;
104 import android.accounts.AccountManager;
105 import android.accounts.AccountManagerFuture;
106 import android.accounts.AuthenticatorException;
107 import android.accounts.OperationCanceledException;
108 import android.accounts.AccountManagerCallback;
110 import com.android.common.Patterns;
112 import com.google.android.gsf.GoogleLoginServiceConstants;
114 import java.io.ByteArrayOutputStream;
116 import java.io.IOException;
117 import java.io.InputStream;
118 import java.net.MalformedURLException;
120 import java.net.URISyntaxException;
122 import java.net.URLEncoder;
123 import java.text.ParseException;
124 import java.util.Date;
125 import java.util.HashMap;
126 import java.util.regex.Matcher;
127 import java.util.regex.Pattern;
129 public class BrowserActivity extends Activity
130 implements View.OnCreateContextMenuListener, DownloadListener,
131 AccountManagerCallback<Account[]> {
133 /* Define some aliases to make these debugging flags easier to refer to.
134 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
136 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
137 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
138 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
140 // These are single-character shortcuts for searching popular sources.
141 private static final int SHORTCUT_INVALID = 0;
142 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
143 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
144 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
145 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
147 private Account[] mAccountsGoogle;
148 private Account[] mAccountsPreferHosted;
150 private void startReadOfGoogleAccounts() {
151 mAccountsGoogle = null;
152 mAccountsPreferHosted = null;
154 AccountManager.get(this).getAccountsByTypeAndFeatures(
155 GoogleLoginServiceConstants.ACCOUNT_TYPE,
156 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
160 /** This implements AccountManagerCallback<Account[]> */
161 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
163 if (mAccountsGoogle == null) {
164 mAccountsGoogle = accountManagerFuture.getResult();
166 AccountManager.get(this).getAccountsByTypeAndFeatures(
167 GoogleLoginServiceConstants.ACCOUNT_TYPE,
168 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
171 mAccountsPreferHosted = accountManagerFuture.getResult();
174 } catch (OperationCanceledException e) {
176 } catch (IOException e) {
178 } catch (AuthenticatorException e) {
183 private void setupHomePage() {
184 // get the default home page
185 String homepage = mSettings.getHomePage();
187 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
190 // hostedUser == googleUser
191 // The device has only a google account
193 // hostedUser != googleUser
194 // The device has a hosted account and a google account
196 // hostedUser != null, googleUser == null
197 // The device has only a hosted account (so far)
198 String hostedUser = mAccountsPreferHosted.length == 0
200 : mAccountsPreferHosted[0].name;
201 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
203 // developers might have no accounts at all
204 if (hostedUser == null) return;
206 if (googleUser == null || !hostedUser.equals(googleUser)) {
207 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
208 homepage = homepage.replace("?", "/a/" + domain + "?");
212 mSettings.setHomePage(BrowserActivity.this, homepage);
213 resumeAfterCredentials();
216 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
218 public Void doInBackground(File... files) {
220 for (File f : files) {
222 Log.e(LOGTAG, f.getPath() + " was not deleted");
231 * This layout holds everything you see below the status bar, including the
232 * error console, the custom view container, and the webviews.
234 private FrameLayout mBrowserFrameLayout;
237 public void onCreate(Bundle icicle) {
239 Log.v(LOGTAG, this + " onStart");
241 super.onCreate(icicle);
242 // test the browser in OpenGL
243 // requestWindowFeature(Window.FEATURE_OPENGL);
245 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
247 mResolver = getContentResolver();
249 // If this was a web search request, pass it on to the default web
250 // search provider and finish this activity.
251 if (handleWebSearchIntent(getIntent())) {
256 mSecLockIcon = Resources.getSystem().getDrawable(
257 android.R.drawable.ic_secure);
258 mMixLockIcon = Resources.getSystem().getDrawable(
259 android.R.drawable.ic_partial_secure);
261 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
262 .findViewById(com.android.internal.R.id.content);
263 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
264 .inflate(R.layout.custom_screen, null);
265 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
267 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
268 .findViewById(R.id.error_console);
269 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
270 .findViewById(R.id.fullscreen_custom_content);
271 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
272 mTitleBar = new TitleBar(this);
273 mFakeTitleBar = new TitleBar(this);
275 // Create the tab control and our initial tab
276 mTabControl = new TabControl(this);
278 // Open the icon database and retain all the bookmark urls for favicons
279 retainIconsOnStartup();
281 // Keep a settings instance handy.
282 mSettings = BrowserSettings.getInstance();
283 mSettings.setTabControl(mTabControl);
284 mSettings.loadFromDb(this);
286 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
287 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
289 /* enables registration for changes in network status from
291 mNetworkStateChangedFilter = new IntentFilter();
292 mNetworkStateChangedFilter.addAction(
293 ConnectivityManager.CONNECTIVITY_ACTION);
294 mNetworkStateIntentReceiver = new BroadcastReceiver() {
296 public void onReceive(Context context, Intent intent) {
297 if (intent.getAction().equals(
298 ConnectivityManager.CONNECTIVITY_ACTION)) {
299 boolean noConnectivity = intent.getBooleanExtra(
300 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
301 if (!noConnectivity) {
302 NetworkInfo info = intent.getParcelableExtra(
303 ConnectivityManager.EXTRA_NETWORK_INFO);
304 String typeName = info.getTypeName();
305 String subtypeName = info.getSubtypeName();
306 sendNetworkType(typeName.toLowerCase(),
307 (subtypeName != null ? subtypeName.toLowerCase() : ""));
309 onNetworkToggle(!noConnectivity);
314 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
315 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
316 filter.addDataScheme("package");
317 mPackageInstallationReceiver = new BroadcastReceiver() {
319 public void onReceive(Context context, Intent intent) {
320 final String action = intent.getAction();
321 final String packageName = intent.getData()
322 .getSchemeSpecificPart();
323 final boolean replacing = intent.getBooleanExtra(
324 Intent.EXTRA_REPLACING, false);
325 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
326 // if it is replacing, refreshPlugins() when adding
329 PackageManager pm = BrowserActivity.this.getPackageManager();
330 PackageInfo pkgInfo = null;
332 pkgInfo = pm.getPackageInfo(packageName,
333 PackageManager.GET_PERMISSIONS);
334 } catch (PackageManager.NameNotFoundException e) {
337 if (pkgInfo != null) {
338 String permissions[] = pkgInfo.requestedPermissions;
339 if (permissions == null) {
342 boolean permissionOk = false;
343 for (String permit : permissions) {
344 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
350 PluginManager.getInstance(BrowserActivity.this)
352 Intent.ACTION_PACKAGE_ADDED
358 registerReceiver(mPackageInstallationReceiver, filter);
360 if (!mTabControl.restoreState(icicle)) {
361 // clear up the thumbnail directory if we can't restore the state as
362 // none of the files in the directory are referenced any more.
363 new ClearThumbnails().execute(
364 mTabControl.getThumbnailDir().listFiles());
365 // there is no quit on Android. But if we can't restore the state,
366 // we can treat it as a new Browser, remove the old session cookies.
367 CookieManager.getInstance().removeSessionCookie();
368 final Intent intent = getIntent();
369 final Bundle extra = intent.getExtras();
370 // Create an initial tab.
371 // If the intent is ACTION_VIEW and data is not null, the Browser is
372 // invoked to view the content by another application. In this case,
373 // the tab will be close when exit.
374 UrlData urlData = getUrlDataFromIntent(intent);
376 final Tab t = mTabControl.createNewTab(
377 Intent.ACTION_VIEW.equals(intent.getAction()) &&
378 intent.getData() != null,
379 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
380 mTabControl.setCurrentTab(t);
381 attachTabToContentView(t);
382 WebView webView = t.getWebView();
384 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
385 if (scale > 0 && scale <= 1000) {
386 webView.setInitialScale(scale);
389 // If we are not restoring from an icicle, then there is a high
390 // likely hood this is the first run. So, check to see if the
391 // homepage needs to be configured and copy any plugins from our
392 // asset directory to the data partition.
393 if ((extra == null || !extra.getBoolean("testing"))
394 && !mSettings.isLoginInitialized()) {
395 startReadOfGoogleAccounts();
398 if (urlData.isEmpty()) {
399 if (mSettings.isLoginInitialized()) {
400 webView.loadUrl(mSettings.getHomePage());
402 waitForCredentials();
406 urlData.setPostData(extra
407 .getByteArray(Browser.EXTRA_POST_DATA));
409 urlData.loadIn(webView);
412 // TabControl.restoreState() will create a new tab even if
413 // restoring the state fails.
414 attachTabToContentView(mTabControl.getCurrentTab());
417 // Read JavaScript flags if it exists.
418 String jsFlags = mSettings.getJsFlags();
419 if (jsFlags.trim().length() != 0) {
420 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
425 protected void onNewIntent(Intent intent) {
426 Tab current = mTabControl.getCurrentTab();
427 // When a tab is closed on exit, the current tab index is set to -1.
428 // Reset before proceed as Browser requires the current tab to be set.
429 if (current == null) {
430 // Try to reset the tab in case the index was incorrect.
431 current = mTabControl.getTab(0);
432 if (current == null) {
433 // No tabs at all so just ignore this intent.
436 mTabControl.setCurrentTab(current);
437 attachTabToContentView(current);
438 resetTitleAndIcon(current.getWebView());
440 final String action = intent.getAction();
441 final int flags = intent.getFlags();
442 if (Intent.ACTION_MAIN.equals(action) ||
443 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
444 // just resume the browser
447 if (Intent.ACTION_VIEW.equals(action)
448 || Intent.ACTION_SEARCH.equals(action)
449 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
450 || Intent.ACTION_WEB_SEARCH.equals(action)) {
451 // If this was a search request (e.g. search query directly typed into the address bar),
452 // pass it on to the default web search provider.
453 if (handleWebSearchIntent(intent)) {
457 UrlData urlData = getUrlDataFromIntent(intent);
458 if (urlData.isEmpty()) {
459 urlData = new UrlData(mSettings.getHomePage());
461 urlData.setPostData(intent
462 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
464 final String appId = intent
465 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
466 if (Intent.ACTION_VIEW.equals(action)
467 && !getPackageName().equals(appId)
468 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
469 Tab appTab = mTabControl.getTabFromId(appId);
470 if (appTab != null) {
471 Log.i(LOGTAG, "Reusing tab for " + appId);
472 // Dismiss the subwindow if applicable.
473 dismissSubWindow(appTab);
474 // Since we might kill the WebView, remove it from the
475 // content view first.
476 removeTabFromContentView(appTab);
477 // Recreate the main WebView after destroying the old one.
478 // If the WebView has the same original url and is on that
479 // page, it can be reused.
481 mTabControl.recreateWebView(appTab, urlData.mUrl);
483 if (current != appTab) {
484 switchToTab(mTabControl.getTabIndex(appTab));
486 urlData.loadIn(appTab.getWebView());
489 // If the tab was the current tab, we have to attach
490 // it to the view system again.
491 attachTabToContentView(appTab);
493 urlData.loadIn(appTab.getWebView());
498 // No matching application tab, try to find a regular tab
499 // with a matching url.
500 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
501 if (appTab != null) {
502 if (current != appTab) {
503 switchToTab(mTabControl.getTabIndex(appTab));
505 // Otherwise, we are already viewing the correct tab.
507 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
508 // will be opened in a new tab unless we have reached
509 // MAX_TABS. Then the url will be opened in the current
510 // tab. If a new tab is created, it will have "true" for
512 openTabAndShow(urlData, true, appId);
516 if (!urlData.isEmpty()
517 && urlData.mUrl.startsWith("about:debug")) {
518 if ("about:debug.dom".equals(urlData.mUrl)) {
519 current.getWebView().dumpDomTree(false);
520 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
521 current.getWebView().dumpDomTree(true);
522 } else if ("about:debug.render".equals(urlData.mUrl)) {
523 current.getWebView().dumpRenderTree(false);
524 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
525 current.getWebView().dumpRenderTree(true);
526 } else if ("about:debug.display".equals(urlData.mUrl)) {
527 current.getWebView().dumpDisplayTree();
528 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
529 int index = urlData.mUrl.codePointAt(16) - '0';
530 if (index <= 0 || index > 9) {
531 current.getWebView().setDragTracker(null);
533 current.getWebView().setDragTracker(new MeshTracker(index));
536 mSettings.toggleDebugSettings();
540 // Get rid of the subwindow if it exists
541 dismissSubWindow(current);
542 urlData.loadIn(current.getWebView());
547 private int parseUrlShortcut(String url) {
548 if (url == null) return SHORTCUT_INVALID;
550 // FIXME: quick search, need to be customized by setting
551 if (url.length() > 2 && url.charAt(1) == ' ') {
552 switch (url.charAt(0)) {
553 case 'g': return SHORTCUT_GOOGLE_SEARCH;
554 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
555 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
556 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
559 return SHORTCUT_INVALID;
563 * Launches the default web search activity with the query parameters if the given intent's data
564 * are identified as plain search terms and not URLs/shortcuts.
565 * @return true if the intent was handled and web search activity was launched, false if not.
567 private boolean handleWebSearchIntent(Intent intent) {
568 if (intent == null) return false;
571 final String action = intent.getAction();
572 if (Intent.ACTION_VIEW.equals(action)) {
573 Uri data = intent.getData();
574 if (data != null) url = data.toString();
575 } else if (Intent.ACTION_SEARCH.equals(action)
576 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
577 || Intent.ACTION_WEB_SEARCH.equals(action)) {
578 url = intent.getStringExtra(SearchManager.QUERY);
580 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
581 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
585 * Launches the default web search activity with the query parameters if the given url string
586 * was identified as plain search terms and not URL/shortcut.
587 * @return true if the request was handled and web search activity was launched, false if not.
589 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
590 if (inUrl == null) return false;
592 // In general, we shouldn't modify URL from Intent.
593 // But currently, we get the user-typed URL from search box as well.
594 String url = fixUrl(inUrl).trim();
596 // URLs and site specific search shortcuts are handled by the regular flow of control, so
598 if (Patterns.WEB_URL.matcher(url).matches()
599 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
600 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
604 Browser.updateVisitedHistory(mResolver, url, false);
605 Browser.addSearchUrl(mResolver, url);
607 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
608 intent.addCategory(Intent.CATEGORY_DEFAULT);
609 intent.putExtra(SearchManager.QUERY, url);
610 if (appData != null) {
611 intent.putExtra(SearchManager.APP_DATA, appData);
613 if (extraData != null) {
614 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
616 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
617 startActivity(intent);
622 private UrlData getUrlDataFromIntent(Intent intent) {
624 if (intent != null) {
625 final String action = intent.getAction();
626 if (Intent.ACTION_VIEW.equals(action)) {
627 url = smartUrlFilter(intent.getData());
628 if (url != null && url.startsWith("content:")) {
629 /* Append mimetype so webview knows how to display */
630 String mimeType = intent.resolveType(getContentResolver());
631 if (mimeType != null) {
632 url += "?" + mimeType;
635 if ("inline:".equals(url)) {
636 return new InlinedUrlData(
637 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
639 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
640 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
642 } else if (Intent.ACTION_SEARCH.equals(action)
643 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
644 || Intent.ACTION_WEB_SEARCH.equals(action)) {
645 url = intent.getStringExtra(SearchManager.QUERY);
647 mLastEnteredUrl = url;
648 Browser.updateVisitedHistory(mResolver, url, 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.
652 url = smartUrlFilter(url);
653 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
654 if (url.contains(searchSource)) {
655 String source = null;
656 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
657 if (appData != null) {
658 source = appData.getString(SearchManager.SOURCE);
660 if (TextUtils.isEmpty(source)) {
661 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
663 url = url.replace(searchSource, "&source=android-"+source+"&");
668 return new UrlData(url);
671 /* package */ static String fixUrl(String inUrl) {
672 // FIXME: Converting the url to lower case
673 // duplicates functionality in smartUrlFilter().
674 // However, changing all current callers of fixUrl to
675 // call smartUrlFilter in addition may have unwanted
676 // consequences, and is deferred for now.
677 int colon = inUrl.indexOf(':');
678 boolean allLower = true;
679 for (int index = 0; index < colon; index++) {
680 char ch = inUrl.charAt(index);
681 if (!Character.isLetter(ch)) {
684 allLower &= Character.isLowerCase(ch);
685 if (index == colon - 1 && !allLower) {
686 inUrl = inUrl.substring(0, colon).toLowerCase()
687 + inUrl.substring(colon);
690 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
692 if (inUrl.startsWith("http:") ||
693 inUrl.startsWith("https:")) {
694 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
695 inUrl = inUrl.replaceFirst("/", "//");
696 } else inUrl = inUrl.replaceFirst(":", "://");
702 protected void onResume() {
705 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
708 if (!mActivityInPause) {
709 Log.e(LOGTAG, "BrowserActivity is already resumed.");
713 mTabControl.resumeCurrentTab();
714 mActivityInPause = false;
715 resumeWebViewTimers();
717 if (mWakeLock.isHeld()) {
718 mHandler.removeMessages(RELEASE_WAKELOCK);
722 if (mCredsDlg != null) {
723 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
724 // In case credential request never comes back
725 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
729 registerReceiver(mNetworkStateIntentReceiver,
730 mNetworkStateChangedFilter);
731 WebView.enablePlatformNotifications();
735 * Since the actual title bar is embedded in the WebView, and removing it
736 * would change its appearance, use a different TitleBar to show overlayed
737 * at the top of the screen, when the menu is open or the page is loading.
739 private TitleBar mFakeTitleBar;
742 * Holder for the fake title bar. It will have a foreground shadow, as well
743 * as a white background, so the fake title bar looks like the real one.
745 private ViewGroup mFakeTitleBarHolder;
748 * Layout parameters for the fake title bar within mFakeTitleBarHolder
750 private FrameLayout.LayoutParams mFakeTitleBarParams
751 = new FrameLayout.LayoutParams(
752 ViewGroup.LayoutParams.MATCH_PARENT,
753 ViewGroup.LayoutParams.WRAP_CONTENT);
755 * Keeps track of whether the options menu is open. This is important in
756 * determining whether to show or hide the title bar overlay.
758 private boolean mOptionsMenuOpen;
761 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
762 * of whether the configuration has changed. The first onMenuOpened call
763 * after a configuration change is simply a reopening of the same menu
764 * (i.e. mIconView did not change).
766 private boolean mConfigChanged;
769 * Whether or not the options menu is in its smaller, icon menu form. When
770 * true, we want the title bar overlay to be up. When false, we do not.
771 * Only meaningful if mOptionsMenuOpen is true.
773 private boolean mIconView;
776 public boolean onMenuOpened(int featureId, Menu menu) {
777 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
778 if (mOptionsMenuOpen) {
779 if (mConfigChanged) {
780 // We do not need to make any changes to the state of the
781 // title bar, since the only thing that happened was a
782 // change in orientation
783 mConfigChanged = false;
786 // Switching the menu to expanded view, so hide the
791 // Switching the menu back to icon view, so show the
792 // title bar once again.
798 // The options menu is closed, so open it, and show the title
800 mOptionsMenuOpen = true;
801 mConfigChanged = false;
809 * Special class used exclusively for the shadow drawn underneath the fake
810 * title bar. The shadow does not need to be drawn if the WebView
811 * underneath is scrolled to the top, because it will draw directly on top
812 * of the embedded shadow.
814 private static class Shadow extends View {
815 private WebView mWebView;
817 public Shadow(Context context, AttributeSet attrs) {
818 super(context, attrs);
821 public void setWebView(WebView view) {
826 public void draw(Canvas canvas) {
827 // In general onDraw is the method to override, but we care about
828 // whether or not the background gets drawn, which happens in draw()
829 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
832 // Need to invalidate so that if the scroll position changes, we
833 // still draw as appropriate.
838 private void showFakeTitleBar() {
839 final View decor = getWindow().peekDecorView();
840 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
841 && !mActivityInPause && decor != null
842 && decor.getWindowToken() != null) {
843 Rect visRect = new Rect();
844 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
846 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
851 WindowManager manager
852 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
854 // Add the title bar to the window manager so it can receive touches
855 // while the menu is up
856 WindowManager.LayoutParams params
857 = new WindowManager.LayoutParams(
858 ViewGroup.LayoutParams.MATCH_PARENT,
859 ViewGroup.LayoutParams.WRAP_CONTENT,
860 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
861 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
862 PixelFormat.TRANSLUCENT);
863 params.gravity = Gravity.TOP;
864 WebView mainView = mTabControl.getCurrentWebView();
865 boolean atTop = mainView != null && mainView.getScrollY() == 0;
866 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
867 // XXX : Without providing an offset, the fake title bar will be
868 // placed underneath the status bar. Use the global visible rect
869 // of mBrowserFrameLayout to determine the bottom of the status bar
870 params.y = visRect.top;
871 // Add a holder for the title bar. It also holds a shadow to show
872 // below the title bar.
873 if (mFakeTitleBarHolder == null) {
874 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
875 .inflate(R.layout.title_bar_bg, null);
877 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
879 shadow.setWebView(mainView);
880 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
881 manager.addView(mFakeTitleBarHolder, params);
886 public void onOptionsMenuClosed(Menu menu) {
887 mOptionsMenuOpen = false;
890 } else if (!mIconView) {
891 // The page is currently loading, and we are in expanded mode, so
892 // we were not showing the menu. Show it once again. It will be
893 // removed when the page finishes.
898 private void hideFakeTitleBar() {
899 if (mFakeTitleBar.getParent() == null) return;
900 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
901 mFakeTitleBarHolder.getLayoutParams();
902 WebView mainView = mTabControl.getCurrentWebView();
903 // Although we decided whether or not to animate based on the current
904 // scroll position, the scroll position may have changed since the
905 // fake title bar was displayed. Make sure it has the appropriate
906 // animation/lack thereof before removing.
907 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
908 ? 0 : R.style.TitleBar;
909 WindowManager manager
910 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
911 manager.updateViewLayout(mFakeTitleBarHolder, params);
912 mFakeTitleBarHolder.removeView(mFakeTitleBar);
913 manager.removeView(mFakeTitleBarHolder);
917 * Special method for the fake title bar to call when displaying its context
918 * menu, since it is in its own Window, and its parent does not show a
921 /* package */ void showTitleBarContextMenu() {
922 if (null == mTitleBar.getParent()) {
925 openContextMenu(mTitleBar);
929 public void onContextMenuClosed(Menu menu) {
930 super.onContextMenuClosed(menu);
937 * onSaveInstanceState(Bundle map)
938 * onSaveInstanceState is called right before onStop(). The map contains
942 protected void onSaveInstanceState(Bundle outState) {
944 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
946 // the default implementation requires each view to have an id. As the
947 // browser handles the state itself and it doesn't use id for the views,
948 // don't call the default implementation. Otherwise it will trigger the
949 // warning like this, "couldn't save which view has focus because the
950 // focused view XXX has no id".
953 mTabControl.saveState(outState);
957 protected void onPause() {
960 if (mActivityInPause) {
961 Log.e(LOGTAG, "BrowserActivity is already paused.");
965 mTabControl.pauseCurrentTab();
966 mActivityInPause = true;
967 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
969 mHandler.sendMessageDelayed(mHandler
970 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
973 // Clear the credentials toast if it is up
974 if (mCredsDlg != null && mCredsDlg.isShowing()) {
979 // FIXME: This removes the active tabs page and resets the menu to
980 // MAIN_MENU. A better solution might be to do this work in onNewIntent
981 // but then we would need to save it in onSaveInstanceState and restore
982 // it in onCreate/onRestoreInstanceState
983 if (mActiveTabsPage != null) {
984 removeActiveTabPage(true);
989 // unregister network state listener
990 unregisterReceiver(mNetworkStateIntentReceiver);
991 WebView.disablePlatformNotifications();
995 protected void onDestroy() {
997 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1001 if (mUploadMessage != null) {
1002 mUploadMessage.onReceiveValue(null);
1003 mUploadMessage = null;
1006 if (mTabControl == null) return;
1008 // Remove the fake title bar if it is there
1011 // Remove the current tab and sub window
1012 Tab t = mTabControl.getCurrentTab();
1014 dismissSubWindow(t);
1015 removeTabFromContentView(t);
1017 // Destroy all the tabs
1018 mTabControl.destroy();
1019 WebIconDatabase.getInstance().close();
1021 unregisterReceiver(mPackageInstallationReceiver);
1025 public void onConfigurationChanged(Configuration newConfig) {
1026 mConfigChanged = true;
1027 super.onConfigurationChanged(newConfig);
1029 if (mPageInfoDialog != null) {
1030 mPageInfoDialog.dismiss();
1033 mPageInfoFromShowSSLCertificateOnError);
1035 if (mSSLCertificateDialog != null) {
1036 mSSLCertificateDialog.dismiss();
1038 mSSLCertificateView);
1040 if (mSSLCertificateOnErrorDialog != null) {
1041 mSSLCertificateOnErrorDialog.dismiss();
1042 showSSLCertificateOnError(
1043 mSSLCertificateOnErrorView,
1044 mSSLCertificateOnErrorHandler,
1045 mSSLCertificateOnErrorError);
1047 if (mHttpAuthenticationDialog != null) {
1048 String title = ((TextView) mHttpAuthenticationDialog
1049 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1051 String name = ((TextView) mHttpAuthenticationDialog
1052 .findViewById(R.id.username_edit)).getText().toString();
1053 String password = ((TextView) mHttpAuthenticationDialog
1054 .findViewById(R.id.password_edit)).getText().toString();
1055 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1057 mHttpAuthenticationDialog.dismiss();
1058 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1059 name, password, focusId);
1064 public void onLowMemory() {
1065 super.onLowMemory();
1066 mTabControl.freeMemory();
1069 private boolean resumeWebViewTimers() {
1070 Tab tab = mTabControl.getCurrentTab();
1071 boolean inLoad = tab.inLoad();
1072 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1073 CookieSyncManager.getInstance().startSync();
1074 WebView w = tab.getWebView();
1084 private boolean pauseWebViewTimers() {
1085 Tab tab = mTabControl.getCurrentTab();
1086 boolean inLoad = tab.inLoad();
1087 if (mActivityInPause && !inLoad) {
1088 CookieSyncManager.getInstance().stopSync();
1089 WebView w = mTabControl.getCurrentWebView();
1099 // FIXME: Do we want to call this when loading google for the first time?
1101 * This function is called when we are launching for the first time. We
1102 * are waiting for the login credentials before loading Google home
1103 * pages. This way the user will be logged in straight away.
1105 private void waitForCredentials() {
1107 mCredsDlg = new ProgressDialog(this);
1108 mCredsDlg.setIndeterminate(true);
1109 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1110 // If the user cancels the operation, then cancel the Google
1111 // Credentials request.
1112 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1115 // We set a timeout for the retrieval of credentials in onResume()
1116 // as that is when we have freed up some CPU time to get
1117 // the login credentials.
1121 * If we have received the credentials or we have timed out and we are
1122 * showing the credentials dialog, then it is time to move on.
1124 private void resumeAfterCredentials() {
1125 if (mCredsDlg == null) {
1130 if (mCredsDlg.isShowing()) {
1131 mCredsDlg.dismiss();
1135 // Clear any pending timeout
1136 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1139 WebView w = mTabControl.getCurrentWebView();
1141 w.loadUrl(mSettings.getHomePage());
1144 // Update the settings, need to do this last as it can take a moment
1145 // to persist the settings. In the mean time we could be loading
1147 mSettings.setLoginInitialized(this);
1150 // Open the icon database and retain all the icons for visited sites.
1151 private void retainIconsOnStartup() {
1152 final WebIconDatabase db = WebIconDatabase.getInstance();
1153 db.open(getDir("icons", 0).getPath());
1155 Cursor c = Browser.getAllBookmarks(mResolver);
1156 if (!c.moveToFirst()) {
1160 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1162 String url = c.getString(urlIndex);
1163 db.retainIconForPageUrl(url);
1164 } while (c.moveToNext());
1166 } catch (IllegalStateException e) {
1167 Log.e(LOGTAG, "retainIconsOnStartup", e);
1171 // Helper method for getting the top window.
1172 WebView getTopWindow() {
1173 return mTabControl.getCurrentTopWebView();
1176 TabControl getTabControl() {
1181 public boolean onCreateOptionsMenu(Menu menu) {
1182 super.onCreateOptionsMenu(menu);
1184 MenuInflater inflater = getMenuInflater();
1185 inflater.inflate(R.menu.browser, menu);
1187 updateInLoadMenuItems();
1192 * As the menu can be open when loading state changes
1193 * we must manually update the state of the stop/reload menu
1196 private void updateInLoadMenuItems() {
1197 if (mMenu == null) {
1200 MenuItem src = mInLoad ?
1201 mMenu.findItem(R.id.stop_menu_id):
1202 mMenu.findItem(R.id.reload_menu_id);
1203 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1204 dest.setIcon(src.getIcon());
1205 dest.setTitle(src.getTitle());
1209 public boolean onContextItemSelected(MenuItem item) {
1210 // chording is not an issue with context menus, but we use the same
1211 // options selector, so set mCanChord to true so we can access them.
1213 int id = item.getItemId();
1214 boolean result = true;
1216 // For the context menu from the title bar
1217 case R.id.title_bar_copy_page_url:
1218 Tab currentTab = mTabControl.getCurrentTab();
1219 if (null == currentTab) {
1223 WebView mainView = currentTab.getWebView();
1224 if (null == mainView) {
1228 copy(mainView.getUrl());
1230 // -- Browser context menu
1231 case R.id.open_context_menu_id:
1232 case R.id.open_newtab_context_menu_id:
1233 case R.id.bookmark_context_menu_id:
1234 case R.id.save_link_context_menu_id:
1235 case R.id.share_link_context_menu_id:
1236 case R.id.copy_link_context_menu_id:
1237 final WebView webView = getTopWindow();
1238 if (null == webView) {
1242 final HashMap hrefMap = new HashMap();
1243 hrefMap.put("webview", webView);
1244 final Message msg = mHandler.obtainMessage(
1245 FOCUS_NODE_HREF, id, 0, hrefMap);
1246 webView.requestFocusNodeHref(msg);
1250 // For other context menus
1251 result = onOptionsItemSelected(item);
1257 private Bundle createGoogleSearchSourceBundle(String source) {
1258 Bundle bundle = new Bundle();
1259 bundle.putString(SearchManager.SOURCE, source);
1264 * Overriding this to insert a local information bundle
1267 public boolean onSearchRequested() {
1268 if (mOptionsMenuOpen) closeOptionsMenu();
1269 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1270 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1271 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1276 public void startSearch(String initialQuery, boolean selectInitialQuery,
1277 Bundle appSearchData, boolean globalSearch) {
1278 if (appSearchData == null) {
1279 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1281 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1285 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1286 * results in changing tabs.
1287 * @param index Index of the tab to change to, as defined by
1288 * mTabControl.getTabIndex(Tab t).
1289 * @return boolean True if we successfully switched to a different tab. If
1290 * the indexth tab is null, or if that tab is the same as
1291 * the current one, return false.
1293 /* package */ boolean switchToTab(int index) {
1294 Tab tab = mTabControl.getTab(index);
1295 Tab currentTab = mTabControl.getCurrentTab();
1296 if (tab == null || tab == currentTab) {
1299 if (currentTab != null) {
1300 // currentTab may be null if it was just removed. In that case,
1301 // we do not need to remove it
1302 removeTabFromContentView(currentTab);
1304 mTabControl.setCurrentTab(tab);
1305 attachTabToContentView(tab);
1306 resetTitleIconAndProgress();
1307 updateLockIconToLatest();
1311 /* package */ Tab openTabToHomePage() {
1312 return openTabAndShow(mSettings.getHomePage(), false, null);
1315 /* package */ void closeCurrentWindow() {
1316 final Tab current = mTabControl.getCurrentTab();
1317 if (mTabControl.getTabCount() == 1) {
1318 // This is the last tab. Open a new one, with the home
1319 // page and close the current one.
1320 openTabToHomePage();
1324 final Tab parent = current.getParentTab();
1325 int indexToShow = -1;
1326 if (parent != null) {
1327 indexToShow = mTabControl.getTabIndex(parent);
1329 final int currentIndex = mTabControl.getCurrentIndex();
1330 // Try to move to the tab to the right
1331 indexToShow = currentIndex + 1;
1332 if (indexToShow > mTabControl.getTabCount() - 1) {
1333 // Try to move to the tab to the left
1334 indexToShow = currentIndex - 1;
1337 if (switchToTab(indexToShow)) {
1343 private ActiveTabsPage mActiveTabsPage;
1346 * Remove the active tabs page.
1347 * @param needToAttach If true, the active tabs page did not attach a tab
1348 * to the content view, so we need to do that here.
1350 /* package */ void removeActiveTabPage(boolean needToAttach) {
1351 mContentView.removeView(mActiveTabsPage);
1352 mActiveTabsPage = null;
1353 mMenuState = R.id.MAIN_MENU;
1355 attachTabToContentView(mTabControl.getCurrentTab());
1357 getTopWindow().requestFocus();
1361 public boolean onOptionsItemSelected(MenuItem item) {
1363 // The user has already fired a shortcut with this hold down of the
1367 if (null == getTopWindow()) {
1371 // The shortcut action consumes the MENU. Even if it is still down,
1372 // it won't trigger the next shortcut action. In the case of the
1373 // shortcut action triggering a new activity, like Bookmarks, we
1374 // won't get onKeyUp for MENU. So it is important to reset it here.
1375 mMenuIsDown = false;
1377 switch (item.getItemId()) {
1379 case R.id.new_tab_menu_id:
1380 openTabToHomePage();
1383 case R.id.goto_menu_id:
1384 onSearchRequested();
1387 case R.id.bookmarks_menu_id:
1388 bookmarksOrHistoryPicker(false);
1391 case R.id.active_tabs_menu_id:
1392 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1393 removeTabFromContentView(mTabControl.getCurrentTab());
1395 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1396 mActiveTabsPage.requestFocus();
1397 mMenuState = EMPTY_MENU;
1400 case R.id.add_bookmark_menu_id:
1401 Intent i = new Intent(BrowserActivity.this,
1402 AddBookmarkPage.class);
1403 WebView w = getTopWindow();
1404 i.putExtra("url", w.getUrl());
1405 i.putExtra("title", w.getTitle());
1406 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1407 i.putExtra("thumbnail", createScreenshot(w));
1411 case R.id.stop_reload_menu_id:
1415 getTopWindow().reload();
1419 case R.id.back_menu_id:
1420 getTopWindow().goBack();
1423 case R.id.forward_menu_id:
1424 getTopWindow().goForward();
1427 case R.id.close_menu_id:
1428 // Close the subwindow if it exists.
1429 if (mTabControl.getCurrentSubWindow() != null) {
1430 dismissSubWindow(mTabControl.getCurrentTab());
1433 closeCurrentWindow();
1436 case R.id.homepage_menu_id:
1437 Tab current = mTabControl.getCurrentTab();
1438 if (current != null) {
1439 dismissSubWindow(current);
1440 current.getWebView().loadUrl(mSettings.getHomePage());
1444 case R.id.preferences_menu_id:
1445 Intent intent = new Intent(this,
1446 BrowserPreferencesPage.class);
1447 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1448 getTopWindow().getUrl());
1449 startActivityForResult(intent, PREFERENCES_PAGE);
1452 case R.id.find_menu_id:
1453 if (null == mFindDialog) {
1454 mFindDialog = new FindDialog(this);
1456 mFindDialog.setWebView(getTopWindow());
1458 mMenuState = EMPTY_MENU;
1461 case R.id.select_text_id:
1462 getTopWindow().emulateShiftHeld();
1464 case R.id.page_info_menu_id:
1465 showPageInfo(mTabControl.getCurrentTab(), false);
1468 case R.id.classic_history_menu_id:
1469 bookmarksOrHistoryPicker(true);
1472 case R.id.title_bar_share_page_url:
1473 case R.id.share_page_menu_id:
1474 Tab currentTab = mTabControl.getCurrentTab();
1475 if (null == currentTab) {
1479 currentTab.populatePickerData();
1480 sharePage(this, currentTab.getTitle(),
1481 currentTab.getUrl(), currentTab.getFavicon(),
1482 createScreenshot(currentTab.getWebView()));
1485 case R.id.dump_nav_menu_id:
1486 getTopWindow().debugDump();
1489 case R.id.zoom_in_menu_id:
1490 getTopWindow().zoomIn();
1493 case R.id.zoom_out_menu_id:
1494 getTopWindow().zoomOut();
1497 case R.id.view_downloads_menu_id:
1498 viewDownloads(null);
1501 case R.id.window_one_menu_id:
1502 case R.id.window_two_menu_id:
1503 case R.id.window_three_menu_id:
1504 case R.id.window_four_menu_id:
1505 case R.id.window_five_menu_id:
1506 case R.id.window_six_menu_id:
1507 case R.id.window_seven_menu_id:
1508 case R.id.window_eight_menu_id:
1510 int menuid = item.getItemId();
1511 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1512 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1513 Tab desiredTab = mTabControl.getTab(id);
1514 if (desiredTab != null &&
1515 desiredTab != mTabControl.getCurrentTab()) {
1525 if (!super.onOptionsItemSelected(item)) {
1528 // Otherwise fall through.
1534 public void closeFind() {
1535 mMenuState = R.id.MAIN_MENU;
1539 public boolean onPrepareOptionsMenu(Menu menu) {
1540 // This happens when the user begins to hold down the menu key, so
1541 // allow them to chord to get a shortcut.
1543 // Note: setVisible will decide whether an item is visible; while
1544 // setEnabled() will decide whether an item is enabled, which also means
1545 // whether the matching shortcut key will function.
1546 super.onPrepareOptionsMenu(menu);
1547 switch (mMenuState) {
1549 if (mCurrentMenuState != mMenuState) {
1550 menu.setGroupVisible(R.id.MAIN_MENU, false);
1551 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1552 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1556 if (mCurrentMenuState != mMenuState) {
1557 menu.setGroupVisible(R.id.MAIN_MENU, true);
1558 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1559 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1561 final WebView w = getTopWindow();
1562 boolean canGoBack = false;
1563 boolean canGoForward = false;
1564 boolean isHome = false;
1566 canGoBack = w.canGoBack();
1567 canGoForward = w.canGoForward();
1568 isHome = mSettings.getHomePage().equals(w.getUrl());
1570 final MenuItem back = menu.findItem(R.id.back_menu_id);
1571 back.setEnabled(canGoBack);
1573 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1574 home.setEnabled(!isHome);
1576 menu.findItem(R.id.forward_menu_id)
1577 .setEnabled(canGoForward);
1579 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1580 mTabControl.canCreateNewTab());
1582 // decide whether to show the share link option
1583 PackageManager pm = getPackageManager();
1584 Intent send = new Intent(Intent.ACTION_SEND);
1585 send.setType("text/plain");
1586 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1587 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1589 boolean isNavDump = mSettings.isNavDump();
1590 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1591 nav.setVisible(isNavDump);
1592 nav.setEnabled(isNavDump);
1595 mCurrentMenuState = mMenuState;
1600 public void onCreateContextMenu(ContextMenu menu, View v,
1601 ContextMenuInfo menuInfo) {
1602 WebView webview = (WebView) v;
1603 WebView.HitTestResult result = webview.getHitTestResult();
1604 if (result == null) {
1608 int type = result.getType();
1609 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1611 "We should not show context menu when nothing is touched");
1614 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1615 // let TextView handles context menu
1619 // Note, http://b/issue?id=1106666 is requesting that
1620 // an inflated menu can be used again. This is not available
1621 // yet, so inflate each time (yuk!)
1622 MenuInflater inflater = getMenuInflater();
1623 inflater.inflate(R.menu.browsercontext, menu);
1625 // Show the correct menu group
1626 String extra = result.getExtra();
1627 menu.setGroupVisible(R.id.PHONE_MENU,
1628 type == WebView.HitTestResult.PHONE_TYPE);
1629 menu.setGroupVisible(R.id.EMAIL_MENU,
1630 type == WebView.HitTestResult.EMAIL_TYPE);
1631 menu.setGroupVisible(R.id.GEO_MENU,
1632 type == WebView.HitTestResult.GEO_TYPE);
1633 menu.setGroupVisible(R.id.IMAGE_MENU,
1634 type == WebView.HitTestResult.IMAGE_TYPE
1635 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1636 menu.setGroupVisible(R.id.ANCHOR_MENU,
1637 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1638 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1640 // Setup custom handling depending on the type
1642 case WebView.HitTestResult.PHONE_TYPE:
1643 menu.setHeaderTitle(Uri.decode(extra));
1644 menu.findItem(R.id.dial_context_menu_id).setIntent(
1645 new Intent(Intent.ACTION_VIEW, Uri
1646 .parse(WebView.SCHEME_TEL + extra)));
1647 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1648 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1649 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1650 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1652 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1656 case WebView.HitTestResult.EMAIL_TYPE:
1657 menu.setHeaderTitle(extra);
1658 menu.findItem(R.id.email_context_menu_id).setIntent(
1659 new Intent(Intent.ACTION_VIEW, Uri
1660 .parse(WebView.SCHEME_MAILTO + extra)));
1661 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1665 case WebView.HitTestResult.GEO_TYPE:
1666 menu.setHeaderTitle(extra);
1667 menu.findItem(R.id.map_context_menu_id).setIntent(
1668 new Intent(Intent.ACTION_VIEW, Uri
1669 .parse(WebView.SCHEME_GEO
1670 + URLEncoder.encode(extra))));
1671 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1675 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1676 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1677 TextView titleView = (TextView) LayoutInflater.from(this)
1678 .inflate(android.R.layout.browser_link_context_header,
1680 titleView.setText(extra);
1681 menu.setHeaderView(titleView);
1682 // decide whether to show the open link in new tab option
1683 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1684 mTabControl.canCreateNewTab());
1685 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1686 Bookmarks.urlHasAcceptableScheme(extra));
1687 PackageManager pm = getPackageManager();
1688 Intent send = new Intent(Intent.ACTION_SEND);
1689 send.setType("text/plain");
1690 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1691 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1692 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1695 // otherwise fall through to handle image part
1696 case WebView.HitTestResult.IMAGE_TYPE:
1697 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1698 menu.setHeaderTitle(extra);
1700 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1701 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1702 menu.findItem(R.id.download_context_menu_id).
1703 setOnMenuItemClickListener(new Download(extra));
1704 menu.findItem(R.id.set_wallpaper_context_menu_id).
1705 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1709 Log.w(LOGTAG, "We should not get here.");
1715 // Attach the given tab to the content view.
1716 // this should only be called for the current tab.
1717 private void attachTabToContentView(Tab t) {
1718 // Attach the container that contains the main WebView and any other UI
1719 // associated with the tab.
1720 t.attachTabToContentView(mContentView);
1722 if (mShouldShowErrorConsole) {
1723 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1724 if (errorConsole.numberOfErrors() == 0) {
1725 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1727 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1730 mErrorConsoleContainer.addView(errorConsole,
1731 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1732 ViewGroup.LayoutParams.WRAP_CONTENT));
1735 WebView view = t.getWebView();
1736 view.setEmbeddedTitleBar(mTitleBar);
1737 // Request focus on the top window.
1738 t.getTopWindow().requestFocus();
1741 // Attach a sub window to the main WebView of the given tab.
1742 void attachSubWindow(Tab t) {
1743 t.attachSubWindow(mContentView);
1744 getTopWindow().requestFocus();
1747 // Remove the given tab from the content view.
1748 private void removeTabFromContentView(Tab t) {
1749 // Remove the container that contains the main WebView.
1750 t.removeTabFromContentView(mContentView);
1752 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1753 if (errorConsole != null) {
1754 mErrorConsoleContainer.removeView(errorConsole);
1757 WebView view = t.getWebView();
1759 view.setEmbeddedTitleBar(null);
1763 // Remove the sub window if it exists. Also called by TabControl when the
1764 // user clicks the 'X' to dismiss a sub window.
1765 /* package */ void dismissSubWindow(Tab t) {
1766 t.removeSubWindow(mContentView);
1767 // dismiss the subwindow. This will destroy the WebView.
1768 t.dismissSubWindow();
1769 getTopWindow().requestFocus();
1772 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1773 // that accepts url as string.
1774 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1775 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1778 // This method does a ton of stuff. It will attempt to create a new tab
1779 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1780 // url isn't null, it will load the given url.
1781 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1783 final Tab currentTab = mTabControl.getCurrentTab();
1784 if (mTabControl.canCreateNewTab()) {
1785 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1787 WebView webview = tab.getWebView();
1788 // If the last tab was removed from the active tabs page, currentTab
1790 if (currentTab != null) {
1791 removeTabFromContentView(currentTab);
1793 // We must set the new tab as the current tab to reflect the old
1794 // animation behavior.
1795 mTabControl.setCurrentTab(tab);
1796 attachTabToContentView(tab);
1797 if (!urlData.isEmpty()) {
1798 urlData.loadIn(webview);
1802 // Get rid of the subwindow if it exists
1803 dismissSubWindow(currentTab);
1804 if (!urlData.isEmpty()) {
1805 // Load the given url.
1806 urlData.loadIn(currentTab.getWebView());
1812 private Tab openTab(String url) {
1813 if (mSettings.openInBackground()) {
1814 Tab t = mTabControl.createNewTab();
1816 WebView view = t.getWebView();
1821 return openTabAndShow(url, false, null);
1825 private class Copy implements OnMenuItemClickListener {
1826 private CharSequence mText;
1828 public boolean onMenuItemClick(MenuItem item) {
1833 public Copy(CharSequence toCopy) {
1838 private class Download implements OnMenuItemClickListener {
1839 private String mText;
1841 public boolean onMenuItemClick(MenuItem item) {
1842 onDownloadStartNoStream(mText, null, null, null, -1);
1846 public Download(String toDownload) {
1851 private class SetAsWallpaper extends Thread implements
1852 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1854 private ProgressDialog mWallpaperProgress;
1855 private boolean mCanceled = false;
1857 public SetAsWallpaper(String url) {
1859 mUrl = new URL(url);
1860 } catch (MalformedURLException e) {
1865 public void onCancel(DialogInterface dialog) {
1869 public boolean onMenuItemClick(MenuItem item) {
1871 // The user may have tried to set a image with a large file size as their
1872 // background so it may take a few moments to perform the operation. Display
1873 // a progress spinner while it is working.
1874 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1875 mWallpaperProgress.setIndeterminate(true);
1876 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1877 mWallpaperProgress.setCancelable(true);
1878 mWallpaperProgress.setOnCancelListener(this);
1879 mWallpaperProgress.show();
1886 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1888 // TODO: This will cause the resource to be downloaded again, when we
1889 // should in most cases be able to grab it from the cache. To fix this
1890 // we should query WebCore to see if we can access a cached version and
1891 // instead open an input stream on that. This pattern could also be used
1892 // in the download manager where the same problem exists.
1893 InputStream inputstream = mUrl.openStream();
1894 if (inputstream != null) {
1895 setWallpaper(inputstream);
1897 } catch (IOException e) {
1898 Log.e(LOGTAG, "Unable to set new wallpaper");
1899 // Act as though the user canceled the operation so we try to
1900 // restore the old wallpaper.
1905 // Restore the old wallpaper if the user cancelled whilst we were setting
1906 // the new wallpaper.
1907 int width = oldWallpaper.getIntrinsicWidth();
1908 int height = oldWallpaper.getIntrinsicHeight();
1909 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1910 Canvas canvas = new Canvas(bm);
1911 oldWallpaper.setBounds(0, 0, width, height);
1912 oldWallpaper.draw(canvas);
1915 } catch (IOException e) {
1916 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1921 if (mWallpaperProgress.isShowing()) {
1922 mWallpaperProgress.dismiss();
1927 private void copy(CharSequence text) {
1929 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1931 clip.setClipboardText(text);
1933 } catch (android.os.RemoteException e) {
1934 Log.e(LOGTAG, "Copy failed", e);
1939 * Resets the browser title-view to whatever it must be
1940 * (for example, if we had a loading error)
1941 * When we have a new page, we call resetTitle, when we
1942 * have to reset the titlebar to whatever it used to be
1943 * (for example, if the user chose to stop loading), we
1944 * call resetTitleAndRevertLockIcon.
1946 /* package */ void resetTitleAndRevertLockIcon() {
1947 mTabControl.getCurrentTab().revertLockIcon();
1948 updateLockIconToLatest();
1949 resetTitleIconAndProgress();
1953 * Reset the title, favicon, and progress.
1955 private void resetTitleIconAndProgress() {
1956 WebView current = mTabControl.getCurrentWebView();
1957 if (current == null) {
1960 resetTitleAndIcon(current);
1961 int progress = current.getProgress();
1962 current.getWebChromeClient().onProgressChanged(current, progress);
1965 // Reset the title and the icon based on the given item.
1966 private void resetTitleAndIcon(WebView view) {
1967 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1969 setUrlTitle(item.getUrl(), item.getTitle());
1970 setFavicon(item.getFavicon());
1972 setUrlTitle(null, null);
1978 * Sets a title composed of the URL and the title string.
1979 * @param url The URL of the site being loaded.
1980 * @param title The title of the site being loaded.
1982 void setUrlTitle(String url, String title) {
1986 mTitleBar.setTitleAndUrl(title, url);
1987 mFakeTitleBar.setTitleAndUrl(title, url);
1991 * @param url The URL to build a title version of the URL from.
1992 * @return The title version of the URL or null if fails.
1993 * The title version of the URL can be either the URL hostname,
1994 * or the hostname with an "https://" prefix (for secure URLs),
1995 * or an empty string if, for example, the URL in question is a
1996 * file:// URL with no hostname.
1998 /* package */ static String buildTitleUrl(String url) {
1999 String titleUrl = null;
2003 // parse the url string
2004 URL urlObj = new URL(url);
2005 if (urlObj != null) {
2008 String protocol = urlObj.getProtocol();
2009 String host = urlObj.getHost();
2011 if (host != null && 0 < host.length()) {
2013 if (protocol != null) {
2014 // if a secure site, add an "https://" prefix!
2015 if (protocol.equalsIgnoreCase("https")) {
2016 titleUrl = protocol + "://" + host;
2021 } catch (MalformedURLException e) {}
2027 // Set the favicon in the title bar.
2028 void setFavicon(Bitmap icon) {
2029 mTitleBar.setFavicon(icon);
2030 mFakeTitleBar.setFavicon(icon);
2034 * Close the tab, remove its associated title bar, and adjust mTabControl's
2035 * current tab to a valid value.
2037 /* package */ void closeTab(Tab t) {
2038 int currentIndex = mTabControl.getCurrentIndex();
2039 int removeIndex = mTabControl.getTabIndex(t);
2040 mTabControl.removeTab(t);
2041 if (currentIndex >= removeIndex && currentIndex != 0) {
2044 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2045 resetTitleIconAndProgress();
2048 private void goBackOnePageOrQuit() {
2049 Tab current = mTabControl.getCurrentTab();
2050 if (current == null) {
2052 * Instead of finishing the activity, simply push this to the back
2053 * of the stack and let ActivityManager to choose the foreground
2054 * activity. As BrowserActivity is singleTask, it will be always the
2055 * root of the task. So we can use either true or false for
2058 moveTaskToBack(true);
2061 WebView w = current.getWebView();
2062 if (w.canGoBack()) {
2065 // Check to see if we are closing a window that was created by
2066 // another window. If so, we switch back to that window.
2067 Tab parent = current.getParentTab();
2068 if (parent != null) {
2069 switchToTab(mTabControl.getTabIndex(parent));
2070 // Now we close the other tab
2073 if (current.closeOnExit()) {
2074 // force the tab's inLoad() to be false as we are going to
2075 // either finish the activity or remove the tab. This will
2076 // ensure pauseWebViewTimers() taking action.
2077 mTabControl.getCurrentTab().clearInLoad();
2078 if (mTabControl.getTabCount() == 1) {
2082 // call pauseWebViewTimers() now, we won't be able to call
2083 // it in onPause() as the WebView won't be valid.
2084 // Temporarily change mActivityInPause to be true as
2085 // pauseWebViewTimers() will do nothing if mActivityInPause
2087 boolean savedState = mActivityInPause;
2089 Log.e(LOGTAG, "BrowserActivity is already paused "
2090 + "while handing goBackOnePageOrQuit.");
2092 mActivityInPause = true;
2093 pauseWebViewTimers();
2094 mActivityInPause = savedState;
2095 removeTabFromContentView(current);
2096 mTabControl.removeTab(current);
2099 * Instead of finishing the activity, simply push this to the back
2100 * of the stack and let ActivityManager to choose the foreground
2101 * activity. As BrowserActivity is singleTask, it will be always the
2102 * root of the task. So we can use either true or false for
2105 moveTaskToBack(true);
2110 boolean isMenuDown() {
2115 public boolean onKeyDown(int keyCode, KeyEvent event) {
2116 // Even if MENU is already held down, we need to call to super to open
2117 // the IME on long press.
2118 if (KeyEvent.KEYCODE_MENU == keyCode) {
2120 return super.onKeyDown(keyCode, event);
2122 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2123 // still down, we don't want to trigger the search. Pretend to consume
2124 // the key and do nothing.
2125 if (mMenuIsDown) return true;
2128 case KeyEvent.KEYCODE_SPACE:
2129 // WebView/WebTextView handle the keys in the KeyDown. As
2130 // the Activity's shortcut keys are only handled when WebView
2131 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2132 if (event.isShiftPressed()) {
2133 getTopWindow().pageUp(false);
2135 getTopWindow().pageDown(false);
2138 case KeyEvent.KEYCODE_BACK:
2139 if (event.getRepeatCount() == 0) {
2140 event.startTracking();
2142 } else if (mCustomView == null && mActiveTabsPage == null
2143 && event.isLongPress()) {
2144 bookmarksOrHistoryPicker(true);
2149 return super.onKeyDown(keyCode, event);
2153 public boolean onKeyUp(int keyCode, KeyEvent event) {
2155 case KeyEvent.KEYCODE_MENU:
2156 mMenuIsDown = false;
2158 case KeyEvent.KEYCODE_BACK:
2159 if (event.isTracking() && !event.isCanceled()) {
2160 if (mCustomView != null) {
2161 // if a custom view is showing, hide it
2162 mTabControl.getCurrentWebView().getWebChromeClient()
2163 .onHideCustomView();
2164 } else if (mActiveTabsPage != null) {
2165 // if tab page is showing, hide it
2166 removeActiveTabPage(true);
2168 WebView subwindow = mTabControl.getCurrentSubWindow();
2169 if (subwindow != null) {
2170 if (subwindow.canGoBack()) {
2173 dismissSubWindow(mTabControl.getCurrentTab());
2176 goBackOnePageOrQuit();
2183 return super.onKeyUp(keyCode, event);
2186 /* package */ void stopLoading() {
2187 mDidStopLoad = true;
2188 resetTitleAndRevertLockIcon();
2189 WebView w = getTopWindow();
2191 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2192 // same logic here. But for subwindow case, should we call into the main
2193 // WebView's onPageFinished as we never call its onPageStarted and if
2194 // the page finishes itself, we don't call onPageFinished.
2195 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2200 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2204 boolean didUserStopLoading() {
2205 return mDidStopLoad;
2208 private void cancelStopToast() {
2209 if (mStopToast != null) {
2210 mStopToast.cancel();
2215 // called by a UI or non-UI thread to post the message
2216 public void postMessage(int what, int arg1, int arg2, Object obj,
2218 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2222 // called by a UI or non-UI thread to remove the message
2223 void removeMessages(int what, Object object) {
2224 mHandler.removeMessages(what, object);
2227 // public message ids
2228 public final static int LOAD_URL = 1001;
2229 public final static int STOP_LOAD = 1002;
2232 private static final int FOCUS_NODE_HREF = 102;
2233 private static final int CANCEL_CREDS_REQUEST = 103;
2234 private static final int RELEASE_WAKELOCK = 107;
2236 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2238 // Private handler for handling javascript and saving passwords
2239 private Handler mHandler = new Handler() {
2241 public void handleMessage(Message msg) {
2243 case FOCUS_NODE_HREF:
2245 String url = (String) msg.getData().get("url");
2246 String title = (String) msg.getData().get("title");
2247 if (url == null || url.length() == 0) {
2250 HashMap focusNodeMap = (HashMap) msg.obj;
2251 WebView view = (WebView) focusNodeMap.get("webview");
2252 // Only apply the action if the top window did not change.
2253 if (getTopWindow() != view) {
2257 case R.id.open_context_menu_id:
2258 case R.id.view_image_context_menu_id:
2259 loadURL(getTopWindow(), url);
2261 case R.id.open_newtab_context_menu_id:
2262 final Tab parent = mTabControl.getCurrentTab();
2263 final Tab newTab = openTab(url);
2264 if (newTab != parent) {
2265 parent.addChildTab(newTab);
2268 case R.id.bookmark_context_menu_id:
2269 Intent intent = new Intent(BrowserActivity.this,
2270 AddBookmarkPage.class);
2271 intent.putExtra("url", url);
2272 intent.putExtra("title", title);
2273 startActivity(intent);
2275 case R.id.share_link_context_menu_id:
2276 // See if this site has been visited before
2277 StringBuilder sb = new StringBuilder(
2278 Browser.BookmarkColumns.URL + " = ");
2279 DatabaseUtils.appendEscapedSQLString(sb, url);
2280 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2281 Browser.HISTORY_PROJECTION,
2285 if (c.moveToFirst()) {
2286 // The site has been visited before, so grab the
2287 // info from the database.
2288 Bitmap favicon = null;
2289 Bitmap thumbnail = null;
2290 String linkTitle = c.getString(Browser.
2291 HISTORY_PROJECTION_TITLE_INDEX);
2292 byte[] data = c.getBlob(Browser.
2293 HISTORY_PROJECTION_FAVICON_INDEX);
2295 favicon = BitmapFactory.decodeByteArray(
2296 data, 0, data.length);
2298 data = c.getBlob(Browser.
2299 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2301 thumbnail = BitmapFactory.decodeByteArray(
2302 data, 0, data.length);
2304 sharePage(BrowserActivity.this,
2305 linkTitle, url, favicon, thumbnail);
2307 Browser.sendString(BrowserActivity.this, url,
2309 R.string.choosertitle_sharevia));
2312 case R.id.copy_link_context_menu_id:
2315 case R.id.save_link_context_menu_id:
2316 case R.id.download_context_menu_id:
2317 onDownloadStartNoStream(url, null, null, null, -1);
2324 loadURL(getTopWindow(), (String) msg.obj);
2331 case CANCEL_CREDS_REQUEST:
2332 resumeAfterCredentials();
2335 case RELEASE_WAKELOCK:
2336 if (mWakeLock.isHeld()) {
2337 mWakeLock.release();
2338 // if we reach here, Browser should be still in the
2339 // background loading after WAKELOCK_TIMEOUT (5-min).
2340 // To avoid burning the battery, stop loading.
2341 mTabControl.stopAllLoading();
2345 case UPDATE_BOOKMARK_THUMBNAIL:
2346 WebView view = (WebView) msg.obj;
2348 updateScreenshot(view);
2356 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2357 * an {@link Intent} to launch the Activity chooser.
2358 * @param c Context used to launch a new Activity.
2359 * @param title Title of the page. Stored in the Intent with
2360 * {@link Browser#EXTRA_SHARE_TITLE}
2361 * @param url URL of the page. Stored in the Intent with
2362 * {@link Intent#EXTRA_TEXT}
2363 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2364 * with {@link Browser#EXTRA_SHARE_FAVICON}
2365 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2366 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2368 public static final void sharePage(Context c, String title, String url,
2369 Bitmap favicon, Bitmap screenshot) {
2370 Intent send = new Intent(Intent.ACTION_SEND);
2371 send.setType("text/plain");
2372 send.putExtra(Intent.EXTRA_TEXT, url);
2373 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2374 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2375 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2377 c.startActivity(Intent.createChooser(send, c.getString(
2378 R.string.choosertitle_sharevia)));
2379 } catch(android.content.ActivityNotFoundException ex) {
2380 // if no app handles it, do nothing
2384 private void updateScreenshot(WebView view) {
2385 // If this is a bookmarked site, add a screenshot to the database.
2386 // FIXME: When should we update? Every time?
2387 // FIXME: Would like to make sure there is actually something to
2388 // draw, but the API for that (WebViewCore.pictureReady()) is not
2389 // currently accessible here.
2391 ContentResolver cr = getContentResolver();
2392 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2393 cr, view.getOriginalUrl(), view.getUrl(), true);
2395 boolean succeed = c.moveToFirst();
2396 ContentValues values = null;
2398 if (values == null) {
2399 final ByteArrayOutputStream os
2400 = new ByteArrayOutputStream();
2401 Bitmap bm = createScreenshot(view);
2406 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2407 values = new ContentValues();
2408 values.put(Browser.BookmarkColumns.THUMBNAIL,
2411 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2412 c.getInt(0)), values, null, null);
2413 succeed = c.moveToNext();
2420 * Values for the size of the thumbnail created when taking a screenshot.
2421 * Lazily initialized. Instead of using these directly, use
2422 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2424 private static int THUMBNAIL_WIDTH = 0;
2425 private static int THUMBNAIL_HEIGHT = 0;
2428 * Return the desired width for thumbnail screenshots, which are stored in
2429 * the database, and used on the bookmarks screen.
2430 * @param context Context for finding out the density of the screen.
2431 * @return int desired width for thumbnail screenshot.
2433 /* package */ static int getDesiredThumbnailWidth(Context context) {
2434 if (THUMBNAIL_WIDTH == 0) {
2435 float density = context.getResources().getDisplayMetrics().density;
2436 THUMBNAIL_WIDTH = (int) (90 * density);
2437 THUMBNAIL_HEIGHT = (int) (80 * density);
2439 return THUMBNAIL_WIDTH;
2443 * Return the desired height for thumbnail screenshots, which are stored in
2444 * the database, and used on the bookmarks screen.
2445 * @param context Context for finding out the density of the screen.
2446 * @return int desired height for thumbnail screenshot.
2448 /* package */ static int getDesiredThumbnailHeight(Context context) {
2449 // To ensure that they are both initialized.
2450 getDesiredThumbnailWidth(context);
2451 return THUMBNAIL_HEIGHT;
2454 private Bitmap createScreenshot(WebView view) {
2455 Picture thumbnail = view.capturePicture();
2456 if (thumbnail == null) {
2459 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2460 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2461 Canvas canvas = new Canvas(bm);
2462 // May need to tweak these values to determine what is the
2463 // best scale factor
2464 int thumbnailWidth = thumbnail.getWidth();
2465 int thumbnailHeight = thumbnail.getHeight();
2466 float scaleFactorX = 1.0f;
2467 float scaleFactorY = 1.0f;
2468 if (thumbnailWidth > 0) {
2469 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2470 (float)thumbnailWidth;
2475 if (view.getWidth() > view.getHeight() &&
2476 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2477 // If the device is in landscape and the page is shorter
2478 // than the height of the view, stretch the thumbnail to fill the
2480 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2481 (float)thumbnailHeight;
2483 // In the portrait case, this looks nice.
2484 scaleFactorY = scaleFactorX;
2487 canvas.scale(scaleFactorX, scaleFactorY);
2489 thumbnail.draw(canvas);
2493 // -------------------------------------------------------------------------
2494 // Helper function for WebViewClient.
2495 //-------------------------------------------------------------------------
2497 // Use in overrideUrlLoading
2498 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2499 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2500 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2501 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2503 void onPageStarted(WebView view, String url, Bitmap favicon) {
2504 // when BrowserActivity just starts, onPageStarted may be called before
2505 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2506 // to start the timer. As we won't switch tabs while an activity is in
2507 // pause state, we can ensure calling resume and pause in pair.
2508 if (mActivityInPause) resumeWebViewTimers();
2511 setUrlTitle(url, null);
2512 setFavicon(favicon);
2513 // Keep this initial progress in sync with initialProgressValue (* 100)
2514 // in ProgressTracker.cpp
2515 // Show some progress so that the user knows the page is beginning to
2517 onProgressChanged(view, 10);
2518 mDidStopLoad = false;
2519 if (!mIsNetworkUp) createAndShowNetworkDialog();
2521 if (mSettings.isTracing()) {
2524 WebAddress uri = new WebAddress(url);
2526 } catch (android.net.ParseException ex) {
2529 host = host.replace('.', '_');
2532 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2535 // Performance probe
2537 mStart = SystemClock.uptimeMillis();
2538 mProcessStart = Process.getElapsedCpuTime();
2539 long[] sysCpu = new long[7];
2540 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2542 mUserStart = sysCpu[0] + sysCpu[1];
2543 mSystemStart = sysCpu[2];
2544 mIdleStart = sysCpu[3];
2545 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2547 mUiStart = SystemClock.currentThreadTimeMillis();
2551 void onPageFinished(WebView view, String url) {
2552 // Reset the title and icon in case we stopped a provisional load.
2553 resetTitleAndIcon(view);
2554 // Update the lock icon image only once we are done loading
2555 updateLockIconToLatest();
2556 // pause the WebView timer and release the wake lock if it is finished
2557 // while BrowserActivity is in pause state.
2558 if (mActivityInPause && pauseWebViewTimers()) {
2559 if (mWakeLock.isHeld()) {
2560 mHandler.removeMessages(RELEASE_WAKELOCK);
2561 mWakeLock.release();
2565 // Performance probe
2567 long[] sysCpu = new long[7];
2568 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2570 String uiInfo = "UI thread used "
2571 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2574 Log.d(LOGTAG, uiInfo);
2576 //The string that gets written to the log
2577 String performanceString = "It took total "
2578 + (SystemClock.uptimeMillis() - mStart)
2579 + " ms clock time to load the page."
2580 + "\nbrowser process used "
2581 + (Process.getElapsedCpuTime() - mProcessStart)
2582 + " ms, user processes used "
2583 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2584 + " ms, kernel used "
2585 + (sysCpu[2] - mSystemStart) * 10
2586 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2587 + " ms and irq took "
2588 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2589 * 10 + " ms, " + uiInfo;
2591 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2594 // strip the url to maintain consistency
2595 String newUrl = new String(url);
2596 if (newUrl.startsWith("http://www.")) {
2597 newUrl = newUrl.substring(11);
2598 } else if (newUrl.startsWith("http://")) {
2599 newUrl = newUrl.substring(7);
2600 } else if (newUrl.startsWith("https://www.")) {
2601 newUrl = newUrl.substring(12);
2602 } else if (newUrl.startsWith("https://")) {
2603 newUrl = newUrl.substring(8);
2606 Log.d(LOGTAG, newUrl + " loaded");
2614 Debug.stopMethodTracing();
2618 boolean shouldOverrideUrlLoading(WebView view, String url) {
2619 if (url.startsWith(SCHEME_WTAI)) {
2620 // wtai://wp/mc;number
2621 // number=string(phone-number)
2622 if (url.startsWith(SCHEME_WTAI_MC)) {
2623 Intent intent = new Intent(Intent.ACTION_VIEW,
2624 Uri.parse(WebView.SCHEME_TEL +
2625 url.substring(SCHEME_WTAI_MC.length())));
2626 startActivity(intent);
2629 // wtai://wp/sd;dtmf
2630 // dtmf=string(dialstring)
2631 if (url.startsWith(SCHEME_WTAI_SD)) {
2632 // TODO: only send when there is active voice connection
2635 // wtai://wp/ap;number;name
2636 // number=string(phone-number)
2638 if (url.startsWith(SCHEME_WTAI_AP)) {
2644 // The "about:" schemes are internal to the browser; don't want these to
2645 // be dispatched to other apps.
2646 if (url.startsWith("about:")) {
2651 // perform generic parsing of the URI to turn it into an Intent.
2653 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2654 } catch (URISyntaxException ex) {
2655 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2659 // check whether the intent can be resolved. If not, we will see
2660 // whether we can download it from the Market.
2661 if (getPackageManager().resolveActivity(intent, 0) == null) {
2662 String packagename = intent.getPackage();
2663 if (packagename != null) {
2664 intent = new Intent(Intent.ACTION_VIEW, Uri
2665 .parse("market://search?q=pname:" + packagename));
2666 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2667 startActivity(intent);
2674 // sanitize the Intent, ensuring web pages can not bypass browser
2675 // security (only access to BROWSABLE activities).
2676 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2677 intent.setComponent(null);
2679 if (startActivityIfNeeded(intent, -1)) {
2682 } catch (ActivityNotFoundException ex) {
2683 // ignore the error. If no application can handle the URL,
2684 // eg about:blank, assume the browser can handle it.
2695 // -------------------------------------------------------------------------
2696 // Helper function for WebChromeClient
2697 // -------------------------------------------------------------------------
2699 void onProgressChanged(WebView view, int newProgress) {
2700 mTitleBar.setProgress(newProgress);
2701 mFakeTitleBar.setProgress(newProgress);
2703 if (newProgress == 100) {
2704 // onProgressChanged() may continue to be called after the main
2705 // frame has finished loading, as any remaining sub frames continue
2706 // to load. We'll only get called once though with newProgress as
2707 // 100 when everything is loaded. (onPageFinished is called once
2708 // when the main frame completes loading regardless of the state of
2709 // any sub frames so calls to onProgressChanges may continue after
2710 // onPageFinished has executed)
2713 updateInLoadMenuItems();
2714 // If the options menu is open, leave the title bar
2715 if (!mOptionsMenuOpen || !mIconView) {
2719 } else if (!mInLoad) {
2720 // onPageFinished may have already been called but a subframe is
2721 // still loading and updating the progress. Reset mInLoad and update
2724 updateInLoadMenuItems();
2725 if (!mOptionsMenuOpen || mIconView) {
2726 // This page has begun to load, so show the title bar
2732 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2733 // if a view already exists then immediately terminate the new one
2734 if (mCustomView != null) {
2735 callback.onCustomViewHidden();
2739 // Add the custom view to its container.
2740 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2742 mCustomViewCallback = callback;
2743 // Save the menu state and set it to empty while the custom
2745 mOldMenuState = mMenuState;
2746 mMenuState = EMPTY_MENU;
2747 // Hide the content view.
2748 mContentView.setVisibility(View.GONE);
2749 // Finally show the custom view container.
2750 setStatusBarVisibility(false);
2751 mCustomViewContainer.setVisibility(View.VISIBLE);
2752 mCustomViewContainer.bringToFront();
2755 void onHideCustomView() {
2756 if (mCustomView == null)
2759 // Hide the custom view.
2760 mCustomView.setVisibility(View.GONE);
2761 // Remove the custom view from its container.
2762 mCustomViewContainer.removeView(mCustomView);
2764 // Reset the old menu state.
2765 mMenuState = mOldMenuState;
2766 mOldMenuState = EMPTY_MENU;
2767 mCustomViewContainer.setVisibility(View.GONE);
2768 mCustomViewCallback.onCustomViewHidden();
2769 // Show the content view.
2770 setStatusBarVisibility(true);
2771 mContentView.setVisibility(View.VISIBLE);
2774 Bitmap getDefaultVideoPoster() {
2775 if (mDefaultVideoPoster == null) {
2776 mDefaultVideoPoster = BitmapFactory.decodeResource(
2777 getResources(), R.drawable.default_video_poster);
2779 return mDefaultVideoPoster;
2782 View getVideoLoadingProgressView() {
2783 if (mVideoProgressView == null) {
2784 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2785 mVideoProgressView = inflater.inflate(
2786 R.layout.video_loading_progress, null);
2788 return mVideoProgressView;
2792 * The Object used to inform the WebView of the file to upload.
2794 private ValueCallback<Uri> mUploadMessage;
2796 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2797 if (mUploadMessage != null) return;
2798 mUploadMessage = uploadMsg;
2799 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2800 i.addCategory(Intent.CATEGORY_OPENABLE);
2802 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2803 getString(R.string.choose_upload)), FILE_SELECTED);
2806 // -------------------------------------------------------------------------
2807 // Implement functions for DownloadListener
2808 // -------------------------------------------------------------------------
2811 * Notify the host application a download should be done, or that
2812 * the data should be streamed if a streaming viewer is available.
2813 * @param url The full url to the content that should be downloaded
2814 * @param contentDisposition Content-disposition http header, if
2816 * @param mimetype The mimetype of the content reported by the server
2817 * @param contentLength The file size reported by the server
2819 public void onDownloadStart(String url, String userAgent,
2820 String contentDisposition, String mimetype, long contentLength) {
2821 // if we're dealing wih A/V content that's not explicitly marked
2822 // for download, check if it's streamable.
2823 if (contentDisposition == null
2824 || !contentDisposition.regionMatches(
2825 true, 0, "attachment", 0, 10)) {
2826 // query the package manager to see if there's a registered handler
2828 Intent intent = new Intent(Intent.ACTION_VIEW);
2829 intent.setDataAndType(Uri.parse(url), mimetype);
2830 ResolveInfo info = getPackageManager().resolveActivity(intent,
2831 PackageManager.MATCH_DEFAULT_ONLY);
2833 ComponentName myName = getComponentName();
2834 // If we resolved to ourselves, we don't want to attempt to
2835 // load the url only to try and download it again.
2836 if (!myName.getPackageName().equals(
2837 info.activityInfo.packageName)
2838 || !myName.getClassName().equals(
2839 info.activityInfo.name)) {
2840 // someone (other than us) knows how to handle this mime
2841 // type with this scheme, don't download.
2843 startActivity(intent);
2845 } catch (ActivityNotFoundException ex) {
2847 Log.d(LOGTAG, "activity not found for " + mimetype
2848 + " over " + Uri.parse(url).getScheme(),
2851 // Best behavior is to fall back to a download in this
2857 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2861 * Notify the host application a download should be done, even if there
2862 * is a streaming viewer available for thise type.
2863 * @param url The full url to the content that should be downloaded
2864 * @param contentDisposition Content-disposition http header, if
2866 * @param mimetype The mimetype of the content reported by the server
2867 * @param contentLength The file size reported by the server
2869 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2870 String contentDisposition, String mimetype, long contentLength) {
2872 String filename = URLUtil.guessFileName(url,
2873 contentDisposition, mimetype);
2875 // Check to see if we have an SDCard
2876 String status = Environment.getExternalStorageState();
2877 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2881 // Check to see if the SDCard is busy, same as the music app
2882 if (status.equals(Environment.MEDIA_SHARED)) {
2883 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2884 title = R.string.download_sdcard_busy_dlg_title;
2886 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2887 title = R.string.download_no_sdcard_dlg_title;
2890 new AlertDialog.Builder(this)
2892 .setIcon(android.R.drawable.ic_dialog_alert)
2894 .setPositiveButton(R.string.ok, null)
2899 // java.net.URI is a lot stricter than KURL so we have to undo
2900 // KURL's percent-encoding and redo the encoding using java.net.URI.
2903 // Undo the percent-encoding that KURL may have done.
2904 String newUrl = new String(URLUtil.decode(url.getBytes()));
2905 // Parse the url into pieces
2906 WebAddress w = new WebAddress(newUrl);
2908 String query = null;
2909 String path = w.mPath;
2910 // Break the path into path, query, and fragment
2911 if (path.length() > 0) {
2912 // Strip the fragment
2913 int idx = path.lastIndexOf('#');
2915 frag = path.substring(idx + 1);
2916 path = path.substring(0, idx);
2918 idx = path.lastIndexOf('?');
2920 query = path.substring(idx + 1);
2921 path = path.substring(0, idx);
2924 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2926 } catch (Exception e) {
2927 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2931 // XXX: Have to use the old url since the cookies were stored using the
2932 // old percent-encoded url.
2933 String cookies = CookieManager.getInstance().getCookie(url);
2935 ContentValues values = new ContentValues();
2936 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2937 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2938 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2939 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
2941 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
2942 BrowserDownloadPage.class.getCanonicalName());
2943 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2944 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2945 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2946 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2947 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
2948 if (contentLength > 0) {
2949 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
2951 if (mimetype == null) {
2952 // We must have long pressed on a link or image to download it. We
2953 // are not sure of the mimetype in this case, so do a head request
2954 new FetchUrlMimeType(this).execute(values);
2956 final Uri contentUri =
2957 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
2962 // -------------------------------------------------------------------------
2965 * Resets the lock icon. This method is called when we start a new load and
2966 * know the url to be loaded.
2968 private void resetLockIcon(String url) {
2969 // Save the lock-icon state (we revert to it if the load gets cancelled)
2970 mTabControl.getCurrentTab().resetLockIcon(url);
2971 updateLockIconImage(LOCK_ICON_UNSECURE);
2975 * Update the lock icon to correspond to our latest state.
2977 private void updateLockIconToLatest() {
2978 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
2982 * Updates the lock-icon image in the title-bar.
2984 private void updateLockIconImage(int lockIconType) {
2986 if (lockIconType == LOCK_ICON_SECURE) {
2988 } else if (lockIconType == LOCK_ICON_MIXED) {
2991 mTitleBar.setLock(d);
2992 mFakeTitleBar.setLock(d);
2996 * Displays a page-info dialog.
2997 * @param tab The tab to show info about
2998 * @param fromShowSSLCertificateOnError The flag that indicates whether
2999 * this dialog was opened from the SSL-certificate-on-error dialog or
3000 * not. This is important, since we need to know whether to return to
3001 * the parent dialog or simply dismiss.
3003 private void showPageInfo(final Tab tab,
3004 final boolean fromShowSSLCertificateOnError) {
3005 final LayoutInflater factory = LayoutInflater
3008 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3010 final WebView view = tab.getWebView();
3013 String title = null;
3017 title = tab.getTitle();
3018 } else if (view == mTabControl.getCurrentWebView()) {
3019 // Use the cached title and url if this is the current WebView
3023 url = view.getUrl();
3024 title = view.getTitle();
3030 if (title == null) {
3034 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3035 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3037 mPageInfoView = tab;
3038 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3040 AlertDialog.Builder alertDialogBuilder =
3041 new AlertDialog.Builder(this)
3042 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3043 .setView(pageInfoView)
3046 new DialogInterface.OnClickListener() {
3047 public void onClick(DialogInterface dialog,
3049 mPageInfoDialog = null;
3050 mPageInfoView = null;
3052 // if we came here from the SSL error dialog
3053 if (fromShowSSLCertificateOnError) {
3054 // go back to the SSL error dialog
3055 showSSLCertificateOnError(
3056 mSSLCertificateOnErrorView,
3057 mSSLCertificateOnErrorHandler,
3058 mSSLCertificateOnErrorError);
3062 .setOnCancelListener(
3063 new DialogInterface.OnCancelListener() {
3064 public void onCancel(DialogInterface dialog) {
3065 mPageInfoDialog = null;
3066 mPageInfoView = null;
3068 // if we came here from the SSL error dialog
3069 if (fromShowSSLCertificateOnError) {
3070 // go back to the SSL error dialog
3071 showSSLCertificateOnError(
3072 mSSLCertificateOnErrorView,
3073 mSSLCertificateOnErrorHandler,
3074 mSSLCertificateOnErrorError);
3079 // if we have a main top-level page SSL certificate set or a certificate
3081 if (fromShowSSLCertificateOnError ||
3082 (view != null && view.getCertificate() != null)) {
3083 // add a 'View Certificate' button
3084 alertDialogBuilder.setNeutralButton(
3085 R.string.view_certificate,
3086 new DialogInterface.OnClickListener() {
3087 public void onClick(DialogInterface dialog,
3089 mPageInfoDialog = null;
3090 mPageInfoView = null;
3092 // if we came here from the SSL error dialog
3093 if (fromShowSSLCertificateOnError) {
3094 // go back to the SSL error dialog
3095 showSSLCertificateOnError(
3096 mSSLCertificateOnErrorView,
3097 mSSLCertificateOnErrorHandler,
3098 mSSLCertificateOnErrorError);
3100 // otherwise, display the top-most certificate from
3102 if (view.getCertificate() != null) {
3103 showSSLCertificate(tab);
3110 mPageInfoDialog = alertDialogBuilder.show();
3114 * Displays the main top-level page SSL certificate dialog
3115 * (accessible from the Page-Info dialog).
3116 * @param tab The tab to show certificate for.
3118 private void showSSLCertificate(final Tab tab) {
3119 final View certificateView =
3120 inflateCertificateView(tab.getWebView().getCertificate());
3121 if (certificateView == null) {
3125 LayoutInflater factory = LayoutInflater.from(this);
3127 final LinearLayout placeholder =
3128 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3130 LinearLayout ll = (LinearLayout) factory.inflate(
3131 R.layout.ssl_success, placeholder);
3132 ((TextView)ll.findViewById(R.id.success))
3133 .setText(R.string.ssl_certificate_is_valid);
3135 mSSLCertificateView = tab;
3136 mSSLCertificateDialog =
3137 new AlertDialog.Builder(this)
3138 .setTitle(R.string.ssl_certificate).setIcon(
3139 R.drawable.ic_dialog_browser_certificate_secure)
3140 .setView(certificateView)
3141 .setPositiveButton(R.string.ok,
3142 new DialogInterface.OnClickListener() {
3143 public void onClick(DialogInterface dialog,
3145 mSSLCertificateDialog = null;
3146 mSSLCertificateView = null;
3148 showPageInfo(tab, false);
3151 .setOnCancelListener(
3152 new DialogInterface.OnCancelListener() {
3153 public void onCancel(DialogInterface dialog) {
3154 mSSLCertificateDialog = null;
3155 mSSLCertificateView = null;
3157 showPageInfo(tab, false);
3164 * Displays the SSL error certificate dialog.
3165 * @param view The target web-view.
3166 * @param handler The SSL error handler responsible for cancelling the
3167 * connection that resulted in an SSL error or proceeding per user request.
3168 * @param error The SSL error object.
3170 void showSSLCertificateOnError(
3171 final WebView view, final SslErrorHandler handler, final SslError error) {
3173 final View certificateView =
3174 inflateCertificateView(error.getCertificate());
3175 if (certificateView == null) {
3179 LayoutInflater factory = LayoutInflater.from(this);
3181 final LinearLayout placeholder =
3182 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3184 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3185 LinearLayout ll = (LinearLayout)factory
3186 .inflate(R.layout.ssl_warning, placeholder);
3187 ((TextView)ll.findViewById(R.id.warning))
3188 .setText(R.string.ssl_untrusted);
3191 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3192 LinearLayout ll = (LinearLayout)factory
3193 .inflate(R.layout.ssl_warning, placeholder);
3194 ((TextView)ll.findViewById(R.id.warning))
3195 .setText(R.string.ssl_mismatch);
3198 if (error.hasError(SslError.SSL_EXPIRED)) {
3199 LinearLayout ll = (LinearLayout)factory
3200 .inflate(R.layout.ssl_warning, placeholder);
3201 ((TextView)ll.findViewById(R.id.warning))
3202 .setText(R.string.ssl_expired);
3205 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3206 LinearLayout ll = (LinearLayout)factory
3207 .inflate(R.layout.ssl_warning, placeholder);
3208 ((TextView)ll.findViewById(R.id.warning))
3209 .setText(R.string.ssl_not_yet_valid);
3212 mSSLCertificateOnErrorHandler = handler;
3213 mSSLCertificateOnErrorView = view;
3214 mSSLCertificateOnErrorError = error;
3215 mSSLCertificateOnErrorDialog =
3216 new AlertDialog.Builder(this)
3217 .setTitle(R.string.ssl_certificate).setIcon(
3218 R.drawable.ic_dialog_browser_certificate_partially_secure)
3219 .setView(certificateView)
3220 .setPositiveButton(R.string.ok,
3221 new DialogInterface.OnClickListener() {
3222 public void onClick(DialogInterface dialog,
3224 mSSLCertificateOnErrorDialog = null;
3225 mSSLCertificateOnErrorView = null;
3226 mSSLCertificateOnErrorHandler = null;
3227 mSSLCertificateOnErrorError = null;
3229 view.getWebViewClient().onReceivedSslError(
3230 view, handler, error);
3233 .setNeutralButton(R.string.page_info_view,
3234 new DialogInterface.OnClickListener() {
3235 public void onClick(DialogInterface dialog,
3237 mSSLCertificateOnErrorDialog = null;
3239 // do not clear the dialog state: we will
3240 // need to show the dialog again once the
3241 // user is done exploring the page-info details
3243 showPageInfo(mTabControl.getTabFromView(view),
3247 .setOnCancelListener(
3248 new DialogInterface.OnCancelListener() {
3249 public void onCancel(DialogInterface dialog) {
3250 mSSLCertificateOnErrorDialog = null;
3251 mSSLCertificateOnErrorView = null;
3252 mSSLCertificateOnErrorHandler = null;
3253 mSSLCertificateOnErrorError = null;
3255 view.getWebViewClient().onReceivedSslError(
3256 view, handler, error);
3263 * Inflates the SSL certificate view (helper method).
3264 * @param certificate The SSL certificate.
3265 * @return The resultant certificate view with issued-to, issued-by,
3266 * issued-on, expires-on, and possibly other fields set.
3267 * If the input certificate is null, returns null.
3269 private View inflateCertificateView(SslCertificate certificate) {
3270 if (certificate == null) {
3274 LayoutInflater factory = LayoutInflater.from(this);
3276 View certificateView = factory.inflate(
3277 R.layout.ssl_certificate, null);
3280 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3281 if (issuedTo != null) {
3282 ((TextView) certificateView.findViewById(R.id.to_common))
3283 .setText(issuedTo.getCName());
3284 ((TextView) certificateView.findViewById(R.id.to_org))
3285 .setText(issuedTo.getOName());
3286 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3287 .setText(issuedTo.getUName());
3291 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3292 if (issuedBy != null) {
3293 ((TextView) certificateView.findViewById(R.id.by_common))
3294 .setText(issuedBy.getCName());
3295 ((TextView) certificateView.findViewById(R.id.by_org))
3296 .setText(issuedBy.getOName());
3297 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3298 .setText(issuedBy.getUName());
3302 String issuedOn = reformatCertificateDate(
3303 certificate.getValidNotBefore());
3304 ((TextView) certificateView.findViewById(R.id.issued_on))
3308 String expiresOn = reformatCertificateDate(
3309 certificate.getValidNotAfter());
3310 ((TextView) certificateView.findViewById(R.id.expires_on))
3311 .setText(expiresOn);
3313 return certificateView;
3317 * Re-formats the certificate date (Date.toString()) string to
3318 * a properly localized date string.
3319 * @return Properly localized version of the certificate date string and
3320 * the original certificate date string if fails to localize.
3321 * If the original string is null, returns an empty string "".
3323 private String reformatCertificateDate(String certificateDate) {
3324 String reformattedDate = null;
3326 if (certificateDate != null) {
3329 date = java.text.DateFormat.getInstance().parse(certificateDate);
3330 } catch (ParseException e) {
3336 DateFormat.getDateFormat(this).format(date);
3340 return reformattedDate != null ? reformattedDate :
3341 (certificateDate != null ? certificateDate : "");
3345 * Displays an http-authentication dialog.
3347 void showHttpAuthentication(final HttpAuthHandler handler,
3348 final String host, final String realm, final String title,
3349 final String name, final String password, int focusId) {
3350 LayoutInflater factory = LayoutInflater.from(this);
3351 final View v = factory
3352 .inflate(R.layout.http_authentication, null);
3354 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3356 if (password != null) {
3357 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3360 String titleText = title;
3361 if (titleText == null) {
3362 titleText = getText(R.string.sign_in_to).toString().replace(
3363 "%s1", host).replace("%s2", realm);
3366 mHttpAuthHandler = handler;
3367 AlertDialog dialog = new AlertDialog.Builder(this)
3368 .setTitle(titleText)
3369 .setIcon(android.R.drawable.ic_dialog_alert)
3371 .setPositiveButton(R.string.action,
3372 new DialogInterface.OnClickListener() {
3373 public void onClick(DialogInterface dialog,
3375 String nm = ((EditText) v
3376 .findViewById(R.id.username_edit))
3377 .getText().toString();
3378 String pw = ((EditText) v
3379 .findViewById(R.id.password_edit))
3380 .getText().toString();
3381 BrowserActivity.this.setHttpAuthUsernamePassword
3382 (host, realm, nm, pw);
3383 handler.proceed(nm, pw);
3384 mHttpAuthenticationDialog = null;
3385 mHttpAuthHandler = null;
3387 .setNegativeButton(R.string.cancel,
3388 new DialogInterface.OnClickListener() {
3389 public void onClick(DialogInterface dialog,
3392 BrowserActivity.this.resetTitleAndRevertLockIcon();
3393 mHttpAuthenticationDialog = null;
3394 mHttpAuthHandler = null;
3396 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3397 public void onCancel(DialogInterface dialog) {
3399 BrowserActivity.this.resetTitleAndRevertLockIcon();
3400 mHttpAuthenticationDialog = null;
3401 mHttpAuthHandler = null;
3404 // Make the IME appear when the dialog is displayed if applicable.
3405 dialog.getWindow().setSoftInputMode(
3406 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3409 dialog.findViewById(focusId).requestFocus();
3411 v.findViewById(R.id.username_edit).requestFocus();
3413 mHttpAuthenticationDialog = dialog;
3416 public int getProgress() {
3417 WebView w = mTabControl.getCurrentWebView();
3419 return w.getProgress();
3426 * Set HTTP authentication password.
3428 * @param host The host for the password
3429 * @param realm The realm for the password
3430 * @param username The username for the password. If it is null, it means
3431 * password can't be saved.
3432 * @param password The password
3434 public void setHttpAuthUsernamePassword(String host, String realm,
3437 WebView w = mTabControl.getCurrentWebView();
3439 w.setHttpAuthUsernamePassword(host, realm, username, password);
3444 * connectivity manager says net has come or gone... inform the user
3445 * @param up true if net has come up, false if net has gone down
3447 public void onNetworkToggle(boolean up) {
3448 if (up == mIsNetworkUp) {
3451 mIsNetworkUp = true;
3452 if (mAlertDialog != null) {
3453 mAlertDialog.cancel();
3454 mAlertDialog = null;
3457 mIsNetworkUp = false;
3459 createAndShowNetworkDialog();
3462 WebView w = mTabControl.getCurrentWebView();
3464 w.setNetworkAvailable(up);
3468 boolean isNetworkUp() {
3469 return mIsNetworkUp;
3472 // This method shows the network dialog alerting the user that the net is
3473 // down. It will only show the dialog if mAlertDialog is null.
3474 private void createAndShowNetworkDialog() {
3475 if (mAlertDialog == null) {
3476 mAlertDialog = new AlertDialog.Builder(this)
3477 .setTitle(R.string.loadSuspendedTitle)
3478 .setMessage(R.string.loadSuspended)
3479 .setPositiveButton(R.string.ok, null)
3485 protected void onActivityResult(int requestCode, int resultCode,
3487 if (getTopWindow() == null) return;
3489 switch (requestCode) {
3491 if (resultCode == RESULT_OK && intent != null) {
3492 String data = intent.getAction();
3493 Bundle extras = intent.getExtras();
3494 if (extras != null && extras.getBoolean("new_window", false)) {
3497 final Tab currentTab =
3498 mTabControl.getCurrentTab();
3499 dismissSubWindow(currentTab);
3500 if (data != null && data.length() != 0) {
3501 getTopWindow().loadUrl(data);
3505 // Deliberately fall through to PREFERENCES_PAGE, since the
3506 // same extra may be attached to the COMBO_PAGE
3507 case PREFERENCES_PAGE:
3508 if (resultCode == RESULT_OK && intent != null) {
3509 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3510 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3511 mTabControl.removeParentChildRelationShips();
3515 // Choose a file from the file picker.
3517 if (null == mUploadMessage) break;
3518 Uri result = intent == null || resultCode != RESULT_OK ? null
3520 mUploadMessage.onReceiveValue(result);
3521 mUploadMessage = null;
3526 getTopWindow().requestFocus();
3530 * This method is called as a result of the user selecting the options
3531 * menu to see the download window. It shows the download window on top of
3532 * the current window.
3534 private void viewDownloads(Uri downloadRecord) {
3535 Intent intent = new Intent(this,
3536 BrowserDownloadPage.class);
3537 intent.setData(downloadRecord);
3538 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3544 * @param startWithHistory If true, open starting on the history tab.
3545 * Otherwise, start with the bookmarks tab.
3547 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3548 WebView current = mTabControl.getCurrentWebView();
3549 if (current == null) {
3552 Intent intent = new Intent(this,
3553 CombinedBookmarkHistoryActivity.class);
3554 String title = current.getTitle();
3555 String url = current.getUrl();
3556 Bitmap thumbnail = createScreenshot(current);
3558 // Just in case the user opens bookmarks before a page finishes loading
3559 // so the current history item, and therefore the page, is null.
3561 url = mLastEnteredUrl;
3564 url = mSettings.getHomePage();
3567 // In case the web page has not yet received its associated title.
3568 if (title == null) {
3571 intent.putExtra("title", title);
3572 intent.putExtra("url", url);
3573 intent.putExtra("thumbnail", thumbnail);
3574 // Disable opening in a new window if we have maxed out the windows
3575 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3576 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3577 if (startWithHistory) {
3578 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3579 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3581 startActivityForResult(intent, COMBO_PAGE);
3584 // Called when loading from context menu or LOAD_URL message
3585 private void loadURL(WebView view, String url) {
3586 // In case the user enters nothing.
3587 if (url != null && url.length() != 0 && view != null) {
3588 url = smartUrlFilter(url);
3589 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3595 private String smartUrlFilter(Uri inUri) {
3596 if (inUri != null) {
3597 return smartUrlFilter(inUri.toString());
3602 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3603 "(?i)" + // switch on case insensitive matching
3604 "(" + // begin group for schema
3605 "(?:http|https|file):\\/\\/" +
3606 "|(?:inline|data|about|content|javascript):" +
3611 * Attempts to determine whether user input is a URL or search
3612 * terms. Anything with a space is passed to search.
3614 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3615 * "Http://" converts to "http://"
3617 * @return Original or modified URL
3620 String smartUrlFilter(String url) {
3622 String inUrl = url.trim();
3623 boolean hasSpace = inUrl.indexOf(' ') != -1;
3625 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3626 if (matcher.matches()) {
3627 // force scheme to lowercase
3628 String scheme = matcher.group(1);
3629 String lcScheme = scheme.toLowerCase();
3630 if (!lcScheme.equals(scheme)) {
3631 inUrl = lcScheme + matcher.group(2);
3634 inUrl = inUrl.replace(" ", "%20");
3639 // FIXME: Is this the correct place to add to searches?
3640 // what if someone else calls this function?
3641 int shortcut = parseUrlShortcut(inUrl);
3642 if (shortcut != SHORTCUT_INVALID) {
3643 Browser.addSearchUrl(mResolver, inUrl);
3644 String query = inUrl.substring(2);
3646 case SHORTCUT_GOOGLE_SEARCH:
3647 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3648 case SHORTCUT_WIKIPEDIA_SEARCH:
3649 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3650 case SHORTCUT_DICTIONARY_SEARCH:
3651 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3652 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3653 // FIXME: we need location in this case
3654 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3658 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3659 return URLUtil.guessUrl(inUrl);
3663 Browser.addSearchUrl(mResolver, inUrl);
3664 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3667 /* package */ void setShouldShowErrorConsole(boolean flag) {
3668 if (flag == mShouldShowErrorConsole) {
3673 mShouldShowErrorConsole = flag;
3675 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3676 .getErrorConsole(true);
3679 // Setting the show state of the console will cause it's the layout to be inflated.
3680 if (errorConsole.numberOfErrors() > 0) {
3681 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3683 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3686 // Now we can add it to the main view.
3687 mErrorConsoleContainer.addView(errorConsole,
3688 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3689 ViewGroup.LayoutParams.WRAP_CONTENT));
3691 mErrorConsoleContainer.removeView(errorConsole);
3696 boolean shouldShowErrorConsole() {
3697 return mShouldShowErrorConsole;
3700 private void setStatusBarVisibility(boolean visible) {
3701 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3702 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3706 private void sendNetworkType(String type, String subtype) {
3707 WebView w = mTabControl.getCurrentWebView();
3709 w.setNetworkType(type, subtype);
3713 final static int LOCK_ICON_UNSECURE = 0;
3714 final static int LOCK_ICON_SECURE = 1;
3715 final static int LOCK_ICON_MIXED = 2;
3717 private BrowserSettings mSettings;
3718 private TabControl mTabControl;
3719 private ContentResolver mResolver;
3720 private FrameLayout mContentView;
3721 private View mCustomView;
3722 private FrameLayout mCustomViewContainer;
3723 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3725 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3726 // view, we should rewrite this.
3727 private int mCurrentMenuState = 0;
3728 private int mMenuState = R.id.MAIN_MENU;
3729 private int mOldMenuState = EMPTY_MENU;
3730 private static final int EMPTY_MENU = -1;
3733 private FindDialog mFindDialog;
3734 // Used to prevent chording to result in firing two shortcuts immediately
3735 // one after another. Fixes bug 1211714.
3738 private boolean mInLoad;
3739 private boolean mIsNetworkUp;
3740 private boolean mDidStopLoad;
3742 private boolean mActivityInPause = true;
3744 private boolean mMenuIsDown;
3746 private static boolean mInTrace;
3748 // Performance probe
3749 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3750 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3751 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3752 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3753 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3754 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3755 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3756 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3757 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3760 private long mStart;
3761 private long mProcessStart;
3762 private long mUserStart;
3763 private long mSystemStart;
3764 private long mIdleStart;
3765 private long mIrqStart;
3767 private long mUiStart;
3769 private Drawable mMixLockIcon;
3770 private Drawable mSecLockIcon;
3772 /* hold a ref so we can auto-cancel if necessary */
3773 private AlertDialog mAlertDialog;
3775 // Wait for credentials before loading google.com
3776 private ProgressDialog mCredsDlg;
3778 // The up-to-date URL and title (these can be different from those stored
3779 // in WebView, since it takes some time for the information in WebView to
3781 private String mUrl;
3782 private String mTitle;
3784 // As PageInfo has different style for landscape / portrait, we have
3785 // to re-open it when configuration changed
3786 private AlertDialog mPageInfoDialog;
3787 private Tab mPageInfoView;
3788 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3789 // dialog, we should not just dismiss it, but should get back to the
3790 // SSL-certificate-on-error dialog. This flag is used to store this state
3791 private boolean mPageInfoFromShowSSLCertificateOnError;
3793 // as SSLCertificateOnError has different style for landscape / portrait,
3794 // we have to re-open it when configuration changed
3795 private AlertDialog mSSLCertificateOnErrorDialog;
3796 private WebView mSSLCertificateOnErrorView;
3797 private SslErrorHandler mSSLCertificateOnErrorHandler;
3798 private SslError mSSLCertificateOnErrorError;
3800 // as SSLCertificate has different style for landscape / portrait, we
3801 // have to re-open it when configuration changed
3802 private AlertDialog mSSLCertificateDialog;
3803 private Tab mSSLCertificateView;
3805 // as HttpAuthentication has different style for landscape / portrait, we
3806 // have to re-open it when configuration changed
3807 private AlertDialog mHttpAuthenticationDialog;
3808 private HttpAuthHandler mHttpAuthHandler;
3810 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3811 new FrameLayout.LayoutParams(
3812 ViewGroup.LayoutParams.MATCH_PARENT,
3813 ViewGroup.LayoutParams.MATCH_PARENT);
3814 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3815 new FrameLayout.LayoutParams(
3816 ViewGroup.LayoutParams.MATCH_PARENT,
3817 ViewGroup.LayoutParams.MATCH_PARENT,
3820 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3822 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3823 // Dictionary search
3824 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3825 // Google Mobile Local search
3826 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3828 final static String QUERY_PLACE_HOLDER = "%s";
3830 // "source" parameter for Google search through search key
3831 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3832 // "source" parameter for Google search through goto menu
3833 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3834 // "source" parameter for Google search through simplily type
3835 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3836 // "source" parameter for Google search suggested by the browser
3837 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3838 // "source" parameter for Google search from unknown source
3839 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3841 private final static String LOGTAG = "browser";
3843 private String mLastEnteredUrl;
3845 private PowerManager.WakeLock mWakeLock;
3846 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3848 private Toast mStopToast;
3850 private TitleBar mTitleBar;
3852 private LinearLayout mErrorConsoleContainer = null;
3853 private boolean mShouldShowErrorConsole = false;
3855 // As the ids are dynamically created, we can't guarantee that they will
3856 // be in sequence, so this static array maps ids to a window number.
3857 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3858 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3859 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3860 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3862 // monitor platform changes
3863 private IntentFilter mNetworkStateChangedFilter;
3864 private BroadcastReceiver mNetworkStateIntentReceiver;
3866 private BroadcastReceiver mPackageInstallationReceiver;
3868 // activity requestCode
3869 final static int COMBO_PAGE = 1;
3870 final static int DOWNLOAD_PAGE = 2;
3871 final static int PREFERENCES_PAGE = 3;
3872 final static int FILE_SELECTED = 4;
3874 // the default <video> poster
3875 private Bitmap mDefaultVideoPoster;
3876 // the video progress view
3877 private View mVideoProgressView;
3880 * A UrlData class to abstract how the content will be set to WebView.
3881 * This base class uses loadUrl to show the content.
3883 private static class UrlData {
3887 UrlData(String url) {
3891 void setPostData(byte[] postData) {
3892 mPostData = postData;
3896 return mUrl == null || mUrl.length() == 0;
3899 public void loadIn(WebView webView) {
3900 if (mPostData != null) {
3901 webView.postUrl(mUrl, mPostData);
3903 webView.loadUrl(mUrl);
3909 * A subclass of UrlData class that can display inlined content using
3910 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3912 private static class InlinedUrlData extends UrlData {
3913 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3916 mMimeType = mimeType;
3917 mEncoding = encoding;
3924 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
3928 public void loadIn(WebView webView) {
3929 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3933 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);