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.Canvas;
49 import android.graphics.DrawFilter;
50 import android.graphics.Paint;
51 import android.graphics.PaintFlagsDrawFilter;
52 import android.graphics.Picture;
53 import android.graphics.PixelFormat;
54 import android.graphics.Rect;
55 import android.graphics.drawable.Drawable;
56 import android.hardware.SensorListener;
57 import android.hardware.SensorManager;
58 import android.net.ConnectivityManager;
59 import android.net.NetworkInfo;
60 import android.net.Uri;
61 import android.net.WebAddress;
62 import android.net.http.EventHandler;
63 import android.net.http.SslCertificate;
64 import android.net.http.SslError;
65 import android.os.AsyncTask;
66 import android.os.Bundle;
67 import android.os.Debug;
68 import android.os.Environment;
69 import android.os.Handler;
70 import android.os.IBinder;
71 import android.os.Message;
72 import android.os.PowerManager;
73 import android.os.Process;
74 import android.os.RemoteException;
75 import android.os.ServiceManager;
76 import android.os.SystemClock;
77 import android.provider.Browser;
78 import android.provider.Contacts;
79 import android.provider.Downloads;
80 import android.provider.MediaStore;
81 import android.provider.Contacts.Intents.Insert;
82 import android.text.IClipboard;
83 import android.text.TextUtils;
84 import android.text.format.DateFormat;
85 import android.text.util.Regex;
86 import android.util.Log;
87 import android.view.ContextMenu;
88 import android.view.Gravity;
89 import android.view.KeyEvent;
90 import android.view.LayoutInflater;
91 import android.view.Menu;
92 import android.view.MenuInflater;
93 import android.view.MenuItem;
94 import android.view.View;
95 import android.view.ViewGroup;
96 import android.view.Window;
97 import android.view.WindowManager;
98 import android.view.ContextMenu.ContextMenuInfo;
99 import android.view.MenuItem.OnMenuItemClickListener;
100 import android.view.animation.AlphaAnimation;
101 import android.view.animation.Animation;
102 import android.view.animation.AnimationSet;
103 import android.view.animation.DecelerateInterpolator;
104 import android.view.animation.ScaleAnimation;
105 import android.view.animation.TranslateAnimation;
106 import android.webkit.CookieManager;
107 import android.webkit.CookieSyncManager;
108 import android.webkit.DownloadListener;
109 import android.webkit.GeolocationPermissions;
110 import android.webkit.HttpAuthHandler;
111 import android.webkit.PluginManager;
112 import android.webkit.SslErrorHandler;
113 import android.webkit.URLUtil;
114 import android.webkit.WebChromeClient;
115 import android.webkit.WebChromeClient.CustomViewCallback;
116 import android.webkit.WebHistoryItem;
117 import android.webkit.WebIconDatabase;
118 import android.webkit.WebStorage;
119 import android.webkit.WebView;
120 import android.webkit.WebViewClient;
121 import android.widget.EditText;
122 import android.widget.FrameLayout;
123 import android.widget.LinearLayout;
124 import android.widget.TextView;
125 import android.widget.Toast;
127 import java.io.BufferedOutputStream;
128 import java.io.ByteArrayOutputStream;
130 import java.io.FileInputStream;
131 import java.io.FileOutputStream;
132 import java.io.IOException;
133 import java.io.InputStream;
134 import java.net.MalformedURLException;
136 import java.net.URISyntaxException;
138 import java.net.URLEncoder;
139 import java.text.ParseException;
140 import java.util.Date;
141 import java.util.Enumeration;
142 import java.util.HashMap;
143 import java.util.LinkedList;
144 import java.util.Vector;
145 import java.util.regex.Matcher;
146 import java.util.regex.Pattern;
147 import java.util.zip.ZipEntry;
148 import java.util.zip.ZipFile;
150 public class BrowserActivity extends Activity
151 implements KeyTracker.OnKeyTracker,
152 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));
624 * Launches the default web search activity with the query parameters if the given url string
625 * was identified as plain search terms and not URL/shortcut.
626 * @return true if the request was handled and web search activity was launched, false if not.
628 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
629 if (inUrl == null) return false;
631 // In general, we shouldn't modify URL from Intent.
632 // But currently, we get the user-typed URL from search box as well.
633 String url = fixUrl(inUrl).trim();
635 // URLs and site specific search shortcuts are handled by the regular flow of control, so
637 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
638 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
639 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
643 Browser.updateVisitedHistory(mResolver, url, false);
644 Browser.addSearchUrl(mResolver, url);
646 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
647 intent.addCategory(Intent.CATEGORY_DEFAULT);
648 intent.putExtra(SearchManager.QUERY, url);
649 if (appData != null) {
650 intent.putExtra(SearchManager.APP_DATA, appData);
652 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
653 startActivity(intent);
658 private UrlData getUrlDataFromIntent(Intent intent) {
660 if (intent != null) {
661 final String action = intent.getAction();
662 if (Intent.ACTION_VIEW.equals(action)) {
663 url = smartUrlFilter(intent.getData());
664 if (url != null && url.startsWith("content:")) {
665 /* Append mimetype so webview knows how to display */
666 String mimeType = intent.resolveType(getContentResolver());
667 if (mimeType != null) {
668 url += "?" + mimeType;
671 if ("inline:".equals(url)) {
672 return new InlinedUrlData(
673 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
675 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
676 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
678 } else if (Intent.ACTION_SEARCH.equals(action)
679 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
680 || Intent.ACTION_WEB_SEARCH.equals(action)) {
681 url = intent.getStringExtra(SearchManager.QUERY);
683 mLastEnteredUrl = url;
684 // Don't add Urls, just search terms.
685 // Urls will get added when the page is loaded.
686 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
687 Browser.updateVisitedHistory(mResolver, url, false);
689 // In general, we shouldn't modify URL from Intent.
690 // But currently, we get the user-typed URL from search box as well.
692 url = smartUrlFilter(url);
693 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
694 if (url.contains(searchSource)) {
695 String source = null;
696 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
697 if (appData != null) {
698 source = appData.getString(SearchManager.SOURCE);
700 if (TextUtils.isEmpty(source)) {
701 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
703 url = url.replace(searchSource, "&source=android-"+source+"&");
708 return new UrlData(url);
711 /* package */ static String fixUrl(String inUrl) {
712 // FIXME: Converting the url to lower case
713 // duplicates functionality in smartUrlFilter().
714 // However, changing all current callers of fixUrl to
715 // call smartUrlFilter in addition may have unwanted
716 // consequences, and is deferred for now.
717 int colon = inUrl.indexOf(':');
718 boolean allLower = true;
719 for (int index = 0; index < colon; index++) {
720 char ch = inUrl.charAt(index);
721 if (!Character.isLetter(ch)) {
724 allLower &= Character.isLowerCase(ch);
725 if (index == colon - 1 && !allLower) {
726 inUrl = inUrl.substring(0, colon).toLowerCase()
727 + inUrl.substring(colon);
730 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
732 if (inUrl.startsWith("http:") ||
733 inUrl.startsWith("https:")) {
734 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
735 inUrl = inUrl.replaceFirst("/", "//");
736 } else inUrl = inUrl.replaceFirst(":", "://");
742 * Looking for the pattern like this
751 private final SensorListener mSensorListener = new SensorListener() {
752 private long mLastGestureTime;
753 private float[] mPrev = new float[3];
754 private float[] mPrevDiff = new float[3];
755 private float[] mDiff = new float[3];
756 private float[] mRevertDiff = new float[3];
758 public void onSensorChanged(int sensor, float[] values) {
759 boolean show = false;
760 float[] diff = new float[3];
762 for (int i = 0; i < 3; i++) {
763 diff[i] = values[i] - mPrev[i];
764 if (Math.abs(diff[i]) > 1) {
767 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
768 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
769 // start track when there is a big move, or revert
770 mRevertDiff[i] = mDiff[i];
772 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
773 // reset when it is flat
774 mDiff[i] = mRevertDiff[i] = 0;
777 mPrevDiff[i] = diff[i];
778 mPrev[i] = values[i];
782 // only shows if we think the delta is big enough, in an attempt
783 // to detect "serious" moves left/right or up/down
784 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
785 + values[0] + ", " + values[1] + ", " + values[2] + ")"
786 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
788 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
789 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
790 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
791 + mRevertDiff[2] + ")");
794 long now = android.os.SystemClock.uptimeMillis();
795 if (now - mLastGestureTime > 1000) {
796 mLastGestureTime = 0;
800 float ay = Math.abs(y);
801 float az = Math.abs(z);
802 float ry = mRevertDiff[1];
803 float rz = mRevertDiff[2];
804 float ary = Math.abs(ry);
805 float arz = Math.abs(rz);
806 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
807 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
809 if ((gestY || gestZ) && !(gestY && gestZ)) {
810 WebView view = mTabControl.getCurrentWebView();
820 view.flingScroll(0, Math.round(y * 100));
823 mLastGestureTime = now;
828 public void onAccuracyChanged(int sensor, int accuracy) {
829 // TODO Auto-generated method stub
834 @Override protected void onResume() {
837 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
840 if (!mActivityInPause) {
841 Log.e(LOGTAG, "BrowserActivity is already resumed.");
845 mTabControl.resumeCurrentTab();
846 mActivityInPause = false;
847 resumeWebViewTimers();
849 if (mWakeLock.isHeld()) {
850 mHandler.removeMessages(RELEASE_WAKELOCK);
854 if (mCredsDlg != null) {
855 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
856 // In case credential request never comes back
857 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
861 registerReceiver(mNetworkStateIntentReceiver,
862 mNetworkStateChangedFilter);
863 WebView.enablePlatformNotifications();
865 if (mSettings.doFlick()) {
866 if (mSensorManager == null) {
867 mSensorManager = (SensorManager) getSystemService(
868 Context.SENSOR_SERVICE);
870 mSensorManager.registerListener(mSensorListener,
871 SensorManager.SENSOR_ACCELEROMETER,
872 SensorManager.SENSOR_DELAY_FASTEST);
874 mSensorManager = null;
879 * Since the actual title bar is embedded in the WebView, and removing it
880 * would change its appearance, create a temporary title bar to go at
881 * the top of the screen while the menu is open.
883 private TitleBar mFakeTitleBar;
886 * Holder for the fake title bar. It will have a foreground shadow, as well
887 * as a white background, so the fake title bar looks like the real one.
889 private ViewGroup mFakeTitleBarHolder;
892 * Layout parameters for the fake title bar within mFakeTitleBarHolder
894 private FrameLayout.LayoutParams mFakeTitleBarParams
895 = new FrameLayout.LayoutParams(
896 ViewGroup.LayoutParams.FILL_PARENT,
897 ViewGroup.LayoutParams.WRAP_CONTENT);
899 * Keeps track of whether the options menu is open. This is important in
900 * determining whether to show or hide the title bar overlay.
902 private boolean mOptionsMenuOpen;
905 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
906 * of whether the configuration has changed. The first onMenuOpened call
907 * after a configuration change is simply a reopening of the same menu
908 * (i.e. mIconView did not change).
910 private boolean mConfigChanged;
913 * Whether or not the options menu is in its smaller, icon menu form. When
914 * true, we want the title bar overlay to be up. When false, we do not.
915 * Only meaningful if mOptionsMenuOpen is true.
917 private boolean mIconView;
920 public boolean onMenuOpened(int featureId, Menu menu) {
921 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
922 if (mOptionsMenuOpen) {
923 if (mConfigChanged) {
924 // We do not need to make any changes to the state of the
925 // title bar, since the only thing that happened was a
926 // change in orientation
927 mConfigChanged = false;
930 // Switching the menu to expanded view, so hide the
935 // Switching the menu back to icon view, so show the
936 // title bar once again.
942 // The options menu is closed, so open it, and show the title
944 mOptionsMenuOpen = true;
945 mConfigChanged = false;
952 private void showFakeTitleBar() {
953 if (mFakeTitleBar == null && mActiveTabsPage == null
954 && !mActivityInPause) {
955 final WebView webView = getTopWindow();
956 mFakeTitleBar = new TitleBar(this);
957 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
958 mFakeTitleBar.setProgress(webView.getProgress());
959 mFakeTitleBar.setFavicon(webView.getFavicon());
960 updateLockIconToLatest();
962 WindowManager manager
963 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
965 // Add the title bar to the window manager so it can receive touches
966 // while the menu is up
967 WindowManager.LayoutParams params
968 = new WindowManager.LayoutParams(
969 ViewGroup.LayoutParams.FILL_PARENT,
970 ViewGroup.LayoutParams.WRAP_CONTENT,
971 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
972 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
974 params.gravity = Gravity.TOP;
975 WebView mainView = mTabControl.getCurrentWebView();
976 params.windowAnimations = mainView == null
977 || mainView.getScrollY() != 0
978 ? com.android.internal.R.style.Animation_DropDownDown : 0;
979 // XXX : Without providing an offset, the fake title bar will be
980 // placed underneath the status bar. Use the global visible rect
981 // of mBrowserFrameLayout to determine the bottom of the status bar
982 Rect rectangle = new Rect();
983 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
984 params.y = rectangle.top;
985 // Add a holder for the title bar. It is a FrameLayout, which
986 // allows it to have an overlay shadow. It also has a white
987 // background, which is the same as the background when it is
988 // placed in a WebView.
989 if (mFakeTitleBarHolder == null) {
990 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
991 .inflate(R.layout.title_bar_bg, null);
993 mFakeTitleBarHolder.addView(mFakeTitleBar, mFakeTitleBarParams);
994 manager.addView(mFakeTitleBarHolder, params);
999 public void onOptionsMenuClosed(Menu menu) {
1000 mOptionsMenuOpen = false;
1003 } else if (!mIconView) {
1004 // The page is currently loading, and we are in expanded mode, so
1005 // we were not showing the menu. Show it once again. It will be
1006 // removed when the page finishes.
1010 private void hideFakeTitleBar() {
1011 if (mFakeTitleBar == null) return;
1012 WindowManager manager
1013 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1014 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1015 manager.removeView(mFakeTitleBarHolder);
1016 mFakeTitleBar = null;
1020 * onSaveInstanceState(Bundle map)
1021 * onSaveInstanceState is called right before onStop(). The map contains
1024 @Override protected void onSaveInstanceState(Bundle outState) {
1026 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1028 // the default implementation requires each view to have an id. As the
1029 // browser handles the state itself and it doesn't use id for the views,
1030 // don't call the default implementation. Otherwise it will trigger the
1031 // warning like this, "couldn't save which view has focus because the
1032 // focused view XXX has no id".
1034 // Save all the tabs
1035 mTabControl.saveState(outState);
1038 @Override protected void onPause() {
1041 if (mActivityInPause) {
1042 Log.e(LOGTAG, "BrowserActivity is already paused.");
1046 mTabControl.pauseCurrentTab();
1047 mActivityInPause = true;
1048 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1049 mWakeLock.acquire();
1050 mHandler.sendMessageDelayed(mHandler
1051 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1054 // Clear the credentials toast if it is up
1055 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1056 mCredsDlg.dismiss();
1060 // FIXME: This removes the active tabs page and resets the menu to
1061 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1062 // but then we would need to save it in onSaveInstanceState and restore
1063 // it in onCreate/onRestoreInstanceState
1064 if (mActiveTabsPage != null) {
1065 removeActiveTabPage(true);
1070 // unregister network state listener
1071 unregisterReceiver(mNetworkStateIntentReceiver);
1072 WebView.disablePlatformNotifications();
1074 if (mSensorManager != null) {
1075 mSensorManager.unregisterListener(mSensorListener);
1079 @Override protected void onDestroy() {
1081 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1084 // Remove the current tab and sub window
1085 TabControl.Tab t = mTabControl.getCurrentTab();
1087 dismissSubWindow(t);
1088 removeTabFromContentView(t);
1090 // Destroy all the tabs
1091 mTabControl.destroy();
1092 WebIconDatabase.getInstance().close();
1093 if (mGlsConnection != null) {
1094 unbindService(mGlsConnection);
1095 mGlsConnection = null;
1099 // stop MASF proxy service
1101 //Intent proxyServiceIntent = new Intent();
1102 //proxyServiceIntent.setComponent
1103 // (new ComponentName(
1104 // "com.android.masfproxyservice",
1105 // "com.android.masfproxyservice.MasfProxyService"));
1106 //stopService(proxyServiceIntent);
1108 unregisterReceiver(mPackageInstallationReceiver);
1112 public void onConfigurationChanged(Configuration newConfig) {
1113 mConfigChanged = true;
1114 super.onConfigurationChanged(newConfig);
1116 if (mPageInfoDialog != null) {
1117 mPageInfoDialog.dismiss();
1120 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1122 if (mSSLCertificateDialog != null) {
1123 mSSLCertificateDialog.dismiss();
1125 mSSLCertificateView);
1127 if (mSSLCertificateOnErrorDialog != null) {
1128 mSSLCertificateOnErrorDialog.dismiss();
1129 showSSLCertificateOnError(
1130 mSSLCertificateOnErrorView,
1131 mSSLCertificateOnErrorHandler,
1132 mSSLCertificateOnErrorError);
1134 if (mHttpAuthenticationDialog != null) {
1135 String title = ((TextView) mHttpAuthenticationDialog
1136 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1138 String name = ((TextView) mHttpAuthenticationDialog
1139 .findViewById(R.id.username_edit)).getText().toString();
1140 String password = ((TextView) mHttpAuthenticationDialog
1141 .findViewById(R.id.password_edit)).getText().toString();
1142 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1144 mHttpAuthenticationDialog.dismiss();
1145 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1146 name, password, focusId);
1148 if (mFindDialog != null && mFindDialog.isShowing()) {
1149 mFindDialog.onConfigurationChanged(newConfig);
1153 @Override public void onLowMemory() {
1154 super.onLowMemory();
1155 mTabControl.freeMemory();
1158 private boolean resumeWebViewTimers() {
1159 if ((!mActivityInPause && !mPageStarted) ||
1160 (mActivityInPause && mPageStarted)) {
1161 CookieSyncManager.getInstance().startSync();
1162 WebView w = mTabControl.getCurrentWebView();
1172 private boolean pauseWebViewTimers() {
1173 if (mActivityInPause && !mPageStarted) {
1174 CookieSyncManager.getInstance().stopSync();
1175 WebView w = mTabControl.getCurrentWebView();
1185 // FIXME: Do we want to call this when loading google for the first time?
1187 * This function is called when we are launching for the first time. We
1188 * are waiting for the login credentials before loading Google home
1189 * pages. This way the user will be logged in straight away.
1191 private void waitForCredentials() {
1193 mCredsDlg = new ProgressDialog(this);
1194 mCredsDlg.setIndeterminate(true);
1195 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1196 // If the user cancels the operation, then cancel the Google
1197 // Credentials request.
1198 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1201 // We set a timeout for the retrieval of credentials in onResume()
1202 // as that is when we have freed up some CPU time to get
1203 // the login credentials.
1207 * If we have received the credentials or we have timed out and we are
1208 * showing the credentials dialog, then it is time to move on.
1210 private void resumeAfterCredentials() {
1211 if (mCredsDlg == null) {
1216 if (mCredsDlg.isShowing()) {
1217 mCredsDlg.dismiss();
1221 // Clear any pending timeout
1222 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1225 WebView w = mTabControl.getCurrentWebView();
1227 w.loadUrl(mSettings.getHomePage());
1230 // Update the settings, need to do this last as it can take a moment
1231 // to persist the settings. In the mean time we could be loading
1233 mSettings.setLoginInitialized(this);
1236 // Open the icon database and retain all the icons for visited sites.
1237 private void retainIconsOnStartup() {
1238 final WebIconDatabase db = WebIconDatabase.getInstance();
1239 db.open(getDir("icons", 0).getPath());
1241 Cursor c = Browser.getAllBookmarks(mResolver);
1242 if (!c.moveToFirst()) {
1246 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1248 String url = c.getString(urlIndex);
1249 db.retainIconForPageUrl(url);
1250 } while (c.moveToNext());
1252 } catch (IllegalStateException e) {
1253 Log.e(LOGTAG, "retainIconsOnStartup", e);
1257 // Helper method for getting the top window.
1258 WebView getTopWindow() {
1259 return mTabControl.getCurrentTopWebView();
1263 public boolean onCreateOptionsMenu(Menu menu) {
1264 super.onCreateOptionsMenu(menu);
1266 MenuInflater inflater = getMenuInflater();
1267 inflater.inflate(R.menu.browser, menu);
1269 updateInLoadMenuItems();
1274 * As the menu can be open when loading state changes
1275 * we must manually update the state of the stop/reload menu
1278 private void updateInLoadMenuItems() {
1279 if (mMenu == null) {
1282 MenuItem src = mInLoad ?
1283 mMenu.findItem(R.id.stop_menu_id):
1284 mMenu.findItem(R.id.reload_menu_id);
1285 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1286 dest.setIcon(src.getIcon());
1287 dest.setTitle(src.getTitle());
1291 public boolean onContextItemSelected(MenuItem item) {
1292 // chording is not an issue with context menus, but we use the same
1293 // options selector, so set mCanChord to true so we can access them.
1295 int id = item.getItemId();
1296 final WebView webView = getTopWindow();
1297 if (null == webView) {
1300 final HashMap hrefMap = new HashMap();
1301 hrefMap.put("webview", webView);
1302 final Message msg = mHandler.obtainMessage(
1303 FOCUS_NODE_HREF, id, 0, hrefMap);
1305 // -- Browser context menu
1306 case R.id.open_context_menu_id:
1307 case R.id.open_newtab_context_menu_id:
1308 case R.id.bookmark_context_menu_id:
1309 case R.id.save_link_context_menu_id:
1310 case R.id.share_link_context_menu_id:
1311 case R.id.copy_link_context_menu_id:
1312 webView.requestFocusNodeHref(msg);
1316 // For other context menus
1317 return onOptionsItemSelected(item);
1323 private Bundle createGoogleSearchSourceBundle(String source) {
1324 Bundle bundle = new Bundle();
1325 bundle.putString(SearchManager.SOURCE, source);
1330 * Overriding this to insert a local information bundle
1333 public boolean onSearchRequested() {
1334 if (mOptionsMenuOpen) closeOptionsMenu();
1335 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1336 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1337 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1342 public void startSearch(String initialQuery, boolean selectInitialQuery,
1343 Bundle appSearchData, boolean globalSearch) {
1344 if (appSearchData == null) {
1345 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1347 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1351 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1352 * results in changing tabs.
1353 * @param index Index of the tab to change to, as defined by
1354 * mTabControl.getTabIndex(Tab t).
1355 * @return boolean True if we successfully switched to a different tab. If
1356 * the indexth tab is null, or if that tab is the same as
1357 * the current one, return false.
1359 /* package */ boolean switchToTab(int index) {
1360 TabControl.Tab tab = mTabControl.getTab(index);
1361 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1362 if (tab == null || tab == currentTab) {
1365 if (currentTab != null) {
1366 // currentTab may be null if it was just removed. In that case,
1367 // we do not need to remove it
1368 removeTabFromContentView(currentTab);
1370 mTabControl.setCurrentTab(tab);
1371 attachTabToContentView(tab);
1372 resetTitleIconAndProgress();
1373 updateLockIconToLatest();
1377 /* package */ TabControl.Tab openTabToHomePage() {
1378 return openTabAndShow(mSettings.getHomePage(), false, null);
1381 /* package */ void closeCurrentWindow() {
1382 final TabControl.Tab current = mTabControl.getCurrentTab();
1383 if (mTabControl.getTabCount() == 1) {
1384 // This is the last tab. Open a new one, with the home
1385 // page and close the current one.
1386 TabControl.Tab newTab = openTabToHomePage();
1390 final TabControl.Tab parent = current.getParentTab();
1391 int indexToShow = -1;
1392 if (parent != null) {
1393 indexToShow = mTabControl.getTabIndex(parent);
1395 final int currentIndex = mTabControl.getCurrentIndex();
1396 // Try to move to the tab to the right
1397 indexToShow = currentIndex + 1;
1398 if (indexToShow > mTabControl.getTabCount() - 1) {
1399 // Try to move to the tab to the left
1400 indexToShow = currentIndex - 1;
1403 if (switchToTab(indexToShow)) {
1409 private ActiveTabsPage mActiveTabsPage;
1412 * Remove the active tabs page.
1413 * @param needToAttach If true, the active tabs page did not attach a tab
1414 * to the content view, so we need to do that here.
1416 /* package */ void removeActiveTabPage(boolean needToAttach) {
1417 mContentView.removeView(mActiveTabsPage);
1418 mActiveTabsPage = null;
1419 mMenuState = R.id.MAIN_MENU;
1421 attachTabToContentView(mTabControl.getCurrentTab());
1423 getTopWindow().requestFocus();
1427 public boolean onOptionsItemSelected(MenuItem item) {
1429 // The user has already fired a shortcut with this hold down of the
1433 if (null == getTopWindow()) {
1437 // The shortcut action consumes the MENU. Even if it is still down,
1438 // it won't trigger the next shortcut action. In the case of the
1439 // shortcut action triggering a new activity, like Bookmarks, we
1440 // won't get onKeyUp for MENU. So it is important to reset it here.
1441 mMenuIsDown = false;
1443 switch (item.getItemId()) {
1445 case R.id.new_tab_menu_id:
1446 openTabToHomePage();
1449 case R.id.goto_menu_id:
1450 bookmarksOrHistoryPicker(false);
1453 case R.id.active_tabs_menu_id:
1454 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1455 removeTabFromContentView(mTabControl.getCurrentTab());
1457 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1458 mActiveTabsPage.requestFocus();
1459 mMenuState = EMPTY_MENU;
1462 case R.id.add_bookmark_menu_id:
1463 Intent i = new Intent(BrowserActivity.this,
1464 AddBookmarkPage.class);
1465 WebView w = getTopWindow();
1466 i.putExtra("url", w.getUrl());
1467 i.putExtra("title", w.getTitle());
1468 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1472 case R.id.stop_reload_menu_id:
1476 getTopWindow().reload();
1480 case R.id.back_menu_id:
1481 getTopWindow().goBack();
1484 case R.id.forward_menu_id:
1485 getTopWindow().goForward();
1488 case R.id.close_menu_id:
1489 // Close the subwindow if it exists.
1490 if (mTabControl.getCurrentSubWindow() != null) {
1491 dismissSubWindow(mTabControl.getCurrentTab());
1494 closeCurrentWindow();
1497 case R.id.homepage_menu_id:
1498 TabControl.Tab current = mTabControl.getCurrentTab();
1499 if (current != null) {
1500 dismissSubWindow(current);
1501 current.getWebView().loadUrl(mSettings.getHomePage());
1505 case R.id.preferences_menu_id:
1506 Intent intent = new Intent(this,
1507 BrowserPreferencesPage.class);
1508 startActivityForResult(intent, PREFERENCES_PAGE);
1511 case R.id.find_menu_id:
1512 if (null == mFindDialog) {
1513 mFindDialog = new FindDialog(this);
1515 mFindDialog.setWebView(getTopWindow());
1517 mMenuState = EMPTY_MENU;
1520 case R.id.select_text_id:
1521 getTopWindow().emulateShiftHeld();
1523 case R.id.page_info_menu_id:
1524 showPageInfo(mTabControl.getCurrentTab(), false);
1527 case R.id.classic_history_menu_id:
1528 bookmarksOrHistoryPicker(true);
1531 case R.id.share_page_menu_id:
1532 Browser.sendString(this, getTopWindow().getUrl());
1535 case R.id.dump_nav_menu_id:
1536 getTopWindow().debugDump();
1539 case R.id.zoom_in_menu_id:
1540 getTopWindow().zoomIn();
1543 case R.id.zoom_out_menu_id:
1544 getTopWindow().zoomOut();
1547 case R.id.view_downloads_menu_id:
1548 viewDownloads(null);
1551 case R.id.window_one_menu_id:
1552 case R.id.window_two_menu_id:
1553 case R.id.window_three_menu_id:
1554 case R.id.window_four_menu_id:
1555 case R.id.window_five_menu_id:
1556 case R.id.window_six_menu_id:
1557 case R.id.window_seven_menu_id:
1558 case R.id.window_eight_menu_id:
1560 int menuid = item.getItemId();
1561 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1562 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1563 TabControl.Tab desiredTab = mTabControl.getTab(id);
1564 if (desiredTab != null &&
1565 desiredTab != mTabControl.getCurrentTab()) {
1575 if (!super.onOptionsItemSelected(item)) {
1578 // Otherwise fall through.
1584 public void closeFind() {
1585 mMenuState = R.id.MAIN_MENU;
1588 @Override public boolean onPrepareOptionsMenu(Menu menu)
1590 // This happens when the user begins to hold down the menu key, so
1591 // allow them to chord to get a shortcut.
1593 // Note: setVisible will decide whether an item is visible; while
1594 // setEnabled() will decide whether an item is enabled, which also means
1595 // whether the matching shortcut key will function.
1596 super.onPrepareOptionsMenu(menu);
1597 switch (mMenuState) {
1599 if (mCurrentMenuState != mMenuState) {
1600 menu.setGroupVisible(R.id.MAIN_MENU, false);
1601 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1602 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1606 if (mCurrentMenuState != mMenuState) {
1607 menu.setGroupVisible(R.id.MAIN_MENU, true);
1608 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1609 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1611 final WebView w = getTopWindow();
1612 boolean canGoBack = false;
1613 boolean canGoForward = false;
1614 boolean isHome = false;
1616 canGoBack = w.canGoBack();
1617 canGoForward = w.canGoForward();
1618 isHome = mSettings.getHomePage().equals(w.getUrl());
1620 final MenuItem back = menu.findItem(R.id.back_menu_id);
1621 back.setEnabled(canGoBack);
1623 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1624 home.setEnabled(!isHome);
1626 menu.findItem(R.id.forward_menu_id)
1627 .setEnabled(canGoForward);
1629 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1630 mTabControl.getTabCount() < TabControl.MAX_TABS);
1632 // decide whether to show the share link option
1633 PackageManager pm = getPackageManager();
1634 Intent send = new Intent(Intent.ACTION_SEND);
1635 send.setType("text/plain");
1636 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1637 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1639 boolean isNavDump = mSettings.isNavDump();
1640 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1641 nav.setVisible(isNavDump);
1642 nav.setEnabled(isNavDump);
1645 mCurrentMenuState = mMenuState;
1650 public void onCreateContextMenu(ContextMenu menu, View v,
1651 ContextMenuInfo menuInfo) {
1652 WebView webview = (WebView) v;
1653 WebView.HitTestResult result = webview.getHitTestResult();
1654 if (result == null) {
1658 int type = result.getType();
1659 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1661 "We should not show context menu when nothing is touched");
1664 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1665 // let TextView handles context menu
1669 // Note, http://b/issue?id=1106666 is requesting that
1670 // an inflated menu can be used again. This is not available
1671 // yet, so inflate each time (yuk!)
1672 MenuInflater inflater = getMenuInflater();
1673 inflater.inflate(R.menu.browsercontext, menu);
1675 // Show the correct menu group
1676 String extra = result.getExtra();
1677 menu.setGroupVisible(R.id.PHONE_MENU,
1678 type == WebView.HitTestResult.PHONE_TYPE);
1679 menu.setGroupVisible(R.id.EMAIL_MENU,
1680 type == WebView.HitTestResult.EMAIL_TYPE);
1681 menu.setGroupVisible(R.id.GEO_MENU,
1682 type == WebView.HitTestResult.GEO_TYPE);
1683 menu.setGroupVisible(R.id.IMAGE_MENU,
1684 type == WebView.HitTestResult.IMAGE_TYPE
1685 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1686 menu.setGroupVisible(R.id.ANCHOR_MENU,
1687 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1688 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1690 // Setup custom handling depending on the type
1692 case WebView.HitTestResult.PHONE_TYPE:
1693 menu.setHeaderTitle(Uri.decode(extra));
1694 menu.findItem(R.id.dial_context_menu_id).setIntent(
1695 new Intent(Intent.ACTION_VIEW, Uri
1696 .parse(WebView.SCHEME_TEL + extra)));
1697 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1698 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1699 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1700 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1702 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1706 case WebView.HitTestResult.EMAIL_TYPE:
1707 menu.setHeaderTitle(extra);
1708 menu.findItem(R.id.email_context_menu_id).setIntent(
1709 new Intent(Intent.ACTION_VIEW, Uri
1710 .parse(WebView.SCHEME_MAILTO + extra)));
1711 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1715 case WebView.HitTestResult.GEO_TYPE:
1716 menu.setHeaderTitle(extra);
1717 menu.findItem(R.id.map_context_menu_id).setIntent(
1718 new Intent(Intent.ACTION_VIEW, Uri
1719 .parse(WebView.SCHEME_GEO
1720 + URLEncoder.encode(extra))));
1721 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1725 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1726 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1727 TextView titleView = (TextView) LayoutInflater.from(this)
1728 .inflate(android.R.layout.browser_link_context_header,
1730 titleView.setText(extra);
1731 menu.setHeaderView(titleView);
1732 // decide whether to show the open link in new tab option
1733 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1734 mTabControl.getTabCount() < TabControl.MAX_TABS);
1735 PackageManager pm = getPackageManager();
1736 Intent send = new Intent(Intent.ACTION_SEND);
1737 send.setType("text/plain");
1738 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1739 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1740 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1743 // otherwise fall through to handle image part
1744 case WebView.HitTestResult.IMAGE_TYPE:
1745 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1746 menu.setHeaderTitle(extra);
1748 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1749 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1750 menu.findItem(R.id.download_context_menu_id).
1751 setOnMenuItemClickListener(new Download(extra));
1755 Log.w(LOGTAG, "We should not get here.");
1760 // Attach the given tab to the content view.
1761 private void attachTabToContentView(TabControl.Tab t) {
1762 // Attach the container that contains the main WebView and any other UI
1763 // associated with the tab.
1764 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
1766 if (mShouldShowErrorConsole) {
1767 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1768 if (errorConsole.numberOfErrors() == 0) {
1769 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1771 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1774 mErrorConsoleContainer.addView(errorConsole,
1775 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1776 ViewGroup.LayoutParams.WRAP_CONTENT));
1779 if (t == mTabControl.getCurrentTab()) {
1780 setLockIconType(t.getLockIconType());
1781 setPrevLockType(t.getPrevLockIconType());
1784 WebView view = t.getWebView();
1785 view.setEmbeddedTitleBar(mTitleBar);
1786 // Attach the sub window if necessary
1788 // Request focus on the top window.
1789 t.getTopWindow().requestFocus();
1792 // Attach a sub window to the main WebView of the given tab.
1793 private void attachSubWindow(TabControl.Tab t) {
1794 // If a sub window exists, attach it to the content view.
1795 final WebView subView = t.getSubWebView();
1796 if (subView != null) {
1797 final View container = t.getSubWebViewContainer();
1798 mContentView.addView(container, COVER_SCREEN_PARAMS);
1799 subView.requestFocus();
1803 // Remove the given tab from the content view.
1804 private void removeTabFromContentView(TabControl.Tab t) {
1805 // Remove the container that contains the main WebView.
1806 mContentView.removeView(t.getContainer());
1808 if (mTabControl.getCurrentErrorConsole(false) != null) {
1809 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1812 WebView view = t.getWebView();
1814 view.setEmbeddedTitleBar(null);
1817 // Remove the sub window if it exists.
1818 if (t.getSubWebView() != null) {
1819 mContentView.removeView(t.getSubWebViewContainer());
1822 if (t == mTabControl.getCurrentTab()) {
1823 t.setLockIconType(getLockIconType());
1824 t.setPrevLockIconType(getPrevLockType());
1828 // Remove the sub window if it exists. Also called by TabControl when the
1829 // user clicks the 'X' to dismiss a sub window.
1830 /* package */ void dismissSubWindow(TabControl.Tab t) {
1831 final WebView mainView = t.getWebView();
1832 if (t.getSubWebView() != null) {
1833 // Remove the container view and request focus on the main WebView.
1834 mContentView.removeView(t.getSubWebViewContainer());
1835 mainView.requestFocus();
1836 // Tell the TabControl to dismiss the subwindow. This will destroy
1838 mTabControl.dismissSubWindow(t);
1842 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1843 // that accepts url as string.
1844 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1846 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1849 // This method does a ton of stuff. It will attempt to create a new tab
1850 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1851 // url isn't null, it will load the given url.
1852 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
1853 boolean closeOnExit, String appId) {
1854 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1855 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1857 final TabControl.Tab tab = mTabControl.createNewTab(
1858 closeOnExit, appId, urlData.mUrl);
1859 WebView webview = tab.getWebView();
1860 // If the last tab was removed from the active tabs page, currentTab
1862 if (currentTab != null) {
1863 removeTabFromContentView(currentTab);
1865 // We must set the new tab as the current tab to reflect the old
1866 // animation behavior.
1867 mTabControl.setCurrentTab(tab);
1868 attachTabToContentView(tab);
1869 if (!urlData.isEmpty()) {
1870 urlData.loadIn(webview);
1874 // Get rid of the subwindow if it exists
1875 dismissSubWindow(currentTab);
1876 if (!urlData.isEmpty()) {
1877 // Load the given url.
1878 urlData.loadIn(currentTab.getWebView());
1884 private TabControl.Tab openTab(String url) {
1885 if (mSettings.openInBackground()) {
1886 TabControl.Tab t = mTabControl.createNewTab();
1888 WebView view = t.getWebView();
1893 return openTabAndShow(url, false, null);
1897 private class Copy implements OnMenuItemClickListener {
1898 private CharSequence mText;
1900 public boolean onMenuItemClick(MenuItem item) {
1905 public Copy(CharSequence toCopy) {
1910 private class Download implements OnMenuItemClickListener {
1911 private String mText;
1913 public boolean onMenuItemClick(MenuItem item) {
1914 onDownloadStartNoStream(mText, null, null, null, -1);
1918 public Download(String toDownload) {
1923 private void copy(CharSequence text) {
1925 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1927 clip.setClipboardText(text);
1929 } catch (android.os.RemoteException e) {
1930 Log.e(LOGTAG, "Copy failed", e);
1935 * Resets the browser title-view to whatever it must be
1936 * (for example, if we had a loading error)
1937 * When we have a new page, we call resetTitle, when we
1938 * have to reset the titlebar to whatever it used to be
1939 * (for example, if the user chose to stop loading), we
1940 * call resetTitleAndRevertLockIcon.
1942 /* package */ void resetTitleAndRevertLockIcon() {
1944 resetTitleIconAndProgress();
1948 * Reset the title, favicon, and progress.
1950 private void resetTitleIconAndProgress() {
1951 WebView current = mTabControl.getCurrentWebView();
1952 if (current == null) {
1955 resetTitleAndIcon(current);
1956 int progress = current.getProgress();
1957 mWebChromeClient.onProgressChanged(current, progress);
1960 // Reset the title and the icon based on the given item.
1961 private void resetTitleAndIcon(WebView view) {
1962 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1964 setUrlTitle(item.getUrl(), item.getTitle());
1965 setFavicon(item.getFavicon());
1967 setUrlTitle(null, null);
1973 * Sets a title composed of the URL and the title string.
1974 * @param url The URL of the site being loaded.
1975 * @param title The title of the site being loaded.
1977 private void setUrlTitle(String url, String title) {
1981 mTitleBar.setTitleAndUrl(title, url);
1982 if (mFakeTitleBar != null) {
1983 mFakeTitleBar.setTitleAndUrl(title, url);
1988 * @param url The URL to build a title version of the URL from.
1989 * @return The title version of the URL or null if fails.
1990 * The title version of the URL can be either the URL hostname,
1991 * or the hostname with an "https://" prefix (for secure URLs),
1992 * or an empty string if, for example, the URL in question is a
1993 * file:// URL with no hostname.
1995 /* package */ static String buildTitleUrl(String url) {
1996 String titleUrl = null;
2000 // parse the url string
2001 URL urlObj = new URL(url);
2002 if (urlObj != null) {
2005 String protocol = urlObj.getProtocol();
2006 String host = urlObj.getHost();
2008 if (host != null && 0 < host.length()) {
2010 if (protocol != null) {
2011 // if a secure site, add an "https://" prefix!
2012 if (protocol.equalsIgnoreCase("https")) {
2013 titleUrl = protocol + "://" + host;
2018 } catch (MalformedURLException e) {}
2024 // Set the favicon in the title bar.
2025 private void setFavicon(Bitmap icon) {
2026 mTitleBar.setFavicon(icon);
2027 if (mFakeTitleBar != null) {
2028 mFakeTitleBar.setFavicon(icon);
2033 * Saves the current lock-icon state before resetting
2034 * the lock icon. If we have an error, we may need to
2035 * roll back to the previous state.
2037 private void saveLockIcon() {
2038 mPrevLockType = mLockIconType;
2042 * Reverts the lock-icon state to the last saved state,
2043 * for example, if we had an error, and need to cancel
2046 private void revertLockIcon() {
2047 mLockIconType = mPrevLockType;
2050 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2051 " revert lock icon to " + mLockIconType);
2054 updateLockIconToLatest();
2058 * Close the tab, remove its associated title bar, and adjust mTabControl's
2059 * current tab to a valid value.
2061 /* package */ void closeTab(TabControl.Tab t) {
2062 int currentIndex = mTabControl.getCurrentIndex();
2063 int removeIndex = mTabControl.getTabIndex(t);
2064 mTabControl.removeTab(t);
2065 if (currentIndex >= removeIndex && currentIndex != 0) {
2068 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2071 private void goBackOnePageOrQuit() {
2072 TabControl.Tab current = mTabControl.getCurrentTab();
2073 if (current == null) {
2075 * Instead of finishing the activity, simply push this to the back
2076 * of the stack and let ActivityManager to choose the foreground
2077 * activity. As BrowserActivity is singleTask, it will be always the
2078 * root of the task. So we can use either true or false for
2081 moveTaskToBack(true);
2083 WebView w = current.getWebView();
2084 if (w.canGoBack()) {
2087 // Check to see if we are closing a window that was created by
2088 // another window. If so, we switch back to that window.
2089 TabControl.Tab parent = current.getParentTab();
2090 if (parent != null) {
2091 switchToTab(mTabControl.getTabIndex(parent));
2092 // Now we close the other tab
2095 if (current.closeOnExit()) {
2096 // force mPageStarted to be false as we are going to either
2097 // finish the activity or remove the tab. This will ensure
2098 // pauseWebView() taking action.
2099 mPageStarted = false;
2100 if (mTabControl.getTabCount() == 1) {
2104 // call pauseWebViewTimers() now, we won't be able to call
2105 // it in onPause() as the WebView won't be valid.
2106 // Temporarily change mActivityInPause to be true as
2107 // pauseWebViewTimers() will do nothing if mActivityInPause
2109 boolean savedState = mActivityInPause;
2111 Log.e(LOGTAG, "BrowserActivity is already paused "
2112 + "while handing goBackOnePageOrQuit.");
2114 mActivityInPause = true;
2115 pauseWebViewTimers();
2116 mActivityInPause = savedState;
2117 removeTabFromContentView(current);
2118 mTabControl.removeTab(current);
2121 * Instead of finishing the activity, simply push this to the back
2122 * of the stack and let ActivityManager to choose the foreground
2123 * activity. As BrowserActivity is singleTask, it will be always the
2124 * root of the task. So we can use either true or false for
2127 moveTaskToBack(true);
2132 public KeyTracker.State onKeyTracker(int keyCode,
2134 KeyTracker.Stage stage,
2136 // if onKeyTracker() is called after activity onStop()
2137 // because of accumulated key events,
2138 // we should ignore it as browser is not active any more.
2139 WebView topWindow = getTopWindow();
2140 if (topWindow == null && mCustomView == null)
2141 return KeyTracker.State.NOT_TRACKING;
2143 if (keyCode == KeyEvent.KEYCODE_BACK) {
2144 // Check if a custom view is currently showing and, if it is, hide it.
2145 if (mCustomView != null) {
2146 mWebChromeClient.onHideCustomView();
2147 return KeyTracker.State.DONE_TRACKING;
2149 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2150 bookmarksOrHistoryPicker(true);
2151 return KeyTracker.State.DONE_TRACKING;
2152 } else if (stage == KeyTracker.Stage.UP) {
2153 // FIXME: Currently, we do not have a notion of the
2154 // history picker for the subwindow, but maybe we
2156 WebView subwindow = mTabControl.getCurrentSubWindow();
2157 if (subwindow != null) {
2158 if (subwindow.canGoBack()) {
2161 dismissSubWindow(mTabControl.getCurrentTab());
2164 goBackOnePageOrQuit();
2166 return KeyTracker.State.DONE_TRACKING;
2168 return KeyTracker.State.KEEP_TRACKING;
2170 return KeyTracker.State.NOT_TRACKING;
2173 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2174 if (keyCode == KeyEvent.KEYCODE_MENU) {
2176 } else if (mMenuIsDown) {
2177 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2178 // still down, we don't want to trigger the search. Pretend to
2179 // consume the key and do nothing.
2182 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2185 case KeyEvent.KEYCODE_SPACE:
2186 if (event.isShiftPressed()) {
2187 getTopWindow().pageUp(false);
2189 getTopWindow().pageDown(false);
2198 return handled || super.onKeyDown(keyCode, event);
2201 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2202 if (keyCode == KeyEvent.KEYCODE_MENU) {
2203 mMenuIsDown = false;
2205 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2208 /* package */ void stopLoading() {
2209 resetTitleAndRevertLockIcon();
2210 WebView w = getTopWindow();
2212 mWebViewClient.onPageFinished(w, w.getUrl());
2216 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2220 private void cancelStopToast() {
2221 if (mStopToast != null) {
2222 mStopToast.cancel();
2227 // called by a non-UI thread to post the message
2228 public void postMessage(int what, int arg1, int arg2, Object obj) {
2229 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2232 // public message ids
2233 public final static int LOAD_URL = 1001;
2234 public final static int STOP_LOAD = 1002;
2237 private static final int FOCUS_NODE_HREF = 102;
2238 private static final int CANCEL_CREDS_REQUEST = 103;
2239 private static final int RELEASE_WAKELOCK = 107;
2241 // Private handler for handling javascript and saving passwords
2242 private Handler mHandler = new Handler() {
2244 public void handleMessage(Message msg) {
2246 case FOCUS_NODE_HREF:
2247 String url = (String) msg.getData().get("url");
2248 if (url == null || url.length() == 0) {
2251 HashMap focusNodeMap = (HashMap) msg.obj;
2252 WebView view = (WebView) focusNodeMap.get("webview");
2253 // Only apply the action if the top window did not change.
2254 if (getTopWindow() != view) {
2258 case R.id.open_context_menu_id:
2259 case R.id.view_image_context_menu_id:
2260 loadURL(getTopWindow(), url);
2262 case R.id.open_newtab_context_menu_id:
2263 final TabControl.Tab parent = mTabControl
2265 final TabControl.Tab newTab = openTab(url);
2266 if (newTab != parent) {
2267 parent.addChildTab(newTab);
2270 case R.id.bookmark_context_menu_id:
2271 Intent intent = new Intent(BrowserActivity.this,
2272 AddBookmarkPage.class);
2273 intent.putExtra("url", url);
2274 startActivity(intent);
2276 case R.id.share_link_context_menu_id:
2277 Browser.sendString(BrowserActivity.this, url);
2279 case R.id.copy_link_context_menu_id:
2282 case R.id.save_link_context_menu_id:
2283 case R.id.download_context_menu_id:
2284 onDownloadStartNoStream(url, null, null, null, -1);
2290 loadURL(getTopWindow(), (String) msg.obj);
2297 case CANCEL_CREDS_REQUEST:
2298 resumeAfterCredentials();
2301 case RELEASE_WAKELOCK:
2302 if (mWakeLock.isHeld()) {
2303 mWakeLock.release();
2310 private void updateScreenshot(WebView view) {
2311 // If this is a bookmarked site, add a screenshot to the database.
2312 // FIXME: When should we update? Every time?
2313 // FIXME: Would like to make sure there is actually something to
2314 // draw, but the API for that (WebViewCore.pictureReady()) is not
2315 // currently accessible here.
2316 ContentResolver cr = getContentResolver();
2317 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2318 cr, view.getOriginalUrl(), view.getUrl(), false);
2320 boolean succeed = c.moveToFirst();
2321 ContentValues values = null;
2323 if (values == null) {
2324 final ByteArrayOutputStream os
2325 = new ByteArrayOutputStream();
2326 Picture thumbnail = view.capturePicture();
2327 // Keep width and height in sync with BrowserBookmarksPage
2328 // and bookmark_thumb
2329 Bitmap bm = Bitmap.createBitmap(100, 80,
2330 Bitmap.Config.ARGB_4444);
2331 Canvas canvas = new Canvas(bm);
2332 // May need to tweak these values to determine what is the
2333 // best scale factor
2334 canvas.scale(.5f, .5f);
2335 thumbnail.draw(canvas);
2336 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2337 values = new ContentValues();
2338 values.put(Browser.BookmarkColumns.THUMBNAIL,
2341 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2342 c.getInt(0)), values, null, null);
2343 succeed = c.moveToNext();
2349 // -------------------------------------------------------------------------
2350 // WebViewClient implementation.
2351 //-------------------------------------------------------------------------
2353 // Use in overrideUrlLoading
2354 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2355 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2356 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2357 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2359 /* package */ WebViewClient getWebViewClient() {
2360 return mWebViewClient;
2363 private void updateIcon(WebView view, Bitmap icon) {
2365 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2371 private final WebViewClient mWebViewClient = new WebViewClient() {
2373 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2375 setUrlTitle(url, null);
2377 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2378 if (errorConsole != null) {
2379 errorConsole.clearErrorMessages();
2380 if (mShouldShowErrorConsole) {
2381 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2385 // Call updateIcon instead of setFavicon so the bookmark
2386 // database can be updated.
2387 updateIcon(view, favicon);
2389 if (mSettings.isTracing()) {
2392 WebAddress uri = new WebAddress(url);
2394 } catch (android.net.ParseException ex) {
2397 host = host.replace('.', '_');
2400 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2403 // Performance probe
2405 mStart = SystemClock.uptimeMillis();
2406 mProcessStart = Process.getElapsedCpuTime();
2407 long[] sysCpu = new long[7];
2408 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2410 mUserStart = sysCpu[0] + sysCpu[1];
2411 mSystemStart = sysCpu[2];
2412 mIdleStart = sysCpu[3];
2413 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2415 mUiStart = SystemClock.currentThreadTimeMillis();
2418 if (!mPageStarted) {
2419 mPageStarted = true;
2420 // if onResume() has been called, resumeWebViewTimers() does
2422 resumeWebViewTimers();
2425 // reset sync timer to avoid sync starts during loading a page
2426 CookieSyncManager.getInstance().resetSync();
2429 WebView currentWebView = mTabControl.getCurrentWebView();
2430 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2431 // This page has begun to load, so show the title bar
2434 updateInLoadMenuItems();
2435 if (!mIsNetworkUp) {
2436 createAndShowNetworkDialog();
2438 view.setNetworkAvailable(false);
2444 public void onPageFinished(WebView view, String url) {
2445 // Reset the title and icon in case we stopped a provisional
2447 resetTitleAndIcon(view);
2449 // Update the lock icon image only once we are done loading
2450 updateLockIconToLatest();
2451 updateScreenshot(view);
2453 // Performance probe
2455 long[] sysCpu = new long[7];
2456 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2458 String uiInfo = "UI thread used "
2459 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2462 Log.d(LOGTAG, uiInfo);
2464 //The string that gets written to the log
2465 String performanceString = "It took total "
2466 + (SystemClock.uptimeMillis() - mStart)
2467 + " ms clock time to load the page."
2468 + "\nbrowser process used "
2469 + (Process.getElapsedCpuTime() - mProcessStart)
2470 + " ms, user processes used "
2471 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2472 + " ms, kernel used "
2473 + (sysCpu[2] - mSystemStart) * 10
2474 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2475 + " ms and irq took "
2476 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2477 * 10 + " ms, " + uiInfo;
2479 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2482 // strip the url to maintain consistency
2483 String newUrl = new String(url);
2484 if (newUrl.startsWith("http://www.")) {
2485 newUrl = newUrl.substring(11);
2486 } else if (newUrl.startsWith("http://")) {
2487 newUrl = newUrl.substring(7);
2488 } else if (newUrl.startsWith("https://www.")) {
2489 newUrl = newUrl.substring(12);
2490 } else if (newUrl.startsWith("https://")) {
2491 newUrl = newUrl.substring(8);
2494 Log.d(LOGTAG, newUrl + " loaded");
2497 if (sWhiteList.contains(newUrl)) {
2498 // The string that gets pushed to the statistcs
2500 performanceString = performanceString
2504 + android.os.SystemProperties
2505 .get("gsm.sim.operator.alpha");
2506 if (mWebView != null
2507 && mWebView.getContext() != null
2508 && mWebView.getContext().getSystemService(
2509 Context.CONNECTIVITY_SERVICE) != null) {
2510 ConnectivityManager cManager =
2511 (ConnectivityManager) mWebView
2512 .getContext().getSystemService(
2513 Context.CONNECTIVITY_SERVICE);
2514 NetworkInfo nInfo = cManager
2515 .getActiveNetworkInfo();
2516 if (nInfo != null) {
2517 performanceString = performanceString
2518 + "\nNetwork Type: "
2519 + nInfo.getType().toString();
2522 Checkin.logEvent(mResolver,
2523 Checkin.Events.Tag.WEBPAGE_LOAD,
2525 Log.w(LOGTAG, "pushed to the statistics service");
2534 Debug.stopMethodTracing();
2538 mPageStarted = false;
2539 // pauseWebViewTimers() will do nothing and return false if
2540 // onPause() is not called yet.
2541 if (pauseWebViewTimers()) {
2542 if (mWakeLock.isHeld()) {
2543 mHandler.removeMessages(RELEASE_WAKELOCK);
2544 mWakeLock.release();
2550 // return true if want to hijack the url to let another app to handle it
2552 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2553 if (url.startsWith(SCHEME_WTAI)) {
2554 // wtai://wp/mc;number
2555 // number=string(phone-number)
2556 if (url.startsWith(SCHEME_WTAI_MC)) {
2557 Intent intent = new Intent(Intent.ACTION_VIEW,
2558 Uri.parse(WebView.SCHEME_TEL +
2559 url.substring(SCHEME_WTAI_MC.length())));
2560 startActivity(intent);
2563 // wtai://wp/sd;dtmf
2564 // dtmf=string(dialstring)
2565 if (url.startsWith(SCHEME_WTAI_SD)) {
2567 // only send when there is active voice connection
2570 // wtai://wp/ap;number;name
2571 // number=string(phone-number)
2573 if (url.startsWith(SCHEME_WTAI_AP)) {
2579 // The "about:" schemes are internal to the browser; don't
2580 // want these to be dispatched to other apps.
2581 if (url.startsWith("about:")) {
2587 // perform generic parsing of the URI to turn it into an Intent.
2589 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2590 } catch (URISyntaxException ex) {
2591 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2595 // check whether the intent can be resolved. If not, we will see
2596 // whether we can download it from the Market.
2597 if (getPackageManager().resolveActivity(intent, 0) == null) {
2598 String packagename = intent.getPackage();
2599 if (packagename != null) {
2600 intent = new Intent(Intent.ACTION_VIEW, Uri
2601 .parse("market://search?q=pname:" + packagename));
2602 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2603 startActivity(intent);
2610 // sanitize the Intent, ensuring web pages can not bypass browser
2611 // security (only access to BROWSABLE activities).
2612 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2613 intent.setComponent(null);
2615 if (startActivityIfNeeded(intent, -1)) {
2618 } catch (ActivityNotFoundException ex) {
2619 // ignore the error. If no application can handle the URL,
2620 // eg about:blank, assume the browser can handle it.
2633 * Updates the lock icon. This method is called when we discover another
2634 * resource to be loaded for this page (for example, javascript). While
2635 * we update the icon type, we do not update the lock icon itself until
2636 * we are done loading, it is slightly more secure this way.
2639 public void onLoadResource(WebView view, String url) {
2640 if (url != null && url.length() > 0) {
2641 // It is only if the page claims to be secure
2642 // that we may have to update the lock:
2643 if (mLockIconType == LOCK_ICON_SECURE) {
2644 // If NOT a 'safe' url, change the lock to mixed content!
2645 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2646 mLockIconType = LOCK_ICON_MIXED;
2648 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2649 " updated lock icon to " + mLockIconType + " due to " + url);
2657 * Show the dialog, asking the user if they would like to continue after
2658 * an excessive number of HTTP redirects.
2661 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2662 final Message continueMsg) {
2663 new AlertDialog.Builder(BrowserActivity.this)
2664 .setTitle(R.string.browserFrameRedirect)
2665 .setMessage(R.string.browserFrame307Post)
2666 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2667 public void onClick(DialogInterface dialog, int which) {
2668 continueMsg.sendToTarget();
2670 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2671 public void onClick(DialogInterface dialog, int which) {
2672 cancelMsg.sendToTarget();
2674 .setOnCancelListener(new OnCancelListener() {
2675 public void onCancel(DialogInterface dialog) {
2676 cancelMsg.sendToTarget();
2681 // Container class for the next error dialog that needs to be
2684 public final int mTitle;
2685 public final String mDescription;
2686 public final int mError;
2687 ErrorDialog(int title, String desc, int error) {
2689 mDescription = desc;
2694 private void processNextError() {
2695 if (mQueuedErrors == null) {
2698 // The first one is currently displayed so just remove it.
2699 mQueuedErrors.removeFirst();
2700 if (mQueuedErrors.size() == 0) {
2701 mQueuedErrors = null;
2704 showError(mQueuedErrors.getFirst());
2707 private DialogInterface.OnDismissListener mDialogListener =
2708 new DialogInterface.OnDismissListener() {
2709 public void onDismiss(DialogInterface d) {
2713 private LinkedList<ErrorDialog> mQueuedErrors;
2715 private void queueError(int err, String desc) {
2716 if (mQueuedErrors == null) {
2717 mQueuedErrors = new LinkedList<ErrorDialog>();
2719 for (ErrorDialog d : mQueuedErrors) {
2720 if (d.mError == err) {
2721 // Already saw a similar error, ignore the new one.
2725 ErrorDialog errDialog = new ErrorDialog(
2726 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
2727 R.string.browserFrameFileErrorLabel :
2728 R.string.browserFrameNetworkErrorLabel,
2730 mQueuedErrors.addLast(errDialog);
2732 // Show the dialog now if the queue was empty.
2733 if (mQueuedErrors.size() == 1) {
2734 showError(errDialog);
2738 private void showError(ErrorDialog errDialog) {
2739 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2740 .setTitle(errDialog.mTitle)
2741 .setMessage(errDialog.mDescription)
2742 .setPositiveButton(R.string.ok, null)
2744 d.setOnDismissListener(mDialogListener);
2749 * Show a dialog informing the user of the network error reported by
2753 public void onReceivedError(WebView view, int errorCode,
2754 String description, String failingUrl) {
2755 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2756 errorCode != WebViewClient.ERROR_CONNECT &&
2757 errorCode != WebViewClient.ERROR_BAD_URL &&
2758 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2759 errorCode != WebViewClient.ERROR_FILE) {
2760 queueError(errorCode, description);
2762 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2763 + " " + description);
2765 // We need to reset the title after an error.
2766 resetTitleAndRevertLockIcon();
2770 * Check with the user if it is ok to resend POST data as the page they
2771 * are trying to navigate to is the result of a POST.
2774 public void onFormResubmission(WebView view, final Message dontResend,
2775 final Message resend) {
2776 new AlertDialog.Builder(BrowserActivity.this)
2777 .setTitle(R.string.browserFrameFormResubmitLabel)
2778 .setMessage(R.string.browserFrameFormResubmitMessage)
2779 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2780 public void onClick(DialogInterface dialog, int which) {
2781 resend.sendToTarget();
2783 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2784 public void onClick(DialogInterface dialog, int which) {
2785 dontResend.sendToTarget();
2787 .setOnCancelListener(new OnCancelListener() {
2788 public void onCancel(DialogInterface dialog) {
2789 dontResend.sendToTarget();
2795 * Insert the url into the visited history database.
2796 * @param url The url to be inserted.
2797 * @param isReload True if this url is being reloaded.
2798 * FIXME: Not sure what to do when reloading the page.
2801 public void doUpdateVisitedHistory(WebView view, String url,
2803 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2806 // remove "client" before updating it to the history so that it wont
2807 // show up in the auto-complete list.
2808 int index = url.indexOf("client=ms-");
2809 if (index > 0 && url.contains(".google.")) {
2810 int end = url.indexOf('&', index);
2812 url = url.substring(0, index-1).concat(url.substring(end));
2814 url = url.substring(0, index-1);
2817 Browser.updateVisitedHistory(mResolver, url, true);
2818 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2822 * Displays SSL error(s) dialog to the user.
2825 public void onReceivedSslError(
2826 final WebView view, final SslErrorHandler handler, final SslError error) {
2828 if (mSettings.showSecurityWarnings()) {
2829 final LayoutInflater factory =
2830 LayoutInflater.from(BrowserActivity.this);
2831 final View warningsView =
2832 factory.inflate(R.layout.ssl_warnings, null);
2833 final LinearLayout placeholder =
2834 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2836 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2837 LinearLayout ll = (LinearLayout)factory
2838 .inflate(R.layout.ssl_warning, null);
2839 ((TextView)ll.findViewById(R.id.warning))
2840 .setText(R.string.ssl_untrusted);
2841 placeholder.addView(ll);
2844 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2845 LinearLayout ll = (LinearLayout)factory
2846 .inflate(R.layout.ssl_warning, null);
2847 ((TextView)ll.findViewById(R.id.warning))
2848 .setText(R.string.ssl_mismatch);
2849 placeholder.addView(ll);
2852 if (error.hasError(SslError.SSL_EXPIRED)) {
2853 LinearLayout ll = (LinearLayout)factory
2854 .inflate(R.layout.ssl_warning, null);
2855 ((TextView)ll.findViewById(R.id.warning))
2856 .setText(R.string.ssl_expired);
2857 placeholder.addView(ll);
2860 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2861 LinearLayout ll = (LinearLayout)factory
2862 .inflate(R.layout.ssl_warning, null);
2863 ((TextView)ll.findViewById(R.id.warning))
2864 .setText(R.string.ssl_not_yet_valid);
2865 placeholder.addView(ll);
2868 new AlertDialog.Builder(BrowserActivity.this)
2869 .setTitle(R.string.security_warning)
2870 .setIcon(android.R.drawable.ic_dialog_alert)
2871 .setView(warningsView)
2872 .setPositiveButton(R.string.ssl_continue,
2873 new DialogInterface.OnClickListener() {
2874 public void onClick(DialogInterface dialog, int whichButton) {
2878 .setNeutralButton(R.string.view_certificate,
2879 new DialogInterface.OnClickListener() {
2880 public void onClick(DialogInterface dialog, int whichButton) {
2881 showSSLCertificateOnError(view, handler, error);
2884 .setNegativeButton(R.string.cancel,
2885 new DialogInterface.OnClickListener() {
2886 public void onClick(DialogInterface dialog, int whichButton) {
2888 BrowserActivity.this.resetTitleAndRevertLockIcon();
2891 .setOnCancelListener(
2892 new DialogInterface.OnCancelListener() {
2893 public void onCancel(DialogInterface dialog) {
2895 BrowserActivity.this.resetTitleAndRevertLockIcon();
2905 * Handles an HTTP authentication request.
2907 * @param handler The authentication handler
2908 * @param host The host
2909 * @param realm The realm
2912 public void onReceivedHttpAuthRequest(WebView view,
2913 final HttpAuthHandler handler, final String host, final String realm) {
2914 String username = null;
2915 String password = null;
2917 boolean reuseHttpAuthUsernamePassword =
2918 handler.useHttpAuthUsernamePassword();
2920 if (reuseHttpAuthUsernamePassword &&
2921 (mTabControl.getCurrentWebView() != null)) {
2922 String[] credentials =
2923 mTabControl.getCurrentWebView()
2924 .getHttpAuthUsernamePassword(host, realm);
2925 if (credentials != null && credentials.length == 2) {
2926 username = credentials[0];
2927 password = credentials[1];
2931 if (username != null && password != null) {
2932 handler.proceed(username, password);
2934 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2939 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2941 // only check shortcut key when MENU is held
2942 return getWindow().isShortcutKey(event.getKeyCode(), event);
2949 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2950 if (view != mTabControl.getCurrentTopWebView()) {
2953 if (event.isDown()) {
2954 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2956 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2961 //--------------------------------------------------------------------------
2962 // WebChromeClient implementation
2963 //--------------------------------------------------------------------------
2965 /* package */ WebChromeClient getWebChromeClient() {
2966 return mWebChromeClient;
2969 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2970 // Helper method to create a new tab or sub window.
2971 private void createWindow(final boolean dialog, final Message msg) {
2973 mTabControl.createSubWindow();
2974 final TabControl.Tab t = mTabControl.getCurrentTab();
2976 WebView.WebViewTransport transport =
2977 (WebView.WebViewTransport) msg.obj;
2978 transport.setWebView(t.getSubWebView());
2981 final TabControl.Tab parent = mTabControl.getCurrentTab();
2982 final TabControl.Tab newTab
2983 = openTabAndShow(EMPTY_URL_DATA, false, null);
2984 if (newTab != parent) {
2985 parent.addChildTab(newTab);
2987 WebView.WebViewTransport transport =
2988 (WebView.WebViewTransport) msg.obj;
2989 transport.setWebView(mTabControl.getCurrentWebView());
2995 public boolean onCreateWindow(WebView view, final boolean dialog,
2996 final boolean userGesture, final Message resultMsg) {
2997 // Short-circuit if we can't create any more tabs or sub windows.
2998 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2999 new AlertDialog.Builder(BrowserActivity.this)
3000 .setTitle(R.string.too_many_subwindows_dialog_title)
3001 .setIcon(android.R.drawable.ic_dialog_alert)
3002 .setMessage(R.string.too_many_subwindows_dialog_message)
3003 .setPositiveButton(R.string.ok, null)
3006 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3007 new AlertDialog.Builder(BrowserActivity.this)
3008 .setTitle(R.string.too_many_windows_dialog_title)
3009 .setIcon(android.R.drawable.ic_dialog_alert)
3010 .setMessage(R.string.too_many_windows_dialog_message)
3011 .setPositiveButton(R.string.ok, null)
3016 // Short-circuit if this was a user gesture.
3018 createWindow(dialog, resultMsg);
3022 // Allow the popup and create the appropriate window.
3023 final AlertDialog.OnClickListener allowListener =
3024 new AlertDialog.OnClickListener() {
3025 public void onClick(DialogInterface d,
3027 createWindow(dialog, resultMsg);
3031 // Block the popup by returning a null WebView.
3032 final AlertDialog.OnClickListener blockListener =
3033 new AlertDialog.OnClickListener() {
3034 public void onClick(DialogInterface d, int which) {
3035 resultMsg.sendToTarget();
3039 // Build a confirmation dialog to display to the user.
3040 final AlertDialog d =
3041 new AlertDialog.Builder(BrowserActivity.this)
3042 .setTitle(R.string.attention)
3043 .setIcon(android.R.drawable.ic_dialog_alert)
3044 .setMessage(R.string.popup_window_attempt)
3045 .setPositiveButton(R.string.allow, allowListener)
3046 .setNegativeButton(R.string.block, blockListener)
3047 .setCancelable(false)
3050 // Show the confirmation dialog.
3056 public void onCloseWindow(WebView window) {
3057 final TabControl.Tab current = mTabControl.getCurrentTab();
3058 final TabControl.Tab parent = current.getParentTab();
3059 if (parent != null) {
3060 // JavaScript can only close popup window.
3061 switchToTab(mTabControl.getTabIndex(parent));
3062 // Now we need to close the window
3068 public void onProgressChanged(WebView view, int newProgress) {
3069 mTitleBar.setProgress(newProgress);
3070 if (mFakeTitleBar != null) {
3071 mFakeTitleBar.setProgress(newProgress);
3074 if (newProgress == 100) {
3075 // onProgressChanged() is called for sub-frame too while
3076 // onPageFinished() is only called for the main frame. sync
3077 // cookie and cache promptly here.
3078 CookieSyncManager.getInstance().sync();
3081 updateInLoadMenuItems();
3082 // If the options menu is open, leave the title bar
3083 if (!mOptionsMenuOpen || !mIconView) {
3087 } else if (!mInLoad) {
3088 // onPageFinished may have already been called but a subframe
3089 // is still loading and updating the progress. Reset mInLoad
3090 // and update the menu items.
3092 updateInLoadMenuItems();
3093 WebView currentWebView = mTabControl.getCurrentWebView();
3094 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3095 && (!mOptionsMenuOpen || mIconView)) {
3096 // This page has begun to load, so show the title bar
3103 public void onReceivedTitle(WebView view, String title) {
3104 String url = view.getUrl();
3106 // here, if url is null, we want to reset the title
3107 setUrlTitle(url, title);
3110 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3113 // See if we can find the current url in our history database and
3114 // add the new title to it.
3115 if (url.startsWith("http://www.")) {
3116 url = url.substring(11);
3117 } else if (url.startsWith("http://")) {
3118 url = url.substring(4);
3122 String [] selArgs = new String[] { url };
3124 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3125 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3126 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3127 Browser.HISTORY_PROJECTION, where, selArgs, null);
3128 if (c.moveToFirst()) {
3129 // Current implementation of database only has one entry per
3131 ContentValues map = new ContentValues();
3132 map.put(Browser.BookmarkColumns.TITLE, title);
3133 mResolver.update(Browser.BOOKMARKS_URI, map,
3134 "_id = " + c.getInt(0), null);
3137 } catch (IllegalStateException e) {
3138 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3139 } catch (SQLiteException ex) {
3140 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3145 public void onReceivedIcon(WebView view, Bitmap icon) {
3146 updateIcon(view, icon);
3150 public void onReceivedTouchIconUrl(WebView view, String url) {
3151 final ContentResolver cr = getContentResolver();
3153 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
3154 view.getOriginalUrl(), view.getUrl(), true);
3156 if (c.getCount() > 0) {
3157 new DownloadTouchIcon(cr, c, view).execute(url);
3165 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
3166 if (mCustomView != null)
3169 // Add the custom view to its container.
3170 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3172 mCustomViewCallback = callback;
3173 // Save the menu state and set it to empty while the custom
3175 mOldMenuState = mMenuState;
3176 mMenuState = EMPTY_MENU;
3177 // Hide the content view.
3178 mContentView.setVisibility(View.GONE);
3179 // Finally show the custom view container.
3180 mCustomViewContainer.setVisibility(View.VISIBLE);
3181 mCustomViewContainer.bringToFront();
3185 public void onHideCustomView() {
3186 if (mCustomView == null)
3189 // Hide the custom view.
3190 mCustomView.setVisibility(View.GONE);
3191 // Remove the custom view from its container.
3192 mCustomViewContainer.removeView(mCustomView);
3194 // Reset the old menu state.
3195 mMenuState = mOldMenuState;
3196 mOldMenuState = EMPTY_MENU;
3197 mCustomViewContainer.setVisibility(View.GONE);
3198 mCustomViewCallback.onCustomViewHidden();
3199 // Show the content view.
3200 mContentView.setVisibility(View.VISIBLE);
3204 * The origin has exceeded its database quota.
3205 * @param url the URL that exceeded the quota
3206 * @param databaseIdentifier the identifier of the database on
3207 * which the transaction that caused the quota overflow was run
3208 * @param currentQuota the current quota for the origin.
3209 * @param estimatedSize the estimated size of the database.
3210 * @param totalUsedQuota is the sum of all origins' quota.
3211 * @param quotaUpdater The callback to run when a decision to allow or
3212 * deny quota has been made. Don't forget to call this!
3215 public void onExceededDatabaseQuota(String url,
3216 String databaseIdentifier, long currentQuota, long estimatedSize,
3217 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3218 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3219 url, databaseIdentifier, currentQuota, estimatedSize,
3220 totalUsedQuota, quotaUpdater);
3224 * The Application Cache has exceeded its max size.
3225 * @param spaceNeeded is the amount of disk space that would be needed
3226 * in order for the last appcache operation to succeed.
3227 * @param totalUsedQuota is the sum of all origins' quota.
3228 * @param quotaUpdater A callback to inform the WebCore thread that a new
3229 * app cache size is available. This callback must always be executed at
3230 * some point to ensure that the sleeping WebCore thread is woken up.
3233 public void onReachedMaxAppCacheSize(long spaceNeeded,
3234 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3235 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3236 spaceNeeded, totalUsedQuota, quotaUpdater);
3240 * Instructs the browser to show a prompt to ask the user to set the
3241 * Geolocation permission state for the specified origin.
3242 * @param origin The origin for which Geolocation permissions are
3244 * @param callback The callback to call once the user has set the
3245 * Geolocation permission state.
3248 public void onGeolocationPermissionsShowPrompt(String origin,
3249 GeolocationPermissions.Callback callback) {
3250 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3255 * Instructs the browser to hide the Geolocation permissions prompt.
3258 public void onGeolocationPermissionsHidePrompt() {
3259 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3262 /* Adds a JavaScript error message to the system log.
3263 * @param message The error message to report.
3264 * @param lineNumber The line number of the error.
3265 * @param sourceID The name of the source file that caused the error.
3268 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3269 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3270 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3271 if (mShouldShowErrorConsole &&
3272 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3273 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3275 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
3280 * Notify the host application a download should be done, or that
3281 * the data should be streamed if a streaming viewer is available.
3282 * @param url The full url to the content that should be downloaded
3283 * @param contentDisposition Content-disposition http header, if
3285 * @param mimetype The mimetype of the content reported by the server
3286 * @param contentLength The file size reported by the server
3288 public void onDownloadStart(String url, String userAgent,
3289 String contentDisposition, String mimetype, long contentLength) {
3290 // if we're dealing wih A/V content that's not explicitly marked
3291 // for download, check if it's streamable.
3292 if (contentDisposition == null
3293 || !contentDisposition.regionMatches(
3294 true, 0, "attachment", 0, 10)) {
3295 // query the package manager to see if there's a registered handler
3297 Intent intent = new Intent(Intent.ACTION_VIEW);
3298 intent.setDataAndType(Uri.parse(url), mimetype);
3299 ResolveInfo info = getPackageManager().resolveActivity(intent,
3300 PackageManager.MATCH_DEFAULT_ONLY);
3302 ComponentName myName = getComponentName();
3303 // If we resolved to ourselves, we don't want to attempt to
3304 // load the url only to try and download it again.
3305 if (!myName.getPackageName().equals(
3306 info.activityInfo.packageName)
3307 || !myName.getClassName().equals(
3308 info.activityInfo.name)) {
3309 // someone (other than us) knows how to handle this mime
3310 // type with this scheme, don't download.
3312 startActivity(intent);
3314 } catch (ActivityNotFoundException ex) {
3316 Log.d(LOGTAG, "activity not found for " + mimetype
3317 + " over " + Uri.parse(url).getScheme(),
3320 // Best behavior is to fall back to a download in this
3326 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3330 * Notify the host application a download should be done, even if there
3331 * is a streaming viewer available for thise type.
3332 * @param url The full url to the content that should be downloaded
3333 * @param contentDisposition Content-disposition http header, if
3335 * @param mimetype The mimetype of the content reported by the server
3336 * @param contentLength The file size reported by the server
3338 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3339 String contentDisposition, String mimetype, long contentLength) {
3341 String filename = URLUtil.guessFileName(url,
3342 contentDisposition, mimetype);
3344 // Check to see if we have an SDCard
3345 String status = Environment.getExternalStorageState();
3346 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3350 // Check to see if the SDCard is busy, same as the music app
3351 if (status.equals(Environment.MEDIA_SHARED)) {
3352 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3353 title = R.string.download_sdcard_busy_dlg_title;
3355 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3356 title = R.string.download_no_sdcard_dlg_title;
3359 new AlertDialog.Builder(this)
3361 .setIcon(android.R.drawable.ic_dialog_alert)
3363 .setPositiveButton(R.string.ok, null)
3368 // java.net.URI is a lot stricter than KURL so we have to undo
3369 // KURL's percent-encoding and redo the encoding using java.net.URI.
3372 // Undo the percent-encoding that KURL may have done.
3373 String newUrl = new String(URLUtil.decode(url.getBytes()));
3374 // Parse the url into pieces
3375 WebAddress w = new WebAddress(newUrl);
3377 String query = null;
3378 String path = w.mPath;
3379 // Break the path into path, query, and fragment
3380 if (path.length() > 0) {
3381 // Strip the fragment
3382 int idx = path.lastIndexOf('#');
3384 frag = path.substring(idx + 1);
3385 path = path.substring(0, idx);
3387 idx = path.lastIndexOf('?');
3389 query = path.substring(idx + 1);
3390 path = path.substring(0, idx);
3393 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3395 } catch (Exception e) {
3396 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3400 // XXX: Have to use the old url since the cookies were stored using the
3401 // old percent-encoded url.
3402 String cookies = CookieManager.getInstance().getCookie(url);
3404 ContentValues values = new ContentValues();
3405 values.put(Downloads.COLUMN_URI, uri.toString());
3406 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3407 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3408 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
3410 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
3411 BrowserDownloadPage.class.getCanonicalName());
3412 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3413 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3414 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3415 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
3416 if (contentLength > 0) {
3417 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
3419 if (mimetype == null) {
3420 // We must have long pressed on a link or image to download it. We
3421 // are not sure of the mimetype in this case, so do a head request
3422 new FetchUrlMimeType(this).execute(values);
3424 final Uri contentUri =
3425 getContentResolver().insert(Downloads.CONTENT_URI, values);
3426 viewDownloads(contentUri);
3432 * Resets the lock icon. This method is called when we start a new load and
3433 * know the url to be loaded.
3435 private void resetLockIcon(String url) {
3436 // Save the lock-icon state (we revert to it if the load gets cancelled)
3439 mLockIconType = LOCK_ICON_UNSECURE;
3440 if (URLUtil.isHttpsUrl(url)) {
3441 mLockIconType = LOCK_ICON_SECURE;
3443 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3444 " reset lock icon to " + mLockIconType);
3448 updateLockIconImage(LOCK_ICON_UNSECURE);
3451 /* package */ void setLockIconType(int type) {
3452 mLockIconType = type;
3455 /* package */ int getLockIconType() {
3456 return mLockIconType;
3459 /* package */ void setPrevLockType(int type) {
3460 mPrevLockType = type;
3463 /* package */ int getPrevLockType() {
3464 return mPrevLockType;
3468 * Update the lock icon to correspond to our latest state.
3470 /* package */ void updateLockIconToLatest() {
3471 updateLockIconImage(mLockIconType);
3475 * Updates the lock-icon image in the title-bar.
3477 private void updateLockIconImage(int lockIconType) {
3479 if (lockIconType == LOCK_ICON_SECURE) {
3481 } else if (lockIconType == LOCK_ICON_MIXED) {
3484 mTitleBar.setLock(d);
3485 if (mFakeTitleBar != null) {
3486 mFakeTitleBar.setLock(d);
3491 * Displays a page-info dialog.
3492 * @param tab The tab to show info about
3493 * @param fromShowSSLCertificateOnError The flag that indicates whether
3494 * this dialog was opened from the SSL-certificate-on-error dialog or
3495 * not. This is important, since we need to know whether to return to
3496 * the parent dialog or simply dismiss.
3498 private void showPageInfo(final TabControl.Tab tab,
3499 final boolean fromShowSSLCertificateOnError) {
3500 final LayoutInflater factory = LayoutInflater
3503 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3505 final WebView view = tab.getWebView();
3508 String title = null;
3512 title = tab.getTitle();
3513 } else if (view == mTabControl.getCurrentWebView()) {
3514 // Use the cached title and url if this is the current WebView
3518 url = view.getUrl();
3519 title = view.getTitle();
3525 if (title == null) {
3529 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3530 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3532 mPageInfoView = tab;
3533 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3535 AlertDialog.Builder alertDialogBuilder =
3536 new AlertDialog.Builder(this)
3537 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3538 .setView(pageInfoView)
3541 new DialogInterface.OnClickListener() {
3542 public void onClick(DialogInterface dialog,
3544 mPageInfoDialog = null;
3545 mPageInfoView = null;
3546 mPageInfoFromShowSSLCertificateOnError = null;
3548 // if we came here from the SSL error dialog
3549 if (fromShowSSLCertificateOnError) {
3550 // go back to the SSL error dialog
3551 showSSLCertificateOnError(
3552 mSSLCertificateOnErrorView,
3553 mSSLCertificateOnErrorHandler,
3554 mSSLCertificateOnErrorError);
3558 .setOnCancelListener(
3559 new DialogInterface.OnCancelListener() {
3560 public void onCancel(DialogInterface dialog) {
3561 mPageInfoDialog = null;
3562 mPageInfoView = null;
3563 mPageInfoFromShowSSLCertificateOnError = null;
3565 // if we came here from the SSL error dialog
3566 if (fromShowSSLCertificateOnError) {
3567 // go back to the SSL error dialog
3568 showSSLCertificateOnError(
3569 mSSLCertificateOnErrorView,
3570 mSSLCertificateOnErrorHandler,
3571 mSSLCertificateOnErrorError);
3576 // if we have a main top-level page SSL certificate set or a certificate
3578 if (fromShowSSLCertificateOnError ||
3579 (view != null && view.getCertificate() != null)) {
3580 // add a 'View Certificate' button
3581 alertDialogBuilder.setNeutralButton(
3582 R.string.view_certificate,
3583 new DialogInterface.OnClickListener() {
3584 public void onClick(DialogInterface dialog,
3586 mPageInfoDialog = null;
3587 mPageInfoView = null;
3588 mPageInfoFromShowSSLCertificateOnError = null;
3590 // if we came here from the SSL error dialog
3591 if (fromShowSSLCertificateOnError) {
3592 // go back to the SSL error dialog
3593 showSSLCertificateOnError(
3594 mSSLCertificateOnErrorView,
3595 mSSLCertificateOnErrorHandler,
3596 mSSLCertificateOnErrorError);
3598 // otherwise, display the top-most certificate from
3600 if (view.getCertificate() != null) {
3601 showSSLCertificate(tab);
3608 mPageInfoDialog = alertDialogBuilder.show();
3612 * Displays the main top-level page SSL certificate dialog
3613 * (accessible from the Page-Info dialog).
3614 * @param tab The tab to show certificate for.
3616 private void showSSLCertificate(final TabControl.Tab tab) {
3617 final View certificateView =
3618 inflateCertificateView(tab.getWebView().getCertificate());
3619 if (certificateView == null) {
3623 LayoutInflater factory = LayoutInflater.from(this);
3625 final LinearLayout placeholder =
3626 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3628 LinearLayout ll = (LinearLayout) factory.inflate(
3629 R.layout.ssl_success, placeholder);
3630 ((TextView)ll.findViewById(R.id.success))
3631 .setText(R.string.ssl_certificate_is_valid);
3633 mSSLCertificateView = tab;
3634 mSSLCertificateDialog =
3635 new AlertDialog.Builder(this)
3636 .setTitle(R.string.ssl_certificate).setIcon(
3637 R.drawable.ic_dialog_browser_certificate_secure)
3638 .setView(certificateView)
3639 .setPositiveButton(R.string.ok,
3640 new DialogInterface.OnClickListener() {
3641 public void onClick(DialogInterface dialog,
3643 mSSLCertificateDialog = null;
3644 mSSLCertificateView = null;
3646 showPageInfo(tab, false);
3649 .setOnCancelListener(
3650 new DialogInterface.OnCancelListener() {
3651 public void onCancel(DialogInterface dialog) {
3652 mSSLCertificateDialog = null;
3653 mSSLCertificateView = null;
3655 showPageInfo(tab, false);
3662 * Displays the SSL error certificate dialog.
3663 * @param view The target web-view.
3664 * @param handler The SSL error handler responsible for cancelling the
3665 * connection that resulted in an SSL error or proceeding per user request.
3666 * @param error The SSL error object.
3668 private void showSSLCertificateOnError(
3669 final WebView view, final SslErrorHandler handler, final SslError error) {
3671 final View certificateView =
3672 inflateCertificateView(error.getCertificate());
3673 if (certificateView == null) {
3677 LayoutInflater factory = LayoutInflater.from(this);
3679 final LinearLayout placeholder =
3680 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3682 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3683 LinearLayout ll = (LinearLayout)factory
3684 .inflate(R.layout.ssl_warning, placeholder);
3685 ((TextView)ll.findViewById(R.id.warning))
3686 .setText(R.string.ssl_untrusted);
3689 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3690 LinearLayout ll = (LinearLayout)factory
3691 .inflate(R.layout.ssl_warning, placeholder);
3692 ((TextView)ll.findViewById(R.id.warning))
3693 .setText(R.string.ssl_mismatch);
3696 if (error.hasError(SslError.SSL_EXPIRED)) {
3697 LinearLayout ll = (LinearLayout)factory
3698 .inflate(R.layout.ssl_warning, placeholder);
3699 ((TextView)ll.findViewById(R.id.warning))
3700 .setText(R.string.ssl_expired);
3703 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3704 LinearLayout ll = (LinearLayout)factory
3705 .inflate(R.layout.ssl_warning, placeholder);
3706 ((TextView)ll.findViewById(R.id.warning))
3707 .setText(R.string.ssl_not_yet_valid);
3710 mSSLCertificateOnErrorHandler = handler;
3711 mSSLCertificateOnErrorView = view;
3712 mSSLCertificateOnErrorError = error;
3713 mSSLCertificateOnErrorDialog =
3714 new AlertDialog.Builder(this)
3715 .setTitle(R.string.ssl_certificate).setIcon(
3716 R.drawable.ic_dialog_browser_certificate_partially_secure)
3717 .setView(certificateView)
3718 .setPositiveButton(R.string.ok,
3719 new DialogInterface.OnClickListener() {
3720 public void onClick(DialogInterface dialog,
3722 mSSLCertificateOnErrorDialog = null;
3723 mSSLCertificateOnErrorView = null;
3724 mSSLCertificateOnErrorHandler = null;
3725 mSSLCertificateOnErrorError = null;
3727 mWebViewClient.onReceivedSslError(
3728 view, handler, error);
3731 .setNeutralButton(R.string.page_info_view,
3732 new DialogInterface.OnClickListener() {
3733 public void onClick(DialogInterface dialog,
3735 mSSLCertificateOnErrorDialog = null;
3737 // do not clear the dialog state: we will
3738 // need to show the dialog again once the
3739 // user is done exploring the page-info details
3741 showPageInfo(mTabControl.getTabFromView(view),
3745 .setOnCancelListener(
3746 new DialogInterface.OnCancelListener() {
3747 public void onCancel(DialogInterface dialog) {
3748 mSSLCertificateOnErrorDialog = null;
3749 mSSLCertificateOnErrorView = null;
3750 mSSLCertificateOnErrorHandler = null;
3751 mSSLCertificateOnErrorError = null;
3753 mWebViewClient.onReceivedSslError(
3754 view, handler, error);
3761 * Inflates the SSL certificate view (helper method).
3762 * @param certificate The SSL certificate.
3763 * @return The resultant certificate view with issued-to, issued-by,
3764 * issued-on, expires-on, and possibly other fields set.
3765 * If the input certificate is null, returns null.
3767 private View inflateCertificateView(SslCertificate certificate) {
3768 if (certificate == null) {
3772 LayoutInflater factory = LayoutInflater.from(this);
3774 View certificateView = factory.inflate(
3775 R.layout.ssl_certificate, null);
3778 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3779 if (issuedTo != null) {
3780 ((TextView) certificateView.findViewById(R.id.to_common))
3781 .setText(issuedTo.getCName());
3782 ((TextView) certificateView.findViewById(R.id.to_org))
3783 .setText(issuedTo.getOName());
3784 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3785 .setText(issuedTo.getUName());
3789 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3790 if (issuedBy != null) {
3791 ((TextView) certificateView.findViewById(R.id.by_common))
3792 .setText(issuedBy.getCName());
3793 ((TextView) certificateView.findViewById(R.id.by_org))
3794 .setText(issuedBy.getOName());
3795 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3796 .setText(issuedBy.getUName());
3800 String issuedOn = reformatCertificateDate(
3801 certificate.getValidNotBefore());
3802 ((TextView) certificateView.findViewById(R.id.issued_on))
3806 String expiresOn = reformatCertificateDate(
3807 certificate.getValidNotAfter());
3808 ((TextView) certificateView.findViewById(R.id.expires_on))
3809 .setText(expiresOn);
3811 return certificateView;
3815 * Re-formats the certificate date (Date.toString()) string to
3816 * a properly localized date string.
3817 * @return Properly localized version of the certificate date string and
3818 * the original certificate date string if fails to localize.
3819 * If the original string is null, returns an empty string "".
3821 private String reformatCertificateDate(String certificateDate) {
3822 String reformattedDate = null;
3824 if (certificateDate != null) {
3827 date = java.text.DateFormat.getInstance().parse(certificateDate);
3828 } catch (ParseException e) {
3834 DateFormat.getDateFormat(this).format(date);
3838 return reformattedDate != null ? reformattedDate :
3839 (certificateDate != null ? certificateDate : "");
3843 * Displays an http-authentication dialog.
3845 private void showHttpAuthentication(final HttpAuthHandler handler,
3846 final String host, final String realm, final String title,
3847 final String name, final String password, int focusId) {
3848 LayoutInflater factory = LayoutInflater.from(this);
3849 final View v = factory
3850 .inflate(R.layout.http_authentication, null);
3852 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3854 if (password != null) {
3855 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3858 String titleText = title;
3859 if (titleText == null) {
3860 titleText = getText(R.string.sign_in_to).toString().replace(
3861 "%s1", host).replace("%s2", realm);
3864 mHttpAuthHandler = handler;
3865 AlertDialog dialog = new AlertDialog.Builder(this)
3866 .setTitle(titleText)
3867 .setIcon(android.R.drawable.ic_dialog_alert)
3869 .setPositiveButton(R.string.action,
3870 new DialogInterface.OnClickListener() {
3871 public void onClick(DialogInterface dialog,
3873 String nm = ((EditText) v
3874 .findViewById(R.id.username_edit))
3875 .getText().toString();
3876 String pw = ((EditText) v
3877 .findViewById(R.id.password_edit))
3878 .getText().toString();
3879 BrowserActivity.this.setHttpAuthUsernamePassword
3880 (host, realm, nm, pw);
3881 handler.proceed(nm, pw);
3882 mHttpAuthenticationDialog = null;
3883 mHttpAuthHandler = null;
3885 .setNegativeButton(R.string.cancel,
3886 new DialogInterface.OnClickListener() {
3887 public void onClick(DialogInterface dialog,
3890 BrowserActivity.this.resetTitleAndRevertLockIcon();
3891 mHttpAuthenticationDialog = null;
3892 mHttpAuthHandler = null;
3894 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3895 public void onCancel(DialogInterface dialog) {
3897 BrowserActivity.this.resetTitleAndRevertLockIcon();
3898 mHttpAuthenticationDialog = null;
3899 mHttpAuthHandler = null;
3902 // Make the IME appear when the dialog is displayed if applicable.
3903 dialog.getWindow().setSoftInputMode(
3904 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3907 dialog.findViewById(focusId).requestFocus();
3909 v.findViewById(R.id.username_edit).requestFocus();
3911 mHttpAuthenticationDialog = dialog;
3914 public int getProgress() {
3915 WebView w = mTabControl.getCurrentWebView();
3917 return w.getProgress();
3924 * Set HTTP authentication password.
3926 * @param host The host for the password
3927 * @param realm The realm for the password
3928 * @param username The username for the password. If it is null, it means
3929 * password can't be saved.
3930 * @param password The password
3932 public void setHttpAuthUsernamePassword(String host, String realm,
3935 WebView w = mTabControl.getCurrentWebView();
3937 w.setHttpAuthUsernamePassword(host, realm, username, password);
3942 * connectivity manager says net has come or gone... inform the user
3943 * @param up true if net has come up, false if net has gone down
3945 public void onNetworkToggle(boolean up) {
3946 if (up == mIsNetworkUp) {
3949 mIsNetworkUp = true;
3950 if (mAlertDialog != null) {
3951 mAlertDialog.cancel();
3952 mAlertDialog = null;
3955 mIsNetworkUp = false;
3957 createAndShowNetworkDialog();
3960 WebView w = mTabControl.getCurrentWebView();
3962 w.setNetworkAvailable(up);
3966 // This method shows the network dialog alerting the user that the net is
3967 // down. It will only show the dialog if mAlertDialog is null.
3968 private void createAndShowNetworkDialog() {
3969 if (mAlertDialog == null) {
3970 mAlertDialog = new AlertDialog.Builder(this)
3971 .setTitle(R.string.loadSuspendedTitle)
3972 .setMessage(R.string.loadSuspended)
3973 .setPositiveButton(R.string.ok, null)
3979 protected void onActivityResult(int requestCode, int resultCode,
3981 switch (requestCode) {
3983 if (resultCode == RESULT_OK && intent != null) {
3984 String data = intent.getAction();
3985 Bundle extras = intent.getExtras();
3986 if (extras != null && extras.getBoolean("new_window", false)) {
3989 final TabControl.Tab currentTab =
3990 mTabControl.getCurrentTab();
3991 dismissSubWindow(currentTab);
3992 if (data != null && data.length() != 0) {
3993 getTopWindow().loadUrl(data);
4001 getTopWindow().requestFocus();
4005 * This method is called as a result of the user selecting the options
4006 * menu to see the download window, or when a download changes state. It
4007 * shows the download window ontop of the current window.
4009 /* package */ void viewDownloads(Uri downloadRecord) {
4010 Intent intent = new Intent(this,
4011 BrowserDownloadPage.class);
4012 intent.setData(downloadRecord);
4013 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4019 * @param startWithHistory If true, open starting on the history tab.
4020 * Otherwise, start with the bookmarks tab.
4022 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
4023 WebView current = mTabControl.getCurrentWebView();
4024 if (current == null) {
4027 Intent intent = new Intent(this,
4028 CombinedBookmarkHistoryActivity.class);
4029 String title = current.getTitle();
4030 String url = current.getUrl();
4031 // Just in case the user opens bookmarks before a page finishes loading
4032 // so the current history item, and therefore the page, is null.
4034 url = mLastEnteredUrl;
4037 url = mSettings.getHomePage();
4040 // In case the web page has not yet received its associated title.
4041 if (title == null) {
4044 intent.putExtra("title", title);
4045 intent.putExtra("url", url);
4046 // Disable opening in a new window if we have maxed out the windows
4047 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4048 >= TabControl.MAX_TABS);
4049 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
4050 if (startWithHistory) {
4051 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4052 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4054 startActivityForResult(intent, COMBO_PAGE);
4057 // Called when loading from context menu or LOAD_URL message
4058 private void loadURL(WebView view, String url) {
4059 // In case the user enters nothing.
4060 if (url != null && url.length() != 0 && view != null) {
4061 url = smartUrlFilter(url);
4062 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4068 private String smartUrlFilter(Uri inUri) {
4069 if (inUri != null) {
4070 return smartUrlFilter(inUri.toString());
4078 int getWindowCount(){
4079 if(mTabControl != null){
4080 return mTabControl.getTabCount();
4085 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4086 "(?i)" + // switch on case insensitive matching
4087 "(" + // begin group for schema
4088 "(?:http|https|file):\\/\\/" +
4089 "|(?:inline|data|about|content|javascript):" +
4094 * Attempts to determine whether user input is a URL or search
4095 * terms. Anything with a space is passed to search.
4097 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4098 * "Http://" converts to "http://"
4100 * @return Original or modified URL
4103 String smartUrlFilter(String url) {
4105 String inUrl = url.trim();
4106 boolean hasSpace = inUrl.indexOf(' ') != -1;
4108 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4109 if (matcher.matches()) {
4110 // force scheme to lowercase
4111 String scheme = matcher.group(1);
4112 String lcScheme = scheme.toLowerCase();
4113 if (!lcScheme.equals(scheme)) {
4114 inUrl = lcScheme + matcher.group(2);
4117 inUrl = inUrl.replace(" ", "%20");
4122 // FIXME: Is this the correct place to add to searches?
4123 // what if someone else calls this function?
4124 int shortcut = parseUrlShortcut(inUrl);
4125 if (shortcut != SHORTCUT_INVALID) {
4126 Browser.addSearchUrl(mResolver, inUrl);
4127 String query = inUrl.substring(2);
4129 case SHORTCUT_GOOGLE_SEARCH:
4130 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
4131 case SHORTCUT_WIKIPEDIA_SEARCH:
4132 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4133 case SHORTCUT_DICTIONARY_SEARCH:
4134 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4135 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
4136 // FIXME: we need location in this case
4137 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
4141 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4142 return URLUtil.guessUrl(inUrl);
4146 Browser.addSearchUrl(mResolver, inUrl);
4147 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
4150 /* package */ void setShouldShowErrorConsole(boolean flag) {
4151 if (flag == mShouldShowErrorConsole) {
4156 mShouldShowErrorConsole = flag;
4158 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4161 // Setting the show state of the console will cause it's the layout to be inflated.
4162 if (errorConsole.numberOfErrors() > 0) {
4163 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4165 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4168 // Now we can add it to the main view.
4169 mErrorConsoleContainer.addView(errorConsole,
4170 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4171 ViewGroup.LayoutParams.WRAP_CONTENT));
4173 mErrorConsoleContainer.removeView(errorConsole);
4178 final static int LOCK_ICON_UNSECURE = 0;
4179 final static int LOCK_ICON_SECURE = 1;
4180 final static int LOCK_ICON_MIXED = 2;
4182 private int mLockIconType = LOCK_ICON_UNSECURE;
4183 private int mPrevLockType = LOCK_ICON_UNSECURE;
4185 private BrowserSettings mSettings;
4186 private TabControl mTabControl;
4187 private ContentResolver mResolver;
4188 private FrameLayout mContentView;
4189 private View mCustomView;
4190 private FrameLayout mCustomViewContainer;
4191 private WebChromeClient.CustomViewCallback mCustomViewCallback;
4193 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4194 // view, we should rewrite this.
4195 private int mCurrentMenuState = 0;
4196 private int mMenuState = R.id.MAIN_MENU;
4197 private int mOldMenuState = EMPTY_MENU;
4198 private static final int EMPTY_MENU = -1;
4201 private FindDialog mFindDialog;
4202 // Used to prevent chording to result in firing two shortcuts immediately
4203 // one after another. Fixes bug 1211714.
4206 private boolean mInLoad;
4207 private boolean mIsNetworkUp;
4209 private boolean mPageStarted;
4210 private boolean mActivityInPause = true;
4212 private boolean mMenuIsDown;
4214 private final KeyTracker mKeyTracker = new KeyTracker(this);
4216 // As trackball doesn't send repeat down, we have to track it ourselves
4217 private boolean mTrackTrackball;
4219 private static boolean mInTrace;
4221 // Performance probe
4222 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4223 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4224 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4225 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4226 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4227 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4228 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4229 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4230 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4233 private long mStart;
4234 private long mProcessStart;
4235 private long mUserStart;
4236 private long mSystemStart;
4237 private long mIdleStart;
4238 private long mIrqStart;
4240 private long mUiStart;
4242 private Drawable mMixLockIcon;
4243 private Drawable mSecLockIcon;
4245 /* hold a ref so we can auto-cancel if necessary */
4246 private AlertDialog mAlertDialog;
4248 // Wait for credentials before loading google.com
4249 private ProgressDialog mCredsDlg;
4251 // The up-to-date URL and title (these can be different from those stored
4252 // in WebView, since it takes some time for the information in WebView to
4254 private String mUrl;
4255 private String mTitle;
4257 // As PageInfo has different style for landscape / portrait, we have
4258 // to re-open it when configuration changed
4259 private AlertDialog mPageInfoDialog;
4260 private TabControl.Tab mPageInfoView;
4261 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4262 // dialog, we should not just dismiss it, but should get back to the
4263 // SSL-certificate-on-error dialog. This flag is used to store this state
4264 private Boolean mPageInfoFromShowSSLCertificateOnError;
4266 // as SSLCertificateOnError has different style for landscape / portrait,
4267 // we have to re-open it when configuration changed
4268 private AlertDialog mSSLCertificateOnErrorDialog;
4269 private WebView mSSLCertificateOnErrorView;
4270 private SslErrorHandler mSSLCertificateOnErrorHandler;
4271 private SslError mSSLCertificateOnErrorError;
4273 // as SSLCertificate has different style for landscape / portrait, we
4274 // have to re-open it when configuration changed
4275 private AlertDialog mSSLCertificateDialog;
4276 private TabControl.Tab mSSLCertificateView;
4278 // as HttpAuthentication has different style for landscape / portrait, we
4279 // have to re-open it when configuration changed
4280 private AlertDialog mHttpAuthenticationDialog;
4281 private HttpAuthHandler mHttpAuthHandler;
4283 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4284 new FrameLayout.LayoutParams(
4285 ViewGroup.LayoutParams.FILL_PARENT,
4286 ViewGroup.LayoutParams.FILL_PARENT);
4287 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4288 new FrameLayout.LayoutParams(
4289 ViewGroup.LayoutParams.FILL_PARENT,
4290 ViewGroup.LayoutParams.FILL_PARENT,
4293 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4295 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4296 // Dictionary search
4297 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4298 // Google Mobile Local search
4299 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4301 final static String QUERY_PLACE_HOLDER = "%s";
4303 // "source" parameter for Google search through search key
4304 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4305 // "source" parameter for Google search through goto menu
4306 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4307 // "source" parameter for Google search through simplily type
4308 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4309 // "source" parameter for Google search suggested by the browser
4310 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4311 // "source" parameter for Google search from unknown source
4312 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4314 private final static String LOGTAG = "browser";
4316 private String mLastEnteredUrl;
4318 private PowerManager.WakeLock mWakeLock;
4319 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4321 private Toast mStopToast;
4323 private TitleBar mTitleBar;
4325 private LinearLayout mErrorConsoleContainer = null;
4326 private boolean mShouldShowErrorConsole = false;
4328 // As the ids are dynamically created, we can't guarantee that they will
4329 // be in sequence, so this static array maps ids to a window number.
4330 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4331 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4332 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4333 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4335 // monitor platform changes
4336 private IntentFilter mNetworkStateChangedFilter;
4337 private BroadcastReceiver mNetworkStateIntentReceiver;
4339 private BroadcastReceiver mPackageInstallationReceiver;
4341 // activity requestCode
4342 final static int COMBO_PAGE = 1;
4343 final static int DOWNLOAD_PAGE = 2;
4344 final static int PREFERENCES_PAGE = 3;
4347 * A UrlData class to abstract how the content will be set to WebView.
4348 * This base class uses loadUrl to show the content.
4350 private static class UrlData {
4354 UrlData(String url) {
4358 void setPostData(byte[] postData) {
4359 mPostData = postData;
4363 return mUrl == null || mUrl.length() == 0;
4366 public void loadIn(WebView webView) {
4367 if (mPostData != null) {
4368 webView.postUrl(mUrl, mPostData);
4370 webView.loadUrl(mUrl);
4376 * A subclass of UrlData class that can display inlined content using
4377 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4379 private static class InlinedUrlData extends UrlData {
4380 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4383 mMimeType = mimeType;
4384 mEncoding = encoding;
4391 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4395 public void loadIn(WebView webView) {
4396 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4400 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);