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.Log;
88 import android.view.ContextMenu;
89 import android.view.Gravity;
90 import android.view.KeyEvent;
91 import android.view.LayoutInflater;
92 import android.view.Menu;
93 import android.view.MenuInflater;
94 import android.view.MenuItem;
95 import android.view.View;
96 import android.view.ViewGroup;
97 import android.view.Window;
98 import android.view.WindowManager;
99 import android.view.ContextMenu.ContextMenuInfo;
100 import android.view.MenuItem.OnMenuItemClickListener;
101 import android.view.animation.AlphaAnimation;
102 import android.view.animation.Animation;
103 import android.view.animation.AnimationSet;
104 import android.view.animation.DecelerateInterpolator;
105 import android.view.animation.ScaleAnimation;
106 import android.view.animation.TranslateAnimation;
107 import android.webkit.CookieManager;
108 import android.webkit.CookieSyncManager;
109 import android.webkit.DownloadListener;
110 import android.webkit.GeolocationPermissions;
111 import android.webkit.HttpAuthHandler;
112 import android.webkit.PluginManager;
113 import android.webkit.SslErrorHandler;
114 import android.webkit.URLUtil;
115 import android.webkit.WebChromeClient;
116 import android.webkit.WebChromeClient.CustomViewCallback;
117 import android.webkit.WebHistoryItem;
118 import android.webkit.WebIconDatabase;
119 import android.webkit.WebStorage;
120 import android.webkit.WebView;
121 import android.webkit.WebViewClient;
122 import android.widget.EditText;
123 import android.widget.FrameLayout;
124 import android.widget.LinearLayout;
125 import android.widget.TextView;
126 import android.widget.Toast;
128 import java.io.BufferedOutputStream;
129 import java.io.ByteArrayOutputStream;
131 import java.io.FileInputStream;
132 import java.io.FileOutputStream;
133 import java.io.IOException;
134 import java.io.InputStream;
135 import java.net.MalformedURLException;
137 import java.net.URISyntaxException;
139 import java.net.URLEncoder;
140 import java.text.ParseException;
141 import java.util.Date;
142 import java.util.Enumeration;
143 import java.util.HashMap;
144 import java.util.LinkedList;
145 import java.util.Vector;
146 import java.util.regex.Matcher;
147 import java.util.regex.Pattern;
148 import java.util.zip.ZipEntry;
149 import java.util.zip.ZipFile;
151 public class BrowserActivity extends Activity
152 implements View.OnCreateContextMenuListener,
155 /* Define some aliases to make these debugging flags easier to refer to.
156 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
158 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
159 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
160 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
162 private IGoogleLoginService mGls = null;
163 private ServiceConnection mGlsConnection = null;
165 private SensorManager mSensorManager = null;
167 // These are single-character shortcuts for searching popular sources.
168 private static final int SHORTCUT_INVALID = 0;
169 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
170 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
171 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
172 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
174 /* Whitelisted webpages
175 private static HashSet<String> sWhiteList;
178 sWhiteList = new HashSet<String>();
179 sWhiteList.add("cnn.com/");
180 sWhiteList.add("espn.go.com/");
181 sWhiteList.add("nytimes.com/");
182 sWhiteList.add("engadget.com/");
183 sWhiteList.add("yahoo.com/");
184 sWhiteList.add("msn.com/");
185 sWhiteList.add("amazon.com/");
186 sWhiteList.add("consumerist.com/");
187 sWhiteList.add("google.com/m/news");
191 private void setupHomePage() {
192 final Runnable getAccount = new Runnable() {
195 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
196 // get the default home page
197 String homepage = mSettings.getHomePage();
200 if (mGls == null) return;
202 if (!homepage.startsWith("http://www.google.")) return;
203 if (homepage.indexOf('?') == -1) return;
205 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
206 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
210 // hostedUser == googleUser
211 // The device has only a google account
213 // hostedUser != googleUser
214 // The device has a hosted account and a google account
216 // hostedUser != null, googleUser == null
217 // The device has only a hosted account (so far)
219 // developers might have no accounts at all
220 if (hostedUser == null) return;
222 if (googleUser == null || !hostedUser.equals(googleUser)) {
223 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
224 homepage = homepage.replace("?", "/a/" + domain + "?");
226 } catch (RemoteException ignore) {
227 // Login service died; carry on
228 } catch (RuntimeException ignore) {
229 // Login service died; carry on
235 private void finish(final String homepage) {
236 mHandler.post(new Runnable() {
238 mSettings.setHomePage(BrowserActivity.this, homepage);
239 resumeAfterCredentials();
241 // as this is running in a separate thread,
242 // BrowserActivity's onDestroy() may have been called,
243 // which also calls unbindService().
244 if (mGlsConnection != null) {
245 // we no longer need to keep GLS open
246 unbindService(mGlsConnection);
247 mGlsConnection = null;
252 final boolean[] done = { false };
254 // Open a connection to the Google Login Service. The first
255 // time the connection is established, set up the homepage depending on
256 // the account in a background thread.
257 mGlsConnection = new ServiceConnection() {
258 public void onServiceConnected(ComponentName className, IBinder service) {
259 mGls = IGoogleLoginService.Stub.asInterface(service);
260 if (done[0] == false) {
262 Thread account = new Thread(getAccount);
263 account.setName("GLSAccount");
267 public void onServiceDisconnected(ComponentName className) {
272 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
273 mGlsConnection, Context.BIND_AUTO_CREATE);
276 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
278 public Void doInBackground(File... files) {
280 for (File f : files) {
282 Log.e(LOGTAG, f.getPath() + " was not deleted");
291 * This layout holds everything you see below the status bar, including the
292 * error console, the custom view container, and the webviews.
294 private FrameLayout mBrowserFrameLayout;
296 @Override public void onCreate(Bundle icicle) {
298 Log.v(LOGTAG, this + " onStart");
300 super.onCreate(icicle);
301 // test the browser in OpenGL
302 // requestWindowFeature(Window.FEATURE_OPENGL);
304 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
306 mResolver = getContentResolver();
309 // start MASF proxy service
311 //Intent proxyServiceIntent = new Intent();
312 //proxyServiceIntent.setComponent
313 // (new ComponentName(
314 // "com.android.masfproxyservice",
315 // "com.android.masfproxyservice.MasfProxyService"));
316 //startService(proxyServiceIntent, null);
318 mSecLockIcon = Resources.getSystem().getDrawable(
319 android.R.drawable.ic_secure);
320 mMixLockIcon = Resources.getSystem().getDrawable(
321 android.R.drawable.ic_partial_secure);
323 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
324 .findViewById(com.android.internal.R.id.content);
325 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
326 .inflate(R.layout.custom_screen, null);
327 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
329 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
330 .findViewById(R.id.error_console);
331 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
332 .findViewById(R.id.fullscreen_custom_content);
333 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
334 mTitleBar = new TitleBar(this);
336 // Create the tab control and our initial tab
337 mTabControl = new TabControl(this);
339 // Open the icon database and retain all the bookmark urls for favicons
340 retainIconsOnStartup();
342 // Keep a settings instance handy.
343 mSettings = BrowserSettings.getInstance();
344 mSettings.setTabControl(mTabControl);
345 mSettings.loadFromDb(this);
347 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
348 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
350 /* enables registration for changes in network status from
352 mNetworkStateChangedFilter = new IntentFilter();
353 mNetworkStateChangedFilter.addAction(
354 ConnectivityManager.CONNECTIVITY_ACTION);
355 mNetworkStateIntentReceiver = new BroadcastReceiver() {
357 public void onReceive(Context context, Intent intent) {
358 if (intent.getAction().equals(
359 ConnectivityManager.CONNECTIVITY_ACTION)) {
361 (NetworkInfo) intent.getParcelableExtra(
362 ConnectivityManager.EXTRA_NETWORK_INFO);
364 (info != null) ? info.isConnected() : false);
369 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
370 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
371 filter.addDataScheme("package");
372 mPackageInstallationReceiver = new BroadcastReceiver() {
374 public void onReceive(Context context, Intent intent) {
375 final String action = intent.getAction();
376 final String packageName = intent.getData()
377 .getSchemeSpecificPart();
378 final boolean replacing = intent.getBooleanExtra(
379 Intent.EXTRA_REPLACING, false);
380 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
381 // if it is replacing, refreshPlugins() when adding
384 PackageManager pm = BrowserActivity.this.getPackageManager();
385 PackageInfo pkgInfo = null;
387 pkgInfo = pm.getPackageInfo(packageName,
388 PackageManager.GET_PERMISSIONS);
389 } catch (PackageManager.NameNotFoundException e) {
392 if (pkgInfo != null) {
393 String permissions[] = pkgInfo.requestedPermissions;
394 if (permissions == null) {
397 boolean permissionOk = false;
398 for (String permit : permissions) {
399 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
405 PluginManager.getInstance(BrowserActivity.this)
407 Intent.ACTION_PACKAGE_ADDED
413 registerReceiver(mPackageInstallationReceiver, filter);
415 // If this was a web search request, pass it on to the default web search provider.
416 if (handleWebSearchIntent(getIntent())) {
417 moveTaskToBack(true);
421 if (!mTabControl.restoreState(icicle)) {
422 // clear up the thumbnail directory if we can't restore the state as
423 // none of the files in the directory are referenced any more.
424 new ClearThumbnails().execute(
425 mTabControl.getThumbnailDir().listFiles());
426 // there is no quit on Android. But if we can't restore the state,
427 // we can treat it as a new Browser, remove the old session cookies.
428 CookieManager.getInstance().removeSessionCookie();
429 final Intent intent = getIntent();
430 final Bundle extra = intent.getExtras();
431 // Create an initial tab.
432 // If the intent is ACTION_VIEW and data is not null, the Browser is
433 // invoked to view the content by another application. In this case,
434 // the tab will be close when exit.
435 UrlData urlData = getUrlDataFromIntent(intent);
437 final TabControl.Tab t = mTabControl.createNewTab(
438 Intent.ACTION_VIEW.equals(intent.getAction()) &&
439 intent.getData() != null,
440 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
441 mTabControl.setCurrentTab(t);
442 attachTabToContentView(t);
443 WebView webView = t.getWebView();
445 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
446 if (scale > 0 && scale <= 1000) {
447 webView.setInitialScale(scale);
450 // If we are not restoring from an icicle, then there is a high
451 // likely hood this is the first run. So, check to see if the
452 // homepage needs to be configured and copy any plugins from our
453 // asset directory to the data partition.
454 if ((extra == null || !extra.getBoolean("testing"))
455 && !mSettings.isLoginInitialized()) {
459 if (urlData.isEmpty()) {
460 if (mSettings.isLoginInitialized()) {
461 webView.loadUrl(mSettings.getHomePage());
463 waitForCredentials();
467 urlData.setPostData(extra
468 .getByteArray(Browser.EXTRA_POST_DATA));
470 urlData.loadIn(webView);
473 // TabControl.restoreState() will create a new tab even if
474 // restoring the state fails.
475 attachTabToContentView(mTabControl.getCurrentTab());
478 // Read JavaScript flags if it exists.
479 String jsFlags = mSettings.getJsFlags();
480 if (jsFlags.trim().length() != 0) {
481 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
486 protected void onNewIntent(Intent intent) {
487 TabControl.Tab current = mTabControl.getCurrentTab();
488 // When a tab is closed on exit, the current tab index is set to -1.
489 // Reset before proceed as Browser requires the current tab to be set.
490 if (current == null) {
491 // Try to reset the tab in case the index was incorrect.
492 current = mTabControl.getTab(0);
493 if (current == null) {
494 // No tabs at all so just ignore this intent.
497 mTabControl.setCurrentTab(current);
498 attachTabToContentView(current);
499 resetTitleAndIcon(current.getWebView());
501 final String action = intent.getAction();
502 final int flags = intent.getFlags();
503 if (Intent.ACTION_MAIN.equals(action) ||
504 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
505 // just resume the browser
508 if (Intent.ACTION_VIEW.equals(action)
509 || Intent.ACTION_SEARCH.equals(action)
510 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
511 || Intent.ACTION_WEB_SEARCH.equals(action)) {
512 // If this was a search request (e.g. search query directly typed into the address bar),
513 // pass it on to the default web search provider.
514 if (handleWebSearchIntent(intent)) {
518 UrlData urlData = getUrlDataFromIntent(intent);
519 if (urlData.isEmpty()) {
520 urlData = new UrlData(mSettings.getHomePage());
522 urlData.setPostData(intent
523 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
525 final String appId = intent
526 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
527 if (Intent.ACTION_VIEW.equals(action)
528 && !getPackageName().equals(appId)
529 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
530 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
531 if (appTab != null) {
532 Log.i(LOGTAG, "Reusing tab for " + appId);
533 // Dismiss the subwindow if applicable.
534 dismissSubWindow(appTab);
535 // Since we might kill the WebView, remove it from the
536 // content view first.
537 removeTabFromContentView(appTab);
538 // Recreate the main WebView after destroying the old one.
539 // If the WebView has the same original url and is on that
540 // page, it can be reused.
542 mTabControl.recreateWebView(appTab, urlData.mUrl);
544 if (current != appTab) {
545 switchToTab(mTabControl.getTabIndex(appTab));
547 urlData.loadIn(appTab.getWebView());
550 // If the tab was the current tab, we have to attach
551 // it to the view system again.
552 attachTabToContentView(appTab);
554 urlData.loadIn(appTab.getWebView());
559 // No matching application tab, try to find a regular tab
560 // with a matching url.
561 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
562 if (appTab != null) {
563 if (current != appTab) {
564 switchToTab(mTabControl.getTabIndex(appTab));
566 // Otherwise, we are already viewing the correct tab.
568 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
569 // will be opened in a new tab unless we have reached
570 // MAX_TABS. Then the url will be opened in the current
571 // tab. If a new tab is created, it will have "true" for
573 openTabAndShow(urlData, true, appId);
577 if ("about:debug".equals(urlData.mUrl)) {
578 mSettings.toggleDebugSettings();
581 // Get rid of the subwindow if it exists
582 dismissSubWindow(current);
583 urlData.loadIn(current.getWebView());
588 private int parseUrlShortcut(String url) {
589 if (url == null) return SHORTCUT_INVALID;
591 // FIXME: quick search, need to be customized by setting
592 if (url.length() > 2 && url.charAt(1) == ' ') {
593 switch (url.charAt(0)) {
594 case 'g': return SHORTCUT_GOOGLE_SEARCH;
595 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
596 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
597 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
600 return SHORTCUT_INVALID;
604 * Launches the default web search activity with the query parameters if the given intent's data
605 * are identified as plain search terms and not URLs/shortcuts.
606 * @return true if the intent was handled and web search activity was launched, false if not.
608 private boolean handleWebSearchIntent(Intent intent) {
609 if (intent == null) return false;
612 final String action = intent.getAction();
613 if (Intent.ACTION_VIEW.equals(action)) {
614 url = intent.getData().toString();
615 } else if (Intent.ACTION_SEARCH.equals(action)
616 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
617 || Intent.ACTION_WEB_SEARCH.equals(action)) {
618 url = intent.getStringExtra(SearchManager.QUERY);
620 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
621 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
625 * Launches the default web search activity with the query parameters if the given url string
626 * was identified as plain search terms and not URL/shortcut.
627 * @return true if the request was handled and web search activity was launched, false if not.
629 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
630 if (inUrl == null) return false;
632 // In general, we shouldn't modify URL from Intent.
633 // But currently, we get the user-typed URL from search box as well.
634 String url = fixUrl(inUrl).trim();
636 // URLs and site specific search shortcuts are handled by the regular flow of control, so
638 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
639 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
640 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
644 Browser.updateVisitedHistory(mResolver, url, false);
645 Browser.addSearchUrl(mResolver, url);
647 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
648 intent.addCategory(Intent.CATEGORY_DEFAULT);
649 intent.putExtra(SearchManager.QUERY, url);
650 if (appData != null) {
651 intent.putExtra(SearchManager.APP_DATA, appData);
653 if (extraData != null) {
654 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
656 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
657 startActivity(intent);
662 private UrlData getUrlDataFromIntent(Intent intent) {
664 if (intent != null) {
665 final String action = intent.getAction();
666 if (Intent.ACTION_VIEW.equals(action)) {
667 url = smartUrlFilter(intent.getData());
668 if (url != null && url.startsWith("content:")) {
669 /* Append mimetype so webview knows how to display */
670 String mimeType = intent.resolveType(getContentResolver());
671 if (mimeType != null) {
672 url += "?" + mimeType;
675 if ("inline:".equals(url)) {
676 return new InlinedUrlData(
677 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
679 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
680 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
682 } else if (Intent.ACTION_SEARCH.equals(action)
683 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
684 || Intent.ACTION_WEB_SEARCH.equals(action)) {
685 url = intent.getStringExtra(SearchManager.QUERY);
687 mLastEnteredUrl = url;
688 // Don't add Urls, just search terms.
689 // Urls will get added when the page is loaded.
690 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
691 Browser.updateVisitedHistory(mResolver, url, false);
693 // In general, we shouldn't modify URL from Intent.
694 // But currently, we get the user-typed URL from search box as well.
696 url = smartUrlFilter(url);
697 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
698 if (url.contains(searchSource)) {
699 String source = null;
700 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
701 if (appData != null) {
702 source = appData.getString(SearchManager.SOURCE);
704 if (TextUtils.isEmpty(source)) {
705 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
707 url = url.replace(searchSource, "&source=android-"+source+"&");
712 return new UrlData(url);
715 /* package */ static String fixUrl(String inUrl) {
716 // FIXME: Converting the url to lower case
717 // duplicates functionality in smartUrlFilter().
718 // However, changing all current callers of fixUrl to
719 // call smartUrlFilter in addition may have unwanted
720 // consequences, and is deferred for now.
721 int colon = inUrl.indexOf(':');
722 boolean allLower = true;
723 for (int index = 0; index < colon; index++) {
724 char ch = inUrl.charAt(index);
725 if (!Character.isLetter(ch)) {
728 allLower &= Character.isLowerCase(ch);
729 if (index == colon - 1 && !allLower) {
730 inUrl = inUrl.substring(0, colon).toLowerCase()
731 + inUrl.substring(colon);
734 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
736 if (inUrl.startsWith("http:") ||
737 inUrl.startsWith("https:")) {
738 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
739 inUrl = inUrl.replaceFirst("/", "//");
740 } else inUrl = inUrl.replaceFirst(":", "://");
746 * Looking for the pattern like this
755 private final SensorListener mSensorListener = new SensorListener() {
756 private long mLastGestureTime;
757 private float[] mPrev = new float[3];
758 private float[] mPrevDiff = new float[3];
759 private float[] mDiff = new float[3];
760 private float[] mRevertDiff = new float[3];
762 public void onSensorChanged(int sensor, float[] values) {
763 boolean show = false;
764 float[] diff = new float[3];
766 for (int i = 0; i < 3; i++) {
767 diff[i] = values[i] - mPrev[i];
768 if (Math.abs(diff[i]) > 1) {
771 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
772 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
773 // start track when there is a big move, or revert
774 mRevertDiff[i] = mDiff[i];
776 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
777 // reset when it is flat
778 mDiff[i] = mRevertDiff[i] = 0;
781 mPrevDiff[i] = diff[i];
782 mPrev[i] = values[i];
786 // only shows if we think the delta is big enough, in an attempt
787 // to detect "serious" moves left/right or up/down
788 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
789 + values[0] + ", " + values[1] + ", " + values[2] + ")"
790 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
792 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
793 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
794 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
795 + mRevertDiff[2] + ")");
798 long now = android.os.SystemClock.uptimeMillis();
799 if (now - mLastGestureTime > 1000) {
800 mLastGestureTime = 0;
804 float ay = Math.abs(y);
805 float az = Math.abs(z);
806 float ry = mRevertDiff[1];
807 float rz = mRevertDiff[2];
808 float ary = Math.abs(ry);
809 float arz = Math.abs(rz);
810 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
811 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
813 if ((gestY || gestZ) && !(gestY && gestZ)) {
814 WebView view = mTabControl.getCurrentWebView();
824 view.flingScroll(0, Math.round(y * 100));
827 mLastGestureTime = now;
832 public void onAccuracyChanged(int sensor, int accuracy) {
833 // TODO Auto-generated method stub
838 @Override protected void onResume() {
841 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
844 if (!mActivityInPause) {
845 Log.e(LOGTAG, "BrowserActivity is already resumed.");
849 mTabControl.resumeCurrentTab();
850 mActivityInPause = false;
851 resumeWebViewTimers();
853 if (mWakeLock.isHeld()) {
854 mHandler.removeMessages(RELEASE_WAKELOCK);
858 if (mCredsDlg != null) {
859 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
860 // In case credential request never comes back
861 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
865 registerReceiver(mNetworkStateIntentReceiver,
866 mNetworkStateChangedFilter);
867 WebView.enablePlatformNotifications();
869 if (mSettings.doFlick()) {
870 if (mSensorManager == null) {
871 mSensorManager = (SensorManager) getSystemService(
872 Context.SENSOR_SERVICE);
874 mSensorManager.registerListener(mSensorListener,
875 SensorManager.SENSOR_ACCELEROMETER,
876 SensorManager.SENSOR_DELAY_FASTEST);
878 mSensorManager = null;
883 * Since the actual title bar is embedded in the WebView, and removing it
884 * would change its appearance, create a temporary title bar to go at
885 * the top of the screen while the menu is open.
887 private TitleBar mFakeTitleBar;
890 * Holder for the fake title bar. It will have a foreground shadow, as well
891 * as a white background, so the fake title bar looks like the real one.
893 private ViewGroup mFakeTitleBarHolder;
896 * Layout parameters for the fake title bar within mFakeTitleBarHolder
898 private FrameLayout.LayoutParams mFakeTitleBarParams
899 = new FrameLayout.LayoutParams(
900 ViewGroup.LayoutParams.FILL_PARENT,
901 ViewGroup.LayoutParams.WRAP_CONTENT);
903 * Keeps track of whether the options menu is open. This is important in
904 * determining whether to show or hide the title bar overlay.
906 private boolean mOptionsMenuOpen;
909 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
910 * of whether the configuration has changed. The first onMenuOpened call
911 * after a configuration change is simply a reopening of the same menu
912 * (i.e. mIconView did not change).
914 private boolean mConfigChanged;
917 * Whether or not the options menu is in its smaller, icon menu form. When
918 * true, we want the title bar overlay to be up. When false, we do not.
919 * Only meaningful if mOptionsMenuOpen is true.
921 private boolean mIconView;
924 public boolean onMenuOpened(int featureId, Menu menu) {
925 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
926 if (mOptionsMenuOpen) {
927 if (mConfigChanged) {
928 // We do not need to make any changes to the state of the
929 // title bar, since the only thing that happened was a
930 // change in orientation
931 mConfigChanged = false;
934 // Switching the menu to expanded view, so hide the
939 // Switching the menu back to icon view, so show the
940 // title bar once again.
946 // The options menu is closed, so open it, and show the title
948 mOptionsMenuOpen = true;
949 mConfigChanged = false;
956 private void showFakeTitleBar() {
957 final View decor = getWindow().peekDecorView();
958 if (mFakeTitleBar == null && mActiveTabsPage == null
959 && !mActivityInPause && decor != null
960 && decor.getWindowToken() != null) {
961 final WebView webView = getTopWindow();
962 mFakeTitleBar = new TitleBar(this);
963 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
964 mFakeTitleBar.setProgress(webView.getProgress());
965 mFakeTitleBar.setFavicon(webView.getFavicon());
966 updateLockIconToLatest();
968 WindowManager manager
969 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
971 // Add the title bar to the window manager so it can receive touches
972 // while the menu is up
973 WindowManager.LayoutParams params
974 = new WindowManager.LayoutParams(
975 ViewGroup.LayoutParams.FILL_PARENT,
976 ViewGroup.LayoutParams.WRAP_CONTENT,
977 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
978 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
979 PixelFormat.TRANSLUCENT);
980 params.gravity = Gravity.TOP;
981 WebView mainView = mTabControl.getCurrentWebView();
982 boolean atTop = mainView != null && mainView.getScrollY() == 0;
983 params.windowAnimations = atTop ? 0
984 : com.android.internal.R.style.Animation_DropDownDown;
985 // XXX : Without providing an offset, the fake title bar will be
986 // placed underneath the status bar. Use the global visible rect
987 // of mBrowserFrameLayout to determine the bottom of the status bar
988 Rect rectangle = new Rect();
989 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
990 params.y = rectangle.top;
991 // Add a holder for the title bar. It also holds a shadow to show
992 // below the title bar.
993 if (mFakeTitleBarHolder == null) {
994 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
995 .inflate(R.layout.title_bar_bg, null);
997 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
998 manager.addView(mFakeTitleBarHolder, params);
1003 public void onOptionsMenuClosed(Menu menu) {
1004 mOptionsMenuOpen = false;
1007 } else if (!mIconView) {
1008 // The page is currently loading, and we are in expanded mode, so
1009 // we were not showing the menu. Show it once again. It will be
1010 // removed when the page finishes.
1014 private void hideFakeTitleBar() {
1015 if (mFakeTitleBar == null) return;
1016 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
1017 mFakeTitleBarHolder.getLayoutParams();
1018 WebView mainView = mTabControl.getCurrentWebView();
1019 // Although we decided whether or not to animate based on the current
1020 // scroll position, the scroll position may have changed since the
1021 // fake title bar was displayed. Make sure it has the appropriate
1022 // animation/lack thereof before removing.
1023 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
1024 ? 0 : com.android.internal.R.style.Animation_DropDownDown;
1025 WindowManager manager
1026 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1027 manager.updateViewLayout(mFakeTitleBarHolder, params);
1028 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1029 manager.removeView(mFakeTitleBarHolder);
1030 mFakeTitleBar = null;
1034 * onSaveInstanceState(Bundle map)
1035 * onSaveInstanceState is called right before onStop(). The map contains
1038 @Override protected void onSaveInstanceState(Bundle outState) {
1040 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1042 // the default implementation requires each view to have an id. As the
1043 // browser handles the state itself and it doesn't use id for the views,
1044 // don't call the default implementation. Otherwise it will trigger the
1045 // warning like this, "couldn't save which view has focus because the
1046 // focused view XXX has no id".
1048 // Save all the tabs
1049 mTabControl.saveState(outState);
1052 @Override protected void onPause() {
1055 if (mActivityInPause) {
1056 Log.e(LOGTAG, "BrowserActivity is already paused.");
1060 mTabControl.pauseCurrentTab();
1061 mActivityInPause = true;
1062 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1063 mWakeLock.acquire();
1064 mHandler.sendMessageDelayed(mHandler
1065 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1068 // Clear the credentials toast if it is up
1069 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1070 mCredsDlg.dismiss();
1074 // FIXME: This removes the active tabs page and resets the menu to
1075 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1076 // but then we would need to save it in onSaveInstanceState and restore
1077 // it in onCreate/onRestoreInstanceState
1078 if (mActiveTabsPage != null) {
1079 removeActiveTabPage(true);
1084 // unregister network state listener
1085 unregisterReceiver(mNetworkStateIntentReceiver);
1086 WebView.disablePlatformNotifications();
1088 if (mSensorManager != null) {
1089 mSensorManager.unregisterListener(mSensorListener);
1093 @Override protected void onDestroy() {
1095 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1098 // Remove the current tab and sub window
1099 TabControl.Tab t = mTabControl.getCurrentTab();
1101 dismissSubWindow(t);
1102 removeTabFromContentView(t);
1104 // Destroy all the tabs
1105 mTabControl.destroy();
1106 WebIconDatabase.getInstance().close();
1107 if (mGlsConnection != null) {
1108 unbindService(mGlsConnection);
1109 mGlsConnection = null;
1113 // stop MASF proxy service
1115 //Intent proxyServiceIntent = new Intent();
1116 //proxyServiceIntent.setComponent
1117 // (new ComponentName(
1118 // "com.android.masfproxyservice",
1119 // "com.android.masfproxyservice.MasfProxyService"));
1120 //stopService(proxyServiceIntent);
1122 unregisterReceiver(mPackageInstallationReceiver);
1126 public void onConfigurationChanged(Configuration newConfig) {
1127 mConfigChanged = true;
1128 super.onConfigurationChanged(newConfig);
1130 if (mPageInfoDialog != null) {
1131 mPageInfoDialog.dismiss();
1134 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1136 if (mSSLCertificateDialog != null) {
1137 mSSLCertificateDialog.dismiss();
1139 mSSLCertificateView);
1141 if (mSSLCertificateOnErrorDialog != null) {
1142 mSSLCertificateOnErrorDialog.dismiss();
1143 showSSLCertificateOnError(
1144 mSSLCertificateOnErrorView,
1145 mSSLCertificateOnErrorHandler,
1146 mSSLCertificateOnErrorError);
1148 if (mHttpAuthenticationDialog != null) {
1149 String title = ((TextView) mHttpAuthenticationDialog
1150 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1152 String name = ((TextView) mHttpAuthenticationDialog
1153 .findViewById(R.id.username_edit)).getText().toString();
1154 String password = ((TextView) mHttpAuthenticationDialog
1155 .findViewById(R.id.password_edit)).getText().toString();
1156 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1158 mHttpAuthenticationDialog.dismiss();
1159 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1160 name, password, focusId);
1162 if (mFindDialog != null && mFindDialog.isShowing()) {
1163 mFindDialog.onConfigurationChanged(newConfig);
1167 @Override public void onLowMemory() {
1168 super.onLowMemory();
1169 mTabControl.freeMemory();
1172 private boolean resumeWebViewTimers() {
1173 if ((!mActivityInPause && !mPageStarted) ||
1174 (mActivityInPause && mPageStarted)) {
1175 CookieSyncManager.getInstance().startSync();
1176 WebView w = mTabControl.getCurrentWebView();
1186 private boolean pauseWebViewTimers() {
1187 if (mActivityInPause && !mPageStarted) {
1188 CookieSyncManager.getInstance().stopSync();
1189 WebView w = mTabControl.getCurrentWebView();
1199 // FIXME: Do we want to call this when loading google for the first time?
1201 * This function is called when we are launching for the first time. We
1202 * are waiting for the login credentials before loading Google home
1203 * pages. This way the user will be logged in straight away.
1205 private void waitForCredentials() {
1207 mCredsDlg = new ProgressDialog(this);
1208 mCredsDlg.setIndeterminate(true);
1209 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1210 // If the user cancels the operation, then cancel the Google
1211 // Credentials request.
1212 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1215 // We set a timeout for the retrieval of credentials in onResume()
1216 // as that is when we have freed up some CPU time to get
1217 // the login credentials.
1221 * If we have received the credentials or we have timed out and we are
1222 * showing the credentials dialog, then it is time to move on.
1224 private void resumeAfterCredentials() {
1225 if (mCredsDlg == null) {
1230 if (mCredsDlg.isShowing()) {
1231 mCredsDlg.dismiss();
1235 // Clear any pending timeout
1236 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1239 WebView w = mTabControl.getCurrentWebView();
1241 w.loadUrl(mSettings.getHomePage());
1244 // Update the settings, need to do this last as it can take a moment
1245 // to persist the settings. In the mean time we could be loading
1247 mSettings.setLoginInitialized(this);
1250 // Open the icon database and retain all the icons for visited sites.
1251 private void retainIconsOnStartup() {
1252 final WebIconDatabase db = WebIconDatabase.getInstance();
1253 db.open(getDir("icons", 0).getPath());
1255 Cursor c = Browser.getAllBookmarks(mResolver);
1256 if (!c.moveToFirst()) {
1260 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1262 String url = c.getString(urlIndex);
1263 db.retainIconForPageUrl(url);
1264 } while (c.moveToNext());
1266 } catch (IllegalStateException e) {
1267 Log.e(LOGTAG, "retainIconsOnStartup", e);
1271 // Helper method for getting the top window.
1272 WebView getTopWindow() {
1273 return mTabControl.getCurrentTopWebView();
1277 public boolean onCreateOptionsMenu(Menu menu) {
1278 super.onCreateOptionsMenu(menu);
1280 MenuInflater inflater = getMenuInflater();
1281 inflater.inflate(R.menu.browser, menu);
1283 updateInLoadMenuItems();
1288 * As the menu can be open when loading state changes
1289 * we must manually update the state of the stop/reload menu
1292 private void updateInLoadMenuItems() {
1293 if (mMenu == null) {
1296 MenuItem src = mInLoad ?
1297 mMenu.findItem(R.id.stop_menu_id):
1298 mMenu.findItem(R.id.reload_menu_id);
1299 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1300 dest.setIcon(src.getIcon());
1301 dest.setTitle(src.getTitle());
1305 public boolean onContextItemSelected(MenuItem item) {
1306 // chording is not an issue with context menus, but we use the same
1307 // options selector, so set mCanChord to true so we can access them.
1309 int id = item.getItemId();
1310 final WebView webView = getTopWindow();
1311 if (null == webView) {
1314 final HashMap hrefMap = new HashMap();
1315 hrefMap.put("webview", webView);
1316 final Message msg = mHandler.obtainMessage(
1317 FOCUS_NODE_HREF, id, 0, hrefMap);
1319 // -- Browser context menu
1320 case R.id.open_context_menu_id:
1321 case R.id.open_newtab_context_menu_id:
1322 case R.id.bookmark_context_menu_id:
1323 case R.id.save_link_context_menu_id:
1324 case R.id.share_link_context_menu_id:
1325 case R.id.copy_link_context_menu_id:
1326 webView.requestFocusNodeHref(msg);
1330 // For other context menus
1331 return onOptionsItemSelected(item);
1337 private Bundle createGoogleSearchSourceBundle(String source) {
1338 Bundle bundle = new Bundle();
1339 bundle.putString(SearchManager.SOURCE, source);
1344 * Overriding this to insert a local information bundle
1347 public boolean onSearchRequested() {
1348 if (mOptionsMenuOpen) closeOptionsMenu();
1349 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1350 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1351 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1356 public void startSearch(String initialQuery, boolean selectInitialQuery,
1357 Bundle appSearchData, boolean globalSearch) {
1358 if (appSearchData == null) {
1359 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1361 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1365 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1366 * results in changing tabs.
1367 * @param index Index of the tab to change to, as defined by
1368 * mTabControl.getTabIndex(Tab t).
1369 * @return boolean True if we successfully switched to a different tab. If
1370 * the indexth tab is null, or if that tab is the same as
1371 * the current one, return false.
1373 /* package */ boolean switchToTab(int index) {
1374 TabControl.Tab tab = mTabControl.getTab(index);
1375 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1376 if (tab == null || tab == currentTab) {
1379 if (currentTab != null) {
1380 // currentTab may be null if it was just removed. In that case,
1381 // we do not need to remove it
1382 removeTabFromContentView(currentTab);
1384 mTabControl.setCurrentTab(tab);
1385 attachTabToContentView(tab);
1386 resetTitleIconAndProgress();
1387 updateLockIconToLatest();
1391 /* package */ TabControl.Tab openTabToHomePage() {
1392 return openTabAndShow(mSettings.getHomePage(), false, null);
1395 /* package */ void closeCurrentWindow() {
1396 final TabControl.Tab current = mTabControl.getCurrentTab();
1397 if (mTabControl.getTabCount() == 1) {
1398 // This is the last tab. Open a new one, with the home
1399 // page and close the current one.
1400 TabControl.Tab newTab = openTabToHomePage();
1404 final TabControl.Tab parent = current.getParentTab();
1405 int indexToShow = -1;
1406 if (parent != null) {
1407 indexToShow = mTabControl.getTabIndex(parent);
1409 final int currentIndex = mTabControl.getCurrentIndex();
1410 // Try to move to the tab to the right
1411 indexToShow = currentIndex + 1;
1412 if (indexToShow > mTabControl.getTabCount() - 1) {
1413 // Try to move to the tab to the left
1414 indexToShow = currentIndex - 1;
1417 if (switchToTab(indexToShow)) {
1423 private ActiveTabsPage mActiveTabsPage;
1426 * Remove the active tabs page.
1427 * @param needToAttach If true, the active tabs page did not attach a tab
1428 * to the content view, so we need to do that here.
1430 /* package */ void removeActiveTabPage(boolean needToAttach) {
1431 mContentView.removeView(mActiveTabsPage);
1432 mActiveTabsPage = null;
1433 mMenuState = R.id.MAIN_MENU;
1435 attachTabToContentView(mTabControl.getCurrentTab());
1437 getTopWindow().requestFocus();
1441 public boolean onOptionsItemSelected(MenuItem item) {
1443 // The user has already fired a shortcut with this hold down of the
1447 if (null == getTopWindow()) {
1451 // The shortcut action consumes the MENU. Even if it is still down,
1452 // it won't trigger the next shortcut action. In the case of the
1453 // shortcut action triggering a new activity, like Bookmarks, we
1454 // won't get onKeyUp for MENU. So it is important to reset it here.
1455 mMenuIsDown = false;
1457 switch (item.getItemId()) {
1459 case R.id.new_tab_menu_id:
1460 openTabToHomePage();
1463 case R.id.goto_menu_id:
1464 bookmarksOrHistoryPicker(false);
1467 case R.id.active_tabs_menu_id:
1468 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1469 removeTabFromContentView(mTabControl.getCurrentTab());
1471 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1472 mActiveTabsPage.requestFocus();
1473 mMenuState = EMPTY_MENU;
1476 case R.id.add_bookmark_menu_id:
1477 Intent i = new Intent(BrowserActivity.this,
1478 AddBookmarkPage.class);
1479 WebView w = getTopWindow();
1480 i.putExtra("url", w.getUrl());
1481 i.putExtra("title", w.getTitle());
1482 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1483 i.putExtra("thumbnail", createScreenshot(w));
1487 case R.id.stop_reload_menu_id:
1491 getTopWindow().reload();
1495 case R.id.back_menu_id:
1496 getTopWindow().goBack();
1499 case R.id.forward_menu_id:
1500 getTopWindow().goForward();
1503 case R.id.close_menu_id:
1504 // Close the subwindow if it exists.
1505 if (mTabControl.getCurrentSubWindow() != null) {
1506 dismissSubWindow(mTabControl.getCurrentTab());
1509 closeCurrentWindow();
1512 case R.id.homepage_menu_id:
1513 TabControl.Tab current = mTabControl.getCurrentTab();
1514 if (current != null) {
1515 dismissSubWindow(current);
1516 current.getWebView().loadUrl(mSettings.getHomePage());
1520 case R.id.preferences_menu_id:
1521 Intent intent = new Intent(this,
1522 BrowserPreferencesPage.class);
1523 startActivityForResult(intent, PREFERENCES_PAGE);
1526 case R.id.find_menu_id:
1527 if (null == mFindDialog) {
1528 mFindDialog = new FindDialog(this);
1530 mFindDialog.setWebView(getTopWindow());
1532 mMenuState = EMPTY_MENU;
1535 case R.id.select_text_id:
1536 getTopWindow().emulateShiftHeld();
1538 case R.id.page_info_menu_id:
1539 showPageInfo(mTabControl.getCurrentTab(), false);
1542 case R.id.classic_history_menu_id:
1543 bookmarksOrHistoryPicker(true);
1546 case R.id.share_page_menu_id:
1547 Browser.sendString(this, getTopWindow().getUrl());
1550 case R.id.dump_nav_menu_id:
1551 getTopWindow().debugDump();
1554 case R.id.zoom_in_menu_id:
1555 getTopWindow().zoomIn();
1558 case R.id.zoom_out_menu_id:
1559 getTopWindow().zoomOut();
1562 case R.id.view_downloads_menu_id:
1563 viewDownloads(null);
1566 case R.id.window_one_menu_id:
1567 case R.id.window_two_menu_id:
1568 case R.id.window_three_menu_id:
1569 case R.id.window_four_menu_id:
1570 case R.id.window_five_menu_id:
1571 case R.id.window_six_menu_id:
1572 case R.id.window_seven_menu_id:
1573 case R.id.window_eight_menu_id:
1575 int menuid = item.getItemId();
1576 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1577 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1578 TabControl.Tab desiredTab = mTabControl.getTab(id);
1579 if (desiredTab != null &&
1580 desiredTab != mTabControl.getCurrentTab()) {
1590 if (!super.onOptionsItemSelected(item)) {
1593 // Otherwise fall through.
1599 public void closeFind() {
1600 mMenuState = R.id.MAIN_MENU;
1603 @Override public boolean onPrepareOptionsMenu(Menu menu)
1605 // This happens when the user begins to hold down the menu key, so
1606 // allow them to chord to get a shortcut.
1608 // Note: setVisible will decide whether an item is visible; while
1609 // setEnabled() will decide whether an item is enabled, which also means
1610 // whether the matching shortcut key will function.
1611 super.onPrepareOptionsMenu(menu);
1612 switch (mMenuState) {
1614 if (mCurrentMenuState != mMenuState) {
1615 menu.setGroupVisible(R.id.MAIN_MENU, false);
1616 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1617 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1621 if (mCurrentMenuState != mMenuState) {
1622 menu.setGroupVisible(R.id.MAIN_MENU, true);
1623 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1624 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1626 final WebView w = getTopWindow();
1627 boolean canGoBack = false;
1628 boolean canGoForward = false;
1629 boolean isHome = false;
1631 canGoBack = w.canGoBack();
1632 canGoForward = w.canGoForward();
1633 isHome = mSettings.getHomePage().equals(w.getUrl());
1635 final MenuItem back = menu.findItem(R.id.back_menu_id);
1636 back.setEnabled(canGoBack);
1638 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1639 home.setEnabled(!isHome);
1641 menu.findItem(R.id.forward_menu_id)
1642 .setEnabled(canGoForward);
1644 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1645 mTabControl.getTabCount() < TabControl.MAX_TABS);
1647 // decide whether to show the share link option
1648 PackageManager pm = getPackageManager();
1649 Intent send = new Intent(Intent.ACTION_SEND);
1650 send.setType("text/plain");
1651 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1652 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1654 boolean isNavDump = mSettings.isNavDump();
1655 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1656 nav.setVisible(isNavDump);
1657 nav.setEnabled(isNavDump);
1660 mCurrentMenuState = mMenuState;
1665 public void onCreateContextMenu(ContextMenu menu, View v,
1666 ContextMenuInfo menuInfo) {
1667 WebView webview = (WebView) v;
1668 WebView.HitTestResult result = webview.getHitTestResult();
1669 if (result == null) {
1673 int type = result.getType();
1674 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1676 "We should not show context menu when nothing is touched");
1679 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1680 // let TextView handles context menu
1684 // Note, http://b/issue?id=1106666 is requesting that
1685 // an inflated menu can be used again. This is not available
1686 // yet, so inflate each time (yuk!)
1687 MenuInflater inflater = getMenuInflater();
1688 inflater.inflate(R.menu.browsercontext, menu);
1690 // Show the correct menu group
1691 String extra = result.getExtra();
1692 menu.setGroupVisible(R.id.PHONE_MENU,
1693 type == WebView.HitTestResult.PHONE_TYPE);
1694 menu.setGroupVisible(R.id.EMAIL_MENU,
1695 type == WebView.HitTestResult.EMAIL_TYPE);
1696 menu.setGroupVisible(R.id.GEO_MENU,
1697 type == WebView.HitTestResult.GEO_TYPE);
1698 menu.setGroupVisible(R.id.IMAGE_MENU,
1699 type == WebView.HitTestResult.IMAGE_TYPE
1700 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1701 menu.setGroupVisible(R.id.ANCHOR_MENU,
1702 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1703 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1705 // Setup custom handling depending on the type
1707 case WebView.HitTestResult.PHONE_TYPE:
1708 menu.setHeaderTitle(Uri.decode(extra));
1709 menu.findItem(R.id.dial_context_menu_id).setIntent(
1710 new Intent(Intent.ACTION_VIEW, Uri
1711 .parse(WebView.SCHEME_TEL + extra)));
1712 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1713 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1714 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1715 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1717 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1721 case WebView.HitTestResult.EMAIL_TYPE:
1722 menu.setHeaderTitle(extra);
1723 menu.findItem(R.id.email_context_menu_id).setIntent(
1724 new Intent(Intent.ACTION_VIEW, Uri
1725 .parse(WebView.SCHEME_MAILTO + extra)));
1726 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1730 case WebView.HitTestResult.GEO_TYPE:
1731 menu.setHeaderTitle(extra);
1732 menu.findItem(R.id.map_context_menu_id).setIntent(
1733 new Intent(Intent.ACTION_VIEW, Uri
1734 .parse(WebView.SCHEME_GEO
1735 + URLEncoder.encode(extra))));
1736 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1740 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1741 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1742 TextView titleView = (TextView) LayoutInflater.from(this)
1743 .inflate(android.R.layout.browser_link_context_header,
1745 titleView.setText(extra);
1746 menu.setHeaderView(titleView);
1747 // decide whether to show the open link in new tab option
1748 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1749 mTabControl.getTabCount() < TabControl.MAX_TABS);
1750 PackageManager pm = getPackageManager();
1751 Intent send = new Intent(Intent.ACTION_SEND);
1752 send.setType("text/plain");
1753 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1754 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1755 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1758 // otherwise fall through to handle image part
1759 case WebView.HitTestResult.IMAGE_TYPE:
1760 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1761 menu.setHeaderTitle(extra);
1763 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1764 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1765 menu.findItem(R.id.download_context_menu_id).
1766 setOnMenuItemClickListener(new Download(extra));
1770 Log.w(LOGTAG, "We should not get here.");
1775 // Attach the given tab to the content view.
1776 // this should only be called for the current tab.
1777 private void attachTabToContentView(TabControl.Tab t) {
1778 // Attach the container that contains the main WebView and any other UI
1779 // associated with the tab.
1780 t.attachTabToContentView(mContentView);
1782 if (mShouldShowErrorConsole) {
1783 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1784 if (errorConsole.numberOfErrors() == 0) {
1785 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1787 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1790 mErrorConsoleContainer.addView(errorConsole,
1791 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1792 ViewGroup.LayoutParams.WRAP_CONTENT));
1795 setLockIconType(t.getLockIconType());
1796 setPrevLockType(t.getPrevLockIconType());
1798 // this is to match the code in removeTabFromContentView()
1799 if (!mPageStarted && t.getTopWindow().getProgress() < 100) {
1800 mPageStarted = true;
1803 WebView view = t.getWebView();
1804 view.setEmbeddedTitleBar(mTitleBar);
1805 // Request focus on the top window.
1806 t.getTopWindow().requestFocus();
1809 // Attach a sub window to the main WebView of the given tab.
1810 private void attachSubWindow(TabControl.Tab t) {
1811 t.attachSubWindow(mContentView);
1812 getTopWindow().requestFocus();
1815 // Remove the given tab from the content view.
1816 private void removeTabFromContentView(TabControl.Tab t) {
1817 // Remove the container that contains the main WebView.
1818 t.removeTabFromContentView(mContentView);
1820 if (mTabControl.getCurrentErrorConsole(false) != null) {
1821 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1824 WebView view = t.getWebView();
1826 view.setEmbeddedTitleBar(null);
1829 // unlike attachTabToContentView(), removeTabFromContentView() can be
1830 // called for the non-current tab. Need to add the check.
1831 if (t == mTabControl.getCurrentTab()) {
1832 t.setLockIconType(getLockIconType());
1833 t.setPrevLockIconType(getPrevLockType());
1835 // this is not a perfect solution. But currently there is one
1836 // WebViewClient for all the WebView. if user switches from an
1837 // in-load window to an already loaded window, mPageStarted will not
1838 // be set to false. If user leaves the Browser, pauseWebViewTimers()
1839 // won't do anything and leaves the timer running even Browser is in
1842 mPageStarted = false;
1847 // Remove the sub window if it exists. Also called by TabControl when the
1848 // user clicks the 'X' to dismiss a sub window.
1849 /* package */ void dismissSubWindow(TabControl.Tab t) {
1850 t.removeSubWindow(mContentView);
1851 // Tell the TabControl to dismiss the subwindow. This will destroy
1853 mTabControl.dismissSubWindow(t);
1854 getTopWindow().requestFocus();
1857 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1858 // that accepts url as string.
1859 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1861 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1864 // This method does a ton of stuff. It will attempt to create a new tab
1865 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1866 // url isn't null, it will load the given url.
1867 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
1868 boolean closeOnExit, String appId) {
1869 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1870 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1872 final TabControl.Tab tab = mTabControl.createNewTab(
1873 closeOnExit, appId, urlData.mUrl);
1874 WebView webview = tab.getWebView();
1875 // If the last tab was removed from the active tabs page, currentTab
1877 if (currentTab != null) {
1878 removeTabFromContentView(currentTab);
1880 // We must set the new tab as the current tab to reflect the old
1881 // animation behavior.
1882 mTabControl.setCurrentTab(tab);
1883 attachTabToContentView(tab);
1884 if (!urlData.isEmpty()) {
1885 urlData.loadIn(webview);
1889 // Get rid of the subwindow if it exists
1890 dismissSubWindow(currentTab);
1891 if (!urlData.isEmpty()) {
1892 // Load the given url.
1893 urlData.loadIn(currentTab.getWebView());
1899 private TabControl.Tab openTab(String url) {
1900 if (mSettings.openInBackground()) {
1901 TabControl.Tab t = mTabControl.createNewTab();
1903 WebView view = t.getWebView();
1908 return openTabAndShow(url, false, null);
1912 private class Copy implements OnMenuItemClickListener {
1913 private CharSequence mText;
1915 public boolean onMenuItemClick(MenuItem item) {
1920 public Copy(CharSequence toCopy) {
1925 private class Download implements OnMenuItemClickListener {
1926 private String mText;
1928 public boolean onMenuItemClick(MenuItem item) {
1929 onDownloadStartNoStream(mText, null, null, null, -1);
1933 public Download(String toDownload) {
1938 private void copy(CharSequence text) {
1940 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1942 clip.setClipboardText(text);
1944 } catch (android.os.RemoteException e) {
1945 Log.e(LOGTAG, "Copy failed", e);
1950 * Resets the browser title-view to whatever it must be
1951 * (for example, if we had a loading error)
1952 * When we have a new page, we call resetTitle, when we
1953 * have to reset the titlebar to whatever it used to be
1954 * (for example, if the user chose to stop loading), we
1955 * call resetTitleAndRevertLockIcon.
1957 /* package */ void resetTitleAndRevertLockIcon() {
1959 resetTitleIconAndProgress();
1963 * Reset the title, favicon, and progress.
1965 private void resetTitleIconAndProgress() {
1966 WebView current = mTabControl.getCurrentWebView();
1967 if (current == null) {
1970 resetTitleAndIcon(current);
1971 int progress = current.getProgress();
1972 mWebChromeClient.onProgressChanged(current, progress);
1975 // Reset the title and the icon based on the given item.
1976 private void resetTitleAndIcon(WebView view) {
1977 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1979 setUrlTitle(item.getUrl(), item.getTitle());
1980 setFavicon(item.getFavicon());
1982 setUrlTitle(null, null);
1988 * Sets a title composed of the URL and the title string.
1989 * @param url The URL of the site being loaded.
1990 * @param title The title of the site being loaded.
1992 private void setUrlTitle(String url, String title) {
1996 mTitleBar.setTitleAndUrl(title, url);
1997 if (mFakeTitleBar != null) {
1998 mFakeTitleBar.setTitleAndUrl(title, url);
2003 * @param url The URL to build a title version of the URL from.
2004 * @return The title version of the URL or null if fails.
2005 * The title version of the URL can be either the URL hostname,
2006 * or the hostname with an "https://" prefix (for secure URLs),
2007 * or an empty string if, for example, the URL in question is a
2008 * file:// URL with no hostname.
2010 /* package */ static String buildTitleUrl(String url) {
2011 String titleUrl = null;
2015 // parse the url string
2016 URL urlObj = new URL(url);
2017 if (urlObj != null) {
2020 String protocol = urlObj.getProtocol();
2021 String host = urlObj.getHost();
2023 if (host != null && 0 < host.length()) {
2025 if (protocol != null) {
2026 // if a secure site, add an "https://" prefix!
2027 if (protocol.equalsIgnoreCase("https")) {
2028 titleUrl = protocol + "://" + host;
2033 } catch (MalformedURLException e) {}
2039 // Set the favicon in the title bar.
2040 private void setFavicon(Bitmap icon) {
2041 mTitleBar.setFavicon(icon);
2042 if (mFakeTitleBar != null) {
2043 mFakeTitleBar.setFavicon(icon);
2048 * Saves the current lock-icon state before resetting
2049 * the lock icon. If we have an error, we may need to
2050 * roll back to the previous state.
2052 private void saveLockIcon() {
2053 mPrevLockType = mLockIconType;
2057 * Reverts the lock-icon state to the last saved state,
2058 * for example, if we had an error, and need to cancel
2061 private void revertLockIcon() {
2062 mLockIconType = mPrevLockType;
2065 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2066 " revert lock icon to " + mLockIconType);
2069 updateLockIconToLatest();
2073 * Close the tab, remove its associated title bar, and adjust mTabControl's
2074 * current tab to a valid value.
2076 /* package */ void closeTab(TabControl.Tab t) {
2077 int currentIndex = mTabControl.getCurrentIndex();
2078 int removeIndex = mTabControl.getTabIndex(t);
2079 mTabControl.removeTab(t);
2080 if (currentIndex >= removeIndex && currentIndex != 0) {
2083 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2084 resetTitleIconAndProgress();
2087 private void goBackOnePageOrQuit() {
2088 TabControl.Tab current = mTabControl.getCurrentTab();
2089 if (current == null) {
2091 * Instead of finishing the activity, simply push this to the back
2092 * of the stack and let ActivityManager to choose the foreground
2093 * activity. As BrowserActivity is singleTask, it will be always the
2094 * root of the task. So we can use either true or false for
2097 moveTaskToBack(true);
2099 WebView w = current.getWebView();
2100 if (w.canGoBack()) {
2103 // Check to see if we are closing a window that was created by
2104 // another window. If so, we switch back to that window.
2105 TabControl.Tab parent = current.getParentTab();
2106 if (parent != null) {
2107 switchToTab(mTabControl.getTabIndex(parent));
2108 // Now we close the other tab
2111 if (current.closeOnExit()) {
2112 // force mPageStarted to be false as we are going to either
2113 // finish the activity or remove the tab. This will ensure
2114 // pauseWebView() taking action.
2115 mPageStarted = false;
2116 if (mTabControl.getTabCount() == 1) {
2120 // call pauseWebViewTimers() now, we won't be able to call
2121 // it in onPause() as the WebView won't be valid.
2122 // Temporarily change mActivityInPause to be true as
2123 // pauseWebViewTimers() will do nothing if mActivityInPause
2125 boolean savedState = mActivityInPause;
2127 Log.e(LOGTAG, "BrowserActivity is already paused "
2128 + "while handing goBackOnePageOrQuit.");
2130 mActivityInPause = true;
2131 pauseWebViewTimers();
2132 mActivityInPause = savedState;
2133 removeTabFromContentView(current);
2134 mTabControl.removeTab(current);
2137 * Instead of finishing the activity, simply push this to the back
2138 * of the stack and let ActivityManager to choose the foreground
2139 * activity. As BrowserActivity is singleTask, it will be always the
2140 * root of the task. So we can use either true or false for
2143 moveTaskToBack(true);
2149 public boolean onKeyDown(int keyCode, KeyEvent event) {
2150 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2151 // still down, we don't want to trigger the search. Pretend to consume
2152 // the key and do nothing.
2153 if (mMenuIsDown) return true;
2156 case KeyEvent.KEYCODE_MENU:
2159 case KeyEvent.KEYCODE_SPACE:
2160 // WebView/WebTextView handle the keys in the KeyDown. As
2161 // the Activity's shortcut keys are only handled when WebView
2162 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2163 if (event.isShiftPressed()) {
2164 getTopWindow().pageUp(false);
2166 getTopWindow().pageDown(false);
2169 case KeyEvent.KEYCODE_BACK:
2170 if (event.getRepeatCount() == 0) {
2171 event.startTracking();
2173 } else if (mCustomView == null && mActiveTabsPage == null
2174 && event.isLongPress()) {
2175 bookmarksOrHistoryPicker(true);
2180 return super.onKeyDown(keyCode, event);
2184 public boolean onKeyUp(int keyCode, KeyEvent event) {
2186 case KeyEvent.KEYCODE_MENU:
2187 mMenuIsDown = false;
2189 case KeyEvent.KEYCODE_BACK:
2190 if (event.isTracking() && !event.isCanceled()) {
2191 if (mCustomView != null) {
2192 // if a custom view is showing, hide it
2193 mWebChromeClient.onHideCustomView();
2194 } else if (mActiveTabsPage != null) {
2195 // if tab page is showing, hide it
2196 removeActiveTabPage(true);
2198 WebView subwindow = mTabControl.getCurrentSubWindow();
2199 if (subwindow != null) {
2200 if (subwindow.canGoBack()) {
2203 dismissSubWindow(mTabControl.getCurrentTab());
2206 goBackOnePageOrQuit();
2213 return super.onKeyUp(keyCode, event);
2216 /* package */ void stopLoading() {
2217 resetTitleAndRevertLockIcon();
2218 WebView w = getTopWindow();
2220 mWebViewClient.onPageFinished(w, w.getUrl());
2224 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2228 private void cancelStopToast() {
2229 if (mStopToast != null) {
2230 mStopToast.cancel();
2235 // called by a non-UI thread to post the message
2236 public void postMessage(int what, int arg1, int arg2, Object obj) {
2237 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2240 // public message ids
2241 public final static int LOAD_URL = 1001;
2242 public final static int STOP_LOAD = 1002;
2245 private static final int FOCUS_NODE_HREF = 102;
2246 private static final int CANCEL_CREDS_REQUEST = 103;
2247 private static final int RELEASE_WAKELOCK = 107;
2249 // Private handler for handling javascript and saving passwords
2250 private Handler mHandler = new Handler() {
2252 public void handleMessage(Message msg) {
2254 case FOCUS_NODE_HREF:
2255 String url = (String) msg.getData().get("url");
2256 if (url == null || url.length() == 0) {
2259 HashMap focusNodeMap = (HashMap) msg.obj;
2260 WebView view = (WebView) focusNodeMap.get("webview");
2261 // Only apply the action if the top window did not change.
2262 if (getTopWindow() != view) {
2266 case R.id.open_context_menu_id:
2267 case R.id.view_image_context_menu_id:
2268 loadURL(getTopWindow(), url);
2270 case R.id.open_newtab_context_menu_id:
2271 final TabControl.Tab parent = mTabControl
2273 final TabControl.Tab newTab = openTab(url);
2274 if (newTab != parent) {
2275 parent.addChildTab(newTab);
2278 case R.id.bookmark_context_menu_id:
2279 Intent intent = new Intent(BrowserActivity.this,
2280 AddBookmarkPage.class);
2281 intent.putExtra("url", url);
2282 startActivity(intent);
2284 case R.id.share_link_context_menu_id:
2285 Browser.sendString(BrowserActivity.this, url);
2287 case R.id.copy_link_context_menu_id:
2290 case R.id.save_link_context_menu_id:
2291 case R.id.download_context_menu_id:
2292 onDownloadStartNoStream(url, null, null, null, -1);
2298 loadURL(getTopWindow(), (String) msg.obj);
2305 case CANCEL_CREDS_REQUEST:
2306 resumeAfterCredentials();
2309 case RELEASE_WAKELOCK:
2310 if (mWakeLock.isHeld()) {
2311 mWakeLock.release();
2318 private void updateScreenshot(WebView view) {
2319 // If this is a bookmarked site, add a screenshot to the database.
2320 // FIXME: When should we update? Every time?
2321 // FIXME: Would like to make sure there is actually something to
2322 // draw, but the API for that (WebViewCore.pictureReady()) is not
2323 // currently accessible here.
2324 ContentResolver cr = getContentResolver();
2325 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2326 cr, view.getOriginalUrl(), view.getUrl(), false);
2328 boolean succeed = c.moveToFirst();
2329 ContentValues values = null;
2331 if (values == null) {
2332 final ByteArrayOutputStream os
2333 = new ByteArrayOutputStream();
2334 Bitmap bm = createScreenshot(view);
2335 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2336 values = new ContentValues();
2337 values.put(Browser.BookmarkColumns.THUMBNAIL,
2340 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2341 c.getInt(0)), values, null, null);
2342 succeed = c.moveToNext();
2349 * Constants for the size of the thumbnail created when taking a screenshot
2351 /* package */ static final int THUMBNAIL_WIDTH = 130;
2352 /* package */ static final int THUMBNAIL_HEIGHT = 104;
2354 private Bitmap createScreenshot(WebView view) {
2355 Picture thumbnail = view.capturePicture();
2356 Bitmap bm = Bitmap.createBitmap(THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT,
2357 Bitmap.Config.ARGB_4444);
2358 Canvas canvas = new Canvas(bm);
2359 // May need to tweak these values to determine what is the
2360 // best scale factor
2361 int contentWidth = view.getContentWidth();
2362 if (contentWidth > 0) {
2363 float scaleFactor = (float) THUMBNAIL_WIDTH / (float) contentWidth;
2364 canvas.scale(scaleFactor, scaleFactor);
2366 thumbnail.draw(canvas);
2370 // -------------------------------------------------------------------------
2371 // WebViewClient implementation.
2372 //-------------------------------------------------------------------------
2374 // Use in overrideUrlLoading
2375 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2376 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2377 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2378 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2380 /* package */ WebViewClient getWebViewClient() {
2381 return mWebViewClient;
2384 private void updateIcon(WebView view, Bitmap icon) {
2386 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2387 view.getOriginalUrl(), view.getUrl(), icon);
2392 private void updateIcon(String url, Bitmap icon) {
2394 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2400 private final WebViewClient mWebViewClient = new WebViewClient() {
2402 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2404 setUrlTitle(url, null);
2406 // If we start a touch icon load and then load a new page, we don't
2407 // want to cancel the current touch icon loader. But, we do want to
2408 // create a new one when the touch icon url is known.
2409 if (mTouchIconLoader != null) {
2410 mTouchIconLoader.mActivity = null;
2411 mTouchIconLoader = null;
2414 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2415 if (errorConsole != null) {
2416 errorConsole.clearErrorMessages();
2417 if (mShouldShowErrorConsole) {
2418 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2422 // Call updateIcon instead of setFavicon so the bookmark
2423 // database can be updated.
2424 updateIcon(url, favicon);
2426 if (mSettings.isTracing()) {
2429 WebAddress uri = new WebAddress(url);
2431 } catch (android.net.ParseException ex) {
2434 host = host.replace('.', '_');
2437 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2440 // Performance probe
2442 mStart = SystemClock.uptimeMillis();
2443 mProcessStart = Process.getElapsedCpuTime();
2444 long[] sysCpu = new long[7];
2445 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2447 mUserStart = sysCpu[0] + sysCpu[1];
2448 mSystemStart = sysCpu[2];
2449 mIdleStart = sysCpu[3];
2450 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2452 mUiStart = SystemClock.currentThreadTimeMillis();
2455 if (!mPageStarted) {
2456 mPageStarted = true;
2457 // if onResume() has been called, resumeWebViewTimers() does
2459 resumeWebViewTimers();
2462 // reset sync timer to avoid sync starts during loading a page
2463 CookieSyncManager.getInstance().resetSync();
2467 updateInLoadMenuItems();
2468 if (!mIsNetworkUp) {
2469 createAndShowNetworkDialog();
2471 view.setNetworkAvailable(false);
2477 public void onPageFinished(WebView view, String url) {
2478 // Reset the title and icon in case we stopped a provisional
2480 resetTitleAndIcon(view);
2482 // Update the lock icon image only once we are done loading
2483 updateLockIconToLatest();
2484 updateScreenshot(view);
2486 // Performance probe
2488 long[] sysCpu = new long[7];
2489 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2491 String uiInfo = "UI thread used "
2492 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2495 Log.d(LOGTAG, uiInfo);
2497 //The string that gets written to the log
2498 String performanceString = "It took total "
2499 + (SystemClock.uptimeMillis() - mStart)
2500 + " ms clock time to load the page."
2501 + "\nbrowser process used "
2502 + (Process.getElapsedCpuTime() - mProcessStart)
2503 + " ms, user processes used "
2504 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2505 + " ms, kernel used "
2506 + (sysCpu[2] - mSystemStart) * 10
2507 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2508 + " ms and irq took "
2509 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2510 * 10 + " ms, " + uiInfo;
2512 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2515 // strip the url to maintain consistency
2516 String newUrl = new String(url);
2517 if (newUrl.startsWith("http://www.")) {
2518 newUrl = newUrl.substring(11);
2519 } else if (newUrl.startsWith("http://")) {
2520 newUrl = newUrl.substring(7);
2521 } else if (newUrl.startsWith("https://www.")) {
2522 newUrl = newUrl.substring(12);
2523 } else if (newUrl.startsWith("https://")) {
2524 newUrl = newUrl.substring(8);
2527 Log.d(LOGTAG, newUrl + " loaded");
2530 if (sWhiteList.contains(newUrl)) {
2531 // The string that gets pushed to the statistcs
2533 performanceString = performanceString
2537 + android.os.SystemProperties
2538 .get("gsm.sim.operator.alpha");
2539 if (mWebView != null
2540 && mWebView.getContext() != null
2541 && mWebView.getContext().getSystemService(
2542 Context.CONNECTIVITY_SERVICE) != null) {
2543 ConnectivityManager cManager =
2544 (ConnectivityManager) mWebView
2545 .getContext().getSystemService(
2546 Context.CONNECTIVITY_SERVICE);
2547 NetworkInfo nInfo = cManager
2548 .getActiveNetworkInfo();
2549 if (nInfo != null) {
2550 performanceString = performanceString
2551 + "\nNetwork Type: "
2552 + nInfo.getType().toString();
2555 Checkin.logEvent(mResolver,
2556 Checkin.Events.Tag.WEBPAGE_LOAD,
2558 Log.w(LOGTAG, "pushed to the statistics service");
2567 Debug.stopMethodTracing();
2571 mPageStarted = false;
2572 // pauseWebViewTimers() will do nothing and return false if
2573 // onPause() is not called yet.
2574 if (pauseWebViewTimers()) {
2575 if (mWakeLock.isHeld()) {
2576 mHandler.removeMessages(RELEASE_WAKELOCK);
2577 mWakeLock.release();
2583 // return true if want to hijack the url to let another app to handle it
2585 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2586 if (url.startsWith(SCHEME_WTAI)) {
2587 // wtai://wp/mc;number
2588 // number=string(phone-number)
2589 if (url.startsWith(SCHEME_WTAI_MC)) {
2590 Intent intent = new Intent(Intent.ACTION_VIEW,
2591 Uri.parse(WebView.SCHEME_TEL +
2592 url.substring(SCHEME_WTAI_MC.length())));
2593 startActivity(intent);
2596 // wtai://wp/sd;dtmf
2597 // dtmf=string(dialstring)
2598 if (url.startsWith(SCHEME_WTAI_SD)) {
2600 // only send when there is active voice connection
2603 // wtai://wp/ap;number;name
2604 // number=string(phone-number)
2606 if (url.startsWith(SCHEME_WTAI_AP)) {
2612 // The "about:" schemes are internal to the browser; don't
2613 // want these to be dispatched to other apps.
2614 if (url.startsWith("about:")) {
2620 // perform generic parsing of the URI to turn it into an Intent.
2622 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2623 } catch (URISyntaxException ex) {
2624 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2628 // check whether the intent can be resolved. If not, we will see
2629 // whether we can download it from the Market.
2630 if (getPackageManager().resolveActivity(intent, 0) == null) {
2631 String packagename = intent.getPackage();
2632 if (packagename != null) {
2633 intent = new Intent(Intent.ACTION_VIEW, Uri
2634 .parse("market://search?q=pname:" + packagename));
2635 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2636 startActivity(intent);
2643 // sanitize the Intent, ensuring web pages can not bypass browser
2644 // security (only access to BROWSABLE activities).
2645 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2646 intent.setComponent(null);
2648 if (startActivityIfNeeded(intent, -1)) {
2651 } catch (ActivityNotFoundException ex) {
2652 // ignore the error. If no application can handle the URL,
2653 // eg about:blank, assume the browser can handle it.
2666 * Updates the lock icon. This method is called when we discover another
2667 * resource to be loaded for this page (for example, javascript). While
2668 * we update the icon type, we do not update the lock icon itself until
2669 * we are done loading, it is slightly more secure this way.
2672 public void onLoadResource(WebView view, String url) {
2673 if (url != null && url.length() > 0) {
2674 // It is only if the page claims to be secure
2675 // that we may have to update the lock:
2676 if (mLockIconType == LOCK_ICON_SECURE) {
2677 // If NOT a 'safe' url, change the lock to mixed content!
2678 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2679 mLockIconType = LOCK_ICON_MIXED;
2681 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2682 " updated lock icon to " + mLockIconType + " due to " + url);
2690 * Show the dialog, asking the user if they would like to continue after
2691 * an excessive number of HTTP redirects.
2694 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2695 final Message continueMsg) {
2696 new AlertDialog.Builder(BrowserActivity.this)
2697 .setTitle(R.string.browserFrameRedirect)
2698 .setMessage(R.string.browserFrame307Post)
2699 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2700 public void onClick(DialogInterface dialog, int which) {
2701 continueMsg.sendToTarget();
2703 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2704 public void onClick(DialogInterface dialog, int which) {
2705 cancelMsg.sendToTarget();
2707 .setOnCancelListener(new OnCancelListener() {
2708 public void onCancel(DialogInterface dialog) {
2709 cancelMsg.sendToTarget();
2714 // Container class for the next error dialog that needs to be
2717 public final int mTitle;
2718 public final String mDescription;
2719 public final int mError;
2720 ErrorDialog(int title, String desc, int error) {
2722 mDescription = desc;
2727 private void processNextError() {
2728 if (mQueuedErrors == null) {
2731 // The first one is currently displayed so just remove it.
2732 mQueuedErrors.removeFirst();
2733 if (mQueuedErrors.size() == 0) {
2734 mQueuedErrors = null;
2737 showError(mQueuedErrors.getFirst());
2740 private DialogInterface.OnDismissListener mDialogListener =
2741 new DialogInterface.OnDismissListener() {
2742 public void onDismiss(DialogInterface d) {
2746 private LinkedList<ErrorDialog> mQueuedErrors;
2748 private void queueError(int err, String desc) {
2749 if (mQueuedErrors == null) {
2750 mQueuedErrors = new LinkedList<ErrorDialog>();
2752 for (ErrorDialog d : mQueuedErrors) {
2753 if (d.mError == err) {
2754 // Already saw a similar error, ignore the new one.
2758 ErrorDialog errDialog = new ErrorDialog(
2759 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
2760 R.string.browserFrameFileErrorLabel :
2761 R.string.browserFrameNetworkErrorLabel,
2763 mQueuedErrors.addLast(errDialog);
2765 // Show the dialog now if the queue was empty.
2766 if (mQueuedErrors.size() == 1) {
2767 showError(errDialog);
2771 private void showError(ErrorDialog errDialog) {
2772 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2773 .setTitle(errDialog.mTitle)
2774 .setMessage(errDialog.mDescription)
2775 .setPositiveButton(R.string.ok, null)
2777 d.setOnDismissListener(mDialogListener);
2782 * Show a dialog informing the user of the network error reported by
2786 public void onReceivedError(WebView view, int errorCode,
2787 String description, String failingUrl) {
2788 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2789 errorCode != WebViewClient.ERROR_CONNECT &&
2790 errorCode != WebViewClient.ERROR_BAD_URL &&
2791 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2792 errorCode != WebViewClient.ERROR_FILE) {
2793 queueError(errorCode, description);
2795 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2796 + " " + description);
2798 // We need to reset the title after an error.
2799 resetTitleAndRevertLockIcon();
2803 * Check with the user if it is ok to resend POST data as the page they
2804 * are trying to navigate to is the result of a POST.
2807 public void onFormResubmission(WebView view, final Message dontResend,
2808 final Message resend) {
2809 new AlertDialog.Builder(BrowserActivity.this)
2810 .setTitle(R.string.browserFrameFormResubmitLabel)
2811 .setMessage(R.string.browserFrameFormResubmitMessage)
2812 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2813 public void onClick(DialogInterface dialog, int which) {
2814 resend.sendToTarget();
2816 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2817 public void onClick(DialogInterface dialog, int which) {
2818 dontResend.sendToTarget();
2820 .setOnCancelListener(new OnCancelListener() {
2821 public void onCancel(DialogInterface dialog) {
2822 dontResend.sendToTarget();
2828 * Insert the url into the visited history database.
2829 * @param url The url to be inserted.
2830 * @param isReload True if this url is being reloaded.
2831 * FIXME: Not sure what to do when reloading the page.
2834 public void doUpdateVisitedHistory(WebView view, String url,
2836 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2839 // remove "client" before updating it to the history so that it wont
2840 // show up in the auto-complete list.
2841 int index = url.indexOf("client=ms-");
2842 if (index > 0 && url.contains(".google.")) {
2843 int end = url.indexOf('&', index);
2845 url = url.substring(0, index-1).concat(url.substring(end));
2847 url = url.substring(0, index-1);
2850 Browser.updateVisitedHistory(mResolver, url, true);
2851 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2855 * Displays SSL error(s) dialog to the user.
2858 public void onReceivedSslError(
2859 final WebView view, final SslErrorHandler handler, final SslError error) {
2861 if (mSettings.showSecurityWarnings()) {
2862 final LayoutInflater factory =
2863 LayoutInflater.from(BrowserActivity.this);
2864 final View warningsView =
2865 factory.inflate(R.layout.ssl_warnings, null);
2866 final LinearLayout placeholder =
2867 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2869 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2870 LinearLayout ll = (LinearLayout)factory
2871 .inflate(R.layout.ssl_warning, null);
2872 ((TextView)ll.findViewById(R.id.warning))
2873 .setText(R.string.ssl_untrusted);
2874 placeholder.addView(ll);
2877 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2878 LinearLayout ll = (LinearLayout)factory
2879 .inflate(R.layout.ssl_warning, null);
2880 ((TextView)ll.findViewById(R.id.warning))
2881 .setText(R.string.ssl_mismatch);
2882 placeholder.addView(ll);
2885 if (error.hasError(SslError.SSL_EXPIRED)) {
2886 LinearLayout ll = (LinearLayout)factory
2887 .inflate(R.layout.ssl_warning, null);
2888 ((TextView)ll.findViewById(R.id.warning))
2889 .setText(R.string.ssl_expired);
2890 placeholder.addView(ll);
2893 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2894 LinearLayout ll = (LinearLayout)factory
2895 .inflate(R.layout.ssl_warning, null);
2896 ((TextView)ll.findViewById(R.id.warning))
2897 .setText(R.string.ssl_not_yet_valid);
2898 placeholder.addView(ll);
2901 new AlertDialog.Builder(BrowserActivity.this)
2902 .setTitle(R.string.security_warning)
2903 .setIcon(android.R.drawable.ic_dialog_alert)
2904 .setView(warningsView)
2905 .setPositiveButton(R.string.ssl_continue,
2906 new DialogInterface.OnClickListener() {
2907 public void onClick(DialogInterface dialog, int whichButton) {
2911 .setNeutralButton(R.string.view_certificate,
2912 new DialogInterface.OnClickListener() {
2913 public void onClick(DialogInterface dialog, int whichButton) {
2914 showSSLCertificateOnError(view, handler, error);
2917 .setNegativeButton(R.string.cancel,
2918 new DialogInterface.OnClickListener() {
2919 public void onClick(DialogInterface dialog, int whichButton) {
2921 BrowserActivity.this.resetTitleAndRevertLockIcon();
2924 .setOnCancelListener(
2925 new DialogInterface.OnCancelListener() {
2926 public void onCancel(DialogInterface dialog) {
2928 BrowserActivity.this.resetTitleAndRevertLockIcon();
2938 * Handles an HTTP authentication request.
2940 * @param handler The authentication handler
2941 * @param host The host
2942 * @param realm The realm
2945 public void onReceivedHttpAuthRequest(WebView view,
2946 final HttpAuthHandler handler, final String host, final String realm) {
2947 String username = null;
2948 String password = null;
2950 boolean reuseHttpAuthUsernamePassword =
2951 handler.useHttpAuthUsernamePassword();
2953 if (reuseHttpAuthUsernamePassword &&
2954 (mTabControl.getCurrentWebView() != null)) {
2955 String[] credentials =
2956 mTabControl.getCurrentWebView()
2957 .getHttpAuthUsernamePassword(host, realm);
2958 if (credentials != null && credentials.length == 2) {
2959 username = credentials[0];
2960 password = credentials[1];
2964 if (username != null && password != null) {
2965 handler.proceed(username, password);
2967 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2972 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2974 // only check shortcut key when MENU is held
2975 return getWindow().isShortcutKey(event.getKeyCode(), event);
2982 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2983 if (view != mTabControl.getCurrentTopWebView()) {
2986 if (event.isDown()) {
2987 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2989 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2994 //--------------------------------------------------------------------------
2995 // WebChromeClient implementation
2996 //--------------------------------------------------------------------------
2998 /* package */ WebChromeClient getWebChromeClient() {
2999 return mWebChromeClient;
3002 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3003 // Helper method to create a new tab or sub window.
3004 private void createWindow(final boolean dialog, final Message msg) {
3006 mTabControl.createSubWindow();
3007 final TabControl.Tab t = mTabControl.getCurrentTab();
3009 WebView.WebViewTransport transport =
3010 (WebView.WebViewTransport) msg.obj;
3011 transport.setWebView(t.getSubWebView());
3014 final TabControl.Tab parent = mTabControl.getCurrentTab();
3015 final TabControl.Tab newTab
3016 = openTabAndShow(EMPTY_URL_DATA, false, null);
3017 if (newTab != parent) {
3018 parent.addChildTab(newTab);
3020 WebView.WebViewTransport transport =
3021 (WebView.WebViewTransport) msg.obj;
3022 transport.setWebView(mTabControl.getCurrentWebView());
3028 public boolean onCreateWindow(WebView view, final boolean dialog,
3029 final boolean userGesture, final Message resultMsg) {
3030 // Short-circuit if we can't create any more tabs or sub windows.
3031 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3032 new AlertDialog.Builder(BrowserActivity.this)
3033 .setTitle(R.string.too_many_subwindows_dialog_title)
3034 .setIcon(android.R.drawable.ic_dialog_alert)
3035 .setMessage(R.string.too_many_subwindows_dialog_message)
3036 .setPositiveButton(R.string.ok, null)
3039 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3040 new AlertDialog.Builder(BrowserActivity.this)
3041 .setTitle(R.string.too_many_windows_dialog_title)
3042 .setIcon(android.R.drawable.ic_dialog_alert)
3043 .setMessage(R.string.too_many_windows_dialog_message)
3044 .setPositiveButton(R.string.ok, null)
3049 // Short-circuit if this was a user gesture.
3051 createWindow(dialog, resultMsg);
3055 // Allow the popup and create the appropriate window.
3056 final AlertDialog.OnClickListener allowListener =
3057 new AlertDialog.OnClickListener() {
3058 public void onClick(DialogInterface d,
3060 createWindow(dialog, resultMsg);
3064 // Block the popup by returning a null WebView.
3065 final AlertDialog.OnClickListener blockListener =
3066 new AlertDialog.OnClickListener() {
3067 public void onClick(DialogInterface d, int which) {
3068 resultMsg.sendToTarget();
3072 // Build a confirmation dialog to display to the user.
3073 final AlertDialog d =
3074 new AlertDialog.Builder(BrowserActivity.this)
3075 .setTitle(R.string.attention)
3076 .setIcon(android.R.drawable.ic_dialog_alert)
3077 .setMessage(R.string.popup_window_attempt)
3078 .setPositiveButton(R.string.allow, allowListener)
3079 .setNegativeButton(R.string.block, blockListener)
3080 .setCancelable(false)
3083 // Show the confirmation dialog.
3089 public void onCloseWindow(WebView window) {
3090 final TabControl.Tab current = mTabControl.getCurrentTab();
3091 final TabControl.Tab parent = current.getParentTab();
3092 if (parent != null) {
3093 // JavaScript can only close popup window.
3094 switchToTab(mTabControl.getTabIndex(parent));
3095 // Now we need to close the window
3101 public void onProgressChanged(WebView view, int newProgress) {
3102 mTitleBar.setProgress(newProgress);
3103 if (mFakeTitleBar != null) {
3104 mFakeTitleBar.setProgress(newProgress);
3107 if (newProgress == 100) {
3108 // onProgressChanged() is called for sub-frame too while
3109 // onPageFinished() is only called for the main frame. sync
3110 // cookie and cache promptly here.
3111 CookieSyncManager.getInstance().sync();
3114 updateInLoadMenuItems();
3115 // If the options menu is open, leave the title bar
3116 if (!mOptionsMenuOpen || !mIconView) {
3120 } else if (!mInLoad) {
3121 // onPageFinished may have already been called but a subframe
3122 // is still loading and updating the progress. Reset mInLoad
3123 // and update the menu items.
3125 updateInLoadMenuItems();
3126 if (!mOptionsMenuOpen || mIconView) {
3127 // This page has begun to load, so show the title bar
3134 public void onReceivedTitle(WebView view, String title) {
3135 String url = view.getUrl();
3137 // here, if url is null, we want to reset the title
3138 setUrlTitle(url, title);
3141 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3144 // See if we can find the current url in our history database and
3145 // add the new title to it.
3146 if (url.startsWith("http://www.")) {
3147 url = url.substring(11);
3148 } else if (url.startsWith("http://")) {
3149 url = url.substring(4);
3153 String [] selArgs = new String[] { url };
3155 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3156 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3157 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3158 Browser.HISTORY_PROJECTION, where, selArgs, null);
3159 if (c.moveToFirst()) {
3160 // Current implementation of database only has one entry per
3162 ContentValues map = new ContentValues();
3163 map.put(Browser.BookmarkColumns.TITLE, title);
3164 mResolver.update(Browser.BOOKMARKS_URI, map,
3165 "_id = " + c.getInt(0), null);
3168 } catch (IllegalStateException e) {
3169 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3170 } catch (SQLiteException ex) {
3171 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3176 public void onReceivedIcon(WebView view, Bitmap icon) {
3177 updateIcon(view, icon);
3181 public void onReceivedTouchIconUrl(WebView view, String url,
3182 boolean precomposed) {
3183 final ContentResolver cr = getContentResolver();
3185 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
3186 view.getOriginalUrl(), view.getUrl(), true);
3188 if (c.getCount() > 0) {
3189 // Let precomposed icons take precedence over non-composed
3191 if (precomposed && mTouchIconLoader != null) {
3192 mTouchIconLoader.cancel(false);
3193 mTouchIconLoader = null;
3195 // Have only one async task at a time.
3196 if (mTouchIconLoader == null) {
3197 mTouchIconLoader = new DownloadTouchIcon(
3198 BrowserActivity.this, cr, c, view);
3199 mTouchIconLoader.execute(url);
3208 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
3209 if (mCustomView != null)
3212 // Add the custom view to its container.
3213 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3215 mCustomViewCallback = callback;
3216 // Save the menu state and set it to empty while the custom
3218 mOldMenuState = mMenuState;
3219 mMenuState = EMPTY_MENU;
3220 // Hide the content view.
3221 mContentView.setVisibility(View.GONE);
3222 // Finally show the custom view container.
3223 mCustomViewContainer.setVisibility(View.VISIBLE);
3224 mCustomViewContainer.bringToFront();
3228 public void onHideCustomView() {
3229 if (mCustomView == null)
3232 // Hide the custom view.
3233 mCustomView.setVisibility(View.GONE);
3234 // Remove the custom view from its container.
3235 mCustomViewContainer.removeView(mCustomView);
3237 // Reset the old menu state.
3238 mMenuState = mOldMenuState;
3239 mOldMenuState = EMPTY_MENU;
3240 mCustomViewContainer.setVisibility(View.GONE);
3241 mCustomViewCallback.onCustomViewHidden();
3242 // Show the content view.
3243 mContentView.setVisibility(View.VISIBLE);
3247 * The origin has exceeded its database quota.
3248 * @param url the URL that exceeded the quota
3249 * @param databaseIdentifier the identifier of the database on
3250 * which the transaction that caused the quota overflow was run
3251 * @param currentQuota the current quota for the origin.
3252 * @param estimatedSize the estimated size of the database.
3253 * @param totalUsedQuota is the sum of all origins' quota.
3254 * @param quotaUpdater The callback to run when a decision to allow or
3255 * deny quota has been made. Don't forget to call this!
3258 public void onExceededDatabaseQuota(String url,
3259 String databaseIdentifier, long currentQuota, long estimatedSize,
3260 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3261 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3262 url, databaseIdentifier, currentQuota, estimatedSize,
3263 totalUsedQuota, quotaUpdater);
3267 * The Application Cache has exceeded its max size.
3268 * @param spaceNeeded is the amount of disk space that would be needed
3269 * in order for the last appcache operation to succeed.
3270 * @param totalUsedQuota is the sum of all origins' quota.
3271 * @param quotaUpdater A callback to inform the WebCore thread that a new
3272 * app cache size is available. This callback must always be executed at
3273 * some point to ensure that the sleeping WebCore thread is woken up.
3276 public void onReachedMaxAppCacheSize(long spaceNeeded,
3277 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3278 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3279 spaceNeeded, totalUsedQuota, quotaUpdater);
3283 * Instructs the browser to show a prompt to ask the user to set the
3284 * Geolocation permission state for the specified origin.
3285 * @param origin The origin for which Geolocation permissions are
3287 * @param callback The callback to call once the user has set the
3288 * Geolocation permission state.
3291 public void onGeolocationPermissionsShowPrompt(String origin,
3292 GeolocationPermissions.Callback callback) {
3293 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3298 * Instructs the browser to hide the Geolocation permissions prompt.
3301 public void onGeolocationPermissionsHidePrompt() {
3302 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3305 /* Adds a JavaScript error message to the system log.
3306 * @param message The error message to report.
3307 * @param lineNumber The line number of the error.
3308 * @param sourceID The name of the source file that caused the error.
3311 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3312 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3313 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3314 if (mShouldShowErrorConsole &&
3315 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3316 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3318 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
3322 * Ask the browser for an icon to represent a <video> element.
3323 * This icon will be used if the Web page did not specify a poster attribute.
3325 * @return Bitmap The icon or null if no such icon is available.
3326 * @hide pending API Council approval
3329 public Bitmap getDefaultVideoPoster() {
3330 if (mDefaultVideoPoster == null) {
3331 mDefaultVideoPoster = BitmapFactory.decodeResource(
3332 getResources(), R.drawable.default_video_poster);
3334 return mDefaultVideoPoster;
3338 * Ask the host application for a custom progress view to show while
3339 * a <video> is loading.
3341 * @return View The progress view.
3342 * @hide pending API Council approval
3345 public View getVideoLoadingProgressView() {
3346 if (mVideoProgressView == null) {
3347 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
3348 mVideoProgressView = inflater.inflate(R.layout.video_loading_progress, null);
3350 return mVideoProgressView;
3355 * Notify the host application a download should be done, or that
3356 * the data should be streamed if a streaming viewer is available.
3357 * @param url The full url to the content that should be downloaded
3358 * @param contentDisposition Content-disposition http header, if
3360 * @param mimetype The mimetype of the content reported by the server
3361 * @param contentLength The file size reported by the server
3363 public void onDownloadStart(String url, String userAgent,
3364 String contentDisposition, String mimetype, long contentLength) {
3365 // if we're dealing wih A/V content that's not explicitly marked
3366 // for download, check if it's streamable.
3367 if (contentDisposition == null
3368 || !contentDisposition.regionMatches(
3369 true, 0, "attachment", 0, 10)) {
3370 // query the package manager to see if there's a registered handler
3372 Intent intent = new Intent(Intent.ACTION_VIEW);
3373 intent.setDataAndType(Uri.parse(url), mimetype);
3374 ResolveInfo info = getPackageManager().resolveActivity(intent,
3375 PackageManager.MATCH_DEFAULT_ONLY);
3377 ComponentName myName = getComponentName();
3378 // If we resolved to ourselves, we don't want to attempt to
3379 // load the url only to try and download it again.
3380 if (!myName.getPackageName().equals(
3381 info.activityInfo.packageName)
3382 || !myName.getClassName().equals(
3383 info.activityInfo.name)) {
3384 // someone (other than us) knows how to handle this mime
3385 // type with this scheme, don't download.
3387 startActivity(intent);
3389 } catch (ActivityNotFoundException ex) {
3391 Log.d(LOGTAG, "activity not found for " + mimetype
3392 + " over " + Uri.parse(url).getScheme(),
3395 // Best behavior is to fall back to a download in this
3401 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3405 * Notify the host application a download should be done, even if there
3406 * is a streaming viewer available for thise type.
3407 * @param url The full url to the content that should be downloaded
3408 * @param contentDisposition Content-disposition http header, if
3410 * @param mimetype The mimetype of the content reported by the server
3411 * @param contentLength The file size reported by the server
3413 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3414 String contentDisposition, String mimetype, long contentLength) {
3416 String filename = URLUtil.guessFileName(url,
3417 contentDisposition, mimetype);
3419 // Check to see if we have an SDCard
3420 String status = Environment.getExternalStorageState();
3421 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3425 // Check to see if the SDCard is busy, same as the music app
3426 if (status.equals(Environment.MEDIA_SHARED)) {
3427 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3428 title = R.string.download_sdcard_busy_dlg_title;
3430 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3431 title = R.string.download_no_sdcard_dlg_title;
3434 new AlertDialog.Builder(this)
3436 .setIcon(android.R.drawable.ic_dialog_alert)
3438 .setPositiveButton(R.string.ok, null)
3443 // java.net.URI is a lot stricter than KURL so we have to undo
3444 // KURL's percent-encoding and redo the encoding using java.net.URI.
3447 // Undo the percent-encoding that KURL may have done.
3448 String newUrl = new String(URLUtil.decode(url.getBytes()));
3449 // Parse the url into pieces
3450 WebAddress w = new WebAddress(newUrl);
3452 String query = null;
3453 String path = w.mPath;
3454 // Break the path into path, query, and fragment
3455 if (path.length() > 0) {
3456 // Strip the fragment
3457 int idx = path.lastIndexOf('#');
3459 frag = path.substring(idx + 1);
3460 path = path.substring(0, idx);
3462 idx = path.lastIndexOf('?');
3464 query = path.substring(idx + 1);
3465 path = path.substring(0, idx);
3468 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3470 } catch (Exception e) {
3471 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3475 // XXX: Have to use the old url since the cookies were stored using the
3476 // old percent-encoded url.
3477 String cookies = CookieManager.getInstance().getCookie(url);
3479 ContentValues values = new ContentValues();
3480 values.put(Downloads.COLUMN_URI, uri.toString());
3481 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3482 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3483 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
3485 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
3486 BrowserDownloadPage.class.getCanonicalName());
3487 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3488 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3489 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3490 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
3491 if (contentLength > 0) {
3492 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
3494 if (mimetype == null) {
3495 // We must have long pressed on a link or image to download it. We
3496 // are not sure of the mimetype in this case, so do a head request
3497 new FetchUrlMimeType(this).execute(values);
3499 final Uri contentUri =
3500 getContentResolver().insert(Downloads.CONTENT_URI, values);
3501 viewDownloads(contentUri);
3507 * Resets the lock icon. This method is called when we start a new load and
3508 * know the url to be loaded.
3510 private void resetLockIcon(String url) {
3511 // Save the lock-icon state (we revert to it if the load gets cancelled)
3514 mLockIconType = LOCK_ICON_UNSECURE;
3515 if (URLUtil.isHttpsUrl(url)) {
3516 mLockIconType = LOCK_ICON_SECURE;
3518 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3519 " reset lock icon to " + mLockIconType);
3523 updateLockIconImage(LOCK_ICON_UNSECURE);
3526 /* package */ void setLockIconType(int type) {
3527 mLockIconType = type;
3530 /* package */ int getLockIconType() {
3531 return mLockIconType;
3534 /* package */ void setPrevLockType(int type) {
3535 mPrevLockType = type;
3538 /* package */ int getPrevLockType() {
3539 return mPrevLockType;
3543 * Update the lock icon to correspond to our latest state.
3545 /* package */ void updateLockIconToLatest() {
3546 updateLockIconImage(mLockIconType);
3550 * Updates the lock-icon image in the title-bar.
3552 private void updateLockIconImage(int lockIconType) {
3554 if (lockIconType == LOCK_ICON_SECURE) {
3556 } else if (lockIconType == LOCK_ICON_MIXED) {
3559 mTitleBar.setLock(d);
3560 if (mFakeTitleBar != null) {
3561 mFakeTitleBar.setLock(d);
3566 * Displays a page-info dialog.
3567 * @param tab The tab to show info about
3568 * @param fromShowSSLCertificateOnError The flag that indicates whether
3569 * this dialog was opened from the SSL-certificate-on-error dialog or
3570 * not. This is important, since we need to know whether to return to
3571 * the parent dialog or simply dismiss.
3573 private void showPageInfo(final TabControl.Tab tab,
3574 final boolean fromShowSSLCertificateOnError) {
3575 final LayoutInflater factory = LayoutInflater
3578 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3580 final WebView view = tab.getWebView();
3583 String title = null;
3587 title = tab.getTitle();
3588 } else if (view == mTabControl.getCurrentWebView()) {
3589 // Use the cached title and url if this is the current WebView
3593 url = view.getUrl();
3594 title = view.getTitle();
3600 if (title == null) {
3604 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3605 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3607 mPageInfoView = tab;
3608 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3610 AlertDialog.Builder alertDialogBuilder =
3611 new AlertDialog.Builder(this)
3612 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3613 .setView(pageInfoView)
3616 new DialogInterface.OnClickListener() {
3617 public void onClick(DialogInterface dialog,
3619 mPageInfoDialog = null;
3620 mPageInfoView = null;
3621 mPageInfoFromShowSSLCertificateOnError = null;
3623 // if we came here from the SSL error dialog
3624 if (fromShowSSLCertificateOnError) {
3625 // go back to the SSL error dialog
3626 showSSLCertificateOnError(
3627 mSSLCertificateOnErrorView,
3628 mSSLCertificateOnErrorHandler,
3629 mSSLCertificateOnErrorError);
3633 .setOnCancelListener(
3634 new DialogInterface.OnCancelListener() {
3635 public void onCancel(DialogInterface dialog) {
3636 mPageInfoDialog = null;
3637 mPageInfoView = null;
3638 mPageInfoFromShowSSLCertificateOnError = null;
3640 // if we came here from the SSL error dialog
3641 if (fromShowSSLCertificateOnError) {
3642 // go back to the SSL error dialog
3643 showSSLCertificateOnError(
3644 mSSLCertificateOnErrorView,
3645 mSSLCertificateOnErrorHandler,
3646 mSSLCertificateOnErrorError);
3651 // if we have a main top-level page SSL certificate set or a certificate
3653 if (fromShowSSLCertificateOnError ||
3654 (view != null && view.getCertificate() != null)) {
3655 // add a 'View Certificate' button
3656 alertDialogBuilder.setNeutralButton(
3657 R.string.view_certificate,
3658 new DialogInterface.OnClickListener() {
3659 public void onClick(DialogInterface dialog,
3661 mPageInfoDialog = null;
3662 mPageInfoView = null;
3663 mPageInfoFromShowSSLCertificateOnError = null;
3665 // if we came here from the SSL error dialog
3666 if (fromShowSSLCertificateOnError) {
3667 // go back to the SSL error dialog
3668 showSSLCertificateOnError(
3669 mSSLCertificateOnErrorView,
3670 mSSLCertificateOnErrorHandler,
3671 mSSLCertificateOnErrorError);
3673 // otherwise, display the top-most certificate from
3675 if (view.getCertificate() != null) {
3676 showSSLCertificate(tab);
3683 mPageInfoDialog = alertDialogBuilder.show();
3687 * Displays the main top-level page SSL certificate dialog
3688 * (accessible from the Page-Info dialog).
3689 * @param tab The tab to show certificate for.
3691 private void showSSLCertificate(final TabControl.Tab tab) {
3692 final View certificateView =
3693 inflateCertificateView(tab.getWebView().getCertificate());
3694 if (certificateView == null) {
3698 LayoutInflater factory = LayoutInflater.from(this);
3700 final LinearLayout placeholder =
3701 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3703 LinearLayout ll = (LinearLayout) factory.inflate(
3704 R.layout.ssl_success, placeholder);
3705 ((TextView)ll.findViewById(R.id.success))
3706 .setText(R.string.ssl_certificate_is_valid);
3708 mSSLCertificateView = tab;
3709 mSSLCertificateDialog =
3710 new AlertDialog.Builder(this)
3711 .setTitle(R.string.ssl_certificate).setIcon(
3712 R.drawable.ic_dialog_browser_certificate_secure)
3713 .setView(certificateView)
3714 .setPositiveButton(R.string.ok,
3715 new DialogInterface.OnClickListener() {
3716 public void onClick(DialogInterface dialog,
3718 mSSLCertificateDialog = null;
3719 mSSLCertificateView = null;
3721 showPageInfo(tab, false);
3724 .setOnCancelListener(
3725 new DialogInterface.OnCancelListener() {
3726 public void onCancel(DialogInterface dialog) {
3727 mSSLCertificateDialog = null;
3728 mSSLCertificateView = null;
3730 showPageInfo(tab, false);
3737 * Displays the SSL error certificate dialog.
3738 * @param view The target web-view.
3739 * @param handler The SSL error handler responsible for cancelling the
3740 * connection that resulted in an SSL error or proceeding per user request.
3741 * @param error The SSL error object.
3743 private void showSSLCertificateOnError(
3744 final WebView view, final SslErrorHandler handler, final SslError error) {
3746 final View certificateView =
3747 inflateCertificateView(error.getCertificate());
3748 if (certificateView == null) {
3752 LayoutInflater factory = LayoutInflater.from(this);
3754 final LinearLayout placeholder =
3755 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3757 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3758 LinearLayout ll = (LinearLayout)factory
3759 .inflate(R.layout.ssl_warning, placeholder);
3760 ((TextView)ll.findViewById(R.id.warning))
3761 .setText(R.string.ssl_untrusted);
3764 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3765 LinearLayout ll = (LinearLayout)factory
3766 .inflate(R.layout.ssl_warning, placeholder);
3767 ((TextView)ll.findViewById(R.id.warning))
3768 .setText(R.string.ssl_mismatch);
3771 if (error.hasError(SslError.SSL_EXPIRED)) {
3772 LinearLayout ll = (LinearLayout)factory
3773 .inflate(R.layout.ssl_warning, placeholder);
3774 ((TextView)ll.findViewById(R.id.warning))
3775 .setText(R.string.ssl_expired);
3778 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3779 LinearLayout ll = (LinearLayout)factory
3780 .inflate(R.layout.ssl_warning, placeholder);
3781 ((TextView)ll.findViewById(R.id.warning))
3782 .setText(R.string.ssl_not_yet_valid);
3785 mSSLCertificateOnErrorHandler = handler;
3786 mSSLCertificateOnErrorView = view;
3787 mSSLCertificateOnErrorError = error;
3788 mSSLCertificateOnErrorDialog =
3789 new AlertDialog.Builder(this)
3790 .setTitle(R.string.ssl_certificate).setIcon(
3791 R.drawable.ic_dialog_browser_certificate_partially_secure)
3792 .setView(certificateView)
3793 .setPositiveButton(R.string.ok,
3794 new DialogInterface.OnClickListener() {
3795 public void onClick(DialogInterface dialog,
3797 mSSLCertificateOnErrorDialog = null;
3798 mSSLCertificateOnErrorView = null;
3799 mSSLCertificateOnErrorHandler = null;
3800 mSSLCertificateOnErrorError = null;
3802 mWebViewClient.onReceivedSslError(
3803 view, handler, error);
3806 .setNeutralButton(R.string.page_info_view,
3807 new DialogInterface.OnClickListener() {
3808 public void onClick(DialogInterface dialog,
3810 mSSLCertificateOnErrorDialog = null;
3812 // do not clear the dialog state: we will
3813 // need to show the dialog again once the
3814 // user is done exploring the page-info details
3816 showPageInfo(mTabControl.getTabFromView(view),
3820 .setOnCancelListener(
3821 new DialogInterface.OnCancelListener() {
3822 public void onCancel(DialogInterface dialog) {
3823 mSSLCertificateOnErrorDialog = null;
3824 mSSLCertificateOnErrorView = null;
3825 mSSLCertificateOnErrorHandler = null;
3826 mSSLCertificateOnErrorError = null;
3828 mWebViewClient.onReceivedSslError(
3829 view, handler, error);
3836 * Inflates the SSL certificate view (helper method).
3837 * @param certificate The SSL certificate.
3838 * @return The resultant certificate view with issued-to, issued-by,
3839 * issued-on, expires-on, and possibly other fields set.
3840 * If the input certificate is null, returns null.
3842 private View inflateCertificateView(SslCertificate certificate) {
3843 if (certificate == null) {
3847 LayoutInflater factory = LayoutInflater.from(this);
3849 View certificateView = factory.inflate(
3850 R.layout.ssl_certificate, null);
3853 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3854 if (issuedTo != null) {
3855 ((TextView) certificateView.findViewById(R.id.to_common))
3856 .setText(issuedTo.getCName());
3857 ((TextView) certificateView.findViewById(R.id.to_org))
3858 .setText(issuedTo.getOName());
3859 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3860 .setText(issuedTo.getUName());
3864 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3865 if (issuedBy != null) {
3866 ((TextView) certificateView.findViewById(R.id.by_common))
3867 .setText(issuedBy.getCName());
3868 ((TextView) certificateView.findViewById(R.id.by_org))
3869 .setText(issuedBy.getOName());
3870 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3871 .setText(issuedBy.getUName());
3875 String issuedOn = reformatCertificateDate(
3876 certificate.getValidNotBefore());
3877 ((TextView) certificateView.findViewById(R.id.issued_on))
3881 String expiresOn = reformatCertificateDate(
3882 certificate.getValidNotAfter());
3883 ((TextView) certificateView.findViewById(R.id.expires_on))
3884 .setText(expiresOn);
3886 return certificateView;
3890 * Re-formats the certificate date (Date.toString()) string to
3891 * a properly localized date string.
3892 * @return Properly localized version of the certificate date string and
3893 * the original certificate date string if fails to localize.
3894 * If the original string is null, returns an empty string "".
3896 private String reformatCertificateDate(String certificateDate) {
3897 String reformattedDate = null;
3899 if (certificateDate != null) {
3902 date = java.text.DateFormat.getInstance().parse(certificateDate);
3903 } catch (ParseException e) {
3909 DateFormat.getDateFormat(this).format(date);
3913 return reformattedDate != null ? reformattedDate :
3914 (certificateDate != null ? certificateDate : "");
3918 * Displays an http-authentication dialog.
3920 private void showHttpAuthentication(final HttpAuthHandler handler,
3921 final String host, final String realm, final String title,
3922 final String name, final String password, int focusId) {
3923 LayoutInflater factory = LayoutInflater.from(this);
3924 final View v = factory
3925 .inflate(R.layout.http_authentication, null);
3927 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3929 if (password != null) {
3930 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3933 String titleText = title;
3934 if (titleText == null) {
3935 titleText = getText(R.string.sign_in_to).toString().replace(
3936 "%s1", host).replace("%s2", realm);
3939 mHttpAuthHandler = handler;
3940 AlertDialog dialog = new AlertDialog.Builder(this)
3941 .setTitle(titleText)
3942 .setIcon(android.R.drawable.ic_dialog_alert)
3944 .setPositiveButton(R.string.action,
3945 new DialogInterface.OnClickListener() {
3946 public void onClick(DialogInterface dialog,
3948 String nm = ((EditText) v
3949 .findViewById(R.id.username_edit))
3950 .getText().toString();
3951 String pw = ((EditText) v
3952 .findViewById(R.id.password_edit))
3953 .getText().toString();
3954 BrowserActivity.this.setHttpAuthUsernamePassword
3955 (host, realm, nm, pw);
3956 handler.proceed(nm, pw);
3957 mHttpAuthenticationDialog = null;
3958 mHttpAuthHandler = null;
3960 .setNegativeButton(R.string.cancel,
3961 new DialogInterface.OnClickListener() {
3962 public void onClick(DialogInterface dialog,
3965 BrowserActivity.this.resetTitleAndRevertLockIcon();
3966 mHttpAuthenticationDialog = null;
3967 mHttpAuthHandler = null;
3969 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3970 public void onCancel(DialogInterface dialog) {
3972 BrowserActivity.this.resetTitleAndRevertLockIcon();
3973 mHttpAuthenticationDialog = null;
3974 mHttpAuthHandler = null;
3977 // Make the IME appear when the dialog is displayed if applicable.
3978 dialog.getWindow().setSoftInputMode(
3979 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3982 dialog.findViewById(focusId).requestFocus();
3984 v.findViewById(R.id.username_edit).requestFocus();
3986 mHttpAuthenticationDialog = dialog;
3989 public int getProgress() {
3990 WebView w = mTabControl.getCurrentWebView();
3992 return w.getProgress();
3999 * Set HTTP authentication password.
4001 * @param host The host for the password
4002 * @param realm The realm for the password
4003 * @param username The username for the password. If it is null, it means
4004 * password can't be saved.
4005 * @param password The password
4007 public void setHttpAuthUsernamePassword(String host, String realm,
4010 WebView w = mTabControl.getCurrentWebView();
4012 w.setHttpAuthUsernamePassword(host, realm, username, password);
4017 * connectivity manager says net has come or gone... inform the user
4018 * @param up true if net has come up, false if net has gone down
4020 public void onNetworkToggle(boolean up) {
4021 if (up == mIsNetworkUp) {
4024 mIsNetworkUp = true;
4025 if (mAlertDialog != null) {
4026 mAlertDialog.cancel();
4027 mAlertDialog = null;
4030 mIsNetworkUp = false;
4032 createAndShowNetworkDialog();
4035 WebView w = mTabControl.getCurrentWebView();
4037 w.setNetworkAvailable(up);
4041 // This method shows the network dialog alerting the user that the net is
4042 // down. It will only show the dialog if mAlertDialog is null.
4043 private void createAndShowNetworkDialog() {
4044 if (mAlertDialog == null) {
4045 mAlertDialog = new AlertDialog.Builder(this)
4046 .setTitle(R.string.loadSuspendedTitle)
4047 .setMessage(R.string.loadSuspended)
4048 .setPositiveButton(R.string.ok, null)
4054 protected void onActivityResult(int requestCode, int resultCode,
4056 switch (requestCode) {
4058 if (resultCode == RESULT_OK && intent != null) {
4059 String data = intent.getAction();
4060 Bundle extras = intent.getExtras();
4061 if (extras != null && extras.getBoolean("new_window", false)) {
4064 final TabControl.Tab currentTab =
4065 mTabControl.getCurrentTab();
4066 dismissSubWindow(currentTab);
4067 if (data != null && data.length() != 0) {
4068 getTopWindow().loadUrl(data);
4076 getTopWindow().requestFocus();
4080 * This method is called as a result of the user selecting the options
4081 * menu to see the download window, or when a download changes state. It
4082 * shows the download window ontop of the current window.
4084 /* package */ void viewDownloads(Uri downloadRecord) {
4085 Intent intent = new Intent(this,
4086 BrowserDownloadPage.class);
4087 intent.setData(downloadRecord);
4088 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4094 * @param startWithHistory If true, open starting on the history tab.
4095 * Otherwise, start with the bookmarks tab.
4097 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
4098 WebView current = mTabControl.getCurrentWebView();
4099 if (current == null) {
4102 Intent intent = new Intent(this,
4103 CombinedBookmarkHistoryActivity.class);
4104 String title = current.getTitle();
4105 String url = current.getUrl();
4106 Bitmap thumbnail = createScreenshot(current);
4108 // Just in case the user opens bookmarks before a page finishes loading
4109 // so the current history item, and therefore the page, is null.
4111 url = mLastEnteredUrl;
4114 url = mSettings.getHomePage();
4117 // In case the web page has not yet received its associated title.
4118 if (title == null) {
4121 intent.putExtra("title", title);
4122 intent.putExtra("url", url);
4123 intent.putExtra("thumbnail", thumbnail);
4124 // Disable opening in a new window if we have maxed out the windows
4125 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4126 >= TabControl.MAX_TABS);
4127 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
4128 if (startWithHistory) {
4129 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4130 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4132 startActivityForResult(intent, COMBO_PAGE);
4135 // Called when loading from context menu or LOAD_URL message
4136 private void loadURL(WebView view, String url) {
4137 // In case the user enters nothing.
4138 if (url != null && url.length() != 0 && view != null) {
4139 url = smartUrlFilter(url);
4140 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4146 private String smartUrlFilter(Uri inUri) {
4147 if (inUri != null) {
4148 return smartUrlFilter(inUri.toString());
4156 int getWindowCount(){
4157 if(mTabControl != null){
4158 return mTabControl.getTabCount();
4163 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4164 "(?i)" + // switch on case insensitive matching
4165 "(" + // begin group for schema
4166 "(?:http|https|file):\\/\\/" +
4167 "|(?:inline|data|about|content|javascript):" +
4172 * Attempts to determine whether user input is a URL or search
4173 * terms. Anything with a space is passed to search.
4175 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4176 * "Http://" converts to "http://"
4178 * @return Original or modified URL
4181 String smartUrlFilter(String url) {
4183 String inUrl = url.trim();
4184 boolean hasSpace = inUrl.indexOf(' ') != -1;
4186 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4187 if (matcher.matches()) {
4188 // force scheme to lowercase
4189 String scheme = matcher.group(1);
4190 String lcScheme = scheme.toLowerCase();
4191 if (!lcScheme.equals(scheme)) {
4192 inUrl = lcScheme + matcher.group(2);
4195 inUrl = inUrl.replace(" ", "%20");
4200 // FIXME: Is this the correct place to add to searches?
4201 // what if someone else calls this function?
4202 int shortcut = parseUrlShortcut(inUrl);
4203 if (shortcut != SHORTCUT_INVALID) {
4204 Browser.addSearchUrl(mResolver, inUrl);
4205 String query = inUrl.substring(2);
4207 case SHORTCUT_GOOGLE_SEARCH:
4208 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
4209 case SHORTCUT_WIKIPEDIA_SEARCH:
4210 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4211 case SHORTCUT_DICTIONARY_SEARCH:
4212 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4213 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
4214 // FIXME: we need location in this case
4215 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
4219 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4220 return URLUtil.guessUrl(inUrl);
4224 Browser.addSearchUrl(mResolver, inUrl);
4225 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
4228 /* package */ void setShouldShowErrorConsole(boolean flag) {
4229 if (flag == mShouldShowErrorConsole) {
4234 mShouldShowErrorConsole = flag;
4236 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4239 // Setting the show state of the console will cause it's the layout to be inflated.
4240 if (errorConsole.numberOfErrors() > 0) {
4241 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4243 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4246 // Now we can add it to the main view.
4247 mErrorConsoleContainer.addView(errorConsole,
4248 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4249 ViewGroup.LayoutParams.WRAP_CONTENT));
4251 mErrorConsoleContainer.removeView(errorConsole);
4256 final static int LOCK_ICON_UNSECURE = 0;
4257 final static int LOCK_ICON_SECURE = 1;
4258 final static int LOCK_ICON_MIXED = 2;
4260 private int mLockIconType = LOCK_ICON_UNSECURE;
4261 private int mPrevLockType = LOCK_ICON_UNSECURE;
4263 private BrowserSettings mSettings;
4264 private TabControl mTabControl;
4265 private ContentResolver mResolver;
4266 private FrameLayout mContentView;
4267 private View mCustomView;
4268 private FrameLayout mCustomViewContainer;
4269 private WebChromeClient.CustomViewCallback mCustomViewCallback;
4271 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4272 // view, we should rewrite this.
4273 private int mCurrentMenuState = 0;
4274 private int mMenuState = R.id.MAIN_MENU;
4275 private int mOldMenuState = EMPTY_MENU;
4276 private static final int EMPTY_MENU = -1;
4279 private FindDialog mFindDialog;
4280 // Used to prevent chording to result in firing two shortcuts immediately
4281 // one after another. Fixes bug 1211714.
4284 private boolean mInLoad;
4285 private boolean mIsNetworkUp;
4287 private boolean mPageStarted;
4288 private boolean mActivityInPause = true;
4290 private boolean mMenuIsDown;
4292 private static boolean mInTrace;
4294 // Performance probe
4295 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4296 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4297 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4298 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4299 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4300 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4301 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4302 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4303 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4306 private long mStart;
4307 private long mProcessStart;
4308 private long mUserStart;
4309 private long mSystemStart;
4310 private long mIdleStart;
4311 private long mIrqStart;
4313 private long mUiStart;
4315 private Drawable mMixLockIcon;
4316 private Drawable mSecLockIcon;
4318 /* hold a ref so we can auto-cancel if necessary */
4319 private AlertDialog mAlertDialog;
4321 // Wait for credentials before loading google.com
4322 private ProgressDialog mCredsDlg;
4324 // The up-to-date URL and title (these can be different from those stored
4325 // in WebView, since it takes some time for the information in WebView to
4327 private String mUrl;
4328 private String mTitle;
4330 // As PageInfo has different style for landscape / portrait, we have
4331 // to re-open it when configuration changed
4332 private AlertDialog mPageInfoDialog;
4333 private TabControl.Tab mPageInfoView;
4334 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4335 // dialog, we should not just dismiss it, but should get back to the
4336 // SSL-certificate-on-error dialog. This flag is used to store this state
4337 private Boolean mPageInfoFromShowSSLCertificateOnError;
4339 // as SSLCertificateOnError has different style for landscape / portrait,
4340 // we have to re-open it when configuration changed
4341 private AlertDialog mSSLCertificateOnErrorDialog;
4342 private WebView mSSLCertificateOnErrorView;
4343 private SslErrorHandler mSSLCertificateOnErrorHandler;
4344 private SslError mSSLCertificateOnErrorError;
4346 // as SSLCertificate has different style for landscape / portrait, we
4347 // have to re-open it when configuration changed
4348 private AlertDialog mSSLCertificateDialog;
4349 private TabControl.Tab mSSLCertificateView;
4351 // as HttpAuthentication has different style for landscape / portrait, we
4352 // have to re-open it when configuration changed
4353 private AlertDialog mHttpAuthenticationDialog;
4354 private HttpAuthHandler mHttpAuthHandler;
4356 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4357 new FrameLayout.LayoutParams(
4358 ViewGroup.LayoutParams.FILL_PARENT,
4359 ViewGroup.LayoutParams.FILL_PARENT);
4360 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4361 new FrameLayout.LayoutParams(
4362 ViewGroup.LayoutParams.FILL_PARENT,
4363 ViewGroup.LayoutParams.FILL_PARENT,
4366 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4368 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4369 // Dictionary search
4370 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4371 // Google Mobile Local search
4372 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4374 final static String QUERY_PLACE_HOLDER = "%s";
4376 // "source" parameter for Google search through search key
4377 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4378 // "source" parameter for Google search through goto menu
4379 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4380 // "source" parameter for Google search through simplily type
4381 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4382 // "source" parameter for Google search suggested by the browser
4383 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4384 // "source" parameter for Google search from unknown source
4385 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4387 private final static String LOGTAG = "browser";
4389 private String mLastEnteredUrl;
4391 private PowerManager.WakeLock mWakeLock;
4392 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4394 private Toast mStopToast;
4396 private TitleBar mTitleBar;
4398 private LinearLayout mErrorConsoleContainer = null;
4399 private boolean mShouldShowErrorConsole = false;
4401 // As the ids are dynamically created, we can't guarantee that they will
4402 // be in sequence, so this static array maps ids to a window number.
4403 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4404 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4405 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4406 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4408 // monitor platform changes
4409 private IntentFilter mNetworkStateChangedFilter;
4410 private BroadcastReceiver mNetworkStateIntentReceiver;
4412 private BroadcastReceiver mPackageInstallationReceiver;
4414 // AsyncTask for downloading touch icons
4415 /* package */ DownloadTouchIcon mTouchIconLoader;
4417 // activity requestCode
4418 final static int COMBO_PAGE = 1;
4419 final static int DOWNLOAD_PAGE = 2;
4420 final static int PREFERENCES_PAGE = 3;
4422 // the default <video> poster
4423 private Bitmap mDefaultVideoPoster;
4424 // the video progress view
4425 private View mVideoProgressView;
4428 * A UrlData class to abstract how the content will be set to WebView.
4429 * This base class uses loadUrl to show the content.
4431 private static class UrlData {
4435 UrlData(String url) {
4439 void setPostData(byte[] postData) {
4440 mPostData = postData;
4444 return mUrl == null || mUrl.length() == 0;
4447 public void loadIn(WebView webView) {
4448 if (mPostData != null) {
4449 webView.postUrl(mUrl, mPostData);
4451 webView.loadUrl(mUrl);
4457 * A subclass of UrlData class that can display inlined content using
4458 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4460 private static class InlinedUrlData extends UrlData {
4461 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4464 mMimeType = mimeType;
4465 mEncoding = encoding;
4472 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4476 public void loadIn(WebView webView) {
4477 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4481 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);