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.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Canvas;
42 import android.graphics.Picture;
43 import android.graphics.PixelFormat;
44 import android.graphics.Rect;
45 import android.graphics.drawable.Drawable;
46 import android.net.ConnectivityManager;
47 import android.net.Uri;
48 import android.net.WebAddress;
49 import android.net.http.SslCertificate;
50 import android.net.http.SslError;
51 import android.os.AsyncTask;
52 import android.os.Bundle;
53 import android.os.Debug;
54 import android.os.Environment;
55 import android.os.Handler;
56 import android.os.Message;
57 import android.os.PowerManager;
58 import android.os.Process;
59 import android.os.ServiceManager;
60 import android.os.SystemClock;
61 import android.provider.Browser;
62 import android.provider.ContactsContract;
63 import android.provider.ContactsContract.Intents.Insert;
64 import android.provider.Downloads;
65 import android.provider.MediaStore;
66 import android.text.IClipboard;
67 import android.text.TextUtils;
68 import android.text.format.DateFormat;
69 import android.util.AttributeSet;
70 import android.util.Log;
71 import android.view.ContextMenu;
72 import android.view.Gravity;
73 import android.view.KeyEvent;
74 import android.view.LayoutInflater;
75 import android.view.Menu;
76 import android.view.MenuInflater;
77 import android.view.MenuItem;
78 import android.view.View;
79 import android.view.ViewGroup;
80 import android.view.Window;
81 import android.view.WindowManager;
82 import android.view.ContextMenu.ContextMenuInfo;
83 import android.view.MenuItem.OnMenuItemClickListener;
84 import android.webkit.CookieManager;
85 import android.webkit.CookieSyncManager;
86 import android.webkit.DownloadListener;
87 import android.webkit.HttpAuthHandler;
88 import android.webkit.PluginManager;
89 import android.webkit.SslErrorHandler;
90 import android.webkit.URLUtil;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebChromeClient;
93 import android.webkit.WebHistoryItem;
94 import android.webkit.WebIconDatabase;
95 import android.webkit.WebView;
96 import android.widget.EditText;
97 import android.widget.FrameLayout;
98 import android.widget.LinearLayout;
99 import android.widget.TextView;
100 import android.widget.Toast;
101 import android.accounts.Account;
102 import android.accounts.AccountManager;
103 import android.accounts.AccountManagerFuture;
104 import android.accounts.AuthenticatorException;
105 import android.accounts.OperationCanceledException;
106 import android.accounts.AccountManagerCallback;
108 import com.android.common.Patterns;
110 import com.google.android.googlelogin.GoogleLoginServiceConstants;
112 import java.io.ByteArrayOutputStream;
114 import java.io.IOException;
115 import java.io.InputStream;
116 import java.net.MalformedURLException;
118 import java.net.URISyntaxException;
120 import java.net.URLEncoder;
121 import java.text.ParseException;
122 import java.util.Date;
123 import java.util.HashMap;
124 import java.util.regex.Matcher;
125 import java.util.regex.Pattern;
127 public class BrowserActivity extends Activity
128 implements View.OnCreateContextMenuListener, DownloadListener,
129 AccountManagerCallback<Account[]> {
131 /* Define some aliases to make these debugging flags easier to refer to.
132 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
134 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
145 private Account[] mAccountsGoogle;
146 private Account[] mAccountsPreferHosted;
148 private void startReadOfGoogleAccounts() {
149 mAccountsGoogle = null;
150 mAccountsPreferHosted = null;
152 AccountManager.get(this).getAccountsByTypeAndFeatures(
153 GoogleLoginServiceConstants.ACCOUNT_TYPE,
154 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
158 /** This implements AccountManagerCallback<Account[]> */
159 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
161 if (mAccountsGoogle == null) {
162 mAccountsGoogle = accountManagerFuture.getResult();
164 AccountManager.get(this).getAccountsByTypeAndFeatures(
165 GoogleLoginServiceConstants.ACCOUNT_TYPE,
166 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
169 mAccountsPreferHosted = accountManagerFuture.getResult();
172 } catch (OperationCanceledException e) {
174 } catch (IOException e) {
176 } catch (AuthenticatorException e) {
181 private void setupHomePage() {
182 // get the default home page
183 String homepage = mSettings.getHomePage();
185 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
188 // hostedUser == googleUser
189 // The device has only a google account
191 // hostedUser != googleUser
192 // The device has a hosted account and a google account
194 // hostedUser != null, googleUser == null
195 // The device has only a hosted account (so far)
196 String hostedUser = mAccountsPreferHosted.length == 0
198 : mAccountsPreferHosted[0].name;
199 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
201 // developers might have no accounts at all
202 if (hostedUser == null) return;
204 if (googleUser == null || !hostedUser.equals(googleUser)) {
205 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
206 homepage = homepage.replace("?", "/a/" + domain + "?");
210 mSettings.setHomePage(BrowserActivity.this, homepage);
211 resumeAfterCredentials();
214 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
216 public Void doInBackground(File... files) {
218 for (File f : files) {
220 Log.e(LOGTAG, f.getPath() + " was not deleted");
229 * This layout holds everything you see below the status bar, including the
230 * error console, the custom view container, and the webviews.
232 private FrameLayout mBrowserFrameLayout;
235 public void onCreate(Bundle icicle) {
237 Log.v(LOGTAG, this + " onStart");
239 super.onCreate(icicle);
240 // test the browser in OpenGL
241 // requestWindowFeature(Window.FEATURE_OPENGL);
243 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
245 mResolver = getContentResolver();
247 // If this was a web search request, pass it on to the default web
248 // search provider and finish this activity.
249 if (handleWebSearchIntent(getIntent())) {
254 mSecLockIcon = Resources.getSystem().getDrawable(
255 android.R.drawable.ic_secure);
256 mMixLockIcon = Resources.getSystem().getDrawable(
257 android.R.drawable.ic_partial_secure);
259 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
260 .findViewById(com.android.internal.R.id.content);
261 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
262 .inflate(R.layout.custom_screen, null);
263 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
265 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
266 .findViewById(R.id.error_console);
267 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
268 .findViewById(R.id.fullscreen_custom_content);
269 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
270 mTitleBar = new TitleBar(this);
271 mFakeTitleBar = new TitleBar(this);
273 // Create the tab control and our initial tab
274 mTabControl = new TabControl(this);
276 // Open the icon database and retain all the bookmark urls for favicons
277 retainIconsOnStartup();
279 // Keep a settings instance handy.
280 mSettings = BrowserSettings.getInstance();
281 mSettings.setTabControl(mTabControl);
282 mSettings.loadFromDb(this);
284 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
285 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
287 /* enables registration for changes in network status from
289 mNetworkStateChangedFilter = new IntentFilter();
290 mNetworkStateChangedFilter.addAction(
291 ConnectivityManager.CONNECTIVITY_ACTION);
292 mNetworkStateIntentReceiver = new BroadcastReceiver() {
294 public void onReceive(Context context, Intent intent) {
295 if (intent.getAction().equals(
296 ConnectivityManager.CONNECTIVITY_ACTION)) {
297 boolean noConnectivity = intent.getBooleanExtra(
298 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
299 onNetworkToggle(!noConnectivity);
304 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
305 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
306 filter.addDataScheme("package");
307 mPackageInstallationReceiver = new BroadcastReceiver() {
309 public void onReceive(Context context, Intent intent) {
310 final String action = intent.getAction();
311 final String packageName = intent.getData()
312 .getSchemeSpecificPart();
313 final boolean replacing = intent.getBooleanExtra(
314 Intent.EXTRA_REPLACING, false);
315 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
316 // if it is replacing, refreshPlugins() when adding
319 PackageManager pm = BrowserActivity.this.getPackageManager();
320 PackageInfo pkgInfo = null;
322 pkgInfo = pm.getPackageInfo(packageName,
323 PackageManager.GET_PERMISSIONS);
324 } catch (PackageManager.NameNotFoundException e) {
327 if (pkgInfo != null) {
328 String permissions[] = pkgInfo.requestedPermissions;
329 if (permissions == null) {
332 boolean permissionOk = false;
333 for (String permit : permissions) {
334 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
340 PluginManager.getInstance(BrowserActivity.this)
342 Intent.ACTION_PACKAGE_ADDED
348 registerReceiver(mPackageInstallationReceiver, filter);
350 if (!mTabControl.restoreState(icicle)) {
351 // clear up the thumbnail directory if we can't restore the state as
352 // none of the files in the directory are referenced any more.
353 new ClearThumbnails().execute(
354 mTabControl.getThumbnailDir().listFiles());
355 // there is no quit on Android. But if we can't restore the state,
356 // we can treat it as a new Browser, remove the old session cookies.
357 CookieManager.getInstance().removeSessionCookie();
358 final Intent intent = getIntent();
359 final Bundle extra = intent.getExtras();
360 // Create an initial tab.
361 // If the intent is ACTION_VIEW and data is not null, the Browser is
362 // invoked to view the content by another application. In this case,
363 // the tab will be close when exit.
364 UrlData urlData = getUrlDataFromIntent(intent);
366 final Tab t = mTabControl.createNewTab(
367 Intent.ACTION_VIEW.equals(intent.getAction()) &&
368 intent.getData() != null,
369 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
370 mTabControl.setCurrentTab(t);
371 attachTabToContentView(t);
372 WebView webView = t.getWebView();
374 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
375 if (scale > 0 && scale <= 1000) {
376 webView.setInitialScale(scale);
379 // If we are not restoring from an icicle, then there is a high
380 // likely hood this is the first run. So, check to see if the
381 // homepage needs to be configured and copy any plugins from our
382 // asset directory to the data partition.
383 if ((extra == null || !extra.getBoolean("testing"))
384 && !mSettings.isLoginInitialized()) {
385 startReadOfGoogleAccounts();
388 if (urlData.isEmpty()) {
389 if (mSettings.isLoginInitialized()) {
390 webView.loadUrl(mSettings.getHomePage());
392 waitForCredentials();
396 urlData.setPostData(extra
397 .getByteArray(Browser.EXTRA_POST_DATA));
399 urlData.loadIn(webView);
402 // TabControl.restoreState() will create a new tab even if
403 // restoring the state fails.
404 attachTabToContentView(mTabControl.getCurrentTab());
407 // Read JavaScript flags if it exists.
408 String jsFlags = mSettings.getJsFlags();
409 if (jsFlags.trim().length() != 0) {
410 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
415 protected void onNewIntent(Intent intent) {
416 Tab current = mTabControl.getCurrentTab();
417 // When a tab is closed on exit, the current tab index is set to -1.
418 // Reset before proceed as Browser requires the current tab to be set.
419 if (current == null) {
420 // Try to reset the tab in case the index was incorrect.
421 current = mTabControl.getTab(0);
422 if (current == null) {
423 // No tabs at all so just ignore this intent.
426 mTabControl.setCurrentTab(current);
427 attachTabToContentView(current);
428 resetTitleAndIcon(current.getWebView());
430 final String action = intent.getAction();
431 final int flags = intent.getFlags();
432 if (Intent.ACTION_MAIN.equals(action) ||
433 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
434 // just resume the browser
437 if (Intent.ACTION_VIEW.equals(action)
438 || Intent.ACTION_SEARCH.equals(action)
439 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
440 || Intent.ACTION_WEB_SEARCH.equals(action)) {
441 // If this was a search request (e.g. search query directly typed into the address bar),
442 // pass it on to the default web search provider.
443 if (handleWebSearchIntent(intent)) {
447 UrlData urlData = getUrlDataFromIntent(intent);
448 if (urlData.isEmpty()) {
449 urlData = new UrlData(mSettings.getHomePage());
451 urlData.setPostData(intent
452 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
454 final String appId = intent
455 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
456 if (Intent.ACTION_VIEW.equals(action)
457 && !getPackageName().equals(appId)
458 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
459 Tab appTab = mTabControl.getTabFromId(appId);
460 if (appTab != null) {
461 Log.i(LOGTAG, "Reusing tab for " + appId);
462 // Dismiss the subwindow if applicable.
463 dismissSubWindow(appTab);
464 // Since we might kill the WebView, remove it from the
465 // content view first.
466 removeTabFromContentView(appTab);
467 // Recreate the main WebView after destroying the old one.
468 // If the WebView has the same original url and is on that
469 // page, it can be reused.
471 mTabControl.recreateWebView(appTab, urlData.mUrl);
473 if (current != appTab) {
474 switchToTab(mTabControl.getTabIndex(appTab));
476 urlData.loadIn(appTab.getWebView());
479 // If the tab was the current tab, we have to attach
480 // it to the view system again.
481 attachTabToContentView(appTab);
483 urlData.loadIn(appTab.getWebView());
488 // No matching application tab, try to find a regular tab
489 // with a matching url.
490 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
491 if (appTab != null) {
492 if (current != appTab) {
493 switchToTab(mTabControl.getTabIndex(appTab));
495 // Otherwise, we are already viewing the correct tab.
497 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
498 // will be opened in a new tab unless we have reached
499 // MAX_TABS. Then the url will be opened in the current
500 // tab. If a new tab is created, it will have "true" for
502 openTabAndShow(urlData, true, appId);
506 if (!urlData.isEmpty()
507 && urlData.mUrl.startsWith("about:debug")) {
508 if ("about:debug.dom".equals(urlData.mUrl)) {
509 current.getWebView().dumpDomTree(false);
510 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
511 current.getWebView().dumpDomTree(true);
512 } else if ("about:debug.render".equals(urlData.mUrl)) {
513 current.getWebView().dumpRenderTree(false);
514 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
515 current.getWebView().dumpRenderTree(true);
516 } else if ("about:debug.display".equals(urlData.mUrl)) {
517 current.getWebView().dumpDisplayTree();
518 } else if ("about:debug.drag0".equals(urlData.mUrl)) {
519 current.getWebView().setDragTracker(null);
520 } else if ("about:debug.drag1".equals(urlData.mUrl)) {
521 current.getWebView().setDragTracker(new MeshTracker(1));
522 } else if ("about:debug.drag2".equals(urlData.mUrl)) {
523 current.getWebView().setDragTracker(new MeshTracker(2));
525 mSettings.toggleDebugSettings();
529 // Get rid of the subwindow if it exists
530 dismissSubWindow(current);
531 urlData.loadIn(current.getWebView());
536 private int parseUrlShortcut(String url) {
537 if (url == null) return SHORTCUT_INVALID;
539 // FIXME: quick search, need to be customized by setting
540 if (url.length() > 2 && url.charAt(1) == ' ') {
541 switch (url.charAt(0)) {
542 case 'g': return SHORTCUT_GOOGLE_SEARCH;
543 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
544 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
545 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
548 return SHORTCUT_INVALID;
552 * Launches the default web search activity with the query parameters if the given intent's data
553 * are identified as plain search terms and not URLs/shortcuts.
554 * @return true if the intent was handled and web search activity was launched, false if not.
556 private boolean handleWebSearchIntent(Intent intent) {
557 if (intent == null) return false;
560 final String action = intent.getAction();
561 if (Intent.ACTION_VIEW.equals(action)) {
562 Uri data = intent.getData();
563 if (data != null) url = data.toString();
564 } else if (Intent.ACTION_SEARCH.equals(action)
565 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
566 || Intent.ACTION_WEB_SEARCH.equals(action)) {
567 url = intent.getStringExtra(SearchManager.QUERY);
569 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
570 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
574 * Launches the default web search activity with the query parameters if the given url string
575 * was identified as plain search terms and not URL/shortcut.
576 * @return true if the request was handled and web search activity was launched, false if not.
578 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
579 if (inUrl == null) return false;
581 // In general, we shouldn't modify URL from Intent.
582 // But currently, we get the user-typed URL from search box as well.
583 String url = fixUrl(inUrl).trim();
585 // URLs and site specific search shortcuts are handled by the regular flow of control, so
587 if (Patterns.WEB_URL.matcher(url).matches()
588 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
589 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
593 Browser.updateVisitedHistory(mResolver, url, false);
594 Browser.addSearchUrl(mResolver, url);
596 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
597 intent.addCategory(Intent.CATEGORY_DEFAULT);
598 intent.putExtra(SearchManager.QUERY, url);
599 if (appData != null) {
600 intent.putExtra(SearchManager.APP_DATA, appData);
602 if (extraData != null) {
603 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
605 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
606 startActivity(intent);
611 private UrlData getUrlDataFromIntent(Intent intent) {
613 if (intent != null) {
614 final String action = intent.getAction();
615 if (Intent.ACTION_VIEW.equals(action)) {
616 url = smartUrlFilter(intent.getData());
617 if (url != null && url.startsWith("content:")) {
618 /* Append mimetype so webview knows how to display */
619 String mimeType = intent.resolveType(getContentResolver());
620 if (mimeType != null) {
621 url += "?" + mimeType;
624 if ("inline:".equals(url)) {
625 return new InlinedUrlData(
626 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
628 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
629 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
631 } else if (Intent.ACTION_SEARCH.equals(action)
632 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
633 || Intent.ACTION_WEB_SEARCH.equals(action)) {
634 url = intent.getStringExtra(SearchManager.QUERY);
636 mLastEnteredUrl = url;
637 Browser.updateVisitedHistory(mResolver, url, false);
638 // In general, we shouldn't modify URL from Intent.
639 // But currently, we get the user-typed URL from search box as well.
641 url = smartUrlFilter(url);
642 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
643 if (url.contains(searchSource)) {
644 String source = null;
645 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
646 if (appData != null) {
647 source = appData.getString(SearchManager.SOURCE);
649 if (TextUtils.isEmpty(source)) {
650 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
652 url = url.replace(searchSource, "&source=android-"+source+"&");
657 return new UrlData(url);
660 /* package */ static String fixUrl(String inUrl) {
661 // FIXME: Converting the url to lower case
662 // duplicates functionality in smartUrlFilter().
663 // However, changing all current callers of fixUrl to
664 // call smartUrlFilter in addition may have unwanted
665 // consequences, and is deferred for now.
666 int colon = inUrl.indexOf(':');
667 boolean allLower = true;
668 for (int index = 0; index < colon; index++) {
669 char ch = inUrl.charAt(index);
670 if (!Character.isLetter(ch)) {
673 allLower &= Character.isLowerCase(ch);
674 if (index == colon - 1 && !allLower) {
675 inUrl = inUrl.substring(0, colon).toLowerCase()
676 + inUrl.substring(colon);
679 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
681 if (inUrl.startsWith("http:") ||
682 inUrl.startsWith("https:")) {
683 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
684 inUrl = inUrl.replaceFirst("/", "//");
685 } else inUrl = inUrl.replaceFirst(":", "://");
691 protected void onResume() {
694 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
697 if (!mActivityInPause) {
698 Log.e(LOGTAG, "BrowserActivity is already resumed.");
702 mTabControl.resumeCurrentTab();
703 mActivityInPause = false;
704 resumeWebViewTimers();
706 if (mWakeLock.isHeld()) {
707 mHandler.removeMessages(RELEASE_WAKELOCK);
711 if (mCredsDlg != null) {
712 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
713 // In case credential request never comes back
714 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
718 registerReceiver(mNetworkStateIntentReceiver,
719 mNetworkStateChangedFilter);
720 WebView.enablePlatformNotifications();
724 * Since the actual title bar is embedded in the WebView, and removing it
725 * would change its appearance, use a different TitleBar to show overlayed
726 * at the top of the screen, when the menu is open or the page is loading.
728 private TitleBar mFakeTitleBar;
731 * Holder for the fake title bar. It will have a foreground shadow, as well
732 * as a white background, so the fake title bar looks like the real one.
734 private ViewGroup mFakeTitleBarHolder;
737 * Layout parameters for the fake title bar within mFakeTitleBarHolder
739 private FrameLayout.LayoutParams mFakeTitleBarParams
740 = new FrameLayout.LayoutParams(
741 ViewGroup.LayoutParams.MATCH_PARENT,
742 ViewGroup.LayoutParams.WRAP_CONTENT);
744 * Keeps track of whether the options menu is open. This is important in
745 * determining whether to show or hide the title bar overlay.
747 private boolean mOptionsMenuOpen;
750 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
751 * of whether the configuration has changed. The first onMenuOpened call
752 * after a configuration change is simply a reopening of the same menu
753 * (i.e. mIconView did not change).
755 private boolean mConfigChanged;
758 * Whether or not the options menu is in its smaller, icon menu form. When
759 * true, we want the title bar overlay to be up. When false, we do not.
760 * Only meaningful if mOptionsMenuOpen is true.
762 private boolean mIconView;
765 public boolean onMenuOpened(int featureId, Menu menu) {
766 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
767 if (mOptionsMenuOpen) {
768 if (mConfigChanged) {
769 // We do not need to make any changes to the state of the
770 // title bar, since the only thing that happened was a
771 // change in orientation
772 mConfigChanged = false;
775 // Switching the menu to expanded view, so hide the
780 // Switching the menu back to icon view, so show the
781 // title bar once again.
787 // The options menu is closed, so open it, and show the title
789 mOptionsMenuOpen = true;
790 mConfigChanged = false;
798 * Special class used exclusively for the shadow drawn underneath the fake
799 * title bar. The shadow does not need to be drawn if the WebView
800 * underneath is scrolled to the top, because it will draw directly on top
801 * of the embedded shadow.
803 private static class Shadow extends View {
804 private WebView mWebView;
806 public Shadow(Context context, AttributeSet attrs) {
807 super(context, attrs);
810 public void setWebView(WebView view) {
815 public void draw(Canvas canvas) {
816 // In general onDraw is the method to override, but we care about
817 // whether or not the background gets drawn, which happens in draw()
818 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
821 // Need to invalidate so that if the scroll position changes, we
822 // still draw as appropriate.
827 private void showFakeTitleBar() {
828 final View decor = getWindow().peekDecorView();
829 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
830 && !mActivityInPause && decor != null
831 && decor.getWindowToken() != null) {
832 Rect visRect = new Rect();
833 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
835 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
840 WindowManager manager
841 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
843 // Add the title bar to the window manager so it can receive touches
844 // while the menu is up
845 WindowManager.LayoutParams params
846 = new WindowManager.LayoutParams(
847 ViewGroup.LayoutParams.MATCH_PARENT,
848 ViewGroup.LayoutParams.WRAP_CONTENT,
849 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
850 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
851 PixelFormat.TRANSLUCENT);
852 params.gravity = Gravity.TOP;
853 WebView mainView = mTabControl.getCurrentWebView();
854 boolean atTop = mainView != null && mainView.getScrollY() == 0;
855 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
856 // XXX : Without providing an offset, the fake title bar will be
857 // placed underneath the status bar. Use the global visible rect
858 // of mBrowserFrameLayout to determine the bottom of the status bar
859 params.y = visRect.top;
860 // Add a holder for the title bar. It also holds a shadow to show
861 // below the title bar.
862 if (mFakeTitleBarHolder == null) {
863 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
864 .inflate(R.layout.title_bar_bg, null);
866 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
868 shadow.setWebView(mainView);
869 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
870 manager.addView(mFakeTitleBarHolder, params);
875 public void onOptionsMenuClosed(Menu menu) {
876 mOptionsMenuOpen = false;
879 } else if (!mIconView) {
880 // The page is currently loading, and we are in expanded mode, so
881 // we were not showing the menu. Show it once again. It will be
882 // removed when the page finishes.
887 private void hideFakeTitleBar() {
888 if (mFakeTitleBar.getParent() == null) return;
889 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
890 mFakeTitleBarHolder.getLayoutParams();
891 WebView mainView = mTabControl.getCurrentWebView();
892 // Although we decided whether or not to animate based on the current
893 // scroll position, the scroll position may have changed since the
894 // fake title bar was displayed. Make sure it has the appropriate
895 // animation/lack thereof before removing.
896 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
897 ? 0 : R.style.TitleBar;
898 WindowManager manager
899 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
900 manager.updateViewLayout(mFakeTitleBarHolder, params);
901 mFakeTitleBarHolder.removeView(mFakeTitleBar);
902 manager.removeView(mFakeTitleBarHolder);
906 * Special method for the fake title bar to call when displaying its context
907 * menu, since it is in its own Window, and its parent does not show a
910 /* package */ void showTitleBarContextMenu() {
911 if (null == mTitleBar.getParent()) {
914 openContextMenu(mTitleBar);
918 public void onContextMenuClosed(Menu menu) {
919 super.onContextMenuClosed(menu);
926 * onSaveInstanceState(Bundle map)
927 * onSaveInstanceState is called right before onStop(). The map contains
931 protected void onSaveInstanceState(Bundle outState) {
933 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
935 // the default implementation requires each view to have an id. As the
936 // browser handles the state itself and it doesn't use id for the views,
937 // don't call the default implementation. Otherwise it will trigger the
938 // warning like this, "couldn't save which view has focus because the
939 // focused view XXX has no id".
942 mTabControl.saveState(outState);
946 protected void onPause() {
949 if (mActivityInPause) {
950 Log.e(LOGTAG, "BrowserActivity is already paused.");
954 mTabControl.pauseCurrentTab();
955 mActivityInPause = true;
956 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
958 mHandler.sendMessageDelayed(mHandler
959 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
962 // Clear the credentials toast if it is up
963 if (mCredsDlg != null && mCredsDlg.isShowing()) {
968 // FIXME: This removes the active tabs page and resets the menu to
969 // MAIN_MENU. A better solution might be to do this work in onNewIntent
970 // but then we would need to save it in onSaveInstanceState and restore
971 // it in onCreate/onRestoreInstanceState
972 if (mActiveTabsPage != null) {
973 removeActiveTabPage(true);
978 // unregister network state listener
979 unregisterReceiver(mNetworkStateIntentReceiver);
980 WebView.disablePlatformNotifications();
984 protected void onDestroy() {
986 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
990 if (mUploadMessage != null) {
991 mUploadMessage.onReceiveValue(null);
992 mUploadMessage = null;
995 if (mTabControl == null) return;
997 // Remove the fake title bar if it is there
1000 // Remove the current tab and sub window
1001 Tab t = mTabControl.getCurrentTab();
1003 dismissSubWindow(t);
1004 removeTabFromContentView(t);
1006 // Destroy all the tabs
1007 mTabControl.destroy();
1008 WebIconDatabase.getInstance().close();
1010 unregisterReceiver(mPackageInstallationReceiver);
1014 public void onConfigurationChanged(Configuration newConfig) {
1015 mConfigChanged = true;
1016 super.onConfigurationChanged(newConfig);
1018 if (mPageInfoDialog != null) {
1019 mPageInfoDialog.dismiss();
1022 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1024 if (mSSLCertificateDialog != null) {
1025 mSSLCertificateDialog.dismiss();
1027 mSSLCertificateView);
1029 if (mSSLCertificateOnErrorDialog != null) {
1030 mSSLCertificateOnErrorDialog.dismiss();
1031 showSSLCertificateOnError(
1032 mSSLCertificateOnErrorView,
1033 mSSLCertificateOnErrorHandler,
1034 mSSLCertificateOnErrorError);
1036 if (mHttpAuthenticationDialog != null) {
1037 String title = ((TextView) mHttpAuthenticationDialog
1038 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1040 String name = ((TextView) mHttpAuthenticationDialog
1041 .findViewById(R.id.username_edit)).getText().toString();
1042 String password = ((TextView) mHttpAuthenticationDialog
1043 .findViewById(R.id.password_edit)).getText().toString();
1044 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1046 mHttpAuthenticationDialog.dismiss();
1047 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1048 name, password, focusId);
1053 public void onLowMemory() {
1054 super.onLowMemory();
1055 mTabControl.freeMemory();
1058 private boolean resumeWebViewTimers() {
1059 Tab tab = mTabControl.getCurrentTab();
1060 boolean inLoad = tab.inLoad();
1061 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1062 CookieSyncManager.getInstance().startSync();
1063 WebView w = tab.getWebView();
1073 private boolean pauseWebViewTimers() {
1074 Tab tab = mTabControl.getCurrentTab();
1075 boolean inLoad = tab.inLoad();
1076 if (mActivityInPause && !inLoad) {
1077 CookieSyncManager.getInstance().stopSync();
1078 WebView w = mTabControl.getCurrentWebView();
1088 // FIXME: Do we want to call this when loading google for the first time?
1090 * This function is called when we are launching for the first time. We
1091 * are waiting for the login credentials before loading Google home
1092 * pages. This way the user will be logged in straight away.
1094 private void waitForCredentials() {
1096 mCredsDlg = new ProgressDialog(this);
1097 mCredsDlg.setIndeterminate(true);
1098 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1099 // If the user cancels the operation, then cancel the Google
1100 // Credentials request.
1101 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1104 // We set a timeout for the retrieval of credentials in onResume()
1105 // as that is when we have freed up some CPU time to get
1106 // the login credentials.
1110 * If we have received the credentials or we have timed out and we are
1111 * showing the credentials dialog, then it is time to move on.
1113 private void resumeAfterCredentials() {
1114 if (mCredsDlg == null) {
1119 if (mCredsDlg.isShowing()) {
1120 mCredsDlg.dismiss();
1124 // Clear any pending timeout
1125 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1128 WebView w = mTabControl.getCurrentWebView();
1130 w.loadUrl(mSettings.getHomePage());
1133 // Update the settings, need to do this last as it can take a moment
1134 // to persist the settings. In the mean time we could be loading
1136 mSettings.setLoginInitialized(this);
1139 // Open the icon database and retain all the icons for visited sites.
1140 private void retainIconsOnStartup() {
1141 final WebIconDatabase db = WebIconDatabase.getInstance();
1142 db.open(getDir("icons", 0).getPath());
1144 Cursor c = Browser.getAllBookmarks(mResolver);
1145 if (!c.moveToFirst()) {
1149 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1151 String url = c.getString(urlIndex);
1152 db.retainIconForPageUrl(url);
1153 } while (c.moveToNext());
1155 } catch (IllegalStateException e) {
1156 Log.e(LOGTAG, "retainIconsOnStartup", e);
1160 // Helper method for getting the top window.
1161 WebView getTopWindow() {
1162 return mTabControl.getCurrentTopWebView();
1165 TabControl getTabControl() {
1170 public boolean onCreateOptionsMenu(Menu menu) {
1171 super.onCreateOptionsMenu(menu);
1173 MenuInflater inflater = getMenuInflater();
1174 inflater.inflate(R.menu.browser, menu);
1176 updateInLoadMenuItems();
1181 * As the menu can be open when loading state changes
1182 * we must manually update the state of the stop/reload menu
1185 private void updateInLoadMenuItems() {
1186 if (mMenu == null) {
1189 MenuItem src = mInLoad ?
1190 mMenu.findItem(R.id.stop_menu_id):
1191 mMenu.findItem(R.id.reload_menu_id);
1192 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1193 dest.setIcon(src.getIcon());
1194 dest.setTitle(src.getTitle());
1198 public boolean onContextItemSelected(MenuItem item) {
1199 // chording is not an issue with context menus, but we use the same
1200 // options selector, so set mCanChord to true so we can access them.
1202 int id = item.getItemId();
1204 // For the context menu from the title bar
1205 case R.id.title_bar_share_page_url:
1206 case R.id.title_bar_copy_page_url:
1207 WebView mainView = mTabControl.getCurrentWebView();
1208 if (null == mainView) {
1211 if (id == R.id.title_bar_share_page_url) {
1212 Browser.sendString(this, mainView.getUrl());
1214 copy(mainView.getUrl());
1217 // -- Browser context menu
1218 case R.id.open_context_menu_id:
1219 case R.id.open_newtab_context_menu_id:
1220 case R.id.bookmark_context_menu_id:
1221 case R.id.save_link_context_menu_id:
1222 case R.id.share_link_context_menu_id:
1223 case R.id.copy_link_context_menu_id:
1224 final WebView webView = getTopWindow();
1225 if (null == webView) {
1228 final HashMap hrefMap = new HashMap();
1229 hrefMap.put("webview", webView);
1230 final Message msg = mHandler.obtainMessage(
1231 FOCUS_NODE_HREF, id, 0, hrefMap);
1232 webView.requestFocusNodeHref(msg);
1236 // For other context menus
1237 return onOptionsItemSelected(item);
1243 private Bundle createGoogleSearchSourceBundle(String source) {
1244 Bundle bundle = new Bundle();
1245 bundle.putString(SearchManager.SOURCE, source);
1250 * Overriding this to insert a local information bundle
1253 public boolean onSearchRequested() {
1254 if (mOptionsMenuOpen) closeOptionsMenu();
1255 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1256 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1257 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1262 public void startSearch(String initialQuery, boolean selectInitialQuery,
1263 Bundle appSearchData, boolean globalSearch) {
1264 if (appSearchData == null) {
1265 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1267 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1271 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1272 * results in changing tabs.
1273 * @param index Index of the tab to change to, as defined by
1274 * mTabControl.getTabIndex(Tab t).
1275 * @return boolean True if we successfully switched to a different tab. If
1276 * the indexth tab is null, or if that tab is the same as
1277 * the current one, return false.
1279 /* package */ boolean switchToTab(int index) {
1280 Tab tab = mTabControl.getTab(index);
1281 Tab currentTab = mTabControl.getCurrentTab();
1282 if (tab == null || tab == currentTab) {
1285 if (currentTab != null) {
1286 // currentTab may be null if it was just removed. In that case,
1287 // we do not need to remove it
1288 removeTabFromContentView(currentTab);
1290 mTabControl.setCurrentTab(tab);
1291 attachTabToContentView(tab);
1292 resetTitleIconAndProgress();
1293 updateLockIconToLatest();
1297 /* package */ Tab openTabToHomePage() {
1298 return openTabAndShow(mSettings.getHomePage(), false, null);
1301 /* package */ void closeCurrentWindow() {
1302 final Tab current = mTabControl.getCurrentTab();
1303 if (mTabControl.getTabCount() == 1) {
1304 // This is the last tab. Open a new one, with the home
1305 // page and close the current one.
1306 openTabToHomePage();
1310 final Tab parent = current.getParentTab();
1311 int indexToShow = -1;
1312 if (parent != null) {
1313 indexToShow = mTabControl.getTabIndex(parent);
1315 final int currentIndex = mTabControl.getCurrentIndex();
1316 // Try to move to the tab to the right
1317 indexToShow = currentIndex + 1;
1318 if (indexToShow > mTabControl.getTabCount() - 1) {
1319 // Try to move to the tab to the left
1320 indexToShow = currentIndex - 1;
1323 if (switchToTab(indexToShow)) {
1329 private ActiveTabsPage mActiveTabsPage;
1332 * Remove the active tabs page.
1333 * @param needToAttach If true, the active tabs page did not attach a tab
1334 * to the content view, so we need to do that here.
1336 /* package */ void removeActiveTabPage(boolean needToAttach) {
1337 mContentView.removeView(mActiveTabsPage);
1338 mActiveTabsPage = null;
1339 mMenuState = R.id.MAIN_MENU;
1341 attachTabToContentView(mTabControl.getCurrentTab());
1343 getTopWindow().requestFocus();
1347 public boolean onOptionsItemSelected(MenuItem item) {
1349 // The user has already fired a shortcut with this hold down of the
1353 if (null == getTopWindow()) {
1357 // The shortcut action consumes the MENU. Even if it is still down,
1358 // it won't trigger the next shortcut action. In the case of the
1359 // shortcut action triggering a new activity, like Bookmarks, we
1360 // won't get onKeyUp for MENU. So it is important to reset it here.
1361 mMenuIsDown = false;
1363 switch (item.getItemId()) {
1365 case R.id.new_tab_menu_id:
1366 openTabToHomePage();
1369 case R.id.goto_menu_id:
1370 onSearchRequested();
1373 case R.id.bookmarks_menu_id:
1374 bookmarksOrHistoryPicker(false);
1377 case R.id.active_tabs_menu_id:
1378 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1379 removeTabFromContentView(mTabControl.getCurrentTab());
1381 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1382 mActiveTabsPage.requestFocus();
1383 mMenuState = EMPTY_MENU;
1386 case R.id.add_bookmark_menu_id:
1387 Intent i = new Intent(BrowserActivity.this,
1388 AddBookmarkPage.class);
1389 WebView w = getTopWindow();
1390 i.putExtra("url", w.getUrl());
1391 i.putExtra("title", w.getTitle());
1392 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1393 i.putExtra("thumbnail", createScreenshot(w));
1397 case R.id.stop_reload_menu_id:
1401 getTopWindow().reload();
1405 case R.id.back_menu_id:
1406 getTopWindow().goBack();
1409 case R.id.forward_menu_id:
1410 getTopWindow().goForward();
1413 case R.id.close_menu_id:
1414 // Close the subwindow if it exists.
1415 if (mTabControl.getCurrentSubWindow() != null) {
1416 dismissSubWindow(mTabControl.getCurrentTab());
1419 closeCurrentWindow();
1422 case R.id.homepage_menu_id:
1423 Tab current = mTabControl.getCurrentTab();
1424 if (current != null) {
1425 dismissSubWindow(current);
1426 current.getWebView().loadUrl(mSettings.getHomePage());
1430 case R.id.preferences_menu_id:
1431 Intent intent = new Intent(this,
1432 BrowserPreferencesPage.class);
1433 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1434 getTopWindow().getUrl());
1435 startActivityForResult(intent, PREFERENCES_PAGE);
1438 case R.id.find_menu_id:
1439 if (null == mFindDialog) {
1440 mFindDialog = new FindDialog(this);
1442 mFindDialog.setWebView(getTopWindow());
1444 mMenuState = EMPTY_MENU;
1447 case R.id.select_text_id:
1448 getTopWindow().emulateShiftHeld();
1450 case R.id.page_info_menu_id:
1451 showPageInfo(mTabControl.getCurrentTab(), false);
1454 case R.id.classic_history_menu_id:
1455 bookmarksOrHistoryPicker(true);
1458 case R.id.share_page_menu_id:
1459 Browser.sendString(this, getTopWindow().getUrl(),
1460 getText(R.string.choosertitle_sharevia).toString());
1463 case R.id.dump_nav_menu_id:
1464 getTopWindow().debugDump();
1467 case R.id.zoom_in_menu_id:
1468 getTopWindow().zoomIn();
1471 case R.id.zoom_out_menu_id:
1472 getTopWindow().zoomOut();
1475 case R.id.view_downloads_menu_id:
1476 viewDownloads(null);
1479 case R.id.window_one_menu_id:
1480 case R.id.window_two_menu_id:
1481 case R.id.window_three_menu_id:
1482 case R.id.window_four_menu_id:
1483 case R.id.window_five_menu_id:
1484 case R.id.window_six_menu_id:
1485 case R.id.window_seven_menu_id:
1486 case R.id.window_eight_menu_id:
1488 int menuid = item.getItemId();
1489 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1490 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1491 Tab desiredTab = mTabControl.getTab(id);
1492 if (desiredTab != null &&
1493 desiredTab != mTabControl.getCurrentTab()) {
1503 if (!super.onOptionsItemSelected(item)) {
1506 // Otherwise fall through.
1512 public void closeFind() {
1513 mMenuState = R.id.MAIN_MENU;
1517 public boolean onPrepareOptionsMenu(Menu menu) {
1518 // This happens when the user begins to hold down the menu key, so
1519 // allow them to chord to get a shortcut.
1521 // Note: setVisible will decide whether an item is visible; while
1522 // setEnabled() will decide whether an item is enabled, which also means
1523 // whether the matching shortcut key will function.
1524 super.onPrepareOptionsMenu(menu);
1525 switch (mMenuState) {
1527 if (mCurrentMenuState != mMenuState) {
1528 menu.setGroupVisible(R.id.MAIN_MENU, false);
1529 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1530 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1534 if (mCurrentMenuState != mMenuState) {
1535 menu.setGroupVisible(R.id.MAIN_MENU, true);
1536 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1537 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1539 final WebView w = getTopWindow();
1540 boolean canGoBack = false;
1541 boolean canGoForward = false;
1542 boolean isHome = false;
1544 canGoBack = w.canGoBack();
1545 canGoForward = w.canGoForward();
1546 isHome = mSettings.getHomePage().equals(w.getUrl());
1548 final MenuItem back = menu.findItem(R.id.back_menu_id);
1549 back.setEnabled(canGoBack);
1551 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1552 home.setEnabled(!isHome);
1554 menu.findItem(R.id.forward_menu_id)
1555 .setEnabled(canGoForward);
1557 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1558 mTabControl.canCreateNewTab());
1560 // decide whether to show the share link option
1561 PackageManager pm = getPackageManager();
1562 Intent send = new Intent(Intent.ACTION_SEND);
1563 send.setType("text/plain");
1564 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1565 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1567 boolean isNavDump = mSettings.isNavDump();
1568 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1569 nav.setVisible(isNavDump);
1570 nav.setEnabled(isNavDump);
1573 mCurrentMenuState = mMenuState;
1578 public void onCreateContextMenu(ContextMenu menu, View v,
1579 ContextMenuInfo menuInfo) {
1580 WebView webview = (WebView) v;
1581 WebView.HitTestResult result = webview.getHitTestResult();
1582 if (result == null) {
1586 int type = result.getType();
1587 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1589 "We should not show context menu when nothing is touched");
1592 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1593 // let TextView handles context menu
1597 // Note, http://b/issue?id=1106666 is requesting that
1598 // an inflated menu can be used again. This is not available
1599 // yet, so inflate each time (yuk!)
1600 MenuInflater inflater = getMenuInflater();
1601 inflater.inflate(R.menu.browsercontext, menu);
1603 // Show the correct menu group
1604 String extra = result.getExtra();
1605 menu.setGroupVisible(R.id.PHONE_MENU,
1606 type == WebView.HitTestResult.PHONE_TYPE);
1607 menu.setGroupVisible(R.id.EMAIL_MENU,
1608 type == WebView.HitTestResult.EMAIL_TYPE);
1609 menu.setGroupVisible(R.id.GEO_MENU,
1610 type == WebView.HitTestResult.GEO_TYPE);
1611 menu.setGroupVisible(R.id.IMAGE_MENU,
1612 type == WebView.HitTestResult.IMAGE_TYPE
1613 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1614 menu.setGroupVisible(R.id.ANCHOR_MENU,
1615 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1616 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1618 // Setup custom handling depending on the type
1620 case WebView.HitTestResult.PHONE_TYPE:
1621 menu.setHeaderTitle(Uri.decode(extra));
1622 menu.findItem(R.id.dial_context_menu_id).setIntent(
1623 new Intent(Intent.ACTION_VIEW, Uri
1624 .parse(WebView.SCHEME_TEL + extra)));
1625 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1626 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1627 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1628 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1630 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1634 case WebView.HitTestResult.EMAIL_TYPE:
1635 menu.setHeaderTitle(extra);
1636 menu.findItem(R.id.email_context_menu_id).setIntent(
1637 new Intent(Intent.ACTION_VIEW, Uri
1638 .parse(WebView.SCHEME_MAILTO + extra)));
1639 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1643 case WebView.HitTestResult.GEO_TYPE:
1644 menu.setHeaderTitle(extra);
1645 menu.findItem(R.id.map_context_menu_id).setIntent(
1646 new Intent(Intent.ACTION_VIEW, Uri
1647 .parse(WebView.SCHEME_GEO
1648 + URLEncoder.encode(extra))));
1649 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1653 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1654 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1655 TextView titleView = (TextView) LayoutInflater.from(this)
1656 .inflate(android.R.layout.browser_link_context_header,
1658 titleView.setText(extra);
1659 menu.setHeaderView(titleView);
1660 // decide whether to show the open link in new tab option
1661 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1662 mTabControl.canCreateNewTab());
1663 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1664 Bookmarks.urlHasAcceptableScheme(extra));
1665 PackageManager pm = getPackageManager();
1666 Intent send = new Intent(Intent.ACTION_SEND);
1667 send.setType("text/plain");
1668 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1669 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1670 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1673 // otherwise fall through to handle image part
1674 case WebView.HitTestResult.IMAGE_TYPE:
1675 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1676 menu.setHeaderTitle(extra);
1678 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1679 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1680 menu.findItem(R.id.download_context_menu_id).
1681 setOnMenuItemClickListener(new Download(extra));
1682 menu.findItem(R.id.set_wallpaper_context_menu_id).
1683 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1687 Log.w(LOGTAG, "We should not get here.");
1693 // Attach the given tab to the content view.
1694 // this should only be called for the current tab.
1695 private void attachTabToContentView(Tab t) {
1696 // Attach the container that contains the main WebView and any other UI
1697 // associated with the tab.
1698 t.attachTabToContentView(mContentView);
1700 if (mShouldShowErrorConsole) {
1701 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1702 if (errorConsole.numberOfErrors() == 0) {
1703 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1705 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1708 mErrorConsoleContainer.addView(errorConsole,
1709 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1710 ViewGroup.LayoutParams.WRAP_CONTENT));
1713 WebView view = t.getWebView();
1714 view.setEmbeddedTitleBar(mTitleBar);
1715 // Request focus on the top window.
1716 t.getTopWindow().requestFocus();
1719 // Attach a sub window to the main WebView of the given tab.
1720 void attachSubWindow(Tab t) {
1721 t.attachSubWindow(mContentView);
1722 getTopWindow().requestFocus();
1725 // Remove the given tab from the content view.
1726 private void removeTabFromContentView(Tab t) {
1727 // Remove the container that contains the main WebView.
1728 t.removeTabFromContentView(mContentView);
1730 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1731 if (errorConsole != null) {
1732 mErrorConsoleContainer.removeView(errorConsole);
1735 WebView view = t.getWebView();
1737 view.setEmbeddedTitleBar(null);
1741 // Remove the sub window if it exists. Also called by TabControl when the
1742 // user clicks the 'X' to dismiss a sub window.
1743 /* package */ void dismissSubWindow(Tab t) {
1744 t.removeSubWindow(mContentView);
1745 // dismiss the subwindow. This will destroy the WebView.
1746 t.dismissSubWindow();
1747 getTopWindow().requestFocus();
1750 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1751 // that accepts url as string.
1752 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1753 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1756 // This method does a ton of stuff. It will attempt to create a new tab
1757 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1758 // url isn't null, it will load the given url.
1759 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1761 final Tab currentTab = mTabControl.getCurrentTab();
1762 if (mTabControl.canCreateNewTab()) {
1763 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1765 WebView webview = tab.getWebView();
1766 // If the last tab was removed from the active tabs page, currentTab
1768 if (currentTab != null) {
1769 removeTabFromContentView(currentTab);
1771 // We must set the new tab as the current tab to reflect the old
1772 // animation behavior.
1773 mTabControl.setCurrentTab(tab);
1774 attachTabToContentView(tab);
1775 if (!urlData.isEmpty()) {
1776 urlData.loadIn(webview);
1780 // Get rid of the subwindow if it exists
1781 dismissSubWindow(currentTab);
1782 if (!urlData.isEmpty()) {
1783 // Load the given url.
1784 urlData.loadIn(currentTab.getWebView());
1790 private Tab openTab(String url) {
1791 if (mSettings.openInBackground()) {
1792 Tab t = mTabControl.createNewTab();
1794 WebView view = t.getWebView();
1799 return openTabAndShow(url, false, null);
1803 private class Copy implements OnMenuItemClickListener {
1804 private CharSequence mText;
1806 public boolean onMenuItemClick(MenuItem item) {
1811 public Copy(CharSequence toCopy) {
1816 private class Download implements OnMenuItemClickListener {
1817 private String mText;
1819 public boolean onMenuItemClick(MenuItem item) {
1820 onDownloadStartNoStream(mText, null, null, null, -1);
1824 public Download(String toDownload) {
1829 private class SetAsWallpaper extends Thread implements
1830 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1832 private ProgressDialog mWallpaperProgress;
1833 private boolean mCanceled = false;
1835 public SetAsWallpaper(String url) {
1837 mUrl = new URL(url);
1838 } catch (MalformedURLException e) {
1843 public void onCancel(DialogInterface dialog) {
1847 public boolean onMenuItemClick(MenuItem item) {
1849 // The user may have tried to set a image with a large file size as their
1850 // background so it may take a few moments to perform the operation. Display
1851 // a progress spinner while it is working.
1852 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1853 mWallpaperProgress.setIndeterminate(true);
1854 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1855 mWallpaperProgress.setCancelable(true);
1856 mWallpaperProgress.setOnCancelListener(this);
1857 mWallpaperProgress.show();
1864 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1866 // TODO: This will cause the resource to be downloaded again, when we
1867 // should in most cases be able to grab it from the cache. To fix this
1868 // we should query WebCore to see if we can access a cached version and
1869 // instead open an input stream on that. This pattern could also be used
1870 // in the download manager where the same problem exists.
1871 InputStream inputstream = mUrl.openStream();
1872 if (inputstream != null) {
1873 setWallpaper(inputstream);
1875 } catch (IOException e) {
1876 Log.e(LOGTAG, "Unable to set new wallpaper");
1877 // Act as though the user canceled the operation so we try to
1878 // restore the old wallpaper.
1883 // Restore the old wallpaper if the user cancelled whilst we were setting
1884 // the new wallpaper.
1885 int width = oldWallpaper.getIntrinsicWidth();
1886 int height = oldWallpaper.getIntrinsicHeight();
1887 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1888 Canvas canvas = new Canvas(bm);
1889 oldWallpaper.setBounds(0, 0, width, height);
1890 oldWallpaper.draw(canvas);
1893 } catch (IOException e) {
1894 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1899 if (mWallpaperProgress.isShowing()) {
1900 mWallpaperProgress.dismiss();
1905 private void copy(CharSequence text) {
1907 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1909 clip.setClipboardText(text);
1911 } catch (android.os.RemoteException e) {
1912 Log.e(LOGTAG, "Copy failed", e);
1917 * Resets the browser title-view to whatever it must be
1918 * (for example, if we had a loading error)
1919 * When we have a new page, we call resetTitle, when we
1920 * have to reset the titlebar to whatever it used to be
1921 * (for example, if the user chose to stop loading), we
1922 * call resetTitleAndRevertLockIcon.
1924 /* package */ void resetTitleAndRevertLockIcon() {
1925 mTabControl.getCurrentTab().revertLockIcon();
1926 updateLockIconToLatest();
1927 resetTitleIconAndProgress();
1931 * Reset the title, favicon, and progress.
1933 private void resetTitleIconAndProgress() {
1934 WebView current = mTabControl.getCurrentWebView();
1935 if (current == null) {
1938 resetTitleAndIcon(current);
1939 int progress = current.getProgress();
1940 current.getWebChromeClient().onProgressChanged(current, progress);
1943 // Reset the title and the icon based on the given item.
1944 private void resetTitleAndIcon(WebView view) {
1945 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1947 setUrlTitle(item.getUrl(), item.getTitle());
1948 setFavicon(item.getFavicon());
1950 setUrlTitle(null, null);
1956 * Sets a title composed of the URL and the title string.
1957 * @param url The URL of the site being loaded.
1958 * @param title The title of the site being loaded.
1960 void setUrlTitle(String url, String title) {
1964 mTitleBar.setTitleAndUrl(title, url);
1965 mFakeTitleBar.setTitleAndUrl(title, url);
1969 * @param url The URL to build a title version of the URL from.
1970 * @return The title version of the URL or null if fails.
1971 * The title version of the URL can be either the URL hostname,
1972 * or the hostname with an "https://" prefix (for secure URLs),
1973 * or an empty string if, for example, the URL in question is a
1974 * file:// URL with no hostname.
1976 /* package */ static String buildTitleUrl(String url) {
1977 String titleUrl = null;
1981 // parse the url string
1982 URL urlObj = new URL(url);
1983 if (urlObj != null) {
1986 String protocol = urlObj.getProtocol();
1987 String host = urlObj.getHost();
1989 if (host != null && 0 < host.length()) {
1991 if (protocol != null) {
1992 // if a secure site, add an "https://" prefix!
1993 if (protocol.equalsIgnoreCase("https")) {
1994 titleUrl = protocol + "://" + host;
1999 } catch (MalformedURLException e) {}
2005 // Set the favicon in the title bar.
2006 void setFavicon(Bitmap icon) {
2007 mTitleBar.setFavicon(icon);
2008 mFakeTitleBar.setFavicon(icon);
2012 * Close the tab, remove its associated title bar, and adjust mTabControl's
2013 * current tab to a valid value.
2015 /* package */ void closeTab(Tab t) {
2016 int currentIndex = mTabControl.getCurrentIndex();
2017 int removeIndex = mTabControl.getTabIndex(t);
2018 mTabControl.removeTab(t);
2019 if (currentIndex >= removeIndex && currentIndex != 0) {
2022 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2023 resetTitleIconAndProgress();
2026 private void goBackOnePageOrQuit() {
2027 Tab current = mTabControl.getCurrentTab();
2028 if (current == null) {
2030 * Instead of finishing the activity, simply push this to the back
2031 * of the stack and let ActivityManager to choose the foreground
2032 * activity. As BrowserActivity is singleTask, it will be always the
2033 * root of the task. So we can use either true or false for
2036 moveTaskToBack(true);
2039 WebView w = current.getWebView();
2040 if (w.canGoBack()) {
2043 // Check to see if we are closing a window that was created by
2044 // another window. If so, we switch back to that window.
2045 Tab parent = current.getParentTab();
2046 if (parent != null) {
2047 switchToTab(mTabControl.getTabIndex(parent));
2048 // Now we close the other tab
2051 if (current.closeOnExit()) {
2052 // force the tab's inLoad() to be false as we are going to
2053 // either finish the activity or remove the tab. This will
2054 // ensure pauseWebViewTimers() taking action.
2055 mTabControl.getCurrentTab().clearInLoad();
2056 if (mTabControl.getTabCount() == 1) {
2060 // call pauseWebViewTimers() now, we won't be able to call
2061 // it in onPause() as the WebView won't be valid.
2062 // Temporarily change mActivityInPause to be true as
2063 // pauseWebViewTimers() will do nothing if mActivityInPause
2065 boolean savedState = mActivityInPause;
2067 Log.e(LOGTAG, "BrowserActivity is already paused "
2068 + "while handing goBackOnePageOrQuit.");
2070 mActivityInPause = true;
2071 pauseWebViewTimers();
2072 mActivityInPause = savedState;
2073 removeTabFromContentView(current);
2074 mTabControl.removeTab(current);
2077 * Instead of finishing the activity, simply push this to the back
2078 * of the stack and let ActivityManager to choose the foreground
2079 * activity. As BrowserActivity is singleTask, it will be always the
2080 * root of the task. So we can use either true or false for
2083 moveTaskToBack(true);
2088 boolean isMenuDown() {
2093 public boolean onKeyDown(int keyCode, KeyEvent event) {
2094 // Even if MENU is already held down, we need to call to super to open
2095 // the IME on long press.
2096 if (KeyEvent.KEYCODE_MENU == keyCode) {
2098 return super.onKeyDown(keyCode, event);
2100 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2101 // still down, we don't want to trigger the search. Pretend to consume
2102 // the key and do nothing.
2103 if (mMenuIsDown) return true;
2106 case KeyEvent.KEYCODE_SPACE:
2107 // WebView/WebTextView handle the keys in the KeyDown. As
2108 // the Activity's shortcut keys are only handled when WebView
2109 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2110 if (event.isShiftPressed()) {
2111 getTopWindow().pageUp(false);
2113 getTopWindow().pageDown(false);
2116 case KeyEvent.KEYCODE_BACK:
2117 if (event.getRepeatCount() == 0) {
2118 event.startTracking();
2120 } else if (mCustomView == null && mActiveTabsPage == null
2121 && event.isLongPress()) {
2122 bookmarksOrHistoryPicker(true);
2127 return super.onKeyDown(keyCode, event);
2131 public boolean onKeyUp(int keyCode, KeyEvent event) {
2133 case KeyEvent.KEYCODE_MENU:
2134 mMenuIsDown = false;
2136 case KeyEvent.KEYCODE_BACK:
2137 if (event.isTracking() && !event.isCanceled()) {
2138 if (mCustomView != null) {
2139 // if a custom view is showing, hide it
2140 mTabControl.getCurrentWebView().getWebChromeClient()
2141 .onHideCustomView();
2142 } else if (mActiveTabsPage != null) {
2143 // if tab page is showing, hide it
2144 removeActiveTabPage(true);
2146 WebView subwindow = mTabControl.getCurrentSubWindow();
2147 if (subwindow != null) {
2148 if (subwindow.canGoBack()) {
2151 dismissSubWindow(mTabControl.getCurrentTab());
2154 goBackOnePageOrQuit();
2161 return super.onKeyUp(keyCode, event);
2164 /* package */ void stopLoading() {
2165 mDidStopLoad = true;
2166 resetTitleAndRevertLockIcon();
2167 WebView w = getTopWindow();
2169 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2170 // same logic here. But for subwindow case, should we call into the main
2171 // WebView's onPageFinished as we never call its onPageStarted and if
2172 // the page finishes itself, we don't call onPageFinished.
2173 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2178 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2182 boolean didUserStopLoading() {
2183 return mDidStopLoad;
2186 private void cancelStopToast() {
2187 if (mStopToast != null) {
2188 mStopToast.cancel();
2193 // called by a UI or non-UI thread to post the message
2194 public void postMessage(int what, int arg1, int arg2, Object obj,
2196 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2200 // called by a UI or non-UI thread to remove the message
2201 void removeMessages(int what, Object object) {
2202 mHandler.removeMessages(what, object);
2205 // public message ids
2206 public final static int LOAD_URL = 1001;
2207 public final static int STOP_LOAD = 1002;
2210 private static final int FOCUS_NODE_HREF = 102;
2211 private static final int CANCEL_CREDS_REQUEST = 103;
2212 private static final int RELEASE_WAKELOCK = 107;
2214 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2216 // Private handler for handling javascript and saving passwords
2217 private Handler mHandler = new Handler() {
2219 public void handleMessage(Message msg) {
2221 case FOCUS_NODE_HREF:
2223 String url = (String) msg.getData().get("url");
2224 String title = (String) msg.getData().get("title");
2225 if (url == null || url.length() == 0) {
2228 HashMap focusNodeMap = (HashMap) msg.obj;
2229 WebView view = (WebView) focusNodeMap.get("webview");
2230 // Only apply the action if the top window did not change.
2231 if (getTopWindow() != view) {
2235 case R.id.open_context_menu_id:
2236 case R.id.view_image_context_menu_id:
2237 loadURL(getTopWindow(), url);
2239 case R.id.open_newtab_context_menu_id:
2240 final Tab parent = mTabControl.getCurrentTab();
2241 final Tab newTab = openTab(url);
2242 if (newTab != parent) {
2243 parent.addChildTab(newTab);
2246 case R.id.bookmark_context_menu_id:
2247 Intent intent = new Intent(BrowserActivity.this,
2248 AddBookmarkPage.class);
2249 intent.putExtra("url", url);
2250 intent.putExtra("title", title);
2251 startActivity(intent);
2253 case R.id.share_link_context_menu_id:
2254 Browser.sendString(BrowserActivity.this, url,
2255 getText(R.string.choosertitle_sharevia).toString());
2257 case R.id.copy_link_context_menu_id:
2260 case R.id.save_link_context_menu_id:
2261 case R.id.download_context_menu_id:
2262 onDownloadStartNoStream(url, null, null, null, -1);
2269 loadURL(getTopWindow(), (String) msg.obj);
2276 case CANCEL_CREDS_REQUEST:
2277 resumeAfterCredentials();
2280 case RELEASE_WAKELOCK:
2281 if (mWakeLock.isHeld()) {
2282 mWakeLock.release();
2283 // if we reach here, Browser should be still in the
2284 // background loading after WAKELOCK_TIMEOUT (5-min).
2285 // To avoid burning the battery, stop loading.
2286 mTabControl.stopAllLoading();
2290 case UPDATE_BOOKMARK_THUMBNAIL:
2291 WebView view = (WebView) msg.obj;
2293 updateScreenshot(view);
2300 private void updateScreenshot(WebView view) {
2301 // If this is a bookmarked site, add a screenshot to the database.
2302 // FIXME: When should we update? Every time?
2303 // FIXME: Would like to make sure there is actually something to
2304 // draw, but the API for that (WebViewCore.pictureReady()) is not
2305 // currently accessible here.
2307 ContentResolver cr = getContentResolver();
2308 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2309 cr, view.getOriginalUrl(), view.getUrl(), true);
2311 boolean succeed = c.moveToFirst();
2312 ContentValues values = null;
2314 if (values == null) {
2315 final ByteArrayOutputStream os
2316 = new ByteArrayOutputStream();
2317 Bitmap bm = createScreenshot(view);
2322 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2323 values = new ContentValues();
2324 values.put(Browser.BookmarkColumns.THUMBNAIL,
2327 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2328 c.getInt(0)), values, null, null);
2329 succeed = c.moveToNext();
2336 * Values for the size of the thumbnail created when taking a screenshot.
2337 * Lazily initialized. Instead of using these directly, use
2338 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2340 private static int THUMBNAIL_WIDTH = 0;
2341 private static int THUMBNAIL_HEIGHT = 0;
2344 * Return the desired width for thumbnail screenshots, which are stored in
2345 * the database, and used on the bookmarks screen.
2346 * @param context Context for finding out the density of the screen.
2347 * @return int desired width for thumbnail screenshot.
2349 /* package */ static int getDesiredThumbnailWidth(Context context) {
2350 if (THUMBNAIL_WIDTH == 0) {
2351 float density = context.getResources().getDisplayMetrics().density;
2352 THUMBNAIL_WIDTH = (int) (90 * density);
2353 THUMBNAIL_HEIGHT = (int) (80 * density);
2355 return THUMBNAIL_WIDTH;
2359 * Return the desired height for thumbnail screenshots, which are stored in
2360 * the database, and used on the bookmarks screen.
2361 * @param context Context for finding out the density of the screen.
2362 * @return int desired height for thumbnail screenshot.
2364 /* package */ static int getDesiredThumbnailHeight(Context context) {
2365 // To ensure that they are both initialized.
2366 getDesiredThumbnailWidth(context);
2367 return THUMBNAIL_HEIGHT;
2370 private Bitmap createScreenshot(WebView view) {
2371 Picture thumbnail = view.capturePicture();
2372 if (thumbnail == null) {
2375 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2376 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2377 Canvas canvas = new Canvas(bm);
2378 // May need to tweak these values to determine what is the
2379 // best scale factor
2380 int thumbnailWidth = thumbnail.getWidth();
2381 int thumbnailHeight = thumbnail.getHeight();
2382 float scaleFactorX = 1.0f;
2383 float scaleFactorY = 1.0f;
2384 if (thumbnailWidth > 0) {
2385 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2386 (float)thumbnailWidth;
2391 if (view.getWidth() > view.getHeight() &&
2392 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2393 // If the device is in landscape and the page is shorter
2394 // than the height of the view, stretch the thumbnail to fill the
2396 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2397 (float)thumbnailHeight;
2399 // In the portrait case, this looks nice.
2400 scaleFactorY = scaleFactorX;
2403 canvas.scale(scaleFactorX, scaleFactorY);
2405 thumbnail.draw(canvas);
2409 // -------------------------------------------------------------------------
2410 // Helper function for WebViewClient.
2411 //-------------------------------------------------------------------------
2413 // Use in overrideUrlLoading
2414 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2415 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2416 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2417 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2419 void onPageStarted(WebView view, String url, Bitmap favicon) {
2420 // when BrowserActivity just starts, onPageStarted may be called before
2421 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2422 // to start the timer. As we won't switch tabs while an activity is in
2423 // pause state, we can ensure calling resume and pause in pair.
2424 if (mActivityInPause) resumeWebViewTimers();
2427 setUrlTitle(url, null);
2428 setFavicon(favicon);
2429 // Keep this initial progress in sync with initialProgressValue (* 100)
2430 // in ProgressTracker.cpp
2431 // Show some progress so that the user knows the page is beginning to
2433 onProgressChanged(view, 10);
2434 mDidStopLoad = false;
2435 if (!mIsNetworkUp) createAndShowNetworkDialog();
2437 if (mSettings.isTracing()) {
2440 WebAddress uri = new WebAddress(url);
2442 } catch (android.net.ParseException ex) {
2445 host = host.replace('.', '_');
2448 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2451 // Performance probe
2453 mStart = SystemClock.uptimeMillis();
2454 mProcessStart = Process.getElapsedCpuTime();
2455 long[] sysCpu = new long[7];
2456 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2458 mUserStart = sysCpu[0] + sysCpu[1];
2459 mSystemStart = sysCpu[2];
2460 mIdleStart = sysCpu[3];
2461 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2463 mUiStart = SystemClock.currentThreadTimeMillis();
2467 void onPageFinished(WebView view, String url) {
2468 // Reset the title and icon in case we stopped a provisional load.
2469 resetTitleAndIcon(view);
2470 // Update the lock icon image only once we are done loading
2471 updateLockIconToLatest();
2472 // pause the WebView timer and release the wake lock if it is finished
2473 // while BrowserActivity is in pause state.
2474 if (mActivityInPause && pauseWebViewTimers()) {
2475 if (mWakeLock.isHeld()) {
2476 mHandler.removeMessages(RELEASE_WAKELOCK);
2477 mWakeLock.release();
2481 // Performance probe
2483 long[] sysCpu = new long[7];
2484 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2486 String uiInfo = "UI thread used "
2487 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2490 Log.d(LOGTAG, uiInfo);
2492 //The string that gets written to the log
2493 String performanceString = "It took total "
2494 + (SystemClock.uptimeMillis() - mStart)
2495 + " ms clock time to load the page."
2496 + "\nbrowser process used "
2497 + (Process.getElapsedCpuTime() - mProcessStart)
2498 + " ms, user processes used "
2499 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2500 + " ms, kernel used "
2501 + (sysCpu[2] - mSystemStart) * 10
2502 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2503 + " ms and irq took "
2504 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2505 * 10 + " ms, " + uiInfo;
2507 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2510 // strip the url to maintain consistency
2511 String newUrl = new String(url);
2512 if (newUrl.startsWith("http://www.")) {
2513 newUrl = newUrl.substring(11);
2514 } else if (newUrl.startsWith("http://")) {
2515 newUrl = newUrl.substring(7);
2516 } else if (newUrl.startsWith("https://www.")) {
2517 newUrl = newUrl.substring(12);
2518 } else if (newUrl.startsWith("https://")) {
2519 newUrl = newUrl.substring(8);
2522 Log.d(LOGTAG, newUrl + " loaded");
2530 Debug.stopMethodTracing();
2534 boolean shouldOverrideUrlLoading(WebView view, String url) {
2535 if (url.startsWith(SCHEME_WTAI)) {
2536 // wtai://wp/mc;number
2537 // number=string(phone-number)
2538 if (url.startsWith(SCHEME_WTAI_MC)) {
2539 Intent intent = new Intent(Intent.ACTION_VIEW,
2540 Uri.parse(WebView.SCHEME_TEL +
2541 url.substring(SCHEME_WTAI_MC.length())));
2542 startActivity(intent);
2545 // wtai://wp/sd;dtmf
2546 // dtmf=string(dialstring)
2547 if (url.startsWith(SCHEME_WTAI_SD)) {
2548 // TODO: only send when there is active voice connection
2551 // wtai://wp/ap;number;name
2552 // number=string(phone-number)
2554 if (url.startsWith(SCHEME_WTAI_AP)) {
2560 // The "about:" schemes are internal to the browser; don't want these to
2561 // be dispatched to other apps.
2562 if (url.startsWith("about:")) {
2567 // perform generic parsing of the URI to turn it into an Intent.
2569 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2570 } catch (URISyntaxException ex) {
2571 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2575 // check whether the intent can be resolved. If not, we will see
2576 // whether we can download it from the Market.
2577 if (getPackageManager().resolveActivity(intent, 0) == null) {
2578 String packagename = intent.getPackage();
2579 if (packagename != null) {
2580 intent = new Intent(Intent.ACTION_VIEW, Uri
2581 .parse("market://search?q=pname:" + packagename));
2582 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2583 startActivity(intent);
2590 // sanitize the Intent, ensuring web pages can not bypass browser
2591 // security (only access to BROWSABLE activities).
2592 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2593 intent.setComponent(null);
2595 if (startActivityIfNeeded(intent, -1)) {
2598 } catch (ActivityNotFoundException ex) {
2599 // ignore the error. If no application can handle the URL,
2600 // eg about:blank, assume the browser can handle it.
2611 // -------------------------------------------------------------------------
2612 // Helper function for WebChromeClient
2613 // -------------------------------------------------------------------------
2615 void onProgressChanged(WebView view, int newProgress) {
2616 mTitleBar.setProgress(newProgress);
2617 mFakeTitleBar.setProgress(newProgress);
2619 if (newProgress == 100) {
2620 // onProgressChanged() may continue to be called after the main
2621 // frame has finished loading, as any remaining sub frames continue
2622 // to load. We'll only get called once though with newProgress as
2623 // 100 when everything is loaded. (onPageFinished is called once
2624 // when the main frame completes loading regardless of the state of
2625 // any sub frames so calls to onProgressChanges may continue after
2626 // onPageFinished has executed)
2629 updateInLoadMenuItems();
2630 // If the options menu is open, leave the title bar
2631 if (!mOptionsMenuOpen || !mIconView) {
2635 } else if (!mInLoad) {
2636 // onPageFinished may have already been called but a subframe is
2637 // still loading and updating the progress. Reset mInLoad and update
2640 updateInLoadMenuItems();
2641 if (!mOptionsMenuOpen || mIconView) {
2642 // This page has begun to load, so show the title bar
2648 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2649 // if a view already exists then immediately terminate the new one
2650 if (mCustomView != null) {
2651 callback.onCustomViewHidden();
2655 // Add the custom view to its container.
2656 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2658 mCustomViewCallback = callback;
2659 // Save the menu state and set it to empty while the custom
2661 mOldMenuState = mMenuState;
2662 mMenuState = EMPTY_MENU;
2663 // Hide the content view.
2664 mContentView.setVisibility(View.GONE);
2665 // Finally show the custom view container.
2666 setStatusBarVisibility(false);
2667 mCustomViewContainer.setVisibility(View.VISIBLE);
2668 mCustomViewContainer.bringToFront();
2671 void onHideCustomView() {
2672 if (mCustomView == null)
2675 // Hide the custom view.
2676 mCustomView.setVisibility(View.GONE);
2677 // Remove the custom view from its container.
2678 mCustomViewContainer.removeView(mCustomView);
2680 // Reset the old menu state.
2681 mMenuState = mOldMenuState;
2682 mOldMenuState = EMPTY_MENU;
2683 mCustomViewContainer.setVisibility(View.GONE);
2684 mCustomViewCallback.onCustomViewHidden();
2685 // Show the content view.
2686 setStatusBarVisibility(true);
2687 mContentView.setVisibility(View.VISIBLE);
2690 Bitmap getDefaultVideoPoster() {
2691 if (mDefaultVideoPoster == null) {
2692 mDefaultVideoPoster = BitmapFactory.decodeResource(
2693 getResources(), R.drawable.default_video_poster);
2695 return mDefaultVideoPoster;
2698 View getVideoLoadingProgressView() {
2699 if (mVideoProgressView == null) {
2700 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2701 mVideoProgressView = inflater.inflate(
2702 R.layout.video_loading_progress, null);
2704 return mVideoProgressView;
2708 * The Object used to inform the WebView of the file to upload.
2710 private ValueCallback<Uri> mUploadMessage;
2712 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2713 if (mUploadMessage != null) return;
2714 mUploadMessage = uploadMsg;
2715 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2716 i.addCategory(Intent.CATEGORY_OPENABLE);
2718 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2719 getString(R.string.choose_upload)), FILE_SELECTED);
2722 // -------------------------------------------------------------------------
2723 // Implement functions for DownloadListener
2724 // -------------------------------------------------------------------------
2727 * Notify the host application a download should be done, or that
2728 * the data should be streamed if a streaming viewer is available.
2729 * @param url The full url to the content that should be downloaded
2730 * @param contentDisposition Content-disposition http header, if
2732 * @param mimetype The mimetype of the content reported by the server
2733 * @param contentLength The file size reported by the server
2735 public void onDownloadStart(String url, String userAgent,
2736 String contentDisposition, String mimetype, long contentLength) {
2737 // if we're dealing wih A/V content that's not explicitly marked
2738 // for download, check if it's streamable.
2739 if (contentDisposition == null
2740 || !contentDisposition.regionMatches(
2741 true, 0, "attachment", 0, 10)) {
2742 // query the package manager to see if there's a registered handler
2744 Intent intent = new Intent(Intent.ACTION_VIEW);
2745 intent.setDataAndType(Uri.parse(url), mimetype);
2746 ResolveInfo info = getPackageManager().resolveActivity(intent,
2747 PackageManager.MATCH_DEFAULT_ONLY);
2749 ComponentName myName = getComponentName();
2750 // If we resolved to ourselves, we don't want to attempt to
2751 // load the url only to try and download it again.
2752 if (!myName.getPackageName().equals(
2753 info.activityInfo.packageName)
2754 || !myName.getClassName().equals(
2755 info.activityInfo.name)) {
2756 // someone (other than us) knows how to handle this mime
2757 // type with this scheme, don't download.
2759 startActivity(intent);
2761 } catch (ActivityNotFoundException ex) {
2763 Log.d(LOGTAG, "activity not found for " + mimetype
2764 + " over " + Uri.parse(url).getScheme(),
2767 // Best behavior is to fall back to a download in this
2773 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2777 * Notify the host application a download should be done, even if there
2778 * is a streaming viewer available for thise type.
2779 * @param url The full url to the content that should be downloaded
2780 * @param contentDisposition Content-disposition http header, if
2782 * @param mimetype The mimetype of the content reported by the server
2783 * @param contentLength The file size reported by the server
2785 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2786 String contentDisposition, String mimetype, long contentLength) {
2788 String filename = URLUtil.guessFileName(url,
2789 contentDisposition, mimetype);
2791 // Check to see if we have an SDCard
2792 String status = Environment.getExternalStorageState();
2793 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2797 // Check to see if the SDCard is busy, same as the music app
2798 if (status.equals(Environment.MEDIA_SHARED)) {
2799 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2800 title = R.string.download_sdcard_busy_dlg_title;
2802 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2803 title = R.string.download_no_sdcard_dlg_title;
2806 new AlertDialog.Builder(this)
2808 .setIcon(android.R.drawable.ic_dialog_alert)
2810 .setPositiveButton(R.string.ok, null)
2815 // java.net.URI is a lot stricter than KURL so we have to undo
2816 // KURL's percent-encoding and redo the encoding using java.net.URI.
2819 // Undo the percent-encoding that KURL may have done.
2820 String newUrl = new String(URLUtil.decode(url.getBytes()));
2821 // Parse the url into pieces
2822 WebAddress w = new WebAddress(newUrl);
2824 String query = null;
2825 String path = w.mPath;
2826 // Break the path into path, query, and fragment
2827 if (path.length() > 0) {
2828 // Strip the fragment
2829 int idx = path.lastIndexOf('#');
2831 frag = path.substring(idx + 1);
2832 path = path.substring(0, idx);
2834 idx = path.lastIndexOf('?');
2836 query = path.substring(idx + 1);
2837 path = path.substring(0, idx);
2840 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2842 } catch (Exception e) {
2843 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2847 // XXX: Have to use the old url since the cookies were stored using the
2848 // old percent-encoded url.
2849 String cookies = CookieManager.getInstance().getCookie(url);
2851 ContentValues values = new ContentValues();
2852 values.put(Downloads.COLUMN_URI, uri.toString());
2853 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2854 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2855 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
2857 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
2858 BrowserDownloadPage.class.getCanonicalName());
2859 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2860 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2861 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2862 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
2863 if (contentLength > 0) {
2864 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
2866 if (mimetype == null) {
2867 // We must have long pressed on a link or image to download it. We
2868 // are not sure of the mimetype in this case, so do a head request
2869 new FetchUrlMimeType(this).execute(values);
2871 final Uri contentUri =
2872 getContentResolver().insert(Downloads.CONTENT_URI, values);
2873 viewDownloads(contentUri);
2878 // -------------------------------------------------------------------------
2881 * Resets the lock icon. This method is called when we start a new load and
2882 * know the url to be loaded.
2884 private void resetLockIcon(String url) {
2885 // Save the lock-icon state (we revert to it if the load gets cancelled)
2886 mTabControl.getCurrentTab().resetLockIcon(url);
2887 updateLockIconImage(LOCK_ICON_UNSECURE);
2891 * Update the lock icon to correspond to our latest state.
2893 private void updateLockIconToLatest() {
2894 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
2898 * Updates the lock-icon image in the title-bar.
2900 private void updateLockIconImage(int lockIconType) {
2902 if (lockIconType == LOCK_ICON_SECURE) {
2904 } else if (lockIconType == LOCK_ICON_MIXED) {
2907 mTitleBar.setLock(d);
2908 mFakeTitleBar.setLock(d);
2912 * Displays a page-info dialog.
2913 * @param tab The tab to show info about
2914 * @param fromShowSSLCertificateOnError The flag that indicates whether
2915 * this dialog was opened from the SSL-certificate-on-error dialog or
2916 * not. This is important, since we need to know whether to return to
2917 * the parent dialog or simply dismiss.
2919 private void showPageInfo(final Tab tab,
2920 final boolean fromShowSSLCertificateOnError) {
2921 final LayoutInflater factory = LayoutInflater
2924 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2926 final WebView view = tab.getWebView();
2929 String title = null;
2933 title = tab.getTitle();
2934 } else if (view == mTabControl.getCurrentWebView()) {
2935 // Use the cached title and url if this is the current WebView
2939 url = view.getUrl();
2940 title = view.getTitle();
2946 if (title == null) {
2950 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2951 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2953 mPageInfoView = tab;
2954 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
2956 AlertDialog.Builder alertDialogBuilder =
2957 new AlertDialog.Builder(this)
2958 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2959 .setView(pageInfoView)
2962 new DialogInterface.OnClickListener() {
2963 public void onClick(DialogInterface dialog,
2965 mPageInfoDialog = null;
2966 mPageInfoView = null;
2967 mPageInfoFromShowSSLCertificateOnError = null;
2969 // if we came here from the SSL error dialog
2970 if (fromShowSSLCertificateOnError) {
2971 // go back to the SSL error dialog
2972 showSSLCertificateOnError(
2973 mSSLCertificateOnErrorView,
2974 mSSLCertificateOnErrorHandler,
2975 mSSLCertificateOnErrorError);
2979 .setOnCancelListener(
2980 new DialogInterface.OnCancelListener() {
2981 public void onCancel(DialogInterface dialog) {
2982 mPageInfoDialog = null;
2983 mPageInfoView = null;
2984 mPageInfoFromShowSSLCertificateOnError = null;
2986 // if we came here from the SSL error dialog
2987 if (fromShowSSLCertificateOnError) {
2988 // go back to the SSL error dialog
2989 showSSLCertificateOnError(
2990 mSSLCertificateOnErrorView,
2991 mSSLCertificateOnErrorHandler,
2992 mSSLCertificateOnErrorError);
2997 // if we have a main top-level page SSL certificate set or a certificate
2999 if (fromShowSSLCertificateOnError ||
3000 (view != null && view.getCertificate() != null)) {
3001 // add a 'View Certificate' button
3002 alertDialogBuilder.setNeutralButton(
3003 R.string.view_certificate,
3004 new DialogInterface.OnClickListener() {
3005 public void onClick(DialogInterface dialog,
3007 mPageInfoDialog = null;
3008 mPageInfoView = null;
3009 mPageInfoFromShowSSLCertificateOnError = null;
3011 // if we came here from the SSL error dialog
3012 if (fromShowSSLCertificateOnError) {
3013 // go back to the SSL error dialog
3014 showSSLCertificateOnError(
3015 mSSLCertificateOnErrorView,
3016 mSSLCertificateOnErrorHandler,
3017 mSSLCertificateOnErrorError);
3019 // otherwise, display the top-most certificate from
3021 if (view.getCertificate() != null) {
3022 showSSLCertificate(tab);
3029 mPageInfoDialog = alertDialogBuilder.show();
3033 * Displays the main top-level page SSL certificate dialog
3034 * (accessible from the Page-Info dialog).
3035 * @param tab The tab to show certificate for.
3037 private void showSSLCertificate(final Tab tab) {
3038 final View certificateView =
3039 inflateCertificateView(tab.getWebView().getCertificate());
3040 if (certificateView == null) {
3044 LayoutInflater factory = LayoutInflater.from(this);
3046 final LinearLayout placeholder =
3047 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3049 LinearLayout ll = (LinearLayout) factory.inflate(
3050 R.layout.ssl_success, placeholder);
3051 ((TextView)ll.findViewById(R.id.success))
3052 .setText(R.string.ssl_certificate_is_valid);
3054 mSSLCertificateView = tab;
3055 mSSLCertificateDialog =
3056 new AlertDialog.Builder(this)
3057 .setTitle(R.string.ssl_certificate).setIcon(
3058 R.drawable.ic_dialog_browser_certificate_secure)
3059 .setView(certificateView)
3060 .setPositiveButton(R.string.ok,
3061 new DialogInterface.OnClickListener() {
3062 public void onClick(DialogInterface dialog,
3064 mSSLCertificateDialog = null;
3065 mSSLCertificateView = null;
3067 showPageInfo(tab, false);
3070 .setOnCancelListener(
3071 new DialogInterface.OnCancelListener() {
3072 public void onCancel(DialogInterface dialog) {
3073 mSSLCertificateDialog = null;
3074 mSSLCertificateView = null;
3076 showPageInfo(tab, false);
3083 * Displays the SSL error certificate dialog.
3084 * @param view The target web-view.
3085 * @param handler The SSL error handler responsible for cancelling the
3086 * connection that resulted in an SSL error or proceeding per user request.
3087 * @param error The SSL error object.
3089 void showSSLCertificateOnError(
3090 final WebView view, final SslErrorHandler handler, final SslError error) {
3092 final View certificateView =
3093 inflateCertificateView(error.getCertificate());
3094 if (certificateView == null) {
3098 LayoutInflater factory = LayoutInflater.from(this);
3100 final LinearLayout placeholder =
3101 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3103 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3104 LinearLayout ll = (LinearLayout)factory
3105 .inflate(R.layout.ssl_warning, placeholder);
3106 ((TextView)ll.findViewById(R.id.warning))
3107 .setText(R.string.ssl_untrusted);
3110 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3111 LinearLayout ll = (LinearLayout)factory
3112 .inflate(R.layout.ssl_warning, placeholder);
3113 ((TextView)ll.findViewById(R.id.warning))
3114 .setText(R.string.ssl_mismatch);
3117 if (error.hasError(SslError.SSL_EXPIRED)) {
3118 LinearLayout ll = (LinearLayout)factory
3119 .inflate(R.layout.ssl_warning, placeholder);
3120 ((TextView)ll.findViewById(R.id.warning))
3121 .setText(R.string.ssl_expired);
3124 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3125 LinearLayout ll = (LinearLayout)factory
3126 .inflate(R.layout.ssl_warning, placeholder);
3127 ((TextView)ll.findViewById(R.id.warning))
3128 .setText(R.string.ssl_not_yet_valid);
3131 mSSLCertificateOnErrorHandler = handler;
3132 mSSLCertificateOnErrorView = view;
3133 mSSLCertificateOnErrorError = error;
3134 mSSLCertificateOnErrorDialog =
3135 new AlertDialog.Builder(this)
3136 .setTitle(R.string.ssl_certificate).setIcon(
3137 R.drawable.ic_dialog_browser_certificate_partially_secure)
3138 .setView(certificateView)
3139 .setPositiveButton(R.string.ok,
3140 new DialogInterface.OnClickListener() {
3141 public void onClick(DialogInterface dialog,
3143 mSSLCertificateOnErrorDialog = null;
3144 mSSLCertificateOnErrorView = null;
3145 mSSLCertificateOnErrorHandler = null;
3146 mSSLCertificateOnErrorError = null;
3148 view.getWebViewClient().onReceivedSslError(
3149 view, handler, error);
3152 .setNeutralButton(R.string.page_info_view,
3153 new DialogInterface.OnClickListener() {
3154 public void onClick(DialogInterface dialog,
3156 mSSLCertificateOnErrorDialog = null;
3158 // do not clear the dialog state: we will
3159 // need to show the dialog again once the
3160 // user is done exploring the page-info details
3162 showPageInfo(mTabControl.getTabFromView(view),
3166 .setOnCancelListener(
3167 new DialogInterface.OnCancelListener() {
3168 public void onCancel(DialogInterface dialog) {
3169 mSSLCertificateOnErrorDialog = null;
3170 mSSLCertificateOnErrorView = null;
3171 mSSLCertificateOnErrorHandler = null;
3172 mSSLCertificateOnErrorError = null;
3174 view.getWebViewClient().onReceivedSslError(
3175 view, handler, error);
3182 * Inflates the SSL certificate view (helper method).
3183 * @param certificate The SSL certificate.
3184 * @return The resultant certificate view with issued-to, issued-by,
3185 * issued-on, expires-on, and possibly other fields set.
3186 * If the input certificate is null, returns null.
3188 private View inflateCertificateView(SslCertificate certificate) {
3189 if (certificate == null) {
3193 LayoutInflater factory = LayoutInflater.from(this);
3195 View certificateView = factory.inflate(
3196 R.layout.ssl_certificate, null);
3199 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3200 if (issuedTo != null) {
3201 ((TextView) certificateView.findViewById(R.id.to_common))
3202 .setText(issuedTo.getCName());
3203 ((TextView) certificateView.findViewById(R.id.to_org))
3204 .setText(issuedTo.getOName());
3205 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3206 .setText(issuedTo.getUName());
3210 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3211 if (issuedBy != null) {
3212 ((TextView) certificateView.findViewById(R.id.by_common))
3213 .setText(issuedBy.getCName());
3214 ((TextView) certificateView.findViewById(R.id.by_org))
3215 .setText(issuedBy.getOName());
3216 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3217 .setText(issuedBy.getUName());
3221 String issuedOn = reformatCertificateDate(
3222 certificate.getValidNotBefore());
3223 ((TextView) certificateView.findViewById(R.id.issued_on))
3227 String expiresOn = reformatCertificateDate(
3228 certificate.getValidNotAfter());
3229 ((TextView) certificateView.findViewById(R.id.expires_on))
3230 .setText(expiresOn);
3232 return certificateView;
3236 * Re-formats the certificate date (Date.toString()) string to
3237 * a properly localized date string.
3238 * @return Properly localized version of the certificate date string and
3239 * the original certificate date string if fails to localize.
3240 * If the original string is null, returns an empty string "".
3242 private String reformatCertificateDate(String certificateDate) {
3243 String reformattedDate = null;
3245 if (certificateDate != null) {
3248 date = java.text.DateFormat.getInstance().parse(certificateDate);
3249 } catch (ParseException e) {
3255 DateFormat.getDateFormat(this).format(date);
3259 return reformattedDate != null ? reformattedDate :
3260 (certificateDate != null ? certificateDate : "");
3264 * Displays an http-authentication dialog.
3266 void showHttpAuthentication(final HttpAuthHandler handler,
3267 final String host, final String realm, final String title,
3268 final String name, final String password, int focusId) {
3269 LayoutInflater factory = LayoutInflater.from(this);
3270 final View v = factory
3271 .inflate(R.layout.http_authentication, null);
3273 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3275 if (password != null) {
3276 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3279 String titleText = title;
3280 if (titleText == null) {
3281 titleText = getText(R.string.sign_in_to).toString().replace(
3282 "%s1", host).replace("%s2", realm);
3285 mHttpAuthHandler = handler;
3286 AlertDialog dialog = new AlertDialog.Builder(this)
3287 .setTitle(titleText)
3288 .setIcon(android.R.drawable.ic_dialog_alert)
3290 .setPositiveButton(R.string.action,
3291 new DialogInterface.OnClickListener() {
3292 public void onClick(DialogInterface dialog,
3294 String nm = ((EditText) v
3295 .findViewById(R.id.username_edit))
3296 .getText().toString();
3297 String pw = ((EditText) v
3298 .findViewById(R.id.password_edit))
3299 .getText().toString();
3300 BrowserActivity.this.setHttpAuthUsernamePassword
3301 (host, realm, nm, pw);
3302 handler.proceed(nm, pw);
3303 mHttpAuthenticationDialog = null;
3304 mHttpAuthHandler = null;
3306 .setNegativeButton(R.string.cancel,
3307 new DialogInterface.OnClickListener() {
3308 public void onClick(DialogInterface dialog,
3311 BrowserActivity.this.resetTitleAndRevertLockIcon();
3312 mHttpAuthenticationDialog = null;
3313 mHttpAuthHandler = null;
3315 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3316 public void onCancel(DialogInterface dialog) {
3318 BrowserActivity.this.resetTitleAndRevertLockIcon();
3319 mHttpAuthenticationDialog = null;
3320 mHttpAuthHandler = null;
3323 // Make the IME appear when the dialog is displayed if applicable.
3324 dialog.getWindow().setSoftInputMode(
3325 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3328 dialog.findViewById(focusId).requestFocus();
3330 v.findViewById(R.id.username_edit).requestFocus();
3332 mHttpAuthenticationDialog = dialog;
3335 public int getProgress() {
3336 WebView w = mTabControl.getCurrentWebView();
3338 return w.getProgress();
3345 * Set HTTP authentication password.
3347 * @param host The host for the password
3348 * @param realm The realm for the password
3349 * @param username The username for the password. If it is null, it means
3350 * password can't be saved.
3351 * @param password The password
3353 public void setHttpAuthUsernamePassword(String host, String realm,
3356 WebView w = mTabControl.getCurrentWebView();
3358 w.setHttpAuthUsernamePassword(host, realm, username, password);
3363 * connectivity manager says net has come or gone... inform the user
3364 * @param up true if net has come up, false if net has gone down
3366 public void onNetworkToggle(boolean up) {
3367 if (up == mIsNetworkUp) {
3370 mIsNetworkUp = true;
3371 if (mAlertDialog != null) {
3372 mAlertDialog.cancel();
3373 mAlertDialog = null;
3376 mIsNetworkUp = false;
3378 createAndShowNetworkDialog();
3381 WebView w = mTabControl.getCurrentWebView();
3383 w.setNetworkAvailable(up);
3387 boolean isNetworkUp() {
3388 return mIsNetworkUp;
3391 // This method shows the network dialog alerting the user that the net is
3392 // down. It will only show the dialog if mAlertDialog is null.
3393 private void createAndShowNetworkDialog() {
3394 if (mAlertDialog == null) {
3395 mAlertDialog = new AlertDialog.Builder(this)
3396 .setTitle(R.string.loadSuspendedTitle)
3397 .setMessage(R.string.loadSuspended)
3398 .setPositiveButton(R.string.ok, null)
3404 protected void onActivityResult(int requestCode, int resultCode,
3406 if (getTopWindow() == null) return;
3408 switch (requestCode) {
3410 if (resultCode == RESULT_OK && intent != null) {
3411 String data = intent.getAction();
3412 Bundle extras = intent.getExtras();
3413 if (extras != null && extras.getBoolean("new_window", false)) {
3416 final Tab currentTab =
3417 mTabControl.getCurrentTab();
3418 dismissSubWindow(currentTab);
3419 if (data != null && data.length() != 0) {
3420 getTopWindow().loadUrl(data);
3425 // Choose a file from the file picker.
3427 if (null == mUploadMessage) break;
3428 Uri result = intent == null || resultCode != RESULT_OK ? null
3430 mUploadMessage.onReceiveValue(result);
3431 mUploadMessage = null;
3436 getTopWindow().requestFocus();
3440 * This method is called as a result of the user selecting the options
3441 * menu to see the download window, or when a download changes state. It
3442 * shows the download window ontop of the current window.
3444 /* package */ void viewDownloads(Uri downloadRecord) {
3445 Intent intent = new Intent(this,
3446 BrowserDownloadPage.class);
3447 intent.setData(downloadRecord);
3448 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3454 * @param startWithHistory If true, open starting on the history tab.
3455 * Otherwise, start with the bookmarks tab.
3457 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3458 WebView current = mTabControl.getCurrentWebView();
3459 if (current == null) {
3462 Intent intent = new Intent(this,
3463 CombinedBookmarkHistoryActivity.class);
3464 String title = current.getTitle();
3465 String url = current.getUrl();
3466 Bitmap thumbnail = createScreenshot(current);
3468 // Just in case the user opens bookmarks before a page finishes loading
3469 // so the current history item, and therefore the page, is null.
3471 url = mLastEnteredUrl;
3474 url = mSettings.getHomePage();
3477 // In case the web page has not yet received its associated title.
3478 if (title == null) {
3481 intent.putExtra("title", title);
3482 intent.putExtra("url", url);
3483 intent.putExtra("thumbnail", thumbnail);
3484 // Disable opening in a new window if we have maxed out the windows
3485 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3486 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3487 if (startWithHistory) {
3488 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3489 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3491 startActivityForResult(intent, COMBO_PAGE);
3494 // Called when loading from context menu or LOAD_URL message
3495 private void loadURL(WebView view, String url) {
3496 // In case the user enters nothing.
3497 if (url != null && url.length() != 0 && view != null) {
3498 url = smartUrlFilter(url);
3499 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3505 private String smartUrlFilter(Uri inUri) {
3506 if (inUri != null) {
3507 return smartUrlFilter(inUri.toString());
3512 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3513 "(?i)" + // switch on case insensitive matching
3514 "(" + // begin group for schema
3515 "(?:http|https|file):\\/\\/" +
3516 "|(?:inline|data|about|content|javascript):" +
3521 * Attempts to determine whether user input is a URL or search
3522 * terms. Anything with a space is passed to search.
3524 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3525 * "Http://" converts to "http://"
3527 * @return Original or modified URL
3530 String smartUrlFilter(String url) {
3532 String inUrl = url.trim();
3533 boolean hasSpace = inUrl.indexOf(' ') != -1;
3535 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3536 if (matcher.matches()) {
3537 // force scheme to lowercase
3538 String scheme = matcher.group(1);
3539 String lcScheme = scheme.toLowerCase();
3540 if (!lcScheme.equals(scheme)) {
3541 inUrl = lcScheme + matcher.group(2);
3544 inUrl = inUrl.replace(" ", "%20");
3549 // FIXME: Is this the correct place to add to searches?
3550 // what if someone else calls this function?
3551 int shortcut = parseUrlShortcut(inUrl);
3552 if (shortcut != SHORTCUT_INVALID) {
3553 Browser.addSearchUrl(mResolver, inUrl);
3554 String query = inUrl.substring(2);
3556 case SHORTCUT_GOOGLE_SEARCH:
3557 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3558 case SHORTCUT_WIKIPEDIA_SEARCH:
3559 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3560 case SHORTCUT_DICTIONARY_SEARCH:
3561 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3562 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3563 // FIXME: we need location in this case
3564 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3568 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3569 return URLUtil.guessUrl(inUrl);
3573 Browser.addSearchUrl(mResolver, inUrl);
3574 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3577 /* package */ void setShouldShowErrorConsole(boolean flag) {
3578 if (flag == mShouldShowErrorConsole) {
3583 mShouldShowErrorConsole = flag;
3585 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3586 .getErrorConsole(true);
3589 // Setting the show state of the console will cause it's the layout to be inflated.
3590 if (errorConsole.numberOfErrors() > 0) {
3591 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3593 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3596 // Now we can add it to the main view.
3597 mErrorConsoleContainer.addView(errorConsole,
3598 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3599 ViewGroup.LayoutParams.WRAP_CONTENT));
3601 mErrorConsoleContainer.removeView(errorConsole);
3606 boolean shouldShowErrorConsole() {
3607 return mShouldShowErrorConsole;
3610 private void setStatusBarVisibility(boolean visible) {
3611 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3612 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3615 final static int LOCK_ICON_UNSECURE = 0;
3616 final static int LOCK_ICON_SECURE = 1;
3617 final static int LOCK_ICON_MIXED = 2;
3619 private BrowserSettings mSettings;
3620 private TabControl mTabControl;
3621 private ContentResolver mResolver;
3622 private FrameLayout mContentView;
3623 private View mCustomView;
3624 private FrameLayout mCustomViewContainer;
3625 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3627 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3628 // view, we should rewrite this.
3629 private int mCurrentMenuState = 0;
3630 private int mMenuState = R.id.MAIN_MENU;
3631 private int mOldMenuState = EMPTY_MENU;
3632 private static final int EMPTY_MENU = -1;
3635 private FindDialog mFindDialog;
3636 // Used to prevent chording to result in firing two shortcuts immediately
3637 // one after another. Fixes bug 1211714.
3640 private boolean mInLoad;
3641 private boolean mIsNetworkUp;
3642 private boolean mDidStopLoad;
3644 private boolean mActivityInPause = true;
3646 private boolean mMenuIsDown;
3648 private static boolean mInTrace;
3650 // Performance probe
3651 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3652 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3653 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3654 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3655 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3656 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3657 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3658 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3659 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3662 private long mStart;
3663 private long mProcessStart;
3664 private long mUserStart;
3665 private long mSystemStart;
3666 private long mIdleStart;
3667 private long mIrqStart;
3669 private long mUiStart;
3671 private Drawable mMixLockIcon;
3672 private Drawable mSecLockIcon;
3674 /* hold a ref so we can auto-cancel if necessary */
3675 private AlertDialog mAlertDialog;
3677 // Wait for credentials before loading google.com
3678 private ProgressDialog mCredsDlg;
3680 // The up-to-date URL and title (these can be different from those stored
3681 // in WebView, since it takes some time for the information in WebView to
3683 private String mUrl;
3684 private String mTitle;
3686 // As PageInfo has different style for landscape / portrait, we have
3687 // to re-open it when configuration changed
3688 private AlertDialog mPageInfoDialog;
3689 private Tab mPageInfoView;
3690 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3691 // dialog, we should not just dismiss it, but should get back to the
3692 // SSL-certificate-on-error dialog. This flag is used to store this state
3693 private Boolean mPageInfoFromShowSSLCertificateOnError;
3695 // as SSLCertificateOnError has different style for landscape / portrait,
3696 // we have to re-open it when configuration changed
3697 private AlertDialog mSSLCertificateOnErrorDialog;
3698 private WebView mSSLCertificateOnErrorView;
3699 private SslErrorHandler mSSLCertificateOnErrorHandler;
3700 private SslError mSSLCertificateOnErrorError;
3702 // as SSLCertificate has different style for landscape / portrait, we
3703 // have to re-open it when configuration changed
3704 private AlertDialog mSSLCertificateDialog;
3705 private Tab mSSLCertificateView;
3707 // as HttpAuthentication has different style for landscape / portrait, we
3708 // have to re-open it when configuration changed
3709 private AlertDialog mHttpAuthenticationDialog;
3710 private HttpAuthHandler mHttpAuthHandler;
3712 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3713 new FrameLayout.LayoutParams(
3714 ViewGroup.LayoutParams.MATCH_PARENT,
3715 ViewGroup.LayoutParams.MATCH_PARENT);
3716 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3717 new FrameLayout.LayoutParams(
3718 ViewGroup.LayoutParams.MATCH_PARENT,
3719 ViewGroup.LayoutParams.MATCH_PARENT,
3722 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3724 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3725 // Dictionary search
3726 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3727 // Google Mobile Local search
3728 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3730 final static String QUERY_PLACE_HOLDER = "%s";
3732 // "source" parameter for Google search through search key
3733 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3734 // "source" parameter for Google search through goto menu
3735 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3736 // "source" parameter for Google search through simplily type
3737 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3738 // "source" parameter for Google search suggested by the browser
3739 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3740 // "source" parameter for Google search from unknown source
3741 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3743 private final static String LOGTAG = "browser";
3745 private String mLastEnteredUrl;
3747 private PowerManager.WakeLock mWakeLock;
3748 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3750 private Toast mStopToast;
3752 private TitleBar mTitleBar;
3754 private LinearLayout mErrorConsoleContainer = null;
3755 private boolean mShouldShowErrorConsole = false;
3757 // As the ids are dynamically created, we can't guarantee that they will
3758 // be in sequence, so this static array maps ids to a window number.
3759 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3760 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3761 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3762 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3764 // monitor platform changes
3765 private IntentFilter mNetworkStateChangedFilter;
3766 private BroadcastReceiver mNetworkStateIntentReceiver;
3768 private BroadcastReceiver mPackageInstallationReceiver;
3770 // activity requestCode
3771 final static int COMBO_PAGE = 1;
3772 final static int DOWNLOAD_PAGE = 2;
3773 final static int PREFERENCES_PAGE = 3;
3774 final static int FILE_SELECTED = 4;
3776 // the default <video> poster
3777 private Bitmap mDefaultVideoPoster;
3778 // the video progress view
3779 private View mVideoProgressView;
3782 * A UrlData class to abstract how the content will be set to WebView.
3783 * This base class uses loadUrl to show the content.
3785 private static class UrlData {
3789 UrlData(String url) {
3793 void setPostData(byte[] postData) {
3794 mPostData = postData;
3798 return mUrl == null || mUrl.length() == 0;
3801 public void loadIn(WebView webView) {
3802 if (mPostData != null) {
3803 webView.postUrl(mUrl, mPostData);
3805 webView.loadUrl(mUrl);
3811 * A subclass of UrlData class that can display inlined content using
3812 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3814 private static class InlinedUrlData extends UrlData {
3815 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3818 mMimeType = mimeType;
3819 mEncoding = encoding;
3826 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
3830 public void loadIn(WebView webView) {
3831 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3835 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);