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 com.google.android.googleapps.IGoogleLoginService;
20 import com.google.android.googlelogin.GoogleLoginServiceConstants;
22 import android.app.Activity;
23 import android.app.AlertDialog;
24 import android.app.ProgressDialog;
25 import android.app.SearchManager;
26 import android.content.ActivityNotFoundException;
27 import android.content.BroadcastReceiver;
28 import android.content.ComponentName;
29 import android.content.ContentResolver;
30 import android.content.ContentUris;
31 import android.content.ContentValues;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.ServiceConnection;
37 import android.content.DialogInterface.OnCancelListener;
38 import android.content.pm.PackageInfo;
39 import android.content.pm.PackageManager;
40 import android.content.pm.ResolveInfo;
41 import android.content.res.AssetManager;
42 import android.content.res.Configuration;
43 import android.content.res.Resources;
44 import android.database.Cursor;
45 import android.database.sqlite.SQLiteDatabase;
46 import android.database.sqlite.SQLiteException;
47 import android.graphics.Bitmap;
48 import android.graphics.BitmapFactory;
49 import android.graphics.Canvas;
50 import android.graphics.DrawFilter;
51 import android.graphics.Paint;
52 import android.graphics.PaintFlagsDrawFilter;
53 import android.graphics.Picture;
54 import android.graphics.PixelFormat;
55 import android.graphics.Rect;
56 import android.graphics.drawable.Drawable;
57 import android.hardware.SensorListener;
58 import android.hardware.SensorManager;
59 import android.net.ConnectivityManager;
60 import android.net.NetworkInfo;
61 import android.net.Uri;
62 import android.net.WebAddress;
63 import android.net.http.EventHandler;
64 import android.net.http.SslCertificate;
65 import android.net.http.SslError;
66 import android.os.AsyncTask;
67 import android.os.Bundle;
68 import android.os.Debug;
69 import android.os.Environment;
70 import android.os.Handler;
71 import android.os.IBinder;
72 import android.os.Message;
73 import android.os.PowerManager;
74 import android.os.Process;
75 import android.os.RemoteException;
76 import android.os.ServiceManager;
77 import android.os.SystemClock;
78 import android.provider.Browser;
79 import android.provider.ContactsContract;
80 import android.provider.ContactsContract.Intents.Insert;
81 import android.provider.Downloads;
82 import android.provider.MediaStore;
83 import android.text.IClipboard;
84 import android.text.TextUtils;
85 import android.text.format.DateFormat;
86 import android.text.util.Regex;
87 import android.util.AttributeSet;
88 import android.util.Log;
89 import android.view.ContextMenu;
90 import android.view.Gravity;
91 import android.view.KeyEvent;
92 import android.view.LayoutInflater;
93 import android.view.Menu;
94 import android.view.MenuInflater;
95 import android.view.MenuItem;
96 import android.view.View;
97 import android.view.ViewGroup;
98 import android.view.Window;
99 import android.view.WindowManager;
100 import android.view.ContextMenu.ContextMenuInfo;
101 import android.view.MenuItem.OnMenuItemClickListener;
102 import android.view.animation.AlphaAnimation;
103 import android.view.animation.Animation;
104 import android.view.animation.AnimationSet;
105 import android.view.animation.DecelerateInterpolator;
106 import android.view.animation.ScaleAnimation;
107 import android.view.animation.TranslateAnimation;
108 import android.webkit.CookieManager;
109 import android.webkit.CookieSyncManager;
110 import android.webkit.DownloadListener;
111 import android.webkit.GeolocationPermissions;
112 import android.webkit.HttpAuthHandler;
113 import android.webkit.PluginManager;
114 import android.webkit.SslErrorHandler;
115 import android.webkit.URLUtil;
116 import android.webkit.ValueCallback;
117 import android.webkit.WebChromeClient;
118 import android.webkit.WebChromeClient.CustomViewCallback;
119 import android.webkit.WebHistoryItem;
120 import android.webkit.WebIconDatabase;
121 import android.webkit.WebStorage;
122 import android.webkit.WebView;
123 import android.webkit.WebViewClient;
124 import android.widget.EditText;
125 import android.widget.FrameLayout;
126 import android.widget.LinearLayout;
127 import android.widget.TextView;
128 import android.widget.Toast;
130 import java.io.BufferedOutputStream;
131 import java.io.ByteArrayOutputStream;
133 import java.io.FileInputStream;
134 import java.io.FileOutputStream;
135 import java.io.IOException;
136 import java.io.InputStream;
137 import java.net.MalformedURLException;
139 import java.net.URISyntaxException;
141 import java.net.URLEncoder;
142 import java.text.ParseException;
143 import java.util.Date;
144 import java.util.Enumeration;
145 import java.util.HashMap;
146 import java.util.LinkedList;
147 import java.util.Vector;
148 import java.util.regex.Matcher;
149 import java.util.regex.Pattern;
150 import java.util.zip.ZipEntry;
151 import java.util.zip.ZipFile;
153 public class BrowserActivity extends Activity
154 implements View.OnCreateContextMenuListener,
157 /* Define some aliases to make these debugging flags easier to refer to.
158 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
160 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
161 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
162 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
164 private IGoogleLoginService mGls = null;
165 private ServiceConnection mGlsConnection = null;
167 private SensorManager mSensorManager = null;
169 // These are single-character shortcuts for searching popular sources.
170 private static final int SHORTCUT_INVALID = 0;
171 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
172 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
173 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
174 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
176 /* Whitelisted webpages
177 private static HashSet<String> sWhiteList;
180 sWhiteList = new HashSet<String>();
181 sWhiteList.add("cnn.com/");
182 sWhiteList.add("espn.go.com/");
183 sWhiteList.add("nytimes.com/");
184 sWhiteList.add("engadget.com/");
185 sWhiteList.add("yahoo.com/");
186 sWhiteList.add("msn.com/");
187 sWhiteList.add("amazon.com/");
188 sWhiteList.add("consumerist.com/");
189 sWhiteList.add("google.com/m/news");
193 private void setupHomePage() {
194 final Runnable getAccount = new Runnable() {
197 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
198 // get the default home page
199 String homepage = mSettings.getHomePage();
202 if (mGls == null) return;
204 if (!homepage.startsWith("http://www.google.")) return;
205 if (homepage.indexOf('?') == -1) return;
207 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
208 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
212 // hostedUser == googleUser
213 // The device has only a google account
215 // hostedUser != googleUser
216 // The device has a hosted account and a google account
218 // hostedUser != null, googleUser == null
219 // The device has only a hosted account (so far)
221 // developers might have no accounts at all
222 if (hostedUser == null) return;
224 if (googleUser == null || !hostedUser.equals(googleUser)) {
225 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
226 homepage = homepage.replace("?", "/a/" + domain + "?");
228 } catch (RemoteException ignore) {
229 // Login service died; carry on
230 } catch (RuntimeException ignore) {
231 // Login service died; carry on
237 private void finish(final String homepage) {
238 mHandler.post(new Runnable() {
240 mSettings.setHomePage(BrowserActivity.this, homepage);
241 resumeAfterCredentials();
243 // as this is running in a separate thread,
244 // BrowserActivity's onDestroy() may have been called,
245 // which also calls unbindService().
246 if (mGlsConnection != null) {
247 // we no longer need to keep GLS open
248 unbindService(mGlsConnection);
249 mGlsConnection = null;
254 final boolean[] done = { false };
256 // Open a connection to the Google Login Service. The first
257 // time the connection is established, set up the homepage depending on
258 // the account in a background thread.
259 mGlsConnection = new ServiceConnection() {
260 public void onServiceConnected(ComponentName className, IBinder service) {
261 mGls = IGoogleLoginService.Stub.asInterface(service);
262 if (done[0] == false) {
264 Thread account = new Thread(getAccount);
265 account.setName("GLSAccount");
269 public void onServiceDisconnected(ComponentName className) {
274 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
275 mGlsConnection, Context.BIND_AUTO_CREATE);
278 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
280 public Void doInBackground(File... files) {
282 for (File f : files) {
284 Log.e(LOGTAG, f.getPath() + " was not deleted");
293 * This layout holds everything you see below the status bar, including the
294 * error console, the custom view container, and the webviews.
296 private FrameLayout mBrowserFrameLayout;
298 @Override public void onCreate(Bundle icicle) {
300 Log.v(LOGTAG, this + " onStart");
302 super.onCreate(icicle);
303 // test the browser in OpenGL
304 // requestWindowFeature(Window.FEATURE_OPENGL);
306 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
308 mResolver = getContentResolver();
310 // If this was a web search request, pass it on to the default web
311 // search provider and finish this activity.
312 if (handleWebSearchIntent(getIntent())) {
318 // start MASF proxy service
320 //Intent proxyServiceIntent = new Intent();
321 //proxyServiceIntent.setComponent
322 // (new ComponentName(
323 // "com.android.masfproxyservice",
324 // "com.android.masfproxyservice.MasfProxyService"));
325 //startService(proxyServiceIntent, null);
327 mSecLockIcon = Resources.getSystem().getDrawable(
328 android.R.drawable.ic_secure);
329 mMixLockIcon = Resources.getSystem().getDrawable(
330 android.R.drawable.ic_partial_secure);
332 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
333 .findViewById(com.android.internal.R.id.content);
334 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
335 .inflate(R.layout.custom_screen, null);
336 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
338 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
339 .findViewById(R.id.error_console);
340 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
341 .findViewById(R.id.fullscreen_custom_content);
342 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
343 mTitleBar = new TitleBar(this);
345 // Create the tab control and our initial tab
346 mTabControl = new TabControl(this);
348 // Open the icon database and retain all the bookmark urls for favicons
349 retainIconsOnStartup();
351 // Keep a settings instance handy.
352 mSettings = BrowserSettings.getInstance();
353 mSettings.setTabControl(mTabControl);
354 mSettings.loadFromDb(this);
356 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
357 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
359 /* enables registration for changes in network status from
361 mNetworkStateChangedFilter = new IntentFilter();
362 mNetworkStateChangedFilter.addAction(
363 ConnectivityManager.CONNECTIVITY_ACTION);
364 mNetworkStateIntentReceiver = new BroadcastReceiver() {
366 public void onReceive(Context context, Intent intent) {
367 if (intent.getAction().equals(
368 ConnectivityManager.CONNECTIVITY_ACTION)) {
369 boolean noConnectivity = intent.getBooleanExtra(
370 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
371 onNetworkToggle(!noConnectivity);
376 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
377 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
378 filter.addDataScheme("package");
379 mPackageInstallationReceiver = new BroadcastReceiver() {
381 public void onReceive(Context context, Intent intent) {
382 final String action = intent.getAction();
383 final String packageName = intent.getData()
384 .getSchemeSpecificPart();
385 final boolean replacing = intent.getBooleanExtra(
386 Intent.EXTRA_REPLACING, false);
387 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
388 // if it is replacing, refreshPlugins() when adding
391 PackageManager pm = BrowserActivity.this.getPackageManager();
392 PackageInfo pkgInfo = null;
394 pkgInfo = pm.getPackageInfo(packageName,
395 PackageManager.GET_PERMISSIONS);
396 } catch (PackageManager.NameNotFoundException e) {
399 if (pkgInfo != null) {
400 String permissions[] = pkgInfo.requestedPermissions;
401 if (permissions == null) {
404 boolean permissionOk = false;
405 for (String permit : permissions) {
406 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
412 PluginManager.getInstance(BrowserActivity.this)
414 Intent.ACTION_PACKAGE_ADDED
420 registerReceiver(mPackageInstallationReceiver, filter);
422 if (!mTabControl.restoreState(icicle)) {
423 // clear up the thumbnail directory if we can't restore the state as
424 // none of the files in the directory are referenced any more.
425 new ClearThumbnails().execute(
426 mTabControl.getThumbnailDir().listFiles());
427 // there is no quit on Android. But if we can't restore the state,
428 // we can treat it as a new Browser, remove the old session cookies.
429 CookieManager.getInstance().removeSessionCookie();
430 final Intent intent = getIntent();
431 final Bundle extra = intent.getExtras();
432 // Create an initial tab.
433 // If the intent is ACTION_VIEW and data is not null, the Browser is
434 // invoked to view the content by another application. In this case,
435 // the tab will be close when exit.
436 UrlData urlData = getUrlDataFromIntent(intent);
438 final TabControl.Tab t = mTabControl.createNewTab(
439 Intent.ACTION_VIEW.equals(intent.getAction()) &&
440 intent.getData() != null,
441 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
442 mTabControl.setCurrentTab(t);
443 attachTabToContentView(t);
444 WebView webView = t.getWebView();
446 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
447 if (scale > 0 && scale <= 1000) {
448 webView.setInitialScale(scale);
451 // If we are not restoring from an icicle, then there is a high
452 // likely hood this is the first run. So, check to see if the
453 // homepage needs to be configured and copy any plugins from our
454 // asset directory to the data partition.
455 if ((extra == null || !extra.getBoolean("testing"))
456 && !mSettings.isLoginInitialized()) {
460 if (urlData.isEmpty()) {
461 if (mSettings.isLoginInitialized()) {
462 webView.loadUrl(mSettings.getHomePage());
464 waitForCredentials();
468 urlData.setPostData(extra
469 .getByteArray(Browser.EXTRA_POST_DATA));
471 urlData.loadIn(webView);
474 // TabControl.restoreState() will create a new tab even if
475 // restoring the state fails.
476 attachTabToContentView(mTabControl.getCurrentTab());
479 // Read JavaScript flags if it exists.
480 String jsFlags = mSettings.getJsFlags();
481 if (jsFlags.trim().length() != 0) {
482 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
487 protected void onNewIntent(Intent intent) {
488 TabControl.Tab current = mTabControl.getCurrentTab();
489 // When a tab is closed on exit, the current tab index is set to -1.
490 // Reset before proceed as Browser requires the current tab to be set.
491 if (current == null) {
492 // Try to reset the tab in case the index was incorrect.
493 current = mTabControl.getTab(0);
494 if (current == null) {
495 // No tabs at all so just ignore this intent.
498 mTabControl.setCurrentTab(current);
499 attachTabToContentView(current);
500 resetTitleAndIcon(current.getWebView());
502 final String action = intent.getAction();
503 final int flags = intent.getFlags();
504 if (Intent.ACTION_MAIN.equals(action) ||
505 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
506 // just resume the browser
509 if (Intent.ACTION_VIEW.equals(action)
510 || Intent.ACTION_SEARCH.equals(action)
511 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
512 || Intent.ACTION_WEB_SEARCH.equals(action)) {
513 // If this was a search request (e.g. search query directly typed into the address bar),
514 // pass it on to the default web search provider.
515 if (handleWebSearchIntent(intent)) {
519 UrlData urlData = getUrlDataFromIntent(intent);
520 if (urlData.isEmpty()) {
521 urlData = new UrlData(mSettings.getHomePage());
523 urlData.setPostData(intent
524 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
526 final String appId = intent
527 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
528 if (Intent.ACTION_VIEW.equals(action)
529 && !getPackageName().equals(appId)
530 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
531 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
532 if (appTab != null) {
533 Log.i(LOGTAG, "Reusing tab for " + appId);
534 // Dismiss the subwindow if applicable.
535 dismissSubWindow(appTab);
536 // Since we might kill the WebView, remove it from the
537 // content view first.
538 removeTabFromContentView(appTab);
539 // Recreate the main WebView after destroying the old one.
540 // If the WebView has the same original url and is on that
541 // page, it can be reused.
543 mTabControl.recreateWebView(appTab, urlData.mUrl);
545 if (current != appTab) {
546 switchToTab(mTabControl.getTabIndex(appTab));
548 urlData.loadIn(appTab.getWebView());
551 // If the tab was the current tab, we have to attach
552 // it to the view system again.
553 attachTabToContentView(appTab);
555 urlData.loadIn(appTab.getWebView());
560 // No matching application tab, try to find a regular tab
561 // with a matching url.
562 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
563 if (appTab != null) {
564 if (current != appTab) {
565 switchToTab(mTabControl.getTabIndex(appTab));
567 // Otherwise, we are already viewing the correct tab.
569 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
570 // will be opened in a new tab unless we have reached
571 // MAX_TABS. Then the url will be opened in the current
572 // tab. If a new tab is created, it will have "true" for
574 openTabAndShow(urlData, true, appId);
578 if ("about:debug".equals(urlData.mUrl)) {
579 mSettings.toggleDebugSettings();
582 // Get rid of the subwindow if it exists
583 dismissSubWindow(current);
584 urlData.loadIn(current.getWebView());
589 private int parseUrlShortcut(String url) {
590 if (url == null) return SHORTCUT_INVALID;
592 // FIXME: quick search, need to be customized by setting
593 if (url.length() > 2 && url.charAt(1) == ' ') {
594 switch (url.charAt(0)) {
595 case 'g': return SHORTCUT_GOOGLE_SEARCH;
596 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
597 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
598 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
601 return SHORTCUT_INVALID;
605 * Launches the default web search activity with the query parameters if the given intent's data
606 * are identified as plain search terms and not URLs/shortcuts.
607 * @return true if the intent was handled and web search activity was launched, false if not.
609 private boolean handleWebSearchIntent(Intent intent) {
610 if (intent == null) return false;
613 final String action = intent.getAction();
614 if (Intent.ACTION_VIEW.equals(action)) {
615 Uri data = intent.getData();
616 if (data != null) url = data.toString();
617 } else if (Intent.ACTION_SEARCH.equals(action)
618 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
619 || Intent.ACTION_WEB_SEARCH.equals(action)) {
620 url = intent.getStringExtra(SearchManager.QUERY);
622 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
623 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
627 * Launches the default web search activity with the query parameters if the given url string
628 * was identified as plain search terms and not URL/shortcut.
629 * @return true if the request was handled and web search activity was launched, false if not.
631 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
632 if (inUrl == null) return false;
634 // In general, we shouldn't modify URL from Intent.
635 // But currently, we get the user-typed URL from search box as well.
636 String url = fixUrl(inUrl).trim();
638 // URLs and site specific search shortcuts are handled by the regular flow of control, so
640 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
641 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
642 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
646 Browser.updateVisitedHistory(mResolver, url, false);
647 Browser.addSearchUrl(mResolver, url);
649 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
650 intent.addCategory(Intent.CATEGORY_DEFAULT);
651 intent.putExtra(SearchManager.QUERY, url);
652 if (appData != null) {
653 intent.putExtra(SearchManager.APP_DATA, appData);
655 if (extraData != null) {
656 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
658 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
659 startActivity(intent);
664 private UrlData getUrlDataFromIntent(Intent intent) {
666 if (intent != null) {
667 final String action = intent.getAction();
668 if (Intent.ACTION_VIEW.equals(action)) {
669 url = smartUrlFilter(intent.getData());
670 if (url != null && url.startsWith("content:")) {
671 /* Append mimetype so webview knows how to display */
672 String mimeType = intent.resolveType(getContentResolver());
673 if (mimeType != null) {
674 url += "?" + mimeType;
677 if ("inline:".equals(url)) {
678 return new InlinedUrlData(
679 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
681 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
682 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
684 } else if (Intent.ACTION_SEARCH.equals(action)
685 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
686 || Intent.ACTION_WEB_SEARCH.equals(action)) {
687 url = intent.getStringExtra(SearchManager.QUERY);
689 mLastEnteredUrl = url;
690 // Don't add Urls, just search terms.
691 // Urls will get added when the page is loaded.
692 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
693 Browser.updateVisitedHistory(mResolver, url, false);
695 // In general, we shouldn't modify URL from Intent.
696 // But currently, we get the user-typed URL from search box as well.
698 url = smartUrlFilter(url);
699 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
700 if (url.contains(searchSource)) {
701 String source = null;
702 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
703 if (appData != null) {
704 source = appData.getString(SearchManager.SOURCE);
706 if (TextUtils.isEmpty(source)) {
707 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
709 url = url.replace(searchSource, "&source=android-"+source+"&");
714 return new UrlData(url);
717 /* package */ static String fixUrl(String inUrl) {
718 // FIXME: Converting the url to lower case
719 // duplicates functionality in smartUrlFilter().
720 // However, changing all current callers of fixUrl to
721 // call smartUrlFilter in addition may have unwanted
722 // consequences, and is deferred for now.
723 int colon = inUrl.indexOf(':');
724 boolean allLower = true;
725 for (int index = 0; index < colon; index++) {
726 char ch = inUrl.charAt(index);
727 if (!Character.isLetter(ch)) {
730 allLower &= Character.isLowerCase(ch);
731 if (index == colon - 1 && !allLower) {
732 inUrl = inUrl.substring(0, colon).toLowerCase()
733 + inUrl.substring(colon);
736 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
738 if (inUrl.startsWith("http:") ||
739 inUrl.startsWith("https:")) {
740 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
741 inUrl = inUrl.replaceFirst("/", "//");
742 } else inUrl = inUrl.replaceFirst(":", "://");
748 * Looking for the pattern like this
757 private final SensorListener mSensorListener = new SensorListener() {
758 private long mLastGestureTime;
759 private float[] mPrev = new float[3];
760 private float[] mPrevDiff = new float[3];
761 private float[] mDiff = new float[3];
762 private float[] mRevertDiff = new float[3];
764 public void onSensorChanged(int sensor, float[] values) {
765 boolean show = false;
766 float[] diff = new float[3];
768 for (int i = 0; i < 3; i++) {
769 diff[i] = values[i] - mPrev[i];
770 if (Math.abs(diff[i]) > 1) {
773 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
774 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
775 // start track when there is a big move, or revert
776 mRevertDiff[i] = mDiff[i];
778 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
779 // reset when it is flat
780 mDiff[i] = mRevertDiff[i] = 0;
783 mPrevDiff[i] = diff[i];
784 mPrev[i] = values[i];
788 // only shows if we think the delta is big enough, in an attempt
789 // to detect "serious" moves left/right or up/down
790 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
791 + values[0] + ", " + values[1] + ", " + values[2] + ")"
792 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
794 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
795 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
796 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
797 + mRevertDiff[2] + ")");
800 long now = android.os.SystemClock.uptimeMillis();
801 if (now - mLastGestureTime > 1000) {
802 mLastGestureTime = 0;
806 float ay = Math.abs(y);
807 float az = Math.abs(z);
808 float ry = mRevertDiff[1];
809 float rz = mRevertDiff[2];
810 float ary = Math.abs(ry);
811 float arz = Math.abs(rz);
812 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
813 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
815 if ((gestY || gestZ) && !(gestY && gestZ)) {
816 WebView view = mTabControl.getCurrentWebView();
826 view.flingScroll(0, Math.round(y * 100));
829 mLastGestureTime = now;
834 public void onAccuracyChanged(int sensor, int accuracy) {
835 // TODO Auto-generated method stub
840 @Override protected void onResume() {
843 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
846 if (!mActivityInPause) {
847 Log.e(LOGTAG, "BrowserActivity is already resumed.");
851 mTabControl.resumeCurrentTab();
852 mActivityInPause = false;
853 resumeWebViewTimers();
855 if (mWakeLock.isHeld()) {
856 mHandler.removeMessages(RELEASE_WAKELOCK);
860 if (mCredsDlg != null) {
861 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
862 // In case credential request never comes back
863 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
867 registerReceiver(mNetworkStateIntentReceiver,
868 mNetworkStateChangedFilter);
869 WebView.enablePlatformNotifications();
871 if (mSettings.doFlick()) {
872 if (mSensorManager == null) {
873 mSensorManager = (SensorManager) getSystemService(
874 Context.SENSOR_SERVICE);
876 mSensorManager.registerListener(mSensorListener,
877 SensorManager.SENSOR_ACCELEROMETER,
878 SensorManager.SENSOR_DELAY_FASTEST);
880 mSensorManager = null;
885 * Since the actual title bar is embedded in the WebView, and removing it
886 * would change its appearance, create a temporary title bar to go at
887 * the top of the screen while the menu is open.
889 private TitleBar mFakeTitleBar;
892 * Holder for the fake title bar. It will have a foreground shadow, as well
893 * as a white background, so the fake title bar looks like the real one.
895 private ViewGroup mFakeTitleBarHolder;
898 * Layout parameters for the fake title bar within mFakeTitleBarHolder
900 private FrameLayout.LayoutParams mFakeTitleBarParams
901 = new FrameLayout.LayoutParams(
902 ViewGroup.LayoutParams.FILL_PARENT,
903 ViewGroup.LayoutParams.WRAP_CONTENT);
905 * Keeps track of whether the options menu is open. This is important in
906 * determining whether to show or hide the title bar overlay.
908 private boolean mOptionsMenuOpen;
911 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
912 * of whether the configuration has changed. The first onMenuOpened call
913 * after a configuration change is simply a reopening of the same menu
914 * (i.e. mIconView did not change).
916 private boolean mConfigChanged;
919 * Whether or not the options menu is in its smaller, icon menu form. When
920 * true, we want the title bar overlay to be up. When false, we do not.
921 * Only meaningful if mOptionsMenuOpen is true.
923 private boolean mIconView;
926 public boolean onMenuOpened(int featureId, Menu menu) {
927 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
928 if (mOptionsMenuOpen) {
929 if (mConfigChanged) {
930 // We do not need to make any changes to the state of the
931 // title bar, since the only thing that happened was a
932 // change in orientation
933 mConfigChanged = false;
936 // Switching the menu to expanded view, so hide the
941 // Switching the menu back to icon view, so show the
942 // title bar once again.
948 // The options menu is closed, so open it, and show the title
950 mOptionsMenuOpen = true;
951 mConfigChanged = false;
959 * Special class used exclusively for the shadow drawn underneath the fake
960 * title bar. The shadow does not need to be drawn if the WebView
961 * underneath is scrolled to the top, because it will draw directly on top
962 * of the embedded shadow.
964 private static class Shadow extends View {
965 private WebView mWebView;
967 public Shadow(Context context, AttributeSet attrs) {
968 super(context, attrs);
971 public void setWebView(WebView view) {
976 public void draw(Canvas canvas) {
977 // In general onDraw is the method to override, but we care about
978 // whether or not the background gets drawn, which happens in draw()
979 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
982 // Need to invalidate so that if the scroll position changes, we
983 // still draw as appropriate.
988 private void showFakeTitleBar() {
989 final View decor = getWindow().peekDecorView();
990 if (mFakeTitleBar == null && mActiveTabsPage == null
991 && !mActivityInPause && decor != null
992 && decor.getWindowToken() != null) {
993 Rect visRect = new Rect();
994 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
996 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
1000 final WebView webView = getTopWindow();
1001 mFakeTitleBar = new TitleBar(this);
1002 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
1003 mFakeTitleBar.setProgress(webView.getProgress());
1004 mFakeTitleBar.setFavicon(webView.getFavicon());
1005 updateLockIconToLatest();
1007 WindowManager manager
1008 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1010 // Add the title bar to the window manager so it can receive touches
1011 // while the menu is up
1012 WindowManager.LayoutParams params
1013 = new WindowManager.LayoutParams(
1014 ViewGroup.LayoutParams.FILL_PARENT,
1015 ViewGroup.LayoutParams.WRAP_CONTENT,
1016 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
1017 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
1018 PixelFormat.TRANSLUCENT);
1019 params.gravity = Gravity.TOP;
1020 WebView mainView = mTabControl.getCurrentWebView();
1021 boolean atTop = mainView != null && mainView.getScrollY() == 0;
1022 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
1023 // XXX : Without providing an offset, the fake title bar will be
1024 // placed underneath the status bar. Use the global visible rect
1025 // of mBrowserFrameLayout to determine the bottom of the status bar
1026 params.y = visRect.top;
1027 // Add a holder for the title bar. It also holds a shadow to show
1028 // below the title bar.
1029 if (mFakeTitleBarHolder == null) {
1030 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
1031 .inflate(R.layout.title_bar_bg, null);
1033 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
1035 shadow.setWebView(mainView);
1036 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
1037 manager.addView(mFakeTitleBarHolder, params);
1042 public void onOptionsMenuClosed(Menu menu) {
1043 mOptionsMenuOpen = false;
1046 } else if (!mIconView) {
1047 // The page is currently loading, and we are in expanded mode, so
1048 // we were not showing the menu. Show it once again. It will be
1049 // removed when the page finishes.
1053 private void hideFakeTitleBar() {
1054 if (mFakeTitleBar == null) return;
1055 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1056 mFakeTitleBarHolder.getLayoutParams();
1057 WebView mainView = mTabControl.getCurrentWebView();
1058 // Although we decided whether or not to animate based on the current
1059 // scroll position, the scroll position may have changed since the
1060 // fake title bar was displayed. Make sure it has the appropriate
1061 // animation/lack thereof before removing.
1062 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
1063 ? 0 : R.style.TitleBar;
1064 WindowManager manager
1065 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1066 manager.updateViewLayout(mFakeTitleBarHolder, params);
1067 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1068 manager.removeView(mFakeTitleBarHolder);
1069 mFakeTitleBar = null;
1073 * Special method for the fake title bar to call when displaying its context
1074 * menu, since it is in its own Window, and its parent does not show a
1077 /* package */ void showTitleBarContextMenu() {
1078 if (null == mTitleBar.getParent()) {
1081 openContextMenu(mTitleBar);
1085 * onSaveInstanceState(Bundle map)
1086 * onSaveInstanceState is called right before onStop(). The map contains
1089 @Override protected void onSaveInstanceState(Bundle outState) {
1091 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1093 // the default implementation requires each view to have an id. As the
1094 // browser handles the state itself and it doesn't use id for the views,
1095 // don't call the default implementation. Otherwise it will trigger the
1096 // warning like this, "couldn't save which view has focus because the
1097 // focused view XXX has no id".
1099 // Save all the tabs
1100 mTabControl.saveState(outState);
1103 @Override protected void onPause() {
1106 if (mActivityInPause) {
1107 Log.e(LOGTAG, "BrowserActivity is already paused.");
1111 mTabControl.pauseCurrentTab();
1112 mActivityInPause = true;
1113 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1114 mWakeLock.acquire();
1115 mHandler.sendMessageDelayed(mHandler
1116 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1119 // Clear the credentials toast if it is up
1120 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1121 mCredsDlg.dismiss();
1125 // FIXME: This removes the active tabs page and resets the menu to
1126 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1127 // but then we would need to save it in onSaveInstanceState and restore
1128 // it in onCreate/onRestoreInstanceState
1129 if (mActiveTabsPage != null) {
1130 removeActiveTabPage(true);
1135 // unregister network state listener
1136 unregisterReceiver(mNetworkStateIntentReceiver);
1137 WebView.disablePlatformNotifications();
1139 if (mSensorManager != null) {
1140 mSensorManager.unregisterListener(mSensorListener);
1144 @Override protected void onDestroy() {
1146 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1150 if (mTabControl == null) return;
1152 // Remove the current tab and sub window
1153 TabControl.Tab t = mTabControl.getCurrentTab();
1155 dismissSubWindow(t);
1156 removeTabFromContentView(t);
1158 // Destroy all the tabs
1159 mTabControl.destroy();
1160 WebIconDatabase.getInstance().close();
1161 if (mGlsConnection != null) {
1162 unbindService(mGlsConnection);
1163 mGlsConnection = null;
1167 // stop MASF proxy service
1169 //Intent proxyServiceIntent = new Intent();
1170 //proxyServiceIntent.setComponent
1171 // (new ComponentName(
1172 // "com.android.masfproxyservice",
1173 // "com.android.masfproxyservice.MasfProxyService"));
1174 //stopService(proxyServiceIntent);
1176 unregisterReceiver(mPackageInstallationReceiver);
1180 public void onConfigurationChanged(Configuration newConfig) {
1181 mConfigChanged = true;
1182 super.onConfigurationChanged(newConfig);
1184 if (mPageInfoDialog != null) {
1185 mPageInfoDialog.dismiss();
1188 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1190 if (mSSLCertificateDialog != null) {
1191 mSSLCertificateDialog.dismiss();
1193 mSSLCertificateView);
1195 if (mSSLCertificateOnErrorDialog != null) {
1196 mSSLCertificateOnErrorDialog.dismiss();
1197 showSSLCertificateOnError(
1198 mSSLCertificateOnErrorView,
1199 mSSLCertificateOnErrorHandler,
1200 mSSLCertificateOnErrorError);
1202 if (mHttpAuthenticationDialog != null) {
1203 String title = ((TextView) mHttpAuthenticationDialog
1204 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1206 String name = ((TextView) mHttpAuthenticationDialog
1207 .findViewById(R.id.username_edit)).getText().toString();
1208 String password = ((TextView) mHttpAuthenticationDialog
1209 .findViewById(R.id.password_edit)).getText().toString();
1210 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1212 mHttpAuthenticationDialog.dismiss();
1213 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1214 name, password, focusId);
1216 if (mFindDialog != null && mFindDialog.isShowing()) {
1217 mFindDialog.onConfigurationChanged(newConfig);
1221 @Override public void onLowMemory() {
1222 super.onLowMemory();
1223 mTabControl.freeMemory();
1226 private boolean resumeWebViewTimers() {
1227 if ((!mActivityInPause && !mPageStarted) ||
1228 (mActivityInPause && mPageStarted)) {
1229 CookieSyncManager.getInstance().startSync();
1230 WebView w = mTabControl.getCurrentWebView();
1240 private boolean pauseWebViewTimers() {
1241 if (mActivityInPause && !mPageStarted) {
1242 CookieSyncManager.getInstance().stopSync();
1243 WebView w = mTabControl.getCurrentWebView();
1253 // FIXME: Do we want to call this when loading google for the first time?
1255 * This function is called when we are launching for the first time. We
1256 * are waiting for the login credentials before loading Google home
1257 * pages. This way the user will be logged in straight away.
1259 private void waitForCredentials() {
1261 mCredsDlg = new ProgressDialog(this);
1262 mCredsDlg.setIndeterminate(true);
1263 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1264 // If the user cancels the operation, then cancel the Google
1265 // Credentials request.
1266 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1269 // We set a timeout for the retrieval of credentials in onResume()
1270 // as that is when we have freed up some CPU time to get
1271 // the login credentials.
1275 * If we have received the credentials or we have timed out and we are
1276 * showing the credentials dialog, then it is time to move on.
1278 private void resumeAfterCredentials() {
1279 if (mCredsDlg == null) {
1284 if (mCredsDlg.isShowing()) {
1285 mCredsDlg.dismiss();
1289 // Clear any pending timeout
1290 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1293 WebView w = mTabControl.getCurrentWebView();
1295 w.loadUrl(mSettings.getHomePage());
1298 // Update the settings, need to do this last as it can take a moment
1299 // to persist the settings. In the mean time we could be loading
1301 mSettings.setLoginInitialized(this);
1304 // Open the icon database and retain all the icons for visited sites.
1305 private void retainIconsOnStartup() {
1306 final WebIconDatabase db = WebIconDatabase.getInstance();
1307 db.open(getDir("icons", 0).getPath());
1309 Cursor c = Browser.getAllBookmarks(mResolver);
1310 if (!c.moveToFirst()) {
1314 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1316 String url = c.getString(urlIndex);
1317 db.retainIconForPageUrl(url);
1318 } while (c.moveToNext());
1320 } catch (IllegalStateException e) {
1321 Log.e(LOGTAG, "retainIconsOnStartup", e);
1325 // Helper method for getting the top window.
1326 WebView getTopWindow() {
1327 return mTabControl.getCurrentTopWebView();
1331 public boolean onCreateOptionsMenu(Menu menu) {
1332 super.onCreateOptionsMenu(menu);
1334 MenuInflater inflater = getMenuInflater();
1335 inflater.inflate(R.menu.browser, menu);
1337 updateInLoadMenuItems();
1342 * As the menu can be open when loading state changes
1343 * we must manually update the state of the stop/reload menu
1346 private void updateInLoadMenuItems() {
1347 if (mMenu == null) {
1350 MenuItem src = mInLoad ?
1351 mMenu.findItem(R.id.stop_menu_id):
1352 mMenu.findItem(R.id.reload_menu_id);
1353 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1354 dest.setIcon(src.getIcon());
1355 dest.setTitle(src.getTitle());
1359 public boolean onContextItemSelected(MenuItem item) {
1360 // chording is not an issue with context menus, but we use the same
1361 // options selector, so set mCanChord to true so we can access them.
1363 int id = item.getItemId();
1365 // For the context menu from the title bar
1366 case R.id.title_bar_share_page_url:
1367 case R.id.title_bar_copy_page_url:
1368 WebView mainView = mTabControl.getCurrentWebView();
1369 if (null == mainView) {
1372 if (id == R.id.title_bar_share_page_url) {
1373 Browser.sendString(this, mainView.getUrl());
1375 copy(mainView.getUrl());
1378 // -- Browser context menu
1379 case R.id.open_context_menu_id:
1380 case R.id.open_newtab_context_menu_id:
1381 case R.id.bookmark_context_menu_id:
1382 case R.id.save_link_context_menu_id:
1383 case R.id.share_link_context_menu_id:
1384 case R.id.copy_link_context_menu_id:
1385 final WebView webView = getTopWindow();
1386 if (null == webView) {
1389 final HashMap hrefMap = new HashMap();
1390 hrefMap.put("webview", webView);
1391 final Message msg = mHandler.obtainMessage(
1392 FOCUS_NODE_HREF, id, 0, hrefMap);
1393 webView.requestFocusNodeHref(msg);
1397 // For other context menus
1398 return onOptionsItemSelected(item);
1404 private Bundle createGoogleSearchSourceBundle(String source) {
1405 Bundle bundle = new Bundle();
1406 bundle.putString(SearchManager.SOURCE, source);
1411 * Overriding this to insert a local information bundle
1414 public boolean onSearchRequested() {
1415 if (mOptionsMenuOpen) closeOptionsMenu();
1416 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1417 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1418 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1423 public void startSearch(String initialQuery, boolean selectInitialQuery,
1424 Bundle appSearchData, boolean globalSearch) {
1425 if (appSearchData == null) {
1426 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1428 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1432 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1433 * results in changing tabs.
1434 * @param index Index of the tab to change to, as defined by
1435 * mTabControl.getTabIndex(Tab t).
1436 * @return boolean True if we successfully switched to a different tab. If
1437 * the indexth tab is null, or if that tab is the same as
1438 * the current one, return false.
1440 /* package */ boolean switchToTab(int index) {
1441 TabControl.Tab tab = mTabControl.getTab(index);
1442 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1443 if (tab == null || tab == currentTab) {
1446 if (currentTab != null) {
1447 // currentTab may be null if it was just removed. In that case,
1448 // we do not need to remove it
1449 removeTabFromContentView(currentTab);
1451 mTabControl.setCurrentTab(tab);
1452 attachTabToContentView(tab);
1453 resetTitleIconAndProgress();
1454 updateLockIconToLatest();
1458 /* package */ TabControl.Tab openTabToHomePage() {
1459 return openTabAndShow(mSettings.getHomePage(), false, null);
1462 /* package */ void closeCurrentWindow() {
1463 final TabControl.Tab current = mTabControl.getCurrentTab();
1464 if (mTabControl.getTabCount() == 1) {
1465 // This is the last tab. Open a new one, with the home
1466 // page and close the current one.
1467 openTabToHomePage();
1471 final TabControl.Tab parent = current.getParentTab();
1472 int indexToShow = -1;
1473 if (parent != null) {
1474 indexToShow = mTabControl.getTabIndex(parent);
1476 final int currentIndex = mTabControl.getCurrentIndex();
1477 // Try to move to the tab to the right
1478 indexToShow = currentIndex + 1;
1479 if (indexToShow > mTabControl.getTabCount() - 1) {
1480 // Try to move to the tab to the left
1481 indexToShow = currentIndex - 1;
1484 if (switchToTab(indexToShow)) {
1490 private ActiveTabsPage mActiveTabsPage;
1493 * Remove the active tabs page.
1494 * @param needToAttach If true, the active tabs page did not attach a tab
1495 * to the content view, so we need to do that here.
1497 /* package */ void removeActiveTabPage(boolean needToAttach) {
1498 mContentView.removeView(mActiveTabsPage);
1499 mActiveTabsPage = null;
1500 mMenuState = R.id.MAIN_MENU;
1502 attachTabToContentView(mTabControl.getCurrentTab());
1504 getTopWindow().requestFocus();
1508 public boolean onOptionsItemSelected(MenuItem item) {
1510 // The user has already fired a shortcut with this hold down of the
1514 if (null == getTopWindow()) {
1518 // The shortcut action consumes the MENU. Even if it is still down,
1519 // it won't trigger the next shortcut action. In the case of the
1520 // shortcut action triggering a new activity, like Bookmarks, we
1521 // won't get onKeyUp for MENU. So it is important to reset it here.
1522 mMenuIsDown = false;
1524 switch (item.getItemId()) {
1526 case R.id.new_tab_menu_id:
1527 openTabToHomePage();
1530 case R.id.goto_menu_id:
1531 onSearchRequested();
1534 case R.id.bookmarks_menu_id:
1535 bookmarksOrHistoryPicker(false);
1538 case R.id.active_tabs_menu_id:
1539 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1540 removeTabFromContentView(mTabControl.getCurrentTab());
1542 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1543 mActiveTabsPage.requestFocus();
1544 mMenuState = EMPTY_MENU;
1547 case R.id.add_bookmark_menu_id:
1548 Intent i = new Intent(BrowserActivity.this,
1549 AddBookmarkPage.class);
1550 WebView w = getTopWindow();
1551 i.putExtra("url", w.getUrl());
1552 i.putExtra("title", w.getTitle());
1553 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1554 i.putExtra("thumbnail", createScreenshot(w));
1558 case R.id.stop_reload_menu_id:
1562 getTopWindow().reload();
1566 case R.id.back_menu_id:
1567 getTopWindow().goBack();
1570 case R.id.forward_menu_id:
1571 getTopWindow().goForward();
1574 case R.id.close_menu_id:
1575 // Close the subwindow if it exists.
1576 if (mTabControl.getCurrentSubWindow() != null) {
1577 dismissSubWindow(mTabControl.getCurrentTab());
1580 closeCurrentWindow();
1583 case R.id.homepage_menu_id:
1584 TabControl.Tab current = mTabControl.getCurrentTab();
1585 if (current != null) {
1586 dismissSubWindow(current);
1587 current.getWebView().loadUrl(mSettings.getHomePage());
1591 case R.id.preferences_menu_id:
1592 Intent intent = new Intent(this,
1593 BrowserPreferencesPage.class);
1594 startActivityForResult(intent, PREFERENCES_PAGE);
1597 case R.id.find_menu_id:
1598 if (null == mFindDialog) {
1599 mFindDialog = new FindDialog(this);
1601 mFindDialog.setWebView(getTopWindow());
1603 mMenuState = EMPTY_MENU;
1606 case R.id.select_text_id:
1607 getTopWindow().emulateShiftHeld();
1609 case R.id.page_info_menu_id:
1610 showPageInfo(mTabControl.getCurrentTab(), false);
1613 case R.id.classic_history_menu_id:
1614 bookmarksOrHistoryPicker(true);
1617 case R.id.share_page_menu_id:
1618 Browser.sendString(this, getTopWindow().getUrl(),
1619 getText(R.string.choosertitle_sharevia).toString());
1622 case R.id.dump_nav_menu_id:
1623 getTopWindow().debugDump();
1626 case R.id.zoom_in_menu_id:
1627 getTopWindow().zoomIn();
1630 case R.id.zoom_out_menu_id:
1631 getTopWindow().zoomOut();
1634 case R.id.view_downloads_menu_id:
1635 viewDownloads(null);
1638 case R.id.window_one_menu_id:
1639 case R.id.window_two_menu_id:
1640 case R.id.window_three_menu_id:
1641 case R.id.window_four_menu_id:
1642 case R.id.window_five_menu_id:
1643 case R.id.window_six_menu_id:
1644 case R.id.window_seven_menu_id:
1645 case R.id.window_eight_menu_id:
1647 int menuid = item.getItemId();
1648 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1649 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1650 TabControl.Tab desiredTab = mTabControl.getTab(id);
1651 if (desiredTab != null &&
1652 desiredTab != mTabControl.getCurrentTab()) {
1662 if (!super.onOptionsItemSelected(item)) {
1665 // Otherwise fall through.
1671 public void closeFind() {
1672 mMenuState = R.id.MAIN_MENU;
1675 @Override public boolean onPrepareOptionsMenu(Menu menu)
1677 // This happens when the user begins to hold down the menu key, so
1678 // allow them to chord to get a shortcut.
1680 // Note: setVisible will decide whether an item is visible; while
1681 // setEnabled() will decide whether an item is enabled, which also means
1682 // whether the matching shortcut key will function.
1683 super.onPrepareOptionsMenu(menu);
1684 switch (mMenuState) {
1686 if (mCurrentMenuState != mMenuState) {
1687 menu.setGroupVisible(R.id.MAIN_MENU, false);
1688 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1689 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1693 if (mCurrentMenuState != mMenuState) {
1694 menu.setGroupVisible(R.id.MAIN_MENU, true);
1695 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1696 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1698 final WebView w = getTopWindow();
1699 boolean canGoBack = false;
1700 boolean canGoForward = false;
1701 boolean isHome = false;
1703 canGoBack = w.canGoBack();
1704 canGoForward = w.canGoForward();
1705 isHome = mSettings.getHomePage().equals(w.getUrl());
1707 final MenuItem back = menu.findItem(R.id.back_menu_id);
1708 back.setEnabled(canGoBack);
1710 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1711 home.setEnabled(!isHome);
1713 menu.findItem(R.id.forward_menu_id)
1714 .setEnabled(canGoForward);
1716 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1717 mTabControl.getTabCount() < TabControl.MAX_TABS);
1719 // decide whether to show the share link option
1720 PackageManager pm = getPackageManager();
1721 Intent send = new Intent(Intent.ACTION_SEND);
1722 send.setType("text/plain");
1723 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1724 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1726 boolean isNavDump = mSettings.isNavDump();
1727 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1728 nav.setVisible(isNavDump);
1729 nav.setEnabled(isNavDump);
1732 mCurrentMenuState = mMenuState;
1737 public void onCreateContextMenu(ContextMenu menu, View v,
1738 ContextMenuInfo menuInfo) {
1739 WebView webview = (WebView) v;
1740 WebView.HitTestResult result = webview.getHitTestResult();
1741 if (result == null) {
1745 int type = result.getType();
1746 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1748 "We should not show context menu when nothing is touched");
1751 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1752 // let TextView handles context menu
1756 // Note, http://b/issue?id=1106666 is requesting that
1757 // an inflated menu can be used again. This is not available
1758 // yet, so inflate each time (yuk!)
1759 MenuInflater inflater = getMenuInflater();
1760 inflater.inflate(R.menu.browsercontext, menu);
1762 // Show the correct menu group
1763 String extra = result.getExtra();
1764 menu.setGroupVisible(R.id.PHONE_MENU,
1765 type == WebView.HitTestResult.PHONE_TYPE);
1766 menu.setGroupVisible(R.id.EMAIL_MENU,
1767 type == WebView.HitTestResult.EMAIL_TYPE);
1768 menu.setGroupVisible(R.id.GEO_MENU,
1769 type == WebView.HitTestResult.GEO_TYPE);
1770 menu.setGroupVisible(R.id.IMAGE_MENU,
1771 type == WebView.HitTestResult.IMAGE_TYPE
1772 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1773 menu.setGroupVisible(R.id.ANCHOR_MENU,
1774 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1775 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1777 // Setup custom handling depending on the type
1779 case WebView.HitTestResult.PHONE_TYPE:
1780 menu.setHeaderTitle(Uri.decode(extra));
1781 menu.findItem(R.id.dial_context_menu_id).setIntent(
1782 new Intent(Intent.ACTION_VIEW, Uri
1783 .parse(WebView.SCHEME_TEL + extra)));
1784 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1785 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1786 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1787 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1789 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1793 case WebView.HitTestResult.EMAIL_TYPE:
1794 menu.setHeaderTitle(extra);
1795 menu.findItem(R.id.email_context_menu_id).setIntent(
1796 new Intent(Intent.ACTION_VIEW, Uri
1797 .parse(WebView.SCHEME_MAILTO + extra)));
1798 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1802 case WebView.HitTestResult.GEO_TYPE:
1803 menu.setHeaderTitle(extra);
1804 menu.findItem(R.id.map_context_menu_id).setIntent(
1805 new Intent(Intent.ACTION_VIEW, Uri
1806 .parse(WebView.SCHEME_GEO
1807 + URLEncoder.encode(extra))));
1808 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1812 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1813 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1814 TextView titleView = (TextView) LayoutInflater.from(this)
1815 .inflate(android.R.layout.browser_link_context_header,
1817 titleView.setText(extra);
1818 menu.setHeaderView(titleView);
1819 // decide whether to show the open link in new tab option
1820 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1821 mTabControl.getTabCount() < TabControl.MAX_TABS);
1822 PackageManager pm = getPackageManager();
1823 Intent send = new Intent(Intent.ACTION_SEND);
1824 send.setType("text/plain");
1825 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1826 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1827 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1830 // otherwise fall through to handle image part
1831 case WebView.HitTestResult.IMAGE_TYPE:
1832 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1833 menu.setHeaderTitle(extra);
1835 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1836 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1837 menu.findItem(R.id.download_context_menu_id).
1838 setOnMenuItemClickListener(new Download(extra));
1842 Log.w(LOGTAG, "We should not get here.");
1847 // Attach the given tab to the content view.
1848 // this should only be called for the current tab.
1849 private void attachTabToContentView(TabControl.Tab t) {
1850 // Attach the container that contains the main WebView and any other UI
1851 // associated with the tab.
1852 t.attachTabToContentView(mContentView);
1854 if (mShouldShowErrorConsole) {
1855 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1856 if (errorConsole.numberOfErrors() == 0) {
1857 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1859 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1862 mErrorConsoleContainer.addView(errorConsole,
1863 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1864 ViewGroup.LayoutParams.WRAP_CONTENT));
1867 setLockIconType(t.getLockIconType());
1868 setPrevLockType(t.getPrevLockIconType());
1870 // this is to match the code in removeTabFromContentView()
1871 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1872 mPageStarted = true;
1875 WebView view = t.getWebView();
1876 view.setEmbeddedTitleBar(mTitleBar);
1877 // Request focus on the top window.
1878 t.getTopWindow().requestFocus();
1881 // Attach a sub window to the main WebView of the given tab.
1882 private void attachSubWindow(TabControl.Tab t) {
1883 t.attachSubWindow(mContentView);
1884 getTopWindow().requestFocus();
1887 // Remove the given tab from the content view.
1888 private void removeTabFromContentView(TabControl.Tab t) {
1889 // Remove the container that contains the main WebView.
1890 t.removeTabFromContentView(mContentView);
1892 if (mTabControl.getCurrentErrorConsole(false) != null) {
1893 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1896 WebView view = t.getWebView();
1898 view.setEmbeddedTitleBar(null);
1901 // unlike attachTabToContentView(), removeTabFromContentView() can be
1902 // called for the non-current tab. Need to add the check.
1903 if (t == mTabControl.getCurrentTab()) {
1904 t.setLockIconType(getLockIconType());
1905 t.setPrevLockIconType(getPrevLockType());
1907 // this is not a perfect solution. But currently there is one
1908 // WebViewClient for all the WebView. if user switches from an
1909 // in-load window to an already loaded window, mPageStarted will not
1910 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1911 // won't do anything and leaves the timer running even Browser is in
1914 mPageStarted = false;
1919 // Remove the sub window if it exists. Also called by TabControl when the
1920 // user clicks the 'X' to dismiss a sub window.
1921 /* package */ void dismissSubWindow(TabControl.Tab t) {
1922 t.removeSubWindow(mContentView);
1923 // Tell the TabControl to dismiss the subwindow. This will destroy
1925 mTabControl.dismissSubWindow(t);
1926 getTopWindow().requestFocus();
1929 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1930 // that accepts url as string.
1931 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1933 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1936 // This method does a ton of stuff. It will attempt to create a new tab
1937 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1938 // url isn't null, it will load the given url.
1939 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
1940 boolean closeOnExit, String appId) {
1941 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1942 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1944 final TabControl.Tab tab = mTabControl.createNewTab(
1945 closeOnExit, appId, urlData.mUrl);
1946 WebView webview = tab.getWebView();
1947 // If the last tab was removed from the active tabs page, currentTab
1949 if (currentTab != null) {
1950 removeTabFromContentView(currentTab);
1952 // We must set the new tab as the current tab to reflect the old
1953 // animation behavior.
1954 mTabControl.setCurrentTab(tab);
1955 attachTabToContentView(tab);
1956 if (!urlData.isEmpty()) {
1957 urlData.loadIn(webview);
1961 // Get rid of the subwindow if it exists
1962 dismissSubWindow(currentTab);
1963 if (!urlData.isEmpty()) {
1964 // Load the given url.
1965 urlData.loadIn(currentTab.getWebView());
1971 private TabControl.Tab openTab(String url) {
1972 if (mSettings.openInBackground()) {
1973 TabControl.Tab t = mTabControl.createNewTab();
1975 WebView view = t.getWebView();
1980 return openTabAndShow(url, false, null);
1984 private class Copy implements OnMenuItemClickListener {
1985 private CharSequence mText;
1987 public boolean onMenuItemClick(MenuItem item) {
1992 public Copy(CharSequence toCopy) {
1997 private class Download implements OnMenuItemClickListener {
1998 private String mText;
2000 public boolean onMenuItemClick(MenuItem item) {
2001 onDownloadStartNoStream(mText, null, null, null, -1);
2005 public Download(String toDownload) {
2010 private void copy(CharSequence text) {
2012 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2014 clip.setClipboardText(text);
2016 } catch (android.os.RemoteException e) {
2017 Log.e(LOGTAG, "Copy failed", e);
2022 * Resets the browser title-view to whatever it must be
2023 * (for example, if we had a loading error)
2024 * When we have a new page, we call resetTitle, when we
2025 * have to reset the titlebar to whatever it used to be
2026 * (for example, if the user chose to stop loading), we
2027 * call resetTitleAndRevertLockIcon.
2029 /* package */ void resetTitleAndRevertLockIcon() {
2031 resetTitleIconAndProgress();
2035 * Reset the title, favicon, and progress.
2037 private void resetTitleIconAndProgress() {
2038 WebView current = mTabControl.getCurrentWebView();
2039 if (current == null) {
2042 resetTitleAndIcon(current);
2043 int progress = current.getProgress();
2044 mWebChromeClient.onProgressChanged(current, progress);
2047 // Reset the title and the icon based on the given item.
2048 private void resetTitleAndIcon(WebView view) {
2049 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2051 setUrlTitle(item.getUrl(), item.getTitle());
2052 setFavicon(item.getFavicon());
2054 setUrlTitle(null, null);
2060 * Sets a title composed of the URL and the title string.
2061 * @param url The URL of the site being loaded.
2062 * @param title The title of the site being loaded.
2064 private void setUrlTitle(String url, String title) {
2068 mTitleBar.setTitleAndUrl(title, url);
2069 if (mFakeTitleBar != null) {
2070 mFakeTitleBar.setTitleAndUrl(title, url);
2075 * @param url The URL to build a title version of the URL from.
2076 * @return The title version of the URL or null if fails.
2077 * The title version of the URL can be either the URL hostname,
2078 * or the hostname with an "https://" prefix (for secure URLs),
2079 * or an empty string if, for example, the URL in question is a
2080 * file:// URL with no hostname.
2082 /* package */ static String buildTitleUrl(String url) {
2083 String titleUrl = null;
2087 // parse the url string
2088 URL urlObj = new URL(url);
2089 if (urlObj != null) {
2092 String protocol = urlObj.getProtocol();
2093 String host = urlObj.getHost();
2095 if (host != null && 0 < host.length()) {
2097 if (protocol != null) {
2098 // if a secure site, add an "https://" prefix!
2099 if (protocol.equalsIgnoreCase("https")) {
2100 titleUrl = protocol + "://" + host;
2105 } catch (MalformedURLException e) {}
2111 // Set the favicon in the title bar.
2112 private void setFavicon(Bitmap icon) {
2113 mTitleBar.setFavicon(icon);
2114 if (mFakeTitleBar != null) {
2115 mFakeTitleBar.setFavicon(icon);
2120 * Saves the current lock-icon state before resetting
2121 * the lock icon. If we have an error, we may need to
2122 * roll back to the previous state.
2124 private void saveLockIcon() {
2125 mPrevLockType = mLockIconType;
2129 * Reverts the lock-icon state to the last saved state,
2130 * for example, if we had an error, and need to cancel
2133 private void revertLockIcon() {
2134 mLockIconType = mPrevLockType;
2137 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2138 " revert lock icon to " + mLockIconType);
2141 updateLockIconToLatest();
2145 * Close the tab, remove its associated title bar, and adjust mTabControl's
2146 * current tab to a valid value.
2148 /* package */ void closeTab(TabControl.Tab t) {
2149 int currentIndex = mTabControl.getCurrentIndex();
2150 int removeIndex = mTabControl.getTabIndex(t);
2151 mTabControl.removeTab(t);
2152 if (currentIndex >= removeIndex && currentIndex != 0) {
2155 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2156 resetTitleIconAndProgress();
2159 private void goBackOnePageOrQuit() {
2160 TabControl.Tab current = mTabControl.getCurrentTab();
2161 if (current == null) {
2163 * Instead of finishing the activity, simply push this to the back
2164 * of the stack and let ActivityManager to choose the foreground
2165 * activity. As BrowserActivity is singleTask, it will be always the
2166 * root of the task. So we can use either true or false for
2169 moveTaskToBack(true);
2172 WebView w = current.getWebView();
2173 if (w.canGoBack()) {
2176 // Check to see if we are closing a window that was created by
2177 // another window. If so, we switch back to that window.
2178 TabControl.Tab parent = current.getParentTab();
2179 if (parent != null) {
2180 switchToTab(mTabControl.getTabIndex(parent));
2181 // Now we close the other tab
2184 if (current.closeOnExit()) {
2185 // force mPageStarted to be false as we are going to either
2186 // finish the activity or remove the tab. This will ensure
2187 // pauseWebView() taking action.
2188 mPageStarted = false;
2189 if (mTabControl.getTabCount() == 1) {
2193 // call pauseWebViewTimers() now, we won't be able to call
2194 // it in onPause() as the WebView won't be valid.
2195 // Temporarily change mActivityInPause to be true as
2196 // pauseWebViewTimers() will do nothing if mActivityInPause
2198 boolean savedState = mActivityInPause;
2200 Log.e(LOGTAG, "BrowserActivity is already paused "
2201 + "while handing goBackOnePageOrQuit.");
2203 mActivityInPause = true;
2204 pauseWebViewTimers();
2205 mActivityInPause = savedState;
2206 removeTabFromContentView(current);
2207 mTabControl.removeTab(current);
2210 * Instead of finishing the activity, simply push this to the back
2211 * of the stack and let ActivityManager to choose the foreground
2212 * activity. As BrowserActivity is singleTask, it will be always the
2213 * root of the task. So we can use either true or false for
2216 moveTaskToBack(true);
2222 public boolean onKeyDown(int keyCode, KeyEvent event) {
2223 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2224 // still down, we don't want to trigger the search. Pretend to consume
2225 // the key and do nothing.
2226 if (mMenuIsDown) return true;
2229 case KeyEvent.KEYCODE_MENU:
2232 case KeyEvent.KEYCODE_SPACE:
2233 // WebView/WebTextView handle the keys in the KeyDown. As
2234 // the Activity's shortcut keys are only handled when WebView
2235 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2236 if (event.isShiftPressed()) {
2237 getTopWindow().pageUp(false);
2239 getTopWindow().pageDown(false);
2242 case KeyEvent.KEYCODE_BACK:
2243 if (event.getRepeatCount() == 0) {
2244 event.startTracking();
2246 } else if (mCustomView == null && mActiveTabsPage == null
2247 && event.isLongPress()) {
2248 bookmarksOrHistoryPicker(true);
2253 return super.onKeyDown(keyCode, event);
2257 public boolean onKeyUp(int keyCode, KeyEvent event) {
2259 case KeyEvent.KEYCODE_MENU:
2260 mMenuIsDown = false;
2262 case KeyEvent.KEYCODE_BACK:
2263 if (event.isTracking() && !event.isCanceled()) {
2264 if (mCustomView != null) {
2265 // if a custom view is showing, hide it
2266 mWebChromeClient.onHideCustomView();
2267 } else if (mActiveTabsPage != null) {
2268 // if tab page is showing, hide it
2269 removeActiveTabPage(true);
2271 WebView subwindow = mTabControl.getCurrentSubWindow();
2272 if (subwindow != null) {
2273 if (subwindow.canGoBack()) {
2276 dismissSubWindow(mTabControl.getCurrentTab());
2279 goBackOnePageOrQuit();
2286 return super.onKeyUp(keyCode, event);
2289 /* package */ void stopLoading() {
2290 mDidStopLoad = true;
2291 resetTitleAndRevertLockIcon();
2292 WebView w = getTopWindow();
2294 mWebViewClient.onPageFinished(w, w.getUrl());
2298 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2302 private void cancelStopToast() {
2303 if (mStopToast != null) {
2304 mStopToast.cancel();
2309 // called by a non-UI thread to post the message
2310 public void postMessage(int what, int arg1, int arg2, Object obj) {
2311 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2314 // public message ids
2315 public final static int LOAD_URL = 1001;
2316 public final static int STOP_LOAD = 1002;
2319 private static final int FOCUS_NODE_HREF = 102;
2320 private static final int CANCEL_CREDS_REQUEST = 103;
2321 private static final int RELEASE_WAKELOCK = 107;
2323 private static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2325 // Private handler for handling javascript and saving passwords
2326 private Handler mHandler = new Handler() {
2328 public void handleMessage(Message msg) {
2330 case FOCUS_NODE_HREF:
2332 String url = (String) msg.getData().get("url");
2333 if (url == null || url.length() == 0) {
2336 HashMap focusNodeMap = (HashMap) msg.obj;
2337 WebView view = (WebView) focusNodeMap.get("webview");
2338 // Only apply the action if the top window did not change.
2339 if (getTopWindow() != view) {
2343 case R.id.open_context_menu_id:
2344 case R.id.view_image_context_menu_id:
2345 loadURL(getTopWindow(), url);
2347 case R.id.open_newtab_context_menu_id:
2348 final TabControl.Tab parent = mTabControl
2350 final TabControl.Tab newTab = openTab(url);
2351 if (newTab != parent) {
2352 parent.addChildTab(newTab);
2355 case R.id.bookmark_context_menu_id:
2356 Intent intent = new Intent(BrowserActivity.this,
2357 AddBookmarkPage.class);
2358 intent.putExtra("url", url);
2359 startActivity(intent);
2361 case R.id.share_link_context_menu_id:
2362 Browser.sendString(BrowserActivity.this, url,
2363 getText(R.string.choosertitle_sharevia).toString());
2365 case R.id.copy_link_context_menu_id:
2368 case R.id.save_link_context_menu_id:
2369 case R.id.download_context_menu_id:
2370 onDownloadStartNoStream(url, null, null, null, -1);
2377 loadURL(getTopWindow(), (String) msg.obj);
2384 case CANCEL_CREDS_REQUEST:
2385 resumeAfterCredentials();
2388 case RELEASE_WAKELOCK:
2389 if (mWakeLock.isHeld()) {
2390 mWakeLock.release();
2394 case UPDATE_BOOKMARK_THUMBNAIL:
2395 WebView view = (WebView) msg.obj;
2397 updateScreenshot(view);
2404 private void updateScreenshot(WebView view) {
2405 // If this is a bookmarked site, add a screenshot to the database.
2406 // FIXME: When should we update? Every time?
2407 // FIXME: Would like to make sure there is actually something to
2408 // draw, but the API for that (WebViewCore.pictureReady()) is not
2409 // currently accessible here.
2411 ContentResolver cr = getContentResolver();
2412 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2413 cr, view.getOriginalUrl(), view.getUrl(), true);
2415 boolean succeed = c.moveToFirst();
2416 ContentValues values = null;
2418 if (values == null) {
2419 final ByteArrayOutputStream os
2420 = new ByteArrayOutputStream();
2421 Bitmap bm = createScreenshot(view);
2426 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2427 values = new ContentValues();
2428 values.put(Browser.BookmarkColumns.THUMBNAIL,
2431 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2432 c.getInt(0)), values, null, null);
2433 succeed = c.moveToNext();
2440 * Values for the size of the thumbnail created when taking a screenshot.
2441 * Lazily initialized. Instead of using these directly, use
2442 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2444 private static int THUMBNAIL_WIDTH = 0;
2445 private static int THUMBNAIL_HEIGHT = 0;
2448 * Return the desired width for thumbnail screenshots, which are stored in
2449 * the database, and used on the bookmarks screen.
2450 * @param context Context for finding out the density of the screen.
2451 * @return int desired width for thumbnail screenshot.
2453 /* package */ static int getDesiredThumbnailWidth(Context context) {
2454 if (THUMBNAIL_WIDTH == 0) {
2455 float density = context.getResources().getDisplayMetrics().density;
2456 THUMBNAIL_WIDTH = (int) (90 * density);
2457 THUMBNAIL_HEIGHT = (int) (80 * density);
2459 return THUMBNAIL_WIDTH;
2463 * Return the desired height for thumbnail screenshots, which are stored in
2464 * the database, and used on the bookmarks screen.
2465 * @param context Context for finding out the density of the screen.
2466 * @return int desired height for thumbnail screenshot.
2468 /* package */ static int getDesiredThumbnailHeight(Context context) {
2469 // To ensure that they are both initialized.
2470 getDesiredThumbnailWidth(context);
2471 return THUMBNAIL_HEIGHT;
2474 private Bitmap createScreenshot(WebView view) {
2475 Picture thumbnail = view.capturePicture();
2476 if (thumbnail == null) {
2479 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2480 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2481 Canvas canvas = new Canvas(bm);
2482 // May need to tweak these values to determine what is the
2483 // best scale factor
2484 int thumbnailWidth = thumbnail.getWidth();
2485 if (thumbnailWidth > 0) {
2486 float scaleFactor = (float) getDesiredThumbnailWidth(this) /
2487 (float)thumbnailWidth;
2488 canvas.scale(scaleFactor, scaleFactor);
2490 thumbnail.draw(canvas);
2494 // -------------------------------------------------------------------------
2495 // WebViewClient implementation.
2496 //-------------------------------------------------------------------------
2498 // Use in overrideUrlLoading
2499 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2500 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2501 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2502 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2504 /* package */ WebViewClient getWebViewClient() {
2505 return mWebViewClient;
2508 private void updateIcon(WebView view, Bitmap icon) {
2510 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2511 view.getOriginalUrl(), view.getUrl(), icon);
2516 private void updateIcon(String url, Bitmap icon) {
2518 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2524 private final WebViewClient mWebViewClient = new WebViewClient() {
2526 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2528 setUrlTitle(url, null);
2530 // We've started to load a new page. If there was a pending message
2531 // to save a screenshot then we will now take the new page and
2532 // save an incorrect screenshot. Therefore, remove any pending
2533 // thumbnail messages from the queue.
2534 mHandler.removeMessages(UPDATE_BOOKMARK_THUMBNAIL);
2536 // If we start a touch icon load and then load a new page, we don't
2537 // want to cancel the current touch icon loader. But, we do want to
2538 // create a new one when the touch icon url is known.
2539 if (mTouchIconLoader != null) {
2540 mTouchIconLoader.mActivity = null;
2541 mTouchIconLoader = null;
2544 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2545 if (errorConsole != null) {
2546 errorConsole.clearErrorMessages();
2547 if (mShouldShowErrorConsole) {
2548 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2552 // Call updateIcon instead of setFavicon so the bookmark
2553 // database can be updated.
2554 updateIcon(url, favicon);
2556 if (mSettings.isTracing()) {
2559 WebAddress uri = new WebAddress(url);
2561 } catch (android.net.ParseException ex) {
2564 host = host.replace('.', '_');
2567 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2570 // Performance probe
2572 mStart = SystemClock.uptimeMillis();
2573 mProcessStart = Process.getElapsedCpuTime();
2574 long[] sysCpu = new long[7];
2575 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2577 mUserStart = sysCpu[0] + sysCpu[1];
2578 mSystemStart = sysCpu[2];
2579 mIdleStart = sysCpu[3];
2580 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2582 mUiStart = SystemClock.currentThreadTimeMillis();
2585 if (!mPageStarted) {
2586 mPageStarted = true;
2587 // if onResume() has been called, resumeWebViewTimers() does
2589 resumeWebViewTimers();
2592 // reset sync timer to avoid sync starts during loading a page
2593 CookieSyncManager.getInstance().resetSync();
2596 mDidStopLoad = false;
2598 updateInLoadMenuItems();
2599 if (!mIsNetworkUp) {
2600 createAndShowNetworkDialog();
2602 view.setNetworkAvailable(false);
2608 public void onPageFinished(WebView view, String url) {
2609 // Reset the title and icon in case we stopped a provisional
2611 resetTitleAndIcon(view);
2613 if (!mDidStopLoad) {
2614 // Only update the bookmark screenshot if the user did not
2615 // cancel the load early.
2616 Message updateScreenshot = Message.obtain(mHandler, UPDATE_BOOKMARK_THUMBNAIL, view);
2617 mHandler.sendMessageDelayed(updateScreenshot, 500);
2620 // Update the lock icon image only once we are done loading
2621 updateLockIconToLatest();
2623 // Performance probe
2625 long[] sysCpu = new long[7];
2626 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2628 String uiInfo = "UI thread used "
2629 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2632 Log.d(LOGTAG, uiInfo);
2634 //The string that gets written to the log
2635 String performanceString = "It took total "
2636 + (SystemClock.uptimeMillis() - mStart)
2637 + " ms clock time to load the page."
2638 + "\nbrowser process used "
2639 + (Process.getElapsedCpuTime() - mProcessStart)
2640 + " ms, user processes used "
2641 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2642 + " ms, kernel used "
2643 + (sysCpu[2] - mSystemStart) * 10
2644 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2645 + " ms and irq took "
2646 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2647 * 10 + " ms, " + uiInfo;
2649 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2652 // strip the url to maintain consistency
2653 String newUrl = new String(url);
2654 if (newUrl.startsWith("http://www.")) {
2655 newUrl = newUrl.substring(11);
2656 } else if (newUrl.startsWith("http://")) {
2657 newUrl = newUrl.substring(7);
2658 } else if (newUrl.startsWith("https://www.")) {
2659 newUrl = newUrl.substring(12);
2660 } else if (newUrl.startsWith("https://")) {
2661 newUrl = newUrl.substring(8);
2664 Log.d(LOGTAG, newUrl + " loaded");
2667 if (sWhiteList.contains(newUrl)) {
2668 // The string that gets pushed to the statistcs
2670 performanceString = performanceString
2674 + android.os.SystemProperties
2675 .get("gsm.sim.operator.alpha");
2676 if (mWebView != null
2677 && mWebView.getContext() != null
2678 && mWebView.getContext().getSystemService(
2679 Context.CONNECTIVITY_SERVICE) != null) {
2680 ConnectivityManager cManager =
2681 (ConnectivityManager) mWebView
2682 .getContext().getSystemService(
2683 Context.CONNECTIVITY_SERVICE);
2684 NetworkInfo nInfo = cManager
2685 .getActiveNetworkInfo();
2686 if (nInfo != null) {
2687 performanceString = performanceString
2688 + "\nNetwork Type: "
2689 + nInfo.getType().toString();
2692 Checkin.logEvent(mResolver,
2693 Checkin.Events.Tag.WEBPAGE_LOAD,
2695 Log.w(LOGTAG, "pushed to the statistics service");
2704 Debug.stopMethodTracing();
2708 mPageStarted = false;
2709 // pauseWebViewTimers() will do nothing and return false if
2710 // onPause() is not called yet.
2711 if (pauseWebViewTimers()) {
2712 if (mWakeLock.isHeld()) {
2713 mHandler.removeMessages(RELEASE_WAKELOCK);
2714 mWakeLock.release();
2720 // return true if want to hijack the url to let another app to handle it
2722 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2723 if (url.startsWith(SCHEME_WTAI)) {
2724 // wtai://wp/mc;number
2725 // number=string(phone-number)
2726 if (url.startsWith(SCHEME_WTAI_MC)) {
2727 Intent intent = new Intent(Intent.ACTION_VIEW,
2728 Uri.parse(WebView.SCHEME_TEL +
2729 url.substring(SCHEME_WTAI_MC.length())));
2730 startActivity(intent);
2733 // wtai://wp/sd;dtmf
2734 // dtmf=string(dialstring)
2735 if (url.startsWith(SCHEME_WTAI_SD)) {
2737 // only send when there is active voice connection
2740 // wtai://wp/ap;number;name
2741 // number=string(phone-number)
2743 if (url.startsWith(SCHEME_WTAI_AP)) {
2749 // The "about:" schemes are internal to the browser; don't
2750 // want these to be dispatched to other apps.
2751 if (url.startsWith("about:")) {
2757 // perform generic parsing of the URI to turn it into an Intent.
2759 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2760 } catch (URISyntaxException ex) {
2761 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2765 // check whether the intent can be resolved. If not, we will see
2766 // whether we can download it from the Market.
2767 if (getPackageManager().resolveActivity(intent, 0) == null) {
2768 String packagename = intent.getPackage();
2769 if (packagename != null) {
2770 intent = new Intent(Intent.ACTION_VIEW, Uri
2771 .parse("market://search?q=pname:" + packagename));
2772 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2773 startActivity(intent);
2780 // sanitize the Intent, ensuring web pages can not bypass browser
2781 // security (only access to BROWSABLE activities).
2782 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2783 intent.setComponent(null);
2785 if (startActivityIfNeeded(intent, -1)) {
2788 } catch (ActivityNotFoundException ex) {
2789 // ignore the error. If no application can handle the URL,
2790 // eg about:blank, assume the browser can handle it.
2803 * Updates the lock icon. This method is called when we discover another
2804 * resource to be loaded for this page (for example, javascript). While
2805 * we update the icon type, we do not update the lock icon itself until
2806 * we are done loading, it is slightly more secure this way.
2809 public void onLoadResource(WebView view, String url) {
2810 if (url != null && url.length() > 0) {
2811 // It is only if the page claims to be secure
2812 // that we may have to update the lock:
2813 if (mLockIconType == LOCK_ICON_SECURE) {
2814 // If NOT a 'safe' url, change the lock to mixed content!
2815 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2816 mLockIconType = LOCK_ICON_MIXED;
2818 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2819 " updated lock icon to " + mLockIconType + " due to " + url);
2827 * Show the dialog, asking the user if they would like to continue after
2828 * an excessive number of HTTP redirects.
2831 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2832 final Message continueMsg) {
2833 new AlertDialog.Builder(BrowserActivity.this)
2834 .setTitle(R.string.browserFrameRedirect)
2835 .setMessage(R.string.browserFrame307Post)
2836 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2837 public void onClick(DialogInterface dialog, int which) {
2838 continueMsg.sendToTarget();
2840 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2841 public void onClick(DialogInterface dialog, int which) {
2842 cancelMsg.sendToTarget();
2844 .setOnCancelListener(new OnCancelListener() {
2845 public void onCancel(DialogInterface dialog) {
2846 cancelMsg.sendToTarget();
2851 // Container class for the next error dialog that needs to be
2854 public final int mTitle;
2855 public final String mDescription;
2856 public final int mError;
2857 ErrorDialog(int title, String desc, int error) {
2859 mDescription = desc;
2864 private void processNextError() {
2865 if (mQueuedErrors == null) {
2868 // The first one is currently displayed so just remove it.
2869 mQueuedErrors.removeFirst();
2870 if (mQueuedErrors.size() == 0) {
2871 mQueuedErrors = null;
2874 showError(mQueuedErrors.getFirst());
2877 private DialogInterface.OnDismissListener mDialogListener =
2878 new DialogInterface.OnDismissListener() {
2879 public void onDismiss(DialogInterface d) {
2883 private LinkedList<ErrorDialog> mQueuedErrors;
2885 private void queueError(int err, String desc) {
2886 if (mQueuedErrors == null) {
2887 mQueuedErrors = new LinkedList<ErrorDialog>();
2889 for (ErrorDialog d : mQueuedErrors) {
2890 if (d.mError == err) {
2891 // Already saw a similar error, ignore the new one.
2895 ErrorDialog errDialog = new ErrorDialog(
2896 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
2897 R.string.browserFrameFileErrorLabel :
2898 R.string.browserFrameNetworkErrorLabel,
2900 mQueuedErrors.addLast(errDialog);
2902 // Show the dialog now if the queue was empty.
2903 if (mQueuedErrors.size() == 1) {
2904 showError(errDialog);
2908 private void showError(ErrorDialog errDialog) {
2909 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2910 .setTitle(errDialog.mTitle)
2911 .setMessage(errDialog.mDescription)
2912 .setPositiveButton(R.string.ok, null)
2914 d.setOnDismissListener(mDialogListener);
2919 * Show a dialog informing the user of the network error reported by
2923 public void onReceivedError(WebView view, int errorCode,
2924 String description, String failingUrl) {
2925 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2926 errorCode != WebViewClient.ERROR_CONNECT &&
2927 errorCode != WebViewClient.ERROR_BAD_URL &&
2928 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2929 errorCode != WebViewClient.ERROR_FILE) {
2930 queueError(errorCode, description);
2932 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2933 + " " + description);
2935 // We need to reset the title after an error.
2936 resetTitleAndRevertLockIcon();
2940 * Check with the user if it is ok to resend POST data as the page they
2941 * are trying to navigate to is the result of a POST.
2944 public void onFormResubmission(WebView view, final Message dontResend,
2945 final Message resend) {
2946 new AlertDialog.Builder(BrowserActivity.this)
2947 .setTitle(R.string.browserFrameFormResubmitLabel)
2948 .setMessage(R.string.browserFrameFormResubmitMessage)
2949 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2950 public void onClick(DialogInterface dialog, int which) {
2951 resend.sendToTarget();
2953 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2954 public void onClick(DialogInterface dialog, int which) {
2955 dontResend.sendToTarget();
2957 .setOnCancelListener(new OnCancelListener() {
2958 public void onCancel(DialogInterface dialog) {
2959 dontResend.sendToTarget();
2965 * Insert the url into the visited history database.
2966 * @param url The url to be inserted.
2967 * @param isReload True if this url is being reloaded.
2968 * FIXME: Not sure what to do when reloading the page.
2971 public void doUpdateVisitedHistory(WebView view, String url,
2973 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2976 // remove "client" before updating it to the history so that it wont
2977 // show up in the auto-complete list.
2978 int index = url.indexOf("client=ms-");
2979 if (index > 0 && url.contains(".google.")) {
2980 int end = url.indexOf('&', index);
2982 url = url.substring(0, index)
2983 .concat(url.substring(end + 1));
2985 // the url.charAt(index-1) should be either '?' or '&'
2986 url = url.substring(0, index-1);
2989 Browser.updateVisitedHistory(mResolver, url, true);
2990 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2994 * Displays SSL error(s) dialog to the user.
2997 public void onReceivedSslError(
2998 final WebView view, final SslErrorHandler handler, final SslError error) {
3000 if (mSettings.showSecurityWarnings()) {
3001 final LayoutInflater factory =
3002 LayoutInflater.from(BrowserActivity.this);
3003 final View warningsView =
3004 factory.inflate(R.layout.ssl_warnings, null);
3005 final LinearLayout placeholder =
3006 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3008 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3009 LinearLayout ll = (LinearLayout)factory
3010 .inflate(R.layout.ssl_warning, null);
3011 ((TextView)ll.findViewById(R.id.warning))
3012 .setText(R.string.ssl_untrusted);
3013 placeholder.addView(ll);
3016 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3017 LinearLayout ll = (LinearLayout)factory
3018 .inflate(R.layout.ssl_warning, null);
3019 ((TextView)ll.findViewById(R.id.warning))
3020 .setText(R.string.ssl_mismatch);
3021 placeholder.addView(ll);
3024 if (error.hasError(SslError.SSL_EXPIRED)) {
3025 LinearLayout ll = (LinearLayout)factory
3026 .inflate(R.layout.ssl_warning, null);
3027 ((TextView)ll.findViewById(R.id.warning))
3028 .setText(R.string.ssl_expired);
3029 placeholder.addView(ll);
3032 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3033 LinearLayout ll = (LinearLayout)factory
3034 .inflate(R.layout.ssl_warning, null);
3035 ((TextView)ll.findViewById(R.id.warning))
3036 .setText(R.string.ssl_not_yet_valid);
3037 placeholder.addView(ll);
3040 new AlertDialog.Builder(BrowserActivity.this)
3041 .setTitle(R.string.security_warning)
3042 .setIcon(android.R.drawable.ic_dialog_alert)
3043 .setView(warningsView)
3044 .setPositiveButton(R.string.ssl_continue,
3045 new DialogInterface.OnClickListener() {
3046 public void onClick(DialogInterface dialog, int whichButton) {
3050 .setNeutralButton(R.string.view_certificate,
3051 new DialogInterface.OnClickListener() {
3052 public void onClick(DialogInterface dialog, int whichButton) {
3053 showSSLCertificateOnError(view, handler, error);
3056 .setNegativeButton(R.string.cancel,
3057 new DialogInterface.OnClickListener() {
3058 public void onClick(DialogInterface dialog, int whichButton) {
3060 BrowserActivity.this.resetTitleAndRevertLockIcon();
3063 .setOnCancelListener(
3064 new DialogInterface.OnCancelListener() {
3065 public void onCancel(DialogInterface dialog) {
3067 BrowserActivity.this.resetTitleAndRevertLockIcon();
3077 * Handles an HTTP authentication request.
3079 * @param handler The authentication handler
3080 * @param host The host
3081 * @param realm The realm
3084 public void onReceivedHttpAuthRequest(WebView view,
3085 final HttpAuthHandler handler, final String host, final String realm) {
3086 String username = null;
3087 String password = null;
3089 boolean reuseHttpAuthUsernamePassword =
3090 handler.useHttpAuthUsernamePassword();
3092 if (reuseHttpAuthUsernamePassword &&
3093 (mTabControl.getCurrentWebView() != null)) {
3094 String[] credentials =
3095 mTabControl.getCurrentWebView()
3096 .getHttpAuthUsernamePassword(host, realm);
3097 if (credentials != null && credentials.length == 2) {
3098 username = credentials[0];
3099 password = credentials[1];
3103 if (username != null && password != null) {
3104 handler.proceed(username, password);
3106 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3111 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3113 // only check shortcut key when MENU is held
3114 return getWindow().isShortcutKey(event.getKeyCode(), event);
3121 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3122 if (view != mTabControl.getCurrentTopWebView()) {
3125 if (event.isDown()) {
3126 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3128 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3133 //--------------------------------------------------------------------------
3134 // WebChromeClient implementation
3135 //--------------------------------------------------------------------------
3137 /* package */ WebChromeClient getWebChromeClient() {
3138 return mWebChromeClient;
3141 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3142 // Helper method to create a new tab or sub window.
3143 private void createWindow(final boolean dialog, final Message msg) {
3145 mTabControl.createSubWindow();
3146 final TabControl.Tab t = mTabControl.getCurrentTab();
3148 WebView.WebViewTransport transport =
3149 (WebView.WebViewTransport) msg.obj;
3150 transport.setWebView(t.getSubWebView());
3153 final TabControl.Tab parent = mTabControl.getCurrentTab();
3154 final TabControl.Tab newTab
3155 = openTabAndShow(EMPTY_URL_DATA, false, null);
3156 if (newTab != parent) {
3157 parent.addChildTab(newTab);
3159 WebView.WebViewTransport transport =
3160 (WebView.WebViewTransport) msg.obj;
3161 transport.setWebView(mTabControl.getCurrentWebView());
3167 public boolean onCreateWindow(WebView view, final boolean dialog,
3168 final boolean userGesture, final Message resultMsg) {
3169 // Short-circuit if we can't create any more tabs or sub windows.
3170 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3171 new AlertDialog.Builder(BrowserActivity.this)
3172 .setTitle(R.string.too_many_subwindows_dialog_title)
3173 .setIcon(android.R.drawable.ic_dialog_alert)
3174 .setMessage(R.string.too_many_subwindows_dialog_message)
3175 .setPositiveButton(R.string.ok, null)
3178 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3179 new AlertDialog.Builder(BrowserActivity.this)
3180 .setTitle(R.string.too_many_windows_dialog_title)
3181 .setIcon(android.R.drawable.ic_dialog_alert)
3182 .setMessage(R.string.too_many_windows_dialog_message)
3183 .setPositiveButton(R.string.ok, null)
3188 // Short-circuit if this was a user gesture.
3190 createWindow(dialog, resultMsg);
3194 // Allow the popup and create the appropriate window.
3195 final AlertDialog.OnClickListener allowListener =
3196 new AlertDialog.OnClickListener() {
3197 public void onClick(DialogInterface d,
3199 createWindow(dialog, resultMsg);
3203 // Block the popup by returning a null WebView.
3204 final AlertDialog.OnClickListener blockListener =
3205 new AlertDialog.OnClickListener() {
3206 public void onClick(DialogInterface d, int which) {
3207 resultMsg.sendToTarget();
3211 // Build a confirmation dialog to display to the user.
3212 final AlertDialog d =
3213 new AlertDialog.Builder(BrowserActivity.this)
3214 .setTitle(R.string.attention)
3215 .setIcon(android.R.drawable.ic_dialog_alert)
3216 .setMessage(R.string.popup_window_attempt)
3217 .setPositiveButton(R.string.allow, allowListener)
3218 .setNegativeButton(R.string.block, blockListener)
3219 .setCancelable(false)
3222 // Show the confirmation dialog.
3228 public void onCloseWindow(WebView window) {
3229 final TabControl.Tab current = mTabControl.getCurrentTab();
3230 final TabControl.Tab parent = current.getParentTab();
3231 if (parent != null) {
3232 // JavaScript can only close popup window.
3233 switchToTab(mTabControl.getTabIndex(parent));
3234 // Now we need to close the window
3240 public void onProgressChanged(WebView view, int newProgress) {
3241 mTitleBar.setProgress(newProgress);
3242 if (mFakeTitleBar != null) {
3243 mFakeTitleBar.setProgress(newProgress);
3246 if (newProgress == 100) {
3247 // onProgressChanged() may continue to be called after the main
3248 // frame has finished loading, as any remaining sub frames
3249 // continue to load. We'll only get called once though with
3250 // newProgress as 100 when everything is loaded.
3251 // (onPageFinished is called once when the main frame completes
3252 // loading regardless of the state of any sub frames so calls
3253 // to onProgressChanges may continue after onPageFinished has
3256 // sync cookies and cache promptly here.
3257 CookieSyncManager.getInstance().sync();
3260 updateInLoadMenuItems();
3261 // If the options menu is open, leave the title bar
3262 if (!mOptionsMenuOpen || !mIconView) {
3266 } else if (!mInLoad) {
3267 // onPageFinished may have already been called but a subframe
3268 // is still loading and updating the progress. Reset mInLoad
3269 // and update the menu items.
3271 updateInLoadMenuItems();
3272 if (!mOptionsMenuOpen || mIconView) {
3273 // This page has begun to load, so show the title bar
3280 public void onReceivedTitle(WebView view, String title) {
3281 String url = view.getUrl();
3283 // here, if url is null, we want to reset the title
3284 setUrlTitle(url, title);
3287 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3290 // See if we can find the current url in our history database and
3291 // add the new title to it.
3292 if (url.startsWith("http://www.")) {
3293 url = url.substring(11);
3294 } else if (url.startsWith("http://")) {
3295 url = url.substring(4);
3299 String [] selArgs = new String[] { url };
3301 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3302 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3303 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3304 Browser.HISTORY_PROJECTION, where, selArgs, null);
3305 if (c.moveToFirst()) {
3306 // Current implementation of database only has one entry per
3308 ContentValues map = new ContentValues();
3309 map.put(Browser.BookmarkColumns.TITLE, title);
3310 mResolver.update(Browser.BOOKMARKS_URI, map,
3311 "_id = " + c.getInt(0), null);
3314 } catch (IllegalStateException e) {
3315 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3316 } catch (SQLiteException ex) {
3317 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3322 public void onReceivedIcon(WebView view, Bitmap icon) {
3323 updateIcon(view, icon);
3327 public void onReceivedTouchIconUrl(WebView view, String url,
3328 boolean precomposed) {
3329 final ContentResolver cr = getContentResolver();
3331 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
3332 view.getOriginalUrl(), view.getUrl(), true);
3334 if (c.getCount() > 0) {
3335 // Let precomposed icons take precedence over non-composed
3337 if (precomposed && mTouchIconLoader != null) {
3338 mTouchIconLoader.cancel(false);
3339 mTouchIconLoader = null;
3341 // Have only one async task at a time.
3342 if (mTouchIconLoader == null) {
3343 mTouchIconLoader = new DownloadTouchIcon(
3344 BrowserActivity.this, cr, c, view);
3345 mTouchIconLoader.execute(url);
3354 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
3355 if (mCustomView != null)
3358 // Add the custom view to its container.
3359 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3361 mCustomViewCallback = callback;
3362 // Save the menu state and set it to empty while the custom
3364 mOldMenuState = mMenuState;
3365 mMenuState = EMPTY_MENU;
3366 // Hide the content view.
3367 mContentView.setVisibility(View.GONE);
3368 // Finally show the custom view container.
3369 mCustomViewContainer.setVisibility(View.VISIBLE);
3370 mCustomViewContainer.bringToFront();
3374 public void onHideCustomView() {
3375 if (mCustomView == null)
3378 // Hide the custom view.
3379 mCustomView.setVisibility(View.GONE);
3380 // Remove the custom view from its container.
3381 mCustomViewContainer.removeView(mCustomView);
3383 // Reset the old menu state.
3384 mMenuState = mOldMenuState;
3385 mOldMenuState = EMPTY_MENU;
3386 mCustomViewContainer.setVisibility(View.GONE);
3387 mCustomViewCallback.onCustomViewHidden();
3388 // Show the content view.
3389 mContentView.setVisibility(View.VISIBLE);
3393 * The origin has exceeded its database quota.
3394 * @param url the URL that exceeded the quota
3395 * @param databaseIdentifier the identifier of the database on
3396 * which the transaction that caused the quota overflow was run
3397 * @param currentQuota the current quota for the origin.
3398 * @param estimatedSize the estimated size of the database.
3399 * @param totalUsedQuota is the sum of all origins' quota.
3400 * @param quotaUpdater The callback to run when a decision to allow or
3401 * deny quota has been made. Don't forget to call this!
3404 public void onExceededDatabaseQuota(String url,
3405 String databaseIdentifier, long currentQuota, long estimatedSize,
3406 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3407 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3408 url, databaseIdentifier, currentQuota, estimatedSize,
3409 totalUsedQuota, quotaUpdater);
3413 * The Application Cache has exceeded its max size.
3414 * @param spaceNeeded is the amount of disk space that would be needed
3415 * in order for the last appcache operation to succeed.
3416 * @param totalUsedQuota is the sum of all origins' quota.
3417 * @param quotaUpdater A callback to inform the WebCore thread that a new
3418 * app cache size is available. This callback must always be executed at
3419 * some point to ensure that the sleeping WebCore thread is woken up.
3422 public void onReachedMaxAppCacheSize(long spaceNeeded,
3423 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3424 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3425 spaceNeeded, totalUsedQuota, quotaUpdater);
3429 * Instructs the browser to show a prompt to ask the user to set the
3430 * Geolocation permission state for the specified origin.
3431 * @param origin The origin for which Geolocation permissions are
3433 * @param callback The callback to call once the user has set the
3434 * Geolocation permission state.
3437 public void onGeolocationPermissionsShowPrompt(String origin,
3438 GeolocationPermissions.Callback callback) {
3439 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3444 * Instructs the browser to hide the Geolocation permissions prompt.
3447 public void onGeolocationPermissionsHidePrompt() {
3448 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3451 /* Adds a JavaScript error message to the system log and if the JS
3452 * console is enabled in the about:debug options, to that console
3454 * @param message The error message to report.
3455 * @param lineNumber The line number of the error.
3456 * @param sourceID The name of the source file that caused the error.
3459 public void onConsoleMessage(String message, int lineNumber, String sourceID) {
3460 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3461 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3462 if (mShouldShowErrorConsole &&
3463 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3464 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3466 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
3470 * Ask the browser for an icon to represent a <video> element.
3471 * This icon will be used if the Web page did not specify a poster attribute.
3473 * @return Bitmap The icon or null if no such icon is available.
3474 * @hide pending API Council approval
3477 public Bitmap getDefaultVideoPoster() {
3478 if (mDefaultVideoPoster == null) {
3479 mDefaultVideoPoster = BitmapFactory.decodeResource(
3480 getResources(), R.drawable.default_video_poster);
3482 return mDefaultVideoPoster;
3486 * Ask the host application for a custom progress view to show while
3487 * a <video> is loading.
3489 * @return View The progress view.
3490 * @hide pending API Council approval
3493 public View getVideoLoadingProgressView() {
3494 if (mVideoProgressView == null) {
3495 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3496 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3498 return mVideoProgressView;
3502 * Deliver a list of already-visited URLs
3503 * @hide pending API Council approval
3506 public void getVisitedHistory(final ValueCallback<String[]> callback) {
3507 AsyncTask<Void, Void, String[]> task = new AsyncTask<Void, Void, String[]>() {
3508 public String[] doInBackground(Void... unused) {
3509 return Browser.getVisitedHistory(getContentResolver());
3512 public void onPostExecute(String[] result) {
3513 callback.onReceiveValue(result);
3522 * Notify the host application a download should be done, or that
3523 * the data should be streamed if a streaming viewer is available.
3524 * @param url The full url to the content that should be downloaded
3525 * @param contentDisposition Content-disposition http header, if
3527 * @param mimetype The mimetype of the content reported by the server
3528 * @param contentLength The file size reported by the server
3530 public void onDownloadStart(String url, String userAgent,
3531 String contentDisposition, String mimetype, long contentLength) {
3532 // if we're dealing wih A/V content that's not explicitly marked
3533 // for download, check if it's streamable.
3534 if (contentDisposition == null
3535 || !contentDisposition.regionMatches(
3536 true, 0, "attachment", 0, 10)) {
3537 // query the package manager to see if there's a registered handler
3539 Intent intent = new Intent(Intent.ACTION_VIEW);
3540 intent.setDataAndType(Uri.parse(url), mimetype);
3541 ResolveInfo info = getPackageManager().resolveActivity(intent,
3542 PackageManager.MATCH_DEFAULT_ONLY);
3544 ComponentName myName = getComponentName();
3545 // If we resolved to ourselves, we don't want to attempt to
3546 // load the url only to try and download it again.
3547 if (!myName.getPackageName().equals(
3548 info.activityInfo.packageName)
3549 || !myName.getClassName().equals(
3550 info.activityInfo.name)) {
3551 // someone (other than us) knows how to handle this mime
3552 // type with this scheme, don't download.
3554 startActivity(intent);
3556 } catch (ActivityNotFoundException ex) {
3558 Log.d(LOGTAG, "activity not found for " + mimetype
3559 + " over " + Uri.parse(url).getScheme(),
3562 // Best behavior is to fall back to a download in this
3568 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3572 * Notify the host application a download should be done, even if there
3573 * is a streaming viewer available for thise type.
3574 * @param url The full url to the content that should be downloaded
3575 * @param contentDisposition Content-disposition http header, if
3577 * @param mimetype The mimetype of the content reported by the server
3578 * @param contentLength The file size reported by the server
3580 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3581 String contentDisposition, String mimetype, long contentLength) {
3583 String filename = URLUtil.guessFileName(url,
3584 contentDisposition, mimetype);
3586 // Check to see if we have an SDCard
3587 String status = Environment.getExternalStorageState();
3588 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3592 // Check to see if the SDCard is busy, same as the music app
3593 if (status.equals(Environment.MEDIA_SHARED)) {
3594 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3595 title = R.string.download_sdcard_busy_dlg_title;
3597 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3598 title = R.string.download_no_sdcard_dlg_title;
3601 new AlertDialog.Builder(this)
3603 .setIcon(android.R.drawable.ic_dialog_alert)
3605 .setPositiveButton(R.string.ok, null)
3610 // java.net.URI is a lot stricter than KURL so we have to undo
3611 // KURL's percent-encoding and redo the encoding using java.net.URI.
3614 // Undo the percent-encoding that KURL may have done.
3615 String newUrl = new String(URLUtil.decode(url.getBytes()));
3616 // Parse the url into pieces
3617 WebAddress w = new WebAddress(newUrl);
3619 String query = null;
3620 String path = w.mPath;
3621 // Break the path into path, query, and fragment
3622 if (path.length() > 0) {
3623 // Strip the fragment
3624 int idx = path.lastIndexOf('#');
3626 frag = path.substring(idx + 1);
3627 path = path.substring(0, idx);
3629 idx = path.lastIndexOf('?');
3631 query = path.substring(idx + 1);
3632 path = path.substring(0, idx);
3635 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3637 } catch (Exception e) {
3638 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3642 // XXX: Have to use the old url since the cookies were stored using the
3643 // old percent-encoded url.
3644 String cookies = CookieManager.getInstance().getCookie(url);
3646 ContentValues values = new ContentValues();
3647 values.put(Downloads.COLUMN_URI, uri.toString());
3648 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3649 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3650 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
3652 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
3653 BrowserDownloadPage.class.getCanonicalName());
3654 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3655 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3656 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3657 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
3658 if (contentLength > 0) {
3659 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
3661 if (mimetype == null) {
3662 // We must have long pressed on a link or image to download it. We
3663 // are not sure of the mimetype in this case, so do a head request
3664 new FetchUrlMimeType(this).execute(values);
3666 final Uri contentUri =
3667 getContentResolver().insert(Downloads.CONTENT_URI, values);
3668 viewDownloads(contentUri);
3674 * Resets the lock icon. This method is called when we start a new load and
3675 * know the url to be loaded.
3677 private void resetLockIcon(String url) {
3678 // Save the lock-icon state (we revert to it if the load gets cancelled)
3681 mLockIconType = LOCK_ICON_UNSECURE;
3682 if (URLUtil.isHttpsUrl(url)) {
3683 mLockIconType = LOCK_ICON_SECURE;
3685 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3686 " reset lock icon to " + mLockIconType);
3690 updateLockIconImage(LOCK_ICON_UNSECURE);
3693 /* package */ void setLockIconType(int type) {
3694 mLockIconType = type;
3697 /* package */ int getLockIconType() {
3698 return mLockIconType;
3701 /* package */ void setPrevLockType(int type) {
3702 mPrevLockType = type;
3705 /* package */ int getPrevLockType() {
3706 return mPrevLockType;
3710 * Update the lock icon to correspond to our latest state.
3712 /* package */ void updateLockIconToLatest() {
3713 updateLockIconImage(mLockIconType);
3717 * Updates the lock-icon image in the title-bar.
3719 private void updateLockIconImage(int lockIconType) {
3721 if (lockIconType == LOCK_ICON_SECURE) {
3723 } else if (lockIconType == LOCK_ICON_MIXED) {
3726 mTitleBar.setLock(d);
3727 if (mFakeTitleBar != null) {
3728 mFakeTitleBar.setLock(d);
3733 * Displays a page-info dialog.
3734 * @param tab The tab to show info about
3735 * @param fromShowSSLCertificateOnError The flag that indicates whether
3736 * this dialog was opened from the SSL-certificate-on-error dialog or
3737 * not. This is important, since we need to know whether to return to
3738 * the parent dialog or simply dismiss.
3740 private void showPageInfo(final TabControl.Tab tab,
3741 final boolean fromShowSSLCertificateOnError) {
3742 final LayoutInflater factory = LayoutInflater
3745 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3747 final WebView view = tab.getWebView();
3750 String title = null;
3754 title = tab.getTitle();
3755 } else if (view == mTabControl.getCurrentWebView()) {
3756 // Use the cached title and url if this is the current WebView
3760 url = view.getUrl();
3761 title = view.getTitle();
3767 if (title == null) {
3771 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3772 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3774 mPageInfoView = tab;
3775 mPageInfoFromShowSSLCertificateOnError = Boolean.valueOf(fromShowSSLCertificateOnError);
3777 AlertDialog.Builder alertDialogBuilder =
3778 new AlertDialog.Builder(this)
3779 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3780 .setView(pageInfoView)
3783 new DialogInterface.OnClickListener() {
3784 public void onClick(DialogInterface dialog,
3786 mPageInfoDialog = null;
3787 mPageInfoView = null;
3788 mPageInfoFromShowSSLCertificateOnError = null;
3790 // if we came here from the SSL error dialog
3791 if (fromShowSSLCertificateOnError) {
3792 // go back to the SSL error dialog
3793 showSSLCertificateOnError(
3794 mSSLCertificateOnErrorView,
3795 mSSLCertificateOnErrorHandler,
3796 mSSLCertificateOnErrorError);
3800 .setOnCancelListener(
3801 new DialogInterface.OnCancelListener() {
3802 public void onCancel(DialogInterface dialog) {
3803 mPageInfoDialog = null;
3804 mPageInfoView = null;
3805 mPageInfoFromShowSSLCertificateOnError = null;
3807 // if we came here from the SSL error dialog
3808 if (fromShowSSLCertificateOnError) {
3809 // go back to the SSL error dialog
3810 showSSLCertificateOnError(
3811 mSSLCertificateOnErrorView,
3812 mSSLCertificateOnErrorHandler,
3813 mSSLCertificateOnErrorError);
3818 // if we have a main top-level page SSL certificate set or a certificate
3820 if (fromShowSSLCertificateOnError ||
3821 (view != null && view.getCertificate() != null)) {
3822 // add a 'View Certificate' button
3823 alertDialogBuilder.setNeutralButton(
3824 R.string.view_certificate,
3825 new DialogInterface.OnClickListener() {
3826 public void onClick(DialogInterface dialog,
3828 mPageInfoDialog = null;
3829 mPageInfoView = null;
3830 mPageInfoFromShowSSLCertificateOnError = null;
3832 // if we came here from the SSL error dialog
3833 if (fromShowSSLCertificateOnError) {
3834 // go back to the SSL error dialog
3835 showSSLCertificateOnError(
3836 mSSLCertificateOnErrorView,
3837 mSSLCertificateOnErrorHandler,
3838 mSSLCertificateOnErrorError);
3840 // otherwise, display the top-most certificate from
3842 if (view.getCertificate() != null) {
3843 showSSLCertificate(tab);
3850 mPageInfoDialog = alertDialogBuilder.show();
3854 * Displays the main top-level page SSL certificate dialog
3855 * (accessible from the Page-Info dialog).
3856 * @param tab The tab to show certificate for.
3858 private void showSSLCertificate(final TabControl.Tab tab) {
3859 final View certificateView =
3860 inflateCertificateView(tab.getWebView().getCertificate());
3861 if (certificateView == null) {
3865 LayoutInflater factory = LayoutInflater.from(this);
3867 final LinearLayout placeholder =
3868 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3870 LinearLayout ll = (LinearLayout) factory.inflate(
3871 R.layout.ssl_success, placeholder);
3872 ((TextView)ll.findViewById(R.id.success))
3873 .setText(R.string.ssl_certificate_is_valid);
3875 mSSLCertificateView = tab;
3876 mSSLCertificateDialog =
3877 new AlertDialog.Builder(this)
3878 .setTitle(R.string.ssl_certificate).setIcon(
3879 R.drawable.ic_dialog_browser_certificate_secure)
3880 .setView(certificateView)
3881 .setPositiveButton(R.string.ok,
3882 new DialogInterface.OnClickListener() {
3883 public void onClick(DialogInterface dialog,
3885 mSSLCertificateDialog = null;
3886 mSSLCertificateView = null;
3888 showPageInfo(tab, false);
3891 .setOnCancelListener(
3892 new DialogInterface.OnCancelListener() {
3893 public void onCancel(DialogInterface dialog) {
3894 mSSLCertificateDialog = null;
3895 mSSLCertificateView = null;
3897 showPageInfo(tab, false);
3904 * Displays the SSL error certificate dialog.
3905 * @param view The target web-view.
3906 * @param handler The SSL error handler responsible for cancelling the
3907 * connection that resulted in an SSL error or proceeding per user request.
3908 * @param error The SSL error object.
3910 private void showSSLCertificateOnError(
3911 final WebView view, final SslErrorHandler handler, final SslError error) {
3913 final View certificateView =
3914 inflateCertificateView(error.getCertificate());
3915 if (certificateView == null) {
3919 LayoutInflater factory = LayoutInflater.from(this);
3921 final LinearLayout placeholder =
3922 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3924 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3925 LinearLayout ll = (LinearLayout)factory
3926 .inflate(R.layout.ssl_warning, placeholder);
3927 ((TextView)ll.findViewById(R.id.warning))
3928 .setText(R.string.ssl_untrusted);
3931 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3932 LinearLayout ll = (LinearLayout)factory
3933 .inflate(R.layout.ssl_warning, placeholder);
3934 ((TextView)ll.findViewById(R.id.warning))
3935 .setText(R.string.ssl_mismatch);
3938 if (error.hasError(SslError.SSL_EXPIRED)) {
3939 LinearLayout ll = (LinearLayout)factory
3940 .inflate(R.layout.ssl_warning, placeholder);
3941 ((TextView)ll.findViewById(R.id.warning))
3942 .setText(R.string.ssl_expired);
3945 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3946 LinearLayout ll = (LinearLayout)factory
3947 .inflate(R.layout.ssl_warning, placeholder);
3948 ((TextView)ll.findViewById(R.id.warning))
3949 .setText(R.string.ssl_not_yet_valid);
3952 mSSLCertificateOnErrorHandler = handler;
3953 mSSLCertificateOnErrorView = view;
3954 mSSLCertificateOnErrorError = error;
3955 mSSLCertificateOnErrorDialog =
3956 new AlertDialog.Builder(this)
3957 .setTitle(R.string.ssl_certificate).setIcon(
3958 R.drawable.ic_dialog_browser_certificate_partially_secure)
3959 .setView(certificateView)
3960 .setPositiveButton(R.string.ok,
3961 new DialogInterface.OnClickListener() {
3962 public void onClick(DialogInterface dialog,
3964 mSSLCertificateOnErrorDialog = null;
3965 mSSLCertificateOnErrorView = null;
3966 mSSLCertificateOnErrorHandler = null;
3967 mSSLCertificateOnErrorError = null;
3969 mWebViewClient.onReceivedSslError(
3970 view, handler, error);
3973 .setNeutralButton(R.string.page_info_view,
3974 new DialogInterface.OnClickListener() {
3975 public void onClick(DialogInterface dialog,
3977 mSSLCertificateOnErrorDialog = null;
3979 // do not clear the dialog state: we will
3980 // need to show the dialog again once the
3981 // user is done exploring the page-info details
3983 showPageInfo(mTabControl.getTabFromView(view),
3987 .setOnCancelListener(
3988 new DialogInterface.OnCancelListener() {
3989 public void onCancel(DialogInterface dialog) {
3990 mSSLCertificateOnErrorDialog = null;
3991 mSSLCertificateOnErrorView = null;
3992 mSSLCertificateOnErrorHandler = null;
3993 mSSLCertificateOnErrorError = null;
3995 mWebViewClient.onReceivedSslError(
3996 view, handler, error);
4003 * Inflates the SSL certificate view (helper method).
4004 * @param certificate The SSL certificate.
4005 * @return The resultant certificate view with issued-to, issued-by,
4006 * issued-on, expires-on, and possibly other fields set.
4007 * If the input certificate is null, returns null.
4009 private View inflateCertificateView(SslCertificate certificate) {
4010 if (certificate == null) {
4014 LayoutInflater factory = LayoutInflater.from(this);
4016 View certificateView = factory.inflate(
4017 R.layout.ssl_certificate, null);
4020 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4021 if (issuedTo != null) {
4022 ((TextView) certificateView.findViewById(R.id.to_common))
4023 .setText(issuedTo.getCName());
4024 ((TextView) certificateView.findViewById(R.id.to_org))
4025 .setText(issuedTo.getOName());
4026 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4027 .setText(issuedTo.getUName());
4031 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4032 if (issuedBy != null) {
4033 ((TextView) certificateView.findViewById(R.id.by_common))
4034 .setText(issuedBy.getCName());
4035 ((TextView) certificateView.findViewById(R.id.by_org))
4036 .setText(issuedBy.getOName());
4037 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4038 .setText(issuedBy.getUName());
4042 String issuedOn = reformatCertificateDate(
4043 certificate.getValidNotBefore());
4044 ((TextView) certificateView.findViewById(R.id.issued_on))
4048 String expiresOn = reformatCertificateDate(
4049 certificate.getValidNotAfter());
4050 ((TextView) certificateView.findViewById(R.id.expires_on))
4051 .setText(expiresOn);
4053 return certificateView;
4057 * Re-formats the certificate date (Date.toString()) string to
4058 * a properly localized date string.
4059 * @return Properly localized version of the certificate date string and
4060 * the original certificate date string if fails to localize.
4061 * If the original string is null, returns an empty string "".
4063 private String reformatCertificateDate(String certificateDate) {
4064 String reformattedDate = null;
4066 if (certificateDate != null) {
4069 date = java.text.DateFormat.getInstance().parse(certificateDate);
4070 } catch (ParseException e) {
4076 DateFormat.getDateFormat(this).format(date);
4080 return reformattedDate != null ? reformattedDate :
4081 (certificateDate != null ? certificateDate : "");
4085 * Displays an http-authentication dialog.
4087 private void showHttpAuthentication(final HttpAuthHandler handler,
4088 final String host, final String realm, final String title,
4089 final String name, final String password, int focusId) {
4090 LayoutInflater factory = LayoutInflater.from(this);
4091 final View v = factory
4092 .inflate(R.layout.http_authentication, null);
4094 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4096 if (password != null) {
4097 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4100 String titleText = title;
4101 if (titleText == null) {
4102 titleText = getText(R.string.sign_in_to).toString().replace(
4103 "%s1", host).replace("%s2", realm);
4106 mHttpAuthHandler = handler;
4107 AlertDialog dialog = new AlertDialog.Builder(this)
4108 .setTitle(titleText)
4109 .setIcon(android.R.drawable.ic_dialog_alert)
4111 .setPositiveButton(R.string.action,
4112 new DialogInterface.OnClickListener() {
4113 public void onClick(DialogInterface dialog,
4115 String nm = ((EditText) v
4116 .findViewById(R.id.username_edit))
4117 .getText().toString();
4118 String pw = ((EditText) v
4119 .findViewById(R.id.password_edit))
4120 .getText().toString();
4121 BrowserActivity.this.setHttpAuthUsernamePassword
4122 (host, realm, nm, pw);
4123 handler.proceed(nm, pw);
4124 mHttpAuthenticationDialog = null;
4125 mHttpAuthHandler = null;
4127 .setNegativeButton(R.string.cancel,
4128 new DialogInterface.OnClickListener() {
4129 public void onClick(DialogInterface dialog,
4132 BrowserActivity.this.resetTitleAndRevertLockIcon();
4133 mHttpAuthenticationDialog = null;
4134 mHttpAuthHandler = null;
4136 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4137 public void onCancel(DialogInterface dialog) {
4139 BrowserActivity.this.resetTitleAndRevertLockIcon();
4140 mHttpAuthenticationDialog = null;
4141 mHttpAuthHandler = null;
4144 // Make the IME appear when the dialog is displayed if applicable.
4145 dialog.getWindow().setSoftInputMode(
4146 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4149 dialog.findViewById(focusId).requestFocus();
4151 v.findViewById(R.id.username_edit).requestFocus();
4153 mHttpAuthenticationDialog = dialog;
4156 public int getProgress() {
4157 WebView w = mTabControl.getCurrentWebView();
4159 return w.getProgress();
4166 * Set HTTP authentication password.
4168 * @param host The host for the password
4169 * @param realm The realm for the password
4170 * @param username The username for the password. If it is null, it means
4171 * password can't be saved.
4172 * @param password The password
4174 public void setHttpAuthUsernamePassword(String host, String realm,
4177 WebView w = mTabControl.getCurrentWebView();
4179 w.setHttpAuthUsernamePassword(host, realm, username, password);
4184 * connectivity manager says net has come or gone... inform the user
4185 * @param up true if net has come up, false if net has gone down
4187 public void onNetworkToggle(boolean up) {
4188 if (up == mIsNetworkUp) {
4191 mIsNetworkUp = true;
4192 if (mAlertDialog != null) {
4193 mAlertDialog.cancel();
4194 mAlertDialog = null;
4197 mIsNetworkUp = false;
4199 createAndShowNetworkDialog();
4202 WebView w = mTabControl.getCurrentWebView();
4204 w.setNetworkAvailable(up);
4208 // This method shows the network dialog alerting the user that the net is
4209 // down. It will only show the dialog if mAlertDialog is null.
4210 private void createAndShowNetworkDialog() {
4211 if (mAlertDialog == null) {
4212 mAlertDialog = new AlertDialog.Builder(this)
4213 .setTitle(R.string.loadSuspendedTitle)
4214 .setMessage(R.string.loadSuspended)
4215 .setPositiveButton(R.string.ok, null)
4221 protected void onActivityResult(int requestCode, int resultCode,
4223 switch (requestCode) {
4225 if (resultCode == RESULT_OK && intent != null) {
4226 String data = intent.getAction();
4227 Bundle extras = intent.getExtras();
4228 if (extras != null && extras.getBoolean("new_window", false)) {
4231 final TabControl.Tab currentTab =
4232 mTabControl.getCurrentTab();
4233 dismissSubWindow(currentTab);
4234 if (data != null && data.length() != 0) {
4235 getTopWindow().loadUrl(data);
4243 getTopWindow().requestFocus();
4247 * This method is called as a result of the user selecting the options
4248 * menu to see the download window, or when a download changes state. It
4249 * shows the download window ontop of the current window.
4251 /* package */ void viewDownloads(Uri downloadRecord) {
4252 Intent intent = new Intent(this,
4253 BrowserDownloadPage.class);
4254 intent.setData(downloadRecord);
4255 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4261 * @param startWithHistory If true, open starting on the history tab.
4262 * Otherwise, start with the bookmarks tab.
4264 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
4265 WebView current = mTabControl.getCurrentWebView();
4266 if (current == null) {
4269 Intent intent = new Intent(this,
4270 CombinedBookmarkHistoryActivity.class);
4271 String title = current.getTitle();
4272 String url = current.getUrl();
4273 Bitmap thumbnail = createScreenshot(current);
4275 // Just in case the user opens bookmarks before a page finishes loading
4276 // so the current history item, and therefore the page, is null.
4278 url = mLastEnteredUrl;
4281 url = mSettings.getHomePage();
4284 // In case the web page has not yet received its associated title.
4285 if (title == null) {
4288 intent.putExtra("title", title);
4289 intent.putExtra("url", url);
4290 intent.putExtra("thumbnail", thumbnail);
4291 // Disable opening in a new window if we have maxed out the windows
4292 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4293 >= TabControl.MAX_TABS);
4294 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
4295 if (startWithHistory) {
4296 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4297 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4299 startActivityForResult(intent, COMBO_PAGE);
4302 // Called when loading from context menu or LOAD_URL message
4303 private void loadURL(WebView view, String url) {
4304 // In case the user enters nothing.
4305 if (url != null && url.length() != 0 && view != null) {
4306 url = smartUrlFilter(url);
4307 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4313 private String smartUrlFilter(Uri inUri) {
4314 if (inUri != null) {
4315 return smartUrlFilter(inUri.toString());
4323 int getWindowCount(){
4324 if(mTabControl != null){
4325 return mTabControl.getTabCount();
4330 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4331 "(?i)" + // switch on case insensitive matching
4332 "(" + // begin group for schema
4333 "(?:http|https|file):\\/\\/" +
4334 "|(?:inline|data|about|content|javascript):" +
4339 * Attempts to determine whether user input is a URL or search
4340 * terms. Anything with a space is passed to search.
4342 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4343 * "Http://" converts to "http://"
4345 * @return Original or modified URL
4348 String smartUrlFilter(String url) {
4350 String inUrl = url.trim();
4351 boolean hasSpace = inUrl.indexOf(' ') != -1;
4353 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4354 if (matcher.matches()) {
4355 // force scheme to lowercase
4356 String scheme = matcher.group(1);
4357 String lcScheme = scheme.toLowerCase();
4358 if (!lcScheme.equals(scheme)) {
4359 inUrl = lcScheme + matcher.group(2);
4362 inUrl = inUrl.replace(" ", "%20");
4367 // FIXME: Is this the correct place to add to searches?
4368 // what if someone else calls this function?
4369 int shortcut = parseUrlShortcut(inUrl);
4370 if (shortcut != SHORTCUT_INVALID) {
4371 Browser.addSearchUrl(mResolver, inUrl);
4372 String query = inUrl.substring(2);
4374 case SHORTCUT_GOOGLE_SEARCH:
4375 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
4376 case SHORTCUT_WIKIPEDIA_SEARCH:
4377 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4378 case SHORTCUT_DICTIONARY_SEARCH:
4379 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4380 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
4381 // FIXME: we need location in this case
4382 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
4386 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4387 return URLUtil.guessUrl(inUrl);
4391 Browser.addSearchUrl(mResolver, inUrl);
4392 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
4395 /* package */ void setShouldShowErrorConsole(boolean flag) {
4396 if (flag == mShouldShowErrorConsole) {
4401 mShouldShowErrorConsole = flag;
4403 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4406 // Setting the show state of the console will cause it's the layout to be inflated.
4407 if (errorConsole.numberOfErrors() > 0) {
4408 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4410 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4413 // Now we can add it to the main view.
4414 mErrorConsoleContainer.addView(errorConsole,
4415 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4416 ViewGroup.LayoutParams.WRAP_CONTENT));
4418 mErrorConsoleContainer.removeView(errorConsole);
4423 final static int LOCK_ICON_UNSECURE = 0;
4424 final static int LOCK_ICON_SECURE = 1;
4425 final static int LOCK_ICON_MIXED = 2;
4427 private int mLockIconType = LOCK_ICON_UNSECURE;
4428 private int mPrevLockType = LOCK_ICON_UNSECURE;
4430 private BrowserSettings mSettings;
4431 private TabControl mTabControl;
4432 private ContentResolver mResolver;
4433 private FrameLayout mContentView;
4434 private View mCustomView;
4435 private FrameLayout mCustomViewContainer;
4436 private WebChromeClient.CustomViewCallback mCustomViewCallback;
4438 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4439 // view, we should rewrite this.
4440 private int mCurrentMenuState = 0;
4441 private int mMenuState = R.id.MAIN_MENU;
4442 private int mOldMenuState = EMPTY_MENU;
4443 private static final int EMPTY_MENU = -1;
4446 private FindDialog mFindDialog;
4447 // Used to prevent chording to result in firing two shortcuts immediately
4448 // one after another. Fixes bug 1211714.
4451 private boolean mInLoad;
4452 private boolean mIsNetworkUp;
4453 private boolean mDidStopLoad;
4455 private boolean mPageStarted;
4456 private boolean mActivityInPause = true;
4458 private boolean mMenuIsDown;
4460 private static boolean mInTrace;
4462 // Performance probe
4463 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4464 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4465 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4466 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4467 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4468 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4469 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4470 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4471 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4474 private long mStart;
4475 private long mProcessStart;
4476 private long mUserStart;
4477 private long mSystemStart;
4478 private long mIdleStart;
4479 private long mIrqStart;
4481 private long mUiStart;
4483 private Drawable mMixLockIcon;
4484 private Drawable mSecLockIcon;
4486 /* hold a ref so we can auto-cancel if necessary */
4487 private AlertDialog mAlertDialog;
4489 // Wait for credentials before loading google.com
4490 private ProgressDialog mCredsDlg;
4492 // The up-to-date URL and title (these can be different from those stored
4493 // in WebView, since it takes some time for the information in WebView to
4495 private String mUrl;
4496 private String mTitle;
4498 // As PageInfo has different style for landscape / portrait, we have
4499 // to re-open it when configuration changed
4500 private AlertDialog mPageInfoDialog;
4501 private TabControl.Tab mPageInfoView;
4502 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4503 // dialog, we should not just dismiss it, but should get back to the
4504 // SSL-certificate-on-error dialog. This flag is used to store this state
4505 private Boolean mPageInfoFromShowSSLCertificateOnError;
4507 // as SSLCertificateOnError has different style for landscape / portrait,
4508 // we have to re-open it when configuration changed
4509 private AlertDialog mSSLCertificateOnErrorDialog;
4510 private WebView mSSLCertificateOnErrorView;
4511 private SslErrorHandler mSSLCertificateOnErrorHandler;
4512 private SslError mSSLCertificateOnErrorError;
4514 // as SSLCertificate has different style for landscape / portrait, we
4515 // have to re-open it when configuration changed
4516 private AlertDialog mSSLCertificateDialog;
4517 private TabControl.Tab mSSLCertificateView;
4519 // as HttpAuthentication has different style for landscape / portrait, we
4520 // have to re-open it when configuration changed
4521 private AlertDialog mHttpAuthenticationDialog;
4522 private HttpAuthHandler mHttpAuthHandler;
4524 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4525 new FrameLayout.LayoutParams(
4526 ViewGroup.LayoutParams.FILL_PARENT,
4527 ViewGroup.LayoutParams.FILL_PARENT);
4528 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4529 new FrameLayout.LayoutParams(
4530 ViewGroup.LayoutParams.FILL_PARENT,
4531 ViewGroup.LayoutParams.FILL_PARENT,
4534 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4536 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4537 // Dictionary search
4538 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4539 // Google Mobile Local search
4540 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4542 final static String QUERY_PLACE_HOLDER = "%s";
4544 // "source" parameter for Google search through search key
4545 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4546 // "source" parameter for Google search through goto menu
4547 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4548 // "source" parameter for Google search through simplily type
4549 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4550 // "source" parameter for Google search suggested by the browser
4551 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4552 // "source" parameter for Google search from unknown source
4553 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4555 private final static String LOGTAG = "browser";
4557 private String mLastEnteredUrl;
4559 private PowerManager.WakeLock mWakeLock;
4560 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4562 private Toast mStopToast;
4564 private TitleBar mTitleBar;
4566 private LinearLayout mErrorConsoleContainer = null;
4567 private boolean mShouldShowErrorConsole = false;
4569 // As the ids are dynamically created, we can't guarantee that they will
4570 // be in sequence, so this static array maps ids to a window number.
4571 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4572 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4573 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4574 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4576 // monitor platform changes
4577 private IntentFilter mNetworkStateChangedFilter;
4578 private BroadcastReceiver mNetworkStateIntentReceiver;
4580 private BroadcastReceiver mPackageInstallationReceiver;
4582 // AsyncTask for downloading touch icons
4583 /* package */ DownloadTouchIcon mTouchIconLoader;
4585 // activity requestCode
4586 final static int COMBO_PAGE = 1;
4587 final static int DOWNLOAD_PAGE = 2;
4588 final static int PREFERENCES_PAGE = 3;
4590 // the default <video> poster
4591 private Bitmap mDefaultVideoPoster;
4592 // the video progress view
4593 private View mVideoProgressView;
4596 * A UrlData class to abstract how the content will be set to WebView.
4597 * This base class uses loadUrl to show the content.
4599 private static class UrlData {
4603 UrlData(String url) {
4607 void setPostData(byte[] postData) {
4608 mPostData = postData;
4612 return mUrl == null || mUrl.length() == 0;
4615 public void loadIn(WebView webView) {
4616 if (mPostData != null) {
4617 webView.postUrl(mUrl, mPostData);
4619 webView.loadUrl(mUrl);
4625 * A subclass of UrlData class that can display inlined content using
4626 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4628 private static class InlinedUrlData extends UrlData {
4629 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4632 mMimeType = mimeType;
4633 mEncoding = encoding;
4640 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4644 public void loadIn(WebView webView) {
4645 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4649 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);