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.Uri;
60 import android.net.WebAddress;
61 import android.net.http.EventHandler;
62 import android.net.http.SslCertificate;
63 import android.net.http.SslError;
64 import android.os.AsyncTask;
65 import android.os.Bundle;
66 import android.os.Debug;
67 import android.os.Environment;
68 import android.os.Handler;
69 import android.os.IBinder;
70 import android.os.Message;
71 import android.os.PowerManager;
72 import android.os.Process;
73 import android.os.RemoteException;
74 import android.os.ServiceManager;
75 import android.os.SystemClock;
76 import android.provider.Browser;
77 import android.provider.Contacts;
78 import android.provider.Downloads;
79 import android.provider.MediaStore;
80 import android.provider.Contacts.Intents.Insert;
81 import android.text.IClipboard;
82 import android.text.TextUtils;
83 import android.text.format.DateFormat;
84 import android.text.util.Regex;
85 import android.util.Log;
86 import android.view.ContextMenu;
87 import android.view.Gravity;
88 import android.view.KeyEvent;
89 import android.view.LayoutInflater;
90 import android.view.Menu;
91 import android.view.MenuInflater;
92 import android.view.MenuItem;
93 import android.view.MotionEvent;
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 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
302 // test the browser in OpenGL
303 // requestWindowFeature(Window.FEATURE_OPENGL);
305 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
307 mResolver = getContentResolver();
310 // start MASF proxy service
312 //Intent proxyServiceIntent = new Intent();
313 //proxyServiceIntent.setComponent
314 // (new ComponentName(
315 // "com.android.masfproxyservice",
316 // "com.android.masfproxyservice.MasfProxyService"));
317 //startService(proxyServiceIntent, null);
319 mSecLockIcon = Resources.getSystem().getDrawable(
320 android.R.drawable.ic_secure);
321 mMixLockIcon = Resources.getSystem().getDrawable(
322 android.R.drawable.ic_partial_secure);
324 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
325 .findViewById(com.android.internal.R.id.content);
326 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
327 .inflate(R.layout.custom_screen, null);
328 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
330 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
331 .findViewById(R.id.error_console);
332 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
333 .findViewById(R.id.fullscreen_custom_content);
334 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
335 mTitleBar = new TitleBarSet(this);
337 // Create the tab control and our initial tab
338 mTabControl = new TabControl(this);
340 // Open the icon database and retain all the bookmark urls for favicons
341 retainIconsOnStartup();
343 // Keep a settings instance handy.
344 mSettings = BrowserSettings.getInstance();
345 mSettings.setTabControl(mTabControl);
346 mSettings.loadFromDb(this);
348 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
349 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
351 /* enables registration for changes in network status from
353 mNetworkStateChangedFilter = new IntentFilter();
354 mNetworkStateChangedFilter.addAction(
355 ConnectivityManager.CONNECTIVITY_ACTION);
356 mNetworkStateIntentReceiver = new BroadcastReceiver() {
358 public void onReceive(Context context, Intent intent) {
359 if (intent.getAction().equals(
360 ConnectivityManager.CONNECTIVITY_ACTION)) {
361 boolean down = intent.getBooleanExtra(
362 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
363 onNetworkToggle(!down);
368 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
369 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
370 filter.addDataScheme("package");
371 mPackageInstallationReceiver = new BroadcastReceiver() {
373 public void onReceive(Context context, Intent intent) {
374 final String action = intent.getAction();
375 final String packageName = intent.getData()
376 .getSchemeSpecificPart();
377 final boolean replacing = intent.getBooleanExtra(
378 Intent.EXTRA_REPLACING, false);
379 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
380 // if it is replacing, refreshPlugins() when adding
383 PackageManager pm = BrowserActivity.this.getPackageManager();
384 PackageInfo pkgInfo = null;
386 pkgInfo = pm.getPackageInfo(packageName,
387 PackageManager.GET_PERMISSIONS);
388 } catch (PackageManager.NameNotFoundException e) {
391 if (pkgInfo != null) {
392 String permissions[] = pkgInfo.requestedPermissions;
393 if (permissions == null) {
396 boolean permissionOk = false;
397 for (String permit : permissions) {
398 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
404 PluginManager.getInstance(BrowserActivity.this)
406 Intent.ACTION_PACKAGE_ADDED
412 registerReceiver(mPackageInstallationReceiver, filter);
414 // If this was a web search request, pass it on to the default web search provider.
415 if (handleWebSearchIntent(getIntent())) {
416 moveTaskToBack(true);
420 if (!mTabControl.restoreState(icicle)) {
421 // clear up the thumbnail directory if we can't restore the state as
422 // none of the files in the directory are referenced any more.
423 new ClearThumbnails().execute(
424 mTabControl.getThumbnailDir().listFiles());
425 // there is no quit on Android. But if we can't restore the state,
426 // we can treat it as a new Browser, remove the old session cookies.
427 CookieManager.getInstance().removeSessionCookie();
428 final Intent intent = getIntent();
429 final Bundle extra = intent.getExtras();
430 // Create an initial tab.
431 // If the intent is ACTION_VIEW and data is not null, the Browser is
432 // invoked to view the content by another application. In this case,
433 // the tab will be close when exit.
434 UrlData urlData = getUrlDataFromIntent(intent);
436 final TabControl.Tab t = mTabControl.createNewTab(
437 Intent.ACTION_VIEW.equals(intent.getAction()) &&
438 intent.getData() != null,
439 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
440 mTabControl.setCurrentTab(t);
441 attachTabToContentView(t);
442 WebView webView = t.getWebView();
444 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
445 if (scale > 0 && scale <= 1000) {
446 webView.setInitialScale(scale);
449 // If we are not restoring from an icicle, then there is a high
450 // likely hood this is the first run. So, check to see if the
451 // homepage needs to be configured and copy any plugins from our
452 // asset directory to the data partition.
453 if ((extra == null || !extra.getBoolean("testing"))
454 && !mSettings.isLoginInitialized()) {
458 if (urlData.isEmpty()) {
459 if (mSettings.isLoginInitialized()) {
460 webView.loadUrl(mSettings.getHomePage());
462 waitForCredentials();
466 urlData.setPostData(extra
467 .getByteArray(Browser.EXTRA_POST_DATA));
469 urlData.loadIn(webView);
472 // TabControl.restoreState() will create a new tab even if
473 // restoring the state fails.
474 attachTabToContentView(mTabControl.getCurrentTab());
477 mTitleBar.init(this);
478 // Create title bars for all of the tabs that have been created
479 for (int i = 0; i < mTabControl.getTabCount(); i ++) {
480 WebView view = mTabControl.getTab(i).getWebView();
481 mTitleBar.addTab(view, false);
484 mTitleBar.setCurrentTab(mTabControl.getCurrentIndex());
486 // Read JavaScript flags if it exists.
487 String jsFlags = mSettings.getJsFlags();
488 if (jsFlags.trim().length() != 0) {
489 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
494 protected void onNewIntent(Intent intent) {
495 TabControl.Tab current = mTabControl.getCurrentTab();
496 // When a tab is closed on exit, the current tab index is set to -1.
497 // Reset before proceed as Browser requires the current tab to be set.
498 if (current == null) {
499 // Try to reset the tab in case the index was incorrect.
500 current = mTabControl.getTab(0);
501 if (current == null) {
502 // No tabs at all so just ignore this intent.
505 mTabControl.setCurrentTab(current);
506 mTitleBar.setCurrentTab(mTabControl.getTabIndex(current));
507 attachTabToContentView(current);
508 resetTitleAndIcon(current.getWebView());
510 final String action = intent.getAction();
511 final int flags = intent.getFlags();
512 if (Intent.ACTION_MAIN.equals(action) ||
513 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
514 // just resume the browser
517 if (Intent.ACTION_VIEW.equals(action)
518 || Intent.ACTION_SEARCH.equals(action)
519 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
520 || Intent.ACTION_WEB_SEARCH.equals(action)) {
521 // If this was a search request (e.g. search query directly typed into the address bar),
522 // pass it on to the default web search provider.
523 if (handleWebSearchIntent(intent)) {
527 UrlData urlData = getUrlDataFromIntent(intent);
528 if (urlData.isEmpty()) {
529 urlData = new UrlData(mSettings.getHomePage());
531 urlData.setPostData(intent
532 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
534 final String appId = intent
535 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
536 if (Intent.ACTION_VIEW.equals(action)
537 && !getPackageName().equals(appId)
538 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
539 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
540 if (appTab != null) {
541 Log.i(LOGTAG, "Reusing tab for " + appId);
542 // Dismiss the subwindow if applicable.
543 dismissSubWindow(appTab);
544 // Since we might kill the WebView, remove it from the
545 // content view first.
546 removeTabFromContentView(appTab);
547 // Recreate the main WebView after destroying the old one.
548 // If the WebView has the same original url and is on that
549 // page, it can be reused.
551 mTabControl.recreateWebView(appTab, urlData.mUrl);
553 if (current != appTab) {
554 switchToTab(mTabControl.getTabIndex(appTab));
556 urlData.loadIn(appTab.getWebView());
559 // If the tab was the current tab, we have to attach
560 // it to the view system again.
561 attachTabToContentView(appTab);
563 urlData.loadIn(appTab.getWebView());
568 // No matching application tab, try to find a regular tab
569 // with a matching url.
570 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
571 if (appTab != null) {
572 if (current != appTab) {
573 switchToTab(mTabControl.getTabIndex(appTab));
575 // Otherwise, we are already viewing the correct tab.
577 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
578 // will be opened in a new tab unless we have reached
579 // MAX_TABS. Then the url will be opened in the current
580 // tab. If a new tab is created, it will have "true" for
582 openTabAndShow(urlData, true, appId);
586 if ("about:debug".equals(urlData.mUrl)) {
587 mSettings.toggleDebugSettings();
590 // Get rid of the subwindow if it exists
591 dismissSubWindow(current);
592 urlData.loadIn(current.getWebView());
597 private int parseUrlShortcut(String url) {
598 if (url == null) return SHORTCUT_INVALID;
600 // FIXME: quick search, need to be customized by setting
601 if (url.length() > 2 && url.charAt(1) == ' ') {
602 switch (url.charAt(0)) {
603 case 'g': return SHORTCUT_GOOGLE_SEARCH;
604 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
605 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
606 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
609 return SHORTCUT_INVALID;
613 * Launches the default web search activity with the query parameters if the given intent's data
614 * are identified as plain search terms and not URLs/shortcuts.
615 * @return true if the intent was handled and web search activity was launched, false if not.
617 private boolean handleWebSearchIntent(Intent intent) {
618 if (intent == null) return false;
621 final String action = intent.getAction();
622 if (Intent.ACTION_VIEW.equals(action)) {
623 url = intent.getData().toString();
624 } else if (Intent.ACTION_SEARCH.equals(action)
625 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
626 || Intent.ACTION_WEB_SEARCH.equals(action)) {
627 url = intent.getStringExtra(SearchManager.QUERY);
629 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
633 * Launches the default web search activity with the query parameters if the given url string
634 * was identified as plain search terms and not URL/shortcut.
635 * @return true if the request was handled and web search activity was launched, false if not.
637 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
638 if (inUrl == null) return false;
640 // In general, we shouldn't modify URL from Intent.
641 // But currently, we get the user-typed URL from search box as well.
642 String url = fixUrl(inUrl).trim();
644 // URLs and site specific search shortcuts are handled by the regular flow of control, so
646 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
647 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
648 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
652 Browser.updateVisitedHistory(mResolver, url, false);
653 Browser.addSearchUrl(mResolver, url);
655 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
656 intent.addCategory(Intent.CATEGORY_DEFAULT);
657 intent.putExtra(SearchManager.QUERY, url);
658 if (appData != null) {
659 intent.putExtra(SearchManager.APP_DATA, appData);
661 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
662 startActivity(intent);
667 private UrlData getUrlDataFromIntent(Intent intent) {
669 if (intent != null) {
670 final String action = intent.getAction();
671 if (Intent.ACTION_VIEW.equals(action)) {
672 url = smartUrlFilter(intent.getData());
673 if (url != null && url.startsWith("content:")) {
674 /* Append mimetype so webview knows how to display */
675 String mimeType = intent.resolveType(getContentResolver());
676 if (mimeType != null) {
677 url += "?" + mimeType;
680 if ("inline:".equals(url)) {
681 return new InlinedUrlData(
682 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
684 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
685 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
687 } else if (Intent.ACTION_SEARCH.equals(action)
688 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
689 || Intent.ACTION_WEB_SEARCH.equals(action)) {
690 url = intent.getStringExtra(SearchManager.QUERY);
692 mLastEnteredUrl = url;
693 // Don't add Urls, just search terms.
694 // Urls will get added when the page is loaded.
695 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
696 Browser.updateVisitedHistory(mResolver, url, false);
698 // In general, we shouldn't modify URL from Intent.
699 // But currently, we get the user-typed URL from search box as well.
701 url = smartUrlFilter(url);
702 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
703 if (url.contains(searchSource)) {
704 String source = null;
705 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
706 if (appData != null) {
707 source = appData.getString(SearchManager.SOURCE);
709 if (TextUtils.isEmpty(source)) {
710 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
712 url = url.replace(searchSource, "&source=android-"+source+"&");
717 return new UrlData(url);
720 /* package */ static String fixUrl(String inUrl) {
721 // FIXME: Converting the url to lower case
722 // duplicates functionality in smartUrlFilter().
723 // However, changing all current callers of fixUrl to
724 // call smartUrlFilter in addition may have unwanted
725 // consequences, and is deferred for now.
726 int colon = inUrl.indexOf(':');
727 boolean allLower = true;
728 for (int index = 0; index < colon; index++) {
729 char ch = inUrl.charAt(index);
730 if (!Character.isLetter(ch)) {
733 allLower &= Character.isLowerCase(ch);
734 if (index == colon - 1 && !allLower) {
735 inUrl = inUrl.substring(0, colon).toLowerCase()
736 + inUrl.substring(colon);
739 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
741 if (inUrl.startsWith("http:") ||
742 inUrl.startsWith("https:")) {
743 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
744 inUrl = inUrl.replaceFirst("/", "//");
745 } else inUrl = inUrl.replaceFirst(":", "://");
751 * Looking for the pattern like this
760 private final SensorListener mSensorListener = new SensorListener() {
761 private long mLastGestureTime;
762 private float[] mPrev = new float[3];
763 private float[] mPrevDiff = new float[3];
764 private float[] mDiff = new float[3];
765 private float[] mRevertDiff = new float[3];
767 public void onSensorChanged(int sensor, float[] values) {
768 boolean show = false;
769 float[] diff = new float[3];
771 for (int i = 0; i < 3; i++) {
772 diff[i] = values[i] - mPrev[i];
773 if (Math.abs(diff[i]) > 1) {
776 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
777 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
778 // start track when there is a big move, or revert
779 mRevertDiff[i] = mDiff[i];
781 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
782 // reset when it is flat
783 mDiff[i] = mRevertDiff[i] = 0;
786 mPrevDiff[i] = diff[i];
787 mPrev[i] = values[i];
791 // only shows if we think the delta is big enough, in an attempt
792 // to detect "serious" moves left/right or up/down
793 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
794 + values[0] + ", " + values[1] + ", " + values[2] + ")"
795 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
797 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
798 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
799 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
800 + mRevertDiff[2] + ")");
803 long now = android.os.SystemClock.uptimeMillis();
804 if (now - mLastGestureTime > 1000) {
805 mLastGestureTime = 0;
809 float ay = Math.abs(y);
810 float az = Math.abs(z);
811 float ry = mRevertDiff[1];
812 float rz = mRevertDiff[2];
813 float ary = Math.abs(ry);
814 float arz = Math.abs(rz);
815 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
816 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
818 if ((gestY || gestZ) && !(gestY && gestZ)) {
819 WebView view = mTabControl.getCurrentWebView();
829 view.flingScroll(0, Math.round(y * 100));
832 mLastGestureTime = now;
837 public void onAccuracyChanged(int sensor, int accuracy) {
838 // TODO Auto-generated method stub
843 @Override protected void onResume() {
846 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
849 if (!mActivityInPause) {
850 Log.e(LOGTAG, "BrowserActivity is already resumed.");
854 mTabControl.resumeCurrentTab();
855 mActivityInPause = false;
856 resumeWebViewTimers();
858 if (mWakeLock.isHeld()) {
859 mHandler.removeMessages(RELEASE_WAKELOCK);
863 if (mCredsDlg != null) {
864 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
865 // In case credential request never comes back
866 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
870 registerReceiver(mNetworkStateIntentReceiver,
871 mNetworkStateChangedFilter);
872 WebView.enablePlatformNotifications();
874 if (mSettings.doFlick()) {
875 if (mSensorManager == null) {
876 mSensorManager = (SensorManager) getSystemService(
877 Context.SENSOR_SERVICE);
879 mSensorManager.registerListener(mSensorListener,
880 SensorManager.SENSOR_ACCELEROMETER,
881 SensorManager.SENSOR_DELAY_FASTEST);
883 mSensorManager = null;
888 * Since the actual title bar is embedded in the WebView, and removing it
889 * would change its appearance, create a temporary title bar to go at
890 * the top of the screen while the menu is open.
892 private TitleBar mFakeTitleBar;
895 * Keeps track of whether the options menu is open. This is important in
896 * determining whether to show or hide the title bar overlay.
898 private boolean mOptionsMenuOpen;
901 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
902 * of whether the configuration has changed. The first onMenuOpened call
903 * after a configuration change is simply a reopening of the same menu
904 * (i.e. mIconView did not change).
906 private boolean mConfigChanged;
909 * Whether or not the options menu is in its smaller, icon menu form. When
910 * true, we want the title bar overlay to be up. When false, we do not.
911 * Only meaningful if mOptionsMenuOpen is true.
913 private boolean mIconView;
916 public boolean onMenuOpened(int featureId, Menu menu) {
917 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
918 if (mOptionsMenuOpen) {
919 if (mConfigChanged) {
920 // We do not need to make any changes to the state of the
921 // title bar, since the only thing that happened was a
922 // change in orientation
923 mConfigChanged = false;
926 // Switching the menu to expanded view, so hide the
931 // Switching the menu back to icon view, so show the
932 // title bar once again.
938 // The options menu is closed, so open it, and show the title
940 mOptionsMenuOpen = true;
941 mConfigChanged = false;
948 private void showFakeTitleBar() {
949 if (mFakeTitleBar == null) {
950 final WebView webView = getTopWindow();
951 mFakeTitleBar = new TitleBar(this, webView);
952 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
953 mFakeTitleBar.setProgress(webView.getProgress());
954 mFakeTitleBar.setFavicon(webView.getFavicon());
955 updateLockIconToLatest();
956 final View title = mFakeTitleBar.findViewById(R.id.title);
957 mFakeTitleBar.setOnTouchListener(new View.OnTouchListener() {
958 public boolean onTouch(View v, MotionEvent event) {
959 if (event.getAction() == MotionEvent.ACTION_UP) {
960 if (event.getX() > title.getRight()) {
962 && webView.getProgress() < 100) {
963 if (webView != null) {
964 webView.stopLoading();
967 bookmarksOrHistoryPicker(false);
978 WindowManager manager
979 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
981 // Add the title bar to the window manager so it can receive touches
982 // while the menu is up
983 WindowManager.LayoutParams params
984 = new WindowManager.LayoutParams(
985 ViewGroup.LayoutParams.FILL_PARENT,
986 ViewGroup.LayoutParams.WRAP_CONTENT,
987 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
988 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
990 params.gravity = Gravity.TOP;
991 WebView mainView = mTabControl.getCurrentWebView();
992 params.windowAnimations = mainView == null
993 || mainView.getScrollY() != 0
994 ? com.android.internal.R.style.Animation_DropDownDown : 0;
995 // XXX : Without providing an offset, the fake title bar will be
996 // placed underneath the status bar. Use the global visible rect
997 // of mBrowserFrameLayout to determine the bottom of the status bar
998 Rect rectangle = new Rect();
999 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
1000 params.y = rectangle.top;
1001 manager.addView(mFakeTitleBar, params);
1006 public void onOptionsMenuClosed(Menu menu) {
1007 mOptionsMenuOpen = false;
1010 } else if (!mIconView) {
1011 // The page is currently loading, and we are in expanded mode, so
1012 // we were not showing the menu. Show it once again. It will be
1013 // removed when the page finishes.
1017 private void hideFakeTitleBar() {
1018 if (mFakeTitleBar == null) return;
1019 WindowManager manager
1020 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1021 manager.removeView(mFakeTitleBar);
1022 mFakeTitleBar = null;
1026 * onSaveInstanceState(Bundle map)
1027 * onSaveInstanceState is called right before onStop(). The map contains
1030 @Override protected void onSaveInstanceState(Bundle outState) {
1032 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1034 // the default implementation requires each view to have an id. As the
1035 // browser handles the state itself and it doesn't use id for the views,
1036 // don't call the default implementation. Otherwise it will trigger the
1037 // warning like this, "couldn't save which view has focus because the
1038 // focused view XXX has no id".
1040 // Save all the tabs
1041 mTabControl.saveState(outState);
1044 @Override protected void onPause() {
1047 if (mActivityInPause) {
1048 Log.e(LOGTAG, "BrowserActivity is already paused.");
1052 mTabControl.pauseCurrentTab();
1053 mActivityInPause = true;
1054 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1055 mWakeLock.acquire();
1056 mHandler.sendMessageDelayed(mHandler
1057 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1060 // Clear the credentials toast if it is up
1061 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1062 mCredsDlg.dismiss();
1066 // FIXME: This removes the active tabs page and resets the menu to
1067 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1068 // but then we would need to save it in onSaveInstanceState and restore
1069 // it in onCreate/onRestoreInstanceState
1070 if (mActiveTabsPage != null) {
1071 removeActiveTabPage(true);
1076 // unregister network state listener
1077 unregisterReceiver(mNetworkStateIntentReceiver);
1078 WebView.disablePlatformNotifications();
1080 if (mSensorManager != null) {
1081 mSensorManager.unregisterListener(mSensorListener);
1085 @Override protected void onDestroy() {
1087 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1090 // Remove the current tab and sub window
1091 TabControl.Tab t = mTabControl.getCurrentTab();
1093 dismissSubWindow(t);
1094 removeTabFromContentView(t);
1096 // Destroy all the tabs
1097 mTabControl.destroy();
1098 WebIconDatabase.getInstance().close();
1099 if (mGlsConnection != null) {
1100 unbindService(mGlsConnection);
1101 mGlsConnection = null;
1105 // stop MASF proxy service
1107 //Intent proxyServiceIntent = new Intent();
1108 //proxyServiceIntent.setComponent
1109 // (new ComponentName(
1110 // "com.android.masfproxyservice",
1111 // "com.android.masfproxyservice.MasfProxyService"));
1112 //stopService(proxyServiceIntent);
1114 unregisterReceiver(mPackageInstallationReceiver);
1118 public void onConfigurationChanged(Configuration newConfig) {
1119 mConfigChanged = true;
1120 super.onConfigurationChanged(newConfig);
1122 if (mPageInfoDialog != null) {
1123 mPageInfoDialog.dismiss();
1126 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1128 if (mSSLCertificateDialog != null) {
1129 mSSLCertificateDialog.dismiss();
1131 mSSLCertificateView);
1133 if (mSSLCertificateOnErrorDialog != null) {
1134 mSSLCertificateOnErrorDialog.dismiss();
1135 showSSLCertificateOnError(
1136 mSSLCertificateOnErrorView,
1137 mSSLCertificateOnErrorHandler,
1138 mSSLCertificateOnErrorError);
1140 if (mHttpAuthenticationDialog != null) {
1141 String title = ((TextView) mHttpAuthenticationDialog
1142 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1144 String name = ((TextView) mHttpAuthenticationDialog
1145 .findViewById(R.id.username_edit)).getText().toString();
1146 String password = ((TextView) mHttpAuthenticationDialog
1147 .findViewById(R.id.password_edit)).getText().toString();
1148 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1150 mHttpAuthenticationDialog.dismiss();
1151 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1152 name, password, focusId);
1154 if (mFindDialog != null && mFindDialog.isShowing()) {
1155 mFindDialog.onConfigurationChanged(newConfig);
1159 @Override public void onLowMemory() {
1160 super.onLowMemory();
1161 mTabControl.freeMemory();
1164 private boolean resumeWebViewTimers() {
1165 if ((!mActivityInPause && !mPageStarted) ||
1166 (mActivityInPause && mPageStarted)) {
1167 CookieSyncManager.getInstance().startSync();
1168 WebView w = mTabControl.getCurrentWebView();
1178 private boolean pauseWebViewTimers() {
1179 if (mActivityInPause && !mPageStarted) {
1180 CookieSyncManager.getInstance().stopSync();
1181 WebView w = mTabControl.getCurrentWebView();
1191 // FIXME: Do we want to call this when loading google for the first time?
1193 * This function is called when we are launching for the first time. We
1194 * are waiting for the login credentials before loading Google home
1195 * pages. This way the user will be logged in straight away.
1197 private void waitForCredentials() {
1199 mCredsDlg = new ProgressDialog(this);
1200 mCredsDlg.setIndeterminate(true);
1201 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1202 // If the user cancels the operation, then cancel the Google
1203 // Credentials request.
1204 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1207 // We set a timeout for the retrieval of credentials in onResume()
1208 // as that is when we have freed up some CPU time to get
1209 // the login credentials.
1213 * If we have received the credentials or we have timed out and we are
1214 * showing the credentials dialog, then it is time to move on.
1216 private void resumeAfterCredentials() {
1217 if (mCredsDlg == null) {
1222 if (mCredsDlg.isShowing()) {
1223 mCredsDlg.dismiss();
1227 // Clear any pending timeout
1228 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1231 WebView w = mTabControl.getCurrentWebView();
1233 w.loadUrl(mSettings.getHomePage());
1236 // Update the settings, need to do this last as it can take a moment
1237 // to persist the settings. In the mean time we could be loading
1239 mSettings.setLoginInitialized(this);
1242 // Open the icon database and retain all the icons for visited sites.
1243 private void retainIconsOnStartup() {
1244 final WebIconDatabase db = WebIconDatabase.getInstance();
1245 db.open(getDir("icons", 0).getPath());
1247 Cursor c = Browser.getAllBookmarks(mResolver);
1248 if (!c.moveToFirst()) {
1252 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1254 String url = c.getString(urlIndex);
1255 db.retainIconForPageUrl(url);
1256 } while (c.moveToNext());
1258 } catch (IllegalStateException e) {
1259 Log.e(LOGTAG, "retainIconsOnStartup", e);
1263 // Helper method for getting the top window.
1264 WebView getTopWindow() {
1265 return mTabControl.getCurrentTopWebView();
1269 public boolean onCreateOptionsMenu(Menu menu) {
1270 super.onCreateOptionsMenu(menu);
1272 MenuInflater inflater = getMenuInflater();
1273 inflater.inflate(R.menu.browser, menu);
1275 updateInLoadMenuItems();
1280 * As the menu can be open when loading state changes
1281 * we must manually update the state of the stop/reload menu
1284 private void updateInLoadMenuItems() {
1285 if (mMenu == null) {
1288 MenuItem src = mInLoad ?
1289 mMenu.findItem(R.id.stop_menu_id):
1290 mMenu.findItem(R.id.reload_menu_id);
1291 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1292 dest.setIcon(src.getIcon());
1293 dest.setTitle(src.getTitle());
1297 public boolean onContextItemSelected(MenuItem item) {
1298 // chording is not an issue with context menus, but we use the same
1299 // options selector, so set mCanChord to true so we can access them.
1301 int id = item.getItemId();
1302 final WebView webView = getTopWindow();
1303 if (null == webView) {
1306 final HashMap hrefMap = new HashMap();
1307 hrefMap.put("webview", webView);
1308 final Message msg = mHandler.obtainMessage(
1309 FOCUS_NODE_HREF, id, 0, hrefMap);
1311 // -- Browser context menu
1312 case R.id.open_context_menu_id:
1313 case R.id.open_newtab_context_menu_id:
1314 case R.id.bookmark_context_menu_id:
1315 case R.id.save_link_context_menu_id:
1316 case R.id.share_link_context_menu_id:
1317 case R.id.copy_link_context_menu_id:
1318 webView.requestFocusNodeHref(msg);
1322 // For other context menus
1323 return onOptionsItemSelected(item);
1329 private Bundle createGoogleSearchSourceBundle(String source) {
1330 Bundle bundle = new Bundle();
1331 bundle.putString(SearchManager.SOURCE, source);
1336 * Overriding this to insert a local information bundle
1339 public boolean onSearchRequested() {
1340 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1341 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1342 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1347 public void startSearch(String initialQuery, boolean selectInitialQuery,
1348 Bundle appSearchData, boolean globalSearch) {
1349 if (appSearchData == null) {
1350 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1352 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1356 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1357 * results in changing tabs.
1358 * @param index Index of the tab to change to, as defined by
1359 * mTabControl.getTabIndex(Tab t).
1360 * @return boolean True if we successfully switched to a different tab. If
1361 * the indexth tab is null, or if that tab is the same as
1362 * the current one, return false.
1364 /* package */ boolean switchToTab(int index) {
1365 TabControl.Tab tab = mTabControl.getTab(index);
1366 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1367 if (tab == null || tab == currentTab) {
1370 if (currentTab != null) {
1371 // currentTab may be null if it was just removed. In that case,
1372 // we do not need to remove it
1373 removeTabFromContentView(currentTab);
1375 removeTabFromContentView(tab);
1376 mTabControl.setCurrentTab(tab);
1377 attachTabToContentView(tab);
1378 mTitleBar.setCurrentTab(index);
1383 /* package */ TabControl.Tab openTabToHomePage() {
1384 return openTabAndShow(mSettings.getHomePage(), false, null);
1387 /* package */ void closeCurrentWindow() {
1388 final TabControl.Tab current = mTabControl.getCurrentTab();
1389 if (mTabControl.getTabCount() == 1) {
1390 // This is the last tab. Open a new one, with the home
1391 // page and close the current one.
1392 TabControl.Tab newTab = openTabToHomePage();
1396 final TabControl.Tab parent = current.getParentTab();
1397 int indexToShow = -1;
1398 if (parent != null) {
1399 indexToShow = mTabControl.getTabIndex(parent);
1401 final int currentIndex = mTabControl.getCurrentIndex();
1402 // Try to move to the tab to the right
1403 indexToShow = currentIndex + 1;
1404 if (indexToShow > mTabControl.getTabCount() - 1) {
1405 // Try to move to the tab to the left
1406 indexToShow = currentIndex - 1;
1409 if (switchToTab(indexToShow)) {
1415 private ActiveTabsPage mActiveTabsPage;
1418 * Remove the active tabs page.
1419 * @param needToAttach If true, the active tabs page did not attach a tab
1420 * to the content view, so we need to do that here.
1422 /* package */ void removeActiveTabPage(boolean needToAttach) {
1423 mContentView.removeView(mActiveTabsPage);
1424 mActiveTabsPage = null;
1425 mMenuState = R.id.MAIN_MENU;
1427 attachTabToContentView(mTabControl.getCurrentTab());
1429 getTopWindow().requestFocus();
1433 public boolean onOptionsItemSelected(MenuItem item) {
1435 // The user has already fired a shortcut with this hold down of the
1439 if (null == getTopWindow()) {
1443 // The shortcut action consumes the MENU. Even if it is still down,
1444 // it won't trigger the next shortcut action. In the case of the
1445 // shortcut action triggering a new activity, like Bookmarks, we
1446 // won't get onKeyUp for MENU. So it is important to reset it here.
1447 mMenuIsDown = false;
1449 switch (item.getItemId()) {
1451 case R.id.new_tab_menu_id:
1452 openTabToHomePage();
1455 case R.id.goto_menu_id:
1456 bookmarksOrHistoryPicker(false);
1459 case R.id.active_tabs_menu_id:
1460 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1461 removeTabFromContentView(mTabControl.getCurrentTab());
1462 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1463 mActiveTabsPage.requestFocus();
1464 mMenuState = EMPTY_MENU;
1467 case R.id.add_bookmark_menu_id:
1468 Intent i = new Intent(BrowserActivity.this,
1469 AddBookmarkPage.class);
1470 WebView w = getTopWindow();
1471 i.putExtra("url", w.getUrl());
1472 i.putExtra("title", w.getTitle());
1476 case R.id.stop_reload_menu_id:
1480 getTopWindow().reload();
1484 case R.id.back_menu_id:
1485 getTopWindow().goBack();
1488 case R.id.forward_menu_id:
1489 getTopWindow().goForward();
1492 case R.id.close_menu_id:
1493 // Close the subwindow if it exists.
1494 if (mTabControl.getCurrentSubWindow() != null) {
1495 dismissSubWindow(mTabControl.getCurrentTab());
1498 closeCurrentWindow();
1501 case R.id.homepage_menu_id:
1502 TabControl.Tab current = mTabControl.getCurrentTab();
1503 if (current != null) {
1504 dismissSubWindow(current);
1505 current.getWebView().loadUrl(mSettings.getHomePage());
1509 case R.id.preferences_menu_id:
1510 Intent intent = new Intent(this,
1511 BrowserPreferencesPage.class);
1512 startActivityForResult(intent, PREFERENCES_PAGE);
1515 case R.id.find_menu_id:
1516 if (null == mFindDialog) {
1517 mFindDialog = new FindDialog(this);
1519 mFindDialog.setWebView(getTopWindow());
1521 mMenuState = EMPTY_MENU;
1524 case R.id.select_text_id:
1525 getTopWindow().emulateShiftHeld();
1527 case R.id.page_info_menu_id:
1528 showPageInfo(mTabControl.getCurrentTab(), false);
1531 case R.id.classic_history_menu_id:
1532 bookmarksOrHistoryPicker(true);
1535 case R.id.share_page_menu_id:
1536 Browser.sendString(this, getTopWindow().getUrl());
1539 case R.id.dump_nav_menu_id:
1540 getTopWindow().debugDump();
1543 case R.id.zoom_in_menu_id:
1544 getTopWindow().zoomIn();
1547 case R.id.zoom_out_menu_id:
1548 getTopWindow().zoomOut();
1551 case R.id.view_downloads_menu_id:
1552 viewDownloads(null);
1555 case R.id.window_one_menu_id:
1556 case R.id.window_two_menu_id:
1557 case R.id.window_three_menu_id:
1558 case R.id.window_four_menu_id:
1559 case R.id.window_five_menu_id:
1560 case R.id.window_six_menu_id:
1561 case R.id.window_seven_menu_id:
1562 case R.id.window_eight_menu_id:
1564 int menuid = item.getItemId();
1565 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1566 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1567 TabControl.Tab desiredTab = mTabControl.getTab(id);
1568 if (desiredTab != null &&
1569 desiredTab != mTabControl.getCurrentTab()) {
1579 if (!super.onOptionsItemSelected(item)) {
1582 // Otherwise fall through.
1588 public void closeFind() {
1589 mMenuState = R.id.MAIN_MENU;
1592 @Override public boolean onPrepareOptionsMenu(Menu menu)
1594 // This happens when the user begins to hold down the menu key, so
1595 // allow them to chord to get a shortcut.
1597 // Note: setVisible will decide whether an item is visible; while
1598 // setEnabled() will decide whether an item is enabled, which also means
1599 // whether the matching shortcut key will function.
1600 super.onPrepareOptionsMenu(menu);
1601 switch (mMenuState) {
1603 if (mCurrentMenuState != mMenuState) {
1604 menu.setGroupVisible(R.id.MAIN_MENU, false);
1605 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1606 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1610 if (mCurrentMenuState != mMenuState) {
1611 menu.setGroupVisible(R.id.MAIN_MENU, true);
1612 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1613 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1615 final WebView w = getTopWindow();
1616 boolean canGoBack = false;
1617 boolean canGoForward = false;
1618 boolean isHome = false;
1620 canGoBack = w.canGoBack();
1621 canGoForward = w.canGoForward();
1622 isHome = mSettings.getHomePage().equals(w.getUrl());
1624 final MenuItem back = menu.findItem(R.id.back_menu_id);
1625 back.setEnabled(canGoBack);
1627 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1628 home.setEnabled(!isHome);
1630 menu.findItem(R.id.forward_menu_id)
1631 .setEnabled(canGoForward);
1633 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1634 mTabControl.getTabCount() < TabControl.MAX_TABS);
1636 // decide whether to show the share link option
1637 PackageManager pm = getPackageManager();
1638 Intent send = new Intent(Intent.ACTION_SEND);
1639 send.setType("text/plain");
1640 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1641 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1643 boolean isNavDump = mSettings.isNavDump();
1644 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1645 nav.setVisible(isNavDump);
1646 nav.setEnabled(isNavDump);
1649 mCurrentMenuState = mMenuState;
1654 public void onCreateContextMenu(ContextMenu menu, View v,
1655 ContextMenuInfo menuInfo) {
1656 WebView webview = (WebView) v;
1657 WebView.HitTestResult result = webview.getHitTestResult();
1658 if (result == null) {
1662 int type = result.getType();
1663 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1665 "We should not show context menu when nothing is touched");
1668 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1669 // let TextView handles context menu
1673 // Note, http://b/issue?id=1106666 is requesting that
1674 // an inflated menu can be used again. This is not available
1675 // yet, so inflate each time (yuk!)
1676 MenuInflater inflater = getMenuInflater();
1677 inflater.inflate(R.menu.browsercontext, menu);
1679 // Show the correct menu group
1680 String extra = result.getExtra();
1681 menu.setGroupVisible(R.id.PHONE_MENU,
1682 type == WebView.HitTestResult.PHONE_TYPE);
1683 menu.setGroupVisible(R.id.EMAIL_MENU,
1684 type == WebView.HitTestResult.EMAIL_TYPE);
1685 menu.setGroupVisible(R.id.GEO_MENU,
1686 type == WebView.HitTestResult.GEO_TYPE);
1687 menu.setGroupVisible(R.id.IMAGE_MENU,
1688 type == WebView.HitTestResult.IMAGE_TYPE
1689 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1690 menu.setGroupVisible(R.id.ANCHOR_MENU,
1691 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1692 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1694 // Setup custom handling depending on the type
1696 case WebView.HitTestResult.PHONE_TYPE:
1697 menu.setHeaderTitle(Uri.decode(extra));
1698 menu.findItem(R.id.dial_context_menu_id).setIntent(
1699 new Intent(Intent.ACTION_VIEW, Uri
1700 .parse(WebView.SCHEME_TEL + extra)));
1701 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1702 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1703 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1704 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1706 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1710 case WebView.HitTestResult.EMAIL_TYPE:
1711 menu.setHeaderTitle(extra);
1712 menu.findItem(R.id.email_context_menu_id).setIntent(
1713 new Intent(Intent.ACTION_VIEW, Uri
1714 .parse(WebView.SCHEME_MAILTO + extra)));
1715 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1719 case WebView.HitTestResult.GEO_TYPE:
1720 menu.setHeaderTitle(extra);
1721 menu.findItem(R.id.map_context_menu_id).setIntent(
1722 new Intent(Intent.ACTION_VIEW, Uri
1723 .parse(WebView.SCHEME_GEO
1724 + URLEncoder.encode(extra))));
1725 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1729 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1730 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1731 TextView titleView = (TextView) LayoutInflater.from(this)
1732 .inflate(android.R.layout.browser_link_context_header,
1734 titleView.setText(extra);
1735 menu.setHeaderView(titleView);
1736 // decide whether to show the open link in new tab option
1737 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1738 mTabControl.getTabCount() < TabControl.MAX_TABS);
1739 PackageManager pm = getPackageManager();
1740 Intent send = new Intent(Intent.ACTION_SEND);
1741 send.setType("text/plain");
1742 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1743 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1744 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1747 // otherwise fall through to handle image part
1748 case WebView.HitTestResult.IMAGE_TYPE:
1749 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1750 menu.setHeaderTitle(extra);
1752 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1753 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1754 menu.findItem(R.id.download_context_menu_id).
1755 setOnMenuItemClickListener(new Download(extra));
1759 Log.w(LOGTAG, "We should not get here.");
1764 // Attach the given tab to the content view.
1765 private void attachTabToContentView(TabControl.Tab t) {
1766 // Attach the container that contains the main WebView and any other UI
1767 // associated with the tab.
1768 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
1770 if (mShouldShowErrorConsole) {
1771 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1772 if (errorConsole.numberOfErrors() == 0) {
1773 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1775 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1778 mErrorConsoleContainer.addView(errorConsole,
1779 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1780 ViewGroup.LayoutParams.WRAP_CONTENT));
1783 WebView view = t.getWebView();
1784 view.setEmbeddedTitleBar(mTitleBar);
1785 // Attach the sub window if necessary
1787 // Request focus on the top window.
1788 t.getTopWindow().requestFocus();
1791 // Attach a sub window to the main WebView of the given tab.
1792 private void attachSubWindow(TabControl.Tab t) {
1793 // If a sub window exists, attach it to the content view.
1794 final WebView subView = t.getSubWebView();
1795 if (subView != null) {
1796 final View container = t.getSubWebViewContainer();
1797 mContentView.addView(container, COVER_SCREEN_PARAMS);
1798 subView.requestFocus();
1802 // Remove the given tab from the content view.
1803 private void removeTabFromContentView(TabControl.Tab t) {
1804 // Remove the container that contains the main WebView.
1805 mContentView.removeView(t.getContainer());
1807 if (mTabControl.getCurrentErrorConsole(false) != null) {
1808 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1811 WebView view = t.getWebView();
1813 view.setEmbeddedTitleBar(null);
1816 // Remove the sub window if it exists.
1817 if (t.getSubWebView() != null) {
1818 mContentView.removeView(t.getSubWebViewContainer());
1822 // Remove the sub window if it exists. Also called by TabControl when the
1823 // user clicks the 'X' to dismiss a sub window.
1824 /* package */ void dismissSubWindow(TabControl.Tab t) {
1825 final WebView mainView = t.getWebView();
1826 if (t.getSubWebView() != null) {
1827 // Remove the container view and request focus on the main WebView.
1828 mContentView.removeView(t.getSubWebViewContainer());
1829 mainView.requestFocus();
1830 // Tell the TabControl to dismiss the subwindow. This will destroy
1832 mTabControl.dismissSubWindow(t);
1836 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1837 // that accepts url as string.
1838 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1840 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1843 // This method does a ton of stuff. It will attempt to create a new tab
1844 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1845 // url isn't null, it will load the given url.
1846 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
1847 boolean closeOnExit, String appId) {
1848 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1849 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1851 final TabControl.Tab tab = mTabControl.createNewTab(
1852 closeOnExit, appId, urlData.mUrl);
1853 WebView webview = tab.getWebView();
1854 mTitleBar.addTab(webview, true);
1855 // If the last tab was removed from the active tabs page, currentTab
1857 if (currentTab != null) {
1858 removeTabFromContentView(currentTab);
1860 attachTabToContentView(tab);
1861 // We must set the new tab as the current tab to reflect the old
1862 // animation behavior.
1863 mTabControl.setCurrentTab(tab);
1864 if (!urlData.isEmpty()) {
1865 urlData.loadIn(webview);
1869 // Get rid of the subwindow if it exists
1870 dismissSubWindow(currentTab);
1871 if (!urlData.isEmpty()) {
1872 // Load the given url.
1873 urlData.loadIn(currentTab.getWebView());
1879 private TabControl.Tab openTab(String url) {
1880 if (mSettings.openInBackground()) {
1881 TabControl.Tab t = mTabControl.createNewTab();
1883 WebView view = t.getWebView();
1884 mTitleBar.addTab(view, false);
1889 return openTabAndShow(url, false, null);
1893 private class Copy implements OnMenuItemClickListener {
1894 private CharSequence mText;
1896 public boolean onMenuItemClick(MenuItem item) {
1901 public Copy(CharSequence toCopy) {
1906 private class Download implements OnMenuItemClickListener {
1907 private String mText;
1909 public boolean onMenuItemClick(MenuItem item) {
1910 onDownloadStartNoStream(mText, null, null, null, -1);
1914 public Download(String toDownload) {
1919 private void copy(CharSequence text) {
1921 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1923 clip.setClipboardText(text);
1925 } catch (android.os.RemoteException e) {
1926 Log.e(LOGTAG, "Copy failed", e);
1931 * Resets the browser title-view to whatever it must be (for example, if we
1932 * load a page from history).
1934 private void resetTitle() {
1936 resetTitleIconAndProgress();
1940 * Resets the browser title-view to whatever it must be
1941 * (for example, if we had a loading error)
1942 * When we have a new page, we call resetTitle, when we
1943 * have to reset the titlebar to whatever it used to be
1944 * (for example, if the user chose to stop loading), we
1945 * call resetTitleAndRevertLockIcon.
1947 /* package */ void resetTitleAndRevertLockIcon() {
1949 resetTitleIconAndProgress();
1953 * Reset the title, favicon, and progress.
1955 private void resetTitleIconAndProgress() {
1956 WebView current = mTabControl.getCurrentWebView();
1957 if (current == null) {
1960 resetTitleAndIcon(current);
1961 int progress = current.getProgress();
1962 mWebChromeClient.onProgressChanged(current, progress);
1965 // Reset the title and the icon based on the given item.
1966 private void resetTitleAndIcon(WebView view) {
1967 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1969 setUrlTitle(item.getUrl(), item.getTitle(), view);
1970 setFavicon(item.getFavicon());
1972 setUrlTitle(null, null, view);
1978 * Sets a title composed of the URL and the title string.
1979 * @param url The URL of the site being loaded.
1980 * @param title The title of the site being loaded.
1982 private void setUrlTitle(String url, String title, WebView view) {
1986 mTitleBar.setTitleAndUrl(title, url, view);
1987 if (mFakeTitleBar != null) {
1988 mFakeTitleBar.setTitleAndUrl(title, url);
1993 * @param url The URL to build a title version of the URL from.
1994 * @return The title version of the URL or null if fails.
1995 * The title version of the URL can be either the URL hostname,
1996 * or the hostname with an "https://" prefix (for secure URLs),
1997 * or an empty string if, for example, the URL in question is a
1998 * file:// URL with no hostname.
2000 /* package */ static String buildTitleUrl(String url) {
2001 String titleUrl = null;
2005 // parse the url string
2006 URL urlObj = new URL(url);
2007 if (urlObj != null) {
2010 String protocol = urlObj.getProtocol();
2011 String host = urlObj.getHost();
2013 if (host != null && 0 < host.length()) {
2015 if (protocol != null) {
2016 // if a secure site, add an "https://" prefix!
2017 if (protocol.equalsIgnoreCase("https")) {
2018 titleUrl = protocol + "://" + host;
2023 } catch (MalformedURLException e) {}
2029 // Set the favicon in the title bar.
2030 private void setFavicon(Bitmap icon) {
2031 mTitleBar.setFavicon(icon, getTopWindow());
2032 if (mFakeTitleBar != null) {
2033 mFakeTitleBar.setFavicon(icon);
2038 * Saves the current lock-icon state before resetting
2039 * the lock icon. If we have an error, we may need to
2040 * roll back to the previous state.
2042 private void saveLockIcon() {
2043 mPrevLockType = mLockIconType;
2047 * Reverts the lock-icon state to the last saved state,
2048 * for example, if we had an error, and need to cancel
2051 private void revertLockIcon() {
2052 mLockIconType = mPrevLockType;
2055 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2056 " revert lock icon to " + mLockIconType);
2059 updateLockIconToLatest();
2063 * Close the tab, remove its associated title bar, and adjust mTabControl's
2064 * current tab to a valid value.
2066 /* package */ void closeTab(TabControl.Tab t) {
2067 int currentIndex = mTabControl.getCurrentIndex();
2068 int removeIndex = mTabControl.getTabIndex(t);
2069 mTitleBar.removeTab(removeIndex);
2070 mTabControl.removeTab(t);
2071 if (currentIndex >= removeIndex && currentIndex != 0) {
2074 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2077 private void goBackOnePageOrQuit() {
2078 TabControl.Tab current = mTabControl.getCurrentTab();
2079 if (current == null) {
2081 * Instead of finishing the activity, simply push this to the back
2082 * of the stack and let ActivityManager to choose the foreground
2083 * activity. As BrowserActivity is singleTask, it will be always the
2084 * root of the task. So we can use either true or false for
2087 moveTaskToBack(true);
2089 WebView w = current.getWebView();
2090 if (w.canGoBack()) {
2093 // Check to see if we are closing a window that was created by
2094 // another window. If so, we switch back to that window.
2095 TabControl.Tab parent = current.getParentTab();
2096 if (parent != null) {
2097 switchToTab(mTabControl.getTabIndex(parent));
2098 // Now we close the other tab
2101 if (current.closeOnExit()) {
2102 // force mPageStarted to be false as we are going to either
2103 // finish the activity or remove the tab. This will ensure
2104 // pauseWebView() taking action.
2105 mPageStarted = false;
2106 if (mTabControl.getTabCount() == 1) {
2110 // call pauseWebViewTimers() now, we won't be able to call
2111 // it in onPause() as the WebView won't be valid.
2112 // Temporarily change mActivityInPause to be true as
2113 // pauseWebViewTimers() will do nothing if mActivityInPause
2115 boolean savedState = mActivityInPause;
2117 Log.e(LOGTAG, "BrowserActivity is already paused "
2118 + "while handing goBackOnePageOrQuit.");
2120 mActivityInPause = true;
2121 pauseWebViewTimers();
2122 mActivityInPause = savedState;
2123 removeTabFromContentView(current);
2124 mTitleBar.removeTab(mTabControl.getTabIndex(current));
2125 mTabControl.removeTab(current);
2128 * Instead of finishing the activity, simply push this to the back
2129 * of the stack and let ActivityManager to choose the foreground
2130 * activity. As BrowserActivity is singleTask, it will be always the
2131 * root of the task. So we can use either true or false for
2134 moveTaskToBack(true);
2139 public KeyTracker.State onKeyTracker(int keyCode,
2141 KeyTracker.Stage stage,
2143 // if onKeyTracker() is called after activity onStop()
2144 // because of accumulated key events,
2145 // we should ignore it as browser is not active any more.
2146 WebView topWindow = getTopWindow();
2147 if (topWindow == null && mCustomView == null)
2148 return KeyTracker.State.NOT_TRACKING;
2150 if (keyCode == KeyEvent.KEYCODE_BACK) {
2151 // Check if a custom view is currently showing and, if it is, hide it.
2152 if (mCustomView != null) {
2153 mWebChromeClient.onHideCustomView();
2154 return KeyTracker.State.DONE_TRACKING;
2156 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2157 bookmarksOrHistoryPicker(true);
2158 return KeyTracker.State.DONE_TRACKING;
2159 } else if (stage == KeyTracker.Stage.UP) {
2160 // FIXME: Currently, we do not have a notion of the
2161 // history picker for the subwindow, but maybe we
2163 WebView subwindow = mTabControl.getCurrentSubWindow();
2164 if (subwindow != null) {
2165 if (subwindow.canGoBack()) {
2168 dismissSubWindow(mTabControl.getCurrentTab());
2171 goBackOnePageOrQuit();
2173 return KeyTracker.State.DONE_TRACKING;
2175 return KeyTracker.State.KEEP_TRACKING;
2177 return KeyTracker.State.NOT_TRACKING;
2180 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2181 if (keyCode == KeyEvent.KEYCODE_MENU) {
2183 } else if (mMenuIsDown) {
2184 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2185 // still down, we don't want to trigger the search. Pretend to
2186 // consume the key and do nothing.
2189 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2192 case KeyEvent.KEYCODE_SPACE:
2193 if (event.isShiftPressed()) {
2194 getTopWindow().pageUp(false);
2196 getTopWindow().pageDown(false);
2205 return handled || super.onKeyDown(keyCode, event);
2208 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2209 if (keyCode == KeyEvent.KEYCODE_MENU) {
2210 mMenuIsDown = false;
2212 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2215 private void stopLoading() {
2216 resetTitleAndRevertLockIcon();
2217 WebView w = getTopWindow();
2219 mWebViewClient.onPageFinished(w, w.getUrl());
2223 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2227 private void cancelStopToast() {
2228 if (mStopToast != null) {
2229 mStopToast.cancel();
2234 // called by a non-UI thread to post the message
2235 public void postMessage(int what, int arg1, int arg2, Object obj) {
2236 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2239 // public message ids
2240 public final static int LOAD_URL = 1001;
2241 public final static int STOP_LOAD = 1002;
2244 private static final int FOCUS_NODE_HREF = 102;
2245 private static final int CANCEL_CREDS_REQUEST = 103;
2246 private static final int RELEASE_WAKELOCK = 107;
2248 // Private handler for handling javascript and saving passwords
2249 private Handler mHandler = new Handler() {
2251 public void handleMessage(Message msg) {
2253 case FOCUS_NODE_HREF:
2254 String url = (String) msg.getData().get("url");
2255 if (url == null || url.length() == 0) {
2258 HashMap focusNodeMap = (HashMap) msg.obj;
2259 WebView view = (WebView) focusNodeMap.get("webview");
2260 // Only apply the action if the top window did not change.
2261 if (getTopWindow() != view) {
2265 case R.id.open_context_menu_id:
2266 case R.id.view_image_context_menu_id:
2267 loadURL(getTopWindow(), url);
2269 case R.id.open_newtab_context_menu_id:
2270 final TabControl.Tab parent = mTabControl
2272 final TabControl.Tab newTab = openTab(url);
2273 if (newTab != parent) {
2274 parent.addChildTab(newTab);
2277 case R.id.bookmark_context_menu_id:
2278 Intent intent = new Intent(BrowserActivity.this,
2279 AddBookmarkPage.class);
2280 intent.putExtra("url", url);
2281 startActivity(intent);
2283 case R.id.share_link_context_menu_id:
2284 Browser.sendString(BrowserActivity.this, url);
2286 case R.id.copy_link_context_menu_id:
2289 case R.id.save_link_context_menu_id:
2290 case R.id.download_context_menu_id:
2291 onDownloadStartNoStream(url, null, null, null, -1);
2297 loadURL(getTopWindow(), (String) msg.obj);
2304 case CANCEL_CREDS_REQUEST:
2305 resumeAfterCredentials();
2308 case RELEASE_WAKELOCK:
2309 if (mWakeLock.isHeld()) {
2310 mWakeLock.release();
2317 private void updateScreenshot(WebView view) {
2318 // If this is a bookmarked site, add a screenshot to the database.
2319 // FIXME: When should we update? Every time?
2320 // FIXME: Would like to make sure there is actually something to
2321 // draw, but the API for that (WebViewCore.pictureReady()) is not
2322 // currently accessible here.
2323 ContentResolver cr = getContentResolver();
2324 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2325 cr, view.getOriginalUrl(), view.getUrl(), false);
2327 boolean succeed = c.moveToFirst();
2328 ContentValues values = null;
2330 if (values == null) {
2331 final ByteArrayOutputStream os
2332 = new ByteArrayOutputStream();
2333 Picture thumbnail = view.capturePicture();
2334 // Keep width and height in sync with BrowserBookmarksPage
2335 // and bookmark_thumb
2336 Bitmap bm = Bitmap.createBitmap(100, 80,
2337 Bitmap.Config.ARGB_4444);
2338 Canvas canvas = new Canvas(bm);
2339 // May need to tweak these values to determine what is the
2340 // best scale factor
2341 canvas.scale(.5f, .5f);
2342 thumbnail.draw(canvas);
2343 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2344 values = new ContentValues();
2345 values.put(Browser.BookmarkColumns.THUMBNAIL,
2348 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2349 c.getInt(0)), values, null, null);
2350 succeed = c.moveToNext();
2356 // -------------------------------------------------------------------------
2357 // WebViewClient implementation.
2358 //-------------------------------------------------------------------------
2360 // Use in overrideUrlLoading
2361 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2362 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2363 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2364 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2366 /* package */ WebViewClient getWebViewClient() {
2367 return mWebViewClient;
2370 private void updateIcon(WebView view, Bitmap icon) {
2372 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2378 private final WebViewClient mWebViewClient = new WebViewClient() {
2380 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2382 setUrlTitle(url, null, view);
2384 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2385 if (errorConsole != null) {
2386 errorConsole.clearErrorMessages();
2387 if (mShouldShowErrorConsole) {
2388 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2392 // Call updateIcon instead of setFavicon so the bookmark
2393 // database can be updated.
2394 updateIcon(view, favicon);
2396 if (mSettings.isTracing()) {
2399 WebAddress uri = new WebAddress(url);
2401 } catch (android.net.ParseException ex) {
2404 host = host.replace('.', '_');
2407 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2410 // Performance probe
2412 mStart = SystemClock.uptimeMillis();
2413 mProcessStart = Process.getElapsedCpuTime();
2414 long[] sysCpu = new long[7];
2415 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2417 mUserStart = sysCpu[0] + sysCpu[1];
2418 mSystemStart = sysCpu[2];
2419 mIdleStart = sysCpu[3];
2420 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2422 mUiStart = SystemClock.currentThreadTimeMillis();
2425 if (!mPageStarted) {
2426 mPageStarted = true;
2427 // if onResume() has been called, resumeWebViewTimers() does
2429 resumeWebViewTimers();
2432 // reset sync timer to avoid sync starts during loading a page
2433 CookieSyncManager.getInstance().resetSync();
2436 WebView currentWebView = mTabControl.getCurrentWebView();
2437 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2438 // This page has begun to load, so show the title bar
2441 updateInLoadMenuItems();
2442 if (!mIsNetworkUp) {
2443 if ( mAlertDialog == null) {
2444 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2445 .setTitle(R.string.loadSuspendedTitle)
2446 .setMessage(R.string.loadSuspended)
2447 .setPositiveButton(R.string.ok, null)
2451 view.setNetworkAvailable(false);
2457 public void onPageFinished(WebView view, String url) {
2458 // Reset the title and icon in case we stopped a provisional
2460 resetTitleAndIcon(view);
2462 // Update the lock icon image only once we are done loading
2463 updateLockIconToLatest();
2464 updateScreenshot(view);
2466 // Performance probe
2468 long[] sysCpu = new long[7];
2469 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2471 String uiInfo = "UI thread used "
2472 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2475 Log.d(LOGTAG, uiInfo);
2477 //The string that gets written to the log
2478 String performanceString = "It took total "
2479 + (SystemClock.uptimeMillis() - mStart)
2480 + " ms clock time to load the page."
2481 + "\nbrowser process used "
2482 + (Process.getElapsedCpuTime() - mProcessStart)
2483 + " ms, user processes used "
2484 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2485 + " ms, kernel used "
2486 + (sysCpu[2] - mSystemStart) * 10
2487 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2488 + " ms and irq took "
2489 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2490 * 10 + " ms, " + uiInfo;
2492 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2495 // strip the url to maintain consistency
2496 String newUrl = new String(url);
2497 if (newUrl.startsWith("http://www.")) {
2498 newUrl = newUrl.substring(11);
2499 } else if (newUrl.startsWith("http://")) {
2500 newUrl = newUrl.substring(7);
2501 } else if (newUrl.startsWith("https://www.")) {
2502 newUrl = newUrl.substring(12);
2503 } else if (newUrl.startsWith("https://")) {
2504 newUrl = newUrl.substring(8);
2507 Log.d(LOGTAG, newUrl + " loaded");
2510 if (sWhiteList.contains(newUrl)) {
2511 // The string that gets pushed to the statistcs
2513 performanceString = performanceString
2517 + android.os.SystemProperties
2518 .get("gsm.sim.operator.alpha");
2519 if (mWebView != null
2520 && mWebView.getContext() != null
2521 && mWebView.getContext().getSystemService(
2522 Context.CONNECTIVITY_SERVICE) != null) {
2523 ConnectivityManager cManager =
2524 (ConnectivityManager) mWebView
2525 .getContext().getSystemService(
2526 Context.CONNECTIVITY_SERVICE);
2527 NetworkInfo nInfo = cManager
2528 .getActiveNetworkInfo();
2529 if (nInfo != null) {
2530 performanceString = performanceString
2531 + "\nNetwork Type: "
2532 + nInfo.getType().toString();
2535 Checkin.logEvent(mResolver,
2536 Checkin.Events.Tag.WEBPAGE_LOAD,
2538 Log.w(LOGTAG, "pushed to the statistics service");
2547 Debug.stopMethodTracing();
2551 mPageStarted = false;
2552 // pauseWebViewTimers() will do nothing and return false if
2553 // onPause() is not called yet.
2554 if (pauseWebViewTimers()) {
2555 if (mWakeLock.isHeld()) {
2556 mHandler.removeMessages(RELEASE_WAKELOCK);
2557 mWakeLock.release();
2563 // return true if want to hijack the url to let another app to handle it
2565 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2566 if (url.startsWith(SCHEME_WTAI)) {
2567 // wtai://wp/mc;number
2568 // number=string(phone-number)
2569 if (url.startsWith(SCHEME_WTAI_MC)) {
2570 Intent intent = new Intent(Intent.ACTION_VIEW,
2571 Uri.parse(WebView.SCHEME_TEL +
2572 url.substring(SCHEME_WTAI_MC.length())));
2573 startActivity(intent);
2576 // wtai://wp/sd;dtmf
2577 // dtmf=string(dialstring)
2578 if (url.startsWith(SCHEME_WTAI_SD)) {
2580 // only send when there is active voice connection
2583 // wtai://wp/ap;number;name
2584 // number=string(phone-number)
2586 if (url.startsWith(SCHEME_WTAI_AP)) {
2592 // The "about:" schemes are internal to the browser; don't
2593 // want these to be dispatched to other apps.
2594 if (url.startsWith("about:")) {
2600 // perform generic parsing of the URI to turn it into an Intent.
2602 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2603 } catch (URISyntaxException ex) {
2604 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2608 // check whether the intent can be resolved. If not, we will see
2609 // whether we can download it from the Market.
2610 if (getPackageManager().resolveActivity(intent, 0) == null) {
2611 String packagename = intent.getPackage();
2612 if (packagename != null) {
2613 intent = new Intent(Intent.ACTION_VIEW, Uri
2614 .parse("market://search?q=pname:" + packagename));
2615 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2616 startActivity(intent);
2623 // sanitize the Intent, ensuring web pages can not bypass browser
2624 // security (only access to BROWSABLE activities).
2625 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2626 intent.setComponent(null);
2628 if (startActivityIfNeeded(intent, -1)) {
2631 } catch (ActivityNotFoundException ex) {
2632 // ignore the error. If no application can handle the URL,
2633 // eg about:blank, assume the browser can handle it.
2646 * Updates the lock icon. This method is called when we discover another
2647 * resource to be loaded for this page (for example, javascript). While
2648 * we update the icon type, we do not update the lock icon itself until
2649 * we are done loading, it is slightly more secure this way.
2652 public void onLoadResource(WebView view, String url) {
2653 if (url != null && url.length() > 0) {
2654 // It is only if the page claims to be secure
2655 // that we may have to update the lock:
2656 if (mLockIconType == LOCK_ICON_SECURE) {
2657 // If NOT a 'safe' url, change the lock to mixed content!
2658 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2659 mLockIconType = LOCK_ICON_MIXED;
2661 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2662 " updated lock icon to " + mLockIconType + " due to " + url);
2670 * Show the dialog, asking the user if they would like to continue after
2671 * an excessive number of HTTP redirects.
2674 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2675 final Message continueMsg) {
2676 new AlertDialog.Builder(BrowserActivity.this)
2677 .setTitle(R.string.browserFrameRedirect)
2678 .setMessage(R.string.browserFrame307Post)
2679 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2680 public void onClick(DialogInterface dialog, int which) {
2681 continueMsg.sendToTarget();
2683 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2684 public void onClick(DialogInterface dialog, int which) {
2685 cancelMsg.sendToTarget();
2687 .setOnCancelListener(new OnCancelListener() {
2688 public void onCancel(DialogInterface dialog) {
2689 cancelMsg.sendToTarget();
2694 // Container class for the next error dialog that needs to be
2697 public final int mTitle;
2698 public final String mDescription;
2699 public final int mError;
2700 ErrorDialog(int title, String desc, int error) {
2702 mDescription = desc;
2707 private void processNextError() {
2708 if (mQueuedErrors == null) {
2711 // The first one is currently displayed so just remove it.
2712 mQueuedErrors.removeFirst();
2713 if (mQueuedErrors.size() == 0) {
2714 mQueuedErrors = null;
2717 showError(mQueuedErrors.getFirst());
2720 private DialogInterface.OnDismissListener mDialogListener =
2721 new DialogInterface.OnDismissListener() {
2722 public void onDismiss(DialogInterface d) {
2726 private LinkedList<ErrorDialog> mQueuedErrors;
2728 private void queueError(int err, String desc) {
2729 if (mQueuedErrors == null) {
2730 mQueuedErrors = new LinkedList<ErrorDialog>();
2732 for (ErrorDialog d : mQueuedErrors) {
2733 if (d.mError == err) {
2734 // Already saw a similar error, ignore the new one.
2738 ErrorDialog errDialog = new ErrorDialog(
2739 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
2740 R.string.browserFrameFileErrorLabel :
2741 R.string.browserFrameNetworkErrorLabel,
2743 mQueuedErrors.addLast(errDialog);
2745 // Show the dialog now if the queue was empty.
2746 if (mQueuedErrors.size() == 1) {
2747 showError(errDialog);
2751 private void showError(ErrorDialog errDialog) {
2752 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2753 .setTitle(errDialog.mTitle)
2754 .setMessage(errDialog.mDescription)
2755 .setPositiveButton(R.string.ok, null)
2757 d.setOnDismissListener(mDialogListener);
2762 * Show a dialog informing the user of the network error reported by
2766 public void onReceivedError(WebView view, int errorCode,
2767 String description, String failingUrl) {
2768 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2769 errorCode != WebViewClient.ERROR_CONNECT &&
2770 errorCode != WebViewClient.ERROR_BAD_URL &&
2771 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2772 errorCode != WebViewClient.ERROR_FILE) {
2773 queueError(errorCode, description);
2775 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2776 + " " + description);
2778 // We need to reset the title after an error.
2779 resetTitleAndRevertLockIcon();
2783 * Check with the user if it is ok to resend POST data as the page they
2784 * are trying to navigate to is the result of a POST.
2787 public void onFormResubmission(WebView view, final Message dontResend,
2788 final Message resend) {
2789 new AlertDialog.Builder(BrowserActivity.this)
2790 .setTitle(R.string.browserFrameFormResubmitLabel)
2791 .setMessage(R.string.browserFrameFormResubmitMessage)
2792 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2793 public void onClick(DialogInterface dialog, int which) {
2794 resend.sendToTarget();
2796 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2797 public void onClick(DialogInterface dialog, int which) {
2798 dontResend.sendToTarget();
2800 .setOnCancelListener(new OnCancelListener() {
2801 public void onCancel(DialogInterface dialog) {
2802 dontResend.sendToTarget();
2808 * Insert the url into the visited history database.
2809 * @param url The url to be inserted.
2810 * @param isReload True if this url is being reloaded.
2811 * FIXME: Not sure what to do when reloading the page.
2814 public void doUpdateVisitedHistory(WebView view, String url,
2816 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2819 // remove "client" before updating it to the history so that it wont
2820 // show up in the auto-complete list.
2821 int index = url.indexOf("client=ms-");
2822 if (index > 0 && url.contains(".google.")) {
2823 int end = url.indexOf('&', index);
2825 url = url.substring(0, index-1).concat(url.substring(end));
2827 url = url.substring(0, index-1);
2830 Browser.updateVisitedHistory(mResolver, url, true);
2831 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2835 * Displays SSL error(s) dialog to the user.
2838 public void onReceivedSslError(
2839 final WebView view, final SslErrorHandler handler, final SslError error) {
2841 if (mSettings.showSecurityWarnings()) {
2842 final LayoutInflater factory =
2843 LayoutInflater.from(BrowserActivity.this);
2844 final View warningsView =
2845 factory.inflate(R.layout.ssl_warnings, null);
2846 final LinearLayout placeholder =
2847 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2849 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2850 LinearLayout ll = (LinearLayout)factory
2851 .inflate(R.layout.ssl_warning, null);
2852 ((TextView)ll.findViewById(R.id.warning))
2853 .setText(R.string.ssl_untrusted);
2854 placeholder.addView(ll);
2857 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2858 LinearLayout ll = (LinearLayout)factory
2859 .inflate(R.layout.ssl_warning, null);
2860 ((TextView)ll.findViewById(R.id.warning))
2861 .setText(R.string.ssl_mismatch);
2862 placeholder.addView(ll);
2865 if (error.hasError(SslError.SSL_EXPIRED)) {
2866 LinearLayout ll = (LinearLayout)factory
2867 .inflate(R.layout.ssl_warning, null);
2868 ((TextView)ll.findViewById(R.id.warning))
2869 .setText(R.string.ssl_expired);
2870 placeholder.addView(ll);
2873 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2874 LinearLayout ll = (LinearLayout)factory
2875 .inflate(R.layout.ssl_warning, null);
2876 ((TextView)ll.findViewById(R.id.warning))
2877 .setText(R.string.ssl_not_yet_valid);
2878 placeholder.addView(ll);
2881 new AlertDialog.Builder(BrowserActivity.this)
2882 .setTitle(R.string.security_warning)
2883 .setIcon(android.R.drawable.ic_dialog_alert)
2884 .setView(warningsView)
2885 .setPositiveButton(R.string.ssl_continue,
2886 new DialogInterface.OnClickListener() {
2887 public void onClick(DialogInterface dialog, int whichButton) {
2891 .setNeutralButton(R.string.view_certificate,
2892 new DialogInterface.OnClickListener() {
2893 public void onClick(DialogInterface dialog, int whichButton) {
2894 showSSLCertificateOnError(view, handler, error);
2897 .setNegativeButton(R.string.cancel,
2898 new DialogInterface.OnClickListener() {
2899 public void onClick(DialogInterface dialog, int whichButton) {
2901 BrowserActivity.this.resetTitleAndRevertLockIcon();
2904 .setOnCancelListener(
2905 new DialogInterface.OnCancelListener() {
2906 public void onCancel(DialogInterface dialog) {
2908 BrowserActivity.this.resetTitleAndRevertLockIcon();
2918 * Handles an HTTP authentication request.
2920 * @param handler The authentication handler
2921 * @param host The host
2922 * @param realm The realm
2925 public void onReceivedHttpAuthRequest(WebView view,
2926 final HttpAuthHandler handler, final String host, final String realm) {
2927 String username = null;
2928 String password = null;
2930 boolean reuseHttpAuthUsernamePassword =
2931 handler.useHttpAuthUsernamePassword();
2933 if (reuseHttpAuthUsernamePassword &&
2934 (mTabControl.getCurrentWebView() != null)) {
2935 String[] credentials =
2936 mTabControl.getCurrentWebView()
2937 .getHttpAuthUsernamePassword(host, realm);
2938 if (credentials != null && credentials.length == 2) {
2939 username = credentials[0];
2940 password = credentials[1];
2944 if (username != null && password != null) {
2945 handler.proceed(username, password);
2947 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2952 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2954 // only check shortcut key when MENU is held
2955 return getWindow().isShortcutKey(event.getKeyCode(), event);
2962 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2963 if (view != mTabControl.getCurrentTopWebView()) {
2966 if (event.isDown()) {
2967 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2969 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2974 //--------------------------------------------------------------------------
2975 // WebChromeClient implementation
2976 //--------------------------------------------------------------------------
2978 /* package */ WebChromeClient getWebChromeClient() {
2979 return mWebChromeClient;
2982 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2983 // Helper method to create a new tab or sub window.
2984 private void createWindow(final boolean dialog, final Message msg) {
2986 mTabControl.createSubWindow();
2987 final TabControl.Tab t = mTabControl.getCurrentTab();
2989 WebView.WebViewTransport transport =
2990 (WebView.WebViewTransport) msg.obj;
2991 transport.setWebView(t.getSubWebView());
2994 final TabControl.Tab parent = mTabControl.getCurrentTab();
2995 final TabControl.Tab newTab
2996 = openTabAndShow(EMPTY_URL_DATA, false, null);
2997 if (newTab != parent) {
2998 parent.addChildTab(newTab);
3000 WebView.WebViewTransport transport =
3001 (WebView.WebViewTransport) msg.obj;
3002 transport.setWebView(mTabControl.getCurrentWebView());
3008 public boolean onCreateWindow(WebView view, final boolean dialog,
3009 final boolean userGesture, final Message resultMsg) {
3010 // Short-circuit if we can't create any more tabs or sub windows.
3011 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3012 new AlertDialog.Builder(BrowserActivity.this)
3013 .setTitle(R.string.too_many_subwindows_dialog_title)
3014 .setIcon(android.R.drawable.ic_dialog_alert)
3015 .setMessage(R.string.too_many_subwindows_dialog_message)
3016 .setPositiveButton(R.string.ok, null)
3019 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3020 new AlertDialog.Builder(BrowserActivity.this)
3021 .setTitle(R.string.too_many_windows_dialog_title)
3022 .setIcon(android.R.drawable.ic_dialog_alert)
3023 .setMessage(R.string.too_many_windows_dialog_message)
3024 .setPositiveButton(R.string.ok, null)
3029 // Short-circuit if this was a user gesture.
3031 createWindow(dialog, resultMsg);
3035 // Allow the popup and create the appropriate window.
3036 final AlertDialog.OnClickListener allowListener =
3037 new AlertDialog.OnClickListener() {
3038 public void onClick(DialogInterface d,
3040 createWindow(dialog, resultMsg);
3044 // Block the popup by returning a null WebView.
3045 final AlertDialog.OnClickListener blockListener =
3046 new AlertDialog.OnClickListener() {
3047 public void onClick(DialogInterface d, int which) {
3048 resultMsg.sendToTarget();
3052 // Build a confirmation dialog to display to the user.
3053 final AlertDialog d =
3054 new AlertDialog.Builder(BrowserActivity.this)
3055 .setTitle(R.string.attention)
3056 .setIcon(android.R.drawable.ic_dialog_alert)
3057 .setMessage(R.string.popup_window_attempt)
3058 .setPositiveButton(R.string.allow, allowListener)
3059 .setNegativeButton(R.string.block, blockListener)
3060 .setCancelable(false)
3063 // Show the confirmation dialog.
3069 public void onCloseWindow(WebView window) {
3070 final TabControl.Tab current = mTabControl.getCurrentTab();
3071 final TabControl.Tab parent = current.getParentTab();
3072 if (parent != null) {
3073 // JavaScript can only close popup window.
3074 switchToTab(mTabControl.getTabIndex(parent));
3075 // Now we need to close the window
3081 public void onProgressChanged(WebView view, int newProgress) {
3082 mTitleBar.setProgress(newProgress, view);
3083 if (mFakeTitleBar != null) {
3084 mFakeTitleBar.setProgress(newProgress);
3087 if (newProgress == 100) {
3088 // onProgressChanged() is called for sub-frame too while
3089 // onPageFinished() is only called for the main frame. sync
3090 // cookie and cache promptly here.
3091 CookieSyncManager.getInstance().sync();
3094 updateInLoadMenuItems();
3095 // If the options menu is open, leave the title bar
3096 if (!mOptionsMenuOpen || !mIconView) {
3100 } else if (!mInLoad) {
3101 // onPageFinished may have already been called but a subframe
3102 // is still loading and updating the progress. Reset mInLoad
3103 // and update the menu items.
3105 updateInLoadMenuItems();
3106 WebView currentWebView = mTabControl.getCurrentWebView();
3107 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3108 && (!mOptionsMenuOpen || mIconView)) {
3109 // This page has begun to load, so show the title bar
3116 public void onReceivedTitle(WebView view, String title) {
3117 String url = view.getUrl();
3119 // here, if url is null, we want to reset the title
3120 setUrlTitle(url, title, view);
3123 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3126 // See if we can find the current url in our history database and
3127 // add the new title to it.
3128 if (url.startsWith("http://www.")) {
3129 url = url.substring(11);
3130 } else if (url.startsWith("http://")) {
3131 url = url.substring(4);
3135 String [] selArgs = new String[] { url };
3137 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3138 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3139 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3140 Browser.HISTORY_PROJECTION, where, selArgs, null);
3141 if (c.moveToFirst()) {
3142 // Current implementation of database only has one entry per
3144 ContentValues map = new ContentValues();
3145 map.put(Browser.BookmarkColumns.TITLE, title);
3146 mResolver.update(Browser.BOOKMARKS_URI, map,
3147 "_id = " + c.getInt(0), null);
3150 } catch (IllegalStateException e) {
3151 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3152 } catch (SQLiteException ex) {
3153 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3158 public void onReceivedIcon(WebView view, Bitmap icon) {
3159 updateIcon(view, icon);
3163 public void onReceivedTouchIconUrl(WebView view, String url) {
3164 final ContentResolver cr = getContentResolver();
3166 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
3167 view.getOriginalUrl(), view.getUrl(), true);
3169 if (c.getCount() > 0) {
3170 new DownloadTouchIcon(cr, c, view).execute(url);
3178 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
3179 if (mCustomView != null)
3182 // Add the custom view to its container.
3183 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3185 mCustomViewCallback = callback;
3186 // Save the menu state and set it to empty while the custom
3188 mOldMenuState = mMenuState;
3189 mMenuState = EMPTY_MENU;
3190 // Hide the content view.
3191 mContentView.setVisibility(View.GONE);
3192 // Finally show the custom view container.
3193 mCustomViewContainer.setVisibility(View.VISIBLE);
3194 mCustomViewContainer.bringToFront();
3198 public void onHideCustomView() {
3199 if (mCustomView == null)
3202 // Hide the custom view.
3203 mCustomView.setVisibility(View.GONE);
3204 // Remove the custom view from its container.
3205 mCustomViewContainer.removeView(mCustomView);
3207 // Reset the old menu state.
3208 mMenuState = mOldMenuState;
3209 mOldMenuState = EMPTY_MENU;
3210 mCustomViewContainer.setVisibility(View.GONE);
3211 mCustomViewCallback.onCustomViewHidden();
3212 // Show the content view.
3213 mContentView.setVisibility(View.VISIBLE);
3217 * The origin has exceeded its database quota.
3218 * @param url the URL that exceeded the quota
3219 * @param databaseIdentifier the identifier of the database on
3220 * which the transaction that caused the quota overflow was run
3221 * @param currentQuota the current quota for the origin.
3222 * @param estimatedSize the estimated size of the database.
3223 * @param totalUsedQuota is the sum of all origins' quota.
3224 * @param quotaUpdater The callback to run when a decision to allow or
3225 * deny quota has been made. Don't forget to call this!
3228 public void onExceededDatabaseQuota(String url,
3229 String databaseIdentifier, long currentQuota, long estimatedSize,
3230 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3231 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3232 url, databaseIdentifier, currentQuota, estimatedSize,
3233 totalUsedQuota, quotaUpdater);
3237 * The Application Cache has exceeded its max size.
3238 * @param spaceNeeded is the amount of disk space that would be needed
3239 * in order for the last appcache operation to succeed.
3240 * @param totalUsedQuota is the sum of all origins' quota.
3241 * @param quotaUpdater A callback to inform the WebCore thread that a new
3242 * app cache size is available. This callback must always be executed at
3243 * some point to ensure that the sleeping WebCore thread is woken up.
3246 public void onReachedMaxAppCacheSize(long spaceNeeded,
3247 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3248 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3249 spaceNeeded, totalUsedQuota, quotaUpdater);
3253 * Instructs the browser to show a prompt to ask the user to set the
3254 * Geolocation permission state for the specified origin.
3255 * @param origin The origin for which Geolocation permissions are
3257 * @param callback The callback to call once the user has set the
3258 * Geolocation permission state.
3261 public void onGeolocationPermissionsShowPrompt(String origin,
3262 GeolocationPermissions.Callback callback) {
3263 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3268 * Instructs the browser to hide the Geolocation permissions prompt.
3271 public void onGeolocationPermissionsHidePrompt() {
3272 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3275 /* Adds a JavaScript error message to the system log.
3276 * @param message The error message to report.
3277 * @param lineNumber The line number of the error.
3278 * @param sourceID The name of the source file that caused the error.
3281 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3282 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3283 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3284 if (mShouldShowErrorConsole &&
3285 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3286 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3288 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
3293 * Notify the host application a download should be done, or that
3294 * the data should be streamed if a streaming viewer is available.
3295 * @param url The full url to the content that should be downloaded
3296 * @param contentDisposition Content-disposition http header, if
3298 * @param mimetype The mimetype of the content reported by the server
3299 * @param contentLength The file size reported by the server
3301 public void onDownloadStart(String url, String userAgent,
3302 String contentDisposition, String mimetype, long contentLength) {
3303 // if we're dealing wih A/V content that's not explicitly marked
3304 // for download, check if it's streamable.
3305 if (contentDisposition == null
3306 || !contentDisposition.regionMatches(
3307 true, 0, "attachment", 0, 10)) {
3308 // query the package manager to see if there's a registered handler
3310 Intent intent = new Intent(Intent.ACTION_VIEW);
3311 intent.setDataAndType(Uri.parse(url), mimetype);
3312 ResolveInfo info = getPackageManager().resolveActivity(intent,
3313 PackageManager.MATCH_DEFAULT_ONLY);
3315 ComponentName myName = getComponentName();
3316 // If we resolved to ourselves, we don't want to attempt to
3317 // load the url only to try and download it again.
3318 if (!myName.getPackageName().equals(
3319 info.activityInfo.packageName)
3320 || !myName.getClassName().equals(
3321 info.activityInfo.name)) {
3322 // someone (other than us) knows how to handle this mime
3323 // type with this scheme, don't download.
3325 startActivity(intent);
3327 } catch (ActivityNotFoundException ex) {
3329 Log.d(LOGTAG, "activity not found for " + mimetype
3330 + " over " + Uri.parse(url).getScheme(),
3333 // Best behavior is to fall back to a download in this
3339 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3343 * Notify the host application a download should be done, even if there
3344 * is a streaming viewer available for thise type.
3345 * @param url The full url to the content that should be downloaded
3346 * @param contentDisposition Content-disposition http header, if
3348 * @param mimetype The mimetype of the content reported by the server
3349 * @param contentLength The file size reported by the server
3351 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3352 String contentDisposition, String mimetype, long contentLength) {
3354 String filename = URLUtil.guessFileName(url,
3355 contentDisposition, mimetype);
3357 // Check to see if we have an SDCard
3358 String status = Environment.getExternalStorageState();
3359 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3363 // Check to see if the SDCard is busy, same as the music app
3364 if (status.equals(Environment.MEDIA_SHARED)) {
3365 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3366 title = R.string.download_sdcard_busy_dlg_title;
3368 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3369 title = R.string.download_no_sdcard_dlg_title;
3372 new AlertDialog.Builder(this)
3374 .setIcon(android.R.drawable.ic_dialog_alert)
3376 .setPositiveButton(R.string.ok, null)
3381 // java.net.URI is a lot stricter than KURL so we have to undo
3382 // KURL's percent-encoding and redo the encoding using java.net.URI.
3385 // Undo the percent-encoding that KURL may have done.
3386 String newUrl = new String(URLUtil.decode(url.getBytes()));
3387 // Parse the url into pieces
3388 WebAddress w = new WebAddress(newUrl);
3390 String query = null;
3391 String path = w.mPath;
3392 // Break the path into path, query, and fragment
3393 if (path.length() > 0) {
3394 // Strip the fragment
3395 int idx = path.lastIndexOf('#');
3397 frag = path.substring(idx + 1);
3398 path = path.substring(0, idx);
3400 idx = path.lastIndexOf('?');
3402 query = path.substring(idx + 1);
3403 path = path.substring(0, idx);
3406 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3408 } catch (Exception e) {
3409 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3413 // XXX: Have to use the old url since the cookies were stored using the
3414 // old percent-encoded url.
3415 String cookies = CookieManager.getInstance().getCookie(url);
3417 ContentValues values = new ContentValues();
3418 values.put(Downloads.COLUMN_URI, uri.toString());
3419 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3420 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3421 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
3423 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
3424 BrowserDownloadPage.class.getCanonicalName());
3425 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3426 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3427 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3428 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
3429 if (contentLength > 0) {
3430 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
3432 if (mimetype == null) {
3433 // We must have long pressed on a link or image to download it. We
3434 // are not sure of the mimetype in this case, so do a head request
3435 new FetchUrlMimeType(this).execute(values);
3437 final Uri contentUri =
3438 getContentResolver().insert(Downloads.CONTENT_URI, values);
3439 viewDownloads(contentUri);
3445 * Resets the lock icon. This method is called when we start a new load and
3446 * know the url to be loaded.
3448 private void resetLockIcon(String url) {
3449 // Save the lock-icon state (we revert to it if the load gets cancelled)
3452 mLockIconType = LOCK_ICON_UNSECURE;
3453 if (URLUtil.isHttpsUrl(url)) {
3454 mLockIconType = LOCK_ICON_SECURE;
3456 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3457 " reset lock icon to " + mLockIconType);
3461 updateLockIconImage(LOCK_ICON_UNSECURE);
3465 * Resets the lock icon. This method is called when the icon needs to be
3466 * reset but we do not know whether we are loading a secure or not secure
3469 private void resetLockIcon() {
3470 // Save the lock-icon state (we revert to it if the load gets cancelled)
3473 mLockIconType = LOCK_ICON_UNSECURE;
3476 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3477 " reset lock icon to " + mLockIconType);
3480 updateLockIconImage(LOCK_ICON_UNSECURE);
3484 * Update the lock icon to correspond to our latest state.
3486 /* package */ void updateLockIconToLatest() {
3487 updateLockIconImage(mLockIconType);
3491 * Updates the lock-icon image in the title-bar.
3493 private void updateLockIconImage(int lockIconType) {
3495 if (lockIconType == LOCK_ICON_SECURE) {
3497 } else if (lockIconType == LOCK_ICON_MIXED) {
3500 mTitleBar.setLock(d, getTopWindow());
3501 if (mFakeTitleBar != null) {
3502 mFakeTitleBar.setLock(d);
3507 * Displays a page-info dialog.
3508 * @param tab The tab to show info about
3509 * @param fromShowSSLCertificateOnError The flag that indicates whether
3510 * this dialog was opened from the SSL-certificate-on-error dialog or
3511 * not. This is important, since we need to know whether to return to
3512 * the parent dialog or simply dismiss.
3514 private void showPageInfo(final TabControl.Tab tab,
3515 final boolean fromShowSSLCertificateOnError) {
3516 final LayoutInflater factory = LayoutInflater
3519 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3521 final WebView view = tab.getWebView();
3524 String title = null;
3528 title = tab.getTitle();
3529 } else if (view == mTabControl.getCurrentWebView()) {
3530 // Use the cached title and url if this is the current WebView
3534 url = view.getUrl();
3535 title = view.getTitle();
3541 if (title == null) {
3545 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3546 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3548 mPageInfoView = tab;
3549 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3551 AlertDialog.Builder alertDialogBuilder =
3552 new AlertDialog.Builder(this)
3553 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3554 .setView(pageInfoView)
3557 new DialogInterface.OnClickListener() {
3558 public void onClick(DialogInterface dialog,
3560 mPageInfoDialog = null;
3561 mPageInfoView = null;
3562 mPageInfoFromShowSSLCertificateOnError = null;
3564 // if we came here from the SSL error dialog
3565 if (fromShowSSLCertificateOnError) {
3566 // go back to the SSL error dialog
3567 showSSLCertificateOnError(
3568 mSSLCertificateOnErrorView,
3569 mSSLCertificateOnErrorHandler,
3570 mSSLCertificateOnErrorError);
3574 .setOnCancelListener(
3575 new DialogInterface.OnCancelListener() {
3576 public void onCancel(DialogInterface dialog) {
3577 mPageInfoDialog = null;
3578 mPageInfoView = null;
3579 mPageInfoFromShowSSLCertificateOnError = null;
3581 // if we came here from the SSL error dialog
3582 if (fromShowSSLCertificateOnError) {
3583 // go back to the SSL error dialog
3584 showSSLCertificateOnError(
3585 mSSLCertificateOnErrorView,
3586 mSSLCertificateOnErrorHandler,
3587 mSSLCertificateOnErrorError);
3592 // if we have a main top-level page SSL certificate set or a certificate
3594 if (fromShowSSLCertificateOnError ||
3595 (view != null && view.getCertificate() != null)) {
3596 // add a 'View Certificate' button
3597 alertDialogBuilder.setNeutralButton(
3598 R.string.view_certificate,
3599 new DialogInterface.OnClickListener() {
3600 public void onClick(DialogInterface dialog,
3602 mPageInfoDialog = null;
3603 mPageInfoView = null;
3604 mPageInfoFromShowSSLCertificateOnError = null;
3606 // if we came here from the SSL error dialog
3607 if (fromShowSSLCertificateOnError) {
3608 // go back to the SSL error dialog
3609 showSSLCertificateOnError(
3610 mSSLCertificateOnErrorView,
3611 mSSLCertificateOnErrorHandler,
3612 mSSLCertificateOnErrorError);
3614 // otherwise, display the top-most certificate from
3616 if (view.getCertificate() != null) {
3617 showSSLCertificate(tab);
3624 mPageInfoDialog = alertDialogBuilder.show();
3628 * Displays the main top-level page SSL certificate dialog
3629 * (accessible from the Page-Info dialog).
3630 * @param tab The tab to show certificate for.
3632 private void showSSLCertificate(final TabControl.Tab tab) {
3633 final View certificateView =
3634 inflateCertificateView(tab.getWebView().getCertificate());
3635 if (certificateView == null) {
3639 LayoutInflater factory = LayoutInflater.from(this);
3641 final LinearLayout placeholder =
3642 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3644 LinearLayout ll = (LinearLayout) factory.inflate(
3645 R.layout.ssl_success, placeholder);
3646 ((TextView)ll.findViewById(R.id.success))
3647 .setText(R.string.ssl_certificate_is_valid);
3649 mSSLCertificateView = tab;
3650 mSSLCertificateDialog =
3651 new AlertDialog.Builder(this)
3652 .setTitle(R.string.ssl_certificate).setIcon(
3653 R.drawable.ic_dialog_browser_certificate_secure)
3654 .setView(certificateView)
3655 .setPositiveButton(R.string.ok,
3656 new DialogInterface.OnClickListener() {
3657 public void onClick(DialogInterface dialog,
3659 mSSLCertificateDialog = null;
3660 mSSLCertificateView = null;
3662 showPageInfo(tab, false);
3665 .setOnCancelListener(
3666 new DialogInterface.OnCancelListener() {
3667 public void onCancel(DialogInterface dialog) {
3668 mSSLCertificateDialog = null;
3669 mSSLCertificateView = null;
3671 showPageInfo(tab, false);
3678 * Displays the SSL error certificate dialog.
3679 * @param view The target web-view.
3680 * @param handler The SSL error handler responsible for cancelling the
3681 * connection that resulted in an SSL error or proceeding per user request.
3682 * @param error The SSL error object.
3684 private void showSSLCertificateOnError(
3685 final WebView view, final SslErrorHandler handler, final SslError error) {
3687 final View certificateView =
3688 inflateCertificateView(error.getCertificate());
3689 if (certificateView == null) {
3693 LayoutInflater factory = LayoutInflater.from(this);
3695 final LinearLayout placeholder =
3696 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3698 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3699 LinearLayout ll = (LinearLayout)factory
3700 .inflate(R.layout.ssl_warning, placeholder);
3701 ((TextView)ll.findViewById(R.id.warning))
3702 .setText(R.string.ssl_untrusted);
3705 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3706 LinearLayout ll = (LinearLayout)factory
3707 .inflate(R.layout.ssl_warning, placeholder);
3708 ((TextView)ll.findViewById(R.id.warning))
3709 .setText(R.string.ssl_mismatch);
3712 if (error.hasError(SslError.SSL_EXPIRED)) {
3713 LinearLayout ll = (LinearLayout)factory
3714 .inflate(R.layout.ssl_warning, placeholder);
3715 ((TextView)ll.findViewById(R.id.warning))
3716 .setText(R.string.ssl_expired);
3719 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3720 LinearLayout ll = (LinearLayout)factory
3721 .inflate(R.layout.ssl_warning, placeholder);
3722 ((TextView)ll.findViewById(R.id.warning))
3723 .setText(R.string.ssl_not_yet_valid);
3726 mSSLCertificateOnErrorHandler = handler;
3727 mSSLCertificateOnErrorView = view;
3728 mSSLCertificateOnErrorError = error;
3729 mSSLCertificateOnErrorDialog =
3730 new AlertDialog.Builder(this)
3731 .setTitle(R.string.ssl_certificate).setIcon(
3732 R.drawable.ic_dialog_browser_certificate_partially_secure)
3733 .setView(certificateView)
3734 .setPositiveButton(R.string.ok,
3735 new DialogInterface.OnClickListener() {
3736 public void onClick(DialogInterface dialog,
3738 mSSLCertificateOnErrorDialog = null;
3739 mSSLCertificateOnErrorView = null;
3740 mSSLCertificateOnErrorHandler = null;
3741 mSSLCertificateOnErrorError = null;
3743 mWebViewClient.onReceivedSslError(
3744 view, handler, error);
3747 .setNeutralButton(R.string.page_info_view,
3748 new DialogInterface.OnClickListener() {
3749 public void onClick(DialogInterface dialog,
3751 mSSLCertificateOnErrorDialog = null;
3753 // do not clear the dialog state: we will
3754 // need to show the dialog again once the
3755 // user is done exploring the page-info details
3757 showPageInfo(mTabControl.getTabFromView(view),
3761 .setOnCancelListener(
3762 new DialogInterface.OnCancelListener() {
3763 public void onCancel(DialogInterface dialog) {
3764 mSSLCertificateOnErrorDialog = null;
3765 mSSLCertificateOnErrorView = null;
3766 mSSLCertificateOnErrorHandler = null;
3767 mSSLCertificateOnErrorError = null;
3769 mWebViewClient.onReceivedSslError(
3770 view, handler, error);
3777 * Inflates the SSL certificate view (helper method).
3778 * @param certificate The SSL certificate.
3779 * @return The resultant certificate view with issued-to, issued-by,
3780 * issued-on, expires-on, and possibly other fields set.
3781 * If the input certificate is null, returns null.
3783 private View inflateCertificateView(SslCertificate certificate) {
3784 if (certificate == null) {
3788 LayoutInflater factory = LayoutInflater.from(this);
3790 View certificateView = factory.inflate(
3791 R.layout.ssl_certificate, null);
3794 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3795 if (issuedTo != null) {
3796 ((TextView) certificateView.findViewById(R.id.to_common))
3797 .setText(issuedTo.getCName());
3798 ((TextView) certificateView.findViewById(R.id.to_org))
3799 .setText(issuedTo.getOName());
3800 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3801 .setText(issuedTo.getUName());
3805 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3806 if (issuedBy != null) {
3807 ((TextView) certificateView.findViewById(R.id.by_common))
3808 .setText(issuedBy.getCName());
3809 ((TextView) certificateView.findViewById(R.id.by_org))
3810 .setText(issuedBy.getOName());
3811 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3812 .setText(issuedBy.getUName());
3816 String issuedOn = reformatCertificateDate(
3817 certificate.getValidNotBefore());
3818 ((TextView) certificateView.findViewById(R.id.issued_on))
3822 String expiresOn = reformatCertificateDate(
3823 certificate.getValidNotAfter());
3824 ((TextView) certificateView.findViewById(R.id.expires_on))
3825 .setText(expiresOn);
3827 return certificateView;
3831 * Re-formats the certificate date (Date.toString()) string to
3832 * a properly localized date string.
3833 * @return Properly localized version of the certificate date string and
3834 * the original certificate date string if fails to localize.
3835 * If the original string is null, returns an empty string "".
3837 private String reformatCertificateDate(String certificateDate) {
3838 String reformattedDate = null;
3840 if (certificateDate != null) {
3843 date = java.text.DateFormat.getInstance().parse(certificateDate);
3844 } catch (ParseException e) {
3850 DateFormat.getDateFormat(this).format(date);
3854 return reformattedDate != null ? reformattedDate :
3855 (certificateDate != null ? certificateDate : "");
3859 * Displays an http-authentication dialog.
3861 private void showHttpAuthentication(final HttpAuthHandler handler,
3862 final String host, final String realm, final String title,
3863 final String name, final String password, int focusId) {
3864 LayoutInflater factory = LayoutInflater.from(this);
3865 final View v = factory
3866 .inflate(R.layout.http_authentication, null);
3868 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3870 if (password != null) {
3871 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3874 String titleText = title;
3875 if (titleText == null) {
3876 titleText = getText(R.string.sign_in_to).toString().replace(
3877 "%s1", host).replace("%s2", realm);
3880 mHttpAuthHandler = handler;
3881 AlertDialog dialog = new AlertDialog.Builder(this)
3882 .setTitle(titleText)
3883 .setIcon(android.R.drawable.ic_dialog_alert)
3885 .setPositiveButton(R.string.action,
3886 new DialogInterface.OnClickListener() {
3887 public void onClick(DialogInterface dialog,
3889 String nm = ((EditText) v
3890 .findViewById(R.id.username_edit))
3891 .getText().toString();
3892 String pw = ((EditText) v
3893 .findViewById(R.id.password_edit))
3894 .getText().toString();
3895 BrowserActivity.this.setHttpAuthUsernamePassword
3896 (host, realm, nm, pw);
3897 handler.proceed(nm, pw);
3898 mHttpAuthenticationDialog = null;
3899 mHttpAuthHandler = null;
3901 .setNegativeButton(R.string.cancel,
3902 new DialogInterface.OnClickListener() {
3903 public void onClick(DialogInterface dialog,
3906 BrowserActivity.this.resetTitleAndRevertLockIcon();
3907 mHttpAuthenticationDialog = null;
3908 mHttpAuthHandler = null;
3910 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3911 public void onCancel(DialogInterface dialog) {
3913 BrowserActivity.this.resetTitleAndRevertLockIcon();
3914 mHttpAuthenticationDialog = null;
3915 mHttpAuthHandler = null;
3918 // Make the IME appear when the dialog is displayed if applicable.
3919 dialog.getWindow().setSoftInputMode(
3920 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3923 dialog.findViewById(focusId).requestFocus();
3925 v.findViewById(R.id.username_edit).requestFocus();
3927 mHttpAuthenticationDialog = dialog;
3930 public int getProgress() {
3931 WebView w = mTabControl.getCurrentWebView();
3933 return w.getProgress();
3940 * Set HTTP authentication password.
3942 * @param host The host for the password
3943 * @param realm The realm for the password
3944 * @param username The username for the password. If it is null, it means
3945 * password can't be saved.
3946 * @param password The password
3948 public void setHttpAuthUsernamePassword(String host, String realm,
3951 WebView w = mTabControl.getCurrentWebView();
3953 w.setHttpAuthUsernamePassword(host, realm, username, password);
3958 * connectivity manager says net has come or gone... inform the user
3959 * @param up true if net has come up, false if net has gone down
3961 public void onNetworkToggle(boolean up) {
3962 if (up == mIsNetworkUp) {
3965 mIsNetworkUp = true;
3966 if (mAlertDialog != null) {
3967 mAlertDialog.cancel();
3968 mAlertDialog = null;
3971 mIsNetworkUp = false;
3972 if (mInLoad && mAlertDialog == null) {
3973 mAlertDialog = new AlertDialog.Builder(this)
3974 .setTitle(R.string.loadSuspendedTitle)
3975 .setMessage(R.string.loadSuspended)
3976 .setPositiveButton(R.string.ok, null)
3980 WebView w = mTabControl.getCurrentWebView();
3982 w.setNetworkAvailable(up);
3987 protected void onActivityResult(int requestCode, int resultCode,
3989 switch (requestCode) {
3991 if (resultCode == RESULT_OK && intent != null) {
3992 String data = intent.getAction();
3993 Bundle extras = intent.getExtras();
3994 if (extras != null && extras.getBoolean("new_window", false)) {
3995 final TabControl.Tab newTab = openTab(data);
3996 if (mSettings.openInBackground() &&
3998 mTabControl.populatePickerData(newTab);
3999 mTabControl.setCurrentTab(newTab);
4000 int newIndex = mTabControl.getCurrentIndex();
4001 mTitleBar.setCurrentTab(newIndex);
4004 final TabControl.Tab currentTab =
4005 mTabControl.getCurrentTab();
4006 dismissSubWindow(currentTab);
4007 if (data != null && data.length() != 0) {
4008 getTopWindow().loadUrl(data);
4016 getTopWindow().requestFocus();
4020 * This method is called as a result of the user selecting the options
4021 * menu to see the download window, or when a download changes state. It
4022 * shows the download window ontop of the current window.
4024 /* package */ void viewDownloads(Uri downloadRecord) {
4025 Intent intent = new Intent(this,
4026 BrowserDownloadPage.class);
4027 intent.setData(downloadRecord);
4028 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4034 * @param startWithHistory If true, open starting on the history tab.
4035 * Otherwise, start with the bookmarks tab.
4037 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
4038 WebView current = mTabControl.getCurrentWebView();
4039 if (current == null) {
4042 Intent intent = new Intent(this,
4043 CombinedBookmarkHistoryActivity.class);
4044 String title = current.getTitle();
4045 String url = current.getUrl();
4046 // Just in case the user opens bookmarks before a page finishes loading
4047 // so the current history item, and therefore the page, is null.
4049 url = mLastEnteredUrl;
4052 url = mSettings.getHomePage();
4055 // In case the web page has not yet received its associated title.
4056 if (title == null) {
4059 intent.putExtra("title", title);
4060 intent.putExtra("url", url);
4061 // Disable opening in a new window if we have maxed out the windows
4062 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4063 >= TabControl.MAX_TABS);
4064 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
4065 if (startWithHistory) {
4066 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4067 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4069 startActivityForResult(intent, COMBO_PAGE);
4072 // Called when loading from context menu or LOAD_URL message
4073 private void loadURL(WebView view, String url) {
4074 // In case the user enters nothing.
4075 if (url != null && url.length() != 0 && view != null) {
4076 url = smartUrlFilter(url);
4077 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4083 private String smartUrlFilter(Uri inUri) {
4084 if (inUri != null) {
4085 return smartUrlFilter(inUri.toString());
4093 int getWindowCount(){
4094 if(mTabControl != null){
4095 return mTabControl.getTabCount();
4100 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4101 "(?i)" + // switch on case insensitive matching
4102 "(" + // begin group for schema
4103 "(?:http|https|file):\\/\\/" +
4104 "|(?:inline|data|about|content|javascript):" +
4109 * Attempts to determine whether user input is a URL or search
4110 * terms. Anything with a space is passed to search.
4112 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4113 * "Http://" converts to "http://"
4115 * @return Original or modified URL
4118 String smartUrlFilter(String url) {
4120 String inUrl = url.trim();
4121 boolean hasSpace = inUrl.indexOf(' ') != -1;
4123 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4124 if (matcher.matches()) {
4125 // force scheme to lowercase
4126 String scheme = matcher.group(1);
4127 String lcScheme = scheme.toLowerCase();
4128 if (!lcScheme.equals(scheme)) {
4129 inUrl = lcScheme + matcher.group(2);
4132 inUrl = inUrl.replace(" ", "%20");
4137 // FIXME: Is this the correct place to add to searches?
4138 // what if someone else calls this function?
4139 int shortcut = parseUrlShortcut(inUrl);
4140 if (shortcut != SHORTCUT_INVALID) {
4141 Browser.addSearchUrl(mResolver, inUrl);
4142 String query = inUrl.substring(2);
4144 case SHORTCUT_GOOGLE_SEARCH:
4145 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
4146 case SHORTCUT_WIKIPEDIA_SEARCH:
4147 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4148 case SHORTCUT_DICTIONARY_SEARCH:
4149 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4150 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
4151 // FIXME: we need location in this case
4152 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
4156 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4157 return URLUtil.guessUrl(inUrl);
4161 Browser.addSearchUrl(mResolver, inUrl);
4162 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
4165 /* package */ void setShouldShowErrorConsole(boolean flag) {
4166 if (flag == mShouldShowErrorConsole) {
4171 mShouldShowErrorConsole = flag;
4173 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4176 // Setting the show state of the console will cause it's the layout to be inflated.
4177 if (errorConsole.numberOfErrors() > 0) {
4178 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4180 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4183 // Now we can add it to the main view.
4184 mErrorConsoleContainer.addView(errorConsole,
4185 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4186 ViewGroup.LayoutParams.WRAP_CONTENT));
4188 mErrorConsoleContainer.removeView(errorConsole);
4193 private final static int LOCK_ICON_UNSECURE = 0;
4194 private final static int LOCK_ICON_SECURE = 1;
4195 private final static int LOCK_ICON_MIXED = 2;
4197 private int mLockIconType = LOCK_ICON_UNSECURE;
4198 private int mPrevLockType = LOCK_ICON_UNSECURE;
4200 private BrowserSettings mSettings;
4201 private TabControl mTabControl;
4202 private ContentResolver mResolver;
4203 private FrameLayout mContentView;
4204 private View mCustomView;
4205 private FrameLayout mCustomViewContainer;
4206 private WebChromeClient.CustomViewCallback mCustomViewCallback;
4208 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4209 // view, we should rewrite this.
4210 private int mCurrentMenuState = 0;
4211 private int mMenuState = R.id.MAIN_MENU;
4212 private int mOldMenuState = EMPTY_MENU;
4213 private static final int EMPTY_MENU = -1;
4216 private FindDialog mFindDialog;
4217 // Used to prevent chording to result in firing two shortcuts immediately
4218 // one after another. Fixes bug 1211714.
4221 private boolean mInLoad;
4222 private boolean mIsNetworkUp;
4224 private boolean mPageStarted;
4225 private boolean mActivityInPause = true;
4227 private boolean mMenuIsDown;
4229 private final KeyTracker mKeyTracker = new KeyTracker(this);
4231 // As trackball doesn't send repeat down, we have to track it ourselves
4232 private boolean mTrackTrackball;
4234 private static boolean mInTrace;
4236 // Performance probe
4237 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4238 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4239 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4240 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4241 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4242 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4243 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4244 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4245 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4248 private long mStart;
4249 private long mProcessStart;
4250 private long mUserStart;
4251 private long mSystemStart;
4252 private long mIdleStart;
4253 private long mIrqStart;
4255 private long mUiStart;
4257 private Drawable mMixLockIcon;
4258 private Drawable mSecLockIcon;
4260 /* hold a ref so we can auto-cancel if necessary */
4261 private AlertDialog mAlertDialog;
4263 // Wait for credentials before loading google.com
4264 private ProgressDialog mCredsDlg;
4266 // The up-to-date URL and title (these can be different from those stored
4267 // in WebView, since it takes some time for the information in WebView to
4269 private String mUrl;
4270 private String mTitle;
4272 // As PageInfo has different style for landscape / portrait, we have
4273 // to re-open it when configuration changed
4274 private AlertDialog mPageInfoDialog;
4275 private TabControl.Tab mPageInfoView;
4276 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4277 // dialog, we should not just dismiss it, but should get back to the
4278 // SSL-certificate-on-error dialog. This flag is used to store this state
4279 private Boolean mPageInfoFromShowSSLCertificateOnError;
4281 // as SSLCertificateOnError has different style for landscape / portrait,
4282 // we have to re-open it when configuration changed
4283 private AlertDialog mSSLCertificateOnErrorDialog;
4284 private WebView mSSLCertificateOnErrorView;
4285 private SslErrorHandler mSSLCertificateOnErrorHandler;
4286 private SslError mSSLCertificateOnErrorError;
4288 // as SSLCertificate has different style for landscape / portrait, we
4289 // have to re-open it when configuration changed
4290 private AlertDialog mSSLCertificateDialog;
4291 private TabControl.Tab mSSLCertificateView;
4293 // as HttpAuthentication has different style for landscape / portrait, we
4294 // have to re-open it when configuration changed
4295 private AlertDialog mHttpAuthenticationDialog;
4296 private HttpAuthHandler mHttpAuthHandler;
4298 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4299 new FrameLayout.LayoutParams(
4300 ViewGroup.LayoutParams.FILL_PARENT,
4301 ViewGroup.LayoutParams.FILL_PARENT);
4302 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4303 new FrameLayout.LayoutParams(
4304 ViewGroup.LayoutParams.FILL_PARENT,
4305 ViewGroup.LayoutParams.FILL_PARENT,
4308 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4310 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4311 // Dictionary search
4312 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4313 // Google Mobile Local search
4314 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4316 final static String QUERY_PLACE_HOLDER = "%s";
4318 // "source" parameter for Google search through search key
4319 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4320 // "source" parameter for Google search through goto menu
4321 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4322 // "source" parameter for Google search through simplily type
4323 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4324 // "source" parameter for Google search suggested by the browser
4325 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4326 // "source" parameter for Google search from unknown source
4327 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4329 private final static String LOGTAG = "browser";
4331 private String mLastEnteredUrl;
4333 private PowerManager.WakeLock mWakeLock;
4334 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4336 private Toast mStopToast;
4338 private TitleBarSet mTitleBar;
4340 private LinearLayout mErrorConsoleContainer = null;
4341 private boolean mShouldShowErrorConsole = false;
4343 // As the ids are dynamically created, we can't guarantee that they will
4344 // be in sequence, so this static array maps ids to a window number.
4345 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4346 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4347 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4348 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4350 // monitor platform changes
4351 private IntentFilter mNetworkStateChangedFilter;
4352 private BroadcastReceiver mNetworkStateIntentReceiver;
4354 private BroadcastReceiver mPackageInstallationReceiver;
4356 // activity requestCode
4357 final static int COMBO_PAGE = 1;
4358 final static int DOWNLOAD_PAGE = 2;
4359 final static int PREFERENCES_PAGE = 3;
4362 * A UrlData class to abstract how the content will be set to WebView.
4363 * This base class uses loadUrl to show the content.
4365 private static class UrlData {
4369 UrlData(String url) {
4373 void setPostData(byte[] postData) {
4374 mPostData = postData;
4378 return mUrl == null || mUrl.length() == 0;
4381 public void loadIn(WebView webView) {
4382 if (mPostData != null) {
4383 webView.postUrl(mUrl, mPostData);
4385 webView.loadUrl(mUrl);
4391 * A subclass of UrlData class that can display inlined content using
4392 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4394 private static class InlinedUrlData extends UrlData {
4395 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4398 mMimeType = mimeType;
4399 mEncoding = encoding;
4406 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4410 public void loadIn(WebView webView) {
4411 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4415 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);