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.View;
94 import android.view.ViewGroup;
95 import android.view.Window;
96 import android.view.WindowManager;
97 import android.view.ContextMenu.ContextMenuInfo;
98 import android.view.MenuItem.OnMenuItemClickListener;
99 import android.view.animation.AlphaAnimation;
100 import android.view.animation.Animation;
101 import android.view.animation.AnimationSet;
102 import android.view.animation.DecelerateInterpolator;
103 import android.view.animation.ScaleAnimation;
104 import android.view.animation.TranslateAnimation;
105 import android.webkit.CookieManager;
106 import android.webkit.CookieSyncManager;
107 import android.webkit.DownloadListener;
108 import android.webkit.GeolocationPermissions;
109 import android.webkit.HttpAuthHandler;
110 import android.webkit.PluginManager;
111 import android.webkit.SslErrorHandler;
112 import android.webkit.URLUtil;
113 import android.webkit.WebChromeClient;
114 import android.webkit.WebChromeClient.CustomViewCallback;
115 import android.webkit.WebHistoryItem;
116 import android.webkit.WebIconDatabase;
117 import android.webkit.WebStorage;
118 import android.webkit.WebView;
119 import android.webkit.WebViewClient;
120 import android.widget.EditText;
121 import android.widget.FrameLayout;
122 import android.widget.LinearLayout;
123 import android.widget.TextView;
124 import android.widget.Toast;
126 import java.io.BufferedOutputStream;
127 import java.io.ByteArrayOutputStream;
129 import java.io.FileInputStream;
130 import java.io.FileOutputStream;
131 import java.io.IOException;
132 import java.io.InputStream;
133 import java.net.MalformedURLException;
135 import java.net.URISyntaxException;
137 import java.net.URLEncoder;
138 import java.text.ParseException;
139 import java.util.Date;
140 import java.util.Enumeration;
141 import java.util.HashMap;
142 import java.util.LinkedList;
143 import java.util.Vector;
144 import java.util.regex.Matcher;
145 import java.util.regex.Pattern;
146 import java.util.zip.ZipEntry;
147 import java.util.zip.ZipFile;
149 public class BrowserActivity extends Activity
150 implements KeyTracker.OnKeyTracker,
151 View.OnCreateContextMenuListener,
154 /* Define some aliases to make these debugging flags easier to refer to.
155 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
157 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
158 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
159 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
161 private IGoogleLoginService mGls = null;
162 private ServiceConnection mGlsConnection = null;
164 private SensorManager mSensorManager = null;
166 // These are single-character shortcuts for searching popular sources.
167 private static final int SHORTCUT_INVALID = 0;
168 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
169 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
170 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
171 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
173 /* Whitelisted webpages
174 private static HashSet<String> sWhiteList;
177 sWhiteList = new HashSet<String>();
178 sWhiteList.add("cnn.com/");
179 sWhiteList.add("espn.go.com/");
180 sWhiteList.add("nytimes.com/");
181 sWhiteList.add("engadget.com/");
182 sWhiteList.add("yahoo.com/");
183 sWhiteList.add("msn.com/");
184 sWhiteList.add("amazon.com/");
185 sWhiteList.add("consumerist.com/");
186 sWhiteList.add("google.com/m/news");
190 private void setupHomePage() {
191 final Runnable getAccount = new Runnable() {
194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
195 // get the default home page
196 String homepage = mSettings.getHomePage();
199 if (mGls == null) return;
201 if (!homepage.startsWith("http://www.google.")) return;
202 if (homepage.indexOf('?') == -1) return;
204 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
205 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
209 // hostedUser == googleUser
210 // The device has only a google account
212 // hostedUser != googleUser
213 // The device has a hosted account and a google account
215 // hostedUser != null, googleUser == null
216 // The device has only a hosted account (so far)
218 // developers might have no accounts at all
219 if (hostedUser == null) return;
221 if (googleUser == null || !hostedUser.equals(googleUser)) {
222 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
223 homepage = homepage.replace("?", "/a/" + domain + "?");
225 } catch (RemoteException ignore) {
226 // Login service died; carry on
227 } catch (RuntimeException ignore) {
228 // Login service died; carry on
234 private void finish(final String homepage) {
235 mHandler.post(new Runnable() {
237 mSettings.setHomePage(BrowserActivity.this, homepage);
238 resumeAfterCredentials();
240 // as this is running in a separate thread,
241 // BrowserActivity's onDestroy() may have been called,
242 // which also calls unbindService().
243 if (mGlsConnection != null) {
244 // we no longer need to keep GLS open
245 unbindService(mGlsConnection);
246 mGlsConnection = null;
251 final boolean[] done = { false };
253 // Open a connection to the Google Login Service. The first
254 // time the connection is established, set up the homepage depending on
255 // the account in a background thread.
256 mGlsConnection = new ServiceConnection() {
257 public void onServiceConnected(ComponentName className, IBinder service) {
258 mGls = IGoogleLoginService.Stub.asInterface(service);
259 if (done[0] == false) {
261 Thread account = new Thread(getAccount);
262 account.setName("GLSAccount");
266 public void onServiceDisconnected(ComponentName className) {
271 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
272 mGlsConnection, Context.BIND_AUTO_CREATE);
275 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
277 public Void doInBackground(File... files) {
279 for (File f : files) {
281 Log.e(LOGTAG, f.getPath() + " was not deleted");
290 * This layout holds everything you see below the status bar, including the
291 * error console, the custom view container, and the webviews.
293 private FrameLayout mBrowserFrameLayout;
295 @Override public void onCreate(Bundle icicle) {
297 Log.v(LOGTAG, this + " onStart");
299 super.onCreate(icicle);
300 this.requestWindowFeature(Window.FEATURE_NO_TITLE);
301 // test the browser in OpenGL
302 // requestWindowFeature(Window.FEATURE_OPENGL);
304 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
306 mResolver = getContentResolver();
309 // start MASF proxy service
311 //Intent proxyServiceIntent = new Intent();
312 //proxyServiceIntent.setComponent
313 // (new ComponentName(
314 // "com.android.masfproxyservice",
315 // "com.android.masfproxyservice.MasfProxyService"));
316 //startService(proxyServiceIntent, null);
318 mSecLockIcon = Resources.getSystem().getDrawable(
319 android.R.drawable.ic_secure);
320 mMixLockIcon = Resources.getSystem().getDrawable(
321 android.R.drawable.ic_partial_secure);
323 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
324 .findViewById(com.android.internal.R.id.content);
325 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
326 .inflate(R.layout.custom_screen, null);
327 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
329 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
330 .findViewById(R.id.error_console);
331 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
332 .findViewById(R.id.fullscreen_custom_content);
333 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
334 mTitleBar = new TitleBar(this);
336 // Create the tab control and our initial tab
337 mTabControl = new TabControl(this);
339 // Open the icon database and retain all the bookmark urls for favicons
340 retainIconsOnStartup();
342 // Keep a settings instance handy.
343 mSettings = BrowserSettings.getInstance();
344 mSettings.setTabControl(mTabControl);
345 mSettings.loadFromDb(this);
347 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
348 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
350 /* enables registration for changes in network status from
352 mNetworkStateChangedFilter = new IntentFilter();
353 mNetworkStateChangedFilter.addAction(
354 ConnectivityManager.CONNECTIVITY_ACTION);
355 mNetworkStateIntentReceiver = new BroadcastReceiver() {
357 public void onReceive(Context context, Intent intent) {
358 if (intent.getAction().equals(
359 ConnectivityManager.CONNECTIVITY_ACTION)) {
360 boolean down = intent.getBooleanExtra(
361 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
362 onNetworkToggle(!down);
367 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
368 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
369 filter.addDataScheme("package");
370 mPackageInstallationReceiver = new BroadcastReceiver() {
372 public void onReceive(Context context, Intent intent) {
373 final String action = intent.getAction();
374 final String packageName = intent.getData()
375 .getSchemeSpecificPart();
376 final boolean replacing = intent.getBooleanExtra(
377 Intent.EXTRA_REPLACING, false);
378 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
379 // if it is replacing, refreshPlugins() when adding
382 PackageManager pm = BrowserActivity.this.getPackageManager();
383 PackageInfo pkgInfo = null;
385 pkgInfo = pm.getPackageInfo(packageName,
386 PackageManager.GET_PERMISSIONS);
387 } catch (PackageManager.NameNotFoundException e) {
390 if (pkgInfo != null) {
391 String permissions[] = pkgInfo.requestedPermissions;
392 if (permissions == null) {
395 boolean permissionOk = false;
396 for (String permit : permissions) {
397 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
403 PluginManager.getInstance(BrowserActivity.this)
405 Intent.ACTION_PACKAGE_ADDED
411 registerReceiver(mPackageInstallationReceiver, filter);
413 // If this was a web search request, pass it on to the default web search provider.
414 if (handleWebSearchIntent(getIntent())) {
415 moveTaskToBack(true);
419 if (!mTabControl.restoreState(icicle)) {
420 // clear up the thumbnail directory if we can't restore the state as
421 // none of the files in the directory are referenced any more.
422 new ClearThumbnails().execute(
423 mTabControl.getThumbnailDir().listFiles());
424 // there is no quit on Android. But if we can't restore the state,
425 // we can treat it as a new Browser, remove the old session cookies.
426 CookieManager.getInstance().removeSessionCookie();
427 final Intent intent = getIntent();
428 final Bundle extra = intent.getExtras();
429 // Create an initial tab.
430 // If the intent is ACTION_VIEW and data is not null, the Browser is
431 // invoked to view the content by another application. In this case,
432 // the tab will be close when exit.
433 UrlData urlData = getUrlDataFromIntent(intent);
435 final TabControl.Tab t = mTabControl.createNewTab(
436 Intent.ACTION_VIEW.equals(intent.getAction()) &&
437 intent.getData() != null,
438 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
439 mTabControl.setCurrentTab(t);
440 attachTabToContentView(t);
441 WebView webView = t.getWebView();
443 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
444 if (scale > 0 && scale <= 1000) {
445 webView.setInitialScale(scale);
448 // If we are not restoring from an icicle, then there is a high
449 // likely hood this is the first run. So, check to see if the
450 // homepage needs to be configured and copy any plugins from our
451 // asset directory to the data partition.
452 if ((extra == null || !extra.getBoolean("testing"))
453 && !mSettings.isLoginInitialized()) {
457 if (urlData.isEmpty()) {
458 if (mSettings.isLoginInitialized()) {
459 webView.loadUrl(mSettings.getHomePage());
461 waitForCredentials();
465 urlData.setPostData(extra
466 .getByteArray(Browser.EXTRA_POST_DATA));
468 urlData.loadIn(webView);
471 // TabControl.restoreState() will create a new tab even if
472 // restoring the state fails.
473 attachTabToContentView(mTabControl.getCurrentTab());
476 // Read JavaScript flags if it exists.
477 String jsFlags = mSettings.getJsFlags();
478 if (jsFlags.trim().length() != 0) {
479 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
484 protected void onNewIntent(Intent intent) {
485 TabControl.Tab current = mTabControl.getCurrentTab();
486 // When a tab is closed on exit, the current tab index is set to -1.
487 // Reset before proceed as Browser requires the current tab to be set.
488 if (current == null) {
489 // Try to reset the tab in case the index was incorrect.
490 current = mTabControl.getTab(0);
491 if (current == null) {
492 // No tabs at all so just ignore this intent.
495 mTabControl.setCurrentTab(current);
496 attachTabToContentView(current);
497 resetTitleAndIcon(current.getWebView());
499 final String action = intent.getAction();
500 final int flags = intent.getFlags();
501 if (Intent.ACTION_MAIN.equals(action) ||
502 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
503 // just resume the browser
506 if (Intent.ACTION_VIEW.equals(action)
507 || Intent.ACTION_SEARCH.equals(action)
508 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
509 || Intent.ACTION_WEB_SEARCH.equals(action)) {
510 // If this was a search request (e.g. search query directly typed into the address bar),
511 // pass it on to the default web search provider.
512 if (handleWebSearchIntent(intent)) {
516 UrlData urlData = getUrlDataFromIntent(intent);
517 if (urlData.isEmpty()) {
518 urlData = new UrlData(mSettings.getHomePage());
520 urlData.setPostData(intent
521 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
523 final String appId = intent
524 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
525 if (Intent.ACTION_VIEW.equals(action)
526 && !getPackageName().equals(appId)
527 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
528 TabControl.Tab appTab = mTabControl.getTabFromId(appId);
529 if (appTab != null) {
530 Log.i(LOGTAG, "Reusing tab for " + appId);
531 // Dismiss the subwindow if applicable.
532 dismissSubWindow(appTab);
533 // Since we might kill the WebView, remove it from the
534 // content view first.
535 removeTabFromContentView(appTab);
536 // Recreate the main WebView after destroying the old one.
537 // If the WebView has the same original url and is on that
538 // page, it can be reused.
540 mTabControl.recreateWebView(appTab, urlData.mUrl);
542 if (current != appTab) {
543 switchToTab(mTabControl.getTabIndex(appTab));
545 urlData.loadIn(appTab.getWebView());
548 // If the tab was the current tab, we have to attach
549 // it to the view system again.
550 attachTabToContentView(appTab);
552 urlData.loadIn(appTab.getWebView());
557 // No matching application tab, try to find a regular tab
558 // with a matching url.
559 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
560 if (appTab != null) {
561 if (current != appTab) {
562 switchToTab(mTabControl.getTabIndex(appTab));
564 // Otherwise, we are already viewing the correct tab.
566 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
567 // will be opened in a new tab unless we have reached
568 // MAX_TABS. Then the url will be opened in the current
569 // tab. If a new tab is created, it will have "true" for
571 openTabAndShow(urlData, true, appId);
575 if ("about:debug".equals(urlData.mUrl)) {
576 mSettings.toggleDebugSettings();
579 // Get rid of the subwindow if it exists
580 dismissSubWindow(current);
581 urlData.loadIn(current.getWebView());
586 private int parseUrlShortcut(String url) {
587 if (url == null) return SHORTCUT_INVALID;
589 // FIXME: quick search, need to be customized by setting
590 if (url.length() > 2 && url.charAt(1) == ' ') {
591 switch (url.charAt(0)) {
592 case 'g': return SHORTCUT_GOOGLE_SEARCH;
593 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
594 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
595 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
598 return SHORTCUT_INVALID;
602 * Launches the default web search activity with the query parameters if the given intent's data
603 * are identified as plain search terms and not URLs/shortcuts.
604 * @return true if the intent was handled and web search activity was launched, false if not.
606 private boolean handleWebSearchIntent(Intent intent) {
607 if (intent == null) return false;
610 final String action = intent.getAction();
611 if (Intent.ACTION_VIEW.equals(action)) {
612 url = intent.getData().toString();
613 } else if (Intent.ACTION_SEARCH.equals(action)
614 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
615 || Intent.ACTION_WEB_SEARCH.equals(action)) {
616 url = intent.getStringExtra(SearchManager.QUERY);
618 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
622 * Launches the default web search activity with the query parameters if the given url string
623 * was identified as plain search terms and not URL/shortcut.
624 * @return true if the request was handled and web search activity was launched, false if not.
626 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
627 if (inUrl == null) return false;
629 // In general, we shouldn't modify URL from Intent.
630 // But currently, we get the user-typed URL from search box as well.
631 String url = fixUrl(inUrl).trim();
633 // URLs and site specific search shortcuts are handled by the regular flow of control, so
635 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
636 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
637 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
641 Browser.updateVisitedHistory(mResolver, url, false);
642 Browser.addSearchUrl(mResolver, url);
644 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
645 intent.addCategory(Intent.CATEGORY_DEFAULT);
646 intent.putExtra(SearchManager.QUERY, url);
647 if (appData != null) {
648 intent.putExtra(SearchManager.APP_DATA, appData);
650 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
651 startActivity(intent);
656 private UrlData getUrlDataFromIntent(Intent intent) {
658 if (intent != null) {
659 final String action = intent.getAction();
660 if (Intent.ACTION_VIEW.equals(action)) {
661 url = smartUrlFilter(intent.getData());
662 if (url != null && url.startsWith("content:")) {
663 /* Append mimetype so webview knows how to display */
664 String mimeType = intent.resolveType(getContentResolver());
665 if (mimeType != null) {
666 url += "?" + mimeType;
669 if ("inline:".equals(url)) {
670 return new InlinedUrlData(
671 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
673 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
674 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
676 } else if (Intent.ACTION_SEARCH.equals(action)
677 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
678 || Intent.ACTION_WEB_SEARCH.equals(action)) {
679 url = intent.getStringExtra(SearchManager.QUERY);
681 mLastEnteredUrl = url;
682 // Don't add Urls, just search terms.
683 // Urls will get added when the page is loaded.
684 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
685 Browser.updateVisitedHistory(mResolver, url, false);
687 // In general, we shouldn't modify URL from Intent.
688 // But currently, we get the user-typed URL from search box as well.
690 url = smartUrlFilter(url);
691 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
692 if (url.contains(searchSource)) {
693 String source = null;
694 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
695 if (appData != null) {
696 source = appData.getString(SearchManager.SOURCE);
698 if (TextUtils.isEmpty(source)) {
699 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
701 url = url.replace(searchSource, "&source=android-"+source+"&");
706 return new UrlData(url);
709 /* package */ static String fixUrl(String inUrl) {
710 // FIXME: Converting the url to lower case
711 // duplicates functionality in smartUrlFilter().
712 // However, changing all current callers of fixUrl to
713 // call smartUrlFilter in addition may have unwanted
714 // consequences, and is deferred for now.
715 int colon = inUrl.indexOf(':');
716 boolean allLower = true;
717 for (int index = 0; index < colon; index++) {
718 char ch = inUrl.charAt(index);
719 if (!Character.isLetter(ch)) {
722 allLower &= Character.isLowerCase(ch);
723 if (index == colon - 1 && !allLower) {
724 inUrl = inUrl.substring(0, colon).toLowerCase()
725 + inUrl.substring(colon);
728 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
730 if (inUrl.startsWith("http:") ||
731 inUrl.startsWith("https:")) {
732 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
733 inUrl = inUrl.replaceFirst("/", "//");
734 } else inUrl = inUrl.replaceFirst(":", "://");
740 * Looking for the pattern like this
749 private final SensorListener mSensorListener = new SensorListener() {
750 private long mLastGestureTime;
751 private float[] mPrev = new float[3];
752 private float[] mPrevDiff = new float[3];
753 private float[] mDiff = new float[3];
754 private float[] mRevertDiff = new float[3];
756 public void onSensorChanged(int sensor, float[] values) {
757 boolean show = false;
758 float[] diff = new float[3];
760 for (int i = 0; i < 3; i++) {
761 diff[i] = values[i] - mPrev[i];
762 if (Math.abs(diff[i]) > 1) {
765 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
766 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
767 // start track when there is a big move, or revert
768 mRevertDiff[i] = mDiff[i];
770 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
771 // reset when it is flat
772 mDiff[i] = mRevertDiff[i] = 0;
775 mPrevDiff[i] = diff[i];
776 mPrev[i] = values[i];
780 // only shows if we think the delta is big enough, in an attempt
781 // to detect "serious" moves left/right or up/down
782 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
783 + values[0] + ", " + values[1] + ", " + values[2] + ")"
784 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
786 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
787 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
788 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
789 + mRevertDiff[2] + ")");
792 long now = android.os.SystemClock.uptimeMillis();
793 if (now - mLastGestureTime > 1000) {
794 mLastGestureTime = 0;
798 float ay = Math.abs(y);
799 float az = Math.abs(z);
800 float ry = mRevertDiff[1];
801 float rz = mRevertDiff[2];
802 float ary = Math.abs(ry);
803 float arz = Math.abs(rz);
804 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
805 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
807 if ((gestY || gestZ) && !(gestY && gestZ)) {
808 WebView view = mTabControl.getCurrentWebView();
818 view.flingScroll(0, Math.round(y * 100));
821 mLastGestureTime = now;
826 public void onAccuracyChanged(int sensor, int accuracy) {
827 // TODO Auto-generated method stub
832 @Override protected void onResume() {
835 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
838 if (!mActivityInPause) {
839 Log.e(LOGTAG, "BrowserActivity is already resumed.");
843 mTabControl.resumeCurrentTab();
844 mActivityInPause = false;
845 resumeWebViewTimers();
847 if (mWakeLock.isHeld()) {
848 mHandler.removeMessages(RELEASE_WAKELOCK);
852 if (mCredsDlg != null) {
853 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
854 // In case credential request never comes back
855 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
859 registerReceiver(mNetworkStateIntentReceiver,
860 mNetworkStateChangedFilter);
861 WebView.enablePlatformNotifications();
863 if (mSettings.doFlick()) {
864 if (mSensorManager == null) {
865 mSensorManager = (SensorManager) getSystemService(
866 Context.SENSOR_SERVICE);
868 mSensorManager.registerListener(mSensorListener,
869 SensorManager.SENSOR_ACCELEROMETER,
870 SensorManager.SENSOR_DELAY_FASTEST);
872 mSensorManager = null;
877 * Since the actual title bar is embedded in the WebView, and removing it
878 * would change its appearance, create a temporary title bar to go at
879 * the top of the screen while the menu is open.
881 private TitleBar mFakeTitleBar;
884 * Holder for the fake title bar. It will have a foreground shadow, as well
885 * as a white background, so the fake title bar looks like the real one.
887 private ViewGroup mFakeTitleBarHolder;
890 * Layout parameters for the fake title bar within mFakeTitleBarHolder
892 private FrameLayout.LayoutParams mFakeTitleBarParams
893 = new FrameLayout.LayoutParams(
894 ViewGroup.LayoutParams.FILL_PARENT,
895 ViewGroup.LayoutParams.WRAP_CONTENT);
897 * Keeps track of whether the options menu is open. This is important in
898 * determining whether to show or hide the title bar overlay.
900 private boolean mOptionsMenuOpen;
903 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
904 * of whether the configuration has changed. The first onMenuOpened call
905 * after a configuration change is simply a reopening of the same menu
906 * (i.e. mIconView did not change).
908 private boolean mConfigChanged;
911 * Whether or not the options menu is in its smaller, icon menu form. When
912 * true, we want the title bar overlay to be up. When false, we do not.
913 * Only meaningful if mOptionsMenuOpen is true.
915 private boolean mIconView;
918 public boolean onMenuOpened(int featureId, Menu menu) {
919 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
920 if (mOptionsMenuOpen) {
921 if (mConfigChanged) {
922 // We do not need to make any changes to the state of the
923 // title bar, since the only thing that happened was a
924 // change in orientation
925 mConfigChanged = false;
928 // Switching the menu to expanded view, so hide the
933 // Switching the menu back to icon view, so show the
934 // title bar once again.
940 // The options menu is closed, so open it, and show the title
942 mOptionsMenuOpen = true;
943 mConfigChanged = false;
950 private void showFakeTitleBar() {
951 if (mFakeTitleBar == null && mActiveTabsPage == null
952 && !mActivityInPause) {
953 final WebView webView = getTopWindow();
954 mFakeTitleBar = new TitleBar(this);
955 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
956 mFakeTitleBar.setProgress(webView.getProgress());
957 mFakeTitleBar.setFavicon(webView.getFavicon());
958 updateLockIconToLatest();
960 WindowManager manager
961 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
963 // Add the title bar to the window manager so it can receive touches
964 // while the menu is up
965 WindowManager.LayoutParams params
966 = new WindowManager.LayoutParams(
967 ViewGroup.LayoutParams.FILL_PARENT,
968 ViewGroup.LayoutParams.WRAP_CONTENT,
969 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
970 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
972 params.gravity = Gravity.TOP;
973 WebView mainView = mTabControl.getCurrentWebView();
974 params.windowAnimations = mainView == null
975 || mainView.getScrollY() != 0
976 ? com.android.internal.R.style.Animation_DropDownDown : 0;
977 // XXX : Without providing an offset, the fake title bar will be
978 // placed underneath the status bar. Use the global visible rect
979 // of mBrowserFrameLayout to determine the bottom of the status bar
980 Rect rectangle = new Rect();
981 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
982 params.y = rectangle.top;
983 // Add a holder for the title bar. It is a FrameLayout, which
984 // allows it to have an overlay shadow. It also has a white
985 // background, which is the same as the background when it is
986 // placed in a WebView.
987 if (mFakeTitleBarHolder == null) {
988 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
989 .inflate(R.layout.title_bar_bg, null);
991 mFakeTitleBarHolder.addView(mFakeTitleBar, mFakeTitleBarParams);
992 manager.addView(mFakeTitleBarHolder, params);
997 public void onOptionsMenuClosed(Menu menu) {
998 mOptionsMenuOpen = false;
1001 } else if (!mIconView) {
1002 // The page is currently loading, and we are in expanded mode, so
1003 // we were not showing the menu. Show it once again. It will be
1004 // removed when the page finishes.
1008 private void hideFakeTitleBar() {
1009 if (mFakeTitleBar == null) return;
1010 WindowManager manager
1011 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1012 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1013 manager.removeView(mFakeTitleBarHolder);
1014 mFakeTitleBar = null;
1018 * onSaveInstanceState(Bundle map)
1019 * onSaveInstanceState is called right before onStop(). The map contains
1022 @Override protected void onSaveInstanceState(Bundle outState) {
1024 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1026 // the default implementation requires each view to have an id. As the
1027 // browser handles the state itself and it doesn't use id for the views,
1028 // don't call the default implementation. Otherwise it will trigger the
1029 // warning like this, "couldn't save which view has focus because the
1030 // focused view XXX has no id".
1032 // Save all the tabs
1033 mTabControl.saveState(outState);
1036 @Override protected void onPause() {
1039 if (mActivityInPause) {
1040 Log.e(LOGTAG, "BrowserActivity is already paused.");
1044 mTabControl.pauseCurrentTab();
1045 mActivityInPause = true;
1046 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1047 mWakeLock.acquire();
1048 mHandler.sendMessageDelayed(mHandler
1049 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1052 // Clear the credentials toast if it is up
1053 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1054 mCredsDlg.dismiss();
1058 // FIXME: This removes the active tabs page and resets the menu to
1059 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1060 // but then we would need to save it in onSaveInstanceState and restore
1061 // it in onCreate/onRestoreInstanceState
1062 if (mActiveTabsPage != null) {
1063 removeActiveTabPage(true);
1068 // unregister network state listener
1069 unregisterReceiver(mNetworkStateIntentReceiver);
1070 WebView.disablePlatformNotifications();
1072 if (mSensorManager != null) {
1073 mSensorManager.unregisterListener(mSensorListener);
1077 @Override protected void onDestroy() {
1079 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1082 // Remove the current tab and sub window
1083 TabControl.Tab t = mTabControl.getCurrentTab();
1085 dismissSubWindow(t);
1086 removeTabFromContentView(t);
1088 // Destroy all the tabs
1089 mTabControl.destroy();
1090 WebIconDatabase.getInstance().close();
1091 if (mGlsConnection != null) {
1092 unbindService(mGlsConnection);
1093 mGlsConnection = null;
1097 // stop MASF proxy service
1099 //Intent proxyServiceIntent = new Intent();
1100 //proxyServiceIntent.setComponent
1101 // (new ComponentName(
1102 // "com.android.masfproxyservice",
1103 // "com.android.masfproxyservice.MasfProxyService"));
1104 //stopService(proxyServiceIntent);
1106 unregisterReceiver(mPackageInstallationReceiver);
1110 public void onConfigurationChanged(Configuration newConfig) {
1111 mConfigChanged = true;
1112 super.onConfigurationChanged(newConfig);
1114 if (mPageInfoDialog != null) {
1115 mPageInfoDialog.dismiss();
1118 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1120 if (mSSLCertificateDialog != null) {
1121 mSSLCertificateDialog.dismiss();
1123 mSSLCertificateView);
1125 if (mSSLCertificateOnErrorDialog != null) {
1126 mSSLCertificateOnErrorDialog.dismiss();
1127 showSSLCertificateOnError(
1128 mSSLCertificateOnErrorView,
1129 mSSLCertificateOnErrorHandler,
1130 mSSLCertificateOnErrorError);
1132 if (mHttpAuthenticationDialog != null) {
1133 String title = ((TextView) mHttpAuthenticationDialog
1134 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1136 String name = ((TextView) mHttpAuthenticationDialog
1137 .findViewById(R.id.username_edit)).getText().toString();
1138 String password = ((TextView) mHttpAuthenticationDialog
1139 .findViewById(R.id.password_edit)).getText().toString();
1140 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1142 mHttpAuthenticationDialog.dismiss();
1143 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1144 name, password, focusId);
1146 if (mFindDialog != null && mFindDialog.isShowing()) {
1147 mFindDialog.onConfigurationChanged(newConfig);
1151 @Override public void onLowMemory() {
1152 super.onLowMemory();
1153 mTabControl.freeMemory();
1156 private boolean resumeWebViewTimers() {
1157 if ((!mActivityInPause && !mPageStarted) ||
1158 (mActivityInPause && mPageStarted)) {
1159 CookieSyncManager.getInstance().startSync();
1160 WebView w = mTabControl.getCurrentWebView();
1170 private boolean pauseWebViewTimers() {
1171 if (mActivityInPause && !mPageStarted) {
1172 CookieSyncManager.getInstance().stopSync();
1173 WebView w = mTabControl.getCurrentWebView();
1183 // FIXME: Do we want to call this when loading google for the first time?
1185 * This function is called when we are launching for the first time. We
1186 * are waiting for the login credentials before loading Google home
1187 * pages. This way the user will be logged in straight away.
1189 private void waitForCredentials() {
1191 mCredsDlg = new ProgressDialog(this);
1192 mCredsDlg.setIndeterminate(true);
1193 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1194 // If the user cancels the operation, then cancel the Google
1195 // Credentials request.
1196 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1199 // We set a timeout for the retrieval of credentials in onResume()
1200 // as that is when we have freed up some CPU time to get
1201 // the login credentials.
1205 * If we have received the credentials or we have timed out and we are
1206 * showing the credentials dialog, then it is time to move on.
1208 private void resumeAfterCredentials() {
1209 if (mCredsDlg == null) {
1214 if (mCredsDlg.isShowing()) {
1215 mCredsDlg.dismiss();
1219 // Clear any pending timeout
1220 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1223 WebView w = mTabControl.getCurrentWebView();
1225 w.loadUrl(mSettings.getHomePage());
1228 // Update the settings, need to do this last as it can take a moment
1229 // to persist the settings. In the mean time we could be loading
1231 mSettings.setLoginInitialized(this);
1234 // Open the icon database and retain all the icons for visited sites.
1235 private void retainIconsOnStartup() {
1236 final WebIconDatabase db = WebIconDatabase.getInstance();
1237 db.open(getDir("icons", 0).getPath());
1239 Cursor c = Browser.getAllBookmarks(mResolver);
1240 if (!c.moveToFirst()) {
1244 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1246 String url = c.getString(urlIndex);
1247 db.retainIconForPageUrl(url);
1248 } while (c.moveToNext());
1250 } catch (IllegalStateException e) {
1251 Log.e(LOGTAG, "retainIconsOnStartup", e);
1255 // Helper method for getting the top window.
1256 WebView getTopWindow() {
1257 return mTabControl.getCurrentTopWebView();
1261 public boolean onCreateOptionsMenu(Menu menu) {
1262 super.onCreateOptionsMenu(menu);
1264 MenuInflater inflater = getMenuInflater();
1265 inflater.inflate(R.menu.browser, menu);
1267 updateInLoadMenuItems();
1272 * As the menu can be open when loading state changes
1273 * we must manually update the state of the stop/reload menu
1276 private void updateInLoadMenuItems() {
1277 if (mMenu == null) {
1280 MenuItem src = mInLoad ?
1281 mMenu.findItem(R.id.stop_menu_id):
1282 mMenu.findItem(R.id.reload_menu_id);
1283 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1284 dest.setIcon(src.getIcon());
1285 dest.setTitle(src.getTitle());
1289 public boolean onContextItemSelected(MenuItem item) {
1290 // chording is not an issue with context menus, but we use the same
1291 // options selector, so set mCanChord to true so we can access them.
1293 int id = item.getItemId();
1294 final WebView webView = getTopWindow();
1295 if (null == webView) {
1298 final HashMap hrefMap = new HashMap();
1299 hrefMap.put("webview", webView);
1300 final Message msg = mHandler.obtainMessage(
1301 FOCUS_NODE_HREF, id, 0, hrefMap);
1303 // -- Browser context menu
1304 case R.id.open_context_menu_id:
1305 case R.id.open_newtab_context_menu_id:
1306 case R.id.bookmark_context_menu_id:
1307 case R.id.save_link_context_menu_id:
1308 case R.id.share_link_context_menu_id:
1309 case R.id.copy_link_context_menu_id:
1310 webView.requestFocusNodeHref(msg);
1314 // For other context menus
1315 return onOptionsItemSelected(item);
1321 private Bundle createGoogleSearchSourceBundle(String source) {
1322 Bundle bundle = new Bundle();
1323 bundle.putString(SearchManager.SOURCE, source);
1328 * Overriding this to insert a local information bundle
1331 public boolean onSearchRequested() {
1332 if (mOptionsMenuOpen) closeOptionsMenu();
1333 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1334 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1335 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1340 public void startSearch(String initialQuery, boolean selectInitialQuery,
1341 Bundle appSearchData, boolean globalSearch) {
1342 if (appSearchData == null) {
1343 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1345 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1349 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1350 * results in changing tabs.
1351 * @param index Index of the tab to change to, as defined by
1352 * mTabControl.getTabIndex(Tab t).
1353 * @return boolean True if we successfully switched to a different tab. If
1354 * the indexth tab is null, or if that tab is the same as
1355 * the current one, return false.
1357 /* package */ boolean switchToTab(int index) {
1358 TabControl.Tab tab = mTabControl.getTab(index);
1359 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1360 if (tab == null || tab == currentTab) {
1363 if (currentTab != null) {
1364 // currentTab may be null if it was just removed. In that case,
1365 // we do not need to remove it
1366 removeTabFromContentView(currentTab);
1368 mTabControl.setCurrentTab(tab);
1369 attachTabToContentView(tab);
1370 resetTitleIconAndProgress();
1371 updateLockIconToLatest();
1375 /* package */ TabControl.Tab openTabToHomePage() {
1376 return openTabAndShow(mSettings.getHomePage(), false, null);
1379 /* package */ void closeCurrentWindow() {
1380 final TabControl.Tab current = mTabControl.getCurrentTab();
1381 if (mTabControl.getTabCount() == 1) {
1382 // This is the last tab. Open a new one, with the home
1383 // page and close the current one.
1384 TabControl.Tab newTab = openTabToHomePage();
1388 final TabControl.Tab parent = current.getParentTab();
1389 int indexToShow = -1;
1390 if (parent != null) {
1391 indexToShow = mTabControl.getTabIndex(parent);
1393 final int currentIndex = mTabControl.getCurrentIndex();
1394 // Try to move to the tab to the right
1395 indexToShow = currentIndex + 1;
1396 if (indexToShow > mTabControl.getTabCount() - 1) {
1397 // Try to move to the tab to the left
1398 indexToShow = currentIndex - 1;
1401 if (switchToTab(indexToShow)) {
1407 private ActiveTabsPage mActiveTabsPage;
1410 * Remove the active tabs page.
1411 * @param needToAttach If true, the active tabs page did not attach a tab
1412 * to the content view, so we need to do that here.
1414 /* package */ void removeActiveTabPage(boolean needToAttach) {
1415 mContentView.removeView(mActiveTabsPage);
1416 mActiveTabsPage = null;
1417 mMenuState = R.id.MAIN_MENU;
1419 attachTabToContentView(mTabControl.getCurrentTab());
1421 getTopWindow().requestFocus();
1425 public boolean onOptionsItemSelected(MenuItem item) {
1427 // The user has already fired a shortcut with this hold down of the
1431 if (null == getTopWindow()) {
1435 // The shortcut action consumes the MENU. Even if it is still down,
1436 // it won't trigger the next shortcut action. In the case of the
1437 // shortcut action triggering a new activity, like Bookmarks, we
1438 // won't get onKeyUp for MENU. So it is important to reset it here.
1439 mMenuIsDown = false;
1441 switch (item.getItemId()) {
1443 case R.id.new_tab_menu_id:
1444 openTabToHomePage();
1447 case R.id.goto_menu_id:
1448 bookmarksOrHistoryPicker(false);
1451 case R.id.active_tabs_menu_id:
1452 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1453 removeTabFromContentView(mTabControl.getCurrentTab());
1455 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1456 mActiveTabsPage.requestFocus();
1457 mMenuState = EMPTY_MENU;
1460 case R.id.add_bookmark_menu_id:
1461 Intent i = new Intent(BrowserActivity.this,
1462 AddBookmarkPage.class);
1463 WebView w = getTopWindow();
1464 i.putExtra("url", w.getUrl());
1465 i.putExtra("title", w.getTitle());
1466 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1470 case R.id.stop_reload_menu_id:
1474 getTopWindow().reload();
1478 case R.id.back_menu_id:
1479 getTopWindow().goBack();
1482 case R.id.forward_menu_id:
1483 getTopWindow().goForward();
1486 case R.id.close_menu_id:
1487 // Close the subwindow if it exists.
1488 if (mTabControl.getCurrentSubWindow() != null) {
1489 dismissSubWindow(mTabControl.getCurrentTab());
1492 closeCurrentWindow();
1495 case R.id.homepage_menu_id:
1496 TabControl.Tab current = mTabControl.getCurrentTab();
1497 if (current != null) {
1498 dismissSubWindow(current);
1499 current.getWebView().loadUrl(mSettings.getHomePage());
1503 case R.id.preferences_menu_id:
1504 Intent intent = new Intent(this,
1505 BrowserPreferencesPage.class);
1506 startActivityForResult(intent, PREFERENCES_PAGE);
1509 case R.id.find_menu_id:
1510 if (null == mFindDialog) {
1511 mFindDialog = new FindDialog(this);
1513 mFindDialog.setWebView(getTopWindow());
1515 mMenuState = EMPTY_MENU;
1518 case R.id.select_text_id:
1519 getTopWindow().emulateShiftHeld();
1521 case R.id.page_info_menu_id:
1522 showPageInfo(mTabControl.getCurrentTab(), false);
1525 case R.id.classic_history_menu_id:
1526 bookmarksOrHistoryPicker(true);
1529 case R.id.share_page_menu_id:
1530 Browser.sendString(this, getTopWindow().getUrl());
1533 case R.id.dump_nav_menu_id:
1534 getTopWindow().debugDump();
1537 case R.id.zoom_in_menu_id:
1538 getTopWindow().zoomIn();
1541 case R.id.zoom_out_menu_id:
1542 getTopWindow().zoomOut();
1545 case R.id.view_downloads_menu_id:
1546 viewDownloads(null);
1549 case R.id.window_one_menu_id:
1550 case R.id.window_two_menu_id:
1551 case R.id.window_three_menu_id:
1552 case R.id.window_four_menu_id:
1553 case R.id.window_five_menu_id:
1554 case R.id.window_six_menu_id:
1555 case R.id.window_seven_menu_id:
1556 case R.id.window_eight_menu_id:
1558 int menuid = item.getItemId();
1559 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1560 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1561 TabControl.Tab desiredTab = mTabControl.getTab(id);
1562 if (desiredTab != null &&
1563 desiredTab != mTabControl.getCurrentTab()) {
1573 if (!super.onOptionsItemSelected(item)) {
1576 // Otherwise fall through.
1582 public void closeFind() {
1583 mMenuState = R.id.MAIN_MENU;
1586 @Override public boolean onPrepareOptionsMenu(Menu menu)
1588 // This happens when the user begins to hold down the menu key, so
1589 // allow them to chord to get a shortcut.
1591 // Note: setVisible will decide whether an item is visible; while
1592 // setEnabled() will decide whether an item is enabled, which also means
1593 // whether the matching shortcut key will function.
1594 super.onPrepareOptionsMenu(menu);
1595 switch (mMenuState) {
1597 if (mCurrentMenuState != mMenuState) {
1598 menu.setGroupVisible(R.id.MAIN_MENU, false);
1599 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1600 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1604 if (mCurrentMenuState != mMenuState) {
1605 menu.setGroupVisible(R.id.MAIN_MENU, true);
1606 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1607 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1609 final WebView w = getTopWindow();
1610 boolean canGoBack = false;
1611 boolean canGoForward = false;
1612 boolean isHome = false;
1614 canGoBack = w.canGoBack();
1615 canGoForward = w.canGoForward();
1616 isHome = mSettings.getHomePage().equals(w.getUrl());
1618 final MenuItem back = menu.findItem(R.id.back_menu_id);
1619 back.setEnabled(canGoBack);
1621 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1622 home.setEnabled(!isHome);
1624 menu.findItem(R.id.forward_menu_id)
1625 .setEnabled(canGoForward);
1627 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1628 mTabControl.getTabCount() < TabControl.MAX_TABS);
1630 // decide whether to show the share link option
1631 PackageManager pm = getPackageManager();
1632 Intent send = new Intent(Intent.ACTION_SEND);
1633 send.setType("text/plain");
1634 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1635 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1637 boolean isNavDump = mSettings.isNavDump();
1638 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1639 nav.setVisible(isNavDump);
1640 nav.setEnabled(isNavDump);
1643 mCurrentMenuState = mMenuState;
1648 public void onCreateContextMenu(ContextMenu menu, View v,
1649 ContextMenuInfo menuInfo) {
1650 WebView webview = (WebView) v;
1651 WebView.HitTestResult result = webview.getHitTestResult();
1652 if (result == null) {
1656 int type = result.getType();
1657 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1659 "We should not show context menu when nothing is touched");
1662 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1663 // let TextView handles context menu
1667 // Note, http://b/issue?id=1106666 is requesting that
1668 // an inflated menu can be used again. This is not available
1669 // yet, so inflate each time (yuk!)
1670 MenuInflater inflater = getMenuInflater();
1671 inflater.inflate(R.menu.browsercontext, menu);
1673 // Show the correct menu group
1674 String extra = result.getExtra();
1675 menu.setGroupVisible(R.id.PHONE_MENU,
1676 type == WebView.HitTestResult.PHONE_TYPE);
1677 menu.setGroupVisible(R.id.EMAIL_MENU,
1678 type == WebView.HitTestResult.EMAIL_TYPE);
1679 menu.setGroupVisible(R.id.GEO_MENU,
1680 type == WebView.HitTestResult.GEO_TYPE);
1681 menu.setGroupVisible(R.id.IMAGE_MENU,
1682 type == WebView.HitTestResult.IMAGE_TYPE
1683 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1684 menu.setGroupVisible(R.id.ANCHOR_MENU,
1685 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1686 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1688 // Setup custom handling depending on the type
1690 case WebView.HitTestResult.PHONE_TYPE:
1691 menu.setHeaderTitle(Uri.decode(extra));
1692 menu.findItem(R.id.dial_context_menu_id).setIntent(
1693 new Intent(Intent.ACTION_VIEW, Uri
1694 .parse(WebView.SCHEME_TEL + extra)));
1695 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1696 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1697 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1698 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1700 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1704 case WebView.HitTestResult.EMAIL_TYPE:
1705 menu.setHeaderTitle(extra);
1706 menu.findItem(R.id.email_context_menu_id).setIntent(
1707 new Intent(Intent.ACTION_VIEW, Uri
1708 .parse(WebView.SCHEME_MAILTO + extra)));
1709 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1713 case WebView.HitTestResult.GEO_TYPE:
1714 menu.setHeaderTitle(extra);
1715 menu.findItem(R.id.map_context_menu_id).setIntent(
1716 new Intent(Intent.ACTION_VIEW, Uri
1717 .parse(WebView.SCHEME_GEO
1718 + URLEncoder.encode(extra))));
1719 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1723 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1724 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1725 TextView titleView = (TextView) LayoutInflater.from(this)
1726 .inflate(android.R.layout.browser_link_context_header,
1728 titleView.setText(extra);
1729 menu.setHeaderView(titleView);
1730 // decide whether to show the open link in new tab option
1731 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1732 mTabControl.getTabCount() < TabControl.MAX_TABS);
1733 PackageManager pm = getPackageManager();
1734 Intent send = new Intent(Intent.ACTION_SEND);
1735 send.setType("text/plain");
1736 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1737 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1738 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1741 // otherwise fall through to handle image part
1742 case WebView.HitTestResult.IMAGE_TYPE:
1743 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1744 menu.setHeaderTitle(extra);
1746 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1747 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1748 menu.findItem(R.id.download_context_menu_id).
1749 setOnMenuItemClickListener(new Download(extra));
1753 Log.w(LOGTAG, "We should not get here.");
1758 // Attach the given tab to the content view.
1759 private void attachTabToContentView(TabControl.Tab t) {
1760 // Attach the container that contains the main WebView and any other UI
1761 // associated with the tab.
1762 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
1764 if (mShouldShowErrorConsole) {
1765 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1766 if (errorConsole.numberOfErrors() == 0) {
1767 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1769 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1772 mErrorConsoleContainer.addView(errorConsole,
1773 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1774 ViewGroup.LayoutParams.WRAP_CONTENT));
1777 if (t == mTabControl.getCurrentTab()) {
1778 setLockIconType(t.getLockIconType());
1779 setPrevLockType(t.getPrevLockIconType());
1782 WebView view = t.getWebView();
1783 view.setEmbeddedTitleBar(mTitleBar);
1784 // Attach the sub window if necessary
1786 // Request focus on the top window.
1787 t.getTopWindow().requestFocus();
1790 // Attach a sub window to the main WebView of the given tab.
1791 private void attachSubWindow(TabControl.Tab t) {
1792 // If a sub window exists, attach it to the content view.
1793 final WebView subView = t.getSubWebView();
1794 if (subView != null) {
1795 final View container = t.getSubWebViewContainer();
1796 mContentView.addView(container, COVER_SCREEN_PARAMS);
1797 subView.requestFocus();
1801 // Remove the given tab from the content view.
1802 private void removeTabFromContentView(TabControl.Tab t) {
1803 // Remove the container that contains the main WebView.
1804 mContentView.removeView(t.getContainer());
1806 if (mTabControl.getCurrentErrorConsole(false) != null) {
1807 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1810 WebView view = t.getWebView();
1812 view.setEmbeddedTitleBar(null);
1815 // Remove the sub window if it exists.
1816 if (t.getSubWebView() != null) {
1817 mContentView.removeView(t.getSubWebViewContainer());
1820 if (t == mTabControl.getCurrentTab()) {
1821 t.setLockIconType(getLockIconType());
1822 t.setPrevLockIconType(getPrevLockType());
1826 // Remove the sub window if it exists. Also called by TabControl when the
1827 // user clicks the 'X' to dismiss a sub window.
1828 /* package */ void dismissSubWindow(TabControl.Tab t) {
1829 final WebView mainView = t.getWebView();
1830 if (t.getSubWebView() != null) {
1831 // Remove the container view and request focus on the main WebView.
1832 mContentView.removeView(t.getSubWebViewContainer());
1833 mainView.requestFocus();
1834 // Tell the TabControl to dismiss the subwindow. This will destroy
1836 mTabControl.dismissSubWindow(t);
1840 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1841 // that accepts url as string.
1842 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1844 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1847 // This method does a ton of stuff. It will attempt to create a new tab
1848 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1849 // url isn't null, it will load the given url.
1850 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
1851 boolean closeOnExit, String appId) {
1852 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1853 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1855 final TabControl.Tab tab = mTabControl.createNewTab(
1856 closeOnExit, appId, urlData.mUrl);
1857 WebView webview = tab.getWebView();
1858 // If the last tab was removed from the active tabs page, currentTab
1860 if (currentTab != null) {
1861 removeTabFromContentView(currentTab);
1863 // We must set the new tab as the current tab to reflect the old
1864 // animation behavior.
1865 mTabControl.setCurrentTab(tab);
1866 attachTabToContentView(tab);
1867 if (!urlData.isEmpty()) {
1868 urlData.loadIn(webview);
1872 // Get rid of the subwindow if it exists
1873 dismissSubWindow(currentTab);
1874 if (!urlData.isEmpty()) {
1875 // Load the given url.
1876 urlData.loadIn(currentTab.getWebView());
1882 private TabControl.Tab openTab(String url) {
1883 if (mSettings.openInBackground()) {
1884 TabControl.Tab t = mTabControl.createNewTab();
1886 WebView view = t.getWebView();
1891 return openTabAndShow(url, false, null);
1895 private class Copy implements OnMenuItemClickListener {
1896 private CharSequence mText;
1898 public boolean onMenuItemClick(MenuItem item) {
1903 public Copy(CharSequence toCopy) {
1908 private class Download implements OnMenuItemClickListener {
1909 private String mText;
1911 public boolean onMenuItemClick(MenuItem item) {
1912 onDownloadStartNoStream(mText, null, null, null, -1);
1916 public Download(String toDownload) {
1921 private void copy(CharSequence text) {
1923 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1925 clip.setClipboardText(text);
1927 } catch (android.os.RemoteException e) {
1928 Log.e(LOGTAG, "Copy failed", e);
1933 * Resets the browser title-view to whatever it must be
1934 * (for example, if we had a loading error)
1935 * When we have a new page, we call resetTitle, when we
1936 * have to reset the titlebar to whatever it used to be
1937 * (for example, if the user chose to stop loading), we
1938 * call resetTitleAndRevertLockIcon.
1940 /* package */ void resetTitleAndRevertLockIcon() {
1942 resetTitleIconAndProgress();
1946 * Reset the title, favicon, and progress.
1948 private void resetTitleIconAndProgress() {
1949 WebView current = mTabControl.getCurrentWebView();
1950 if (current == null) {
1953 resetTitleAndIcon(current);
1954 int progress = current.getProgress();
1955 mWebChromeClient.onProgressChanged(current, progress);
1958 // Reset the title and the icon based on the given item.
1959 private void resetTitleAndIcon(WebView view) {
1960 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1962 setUrlTitle(item.getUrl(), item.getTitle());
1963 setFavicon(item.getFavicon());
1965 setUrlTitle(null, null);
1971 * Sets a title composed of the URL and the title string.
1972 * @param url The URL of the site being loaded.
1973 * @param title The title of the site being loaded.
1975 private void setUrlTitle(String url, String title) {
1979 mTitleBar.setTitleAndUrl(title, url);
1980 if (mFakeTitleBar != null) {
1981 mFakeTitleBar.setTitleAndUrl(title, url);
1986 * @param url The URL to build a title version of the URL from.
1987 * @return The title version of the URL or null if fails.
1988 * The title version of the URL can be either the URL hostname,
1989 * or the hostname with an "https://" prefix (for secure URLs),
1990 * or an empty string if, for example, the URL in question is a
1991 * file:// URL with no hostname.
1993 /* package */ static String buildTitleUrl(String url) {
1994 String titleUrl = null;
1998 // parse the url string
1999 URL urlObj = new URL(url);
2000 if (urlObj != null) {
2003 String protocol = urlObj.getProtocol();
2004 String host = urlObj.getHost();
2006 if (host != null && 0 < host.length()) {
2008 if (protocol != null) {
2009 // if a secure site, add an "https://" prefix!
2010 if (protocol.equalsIgnoreCase("https")) {
2011 titleUrl = protocol + "://" + host;
2016 } catch (MalformedURLException e) {}
2022 // Set the favicon in the title bar.
2023 private void setFavicon(Bitmap icon) {
2024 mTitleBar.setFavicon(icon);
2025 if (mFakeTitleBar != null) {
2026 mFakeTitleBar.setFavicon(icon);
2031 * Saves the current lock-icon state before resetting
2032 * the lock icon. If we have an error, we may need to
2033 * roll back to the previous state.
2035 private void saveLockIcon() {
2036 mPrevLockType = mLockIconType;
2040 * Reverts the lock-icon state to the last saved state,
2041 * for example, if we had an error, and need to cancel
2044 private void revertLockIcon() {
2045 mLockIconType = mPrevLockType;
2048 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2049 " revert lock icon to " + mLockIconType);
2052 updateLockIconToLatest();
2056 * Close the tab, remove its associated title bar, and adjust mTabControl's
2057 * current tab to a valid value.
2059 /* package */ void closeTab(TabControl.Tab t) {
2060 int currentIndex = mTabControl.getCurrentIndex();
2061 int removeIndex = mTabControl.getTabIndex(t);
2062 mTabControl.removeTab(t);
2063 if (currentIndex >= removeIndex && currentIndex != 0) {
2066 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2069 private void goBackOnePageOrQuit() {
2070 TabControl.Tab current = mTabControl.getCurrentTab();
2071 if (current == null) {
2073 * Instead of finishing the activity, simply push this to the back
2074 * of the stack and let ActivityManager to choose the foreground
2075 * activity. As BrowserActivity is singleTask, it will be always the
2076 * root of the task. So we can use either true or false for
2079 moveTaskToBack(true);
2081 WebView w = current.getWebView();
2082 if (w.canGoBack()) {
2085 // Check to see if we are closing a window that was created by
2086 // another window. If so, we switch back to that window.
2087 TabControl.Tab parent = current.getParentTab();
2088 if (parent != null) {
2089 switchToTab(mTabControl.getTabIndex(parent));
2090 // Now we close the other tab
2093 if (current.closeOnExit()) {
2094 // force mPageStarted to be false as we are going to either
2095 // finish the activity or remove the tab. This will ensure
2096 // pauseWebView() taking action.
2097 mPageStarted = false;
2098 if (mTabControl.getTabCount() == 1) {
2102 // call pauseWebViewTimers() now, we won't be able to call
2103 // it in onPause() as the WebView won't be valid.
2104 // Temporarily change mActivityInPause to be true as
2105 // pauseWebViewTimers() will do nothing if mActivityInPause
2107 boolean savedState = mActivityInPause;
2109 Log.e(LOGTAG, "BrowserActivity is already paused "
2110 + "while handing goBackOnePageOrQuit.");
2112 mActivityInPause = true;
2113 pauseWebViewTimers();
2114 mActivityInPause = savedState;
2115 removeTabFromContentView(current);
2116 mTabControl.removeTab(current);
2119 * Instead of finishing the activity, simply push this to the back
2120 * of the stack and let ActivityManager to choose the foreground
2121 * activity. As BrowserActivity is singleTask, it will be always the
2122 * root of the task. So we can use either true or false for
2125 moveTaskToBack(true);
2130 public KeyTracker.State onKeyTracker(int keyCode,
2132 KeyTracker.Stage stage,
2134 // if onKeyTracker() is called after activity onStop()
2135 // because of accumulated key events,
2136 // we should ignore it as browser is not active any more.
2137 WebView topWindow = getTopWindow();
2138 if (topWindow == null && mCustomView == null)
2139 return KeyTracker.State.NOT_TRACKING;
2141 if (keyCode == KeyEvent.KEYCODE_BACK) {
2142 // Check if a custom view is currently showing and, if it is, hide it.
2143 if (mCustomView != null) {
2144 mWebChromeClient.onHideCustomView();
2145 return KeyTracker.State.DONE_TRACKING;
2147 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2148 bookmarksOrHistoryPicker(true);
2149 return KeyTracker.State.DONE_TRACKING;
2150 } else if (stage == KeyTracker.Stage.UP) {
2151 // FIXME: Currently, we do not have a notion of the
2152 // history picker for the subwindow, but maybe we
2154 WebView subwindow = mTabControl.getCurrentSubWindow();
2155 if (subwindow != null) {
2156 if (subwindow.canGoBack()) {
2159 dismissSubWindow(mTabControl.getCurrentTab());
2162 goBackOnePageOrQuit();
2164 return KeyTracker.State.DONE_TRACKING;
2166 return KeyTracker.State.KEEP_TRACKING;
2168 return KeyTracker.State.NOT_TRACKING;
2171 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2172 if (keyCode == KeyEvent.KEYCODE_MENU) {
2174 } else if (mMenuIsDown) {
2175 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2176 // still down, we don't want to trigger the search. Pretend to
2177 // consume the key and do nothing.
2180 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2183 case KeyEvent.KEYCODE_SPACE:
2184 if (event.isShiftPressed()) {
2185 getTopWindow().pageUp(false);
2187 getTopWindow().pageDown(false);
2196 return handled || super.onKeyDown(keyCode, event);
2199 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2200 if (keyCode == KeyEvent.KEYCODE_MENU) {
2201 mMenuIsDown = false;
2203 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2206 /* package */ void stopLoading() {
2207 resetTitleAndRevertLockIcon();
2208 WebView w = getTopWindow();
2210 mWebViewClient.onPageFinished(w, w.getUrl());
2214 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2218 private void cancelStopToast() {
2219 if (mStopToast != null) {
2220 mStopToast.cancel();
2225 // called by a non-UI thread to post the message
2226 public void postMessage(int what, int arg1, int arg2, Object obj) {
2227 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2230 // public message ids
2231 public final static int LOAD_URL = 1001;
2232 public final static int STOP_LOAD = 1002;
2235 private static final int FOCUS_NODE_HREF = 102;
2236 private static final int CANCEL_CREDS_REQUEST = 103;
2237 private static final int RELEASE_WAKELOCK = 107;
2239 // Private handler for handling javascript and saving passwords
2240 private Handler mHandler = new Handler() {
2242 public void handleMessage(Message msg) {
2244 case FOCUS_NODE_HREF:
2245 String url = (String) msg.getData().get("url");
2246 if (url == null || url.length() == 0) {
2249 HashMap focusNodeMap = (HashMap) msg.obj;
2250 WebView view = (WebView) focusNodeMap.get("webview");
2251 // Only apply the action if the top window did not change.
2252 if (getTopWindow() != view) {
2256 case R.id.open_context_menu_id:
2257 case R.id.view_image_context_menu_id:
2258 loadURL(getTopWindow(), url);
2260 case R.id.open_newtab_context_menu_id:
2261 final TabControl.Tab parent = mTabControl
2263 final TabControl.Tab newTab = openTab(url);
2264 if (newTab != parent) {
2265 parent.addChildTab(newTab);
2268 case R.id.bookmark_context_menu_id:
2269 Intent intent = new Intent(BrowserActivity.this,
2270 AddBookmarkPage.class);
2271 intent.putExtra("url", url);
2272 startActivity(intent);
2274 case R.id.share_link_context_menu_id:
2275 Browser.sendString(BrowserActivity.this, url);
2277 case R.id.copy_link_context_menu_id:
2280 case R.id.save_link_context_menu_id:
2281 case R.id.download_context_menu_id:
2282 onDownloadStartNoStream(url, null, null, null, -1);
2288 loadURL(getTopWindow(), (String) msg.obj);
2295 case CANCEL_CREDS_REQUEST:
2296 resumeAfterCredentials();
2299 case RELEASE_WAKELOCK:
2300 if (mWakeLock.isHeld()) {
2301 mWakeLock.release();
2308 private void updateScreenshot(WebView view) {
2309 // If this is a bookmarked site, add a screenshot to the database.
2310 // FIXME: When should we update? Every time?
2311 // FIXME: Would like to make sure there is actually something to
2312 // draw, but the API for that (WebViewCore.pictureReady()) is not
2313 // currently accessible here.
2314 ContentResolver cr = getContentResolver();
2315 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2316 cr, view.getOriginalUrl(), view.getUrl(), false);
2318 boolean succeed = c.moveToFirst();
2319 ContentValues values = null;
2321 if (values == null) {
2322 final ByteArrayOutputStream os
2323 = new ByteArrayOutputStream();
2324 Picture thumbnail = view.capturePicture();
2325 // Keep width and height in sync with BrowserBookmarksPage
2326 // and bookmark_thumb
2327 Bitmap bm = Bitmap.createBitmap(100, 80,
2328 Bitmap.Config.ARGB_4444);
2329 Canvas canvas = new Canvas(bm);
2330 // May need to tweak these values to determine what is the
2331 // best scale factor
2332 canvas.scale(.5f, .5f);
2333 thumbnail.draw(canvas);
2334 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2335 values = new ContentValues();
2336 values.put(Browser.BookmarkColumns.THUMBNAIL,
2339 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2340 c.getInt(0)), values, null, null);
2341 succeed = c.moveToNext();
2347 // -------------------------------------------------------------------------
2348 // WebViewClient implementation.
2349 //-------------------------------------------------------------------------
2351 // Use in overrideUrlLoading
2352 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2353 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2354 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2355 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2357 /* package */ WebViewClient getWebViewClient() {
2358 return mWebViewClient;
2361 private void updateIcon(WebView view, Bitmap icon) {
2363 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2369 private final WebViewClient mWebViewClient = new WebViewClient() {
2371 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2373 setUrlTitle(url, null);
2375 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2376 if (errorConsole != null) {
2377 errorConsole.clearErrorMessages();
2378 if (mShouldShowErrorConsole) {
2379 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2383 // Call updateIcon instead of setFavicon so the bookmark
2384 // database can be updated.
2385 updateIcon(view, favicon);
2387 if (mSettings.isTracing()) {
2390 WebAddress uri = new WebAddress(url);
2392 } catch (android.net.ParseException ex) {
2395 host = host.replace('.', '_');
2398 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2401 // Performance probe
2403 mStart = SystemClock.uptimeMillis();
2404 mProcessStart = Process.getElapsedCpuTime();
2405 long[] sysCpu = new long[7];
2406 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2408 mUserStart = sysCpu[0] + sysCpu[1];
2409 mSystemStart = sysCpu[2];
2410 mIdleStart = sysCpu[3];
2411 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2413 mUiStart = SystemClock.currentThreadTimeMillis();
2416 if (!mPageStarted) {
2417 mPageStarted = true;
2418 // if onResume() has been called, resumeWebViewTimers() does
2420 resumeWebViewTimers();
2423 // reset sync timer to avoid sync starts during loading a page
2424 CookieSyncManager.getInstance().resetSync();
2427 WebView currentWebView = mTabControl.getCurrentWebView();
2428 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2429 // This page has begun to load, so show the title bar
2432 updateInLoadMenuItems();
2433 if (!mIsNetworkUp) {
2434 if ( mAlertDialog == null) {
2435 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2436 .setTitle(R.string.loadSuspendedTitle)
2437 .setMessage(R.string.loadSuspended)
2438 .setPositiveButton(R.string.ok, null)
2442 view.setNetworkAvailable(false);
2448 public void onPageFinished(WebView view, String url) {
2449 // Reset the title and icon in case we stopped a provisional
2451 resetTitleAndIcon(view);
2453 // Update the lock icon image only once we are done loading
2454 updateLockIconToLatest();
2455 updateScreenshot(view);
2457 // Performance probe
2459 long[] sysCpu = new long[7];
2460 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2462 String uiInfo = "UI thread used "
2463 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2466 Log.d(LOGTAG, uiInfo);
2468 //The string that gets written to the log
2469 String performanceString = "It took total "
2470 + (SystemClock.uptimeMillis() - mStart)
2471 + " ms clock time to load the page."
2472 + "\nbrowser process used "
2473 + (Process.getElapsedCpuTime() - mProcessStart)
2474 + " ms, user processes used "
2475 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2476 + " ms, kernel used "
2477 + (sysCpu[2] - mSystemStart) * 10
2478 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2479 + " ms and irq took "
2480 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2481 * 10 + " ms, " + uiInfo;
2483 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2486 // strip the url to maintain consistency
2487 String newUrl = new String(url);
2488 if (newUrl.startsWith("http://www.")) {
2489 newUrl = newUrl.substring(11);
2490 } else if (newUrl.startsWith("http://")) {
2491 newUrl = newUrl.substring(7);
2492 } else if (newUrl.startsWith("https://www.")) {
2493 newUrl = newUrl.substring(12);
2494 } else if (newUrl.startsWith("https://")) {
2495 newUrl = newUrl.substring(8);
2498 Log.d(LOGTAG, newUrl + " loaded");
2501 if (sWhiteList.contains(newUrl)) {
2502 // The string that gets pushed to the statistcs
2504 performanceString = performanceString
2508 + android.os.SystemProperties
2509 .get("gsm.sim.operator.alpha");
2510 if (mWebView != null
2511 && mWebView.getContext() != null
2512 && mWebView.getContext().getSystemService(
2513 Context.CONNECTIVITY_SERVICE) != null) {
2514 ConnectivityManager cManager =
2515 (ConnectivityManager) mWebView
2516 .getContext().getSystemService(
2517 Context.CONNECTIVITY_SERVICE);
2518 NetworkInfo nInfo = cManager
2519 .getActiveNetworkInfo();
2520 if (nInfo != null) {
2521 performanceString = performanceString
2522 + "\nNetwork Type: "
2523 + nInfo.getType().toString();
2526 Checkin.logEvent(mResolver,
2527 Checkin.Events.Tag.WEBPAGE_LOAD,
2529 Log.w(LOGTAG, "pushed to the statistics service");
2538 Debug.stopMethodTracing();
2542 mPageStarted = false;
2543 // pauseWebViewTimers() will do nothing and return false if
2544 // onPause() is not called yet.
2545 if (pauseWebViewTimers()) {
2546 if (mWakeLock.isHeld()) {
2547 mHandler.removeMessages(RELEASE_WAKELOCK);
2548 mWakeLock.release();
2554 // return true if want to hijack the url to let another app to handle it
2556 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2557 if (url.startsWith(SCHEME_WTAI)) {
2558 // wtai://wp/mc;number
2559 // number=string(phone-number)
2560 if (url.startsWith(SCHEME_WTAI_MC)) {
2561 Intent intent = new Intent(Intent.ACTION_VIEW,
2562 Uri.parse(WebView.SCHEME_TEL +
2563 url.substring(SCHEME_WTAI_MC.length())));
2564 startActivity(intent);
2567 // wtai://wp/sd;dtmf
2568 // dtmf=string(dialstring)
2569 if (url.startsWith(SCHEME_WTAI_SD)) {
2571 // only send when there is active voice connection
2574 // wtai://wp/ap;number;name
2575 // number=string(phone-number)
2577 if (url.startsWith(SCHEME_WTAI_AP)) {
2583 // The "about:" schemes are internal to the browser; don't
2584 // want these to be dispatched to other apps.
2585 if (url.startsWith("about:")) {
2591 // perform generic parsing of the URI to turn it into an Intent.
2593 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2594 } catch (URISyntaxException ex) {
2595 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2599 // check whether the intent can be resolved. If not, we will see
2600 // whether we can download it from the Market.
2601 if (getPackageManager().resolveActivity(intent, 0) == null) {
2602 String packagename = intent.getPackage();
2603 if (packagename != null) {
2604 intent = new Intent(Intent.ACTION_VIEW, Uri
2605 .parse("market://search?q=pname:" + packagename));
2606 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2607 startActivity(intent);
2614 // sanitize the Intent, ensuring web pages can not bypass browser
2615 // security (only access to BROWSABLE activities).
2616 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2617 intent.setComponent(null);
2619 if (startActivityIfNeeded(intent, -1)) {
2622 } catch (ActivityNotFoundException ex) {
2623 // ignore the error. If no application can handle the URL,
2624 // eg about:blank, assume the browser can handle it.
2637 * Updates the lock icon. This method is called when we discover another
2638 * resource to be loaded for this page (for example, javascript). While
2639 * we update the icon type, we do not update the lock icon itself until
2640 * we are done loading, it is slightly more secure this way.
2643 public void onLoadResource(WebView view, String url) {
2644 if (url != null && url.length() > 0) {
2645 // It is only if the page claims to be secure
2646 // that we may have to update the lock:
2647 if (mLockIconType == LOCK_ICON_SECURE) {
2648 // If NOT a 'safe' url, change the lock to mixed content!
2649 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2650 mLockIconType = LOCK_ICON_MIXED;
2652 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2653 " updated lock icon to " + mLockIconType + " due to " + url);
2661 * Show the dialog, asking the user if they would like to continue after
2662 * an excessive number of HTTP redirects.
2665 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2666 final Message continueMsg) {
2667 new AlertDialog.Builder(BrowserActivity.this)
2668 .setTitle(R.string.browserFrameRedirect)
2669 .setMessage(R.string.browserFrame307Post)
2670 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2671 public void onClick(DialogInterface dialog, int which) {
2672 continueMsg.sendToTarget();
2674 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2675 public void onClick(DialogInterface dialog, int which) {
2676 cancelMsg.sendToTarget();
2678 .setOnCancelListener(new OnCancelListener() {
2679 public void onCancel(DialogInterface dialog) {
2680 cancelMsg.sendToTarget();
2685 // Container class for the next error dialog that needs to be
2688 public final int mTitle;
2689 public final String mDescription;
2690 public final int mError;
2691 ErrorDialog(int title, String desc, int error) {
2693 mDescription = desc;
2698 private void processNextError() {
2699 if (mQueuedErrors == null) {
2702 // The first one is currently displayed so just remove it.
2703 mQueuedErrors.removeFirst();
2704 if (mQueuedErrors.size() == 0) {
2705 mQueuedErrors = null;
2708 showError(mQueuedErrors.getFirst());
2711 private DialogInterface.OnDismissListener mDialogListener =
2712 new DialogInterface.OnDismissListener() {
2713 public void onDismiss(DialogInterface d) {
2717 private LinkedList<ErrorDialog> mQueuedErrors;
2719 private void queueError(int err, String desc) {
2720 if (mQueuedErrors == null) {
2721 mQueuedErrors = new LinkedList<ErrorDialog>();
2723 for (ErrorDialog d : mQueuedErrors) {
2724 if (d.mError == err) {
2725 // Already saw a similar error, ignore the new one.
2729 ErrorDialog errDialog = new ErrorDialog(
2730 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
2731 R.string.browserFrameFileErrorLabel :
2732 R.string.browserFrameNetworkErrorLabel,
2734 mQueuedErrors.addLast(errDialog);
2736 // Show the dialog now if the queue was empty.
2737 if (mQueuedErrors.size() == 1) {
2738 showError(errDialog);
2742 private void showError(ErrorDialog errDialog) {
2743 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2744 .setTitle(errDialog.mTitle)
2745 .setMessage(errDialog.mDescription)
2746 .setPositiveButton(R.string.ok, null)
2748 d.setOnDismissListener(mDialogListener);
2753 * Show a dialog informing the user of the network error reported by
2757 public void onReceivedError(WebView view, int errorCode,
2758 String description, String failingUrl) {
2759 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2760 errorCode != WebViewClient.ERROR_CONNECT &&
2761 errorCode != WebViewClient.ERROR_BAD_URL &&
2762 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2763 errorCode != WebViewClient.ERROR_FILE) {
2764 queueError(errorCode, description);
2766 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2767 + " " + description);
2769 // We need to reset the title after an error.
2770 resetTitleAndRevertLockIcon();
2774 * Check with the user if it is ok to resend POST data as the page they
2775 * are trying to navigate to is the result of a POST.
2778 public void onFormResubmission(WebView view, final Message dontResend,
2779 final Message resend) {
2780 new AlertDialog.Builder(BrowserActivity.this)
2781 .setTitle(R.string.browserFrameFormResubmitLabel)
2782 .setMessage(R.string.browserFrameFormResubmitMessage)
2783 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2784 public void onClick(DialogInterface dialog, int which) {
2785 resend.sendToTarget();
2787 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2788 public void onClick(DialogInterface dialog, int which) {
2789 dontResend.sendToTarget();
2791 .setOnCancelListener(new OnCancelListener() {
2792 public void onCancel(DialogInterface dialog) {
2793 dontResend.sendToTarget();
2799 * Insert the url into the visited history database.
2800 * @param url The url to be inserted.
2801 * @param isReload True if this url is being reloaded.
2802 * FIXME: Not sure what to do when reloading the page.
2805 public void doUpdateVisitedHistory(WebView view, String url,
2807 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2810 // remove "client" before updating it to the history so that it wont
2811 // show up in the auto-complete list.
2812 int index = url.indexOf("client=ms-");
2813 if (index > 0 && url.contains(".google.")) {
2814 int end = url.indexOf('&', index);
2816 url = url.substring(0, index-1).concat(url.substring(end));
2818 url = url.substring(0, index-1);
2821 Browser.updateVisitedHistory(mResolver, url, true);
2822 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2826 * Displays SSL error(s) dialog to the user.
2829 public void onReceivedSslError(
2830 final WebView view, final SslErrorHandler handler, final SslError error) {
2832 if (mSettings.showSecurityWarnings()) {
2833 final LayoutInflater factory =
2834 LayoutInflater.from(BrowserActivity.this);
2835 final View warningsView =
2836 factory.inflate(R.layout.ssl_warnings, null);
2837 final LinearLayout placeholder =
2838 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2840 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2841 LinearLayout ll = (LinearLayout)factory
2842 .inflate(R.layout.ssl_warning, null);
2843 ((TextView)ll.findViewById(R.id.warning))
2844 .setText(R.string.ssl_untrusted);
2845 placeholder.addView(ll);
2848 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2849 LinearLayout ll = (LinearLayout)factory
2850 .inflate(R.layout.ssl_warning, null);
2851 ((TextView)ll.findViewById(R.id.warning))
2852 .setText(R.string.ssl_mismatch);
2853 placeholder.addView(ll);
2856 if (error.hasError(SslError.SSL_EXPIRED)) {
2857 LinearLayout ll = (LinearLayout)factory
2858 .inflate(R.layout.ssl_warning, null);
2859 ((TextView)ll.findViewById(R.id.warning))
2860 .setText(R.string.ssl_expired);
2861 placeholder.addView(ll);
2864 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2865 LinearLayout ll = (LinearLayout)factory
2866 .inflate(R.layout.ssl_warning, null);
2867 ((TextView)ll.findViewById(R.id.warning))
2868 .setText(R.string.ssl_not_yet_valid);
2869 placeholder.addView(ll);
2872 new AlertDialog.Builder(BrowserActivity.this)
2873 .setTitle(R.string.security_warning)
2874 .setIcon(android.R.drawable.ic_dialog_alert)
2875 .setView(warningsView)
2876 .setPositiveButton(R.string.ssl_continue,
2877 new DialogInterface.OnClickListener() {
2878 public void onClick(DialogInterface dialog, int whichButton) {
2882 .setNeutralButton(R.string.view_certificate,
2883 new DialogInterface.OnClickListener() {
2884 public void onClick(DialogInterface dialog, int whichButton) {
2885 showSSLCertificateOnError(view, handler, error);
2888 .setNegativeButton(R.string.cancel,
2889 new DialogInterface.OnClickListener() {
2890 public void onClick(DialogInterface dialog, int whichButton) {
2892 BrowserActivity.this.resetTitleAndRevertLockIcon();
2895 .setOnCancelListener(
2896 new DialogInterface.OnCancelListener() {
2897 public void onCancel(DialogInterface dialog) {
2899 BrowserActivity.this.resetTitleAndRevertLockIcon();
2909 * Handles an HTTP authentication request.
2911 * @param handler The authentication handler
2912 * @param host The host
2913 * @param realm The realm
2916 public void onReceivedHttpAuthRequest(WebView view,
2917 final HttpAuthHandler handler, final String host, final String realm) {
2918 String username = null;
2919 String password = null;
2921 boolean reuseHttpAuthUsernamePassword =
2922 handler.useHttpAuthUsernamePassword();
2924 if (reuseHttpAuthUsernamePassword &&
2925 (mTabControl.getCurrentWebView() != null)) {
2926 String[] credentials =
2927 mTabControl.getCurrentWebView()
2928 .getHttpAuthUsernamePassword(host, realm);
2929 if (credentials != null && credentials.length == 2) {
2930 username = credentials[0];
2931 password = credentials[1];
2935 if (username != null && password != null) {
2936 handler.proceed(username, password);
2938 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2943 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2945 // only check shortcut key when MENU is held
2946 return getWindow().isShortcutKey(event.getKeyCode(), event);
2953 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2954 if (view != mTabControl.getCurrentTopWebView()) {
2957 if (event.isDown()) {
2958 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2960 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2965 //--------------------------------------------------------------------------
2966 // WebChromeClient implementation
2967 //--------------------------------------------------------------------------
2969 /* package */ WebChromeClient getWebChromeClient() {
2970 return mWebChromeClient;
2973 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2974 // Helper method to create a new tab or sub window.
2975 private void createWindow(final boolean dialog, final Message msg) {
2977 mTabControl.createSubWindow();
2978 final TabControl.Tab t = mTabControl.getCurrentTab();
2980 WebView.WebViewTransport transport =
2981 (WebView.WebViewTransport) msg.obj;
2982 transport.setWebView(t.getSubWebView());
2985 final TabControl.Tab parent = mTabControl.getCurrentTab();
2986 final TabControl.Tab newTab
2987 = openTabAndShow(EMPTY_URL_DATA, false, null);
2988 if (newTab != parent) {
2989 parent.addChildTab(newTab);
2991 WebView.WebViewTransport transport =
2992 (WebView.WebViewTransport) msg.obj;
2993 transport.setWebView(mTabControl.getCurrentWebView());
2999 public boolean onCreateWindow(WebView view, final boolean dialog,
3000 final boolean userGesture, final Message resultMsg) {
3001 // Short-circuit if we can't create any more tabs or sub windows.
3002 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3003 new AlertDialog.Builder(BrowserActivity.this)
3004 .setTitle(R.string.too_many_subwindows_dialog_title)
3005 .setIcon(android.R.drawable.ic_dialog_alert)
3006 .setMessage(R.string.too_many_subwindows_dialog_message)
3007 .setPositiveButton(R.string.ok, null)
3010 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3011 new AlertDialog.Builder(BrowserActivity.this)
3012 .setTitle(R.string.too_many_windows_dialog_title)
3013 .setIcon(android.R.drawable.ic_dialog_alert)
3014 .setMessage(R.string.too_many_windows_dialog_message)
3015 .setPositiveButton(R.string.ok, null)
3020 // Short-circuit if this was a user gesture.
3022 createWindow(dialog, resultMsg);
3026 // Allow the popup and create the appropriate window.
3027 final AlertDialog.OnClickListener allowListener =
3028 new AlertDialog.OnClickListener() {
3029 public void onClick(DialogInterface d,
3031 createWindow(dialog, resultMsg);
3035 // Block the popup by returning a null WebView.
3036 final AlertDialog.OnClickListener blockListener =
3037 new AlertDialog.OnClickListener() {
3038 public void onClick(DialogInterface d, int which) {
3039 resultMsg.sendToTarget();
3043 // Build a confirmation dialog to display to the user.
3044 final AlertDialog d =
3045 new AlertDialog.Builder(BrowserActivity.this)
3046 .setTitle(R.string.attention)
3047 .setIcon(android.R.drawable.ic_dialog_alert)
3048 .setMessage(R.string.popup_window_attempt)
3049 .setPositiveButton(R.string.allow, allowListener)
3050 .setNegativeButton(R.string.block, blockListener)
3051 .setCancelable(false)
3054 // Show the confirmation dialog.
3060 public void onCloseWindow(WebView window) {
3061 final TabControl.Tab current = mTabControl.getCurrentTab();
3062 final TabControl.Tab parent = current.getParentTab();
3063 if (parent != null) {
3064 // JavaScript can only close popup window.
3065 switchToTab(mTabControl.getTabIndex(parent));
3066 // Now we need to close the window
3072 public void onProgressChanged(WebView view, int newProgress) {
3073 mTitleBar.setProgress(newProgress);
3074 if (mFakeTitleBar != null) {
3075 mFakeTitleBar.setProgress(newProgress);
3078 if (newProgress == 100) {
3079 // onProgressChanged() is called for sub-frame too while
3080 // onPageFinished() is only called for the main frame. sync
3081 // cookie and cache promptly here.
3082 CookieSyncManager.getInstance().sync();
3085 updateInLoadMenuItems();
3086 // If the options menu is open, leave the title bar
3087 if (!mOptionsMenuOpen || !mIconView) {
3091 } else if (!mInLoad) {
3092 // onPageFinished may have already been called but a subframe
3093 // is still loading and updating the progress. Reset mInLoad
3094 // and update the menu items.
3096 updateInLoadMenuItems();
3097 WebView currentWebView = mTabControl.getCurrentWebView();
3098 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3099 && (!mOptionsMenuOpen || mIconView)) {
3100 // This page has begun to load, so show the title bar
3107 public void onReceivedTitle(WebView view, String title) {
3108 String url = view.getUrl();
3110 // here, if url is null, we want to reset the title
3111 setUrlTitle(url, title);
3114 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3117 // See if we can find the current url in our history database and
3118 // add the new title to it.
3119 if (url.startsWith("http://www.")) {
3120 url = url.substring(11);
3121 } else if (url.startsWith("http://")) {
3122 url = url.substring(4);
3126 String [] selArgs = new String[] { url };
3128 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3129 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3130 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3131 Browser.HISTORY_PROJECTION, where, selArgs, null);
3132 if (c.moveToFirst()) {
3133 // Current implementation of database only has one entry per
3135 ContentValues map = new ContentValues();
3136 map.put(Browser.BookmarkColumns.TITLE, title);
3137 mResolver.update(Browser.BOOKMARKS_URI, map,
3138 "_id = " + c.getInt(0), null);
3141 } catch (IllegalStateException e) {
3142 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3143 } catch (SQLiteException ex) {
3144 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3149 public void onReceivedIcon(WebView view, Bitmap icon) {
3150 updateIcon(view, icon);
3154 public void onReceivedTouchIconUrl(WebView view, String url) {
3155 final ContentResolver cr = getContentResolver();
3157 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
3158 view.getOriginalUrl(), view.getUrl(), true);
3160 if (c.getCount() > 0) {
3161 new DownloadTouchIcon(cr, c, view).execute(url);
3169 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
3170 if (mCustomView != null)
3173 // Add the custom view to its container.
3174 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3176 mCustomViewCallback = callback;
3177 // Save the menu state and set it to empty while the custom
3179 mOldMenuState = mMenuState;
3180 mMenuState = EMPTY_MENU;
3181 // Hide the content view.
3182 mContentView.setVisibility(View.GONE);
3183 // Finally show the custom view container.
3184 mCustomViewContainer.setVisibility(View.VISIBLE);
3185 mCustomViewContainer.bringToFront();
3189 public void onHideCustomView() {
3190 if (mCustomView == null)
3193 // Hide the custom view.
3194 mCustomView.setVisibility(View.GONE);
3195 // Remove the custom view from its container.
3196 mCustomViewContainer.removeView(mCustomView);
3198 // Reset the old menu state.
3199 mMenuState = mOldMenuState;
3200 mOldMenuState = EMPTY_MENU;
3201 mCustomViewContainer.setVisibility(View.GONE);
3202 mCustomViewCallback.onCustomViewHidden();
3203 // Show the content view.
3204 mContentView.setVisibility(View.VISIBLE);
3208 * The origin has exceeded its database quota.
3209 * @param url the URL that exceeded the quota
3210 * @param databaseIdentifier the identifier of the database on
3211 * which the transaction that caused the quota overflow was run
3212 * @param currentQuota the current quota for the origin.
3213 * @param estimatedSize the estimated size of the database.
3214 * @param totalUsedQuota is the sum of all origins' quota.
3215 * @param quotaUpdater The callback to run when a decision to allow or
3216 * deny quota has been made. Don't forget to call this!
3219 public void onExceededDatabaseQuota(String url,
3220 String databaseIdentifier, long currentQuota, long estimatedSize,
3221 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3222 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3223 url, databaseIdentifier, currentQuota, estimatedSize,
3224 totalUsedQuota, quotaUpdater);
3228 * The Application Cache has exceeded its max size.
3229 * @param spaceNeeded is the amount of disk space that would be needed
3230 * in order for the last appcache operation to succeed.
3231 * @param totalUsedQuota is the sum of all origins' quota.
3232 * @param quotaUpdater A callback to inform the WebCore thread that a new
3233 * app cache size is available. This callback must always be executed at
3234 * some point to ensure that the sleeping WebCore thread is woken up.
3237 public void onReachedMaxAppCacheSize(long spaceNeeded,
3238 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3239 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3240 spaceNeeded, totalUsedQuota, quotaUpdater);
3244 * Instructs the browser to show a prompt to ask the user to set the
3245 * Geolocation permission state for the specified origin.
3246 * @param origin The origin for which Geolocation permissions are
3248 * @param callback The callback to call once the user has set the
3249 * Geolocation permission state.
3252 public void onGeolocationPermissionsShowPrompt(String origin,
3253 GeolocationPermissions.Callback callback) {
3254 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3259 * Instructs the browser to hide the Geolocation permissions prompt.
3262 public void onGeolocationPermissionsHidePrompt() {
3263 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3266 /* Adds a JavaScript error message to the system log.
3267 * @param message The error message to report.
3268 * @param lineNumber The line number of the error.
3269 * @param sourceID The name of the source file that caused the error.
3272 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3273 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3274 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3275 if (mShouldShowErrorConsole &&
3276 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3277 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3279 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
3284 * Notify the host application a download should be done, or that
3285 * the data should be streamed if a streaming viewer is available.
3286 * @param url The full url to the content that should be downloaded
3287 * @param contentDisposition Content-disposition http header, if
3289 * @param mimetype The mimetype of the content reported by the server
3290 * @param contentLength The file size reported by the server
3292 public void onDownloadStart(String url, String userAgent,
3293 String contentDisposition, String mimetype, long contentLength) {
3294 // if we're dealing wih A/V content that's not explicitly marked
3295 // for download, check if it's streamable.
3296 if (contentDisposition == null
3297 || !contentDisposition.regionMatches(
3298 true, 0, "attachment", 0, 10)) {
3299 // query the package manager to see if there's a registered handler
3301 Intent intent = new Intent(Intent.ACTION_VIEW);
3302 intent.setDataAndType(Uri.parse(url), mimetype);
3303 ResolveInfo info = getPackageManager().resolveActivity(intent,
3304 PackageManager.MATCH_DEFAULT_ONLY);
3306 ComponentName myName = getComponentName();
3307 // If we resolved to ourselves, we don't want to attempt to
3308 // load the url only to try and download it again.
3309 if (!myName.getPackageName().equals(
3310 info.activityInfo.packageName)
3311 || !myName.getClassName().equals(
3312 info.activityInfo.name)) {
3313 // someone (other than us) knows how to handle this mime
3314 // type with this scheme, don't download.
3316 startActivity(intent);
3318 } catch (ActivityNotFoundException ex) {
3320 Log.d(LOGTAG, "activity not found for " + mimetype
3321 + " over " + Uri.parse(url).getScheme(),
3324 // Best behavior is to fall back to a download in this
3330 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3334 * Notify the host application a download should be done, even if there
3335 * is a streaming viewer available for thise type.
3336 * @param url The full url to the content that should be downloaded
3337 * @param contentDisposition Content-disposition http header, if
3339 * @param mimetype The mimetype of the content reported by the server
3340 * @param contentLength The file size reported by the server
3342 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3343 String contentDisposition, String mimetype, long contentLength) {
3345 String filename = URLUtil.guessFileName(url,
3346 contentDisposition, mimetype);
3348 // Check to see if we have an SDCard
3349 String status = Environment.getExternalStorageState();
3350 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3354 // Check to see if the SDCard is busy, same as the music app
3355 if (status.equals(Environment.MEDIA_SHARED)) {
3356 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3357 title = R.string.download_sdcard_busy_dlg_title;
3359 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3360 title = R.string.download_no_sdcard_dlg_title;
3363 new AlertDialog.Builder(this)
3365 .setIcon(android.R.drawable.ic_dialog_alert)
3367 .setPositiveButton(R.string.ok, null)
3372 // java.net.URI is a lot stricter than KURL so we have to undo
3373 // KURL's percent-encoding and redo the encoding using java.net.URI.
3376 // Undo the percent-encoding that KURL may have done.
3377 String newUrl = new String(URLUtil.decode(url.getBytes()));
3378 // Parse the url into pieces
3379 WebAddress w = new WebAddress(newUrl);
3381 String query = null;
3382 String path = w.mPath;
3383 // Break the path into path, query, and fragment
3384 if (path.length() > 0) {
3385 // Strip the fragment
3386 int idx = path.lastIndexOf('#');
3388 frag = path.substring(idx + 1);
3389 path = path.substring(0, idx);
3391 idx = path.lastIndexOf('?');
3393 query = path.substring(idx + 1);
3394 path = path.substring(0, idx);
3397 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3399 } catch (Exception e) {
3400 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3404 // XXX: Have to use the old url since the cookies were stored using the
3405 // old percent-encoded url.
3406 String cookies = CookieManager.getInstance().getCookie(url);
3408 ContentValues values = new ContentValues();
3409 values.put(Downloads.COLUMN_URI, uri.toString());
3410 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3411 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3412 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
3414 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
3415 BrowserDownloadPage.class.getCanonicalName());
3416 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3417 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3418 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3419 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
3420 if (contentLength > 0) {
3421 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
3423 if (mimetype == null) {
3424 // We must have long pressed on a link or image to download it. We
3425 // are not sure of the mimetype in this case, so do a head request
3426 new FetchUrlMimeType(this).execute(values);
3428 final Uri contentUri =
3429 getContentResolver().insert(Downloads.CONTENT_URI, values);
3430 viewDownloads(contentUri);
3436 * Resets the lock icon. This method is called when we start a new load and
3437 * know the url to be loaded.
3439 private void resetLockIcon(String url) {
3440 // Save the lock-icon state (we revert to it if the load gets cancelled)
3443 mLockIconType = LOCK_ICON_UNSECURE;
3444 if (URLUtil.isHttpsUrl(url)) {
3445 mLockIconType = LOCK_ICON_SECURE;
3447 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3448 " reset lock icon to " + mLockIconType);
3452 updateLockIconImage(LOCK_ICON_UNSECURE);
3455 /* package */ void setLockIconType(int type) {
3456 mLockIconType = type;
3459 /* package */ int getLockIconType() {
3460 return mLockIconType;
3463 /* package */ void setPrevLockType(int type) {
3464 mPrevLockType = type;
3467 /* package */ int getPrevLockType() {
3468 return mPrevLockType;
3472 * Update the lock icon to correspond to our latest state.
3474 /* package */ void updateLockIconToLatest() {
3475 updateLockIconImage(mLockIconType);
3479 * Updates the lock-icon image in the title-bar.
3481 private void updateLockIconImage(int lockIconType) {
3483 if (lockIconType == LOCK_ICON_SECURE) {
3485 } else if (lockIconType == LOCK_ICON_MIXED) {
3488 mTitleBar.setLock(d);
3489 if (mFakeTitleBar != null) {
3490 mFakeTitleBar.setLock(d);
3495 * Displays a page-info dialog.
3496 * @param tab The tab to show info about
3497 * @param fromShowSSLCertificateOnError The flag that indicates whether
3498 * this dialog was opened from the SSL-certificate-on-error dialog or
3499 * not. This is important, since we need to know whether to return to
3500 * the parent dialog or simply dismiss.
3502 private void showPageInfo(final TabControl.Tab tab,
3503 final boolean fromShowSSLCertificateOnError) {
3504 final LayoutInflater factory = LayoutInflater
3507 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3509 final WebView view = tab.getWebView();
3512 String title = null;
3516 title = tab.getTitle();
3517 } else if (view == mTabControl.getCurrentWebView()) {
3518 // Use the cached title and url if this is the current WebView
3522 url = view.getUrl();
3523 title = view.getTitle();
3529 if (title == null) {
3533 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3534 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3536 mPageInfoView = tab;
3537 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3539 AlertDialog.Builder alertDialogBuilder =
3540 new AlertDialog.Builder(this)
3541 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3542 .setView(pageInfoView)
3545 new DialogInterface.OnClickListener() {
3546 public void onClick(DialogInterface dialog,
3548 mPageInfoDialog = null;
3549 mPageInfoView = null;
3550 mPageInfoFromShowSSLCertificateOnError = null;
3552 // if we came here from the SSL error dialog
3553 if (fromShowSSLCertificateOnError) {
3554 // go back to the SSL error dialog
3555 showSSLCertificateOnError(
3556 mSSLCertificateOnErrorView,
3557 mSSLCertificateOnErrorHandler,
3558 mSSLCertificateOnErrorError);
3562 .setOnCancelListener(
3563 new DialogInterface.OnCancelListener() {
3564 public void onCancel(DialogInterface dialog) {
3565 mPageInfoDialog = null;
3566 mPageInfoView = null;
3567 mPageInfoFromShowSSLCertificateOnError = null;
3569 // if we came here from the SSL error dialog
3570 if (fromShowSSLCertificateOnError) {
3571 // go back to the SSL error dialog
3572 showSSLCertificateOnError(
3573 mSSLCertificateOnErrorView,
3574 mSSLCertificateOnErrorHandler,
3575 mSSLCertificateOnErrorError);
3580 // if we have a main top-level page SSL certificate set or a certificate
3582 if (fromShowSSLCertificateOnError ||
3583 (view != null && view.getCertificate() != null)) {
3584 // add a 'View Certificate' button
3585 alertDialogBuilder.setNeutralButton(
3586 R.string.view_certificate,
3587 new DialogInterface.OnClickListener() {
3588 public void onClick(DialogInterface dialog,
3590 mPageInfoDialog = null;
3591 mPageInfoView = null;
3592 mPageInfoFromShowSSLCertificateOnError = null;
3594 // if we came here from the SSL error dialog
3595 if (fromShowSSLCertificateOnError) {
3596 // go back to the SSL error dialog
3597 showSSLCertificateOnError(
3598 mSSLCertificateOnErrorView,
3599 mSSLCertificateOnErrorHandler,
3600 mSSLCertificateOnErrorError);
3602 // otherwise, display the top-most certificate from
3604 if (view.getCertificate() != null) {
3605 showSSLCertificate(tab);
3612 mPageInfoDialog = alertDialogBuilder.show();
3616 * Displays the main top-level page SSL certificate dialog
3617 * (accessible from the Page-Info dialog).
3618 * @param tab The tab to show certificate for.
3620 private void showSSLCertificate(final TabControl.Tab tab) {
3621 final View certificateView =
3622 inflateCertificateView(tab.getWebView().getCertificate());
3623 if (certificateView == null) {
3627 LayoutInflater factory = LayoutInflater.from(this);
3629 final LinearLayout placeholder =
3630 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3632 LinearLayout ll = (LinearLayout) factory.inflate(
3633 R.layout.ssl_success, placeholder);
3634 ((TextView)ll.findViewById(R.id.success))
3635 .setText(R.string.ssl_certificate_is_valid);
3637 mSSLCertificateView = tab;
3638 mSSLCertificateDialog =
3639 new AlertDialog.Builder(this)
3640 .setTitle(R.string.ssl_certificate).setIcon(
3641 R.drawable.ic_dialog_browser_certificate_secure)
3642 .setView(certificateView)
3643 .setPositiveButton(R.string.ok,
3644 new DialogInterface.OnClickListener() {
3645 public void onClick(DialogInterface dialog,
3647 mSSLCertificateDialog = null;
3648 mSSLCertificateView = null;
3650 showPageInfo(tab, false);
3653 .setOnCancelListener(
3654 new DialogInterface.OnCancelListener() {
3655 public void onCancel(DialogInterface dialog) {
3656 mSSLCertificateDialog = null;
3657 mSSLCertificateView = null;
3659 showPageInfo(tab, false);
3666 * Displays the SSL error certificate dialog.
3667 * @param view The target web-view.
3668 * @param handler The SSL error handler responsible for cancelling the
3669 * connection that resulted in an SSL error or proceeding per user request.
3670 * @param error The SSL error object.
3672 private void showSSLCertificateOnError(
3673 final WebView view, final SslErrorHandler handler, final SslError error) {
3675 final View certificateView =
3676 inflateCertificateView(error.getCertificate());
3677 if (certificateView == null) {
3681 LayoutInflater factory = LayoutInflater.from(this);
3683 final LinearLayout placeholder =
3684 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3686 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3687 LinearLayout ll = (LinearLayout)factory
3688 .inflate(R.layout.ssl_warning, placeholder);
3689 ((TextView)ll.findViewById(R.id.warning))
3690 .setText(R.string.ssl_untrusted);
3693 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3694 LinearLayout ll = (LinearLayout)factory
3695 .inflate(R.layout.ssl_warning, placeholder);
3696 ((TextView)ll.findViewById(R.id.warning))
3697 .setText(R.string.ssl_mismatch);
3700 if (error.hasError(SslError.SSL_EXPIRED)) {
3701 LinearLayout ll = (LinearLayout)factory
3702 .inflate(R.layout.ssl_warning, placeholder);
3703 ((TextView)ll.findViewById(R.id.warning))
3704 .setText(R.string.ssl_expired);
3707 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3708 LinearLayout ll = (LinearLayout)factory
3709 .inflate(R.layout.ssl_warning, placeholder);
3710 ((TextView)ll.findViewById(R.id.warning))
3711 .setText(R.string.ssl_not_yet_valid);
3714 mSSLCertificateOnErrorHandler = handler;
3715 mSSLCertificateOnErrorView = view;
3716 mSSLCertificateOnErrorError = error;
3717 mSSLCertificateOnErrorDialog =
3718 new AlertDialog.Builder(this)
3719 .setTitle(R.string.ssl_certificate).setIcon(
3720 R.drawable.ic_dialog_browser_certificate_partially_secure)
3721 .setView(certificateView)
3722 .setPositiveButton(R.string.ok,
3723 new DialogInterface.OnClickListener() {
3724 public void onClick(DialogInterface dialog,
3726 mSSLCertificateOnErrorDialog = null;
3727 mSSLCertificateOnErrorView = null;
3728 mSSLCertificateOnErrorHandler = null;
3729 mSSLCertificateOnErrorError = null;
3731 mWebViewClient.onReceivedSslError(
3732 view, handler, error);
3735 .setNeutralButton(R.string.page_info_view,
3736 new DialogInterface.OnClickListener() {
3737 public void onClick(DialogInterface dialog,
3739 mSSLCertificateOnErrorDialog = null;
3741 // do not clear the dialog state: we will
3742 // need to show the dialog again once the
3743 // user is done exploring the page-info details
3745 showPageInfo(mTabControl.getTabFromView(view),
3749 .setOnCancelListener(
3750 new DialogInterface.OnCancelListener() {
3751 public void onCancel(DialogInterface dialog) {
3752 mSSLCertificateOnErrorDialog = null;
3753 mSSLCertificateOnErrorView = null;
3754 mSSLCertificateOnErrorHandler = null;
3755 mSSLCertificateOnErrorError = null;
3757 mWebViewClient.onReceivedSslError(
3758 view, handler, error);
3765 * Inflates the SSL certificate view (helper method).
3766 * @param certificate The SSL certificate.
3767 * @return The resultant certificate view with issued-to, issued-by,
3768 * issued-on, expires-on, and possibly other fields set.
3769 * If the input certificate is null, returns null.
3771 private View inflateCertificateView(SslCertificate certificate) {
3772 if (certificate == null) {
3776 LayoutInflater factory = LayoutInflater.from(this);
3778 View certificateView = factory.inflate(
3779 R.layout.ssl_certificate, null);
3782 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3783 if (issuedTo != null) {
3784 ((TextView) certificateView.findViewById(R.id.to_common))
3785 .setText(issuedTo.getCName());
3786 ((TextView) certificateView.findViewById(R.id.to_org))
3787 .setText(issuedTo.getOName());
3788 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3789 .setText(issuedTo.getUName());
3793 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3794 if (issuedBy != null) {
3795 ((TextView) certificateView.findViewById(R.id.by_common))
3796 .setText(issuedBy.getCName());
3797 ((TextView) certificateView.findViewById(R.id.by_org))
3798 .setText(issuedBy.getOName());
3799 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3800 .setText(issuedBy.getUName());
3804 String issuedOn = reformatCertificateDate(
3805 certificate.getValidNotBefore());
3806 ((TextView) certificateView.findViewById(R.id.issued_on))
3810 String expiresOn = reformatCertificateDate(
3811 certificate.getValidNotAfter());
3812 ((TextView) certificateView.findViewById(R.id.expires_on))
3813 .setText(expiresOn);
3815 return certificateView;
3819 * Re-formats the certificate date (Date.toString()) string to
3820 * a properly localized date string.
3821 * @return Properly localized version of the certificate date string and
3822 * the original certificate date string if fails to localize.
3823 * If the original string is null, returns an empty string "".
3825 private String reformatCertificateDate(String certificateDate) {
3826 String reformattedDate = null;
3828 if (certificateDate != null) {
3831 date = java.text.DateFormat.getInstance().parse(certificateDate);
3832 } catch (ParseException e) {
3838 DateFormat.getDateFormat(this).format(date);
3842 return reformattedDate != null ? reformattedDate :
3843 (certificateDate != null ? certificateDate : "");
3847 * Displays an http-authentication dialog.
3849 private void showHttpAuthentication(final HttpAuthHandler handler,
3850 final String host, final String realm, final String title,
3851 final String name, final String password, int focusId) {
3852 LayoutInflater factory = LayoutInflater.from(this);
3853 final View v = factory
3854 .inflate(R.layout.http_authentication, null);
3856 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3858 if (password != null) {
3859 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3862 String titleText = title;
3863 if (titleText == null) {
3864 titleText = getText(R.string.sign_in_to).toString().replace(
3865 "%s1", host).replace("%s2", realm);
3868 mHttpAuthHandler = handler;
3869 AlertDialog dialog = new AlertDialog.Builder(this)
3870 .setTitle(titleText)
3871 .setIcon(android.R.drawable.ic_dialog_alert)
3873 .setPositiveButton(R.string.action,
3874 new DialogInterface.OnClickListener() {
3875 public void onClick(DialogInterface dialog,
3877 String nm = ((EditText) v
3878 .findViewById(R.id.username_edit))
3879 .getText().toString();
3880 String pw = ((EditText) v
3881 .findViewById(R.id.password_edit))
3882 .getText().toString();
3883 BrowserActivity.this.setHttpAuthUsernamePassword
3884 (host, realm, nm, pw);
3885 handler.proceed(nm, pw);
3886 mHttpAuthenticationDialog = null;
3887 mHttpAuthHandler = null;
3889 .setNegativeButton(R.string.cancel,
3890 new DialogInterface.OnClickListener() {
3891 public void onClick(DialogInterface dialog,
3894 BrowserActivity.this.resetTitleAndRevertLockIcon();
3895 mHttpAuthenticationDialog = null;
3896 mHttpAuthHandler = null;
3898 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3899 public void onCancel(DialogInterface dialog) {
3901 BrowserActivity.this.resetTitleAndRevertLockIcon();
3902 mHttpAuthenticationDialog = null;
3903 mHttpAuthHandler = null;
3906 // Make the IME appear when the dialog is displayed if applicable.
3907 dialog.getWindow().setSoftInputMode(
3908 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3911 dialog.findViewById(focusId).requestFocus();
3913 v.findViewById(R.id.username_edit).requestFocus();
3915 mHttpAuthenticationDialog = dialog;
3918 public int getProgress() {
3919 WebView w = mTabControl.getCurrentWebView();
3921 return w.getProgress();
3928 * Set HTTP authentication password.
3930 * @param host The host for the password
3931 * @param realm The realm for the password
3932 * @param username The username for the password. If it is null, it means
3933 * password can't be saved.
3934 * @param password The password
3936 public void setHttpAuthUsernamePassword(String host, String realm,
3939 WebView w = mTabControl.getCurrentWebView();
3941 w.setHttpAuthUsernamePassword(host, realm, username, password);
3946 * connectivity manager says net has come or gone... inform the user
3947 * @param up true if net has come up, false if net has gone down
3949 public void onNetworkToggle(boolean up) {
3950 if (up == mIsNetworkUp) {
3953 mIsNetworkUp = true;
3954 if (mAlertDialog != null) {
3955 mAlertDialog.cancel();
3956 mAlertDialog = null;
3959 mIsNetworkUp = false;
3960 if (mInLoad && mAlertDialog == null) {
3961 mAlertDialog = new AlertDialog.Builder(this)
3962 .setTitle(R.string.loadSuspendedTitle)
3963 .setMessage(R.string.loadSuspended)
3964 .setPositiveButton(R.string.ok, null)
3968 WebView w = mTabControl.getCurrentWebView();
3970 w.setNetworkAvailable(up);
3975 protected void onActivityResult(int requestCode, int resultCode,
3977 switch (requestCode) {
3979 if (resultCode == RESULT_OK && intent != null) {
3980 String data = intent.getAction();
3981 Bundle extras = intent.getExtras();
3982 if (extras != null && extras.getBoolean("new_window", false)) {
3985 final TabControl.Tab currentTab =
3986 mTabControl.getCurrentTab();
3987 dismissSubWindow(currentTab);
3988 if (data != null && data.length() != 0) {
3989 getTopWindow().loadUrl(data);
3997 getTopWindow().requestFocus();
4001 * This method is called as a result of the user selecting the options
4002 * menu to see the download window, or when a download changes state. It
4003 * shows the download window ontop of the current window.
4005 /* package */ void viewDownloads(Uri downloadRecord) {
4006 Intent intent = new Intent(this,
4007 BrowserDownloadPage.class);
4008 intent.setData(downloadRecord);
4009 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4015 * @param startWithHistory If true, open starting on the history tab.
4016 * Otherwise, start with the bookmarks tab.
4018 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
4019 WebView current = mTabControl.getCurrentWebView();
4020 if (current == null) {
4023 Intent intent = new Intent(this,
4024 CombinedBookmarkHistoryActivity.class);
4025 String title = current.getTitle();
4026 String url = current.getUrl();
4027 // Just in case the user opens bookmarks before a page finishes loading
4028 // so the current history item, and therefore the page, is null.
4030 url = mLastEnteredUrl;
4033 url = mSettings.getHomePage();
4036 // In case the web page has not yet received its associated title.
4037 if (title == null) {
4040 intent.putExtra("title", title);
4041 intent.putExtra("url", url);
4042 // Disable opening in a new window if we have maxed out the windows
4043 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4044 >= TabControl.MAX_TABS);
4045 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
4046 if (startWithHistory) {
4047 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4048 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4050 startActivityForResult(intent, COMBO_PAGE);
4053 // Called when loading from context menu or LOAD_URL message
4054 private void loadURL(WebView view, String url) {
4055 // In case the user enters nothing.
4056 if (url != null && url.length() != 0 && view != null) {
4057 url = smartUrlFilter(url);
4058 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4064 private String smartUrlFilter(Uri inUri) {
4065 if (inUri != null) {
4066 return smartUrlFilter(inUri.toString());
4074 int getWindowCount(){
4075 if(mTabControl != null){
4076 return mTabControl.getTabCount();
4081 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4082 "(?i)" + // switch on case insensitive matching
4083 "(" + // begin group for schema
4084 "(?:http|https|file):\\/\\/" +
4085 "|(?:inline|data|about|content|javascript):" +
4090 * Attempts to determine whether user input is a URL or search
4091 * terms. Anything with a space is passed to search.
4093 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4094 * "Http://" converts to "http://"
4096 * @return Original or modified URL
4099 String smartUrlFilter(String url) {
4101 String inUrl = url.trim();
4102 boolean hasSpace = inUrl.indexOf(' ') != -1;
4104 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4105 if (matcher.matches()) {
4106 // force scheme to lowercase
4107 String scheme = matcher.group(1);
4108 String lcScheme = scheme.toLowerCase();
4109 if (!lcScheme.equals(scheme)) {
4110 inUrl = lcScheme + matcher.group(2);
4113 inUrl = inUrl.replace(" ", "%20");
4118 // FIXME: Is this the correct place to add to searches?
4119 // what if someone else calls this function?
4120 int shortcut = parseUrlShortcut(inUrl);
4121 if (shortcut != SHORTCUT_INVALID) {
4122 Browser.addSearchUrl(mResolver, inUrl);
4123 String query = inUrl.substring(2);
4125 case SHORTCUT_GOOGLE_SEARCH:
4126 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
4127 case SHORTCUT_WIKIPEDIA_SEARCH:
4128 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4129 case SHORTCUT_DICTIONARY_SEARCH:
4130 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4131 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
4132 // FIXME: we need location in this case
4133 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
4137 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4138 return URLUtil.guessUrl(inUrl);
4142 Browser.addSearchUrl(mResolver, inUrl);
4143 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
4146 /* package */ void setShouldShowErrorConsole(boolean flag) {
4147 if (flag == mShouldShowErrorConsole) {
4152 mShouldShowErrorConsole = flag;
4154 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4157 // Setting the show state of the console will cause it's the layout to be inflated.
4158 if (errorConsole.numberOfErrors() > 0) {
4159 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4161 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4164 // Now we can add it to the main view.
4165 mErrorConsoleContainer.addView(errorConsole,
4166 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4167 ViewGroup.LayoutParams.WRAP_CONTENT));
4169 mErrorConsoleContainer.removeView(errorConsole);
4174 final static int LOCK_ICON_UNSECURE = 0;
4175 final static int LOCK_ICON_SECURE = 1;
4176 final static int LOCK_ICON_MIXED = 2;
4178 private int mLockIconType = LOCK_ICON_UNSECURE;
4179 private int mPrevLockType = LOCK_ICON_UNSECURE;
4181 private BrowserSettings mSettings;
4182 private TabControl mTabControl;
4183 private ContentResolver mResolver;
4184 private FrameLayout mContentView;
4185 private View mCustomView;
4186 private FrameLayout mCustomViewContainer;
4187 private WebChromeClient.CustomViewCallback mCustomViewCallback;
4189 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4190 // view, we should rewrite this.
4191 private int mCurrentMenuState = 0;
4192 private int mMenuState = R.id.MAIN_MENU;
4193 private int mOldMenuState = EMPTY_MENU;
4194 private static final int EMPTY_MENU = -1;
4197 private FindDialog mFindDialog;
4198 // Used to prevent chording to result in firing two shortcuts immediately
4199 // one after another. Fixes bug 1211714.
4202 private boolean mInLoad;
4203 private boolean mIsNetworkUp;
4205 private boolean mPageStarted;
4206 private boolean mActivityInPause = true;
4208 private boolean mMenuIsDown;
4210 private final KeyTracker mKeyTracker = new KeyTracker(this);
4212 // As trackball doesn't send repeat down, we have to track it ourselves
4213 private boolean mTrackTrackball;
4215 private static boolean mInTrace;
4217 // Performance probe
4218 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4219 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4220 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4221 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4222 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4223 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4224 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4225 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4226 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4229 private long mStart;
4230 private long mProcessStart;
4231 private long mUserStart;
4232 private long mSystemStart;
4233 private long mIdleStart;
4234 private long mIrqStart;
4236 private long mUiStart;
4238 private Drawable mMixLockIcon;
4239 private Drawable mSecLockIcon;
4241 /* hold a ref so we can auto-cancel if necessary */
4242 private AlertDialog mAlertDialog;
4244 // Wait for credentials before loading google.com
4245 private ProgressDialog mCredsDlg;
4247 // The up-to-date URL and title (these can be different from those stored
4248 // in WebView, since it takes some time for the information in WebView to
4250 private String mUrl;
4251 private String mTitle;
4253 // As PageInfo has different style for landscape / portrait, we have
4254 // to re-open it when configuration changed
4255 private AlertDialog mPageInfoDialog;
4256 private TabControl.Tab mPageInfoView;
4257 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4258 // dialog, we should not just dismiss it, but should get back to the
4259 // SSL-certificate-on-error dialog. This flag is used to store this state
4260 private Boolean mPageInfoFromShowSSLCertificateOnError;
4262 // as SSLCertificateOnError has different style for landscape / portrait,
4263 // we have to re-open it when configuration changed
4264 private AlertDialog mSSLCertificateOnErrorDialog;
4265 private WebView mSSLCertificateOnErrorView;
4266 private SslErrorHandler mSSLCertificateOnErrorHandler;
4267 private SslError mSSLCertificateOnErrorError;
4269 // as SSLCertificate has different style for landscape / portrait, we
4270 // have to re-open it when configuration changed
4271 private AlertDialog mSSLCertificateDialog;
4272 private TabControl.Tab mSSLCertificateView;
4274 // as HttpAuthentication has different style for landscape / portrait, we
4275 // have to re-open it when configuration changed
4276 private AlertDialog mHttpAuthenticationDialog;
4277 private HttpAuthHandler mHttpAuthHandler;
4279 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4280 new FrameLayout.LayoutParams(
4281 ViewGroup.LayoutParams.FILL_PARENT,
4282 ViewGroup.LayoutParams.FILL_PARENT);
4283 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4284 new FrameLayout.LayoutParams(
4285 ViewGroup.LayoutParams.FILL_PARENT,
4286 ViewGroup.LayoutParams.FILL_PARENT,
4289 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4291 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4292 // Dictionary search
4293 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4294 // Google Mobile Local search
4295 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4297 final static String QUERY_PLACE_HOLDER = "%s";
4299 // "source" parameter for Google search through search key
4300 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4301 // "source" parameter for Google search through goto menu
4302 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4303 // "source" parameter for Google search through simplily type
4304 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4305 // "source" parameter for Google search suggested by the browser
4306 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4307 // "source" parameter for Google search from unknown source
4308 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4310 private final static String LOGTAG = "browser";
4312 private String mLastEnteredUrl;
4314 private PowerManager.WakeLock mWakeLock;
4315 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4317 private Toast mStopToast;
4319 private TitleBar mTitleBar;
4321 private LinearLayout mErrorConsoleContainer = null;
4322 private boolean mShouldShowErrorConsole = false;
4324 // As the ids are dynamically created, we can't guarantee that they will
4325 // be in sequence, so this static array maps ids to a window number.
4326 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4327 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4328 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4329 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4331 // monitor platform changes
4332 private IntentFilter mNetworkStateChangedFilter;
4333 private BroadcastReceiver mNetworkStateIntentReceiver;
4335 private BroadcastReceiver mPackageInstallationReceiver;
4337 // activity requestCode
4338 final static int COMBO_PAGE = 1;
4339 final static int DOWNLOAD_PAGE = 2;
4340 final static int PREFERENCES_PAGE = 3;
4343 * A UrlData class to abstract how the content will be set to WebView.
4344 * This base class uses loadUrl to show the content.
4346 private static class UrlData {
4350 UrlData(String url) {
4354 void setPostData(byte[] postData) {
4355 mPostData = postData;
4359 return mUrl == null || mUrl.length() == 0;
4362 public void loadIn(WebView webView) {
4363 if (mPostData != null) {
4364 webView.postUrl(mUrl, mPostData);
4366 webView.loadUrl(mUrl);
4372 * A subclass of UrlData class that can display inlined content using
4373 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4375 private static class InlinedUrlData extends UrlData {
4376 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4379 mMimeType = mimeType;
4380 mEncoding = encoding;
4387 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4391 public void loadIn(WebView webView) {
4392 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4396 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);