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 // enable this to test the browser in 32bit
247 getWindow().setFormat(PixelFormat.RGBX_8888);
248 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
251 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
253 mResolver = getContentResolver();
255 // If this was a web search request, pass it on to the default web
256 // search provider and finish this activity.
257 if (handleWebSearchIntent(getIntent())) {
262 mSecLockIcon = Resources.getSystem().getDrawable(
263 android.R.drawable.ic_secure);
264 mMixLockIcon = Resources.getSystem().getDrawable(
265 android.R.drawable.ic_partial_secure);
267 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
268 .findViewById(com.android.internal.R.id.content);
269 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
270 .inflate(R.layout.custom_screen, null);
271 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
273 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
274 .findViewById(R.id.error_console);
275 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
276 .findViewById(R.id.fullscreen_custom_content);
277 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
278 mTitleBar = new TitleBar(this);
279 mFakeTitleBar = new TitleBar(this);
281 // Create the tab control and our initial tab
282 mTabControl = new TabControl(this);
284 // Open the icon database and retain all the bookmark urls for favicons
285 retainIconsOnStartup();
287 // Keep a settings instance handy.
288 mSettings = BrowserSettings.getInstance();
289 mSettings.setTabControl(mTabControl);
290 mSettings.loadFromDb(this);
292 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
293 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
295 /* enables registration for changes in network status from
297 mNetworkStateChangedFilter = new IntentFilter();
298 mNetworkStateChangedFilter.addAction(
299 ConnectivityManager.CONNECTIVITY_ACTION);
300 mNetworkStateIntentReceiver = new BroadcastReceiver() {
302 public void onReceive(Context context, Intent intent) {
303 if (intent.getAction().equals(
304 ConnectivityManager.CONNECTIVITY_ACTION)) {
305 boolean noConnectivity = intent.getBooleanExtra(
306 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
307 if (!noConnectivity) {
308 NetworkInfo info = intent.getParcelableExtra(
309 ConnectivityManager.EXTRA_NETWORK_INFO);
310 String typeName = info.getTypeName();
311 String subtypeName = info.getSubtypeName();
312 sendNetworkType(typeName.toLowerCase(),
313 (subtypeName != null ? subtypeName.toLowerCase() : ""));
315 onNetworkToggle(!noConnectivity);
320 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
321 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
322 filter.addDataScheme("package");
323 mPackageInstallationReceiver = new BroadcastReceiver() {
325 public void onReceive(Context context, Intent intent) {
326 final String action = intent.getAction();
327 final String packageName = intent.getData()
328 .getSchemeSpecificPart();
329 final boolean replacing = intent.getBooleanExtra(
330 Intent.EXTRA_REPLACING, false);
331 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
332 // if it is replacing, refreshPlugins() when adding
335 PackageManager pm = BrowserActivity.this.getPackageManager();
336 PackageInfo pkgInfo = null;
338 pkgInfo = pm.getPackageInfo(packageName,
339 PackageManager.GET_PERMISSIONS);
340 } catch (PackageManager.NameNotFoundException e) {
343 if (pkgInfo != null) {
344 String permissions[] = pkgInfo.requestedPermissions;
345 if (permissions == null) {
348 boolean permissionOk = false;
349 for (String permit : permissions) {
350 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
356 PluginManager.getInstance(BrowserActivity.this)
358 Intent.ACTION_PACKAGE_ADDED
364 registerReceiver(mPackageInstallationReceiver, filter);
366 if (!mTabControl.restoreState(icicle)) {
367 // clear up the thumbnail directory if we can't restore the state as
368 // none of the files in the directory are referenced any more.
369 new ClearThumbnails().execute(
370 mTabControl.getThumbnailDir().listFiles());
371 // there is no quit on Android. But if we can't restore the state,
372 // we can treat it as a new Browser, remove the old session cookies.
373 CookieManager.getInstance().removeSessionCookie();
374 final Intent intent = getIntent();
375 final Bundle extra = intent.getExtras();
376 // Create an initial tab.
377 // If the intent is ACTION_VIEW and data is not null, the Browser is
378 // invoked to view the content by another application. In this case,
379 // the tab will be close when exit.
380 UrlData urlData = getUrlDataFromIntent(intent);
382 final Tab t = mTabControl.createNewTab(
383 Intent.ACTION_VIEW.equals(intent.getAction()) &&
384 intent.getData() != null,
385 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
386 mTabControl.setCurrentTab(t);
387 attachTabToContentView(t);
388 WebView webView = t.getWebView();
390 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
391 if (scale > 0 && scale <= 1000) {
392 webView.setInitialScale(scale);
395 // If we are not restoring from an icicle, then there is a high
396 // likely hood this is the first run. So, check to see if the
397 // homepage needs to be configured and copy any plugins from our
398 // asset directory to the data partition.
399 if ((extra == null || !extra.getBoolean("testing"))
400 && !mSettings.isLoginInitialized()) {
401 startReadOfGoogleAccounts();
404 if (urlData.isEmpty()) {
405 if (mSettings.isLoginInitialized()) {
406 webView.loadUrl(mSettings.getHomePage());
408 waitForCredentials();
412 urlData.setPostData(extra
413 .getByteArray(Browser.EXTRA_POST_DATA));
415 urlData.loadIn(webView);
418 // TabControl.restoreState() will create a new tab even if
419 // restoring the state fails.
420 attachTabToContentView(mTabControl.getCurrentTab());
423 // Read JavaScript flags if it exists.
424 String jsFlags = mSettings.getJsFlags();
425 if (jsFlags.trim().length() != 0) {
426 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
431 protected void onNewIntent(Intent intent) {
432 Tab current = mTabControl.getCurrentTab();
433 // When a tab is closed on exit, the current tab index is set to -1.
434 // Reset before proceed as Browser requires the current tab to be set.
435 if (current == null) {
436 // Try to reset the tab in case the index was incorrect.
437 current = mTabControl.getTab(0);
438 if (current == null) {
439 // No tabs at all so just ignore this intent.
442 mTabControl.setCurrentTab(current);
443 attachTabToContentView(current);
444 resetTitleAndIcon(current.getWebView());
446 final String action = intent.getAction();
447 final int flags = intent.getFlags();
448 if (Intent.ACTION_MAIN.equals(action) ||
449 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
450 // just resume the browser
453 if (Intent.ACTION_VIEW.equals(action)
454 || Intent.ACTION_SEARCH.equals(action)
455 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
456 || Intent.ACTION_WEB_SEARCH.equals(action)) {
457 // If this was a search request (e.g. search query directly typed into the address bar),
458 // pass it on to the default web search provider.
459 if (handleWebSearchIntent(intent)) {
463 UrlData urlData = getUrlDataFromIntent(intent);
464 if (urlData.isEmpty()) {
465 urlData = new UrlData(mSettings.getHomePage());
467 urlData.setPostData(intent
468 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
470 final String appId = intent
471 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
472 if (Intent.ACTION_VIEW.equals(action)
473 && !getPackageName().equals(appId)
474 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
475 Tab appTab = mTabControl.getTabFromId(appId);
476 if (appTab != null) {
477 Log.i(LOGTAG, "Reusing tab for " + appId);
478 // Dismiss the subwindow if applicable.
479 dismissSubWindow(appTab);
480 // Since we might kill the WebView, remove it from the
481 // content view first.
482 removeTabFromContentView(appTab);
483 // Recreate the main WebView after destroying the old one.
484 // If the WebView has the same original url and is on that
485 // page, it can be reused.
487 mTabControl.recreateWebView(appTab, urlData.mUrl);
489 if (current != appTab) {
490 switchToTab(mTabControl.getTabIndex(appTab));
492 urlData.loadIn(appTab.getWebView());
495 // If the tab was the current tab, we have to attach
496 // it to the view system again.
497 attachTabToContentView(appTab);
499 urlData.loadIn(appTab.getWebView());
504 // No matching application tab, try to find a regular tab
505 // with a matching url.
506 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
507 if (appTab != null) {
508 if (current != appTab) {
509 switchToTab(mTabControl.getTabIndex(appTab));
511 // Otherwise, we are already viewing the correct tab.
513 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
514 // will be opened in a new tab unless we have reached
515 // MAX_TABS. Then the url will be opened in the current
516 // tab. If a new tab is created, it will have "true" for
518 openTabAndShow(urlData, true, appId);
522 if (!urlData.isEmpty()
523 && urlData.mUrl.startsWith("about:debug")) {
524 if ("about:debug.dom".equals(urlData.mUrl)) {
525 current.getWebView().dumpDomTree(false);
526 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
527 current.getWebView().dumpDomTree(true);
528 } else if ("about:debug.render".equals(urlData.mUrl)) {
529 current.getWebView().dumpRenderTree(false);
530 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
531 current.getWebView().dumpRenderTree(true);
532 } else if ("about:debug.display".equals(urlData.mUrl)) {
533 current.getWebView().dumpDisplayTree();
534 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
535 int index = urlData.mUrl.codePointAt(16) - '0';
536 if (index <= 0 || index > 9) {
537 current.getWebView().setDragTracker(null);
539 current.getWebView().setDragTracker(new MeshTracker(index));
542 mSettings.toggleDebugSettings();
546 // Get rid of the subwindow if it exists
547 dismissSubWindow(current);
548 urlData.loadIn(current.getWebView());
553 private int parseUrlShortcut(String url) {
554 if (url == null) return SHORTCUT_INVALID;
556 // FIXME: quick search, need to be customized by setting
557 if (url.length() > 2 && url.charAt(1) == ' ') {
558 switch (url.charAt(0)) {
559 case 'g': return SHORTCUT_GOOGLE_SEARCH;
560 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
561 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
562 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
565 return SHORTCUT_INVALID;
569 * Launches the default web search activity with the query parameters if the given intent's data
570 * are identified as plain search terms and not URLs/shortcuts.
571 * @return true if the intent was handled and web search activity was launched, false if not.
573 private boolean handleWebSearchIntent(Intent intent) {
574 if (intent == null) return false;
577 final String action = intent.getAction();
578 if (Intent.ACTION_VIEW.equals(action)) {
579 Uri data = intent.getData();
580 if (data != null) url = data.toString();
581 } else if (Intent.ACTION_SEARCH.equals(action)
582 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
583 || Intent.ACTION_WEB_SEARCH.equals(action)) {
584 url = intent.getStringExtra(SearchManager.QUERY);
586 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
587 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
591 * Launches the default web search activity with the query parameters if the given url string
592 * was identified as plain search terms and not URL/shortcut.
593 * @return true if the request was handled and web search activity was launched, false if not.
595 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
596 if (inUrl == null) return false;
598 // In general, we shouldn't modify URL from Intent.
599 // But currently, we get the user-typed URL from search box as well.
600 String url = fixUrl(inUrl).trim();
602 // URLs and site specific search shortcuts are handled by the regular flow of control, so
604 if (Patterns.WEB_URL.matcher(url).matches()
605 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
606 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
610 Browser.updateVisitedHistory(mResolver, url, false);
611 Browser.addSearchUrl(mResolver, url);
613 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
614 intent.addCategory(Intent.CATEGORY_DEFAULT);
615 intent.putExtra(SearchManager.QUERY, url);
616 if (appData != null) {
617 intent.putExtra(SearchManager.APP_DATA, appData);
619 if (extraData != null) {
620 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
622 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
623 startActivity(intent);
628 private UrlData getUrlDataFromIntent(Intent intent) {
630 if (intent != null) {
631 final String action = intent.getAction();
632 if (Intent.ACTION_VIEW.equals(action)) {
633 url = smartUrlFilter(intent.getData());
634 if (url != null && url.startsWith("content:")) {
635 /* Append mimetype so webview knows how to display */
636 String mimeType = intent.resolveType(getContentResolver());
637 if (mimeType != null) {
638 url += "?" + mimeType;
641 if ("inline:".equals(url)) {
642 return new InlinedUrlData(
643 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
645 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
646 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
648 } else if (Intent.ACTION_SEARCH.equals(action)
649 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
650 || Intent.ACTION_WEB_SEARCH.equals(action)) {
651 url = intent.getStringExtra(SearchManager.QUERY);
653 mLastEnteredUrl = url;
654 Browser.updateVisitedHistory(mResolver, url, false);
655 // In general, we shouldn't modify URL from Intent.
656 // But currently, we get the user-typed URL from search box as well.
658 url = smartUrlFilter(url);
659 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
660 if (url.contains(searchSource)) {
661 String source = null;
662 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
663 if (appData != null) {
664 source = appData.getString(SearchManager.SOURCE);
666 if (TextUtils.isEmpty(source)) {
667 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
669 url = url.replace(searchSource, "&source=android-"+source+"&");
674 return new UrlData(url);
677 /* package */ static String fixUrl(String inUrl) {
678 // FIXME: Converting the url to lower case
679 // duplicates functionality in smartUrlFilter().
680 // However, changing all current callers of fixUrl to
681 // call smartUrlFilter in addition may have unwanted
682 // consequences, and is deferred for now.
683 int colon = inUrl.indexOf(':');
684 boolean allLower = true;
685 for (int index = 0; index < colon; index++) {
686 char ch = inUrl.charAt(index);
687 if (!Character.isLetter(ch)) {
690 allLower &= Character.isLowerCase(ch);
691 if (index == colon - 1 && !allLower) {
692 inUrl = inUrl.substring(0, colon).toLowerCase()
693 + inUrl.substring(colon);
696 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
698 if (inUrl.startsWith("http:") ||
699 inUrl.startsWith("https:")) {
700 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
701 inUrl = inUrl.replaceFirst("/", "//");
702 } else inUrl = inUrl.replaceFirst(":", "://");
708 protected void onResume() {
711 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
714 if (!mActivityInPause) {
715 Log.e(LOGTAG, "BrowserActivity is already resumed.");
719 mTabControl.resumeCurrentTab();
720 mActivityInPause = false;
721 resumeWebViewTimers();
723 if (mWakeLock.isHeld()) {
724 mHandler.removeMessages(RELEASE_WAKELOCK);
728 if (mCredsDlg != null) {
729 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
730 // In case credential request never comes back
731 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
735 registerReceiver(mNetworkStateIntentReceiver,
736 mNetworkStateChangedFilter);
737 WebView.enablePlatformNotifications();
741 * Since the actual title bar is embedded in the WebView, and removing it
742 * would change its appearance, use a different TitleBar to show overlayed
743 * at the top of the screen, when the menu is open or the page is loading.
745 private TitleBar mFakeTitleBar;
748 * Holder for the fake title bar. It will have a foreground shadow, as well
749 * as a white background, so the fake title bar looks like the real one.
751 private ViewGroup mFakeTitleBarHolder;
754 * Layout parameters for the fake title bar within mFakeTitleBarHolder
756 private FrameLayout.LayoutParams mFakeTitleBarParams
757 = new FrameLayout.LayoutParams(
758 ViewGroup.LayoutParams.MATCH_PARENT,
759 ViewGroup.LayoutParams.WRAP_CONTENT);
761 * Keeps track of whether the options menu is open. This is important in
762 * determining whether to show or hide the title bar overlay.
764 private boolean mOptionsMenuOpen;
767 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
768 * of whether the configuration has changed. The first onMenuOpened call
769 * after a configuration change is simply a reopening of the same menu
770 * (i.e. mIconView did not change).
772 private boolean mConfigChanged;
775 * Whether or not the options menu is in its smaller, icon menu form. When
776 * true, we want the title bar overlay to be up. When false, we do not.
777 * Only meaningful if mOptionsMenuOpen is true.
779 private boolean mIconView;
782 public boolean onMenuOpened(int featureId, Menu menu) {
783 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
784 if (mOptionsMenuOpen) {
785 if (mConfigChanged) {
786 // We do not need to make any changes to the state of the
787 // title bar, since the only thing that happened was a
788 // change in orientation
789 mConfigChanged = false;
792 // Switching the menu to expanded view, so hide the
797 // Switching the menu back to icon view, so show the
798 // title bar once again.
804 // The options menu is closed, so open it, and show the title
806 mOptionsMenuOpen = true;
807 mConfigChanged = false;
815 * Special class used exclusively for the shadow drawn underneath the fake
816 * title bar. The shadow does not need to be drawn if the WebView
817 * underneath is scrolled to the top, because it will draw directly on top
818 * of the embedded shadow.
820 private static class Shadow extends View {
821 private WebView mWebView;
823 public Shadow(Context context, AttributeSet attrs) {
824 super(context, attrs);
827 public void setWebView(WebView view) {
832 public void draw(Canvas canvas) {
833 // In general onDraw is the method to override, but we care about
834 // whether or not the background gets drawn, which happens in draw()
835 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
838 // Need to invalidate so that if the scroll position changes, we
839 // still draw as appropriate.
844 private void showFakeTitleBar() {
845 final View decor = getWindow().peekDecorView();
846 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
847 && !mActivityInPause && decor != null
848 && decor.getWindowToken() != null) {
849 Rect visRect = new Rect();
850 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
852 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
857 WindowManager manager
858 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
860 // Add the title bar to the window manager so it can receive touches
861 // while the menu is up
862 WindowManager.LayoutParams params
863 = new WindowManager.LayoutParams(
864 ViewGroup.LayoutParams.MATCH_PARENT,
865 ViewGroup.LayoutParams.WRAP_CONTENT,
866 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
867 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
868 PixelFormat.TRANSLUCENT);
869 params.gravity = Gravity.TOP;
870 WebView mainView = mTabControl.getCurrentWebView();
871 boolean atTop = mainView != null && mainView.getScrollY() == 0;
872 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
873 // XXX : Without providing an offset, the fake title bar will be
874 // placed underneath the status bar. Use the global visible rect
875 // of mBrowserFrameLayout to determine the bottom of the status bar
876 params.y = visRect.top;
877 // Add a holder for the title bar. It also holds a shadow to show
878 // below the title bar.
879 if (mFakeTitleBarHolder == null) {
880 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
881 .inflate(R.layout.title_bar_bg, null);
883 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
885 shadow.setWebView(mainView);
886 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
887 manager.addView(mFakeTitleBarHolder, params);
892 public void onOptionsMenuClosed(Menu menu) {
893 mOptionsMenuOpen = false;
896 } else if (!mIconView) {
897 // The page is currently loading, and we are in expanded mode, so
898 // we were not showing the menu. Show it once again. It will be
899 // removed when the page finishes.
904 private void hideFakeTitleBar() {
905 if (mFakeTitleBar.getParent() == null) return;
906 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
907 mFakeTitleBarHolder.getLayoutParams();
908 WebView mainView = mTabControl.getCurrentWebView();
909 // Although we decided whether or not to animate based on the current
910 // scroll position, the scroll position may have changed since the
911 // fake title bar was displayed. Make sure it has the appropriate
912 // animation/lack thereof before removing.
913 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
914 ? 0 : R.style.TitleBar;
915 WindowManager manager
916 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
917 manager.updateViewLayout(mFakeTitleBarHolder, params);
918 mFakeTitleBarHolder.removeView(mFakeTitleBar);
919 manager.removeView(mFakeTitleBarHolder);
923 * Special method for the fake title bar to call when displaying its context
924 * menu, since it is in its own Window, and its parent does not show a
927 /* package */ void showTitleBarContextMenu() {
928 if (null == mTitleBar.getParent()) {
931 openContextMenu(mTitleBar);
935 public void onContextMenuClosed(Menu menu) {
936 super.onContextMenuClosed(menu);
943 * onSaveInstanceState(Bundle map)
944 * onSaveInstanceState is called right before onStop(). The map contains
948 protected void onSaveInstanceState(Bundle outState) {
950 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
952 // the default implementation requires each view to have an id. As the
953 // browser handles the state itself and it doesn't use id for the views,
954 // don't call the default implementation. Otherwise it will trigger the
955 // warning like this, "couldn't save which view has focus because the
956 // focused view XXX has no id".
959 mTabControl.saveState(outState);
963 protected void onPause() {
966 if (mActivityInPause) {
967 Log.e(LOGTAG, "BrowserActivity is already paused.");
971 mTabControl.pauseCurrentTab();
972 mActivityInPause = true;
973 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
975 mHandler.sendMessageDelayed(mHandler
976 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
979 // Clear the credentials toast if it is up
980 if (mCredsDlg != null && mCredsDlg.isShowing()) {
985 // FIXME: This removes the active tabs page and resets the menu to
986 // MAIN_MENU. A better solution might be to do this work in onNewIntent
987 // but then we would need to save it in onSaveInstanceState and restore
988 // it in onCreate/onRestoreInstanceState
989 if (mActiveTabsPage != null) {
990 removeActiveTabPage(true);
995 // unregister network state listener
996 unregisterReceiver(mNetworkStateIntentReceiver);
997 WebView.disablePlatformNotifications();
1001 protected void onDestroy() {
1003 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1007 if (mUploadMessage != null) {
1008 mUploadMessage.onReceiveValue(null);
1009 mUploadMessage = null;
1012 if (mTabControl == null) return;
1014 // Remove the fake title bar if it is there
1017 // Remove the current tab and sub window
1018 Tab t = mTabControl.getCurrentTab();
1020 dismissSubWindow(t);
1021 removeTabFromContentView(t);
1023 // Destroy all the tabs
1024 mTabControl.destroy();
1025 WebIconDatabase.getInstance().close();
1027 unregisterReceiver(mPackageInstallationReceiver);
1031 public void onConfigurationChanged(Configuration newConfig) {
1032 mConfigChanged = true;
1033 super.onConfigurationChanged(newConfig);
1035 if (mPageInfoDialog != null) {
1036 mPageInfoDialog.dismiss();
1039 mPageInfoFromShowSSLCertificateOnError);
1041 if (mSSLCertificateDialog != null) {
1042 mSSLCertificateDialog.dismiss();
1044 mSSLCertificateView);
1046 if (mSSLCertificateOnErrorDialog != null) {
1047 mSSLCertificateOnErrorDialog.dismiss();
1048 showSSLCertificateOnError(
1049 mSSLCertificateOnErrorView,
1050 mSSLCertificateOnErrorHandler,
1051 mSSLCertificateOnErrorError);
1053 if (mHttpAuthenticationDialog != null) {
1054 String title = ((TextView) mHttpAuthenticationDialog
1055 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1057 String name = ((TextView) mHttpAuthenticationDialog
1058 .findViewById(R.id.username_edit)).getText().toString();
1059 String password = ((TextView) mHttpAuthenticationDialog
1060 .findViewById(R.id.password_edit)).getText().toString();
1061 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1063 mHttpAuthenticationDialog.dismiss();
1064 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1065 name, password, focusId);
1070 public void onLowMemory() {
1071 super.onLowMemory();
1072 mTabControl.freeMemory();
1075 private boolean resumeWebViewTimers() {
1076 Tab tab = mTabControl.getCurrentTab();
1077 boolean inLoad = tab.inLoad();
1078 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1079 CookieSyncManager.getInstance().startSync();
1080 WebView w = tab.getWebView();
1090 private boolean pauseWebViewTimers() {
1091 Tab tab = mTabControl.getCurrentTab();
1092 boolean inLoad = tab.inLoad();
1093 if (mActivityInPause && !inLoad) {
1094 CookieSyncManager.getInstance().stopSync();
1095 WebView w = mTabControl.getCurrentWebView();
1105 // FIXME: Do we want to call this when loading google for the first time?
1107 * This function is called when we are launching for the first time. We
1108 * are waiting for the login credentials before loading Google home
1109 * pages. This way the user will be logged in straight away.
1111 private void waitForCredentials() {
1113 mCredsDlg = new ProgressDialog(this);
1114 mCredsDlg.setIndeterminate(true);
1115 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1116 // If the user cancels the operation, then cancel the Google
1117 // Credentials request.
1118 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1121 // We set a timeout for the retrieval of credentials in onResume()
1122 // as that is when we have freed up some CPU time to get
1123 // the login credentials.
1127 * If we have received the credentials or we have timed out and we are
1128 * showing the credentials dialog, then it is time to move on.
1130 private void resumeAfterCredentials() {
1131 if (mCredsDlg == null) {
1136 if (mCredsDlg.isShowing()) {
1137 mCredsDlg.dismiss();
1141 // Clear any pending timeout
1142 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1145 WebView w = mTabControl.getCurrentWebView();
1147 w.loadUrl(mSettings.getHomePage());
1150 // Update the settings, need to do this last as it can take a moment
1151 // to persist the settings. In the mean time we could be loading
1153 mSettings.setLoginInitialized(this);
1156 // Open the icon database and retain all the icons for visited sites.
1157 private void retainIconsOnStartup() {
1158 final WebIconDatabase db = WebIconDatabase.getInstance();
1159 db.open(getDir("icons", 0).getPath());
1161 Cursor c = Browser.getAllBookmarks(mResolver);
1162 if (!c.moveToFirst()) {
1166 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1168 String url = c.getString(urlIndex);
1169 db.retainIconForPageUrl(url);
1170 } while (c.moveToNext());
1172 } catch (IllegalStateException e) {
1173 Log.e(LOGTAG, "retainIconsOnStartup", e);
1177 // Helper method for getting the top window.
1178 WebView getTopWindow() {
1179 return mTabControl.getCurrentTopWebView();
1182 TabControl getTabControl() {
1187 public boolean onCreateOptionsMenu(Menu menu) {
1188 super.onCreateOptionsMenu(menu);
1190 MenuInflater inflater = getMenuInflater();
1191 inflater.inflate(R.menu.browser, menu);
1193 updateInLoadMenuItems();
1198 * As the menu can be open when loading state changes
1199 * we must manually update the state of the stop/reload menu
1202 private void updateInLoadMenuItems() {
1203 if (mMenu == null) {
1206 MenuItem src = mInLoad ?
1207 mMenu.findItem(R.id.stop_menu_id):
1208 mMenu.findItem(R.id.reload_menu_id);
1209 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1210 dest.setIcon(src.getIcon());
1211 dest.setTitle(src.getTitle());
1215 public boolean onContextItemSelected(MenuItem item) {
1216 // chording is not an issue with context menus, but we use the same
1217 // options selector, so set mCanChord to true so we can access them.
1219 int id = item.getItemId();
1220 boolean result = true;
1222 // For the context menu from the title bar
1223 case R.id.title_bar_copy_page_url:
1224 Tab currentTab = mTabControl.getCurrentTab();
1225 if (null == currentTab) {
1229 WebView mainView = currentTab.getWebView();
1230 if (null == mainView) {
1234 copy(mainView.getUrl());
1236 // -- Browser context menu
1237 case R.id.open_context_menu_id:
1238 case R.id.open_newtab_context_menu_id:
1239 case R.id.bookmark_context_menu_id:
1240 case R.id.save_link_context_menu_id:
1241 case R.id.share_link_context_menu_id:
1242 case R.id.copy_link_context_menu_id:
1243 final WebView webView = getTopWindow();
1244 if (null == webView) {
1248 final HashMap hrefMap = new HashMap();
1249 hrefMap.put("webview", webView);
1250 final Message msg = mHandler.obtainMessage(
1251 FOCUS_NODE_HREF, id, 0, hrefMap);
1252 webView.requestFocusNodeHref(msg);
1256 // For other context menus
1257 result = onOptionsItemSelected(item);
1263 private Bundle createGoogleSearchSourceBundle(String source) {
1264 Bundle bundle = new Bundle();
1265 bundle.putString(SearchManager.SOURCE, source);
1270 * Overriding this to insert a local information bundle
1273 public boolean onSearchRequested() {
1274 if (mOptionsMenuOpen) closeOptionsMenu();
1275 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1276 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1277 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1282 public void startSearch(String initialQuery, boolean selectInitialQuery,
1283 Bundle appSearchData, boolean globalSearch) {
1284 if (appSearchData == null) {
1285 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1287 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1291 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1292 * results in changing tabs.
1293 * @param index Index of the tab to change to, as defined by
1294 * mTabControl.getTabIndex(Tab t).
1295 * @return boolean True if we successfully switched to a different tab. If
1296 * the indexth tab is null, or if that tab is the same as
1297 * the current one, return false.
1299 /* package */ boolean switchToTab(int index) {
1300 Tab tab = mTabControl.getTab(index);
1301 Tab currentTab = mTabControl.getCurrentTab();
1302 if (tab == null || tab == currentTab) {
1305 if (currentTab != null) {
1306 // currentTab may be null if it was just removed. In that case,
1307 // we do not need to remove it
1308 removeTabFromContentView(currentTab);
1310 mTabControl.setCurrentTab(tab);
1311 attachTabToContentView(tab);
1312 resetTitleIconAndProgress();
1313 updateLockIconToLatest();
1317 /* package */ Tab openTabToHomePage() {
1318 return openTabAndShow(mSettings.getHomePage(), false, null);
1321 /* package */ void closeCurrentWindow() {
1322 final Tab current = mTabControl.getCurrentTab();
1323 if (mTabControl.getTabCount() == 1) {
1324 // This is the last tab. Open a new one, with the home
1325 // page and close the current one.
1326 openTabToHomePage();
1330 final Tab parent = current.getParentTab();
1331 int indexToShow = -1;
1332 if (parent != null) {
1333 indexToShow = mTabControl.getTabIndex(parent);
1335 final int currentIndex = mTabControl.getCurrentIndex();
1336 // Try to move to the tab to the right
1337 indexToShow = currentIndex + 1;
1338 if (indexToShow > mTabControl.getTabCount() - 1) {
1339 // Try to move to the tab to the left
1340 indexToShow = currentIndex - 1;
1343 if (switchToTab(indexToShow)) {
1349 private ActiveTabsPage mActiveTabsPage;
1352 * Remove the active tabs page.
1353 * @param needToAttach If true, the active tabs page did not attach a tab
1354 * to the content view, so we need to do that here.
1356 /* package */ void removeActiveTabPage(boolean needToAttach) {
1357 mContentView.removeView(mActiveTabsPage);
1358 mActiveTabsPage = null;
1359 mMenuState = R.id.MAIN_MENU;
1361 attachTabToContentView(mTabControl.getCurrentTab());
1363 getTopWindow().requestFocus();
1367 public boolean onOptionsItemSelected(MenuItem item) {
1369 // The user has already fired a shortcut with this hold down of the
1373 if (null == getTopWindow()) {
1377 // The shortcut action consumes the MENU. Even if it is still down,
1378 // it won't trigger the next shortcut action. In the case of the
1379 // shortcut action triggering a new activity, like Bookmarks, we
1380 // won't get onKeyUp for MENU. So it is important to reset it here.
1381 mMenuIsDown = false;
1383 switch (item.getItemId()) {
1385 case R.id.new_tab_menu_id:
1386 openTabToHomePage();
1389 case R.id.goto_menu_id:
1390 onSearchRequested();
1393 case R.id.bookmarks_menu_id:
1394 bookmarksOrHistoryPicker(false);
1397 case R.id.active_tabs_menu_id:
1398 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1399 removeTabFromContentView(mTabControl.getCurrentTab());
1401 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1402 mActiveTabsPage.requestFocus();
1403 mMenuState = EMPTY_MENU;
1406 case R.id.add_bookmark_menu_id:
1407 Intent i = new Intent(BrowserActivity.this,
1408 AddBookmarkPage.class);
1409 WebView w = getTopWindow();
1410 i.putExtra("url", w.getUrl());
1411 i.putExtra("title", w.getTitle());
1412 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1413 i.putExtra("thumbnail", createScreenshot(w));
1417 case R.id.stop_reload_menu_id:
1421 getTopWindow().reload();
1425 case R.id.back_menu_id:
1426 getTopWindow().goBack();
1429 case R.id.forward_menu_id:
1430 getTopWindow().goForward();
1433 case R.id.close_menu_id:
1434 // Close the subwindow if it exists.
1435 if (mTabControl.getCurrentSubWindow() != null) {
1436 dismissSubWindow(mTabControl.getCurrentTab());
1439 closeCurrentWindow();
1442 case R.id.homepage_menu_id:
1443 Tab current = mTabControl.getCurrentTab();
1444 if (current != null) {
1445 dismissSubWindow(current);
1446 current.getWebView().loadUrl(mSettings.getHomePage());
1450 case R.id.preferences_menu_id:
1451 Intent intent = new Intent(this,
1452 BrowserPreferencesPage.class);
1453 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1454 getTopWindow().getUrl());
1455 startActivityForResult(intent, PREFERENCES_PAGE);
1458 case R.id.find_menu_id:
1459 if (null == mFindDialog) {
1460 mFindDialog = new FindDialog(this);
1462 mFindDialog.setWebView(getTopWindow());
1464 mMenuState = EMPTY_MENU;
1467 case R.id.select_text_id:
1468 getTopWindow().emulateShiftHeld();
1470 case R.id.page_info_menu_id:
1471 showPageInfo(mTabControl.getCurrentTab(), false);
1474 case R.id.classic_history_menu_id:
1475 bookmarksOrHistoryPicker(true);
1478 case R.id.title_bar_share_page_url:
1479 case R.id.share_page_menu_id:
1480 Tab currentTab = mTabControl.getCurrentTab();
1481 if (null == currentTab) {
1485 currentTab.populatePickerData();
1486 sharePage(this, currentTab.getTitle(),
1487 currentTab.getUrl(), currentTab.getFavicon(),
1488 createScreenshot(currentTab.getWebView()));
1491 case R.id.dump_nav_menu_id:
1492 getTopWindow().debugDump();
1495 case R.id.zoom_in_menu_id:
1496 getTopWindow().zoomIn();
1499 case R.id.zoom_out_menu_id:
1500 getTopWindow().zoomOut();
1503 case R.id.view_downloads_menu_id:
1504 viewDownloads(null);
1507 case R.id.window_one_menu_id:
1508 case R.id.window_two_menu_id:
1509 case R.id.window_three_menu_id:
1510 case R.id.window_four_menu_id:
1511 case R.id.window_five_menu_id:
1512 case R.id.window_six_menu_id:
1513 case R.id.window_seven_menu_id:
1514 case R.id.window_eight_menu_id:
1516 int menuid = item.getItemId();
1517 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1518 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1519 Tab desiredTab = mTabControl.getTab(id);
1520 if (desiredTab != null &&
1521 desiredTab != mTabControl.getCurrentTab()) {
1531 if (!super.onOptionsItemSelected(item)) {
1534 // Otherwise fall through.
1540 public void closeFind() {
1541 mMenuState = R.id.MAIN_MENU;
1545 public boolean onPrepareOptionsMenu(Menu menu) {
1546 // This happens when the user begins to hold down the menu key, so
1547 // allow them to chord to get a shortcut.
1549 // Note: setVisible will decide whether an item is visible; while
1550 // setEnabled() will decide whether an item is enabled, which also means
1551 // whether the matching shortcut key will function.
1552 super.onPrepareOptionsMenu(menu);
1553 switch (mMenuState) {
1555 if (mCurrentMenuState != mMenuState) {
1556 menu.setGroupVisible(R.id.MAIN_MENU, false);
1557 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1558 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1562 if (mCurrentMenuState != mMenuState) {
1563 menu.setGroupVisible(R.id.MAIN_MENU, true);
1564 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1565 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1567 final WebView w = getTopWindow();
1568 boolean canGoBack = false;
1569 boolean canGoForward = false;
1570 boolean isHome = false;
1572 canGoBack = w.canGoBack();
1573 canGoForward = w.canGoForward();
1574 isHome = mSettings.getHomePage().equals(w.getUrl());
1576 final MenuItem back = menu.findItem(R.id.back_menu_id);
1577 back.setEnabled(canGoBack);
1579 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1580 home.setEnabled(!isHome);
1582 menu.findItem(R.id.forward_menu_id)
1583 .setEnabled(canGoForward);
1585 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1586 mTabControl.canCreateNewTab());
1588 // decide whether to show the share link option
1589 PackageManager pm = getPackageManager();
1590 Intent send = new Intent(Intent.ACTION_SEND);
1591 send.setType("text/plain");
1592 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1593 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1595 boolean isNavDump = mSettings.isNavDump();
1596 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1597 nav.setVisible(isNavDump);
1598 nav.setEnabled(isNavDump);
1601 mCurrentMenuState = mMenuState;
1606 public void onCreateContextMenu(ContextMenu menu, View v,
1607 ContextMenuInfo menuInfo) {
1608 WebView webview = (WebView) v;
1609 WebView.HitTestResult result = webview.getHitTestResult();
1610 if (result == null) {
1614 int type = result.getType();
1615 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1617 "We should not show context menu when nothing is touched");
1620 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1621 // let TextView handles context menu
1625 // Note, http://b/issue?id=1106666 is requesting that
1626 // an inflated menu can be used again. This is not available
1627 // yet, so inflate each time (yuk!)
1628 MenuInflater inflater = getMenuInflater();
1629 inflater.inflate(R.menu.browsercontext, menu);
1631 // Show the correct menu group
1632 String extra = result.getExtra();
1633 menu.setGroupVisible(R.id.PHONE_MENU,
1634 type == WebView.HitTestResult.PHONE_TYPE);
1635 menu.setGroupVisible(R.id.EMAIL_MENU,
1636 type == WebView.HitTestResult.EMAIL_TYPE);
1637 menu.setGroupVisible(R.id.GEO_MENU,
1638 type == WebView.HitTestResult.GEO_TYPE);
1639 menu.setGroupVisible(R.id.IMAGE_MENU,
1640 type == WebView.HitTestResult.IMAGE_TYPE
1641 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1642 menu.setGroupVisible(R.id.ANCHOR_MENU,
1643 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1644 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1646 // Setup custom handling depending on the type
1648 case WebView.HitTestResult.PHONE_TYPE:
1649 menu.setHeaderTitle(Uri.decode(extra));
1650 menu.findItem(R.id.dial_context_menu_id).setIntent(
1651 new Intent(Intent.ACTION_VIEW, Uri
1652 .parse(WebView.SCHEME_TEL + extra)));
1653 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1654 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1655 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1656 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1658 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1662 case WebView.HitTestResult.EMAIL_TYPE:
1663 menu.setHeaderTitle(extra);
1664 menu.findItem(R.id.email_context_menu_id).setIntent(
1665 new Intent(Intent.ACTION_VIEW, Uri
1666 .parse(WebView.SCHEME_MAILTO + extra)));
1667 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1671 case WebView.HitTestResult.GEO_TYPE:
1672 menu.setHeaderTitle(extra);
1673 menu.findItem(R.id.map_context_menu_id).setIntent(
1674 new Intent(Intent.ACTION_VIEW, Uri
1675 .parse(WebView.SCHEME_GEO
1676 + URLEncoder.encode(extra))));
1677 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1681 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1682 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1683 TextView titleView = (TextView) LayoutInflater.from(this)
1684 .inflate(android.R.layout.browser_link_context_header,
1686 titleView.setText(extra);
1687 menu.setHeaderView(titleView);
1688 // decide whether to show the open link in new tab option
1689 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1690 mTabControl.canCreateNewTab());
1691 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1692 Bookmarks.urlHasAcceptableScheme(extra));
1693 PackageManager pm = getPackageManager();
1694 Intent send = new Intent(Intent.ACTION_SEND);
1695 send.setType("text/plain");
1696 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1697 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1698 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1701 // otherwise fall through to handle image part
1702 case WebView.HitTestResult.IMAGE_TYPE:
1703 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1704 menu.setHeaderTitle(extra);
1706 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1708 menu.findItem(R.id.download_context_menu_id).
1709 setOnMenuItemClickListener(new Download(extra));
1710 menu.findItem(R.id.set_wallpaper_context_menu_id).
1711 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1715 Log.w(LOGTAG, "We should not get here.");
1721 // Attach the given tab to the content view.
1722 // this should only be called for the current tab.
1723 private void attachTabToContentView(Tab t) {
1724 // Attach the container that contains the main WebView and any other UI
1725 // associated with the tab.
1726 t.attachTabToContentView(mContentView);
1728 if (mShouldShowErrorConsole) {
1729 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1730 if (errorConsole.numberOfErrors() == 0) {
1731 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1733 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1736 mErrorConsoleContainer.addView(errorConsole,
1737 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1738 ViewGroup.LayoutParams.WRAP_CONTENT));
1741 WebView view = t.getWebView();
1742 view.setEmbeddedTitleBar(mTitleBar);
1743 // Request focus on the top window.
1744 t.getTopWindow().requestFocus();
1747 // Attach a sub window to the main WebView of the given tab.
1748 void attachSubWindow(Tab t) {
1749 t.attachSubWindow(mContentView);
1750 getTopWindow().requestFocus();
1753 // Remove the given tab from the content view.
1754 private void removeTabFromContentView(Tab t) {
1755 // Remove the container that contains the main WebView.
1756 t.removeTabFromContentView(mContentView);
1758 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1759 if (errorConsole != null) {
1760 mErrorConsoleContainer.removeView(errorConsole);
1763 WebView view = t.getWebView();
1765 view.setEmbeddedTitleBar(null);
1769 // Remove the sub window if it exists. Also called by TabControl when the
1770 // user clicks the 'X' to dismiss a sub window.
1771 /* package */ void dismissSubWindow(Tab t) {
1772 t.removeSubWindow(mContentView);
1773 // dismiss the subwindow. This will destroy the WebView.
1774 t.dismissSubWindow();
1775 getTopWindow().requestFocus();
1778 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1779 // that accepts url as string.
1780 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1781 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1784 // This method does a ton of stuff. It will attempt to create a new tab
1785 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1786 // url isn't null, it will load the given url.
1787 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1789 final Tab currentTab = mTabControl.getCurrentTab();
1790 if (mTabControl.canCreateNewTab()) {
1791 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1793 WebView webview = tab.getWebView();
1794 // If the last tab was removed from the active tabs page, currentTab
1796 if (currentTab != null) {
1797 removeTabFromContentView(currentTab);
1799 // We must set the new tab as the current tab to reflect the old
1800 // animation behavior.
1801 mTabControl.setCurrentTab(tab);
1802 attachTabToContentView(tab);
1803 if (!urlData.isEmpty()) {
1804 urlData.loadIn(webview);
1808 // Get rid of the subwindow if it exists
1809 dismissSubWindow(currentTab);
1810 if (!urlData.isEmpty()) {
1811 // Load the given url.
1812 urlData.loadIn(currentTab.getWebView());
1818 private Tab openTab(String url) {
1819 if (mSettings.openInBackground()) {
1820 Tab t = mTabControl.createNewTab();
1822 WebView view = t.getWebView();
1827 return openTabAndShow(url, false, null);
1831 private class Copy implements OnMenuItemClickListener {
1832 private CharSequence mText;
1834 public boolean onMenuItemClick(MenuItem item) {
1839 public Copy(CharSequence toCopy) {
1844 private class Download implements OnMenuItemClickListener {
1845 private String mText;
1847 public boolean onMenuItemClick(MenuItem item) {
1848 onDownloadStartNoStream(mText, null, null, null, -1);
1852 public Download(String toDownload) {
1857 private class SetAsWallpaper extends Thread implements
1858 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1860 private ProgressDialog mWallpaperProgress;
1861 private boolean mCanceled = false;
1863 public SetAsWallpaper(String url) {
1865 mUrl = new URL(url);
1866 } catch (MalformedURLException e) {
1871 public void onCancel(DialogInterface dialog) {
1875 public boolean onMenuItemClick(MenuItem item) {
1877 // The user may have tried to set a image with a large file size as their
1878 // background so it may take a few moments to perform the operation. Display
1879 // a progress spinner while it is working.
1880 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1881 mWallpaperProgress.setIndeterminate(true);
1882 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1883 mWallpaperProgress.setCancelable(true);
1884 mWallpaperProgress.setOnCancelListener(this);
1885 mWallpaperProgress.show();
1892 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1894 // TODO: This will cause the resource to be downloaded again, when we
1895 // should in most cases be able to grab it from the cache. To fix this
1896 // we should query WebCore to see if we can access a cached version and
1897 // instead open an input stream on that. This pattern could also be used
1898 // in the download manager where the same problem exists.
1899 InputStream inputstream = mUrl.openStream();
1900 if (inputstream != null) {
1901 setWallpaper(inputstream);
1903 } catch (IOException e) {
1904 Log.e(LOGTAG, "Unable to set new wallpaper");
1905 // Act as though the user canceled the operation so we try to
1906 // restore the old wallpaper.
1911 // Restore the old wallpaper if the user cancelled whilst we were setting
1912 // the new wallpaper.
1913 int width = oldWallpaper.getIntrinsicWidth();
1914 int height = oldWallpaper.getIntrinsicHeight();
1915 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1916 Canvas canvas = new Canvas(bm);
1917 oldWallpaper.setBounds(0, 0, width, height);
1918 oldWallpaper.draw(canvas);
1921 } catch (IOException e) {
1922 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1927 if (mWallpaperProgress.isShowing()) {
1928 mWallpaperProgress.dismiss();
1933 private void copy(CharSequence text) {
1935 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1937 clip.setClipboardText(text);
1939 } catch (android.os.RemoteException e) {
1940 Log.e(LOGTAG, "Copy failed", e);
1945 * Resets the browser title-view to whatever it must be
1946 * (for example, if we had a loading error)
1947 * When we have a new page, we call resetTitle, when we
1948 * have to reset the titlebar to whatever it used to be
1949 * (for example, if the user chose to stop loading), we
1950 * call resetTitleAndRevertLockIcon.
1952 /* package */ void resetTitleAndRevertLockIcon() {
1953 mTabControl.getCurrentTab().revertLockIcon();
1954 updateLockIconToLatest();
1955 resetTitleIconAndProgress();
1959 * Reset the title, favicon, and progress.
1961 private void resetTitleIconAndProgress() {
1962 WebView current = mTabControl.getCurrentWebView();
1963 if (current == null) {
1966 resetTitleAndIcon(current);
1967 int progress = current.getProgress();
1968 current.getWebChromeClient().onProgressChanged(current, progress);
1971 // Reset the title and the icon based on the given item.
1972 private void resetTitleAndIcon(WebView view) {
1973 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1975 setUrlTitle(item.getUrl(), item.getTitle());
1976 setFavicon(item.getFavicon());
1978 setUrlTitle(null, null);
1984 * Sets a title composed of the URL and the title string.
1985 * @param url The URL of the site being loaded.
1986 * @param title The title of the site being loaded.
1988 void setUrlTitle(String url, String title) {
1992 mTitleBar.setTitleAndUrl(title, url);
1993 mFakeTitleBar.setTitleAndUrl(title, url);
1997 * @param url The URL to build a title version of the URL from.
1998 * @return The title version of the URL or null if fails.
1999 * The title version of the URL can be either the URL hostname,
2000 * or the hostname with an "https://" prefix (for secure URLs),
2001 * or an empty string if, for example, the URL in question is a
2002 * file:// URL with no hostname.
2004 /* package */ static String buildTitleUrl(String url) {
2005 String titleUrl = null;
2009 // parse the url string
2010 URL urlObj = new URL(url);
2011 if (urlObj != null) {
2014 String protocol = urlObj.getProtocol();
2015 String host = urlObj.getHost();
2017 if (host != null && 0 < host.length()) {
2019 if (protocol != null) {
2020 // if a secure site, add an "https://" prefix!
2021 if (protocol.equalsIgnoreCase("https")) {
2022 titleUrl = protocol + "://" + host;
2027 } catch (MalformedURLException e) {}
2033 // Set the favicon in the title bar.
2034 void setFavicon(Bitmap icon) {
2035 mTitleBar.setFavicon(icon);
2036 mFakeTitleBar.setFavicon(icon);
2040 * Close the tab, remove its associated title bar, and adjust mTabControl's
2041 * current tab to a valid value.
2043 /* package */ void closeTab(Tab t) {
2044 int currentIndex = mTabControl.getCurrentIndex();
2045 int removeIndex = mTabControl.getTabIndex(t);
2046 mTabControl.removeTab(t);
2047 if (currentIndex >= removeIndex && currentIndex != 0) {
2050 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2051 resetTitleIconAndProgress();
2054 private void goBackOnePageOrQuit() {
2055 Tab current = mTabControl.getCurrentTab();
2056 if (current == null) {
2058 * Instead of finishing the activity, simply push this to the back
2059 * of the stack and let ActivityManager to choose the foreground
2060 * activity. As BrowserActivity is singleTask, it will be always the
2061 * root of the task. So we can use either true or false for
2064 moveTaskToBack(true);
2067 WebView w = current.getWebView();
2068 if (w.canGoBack()) {
2071 // Check to see if we are closing a window that was created by
2072 // another window. If so, we switch back to that window.
2073 Tab parent = current.getParentTab();
2074 if (parent != null) {
2075 switchToTab(mTabControl.getTabIndex(parent));
2076 // Now we close the other tab
2079 if (current.closeOnExit()) {
2080 // force the tab's inLoad() to be false as we are going to
2081 // either finish the activity or remove the tab. This will
2082 // ensure pauseWebViewTimers() taking action.
2083 mTabControl.getCurrentTab().clearInLoad();
2084 if (mTabControl.getTabCount() == 1) {
2088 // call pauseWebViewTimers() now, we won't be able to call
2089 // it in onPause() as the WebView won't be valid.
2090 // Temporarily change mActivityInPause to be true as
2091 // pauseWebViewTimers() will do nothing if mActivityInPause
2093 boolean savedState = mActivityInPause;
2095 Log.e(LOGTAG, "BrowserActivity is already paused "
2096 + "while handing goBackOnePageOrQuit.");
2098 mActivityInPause = true;
2099 pauseWebViewTimers();
2100 mActivityInPause = savedState;
2101 removeTabFromContentView(current);
2102 mTabControl.removeTab(current);
2105 * Instead of finishing the activity, simply push this to the back
2106 * of the stack and let ActivityManager to choose the foreground
2107 * activity. As BrowserActivity is singleTask, it will be always the
2108 * root of the task. So we can use either true or false for
2111 moveTaskToBack(true);
2116 boolean isMenuDown() {
2121 public boolean onKeyDown(int keyCode, KeyEvent event) {
2122 // Even if MENU is already held down, we need to call to super to open
2123 // the IME on long press.
2124 if (KeyEvent.KEYCODE_MENU == keyCode) {
2126 return super.onKeyDown(keyCode, event);
2128 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2129 // still down, we don't want to trigger the search. Pretend to consume
2130 // the key and do nothing.
2131 if (mMenuIsDown) return true;
2134 case KeyEvent.KEYCODE_SPACE:
2135 // WebView/WebTextView handle the keys in the KeyDown. As
2136 // the Activity's shortcut keys are only handled when WebView
2137 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2138 if (event.isShiftPressed()) {
2139 getTopWindow().pageUp(false);
2141 getTopWindow().pageDown(false);
2144 case KeyEvent.KEYCODE_BACK:
2145 if (event.getRepeatCount() == 0) {
2146 event.startTracking();
2148 } else if (mCustomView == null && mActiveTabsPage == null
2149 && event.isLongPress()) {
2150 bookmarksOrHistoryPicker(true);
2155 return super.onKeyDown(keyCode, event);
2159 public boolean onKeyUp(int keyCode, KeyEvent event) {
2161 case KeyEvent.KEYCODE_MENU:
2162 mMenuIsDown = false;
2164 case KeyEvent.KEYCODE_BACK:
2165 if (event.isTracking() && !event.isCanceled()) {
2166 if (mCustomView != null) {
2167 // if a custom view is showing, hide it
2168 mTabControl.getCurrentWebView().getWebChromeClient()
2169 .onHideCustomView();
2170 } else if (mActiveTabsPage != null) {
2171 // if tab page is showing, hide it
2172 removeActiveTabPage(true);
2174 WebView subwindow = mTabControl.getCurrentSubWindow();
2175 if (subwindow != null) {
2176 if (subwindow.canGoBack()) {
2179 dismissSubWindow(mTabControl.getCurrentTab());
2182 goBackOnePageOrQuit();
2189 return super.onKeyUp(keyCode, event);
2192 /* package */ void stopLoading() {
2193 mDidStopLoad = true;
2194 resetTitleAndRevertLockIcon();
2195 WebView w = getTopWindow();
2197 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2198 // same logic here. But for subwindow case, should we call into the main
2199 // WebView's onPageFinished as we never call its onPageStarted and if
2200 // the page finishes itself, we don't call onPageFinished.
2201 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2206 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2210 boolean didUserStopLoading() {
2211 return mDidStopLoad;
2214 private void cancelStopToast() {
2215 if (mStopToast != null) {
2216 mStopToast.cancel();
2221 // called by a UI or non-UI thread to post the message
2222 public void postMessage(int what, int arg1, int arg2, Object obj,
2224 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2228 // called by a UI or non-UI thread to remove the message
2229 void removeMessages(int what, Object object) {
2230 mHandler.removeMessages(what, object);
2233 // public message ids
2234 public final static int LOAD_URL = 1001;
2235 public final static int STOP_LOAD = 1002;
2238 private static final int FOCUS_NODE_HREF = 102;
2239 private static final int CANCEL_CREDS_REQUEST = 103;
2240 private static final int RELEASE_WAKELOCK = 107;
2242 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2244 // Private handler for handling javascript and saving passwords
2245 private Handler mHandler = new Handler() {
2247 public void handleMessage(Message msg) {
2249 case FOCUS_NODE_HREF:
2251 String url = (String) msg.getData().get("url");
2252 String title = (String) msg.getData().get("title");
2253 if (url == null || url.length() == 0) {
2256 HashMap focusNodeMap = (HashMap) msg.obj;
2257 WebView view = (WebView) focusNodeMap.get("webview");
2258 // Only apply the action if the top window did not change.
2259 if (getTopWindow() != view) {
2263 case R.id.open_context_menu_id:
2264 case R.id.view_image_context_menu_id:
2265 loadURL(getTopWindow(), url);
2267 case R.id.open_newtab_context_menu_id:
2268 final Tab parent = mTabControl.getCurrentTab();
2269 final Tab newTab = openTab(url);
2270 if (newTab != parent) {
2271 parent.addChildTab(newTab);
2274 case R.id.bookmark_context_menu_id:
2275 Intent intent = new Intent(BrowserActivity.this,
2276 AddBookmarkPage.class);
2277 intent.putExtra("url", url);
2278 intent.putExtra("title", title);
2279 startActivity(intent);
2281 case R.id.share_link_context_menu_id:
2282 // See if this site has been visited before
2283 StringBuilder sb = new StringBuilder(
2284 Browser.BookmarkColumns.URL + " = ");
2285 DatabaseUtils.appendEscapedSQLString(sb, url);
2286 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2287 Browser.HISTORY_PROJECTION,
2291 if (c.moveToFirst()) {
2292 // The site has been visited before, so grab the
2293 // info from the database.
2294 Bitmap favicon = null;
2295 Bitmap thumbnail = null;
2296 String linkTitle = c.getString(Browser.
2297 HISTORY_PROJECTION_TITLE_INDEX);
2298 byte[] data = c.getBlob(Browser.
2299 HISTORY_PROJECTION_FAVICON_INDEX);
2301 favicon = BitmapFactory.decodeByteArray(
2302 data, 0, data.length);
2304 data = c.getBlob(Browser.
2305 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2307 thumbnail = BitmapFactory.decodeByteArray(
2308 data, 0, data.length);
2310 sharePage(BrowserActivity.this,
2311 linkTitle, url, favicon, thumbnail);
2313 Browser.sendString(BrowserActivity.this, url,
2315 R.string.choosertitle_sharevia));
2318 case R.id.copy_link_context_menu_id:
2321 case R.id.save_link_context_menu_id:
2322 case R.id.download_context_menu_id:
2323 onDownloadStartNoStream(url, null, null, null, -1);
2330 loadURL(getTopWindow(), (String) msg.obj);
2337 case CANCEL_CREDS_REQUEST:
2338 resumeAfterCredentials();
2341 case RELEASE_WAKELOCK:
2342 if (mWakeLock.isHeld()) {
2343 mWakeLock.release();
2344 // if we reach here, Browser should be still in the
2345 // background loading after WAKELOCK_TIMEOUT (5-min).
2346 // To avoid burning the battery, stop loading.
2347 mTabControl.stopAllLoading();
2351 case UPDATE_BOOKMARK_THUMBNAIL:
2352 WebView view = (WebView) msg.obj;
2354 updateScreenshot(view);
2362 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2363 * an {@link Intent} to launch the Activity chooser.
2364 * @param c Context used to launch a new Activity.
2365 * @param title Title of the page. Stored in the Intent with
2366 * {@link Browser#EXTRA_SHARE_TITLE}
2367 * @param url URL of the page. Stored in the Intent with
2368 * {@link Intent#EXTRA_TEXT}
2369 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2370 * with {@link Browser#EXTRA_SHARE_FAVICON}
2371 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2372 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2374 public static final void sharePage(Context c, String title, String url,
2375 Bitmap favicon, Bitmap screenshot) {
2376 Intent send = new Intent(Intent.ACTION_SEND);
2377 send.setType("text/plain");
2378 send.putExtra(Intent.EXTRA_TEXT, url);
2379 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2380 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2381 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2383 c.startActivity(Intent.createChooser(send, c.getString(
2384 R.string.choosertitle_sharevia)));
2385 } catch(android.content.ActivityNotFoundException ex) {
2386 // if no app handles it, do nothing
2390 private void updateScreenshot(WebView view) {
2391 // If this is a bookmarked site, add a screenshot to the database.
2392 // FIXME: When should we update? Every time?
2393 // FIXME: Would like to make sure there is actually something to
2394 // draw, but the API for that (WebViewCore.pictureReady()) is not
2395 // currently accessible here.
2397 ContentResolver cr = getContentResolver();
2398 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2399 cr, view.getOriginalUrl(), view.getUrl(), true);
2401 boolean succeed = c.moveToFirst();
2402 ContentValues values = null;
2404 if (values == null) {
2405 final ByteArrayOutputStream os
2406 = new ByteArrayOutputStream();
2407 Bitmap bm = createScreenshot(view);
2412 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2413 values = new ContentValues();
2414 values.put(Browser.BookmarkColumns.THUMBNAIL,
2417 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2418 c.getInt(0)), values, null, null);
2419 succeed = c.moveToNext();
2426 * Values for the size of the thumbnail created when taking a screenshot.
2427 * Lazily initialized. Instead of using these directly, use
2428 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2430 private static int THUMBNAIL_WIDTH = 0;
2431 private static int THUMBNAIL_HEIGHT = 0;
2434 * Return the desired width for thumbnail screenshots, which are stored in
2435 * the database, and used on the bookmarks screen.
2436 * @param context Context for finding out the density of the screen.
2437 * @return int desired width for thumbnail screenshot.
2439 /* package */ static int getDesiredThumbnailWidth(Context context) {
2440 if (THUMBNAIL_WIDTH == 0) {
2441 float density = context.getResources().getDisplayMetrics().density;
2442 THUMBNAIL_WIDTH = (int) (90 * density);
2443 THUMBNAIL_HEIGHT = (int) (80 * density);
2445 return THUMBNAIL_WIDTH;
2449 * Return the desired height for thumbnail screenshots, which are stored in
2450 * the database, and used on the bookmarks screen.
2451 * @param context Context for finding out the density of the screen.
2452 * @return int desired height for thumbnail screenshot.
2454 /* package */ static int getDesiredThumbnailHeight(Context context) {
2455 // To ensure that they are both initialized.
2456 getDesiredThumbnailWidth(context);
2457 return THUMBNAIL_HEIGHT;
2460 private Bitmap createScreenshot(WebView view) {
2461 Picture thumbnail = view.capturePicture();
2462 if (thumbnail == null) {
2465 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2466 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2467 Canvas canvas = new Canvas(bm);
2468 // May need to tweak these values to determine what is the
2469 // best scale factor
2470 int thumbnailWidth = thumbnail.getWidth();
2471 int thumbnailHeight = thumbnail.getHeight();
2472 float scaleFactorX = 1.0f;
2473 float scaleFactorY = 1.0f;
2474 if (thumbnailWidth > 0) {
2475 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2476 (float)thumbnailWidth;
2481 if (view.getWidth() > view.getHeight() &&
2482 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2483 // If the device is in landscape and the page is shorter
2484 // than the height of the view, stretch the thumbnail to fill the
2486 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2487 (float)thumbnailHeight;
2489 // In the portrait case, this looks nice.
2490 scaleFactorY = scaleFactorX;
2493 canvas.scale(scaleFactorX, scaleFactorY);
2495 thumbnail.draw(canvas);
2499 // -------------------------------------------------------------------------
2500 // Helper function for WebViewClient.
2501 //-------------------------------------------------------------------------
2503 // Use in overrideUrlLoading
2504 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2505 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2506 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2507 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2509 void onPageStarted(WebView view, String url, Bitmap favicon) {
2510 // when BrowserActivity just starts, onPageStarted may be called before
2511 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2512 // to start the timer. As we won't switch tabs while an activity is in
2513 // pause state, we can ensure calling resume and pause in pair.
2514 if (mActivityInPause) resumeWebViewTimers();
2517 setUrlTitle(url, null);
2518 setFavicon(favicon);
2519 // Keep this initial progress in sync with initialProgressValue (* 100)
2520 // in ProgressTracker.cpp
2521 // Show some progress so that the user knows the page is beginning to
2523 onProgressChanged(view, 10);
2524 mDidStopLoad = false;
2525 if (!mIsNetworkUp) createAndShowNetworkDialog();
2527 if (mSettings.isTracing()) {
2530 WebAddress uri = new WebAddress(url);
2532 } catch (android.net.ParseException ex) {
2535 host = host.replace('.', '_');
2538 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2541 // Performance probe
2543 mStart = SystemClock.uptimeMillis();
2544 mProcessStart = Process.getElapsedCpuTime();
2545 long[] sysCpu = new long[7];
2546 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2548 mUserStart = sysCpu[0] + sysCpu[1];
2549 mSystemStart = sysCpu[2];
2550 mIdleStart = sysCpu[3];
2551 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2553 mUiStart = SystemClock.currentThreadTimeMillis();
2557 void onPageFinished(WebView view, String url) {
2558 // Reset the title and icon in case we stopped a provisional load.
2559 resetTitleAndIcon(view);
2560 // Update the lock icon image only once we are done loading
2561 updateLockIconToLatest();
2562 // pause the WebView timer and release the wake lock if it is finished
2563 // while BrowserActivity is in pause state.
2564 if (mActivityInPause && pauseWebViewTimers()) {
2565 if (mWakeLock.isHeld()) {
2566 mHandler.removeMessages(RELEASE_WAKELOCK);
2567 mWakeLock.release();
2571 // Performance probe
2573 long[] sysCpu = new long[7];
2574 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2576 String uiInfo = "UI thread used "
2577 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2580 Log.d(LOGTAG, uiInfo);
2582 //The string that gets written to the log
2583 String performanceString = "It took total "
2584 + (SystemClock.uptimeMillis() - mStart)
2585 + " ms clock time to load the page."
2586 + "\nbrowser process used "
2587 + (Process.getElapsedCpuTime() - mProcessStart)
2588 + " ms, user processes used "
2589 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2590 + " ms, kernel used "
2591 + (sysCpu[2] - mSystemStart) * 10
2592 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2593 + " ms and irq took "
2594 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2595 * 10 + " ms, " + uiInfo;
2597 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2600 // strip the url to maintain consistency
2601 String newUrl = new String(url);
2602 if (newUrl.startsWith("http://www.")) {
2603 newUrl = newUrl.substring(11);
2604 } else if (newUrl.startsWith("http://")) {
2605 newUrl = newUrl.substring(7);
2606 } else if (newUrl.startsWith("https://www.")) {
2607 newUrl = newUrl.substring(12);
2608 } else if (newUrl.startsWith("https://")) {
2609 newUrl = newUrl.substring(8);
2612 Log.d(LOGTAG, newUrl + " loaded");
2620 Debug.stopMethodTracing();
2624 boolean shouldOverrideUrlLoading(WebView view, String url) {
2625 if (url.startsWith(SCHEME_WTAI)) {
2626 // wtai://wp/mc;number
2627 // number=string(phone-number)
2628 if (url.startsWith(SCHEME_WTAI_MC)) {
2629 Intent intent = new Intent(Intent.ACTION_VIEW,
2630 Uri.parse(WebView.SCHEME_TEL +
2631 url.substring(SCHEME_WTAI_MC.length())));
2632 startActivity(intent);
2635 // wtai://wp/sd;dtmf
2636 // dtmf=string(dialstring)
2637 if (url.startsWith(SCHEME_WTAI_SD)) {
2638 // TODO: only send when there is active voice connection
2641 // wtai://wp/ap;number;name
2642 // number=string(phone-number)
2644 if (url.startsWith(SCHEME_WTAI_AP)) {
2650 // The "about:" schemes are internal to the browser; don't want these to
2651 // be dispatched to other apps.
2652 if (url.startsWith("about:")) {
2657 // perform generic parsing of the URI to turn it into an Intent.
2659 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2660 } catch (URISyntaxException ex) {
2661 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2665 // check whether the intent can be resolved. If not, we will see
2666 // whether we can download it from the Market.
2667 if (getPackageManager().resolveActivity(intent, 0) == null) {
2668 String packagename = intent.getPackage();
2669 if (packagename != null) {
2670 intent = new Intent(Intent.ACTION_VIEW, Uri
2671 .parse("market://search?q=pname:" + packagename));
2672 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2673 startActivity(intent);
2680 // sanitize the Intent, ensuring web pages can not bypass browser
2681 // security (only access to BROWSABLE activities).
2682 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2683 intent.setComponent(null);
2685 if (startActivityIfNeeded(intent, -1)) {
2688 } catch (ActivityNotFoundException ex) {
2689 // ignore the error. If no application can handle the URL,
2690 // eg about:blank, assume the browser can handle it.
2701 // -------------------------------------------------------------------------
2702 // Helper function for WebChromeClient
2703 // -------------------------------------------------------------------------
2705 void onProgressChanged(WebView view, int newProgress) {
2706 mTitleBar.setProgress(newProgress);
2707 mFakeTitleBar.setProgress(newProgress);
2709 if (newProgress == 100) {
2710 // onProgressChanged() may continue to be called after the main
2711 // frame has finished loading, as any remaining sub frames continue
2712 // to load. We'll only get called once though with newProgress as
2713 // 100 when everything is loaded. (onPageFinished is called once
2714 // when the main frame completes loading regardless of the state of
2715 // any sub frames so calls to onProgressChanges may continue after
2716 // onPageFinished has executed)
2719 updateInLoadMenuItems();
2720 // If the options menu is open, leave the title bar
2721 if (!mOptionsMenuOpen || !mIconView) {
2725 } else if (!mInLoad) {
2726 // onPageFinished may have already been called but a subframe is
2727 // still loading and updating the progress. Reset mInLoad and update
2730 updateInLoadMenuItems();
2731 if (!mOptionsMenuOpen || mIconView) {
2732 // This page has begun to load, so show the title bar
2738 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2739 // if a view already exists then immediately terminate the new one
2740 if (mCustomView != null) {
2741 callback.onCustomViewHidden();
2745 // Add the custom view to its container.
2746 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2748 mCustomViewCallback = callback;
2749 // Save the menu state and set it to empty while the custom
2751 mOldMenuState = mMenuState;
2752 mMenuState = EMPTY_MENU;
2753 // Hide the content view.
2754 mContentView.setVisibility(View.GONE);
2755 // Finally show the custom view container.
2756 setStatusBarVisibility(false);
2757 mCustomViewContainer.setVisibility(View.VISIBLE);
2758 mCustomViewContainer.bringToFront();
2761 void onHideCustomView() {
2762 if (mCustomView == null)
2765 // Hide the custom view.
2766 mCustomView.setVisibility(View.GONE);
2767 // Remove the custom view from its container.
2768 mCustomViewContainer.removeView(mCustomView);
2770 // Reset the old menu state.
2771 mMenuState = mOldMenuState;
2772 mOldMenuState = EMPTY_MENU;
2773 mCustomViewContainer.setVisibility(View.GONE);
2774 mCustomViewCallback.onCustomViewHidden();
2775 // Show the content view.
2776 setStatusBarVisibility(true);
2777 mContentView.setVisibility(View.VISIBLE);
2780 Bitmap getDefaultVideoPoster() {
2781 if (mDefaultVideoPoster == null) {
2782 mDefaultVideoPoster = BitmapFactory.decodeResource(
2783 getResources(), R.drawable.default_video_poster);
2785 return mDefaultVideoPoster;
2788 View getVideoLoadingProgressView() {
2789 if (mVideoProgressView == null) {
2790 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2791 mVideoProgressView = inflater.inflate(
2792 R.layout.video_loading_progress, null);
2794 return mVideoProgressView;
2798 * The Object used to inform the WebView of the file to upload.
2800 private ValueCallback<Uri> mUploadMessage;
2802 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2803 if (mUploadMessage != null) return;
2804 mUploadMessage = uploadMsg;
2805 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2806 i.addCategory(Intent.CATEGORY_OPENABLE);
2808 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2809 getString(R.string.choose_upload)), FILE_SELECTED);
2812 // -------------------------------------------------------------------------
2813 // Implement functions for DownloadListener
2814 // -------------------------------------------------------------------------
2817 * Notify the host application a download should be done, or that
2818 * the data should be streamed if a streaming viewer is available.
2819 * @param url The full url to the content that should be downloaded
2820 * @param contentDisposition Content-disposition http header, if
2822 * @param mimetype The mimetype of the content reported by the server
2823 * @param contentLength The file size reported by the server
2825 public void onDownloadStart(String url, String userAgent,
2826 String contentDisposition, String mimetype, long contentLength) {
2827 // if we're dealing wih A/V content that's not explicitly marked
2828 // for download, check if it's streamable.
2829 if (contentDisposition == null
2830 || !contentDisposition.regionMatches(
2831 true, 0, "attachment", 0, 10)) {
2832 // query the package manager to see if there's a registered handler
2834 Intent intent = new Intent(Intent.ACTION_VIEW);
2835 intent.setDataAndType(Uri.parse(url), mimetype);
2836 ResolveInfo info = getPackageManager().resolveActivity(intent,
2837 PackageManager.MATCH_DEFAULT_ONLY);
2839 ComponentName myName = getComponentName();
2840 // If we resolved to ourselves, we don't want to attempt to
2841 // load the url only to try and download it again.
2842 if (!myName.getPackageName().equals(
2843 info.activityInfo.packageName)
2844 || !myName.getClassName().equals(
2845 info.activityInfo.name)) {
2846 // someone (other than us) knows how to handle this mime
2847 // type with this scheme, don't download.
2849 startActivity(intent);
2851 } catch (ActivityNotFoundException ex) {
2853 Log.d(LOGTAG, "activity not found for " + mimetype
2854 + " over " + Uri.parse(url).getScheme(),
2857 // Best behavior is to fall back to a download in this
2863 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2867 * Notify the host application a download should be done, even if there
2868 * is a streaming viewer available for thise type.
2869 * @param url The full url to the content that should be downloaded
2870 * @param contentDisposition Content-disposition http header, if
2872 * @param mimetype The mimetype of the content reported by the server
2873 * @param contentLength The file size reported by the server
2875 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2876 String contentDisposition, String mimetype, long contentLength) {
2878 String filename = URLUtil.guessFileName(url,
2879 contentDisposition, mimetype);
2881 // Check to see if we have an SDCard
2882 String status = Environment.getExternalStorageState();
2883 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2887 // Check to see if the SDCard is busy, same as the music app
2888 if (status.equals(Environment.MEDIA_SHARED)) {
2889 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2890 title = R.string.download_sdcard_busy_dlg_title;
2892 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2893 title = R.string.download_no_sdcard_dlg_title;
2896 new AlertDialog.Builder(this)
2898 .setIcon(android.R.drawable.ic_dialog_alert)
2900 .setPositiveButton(R.string.ok, null)
2905 // java.net.URI is a lot stricter than KURL so we have to undo
2906 // KURL's percent-encoding and redo the encoding using java.net.URI.
2909 // Undo the percent-encoding that KURL may have done.
2910 String newUrl = new String(URLUtil.decode(url.getBytes()));
2911 // Parse the url into pieces
2912 WebAddress w = new WebAddress(newUrl);
2914 String query = null;
2915 String path = w.mPath;
2916 // Break the path into path, query, and fragment
2917 if (path.length() > 0) {
2918 // Strip the fragment
2919 int idx = path.lastIndexOf('#');
2921 frag = path.substring(idx + 1);
2922 path = path.substring(0, idx);
2924 idx = path.lastIndexOf('?');
2926 query = path.substring(idx + 1);
2927 path = path.substring(0, idx);
2930 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2932 } catch (Exception e) {
2933 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2937 // XXX: Have to use the old url since the cookies were stored using the
2938 // old percent-encoded url.
2939 String cookies = CookieManager.getInstance().getCookie(url);
2941 ContentValues values = new ContentValues();
2942 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2943 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2944 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2945 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
2947 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
2948 BrowserDownloadPage.class.getCanonicalName());
2949 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2950 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2951 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2952 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2953 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
2954 if (contentLength > 0) {
2955 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
2957 if (mimetype == null) {
2958 // We must have long pressed on a link or image to download it. We
2959 // are not sure of the mimetype in this case, so do a head request
2960 new FetchUrlMimeType(this).execute(values);
2962 final Uri contentUri =
2963 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
2968 // -------------------------------------------------------------------------
2971 * Resets the lock icon. This method is called when we start a new load and
2972 * know the url to be loaded.
2974 private void resetLockIcon(String url) {
2975 // Save the lock-icon state (we revert to it if the load gets cancelled)
2976 mTabControl.getCurrentTab().resetLockIcon(url);
2977 updateLockIconImage(LOCK_ICON_UNSECURE);
2981 * Update the lock icon to correspond to our latest state.
2983 private void updateLockIconToLatest() {
2984 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
2988 * Updates the lock-icon image in the title-bar.
2990 private void updateLockIconImage(int lockIconType) {
2992 if (lockIconType == LOCK_ICON_SECURE) {
2994 } else if (lockIconType == LOCK_ICON_MIXED) {
2997 mTitleBar.setLock(d);
2998 mFakeTitleBar.setLock(d);
3002 * Displays a page-info dialog.
3003 * @param tab The tab to show info about
3004 * @param fromShowSSLCertificateOnError The flag that indicates whether
3005 * this dialog was opened from the SSL-certificate-on-error dialog or
3006 * not. This is important, since we need to know whether to return to
3007 * the parent dialog or simply dismiss.
3009 private void showPageInfo(final Tab tab,
3010 final boolean fromShowSSLCertificateOnError) {
3011 final LayoutInflater factory = LayoutInflater
3014 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3016 final WebView view = tab.getWebView();
3019 String title = null;
3023 title = tab.getTitle();
3024 } else if (view == mTabControl.getCurrentWebView()) {
3025 // Use the cached title and url if this is the current WebView
3029 url = view.getUrl();
3030 title = view.getTitle();
3036 if (title == null) {
3040 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3041 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3043 mPageInfoView = tab;
3044 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3046 AlertDialog.Builder alertDialogBuilder =
3047 new AlertDialog.Builder(this)
3048 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3049 .setView(pageInfoView)
3052 new DialogInterface.OnClickListener() {
3053 public void onClick(DialogInterface dialog,
3055 mPageInfoDialog = null;
3056 mPageInfoView = null;
3058 // if we came here from the SSL error dialog
3059 if (fromShowSSLCertificateOnError) {
3060 // go back to the SSL error dialog
3061 showSSLCertificateOnError(
3062 mSSLCertificateOnErrorView,
3063 mSSLCertificateOnErrorHandler,
3064 mSSLCertificateOnErrorError);
3068 .setOnCancelListener(
3069 new DialogInterface.OnCancelListener() {
3070 public void onCancel(DialogInterface dialog) {
3071 mPageInfoDialog = null;
3072 mPageInfoView = null;
3074 // if we came here from the SSL error dialog
3075 if (fromShowSSLCertificateOnError) {
3076 // go back to the SSL error dialog
3077 showSSLCertificateOnError(
3078 mSSLCertificateOnErrorView,
3079 mSSLCertificateOnErrorHandler,
3080 mSSLCertificateOnErrorError);
3085 // if we have a main top-level page SSL certificate set or a certificate
3087 if (fromShowSSLCertificateOnError ||
3088 (view != null && view.getCertificate() != null)) {
3089 // add a 'View Certificate' button
3090 alertDialogBuilder.setNeutralButton(
3091 R.string.view_certificate,
3092 new DialogInterface.OnClickListener() {
3093 public void onClick(DialogInterface dialog,
3095 mPageInfoDialog = null;
3096 mPageInfoView = null;
3098 // if we came here from the SSL error dialog
3099 if (fromShowSSLCertificateOnError) {
3100 // go back to the SSL error dialog
3101 showSSLCertificateOnError(
3102 mSSLCertificateOnErrorView,
3103 mSSLCertificateOnErrorHandler,
3104 mSSLCertificateOnErrorError);
3106 // otherwise, display the top-most certificate from
3108 if (view.getCertificate() != null) {
3109 showSSLCertificate(tab);
3116 mPageInfoDialog = alertDialogBuilder.show();
3120 * Displays the main top-level page SSL certificate dialog
3121 * (accessible from the Page-Info dialog).
3122 * @param tab The tab to show certificate for.
3124 private void showSSLCertificate(final Tab tab) {
3125 final View certificateView =
3126 inflateCertificateView(tab.getWebView().getCertificate());
3127 if (certificateView == null) {
3131 LayoutInflater factory = LayoutInflater.from(this);
3133 final LinearLayout placeholder =
3134 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3136 LinearLayout ll = (LinearLayout) factory.inflate(
3137 R.layout.ssl_success, placeholder);
3138 ((TextView)ll.findViewById(R.id.success))
3139 .setText(R.string.ssl_certificate_is_valid);
3141 mSSLCertificateView = tab;
3142 mSSLCertificateDialog =
3143 new AlertDialog.Builder(this)
3144 .setTitle(R.string.ssl_certificate).setIcon(
3145 R.drawable.ic_dialog_browser_certificate_secure)
3146 .setView(certificateView)
3147 .setPositiveButton(R.string.ok,
3148 new DialogInterface.OnClickListener() {
3149 public void onClick(DialogInterface dialog,
3151 mSSLCertificateDialog = null;
3152 mSSLCertificateView = null;
3154 showPageInfo(tab, false);
3157 .setOnCancelListener(
3158 new DialogInterface.OnCancelListener() {
3159 public void onCancel(DialogInterface dialog) {
3160 mSSLCertificateDialog = null;
3161 mSSLCertificateView = null;
3163 showPageInfo(tab, false);
3170 * Displays the SSL error certificate dialog.
3171 * @param view The target web-view.
3172 * @param handler The SSL error handler responsible for cancelling the
3173 * connection that resulted in an SSL error or proceeding per user request.
3174 * @param error The SSL error object.
3176 void showSSLCertificateOnError(
3177 final WebView view, final SslErrorHandler handler, final SslError error) {
3179 final View certificateView =
3180 inflateCertificateView(error.getCertificate());
3181 if (certificateView == null) {
3185 LayoutInflater factory = LayoutInflater.from(this);
3187 final LinearLayout placeholder =
3188 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3190 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3191 LinearLayout ll = (LinearLayout)factory
3192 .inflate(R.layout.ssl_warning, placeholder);
3193 ((TextView)ll.findViewById(R.id.warning))
3194 .setText(R.string.ssl_untrusted);
3197 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3198 LinearLayout ll = (LinearLayout)factory
3199 .inflate(R.layout.ssl_warning, placeholder);
3200 ((TextView)ll.findViewById(R.id.warning))
3201 .setText(R.string.ssl_mismatch);
3204 if (error.hasError(SslError.SSL_EXPIRED)) {
3205 LinearLayout ll = (LinearLayout)factory
3206 .inflate(R.layout.ssl_warning, placeholder);
3207 ((TextView)ll.findViewById(R.id.warning))
3208 .setText(R.string.ssl_expired);
3211 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3212 LinearLayout ll = (LinearLayout)factory
3213 .inflate(R.layout.ssl_warning, placeholder);
3214 ((TextView)ll.findViewById(R.id.warning))
3215 .setText(R.string.ssl_not_yet_valid);
3218 mSSLCertificateOnErrorHandler = handler;
3219 mSSLCertificateOnErrorView = view;
3220 mSSLCertificateOnErrorError = error;
3221 mSSLCertificateOnErrorDialog =
3222 new AlertDialog.Builder(this)
3223 .setTitle(R.string.ssl_certificate).setIcon(
3224 R.drawable.ic_dialog_browser_certificate_partially_secure)
3225 .setView(certificateView)
3226 .setPositiveButton(R.string.ok,
3227 new DialogInterface.OnClickListener() {
3228 public void onClick(DialogInterface dialog,
3230 mSSLCertificateOnErrorDialog = null;
3231 mSSLCertificateOnErrorView = null;
3232 mSSLCertificateOnErrorHandler = null;
3233 mSSLCertificateOnErrorError = null;
3235 view.getWebViewClient().onReceivedSslError(
3236 view, handler, error);
3239 .setNeutralButton(R.string.page_info_view,
3240 new DialogInterface.OnClickListener() {
3241 public void onClick(DialogInterface dialog,
3243 mSSLCertificateOnErrorDialog = null;
3245 // do not clear the dialog state: we will
3246 // need to show the dialog again once the
3247 // user is done exploring the page-info details
3249 showPageInfo(mTabControl.getTabFromView(view),
3253 .setOnCancelListener(
3254 new DialogInterface.OnCancelListener() {
3255 public void onCancel(DialogInterface dialog) {
3256 mSSLCertificateOnErrorDialog = null;
3257 mSSLCertificateOnErrorView = null;
3258 mSSLCertificateOnErrorHandler = null;
3259 mSSLCertificateOnErrorError = null;
3261 view.getWebViewClient().onReceivedSslError(
3262 view, handler, error);
3269 * Inflates the SSL certificate view (helper method).
3270 * @param certificate The SSL certificate.
3271 * @return The resultant certificate view with issued-to, issued-by,
3272 * issued-on, expires-on, and possibly other fields set.
3273 * If the input certificate is null, returns null.
3275 private View inflateCertificateView(SslCertificate certificate) {
3276 if (certificate == null) {
3280 LayoutInflater factory = LayoutInflater.from(this);
3282 View certificateView = factory.inflate(
3283 R.layout.ssl_certificate, null);
3286 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3287 if (issuedTo != null) {
3288 ((TextView) certificateView.findViewById(R.id.to_common))
3289 .setText(issuedTo.getCName());
3290 ((TextView) certificateView.findViewById(R.id.to_org))
3291 .setText(issuedTo.getOName());
3292 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3293 .setText(issuedTo.getUName());
3297 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3298 if (issuedBy != null) {
3299 ((TextView) certificateView.findViewById(R.id.by_common))
3300 .setText(issuedBy.getCName());
3301 ((TextView) certificateView.findViewById(R.id.by_org))
3302 .setText(issuedBy.getOName());
3303 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3304 .setText(issuedBy.getUName());
3308 String issuedOn = reformatCertificateDate(
3309 certificate.getValidNotBefore());
3310 ((TextView) certificateView.findViewById(R.id.issued_on))
3314 String expiresOn = reformatCertificateDate(
3315 certificate.getValidNotAfter());
3316 ((TextView) certificateView.findViewById(R.id.expires_on))
3317 .setText(expiresOn);
3319 return certificateView;
3323 * Re-formats the certificate date (Date.toString()) string to
3324 * a properly localized date string.
3325 * @return Properly localized version of the certificate date string and
3326 * the original certificate date string if fails to localize.
3327 * If the original string is null, returns an empty string "".
3329 private String reformatCertificateDate(String certificateDate) {
3330 String reformattedDate = null;
3332 if (certificateDate != null) {
3335 date = java.text.DateFormat.getInstance().parse(certificateDate);
3336 } catch (ParseException e) {
3342 DateFormat.getDateFormat(this).format(date);
3346 return reformattedDate != null ? reformattedDate :
3347 (certificateDate != null ? certificateDate : "");
3351 * Displays an http-authentication dialog.
3353 void showHttpAuthentication(final HttpAuthHandler handler,
3354 final String host, final String realm, final String title,
3355 final String name, final String password, int focusId) {
3356 LayoutInflater factory = LayoutInflater.from(this);
3357 final View v = factory
3358 .inflate(R.layout.http_authentication, null);
3360 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3362 if (password != null) {
3363 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3366 String titleText = title;
3367 if (titleText == null) {
3368 titleText = getText(R.string.sign_in_to).toString().replace(
3369 "%s1", host).replace("%s2", realm);
3372 mHttpAuthHandler = handler;
3373 AlertDialog dialog = new AlertDialog.Builder(this)
3374 .setTitle(titleText)
3375 .setIcon(android.R.drawable.ic_dialog_alert)
3377 .setPositiveButton(R.string.action,
3378 new DialogInterface.OnClickListener() {
3379 public void onClick(DialogInterface dialog,
3381 String nm = ((EditText) v
3382 .findViewById(R.id.username_edit))
3383 .getText().toString();
3384 String pw = ((EditText) v
3385 .findViewById(R.id.password_edit))
3386 .getText().toString();
3387 BrowserActivity.this.setHttpAuthUsernamePassword
3388 (host, realm, nm, pw);
3389 handler.proceed(nm, pw);
3390 mHttpAuthenticationDialog = null;
3391 mHttpAuthHandler = null;
3393 .setNegativeButton(R.string.cancel,
3394 new DialogInterface.OnClickListener() {
3395 public void onClick(DialogInterface dialog,
3398 BrowserActivity.this.resetTitleAndRevertLockIcon();
3399 mHttpAuthenticationDialog = null;
3400 mHttpAuthHandler = null;
3402 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3403 public void onCancel(DialogInterface dialog) {
3405 BrowserActivity.this.resetTitleAndRevertLockIcon();
3406 mHttpAuthenticationDialog = null;
3407 mHttpAuthHandler = null;
3410 // Make the IME appear when the dialog is displayed if applicable.
3411 dialog.getWindow().setSoftInputMode(
3412 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3415 dialog.findViewById(focusId).requestFocus();
3417 v.findViewById(R.id.username_edit).requestFocus();
3419 mHttpAuthenticationDialog = dialog;
3422 public int getProgress() {
3423 WebView w = mTabControl.getCurrentWebView();
3425 return w.getProgress();
3432 * Set HTTP authentication password.
3434 * @param host The host for the password
3435 * @param realm The realm for the password
3436 * @param username The username for the password. If it is null, it means
3437 * password can't be saved.
3438 * @param password The password
3440 public void setHttpAuthUsernamePassword(String host, String realm,
3443 WebView w = mTabControl.getCurrentWebView();
3445 w.setHttpAuthUsernamePassword(host, realm, username, password);
3450 * connectivity manager says net has come or gone... inform the user
3451 * @param up true if net has come up, false if net has gone down
3453 public void onNetworkToggle(boolean up) {
3454 if (up == mIsNetworkUp) {
3457 mIsNetworkUp = true;
3458 if (mAlertDialog != null) {
3459 mAlertDialog.cancel();
3460 mAlertDialog = null;
3463 mIsNetworkUp = false;
3465 createAndShowNetworkDialog();
3468 WebView w = mTabControl.getCurrentWebView();
3470 w.setNetworkAvailable(up);
3474 boolean isNetworkUp() {
3475 return mIsNetworkUp;
3478 // This method shows the network dialog alerting the user that the net is
3479 // down. It will only show the dialog if mAlertDialog is null.
3480 private void createAndShowNetworkDialog() {
3481 if (mAlertDialog == null) {
3482 mAlertDialog = new AlertDialog.Builder(this)
3483 .setTitle(R.string.loadSuspendedTitle)
3484 .setMessage(R.string.loadSuspended)
3485 .setPositiveButton(R.string.ok, null)
3491 protected void onActivityResult(int requestCode, int resultCode,
3493 if (getTopWindow() == null) return;
3495 switch (requestCode) {
3497 if (resultCode == RESULT_OK && intent != null) {
3498 String data = intent.getAction();
3499 Bundle extras = intent.getExtras();
3500 if (extras != null && extras.getBoolean("new_window", false)) {
3503 final Tab currentTab =
3504 mTabControl.getCurrentTab();
3505 dismissSubWindow(currentTab);
3506 if (data != null && data.length() != 0) {
3507 getTopWindow().loadUrl(data);
3511 // Deliberately fall through to PREFERENCES_PAGE, since the
3512 // same extra may be attached to the COMBO_PAGE
3513 case PREFERENCES_PAGE:
3514 if (resultCode == RESULT_OK && intent != null) {
3515 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3516 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3517 mTabControl.removeParentChildRelationShips();
3521 // Choose a file from the file picker.
3523 if (null == mUploadMessage) break;
3524 Uri result = intent == null || resultCode != RESULT_OK ? null
3526 mUploadMessage.onReceiveValue(result);
3527 mUploadMessage = null;
3532 getTopWindow().requestFocus();
3536 * This method is called as a result of the user selecting the options
3537 * menu to see the download window. It shows the download window on top of
3538 * the current window.
3540 private void viewDownloads(Uri downloadRecord) {
3541 Intent intent = new Intent(this,
3542 BrowserDownloadPage.class);
3543 intent.setData(downloadRecord);
3544 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3550 * @param startWithHistory If true, open starting on the history tab.
3551 * Otherwise, start with the bookmarks tab.
3553 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3554 WebView current = mTabControl.getCurrentWebView();
3555 if (current == null) {
3558 Intent intent = new Intent(this,
3559 CombinedBookmarkHistoryActivity.class);
3560 String title = current.getTitle();
3561 String url = current.getUrl();
3562 Bitmap thumbnail = createScreenshot(current);
3564 // Just in case the user opens bookmarks before a page finishes loading
3565 // so the current history item, and therefore the page, is null.
3567 url = mLastEnteredUrl;
3570 url = mSettings.getHomePage();
3573 // In case the web page has not yet received its associated title.
3574 if (title == null) {
3577 intent.putExtra("title", title);
3578 intent.putExtra("url", url);
3579 intent.putExtra("thumbnail", thumbnail);
3580 // Disable opening in a new window if we have maxed out the windows
3581 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3582 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3583 if (startWithHistory) {
3584 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3585 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3587 startActivityForResult(intent, COMBO_PAGE);
3590 // Called when loading from context menu or LOAD_URL message
3591 private void loadURL(WebView view, String url) {
3592 // In case the user enters nothing.
3593 if (url != null && url.length() != 0 && view != null) {
3594 url = smartUrlFilter(url);
3595 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3601 private String smartUrlFilter(Uri inUri) {
3602 if (inUri != null) {
3603 return smartUrlFilter(inUri.toString());
3608 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3609 "(?i)" + // switch on case insensitive matching
3610 "(" + // begin group for schema
3611 "(?:http|https|file):\\/\\/" +
3612 "|(?:inline|data|about|content|javascript):" +
3617 * Attempts to determine whether user input is a URL or search
3618 * terms. Anything with a space is passed to search.
3620 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3621 * "Http://" converts to "http://"
3623 * @return Original or modified URL
3626 String smartUrlFilter(String url) {
3628 String inUrl = url.trim();
3629 boolean hasSpace = inUrl.indexOf(' ') != -1;
3631 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3632 if (matcher.matches()) {
3633 // force scheme to lowercase
3634 String scheme = matcher.group(1);
3635 String lcScheme = scheme.toLowerCase();
3636 if (!lcScheme.equals(scheme)) {
3637 inUrl = lcScheme + matcher.group(2);
3640 inUrl = inUrl.replace(" ", "%20");
3645 // FIXME: Is this the correct place to add to searches?
3646 // what if someone else calls this function?
3647 int shortcut = parseUrlShortcut(inUrl);
3648 if (shortcut != SHORTCUT_INVALID) {
3649 Browser.addSearchUrl(mResolver, inUrl);
3650 String query = inUrl.substring(2);
3652 case SHORTCUT_GOOGLE_SEARCH:
3653 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3654 case SHORTCUT_WIKIPEDIA_SEARCH:
3655 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3656 case SHORTCUT_DICTIONARY_SEARCH:
3657 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3658 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3659 // FIXME: we need location in this case
3660 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3664 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3665 return URLUtil.guessUrl(inUrl);
3669 Browser.addSearchUrl(mResolver, inUrl);
3670 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3673 /* package */ void setShouldShowErrorConsole(boolean flag) {
3674 if (flag == mShouldShowErrorConsole) {
3679 mShouldShowErrorConsole = flag;
3681 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3682 .getErrorConsole(true);
3685 // Setting the show state of the console will cause it's the layout to be inflated.
3686 if (errorConsole.numberOfErrors() > 0) {
3687 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3689 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3692 // Now we can add it to the main view.
3693 mErrorConsoleContainer.addView(errorConsole,
3694 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3695 ViewGroup.LayoutParams.WRAP_CONTENT));
3697 mErrorConsoleContainer.removeView(errorConsole);
3702 boolean shouldShowErrorConsole() {
3703 return mShouldShowErrorConsole;
3706 private void setStatusBarVisibility(boolean visible) {
3707 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3708 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3712 private void sendNetworkType(String type, String subtype) {
3713 WebView w = mTabControl.getCurrentWebView();
3715 w.setNetworkType(type, subtype);
3719 final static int LOCK_ICON_UNSECURE = 0;
3720 final static int LOCK_ICON_SECURE = 1;
3721 final static int LOCK_ICON_MIXED = 2;
3723 private BrowserSettings mSettings;
3724 private TabControl mTabControl;
3725 private ContentResolver mResolver;
3726 private FrameLayout mContentView;
3727 private View mCustomView;
3728 private FrameLayout mCustomViewContainer;
3729 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3731 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3732 // view, we should rewrite this.
3733 private int mCurrentMenuState = 0;
3734 private int mMenuState = R.id.MAIN_MENU;
3735 private int mOldMenuState = EMPTY_MENU;
3736 private static final int EMPTY_MENU = -1;
3739 private FindDialog mFindDialog;
3740 // Used to prevent chording to result in firing two shortcuts immediately
3741 // one after another. Fixes bug 1211714.
3744 private boolean mInLoad;
3745 private boolean mIsNetworkUp;
3746 private boolean mDidStopLoad;
3748 private boolean mActivityInPause = true;
3750 private boolean mMenuIsDown;
3752 private static boolean mInTrace;
3754 // Performance probe
3755 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3756 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3757 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3758 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3759 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3760 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3761 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3762 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3763 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3766 private long mStart;
3767 private long mProcessStart;
3768 private long mUserStart;
3769 private long mSystemStart;
3770 private long mIdleStart;
3771 private long mIrqStart;
3773 private long mUiStart;
3775 private Drawable mMixLockIcon;
3776 private Drawable mSecLockIcon;
3778 /* hold a ref so we can auto-cancel if necessary */
3779 private AlertDialog mAlertDialog;
3781 // Wait for credentials before loading google.com
3782 private ProgressDialog mCredsDlg;
3784 // The up-to-date URL and title (these can be different from those stored
3785 // in WebView, since it takes some time for the information in WebView to
3787 private String mUrl;
3788 private String mTitle;
3790 // As PageInfo has different style for landscape / portrait, we have
3791 // to re-open it when configuration changed
3792 private AlertDialog mPageInfoDialog;
3793 private Tab mPageInfoView;
3794 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3795 // dialog, we should not just dismiss it, but should get back to the
3796 // SSL-certificate-on-error dialog. This flag is used to store this state
3797 private boolean mPageInfoFromShowSSLCertificateOnError;
3799 // as SSLCertificateOnError has different style for landscape / portrait,
3800 // we have to re-open it when configuration changed
3801 private AlertDialog mSSLCertificateOnErrorDialog;
3802 private WebView mSSLCertificateOnErrorView;
3803 private SslErrorHandler mSSLCertificateOnErrorHandler;
3804 private SslError mSSLCertificateOnErrorError;
3806 // as SSLCertificate has different style for landscape / portrait, we
3807 // have to re-open it when configuration changed
3808 private AlertDialog mSSLCertificateDialog;
3809 private Tab mSSLCertificateView;
3811 // as HttpAuthentication has different style for landscape / portrait, we
3812 // have to re-open it when configuration changed
3813 private AlertDialog mHttpAuthenticationDialog;
3814 private HttpAuthHandler mHttpAuthHandler;
3816 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3817 new FrameLayout.LayoutParams(
3818 ViewGroup.LayoutParams.MATCH_PARENT,
3819 ViewGroup.LayoutParams.MATCH_PARENT);
3820 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3821 new FrameLayout.LayoutParams(
3822 ViewGroup.LayoutParams.MATCH_PARENT,
3823 ViewGroup.LayoutParams.MATCH_PARENT,
3826 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3828 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3829 // Dictionary search
3830 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3831 // Google Mobile Local search
3832 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3834 final static String QUERY_PLACE_HOLDER = "%s";
3836 // "source" parameter for Google search through search key
3837 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3838 // "source" parameter for Google search through goto menu
3839 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3840 // "source" parameter for Google search through simplily type
3841 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3842 // "source" parameter for Google search suggested by the browser
3843 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3844 // "source" parameter for Google search from unknown source
3845 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3847 private final static String LOGTAG = "browser";
3849 private String mLastEnteredUrl;
3851 private PowerManager.WakeLock mWakeLock;
3852 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3854 private Toast mStopToast;
3856 private TitleBar mTitleBar;
3858 private LinearLayout mErrorConsoleContainer = null;
3859 private boolean mShouldShowErrorConsole = false;
3861 // As the ids are dynamically created, we can't guarantee that they will
3862 // be in sequence, so this static array maps ids to a window number.
3863 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3864 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3865 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3866 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3868 // monitor platform changes
3869 private IntentFilter mNetworkStateChangedFilter;
3870 private BroadcastReceiver mNetworkStateIntentReceiver;
3872 private BroadcastReceiver mPackageInstallationReceiver;
3874 // activity requestCode
3875 final static int COMBO_PAGE = 1;
3876 final static int DOWNLOAD_PAGE = 2;
3877 final static int PREFERENCES_PAGE = 3;
3878 final static int FILE_SELECTED = 4;
3880 // the default <video> poster
3881 private Bitmap mDefaultVideoPoster;
3882 // the video progress view
3883 private View mVideoProgressView;
3886 * A UrlData class to abstract how the content will be set to WebView.
3887 * This base class uses loadUrl to show the content.
3889 private static class UrlData {
3893 UrlData(String url) {
3897 void setPostData(byte[] postData) {
3898 mPostData = postData;
3902 return mUrl == null || mUrl.length() == 0;
3905 public void loadIn(WebView webView) {
3906 if (mPostData != null) {
3907 webView.postUrl(mUrl, mPostData);
3909 webView.loadUrl(mUrl);
3915 * A subclass of UrlData class that can display inlined content using
3916 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3918 private static class InlinedUrlData extends UrlData {
3919 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3922 mMimeType = mimeType;
3923 mEncoding = encoding;
3930 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
3934 public void loadIn(WebView webView) {
3935 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3939 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);