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 * Keeps track of whether the options menu is open. This is important in
885 * determining whether to show or hide the title bar overlay.
887 private boolean mOptionsMenuOpen;
890 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
891 * of whether the configuration has changed. The first onMenuOpened call
892 * after a configuration change is simply a reopening of the same menu
893 * (i.e. mIconView did not change).
895 private boolean mConfigChanged;
898 * Whether or not the options menu is in its smaller, icon menu form. When
899 * true, we want the title bar overlay to be up. When false, we do not.
900 * Only meaningful if mOptionsMenuOpen is true.
902 private boolean mIconView;
905 public boolean onMenuOpened(int featureId, Menu menu) {
906 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
907 if (mOptionsMenuOpen) {
908 if (mConfigChanged) {
909 // We do not need to make any changes to the state of the
910 // title bar, since the only thing that happened was a
911 // change in orientation
912 mConfigChanged = false;
915 // Switching the menu to expanded view, so hide the
920 // Switching the menu back to icon view, so show the
921 // title bar once again.
927 // The options menu is closed, so open it, and show the title
929 mOptionsMenuOpen = true;
930 mConfigChanged = false;
937 private void showFakeTitleBar() {
938 if (mFakeTitleBar == null && mActiveTabsPage == null
939 && !mActivityInPause) {
940 final WebView webView = getTopWindow();
941 mFakeTitleBar = new TitleBar(this);
942 mFakeTitleBar.setTitleAndUrl(null, webView.getUrl());
943 mFakeTitleBar.setProgress(webView.getProgress());
944 mFakeTitleBar.setFavicon(webView.getFavicon());
945 updateLockIconToLatest();
947 WindowManager manager
948 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
950 // Add the title bar to the window manager so it can receive touches
951 // while the menu is up
952 WindowManager.LayoutParams params
953 = new WindowManager.LayoutParams(
954 ViewGroup.LayoutParams.FILL_PARENT,
955 ViewGroup.LayoutParams.WRAP_CONTENT,
956 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
957 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
959 params.gravity = Gravity.TOP;
960 WebView mainView = mTabControl.getCurrentWebView();
961 params.windowAnimations = mainView == null
962 || mainView.getScrollY() != 0
963 ? com.android.internal.R.style.Animation_DropDownDown : 0;
964 // XXX : Without providing an offset, the fake title bar will be
965 // placed underneath the status bar. Use the global visible rect
966 // of mBrowserFrameLayout to determine the bottom of the status bar
967 Rect rectangle = new Rect();
968 mBrowserFrameLayout.getGlobalVisibleRect(rectangle);
969 params.y = rectangle.top;
970 manager.addView(mFakeTitleBar, params);
975 public void onOptionsMenuClosed(Menu menu) {
976 mOptionsMenuOpen = false;
979 } else if (!mIconView) {
980 // The page is currently loading, and we are in expanded mode, so
981 // we were not showing the menu. Show it once again. It will be
982 // removed when the page finishes.
986 private void hideFakeTitleBar() {
987 if (mFakeTitleBar == null) return;
988 WindowManager manager
989 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
990 manager.removeView(mFakeTitleBar);
991 mFakeTitleBar = null;
995 * onSaveInstanceState(Bundle map)
996 * onSaveInstanceState is called right before onStop(). The map contains
999 @Override protected void onSaveInstanceState(Bundle outState) {
1001 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1003 // the default implementation requires each view to have an id. As the
1004 // browser handles the state itself and it doesn't use id for the views,
1005 // don't call the default implementation. Otherwise it will trigger the
1006 // warning like this, "couldn't save which view has focus because the
1007 // focused view XXX has no id".
1009 // Save all the tabs
1010 mTabControl.saveState(outState);
1013 @Override protected void onPause() {
1016 if (mActivityInPause) {
1017 Log.e(LOGTAG, "BrowserActivity is already paused.");
1021 mTabControl.pauseCurrentTab();
1022 mActivityInPause = true;
1023 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1024 mWakeLock.acquire();
1025 mHandler.sendMessageDelayed(mHandler
1026 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1029 // Clear the credentials toast if it is up
1030 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1031 mCredsDlg.dismiss();
1035 // FIXME: This removes the active tabs page and resets the menu to
1036 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1037 // but then we would need to save it in onSaveInstanceState and restore
1038 // it in onCreate/onRestoreInstanceState
1039 if (mActiveTabsPage != null) {
1040 removeActiveTabPage(true);
1045 // unregister network state listener
1046 unregisterReceiver(mNetworkStateIntentReceiver);
1047 WebView.disablePlatformNotifications();
1049 if (mSensorManager != null) {
1050 mSensorManager.unregisterListener(mSensorListener);
1054 @Override protected void onDestroy() {
1056 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1059 // Remove the current tab and sub window
1060 TabControl.Tab t = mTabControl.getCurrentTab();
1062 dismissSubWindow(t);
1063 removeTabFromContentView(t);
1065 // Destroy all the tabs
1066 mTabControl.destroy();
1067 WebIconDatabase.getInstance().close();
1068 if (mGlsConnection != null) {
1069 unbindService(mGlsConnection);
1070 mGlsConnection = null;
1074 // stop MASF proxy service
1076 //Intent proxyServiceIntent = new Intent();
1077 //proxyServiceIntent.setComponent
1078 // (new ComponentName(
1079 // "com.android.masfproxyservice",
1080 // "com.android.masfproxyservice.MasfProxyService"));
1081 //stopService(proxyServiceIntent);
1083 unregisterReceiver(mPackageInstallationReceiver);
1087 public void onConfigurationChanged(Configuration newConfig) {
1088 mConfigChanged = true;
1089 super.onConfigurationChanged(newConfig);
1091 if (mPageInfoDialog != null) {
1092 mPageInfoDialog.dismiss();
1095 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1097 if (mSSLCertificateDialog != null) {
1098 mSSLCertificateDialog.dismiss();
1100 mSSLCertificateView);
1102 if (mSSLCertificateOnErrorDialog != null) {
1103 mSSLCertificateOnErrorDialog.dismiss();
1104 showSSLCertificateOnError(
1105 mSSLCertificateOnErrorView,
1106 mSSLCertificateOnErrorHandler,
1107 mSSLCertificateOnErrorError);
1109 if (mHttpAuthenticationDialog != null) {
1110 String title = ((TextView) mHttpAuthenticationDialog
1111 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1113 String name = ((TextView) mHttpAuthenticationDialog
1114 .findViewById(R.id.username_edit)).getText().toString();
1115 String password = ((TextView) mHttpAuthenticationDialog
1116 .findViewById(R.id.password_edit)).getText().toString();
1117 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1119 mHttpAuthenticationDialog.dismiss();
1120 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1121 name, password, focusId);
1123 if (mFindDialog != null && mFindDialog.isShowing()) {
1124 mFindDialog.onConfigurationChanged(newConfig);
1128 @Override public void onLowMemory() {
1129 super.onLowMemory();
1130 mTabControl.freeMemory();
1133 private boolean resumeWebViewTimers() {
1134 if ((!mActivityInPause && !mPageStarted) ||
1135 (mActivityInPause && mPageStarted)) {
1136 CookieSyncManager.getInstance().startSync();
1137 WebView w = mTabControl.getCurrentWebView();
1147 private boolean pauseWebViewTimers() {
1148 if (mActivityInPause && !mPageStarted) {
1149 CookieSyncManager.getInstance().stopSync();
1150 WebView w = mTabControl.getCurrentWebView();
1160 // FIXME: Do we want to call this when loading google for the first time?
1162 * This function is called when we are launching for the first time. We
1163 * are waiting for the login credentials before loading Google home
1164 * pages. This way the user will be logged in straight away.
1166 private void waitForCredentials() {
1168 mCredsDlg = new ProgressDialog(this);
1169 mCredsDlg.setIndeterminate(true);
1170 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1171 // If the user cancels the operation, then cancel the Google
1172 // Credentials request.
1173 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1176 // We set a timeout for the retrieval of credentials in onResume()
1177 // as that is when we have freed up some CPU time to get
1178 // the login credentials.
1182 * If we have received the credentials or we have timed out and we are
1183 * showing the credentials dialog, then it is time to move on.
1185 private void resumeAfterCredentials() {
1186 if (mCredsDlg == null) {
1191 if (mCredsDlg.isShowing()) {
1192 mCredsDlg.dismiss();
1196 // Clear any pending timeout
1197 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1200 WebView w = mTabControl.getCurrentWebView();
1202 w.loadUrl(mSettings.getHomePage());
1205 // Update the settings, need to do this last as it can take a moment
1206 // to persist the settings. In the mean time we could be loading
1208 mSettings.setLoginInitialized(this);
1211 // Open the icon database and retain all the icons for visited sites.
1212 private void retainIconsOnStartup() {
1213 final WebIconDatabase db = WebIconDatabase.getInstance();
1214 db.open(getDir("icons", 0).getPath());
1216 Cursor c = Browser.getAllBookmarks(mResolver);
1217 if (!c.moveToFirst()) {
1221 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1223 String url = c.getString(urlIndex);
1224 db.retainIconForPageUrl(url);
1225 } while (c.moveToNext());
1227 } catch (IllegalStateException e) {
1228 Log.e(LOGTAG, "retainIconsOnStartup", e);
1232 // Helper method for getting the top window.
1233 WebView getTopWindow() {
1234 return mTabControl.getCurrentTopWebView();
1238 public boolean onCreateOptionsMenu(Menu menu) {
1239 super.onCreateOptionsMenu(menu);
1241 MenuInflater inflater = getMenuInflater();
1242 inflater.inflate(R.menu.browser, menu);
1244 updateInLoadMenuItems();
1249 * As the menu can be open when loading state changes
1250 * we must manually update the state of the stop/reload menu
1253 private void updateInLoadMenuItems() {
1254 if (mMenu == null) {
1257 MenuItem src = mInLoad ?
1258 mMenu.findItem(R.id.stop_menu_id):
1259 mMenu.findItem(R.id.reload_menu_id);
1260 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1261 dest.setIcon(src.getIcon());
1262 dest.setTitle(src.getTitle());
1266 public boolean onContextItemSelected(MenuItem item) {
1267 // chording is not an issue with context menus, but we use the same
1268 // options selector, so set mCanChord to true so we can access them.
1270 int id = item.getItemId();
1271 final WebView webView = getTopWindow();
1272 if (null == webView) {
1275 final HashMap hrefMap = new HashMap();
1276 hrefMap.put("webview", webView);
1277 final Message msg = mHandler.obtainMessage(
1278 FOCUS_NODE_HREF, id, 0, hrefMap);
1280 // -- Browser context menu
1281 case R.id.open_context_menu_id:
1282 case R.id.open_newtab_context_menu_id:
1283 case R.id.bookmark_context_menu_id:
1284 case R.id.save_link_context_menu_id:
1285 case R.id.share_link_context_menu_id:
1286 case R.id.copy_link_context_menu_id:
1287 webView.requestFocusNodeHref(msg);
1291 // For other context menus
1292 return onOptionsItemSelected(item);
1298 private Bundle createGoogleSearchSourceBundle(String source) {
1299 Bundle bundle = new Bundle();
1300 bundle.putString(SearchManager.SOURCE, source);
1305 * Overriding this to insert a local information bundle
1308 public boolean onSearchRequested() {
1309 if (mOptionsMenuOpen) closeOptionsMenu();
1310 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1311 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1312 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1317 public void startSearch(String initialQuery, boolean selectInitialQuery,
1318 Bundle appSearchData, boolean globalSearch) {
1319 if (appSearchData == null) {
1320 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1322 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1326 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1327 * results in changing tabs.
1328 * @param index Index of the tab to change to, as defined by
1329 * mTabControl.getTabIndex(Tab t).
1330 * @return boolean True if we successfully switched to a different tab. If
1331 * the indexth tab is null, or if that tab is the same as
1332 * the current one, return false.
1334 /* package */ boolean switchToTab(int index) {
1335 TabControl.Tab tab = mTabControl.getTab(index);
1336 TabControl.Tab currentTab = mTabControl.getCurrentTab();
1337 if (tab == null || tab == currentTab) {
1340 if (currentTab != null) {
1341 // currentTab may be null if it was just removed. In that case,
1342 // we do not need to remove it
1343 removeTabFromContentView(currentTab);
1345 removeTabFromContentView(tab);
1346 mTabControl.setCurrentTab(tab);
1347 attachTabToContentView(tab);
1352 /* package */ TabControl.Tab openTabToHomePage() {
1353 return openTabAndShow(mSettings.getHomePage(), false, null);
1356 /* package */ void closeCurrentWindow() {
1357 final TabControl.Tab current = mTabControl.getCurrentTab();
1358 if (mTabControl.getTabCount() == 1) {
1359 // This is the last tab. Open a new one, with the home
1360 // page and close the current one.
1361 TabControl.Tab newTab = openTabToHomePage();
1365 final TabControl.Tab parent = current.getParentTab();
1366 int indexToShow = -1;
1367 if (parent != null) {
1368 indexToShow = mTabControl.getTabIndex(parent);
1370 final int currentIndex = mTabControl.getCurrentIndex();
1371 // Try to move to the tab to the right
1372 indexToShow = currentIndex + 1;
1373 if (indexToShow > mTabControl.getTabCount() - 1) {
1374 // Try to move to the tab to the left
1375 indexToShow = currentIndex - 1;
1378 if (switchToTab(indexToShow)) {
1384 private ActiveTabsPage mActiveTabsPage;
1387 * Remove the active tabs page.
1388 * @param needToAttach If true, the active tabs page did not attach a tab
1389 * to the content view, so we need to do that here.
1391 /* package */ void removeActiveTabPage(boolean needToAttach) {
1392 mContentView.removeView(mActiveTabsPage);
1393 mActiveTabsPage = null;
1394 mMenuState = R.id.MAIN_MENU;
1396 attachTabToContentView(mTabControl.getCurrentTab());
1398 getTopWindow().requestFocus();
1402 public boolean onOptionsItemSelected(MenuItem item) {
1404 // The user has already fired a shortcut with this hold down of the
1408 if (null == getTopWindow()) {
1412 // The shortcut action consumes the MENU. Even if it is still down,
1413 // it won't trigger the next shortcut action. In the case of the
1414 // shortcut action triggering a new activity, like Bookmarks, we
1415 // won't get onKeyUp for MENU. So it is important to reset it here.
1416 mMenuIsDown = false;
1418 switch (item.getItemId()) {
1420 case R.id.new_tab_menu_id:
1421 openTabToHomePage();
1424 case R.id.goto_menu_id:
1425 bookmarksOrHistoryPicker(false);
1428 case R.id.active_tabs_menu_id:
1429 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1430 removeTabFromContentView(mTabControl.getCurrentTab());
1432 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1433 mActiveTabsPage.requestFocus();
1434 mMenuState = EMPTY_MENU;
1437 case R.id.add_bookmark_menu_id:
1438 Intent i = new Intent(BrowserActivity.this,
1439 AddBookmarkPage.class);
1440 WebView w = getTopWindow();
1441 i.putExtra("url", w.getUrl());
1442 i.putExtra("title", w.getTitle());
1446 case R.id.stop_reload_menu_id:
1450 getTopWindow().reload();
1454 case R.id.back_menu_id:
1455 getTopWindow().goBack();
1458 case R.id.forward_menu_id:
1459 getTopWindow().goForward();
1462 case R.id.close_menu_id:
1463 // Close the subwindow if it exists.
1464 if (mTabControl.getCurrentSubWindow() != null) {
1465 dismissSubWindow(mTabControl.getCurrentTab());
1468 closeCurrentWindow();
1471 case R.id.homepage_menu_id:
1472 TabControl.Tab current = mTabControl.getCurrentTab();
1473 if (current != null) {
1474 dismissSubWindow(current);
1475 current.getWebView().loadUrl(mSettings.getHomePage());
1479 case R.id.preferences_menu_id:
1480 Intent intent = new Intent(this,
1481 BrowserPreferencesPage.class);
1482 startActivityForResult(intent, PREFERENCES_PAGE);
1485 case R.id.find_menu_id:
1486 if (null == mFindDialog) {
1487 mFindDialog = new FindDialog(this);
1489 mFindDialog.setWebView(getTopWindow());
1491 mMenuState = EMPTY_MENU;
1494 case R.id.select_text_id:
1495 getTopWindow().emulateShiftHeld();
1497 case R.id.page_info_menu_id:
1498 showPageInfo(mTabControl.getCurrentTab(), false);
1501 case R.id.classic_history_menu_id:
1502 bookmarksOrHistoryPicker(true);
1505 case R.id.share_page_menu_id:
1506 Browser.sendString(this, getTopWindow().getUrl());
1509 case R.id.dump_nav_menu_id:
1510 getTopWindow().debugDump();
1513 case R.id.zoom_in_menu_id:
1514 getTopWindow().zoomIn();
1517 case R.id.zoom_out_menu_id:
1518 getTopWindow().zoomOut();
1521 case R.id.view_downloads_menu_id:
1522 viewDownloads(null);
1525 case R.id.window_one_menu_id:
1526 case R.id.window_two_menu_id:
1527 case R.id.window_three_menu_id:
1528 case R.id.window_four_menu_id:
1529 case R.id.window_five_menu_id:
1530 case R.id.window_six_menu_id:
1531 case R.id.window_seven_menu_id:
1532 case R.id.window_eight_menu_id:
1534 int menuid = item.getItemId();
1535 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1536 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1537 TabControl.Tab desiredTab = mTabControl.getTab(id);
1538 if (desiredTab != null &&
1539 desiredTab != mTabControl.getCurrentTab()) {
1549 if (!super.onOptionsItemSelected(item)) {
1552 // Otherwise fall through.
1558 public void closeFind() {
1559 mMenuState = R.id.MAIN_MENU;
1562 @Override public boolean onPrepareOptionsMenu(Menu menu)
1564 // This happens when the user begins to hold down the menu key, so
1565 // allow them to chord to get a shortcut.
1567 // Note: setVisible will decide whether an item is visible; while
1568 // setEnabled() will decide whether an item is enabled, which also means
1569 // whether the matching shortcut key will function.
1570 super.onPrepareOptionsMenu(menu);
1571 switch (mMenuState) {
1573 if (mCurrentMenuState != mMenuState) {
1574 menu.setGroupVisible(R.id.MAIN_MENU, false);
1575 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1576 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1580 if (mCurrentMenuState != mMenuState) {
1581 menu.setGroupVisible(R.id.MAIN_MENU, true);
1582 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1583 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1585 final WebView w = getTopWindow();
1586 boolean canGoBack = false;
1587 boolean canGoForward = false;
1588 boolean isHome = false;
1590 canGoBack = w.canGoBack();
1591 canGoForward = w.canGoForward();
1592 isHome = mSettings.getHomePage().equals(w.getUrl());
1594 final MenuItem back = menu.findItem(R.id.back_menu_id);
1595 back.setEnabled(canGoBack);
1597 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1598 home.setEnabled(!isHome);
1600 menu.findItem(R.id.forward_menu_id)
1601 .setEnabled(canGoForward);
1603 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1604 mTabControl.getTabCount() < TabControl.MAX_TABS);
1606 // decide whether to show the share link option
1607 PackageManager pm = getPackageManager();
1608 Intent send = new Intent(Intent.ACTION_SEND);
1609 send.setType("text/plain");
1610 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1611 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1613 boolean isNavDump = mSettings.isNavDump();
1614 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1615 nav.setVisible(isNavDump);
1616 nav.setEnabled(isNavDump);
1619 mCurrentMenuState = mMenuState;
1624 public void onCreateContextMenu(ContextMenu menu, View v,
1625 ContextMenuInfo menuInfo) {
1626 WebView webview = (WebView) v;
1627 WebView.HitTestResult result = webview.getHitTestResult();
1628 if (result == null) {
1632 int type = result.getType();
1633 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1635 "We should not show context menu when nothing is touched");
1638 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1639 // let TextView handles context menu
1643 // Note, http://b/issue?id=1106666 is requesting that
1644 // an inflated menu can be used again. This is not available
1645 // yet, so inflate each time (yuk!)
1646 MenuInflater inflater = getMenuInflater();
1647 inflater.inflate(R.menu.browsercontext, menu);
1649 // Show the correct menu group
1650 String extra = result.getExtra();
1651 menu.setGroupVisible(R.id.PHONE_MENU,
1652 type == WebView.HitTestResult.PHONE_TYPE);
1653 menu.setGroupVisible(R.id.EMAIL_MENU,
1654 type == WebView.HitTestResult.EMAIL_TYPE);
1655 menu.setGroupVisible(R.id.GEO_MENU,
1656 type == WebView.HitTestResult.GEO_TYPE);
1657 menu.setGroupVisible(R.id.IMAGE_MENU,
1658 type == WebView.HitTestResult.IMAGE_TYPE
1659 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1660 menu.setGroupVisible(R.id.ANCHOR_MENU,
1661 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1662 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1664 // Setup custom handling depending on the type
1666 case WebView.HitTestResult.PHONE_TYPE:
1667 menu.setHeaderTitle(Uri.decode(extra));
1668 menu.findItem(R.id.dial_context_menu_id).setIntent(
1669 new Intent(Intent.ACTION_VIEW, Uri
1670 .parse(WebView.SCHEME_TEL + extra)));
1671 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1672 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1673 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1674 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1676 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1680 case WebView.HitTestResult.EMAIL_TYPE:
1681 menu.setHeaderTitle(extra);
1682 menu.findItem(R.id.email_context_menu_id).setIntent(
1683 new Intent(Intent.ACTION_VIEW, Uri
1684 .parse(WebView.SCHEME_MAILTO + extra)));
1685 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1689 case WebView.HitTestResult.GEO_TYPE:
1690 menu.setHeaderTitle(extra);
1691 menu.findItem(R.id.map_context_menu_id).setIntent(
1692 new Intent(Intent.ACTION_VIEW, Uri
1693 .parse(WebView.SCHEME_GEO
1694 + URLEncoder.encode(extra))));
1695 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1699 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1700 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1701 TextView titleView = (TextView) LayoutInflater.from(this)
1702 .inflate(android.R.layout.browser_link_context_header,
1704 titleView.setText(extra);
1705 menu.setHeaderView(titleView);
1706 // decide whether to show the open link in new tab option
1707 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1708 mTabControl.getTabCount() < TabControl.MAX_TABS);
1709 PackageManager pm = getPackageManager();
1710 Intent send = new Intent(Intent.ACTION_SEND);
1711 send.setType("text/plain");
1712 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1713 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1714 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1717 // otherwise fall through to handle image part
1718 case WebView.HitTestResult.IMAGE_TYPE:
1719 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1720 menu.setHeaderTitle(extra);
1722 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1723 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1724 menu.findItem(R.id.download_context_menu_id).
1725 setOnMenuItemClickListener(new Download(extra));
1729 Log.w(LOGTAG, "We should not get here.");
1734 // Attach the given tab to the content view.
1735 private void attachTabToContentView(TabControl.Tab t) {
1736 // Attach the container that contains the main WebView and any other UI
1737 // associated with the tab.
1738 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
1740 if (mShouldShowErrorConsole) {
1741 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1742 if (errorConsole.numberOfErrors() == 0) {
1743 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1745 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1748 mErrorConsoleContainer.addView(errorConsole,
1749 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1750 ViewGroup.LayoutParams.WRAP_CONTENT));
1753 WebView view = t.getWebView();
1754 view.setEmbeddedTitleBar(mTitleBar);
1755 // Attach the sub window if necessary
1757 // Request focus on the top window.
1758 t.getTopWindow().requestFocus();
1761 // Attach a sub window to the main WebView of the given tab.
1762 private void attachSubWindow(TabControl.Tab t) {
1763 // If a sub window exists, attach it to the content view.
1764 final WebView subView = t.getSubWebView();
1765 if (subView != null) {
1766 final View container = t.getSubWebViewContainer();
1767 mContentView.addView(container, COVER_SCREEN_PARAMS);
1768 subView.requestFocus();
1772 // Remove the given tab from the content view.
1773 private void removeTabFromContentView(TabControl.Tab t) {
1774 // Remove the container that contains the main WebView.
1775 mContentView.removeView(t.getContainer());
1777 if (mTabControl.getCurrentErrorConsole(false) != null) {
1778 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
1781 WebView view = t.getWebView();
1783 view.setEmbeddedTitleBar(null);
1786 // Remove the sub window if it exists.
1787 if (t.getSubWebView() != null) {
1788 mContentView.removeView(t.getSubWebViewContainer());
1792 // Remove the sub window if it exists. Also called by TabControl when the
1793 // user clicks the 'X' to dismiss a sub window.
1794 /* package */ void dismissSubWindow(TabControl.Tab t) {
1795 final WebView mainView = t.getWebView();
1796 if (t.getSubWebView() != null) {
1797 // Remove the container view and request focus on the main WebView.
1798 mContentView.removeView(t.getSubWebViewContainer());
1799 mainView.requestFocus();
1800 // Tell the TabControl to dismiss the subwindow. This will destroy
1802 mTabControl.dismissSubWindow(t);
1806 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1807 // that accepts url as string.
1808 private TabControl.Tab openTabAndShow(String url, boolean closeOnExit,
1810 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1813 // This method does a ton of stuff. It will attempt to create a new tab
1814 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1815 // url isn't null, it will load the given url.
1816 /* package */ TabControl.Tab openTabAndShow(UrlData urlData,
1817 boolean closeOnExit, String appId) {
1818 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1819 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1821 final TabControl.Tab tab = mTabControl.createNewTab(
1822 closeOnExit, appId, urlData.mUrl);
1823 WebView webview = tab.getWebView();
1824 // If the last tab was removed from the active tabs page, currentTab
1826 if (currentTab != null) {
1827 removeTabFromContentView(currentTab);
1829 attachTabToContentView(tab);
1830 // We must set the new tab as the current tab to reflect the old
1831 // animation behavior.
1832 mTabControl.setCurrentTab(tab);
1833 if (!urlData.isEmpty()) {
1834 urlData.loadIn(webview);
1838 // Get rid of the subwindow if it exists
1839 dismissSubWindow(currentTab);
1840 if (!urlData.isEmpty()) {
1841 // Load the given url.
1842 urlData.loadIn(currentTab.getWebView());
1848 private TabControl.Tab openTab(String url) {
1849 if (mSettings.openInBackground()) {
1850 TabControl.Tab t = mTabControl.createNewTab();
1852 WebView view = t.getWebView();
1857 return openTabAndShow(url, false, null);
1861 private class Copy implements OnMenuItemClickListener {
1862 private CharSequence mText;
1864 public boolean onMenuItemClick(MenuItem item) {
1869 public Copy(CharSequence toCopy) {
1874 private class Download implements OnMenuItemClickListener {
1875 private String mText;
1877 public boolean onMenuItemClick(MenuItem item) {
1878 onDownloadStartNoStream(mText, null, null, null, -1);
1882 public Download(String toDownload) {
1887 private void copy(CharSequence text) {
1889 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1891 clip.setClipboardText(text);
1893 } catch (android.os.RemoteException e) {
1894 Log.e(LOGTAG, "Copy failed", e);
1899 * Resets the browser title-view to whatever it must be (for example, if we
1900 * load a page from history).
1902 private void resetTitle() {
1904 resetTitleIconAndProgress();
1908 * Resets the browser title-view to whatever it must be
1909 * (for example, if we had a loading error)
1910 * When we have a new page, we call resetTitle, when we
1911 * have to reset the titlebar to whatever it used to be
1912 * (for example, if the user chose to stop loading), we
1913 * call resetTitleAndRevertLockIcon.
1915 /* package */ void resetTitleAndRevertLockIcon() {
1917 resetTitleIconAndProgress();
1921 * Reset the title, favicon, and progress.
1923 private void resetTitleIconAndProgress() {
1924 WebView current = mTabControl.getCurrentWebView();
1925 if (current == null) {
1928 resetTitleAndIcon(current);
1929 int progress = current.getProgress();
1930 mWebChromeClient.onProgressChanged(current, progress);
1933 // Reset the title and the icon based on the given item.
1934 private void resetTitleAndIcon(WebView view) {
1935 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1937 setUrlTitle(item.getUrl(), item.getTitle());
1938 setFavicon(item.getFavicon());
1940 setUrlTitle(null, null);
1946 * Sets a title composed of the URL and the title string.
1947 * @param url The URL of the site being loaded.
1948 * @param title The title of the site being loaded.
1950 private void setUrlTitle(String url, String title) {
1954 mTitleBar.setTitleAndUrl(title, url);
1955 if (mFakeTitleBar != null) {
1956 mFakeTitleBar.setTitleAndUrl(title, url);
1961 * @param url The URL to build a title version of the URL from.
1962 * @return The title version of the URL or null if fails.
1963 * The title version of the URL can be either the URL hostname,
1964 * or the hostname with an "https://" prefix (for secure URLs),
1965 * or an empty string if, for example, the URL in question is a
1966 * file:// URL with no hostname.
1968 /* package */ static String buildTitleUrl(String url) {
1969 String titleUrl = null;
1973 // parse the url string
1974 URL urlObj = new URL(url);
1975 if (urlObj != null) {
1978 String protocol = urlObj.getProtocol();
1979 String host = urlObj.getHost();
1981 if (host != null && 0 < host.length()) {
1983 if (protocol != null) {
1984 // if a secure site, add an "https://" prefix!
1985 if (protocol.equalsIgnoreCase("https")) {
1986 titleUrl = protocol + "://" + host;
1991 } catch (MalformedURLException e) {}
1997 // Set the favicon in the title bar.
1998 private void setFavicon(Bitmap icon) {
1999 mTitleBar.setFavicon(icon);
2000 if (mFakeTitleBar != null) {
2001 mFakeTitleBar.setFavicon(icon);
2006 * Saves the current lock-icon state before resetting
2007 * the lock icon. If we have an error, we may need to
2008 * roll back to the previous state.
2010 private void saveLockIcon() {
2011 mPrevLockType = mLockIconType;
2015 * Reverts the lock-icon state to the last saved state,
2016 * for example, if we had an error, and need to cancel
2019 private void revertLockIcon() {
2020 mLockIconType = mPrevLockType;
2023 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2024 " revert lock icon to " + mLockIconType);
2027 updateLockIconToLatest();
2031 * Close the tab, remove its associated title bar, and adjust mTabControl's
2032 * current tab to a valid value.
2034 /* package */ void closeTab(TabControl.Tab t) {
2035 int currentIndex = mTabControl.getCurrentIndex();
2036 int removeIndex = mTabControl.getTabIndex(t);
2037 mTabControl.removeTab(t);
2038 if (currentIndex >= removeIndex && currentIndex != 0) {
2041 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2044 private void goBackOnePageOrQuit() {
2045 TabControl.Tab current = mTabControl.getCurrentTab();
2046 if (current == null) {
2048 * Instead of finishing the activity, simply push this to the back
2049 * of the stack and let ActivityManager to choose the foreground
2050 * activity. As BrowserActivity is singleTask, it will be always the
2051 * root of the task. So we can use either true or false for
2054 moveTaskToBack(true);
2056 WebView w = current.getWebView();
2057 if (w.canGoBack()) {
2060 // Check to see if we are closing a window that was created by
2061 // another window. If so, we switch back to that window.
2062 TabControl.Tab parent = current.getParentTab();
2063 if (parent != null) {
2064 switchToTab(mTabControl.getTabIndex(parent));
2065 // Now we close the other tab
2068 if (current.closeOnExit()) {
2069 // force mPageStarted to be false as we are going to either
2070 // finish the activity or remove the tab. This will ensure
2071 // pauseWebView() taking action.
2072 mPageStarted = false;
2073 if (mTabControl.getTabCount() == 1) {
2077 // call pauseWebViewTimers() now, we won't be able to call
2078 // it in onPause() as the WebView won't be valid.
2079 // Temporarily change mActivityInPause to be true as
2080 // pauseWebViewTimers() will do nothing if mActivityInPause
2082 boolean savedState = mActivityInPause;
2084 Log.e(LOGTAG, "BrowserActivity is already paused "
2085 + "while handing goBackOnePageOrQuit.");
2087 mActivityInPause = true;
2088 pauseWebViewTimers();
2089 mActivityInPause = savedState;
2090 removeTabFromContentView(current);
2091 mTabControl.removeTab(current);
2094 * Instead of finishing the activity, simply push this to the back
2095 * of the stack and let ActivityManager to choose the foreground
2096 * activity. As BrowserActivity is singleTask, it will be always the
2097 * root of the task. So we can use either true or false for
2100 moveTaskToBack(true);
2105 public KeyTracker.State onKeyTracker(int keyCode,
2107 KeyTracker.Stage stage,
2109 // if onKeyTracker() is called after activity onStop()
2110 // because of accumulated key events,
2111 // we should ignore it as browser is not active any more.
2112 WebView topWindow = getTopWindow();
2113 if (topWindow == null && mCustomView == null)
2114 return KeyTracker.State.NOT_TRACKING;
2116 if (keyCode == KeyEvent.KEYCODE_BACK) {
2117 // Check if a custom view is currently showing and, if it is, hide it.
2118 if (mCustomView != null) {
2119 mWebChromeClient.onHideCustomView();
2120 return KeyTracker.State.DONE_TRACKING;
2122 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2123 bookmarksOrHistoryPicker(true);
2124 return KeyTracker.State.DONE_TRACKING;
2125 } else if (stage == KeyTracker.Stage.UP) {
2126 // FIXME: Currently, we do not have a notion of the
2127 // history picker for the subwindow, but maybe we
2129 WebView subwindow = mTabControl.getCurrentSubWindow();
2130 if (subwindow != null) {
2131 if (subwindow.canGoBack()) {
2134 dismissSubWindow(mTabControl.getCurrentTab());
2137 goBackOnePageOrQuit();
2139 return KeyTracker.State.DONE_TRACKING;
2141 return KeyTracker.State.KEEP_TRACKING;
2143 return KeyTracker.State.NOT_TRACKING;
2146 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2147 if (keyCode == KeyEvent.KEYCODE_MENU) {
2149 } else if (mMenuIsDown) {
2150 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2151 // still down, we don't want to trigger the search. Pretend to
2152 // consume the key and do nothing.
2155 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2158 case KeyEvent.KEYCODE_SPACE:
2159 if (event.isShiftPressed()) {
2160 getTopWindow().pageUp(false);
2162 getTopWindow().pageDown(false);
2171 return handled || super.onKeyDown(keyCode, event);
2174 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2175 if (keyCode == KeyEvent.KEYCODE_MENU) {
2176 mMenuIsDown = false;
2178 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2181 /* package */ void stopLoading() {
2182 resetTitleAndRevertLockIcon();
2183 WebView w = getTopWindow();
2185 mWebViewClient.onPageFinished(w, w.getUrl());
2189 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2193 private void cancelStopToast() {
2194 if (mStopToast != null) {
2195 mStopToast.cancel();
2200 // called by a non-UI thread to post the message
2201 public void postMessage(int what, int arg1, int arg2, Object obj) {
2202 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2205 // public message ids
2206 public final static int LOAD_URL = 1001;
2207 public final static int STOP_LOAD = 1002;
2210 private static final int FOCUS_NODE_HREF = 102;
2211 private static final int CANCEL_CREDS_REQUEST = 103;
2212 private static final int RELEASE_WAKELOCK = 107;
2214 // Private handler for handling javascript and saving passwords
2215 private Handler mHandler = new Handler() {
2217 public void handleMessage(Message msg) {
2219 case FOCUS_NODE_HREF:
2220 String url = (String) msg.getData().get("url");
2221 if (url == null || url.length() == 0) {
2224 HashMap focusNodeMap = (HashMap) msg.obj;
2225 WebView view = (WebView) focusNodeMap.get("webview");
2226 // Only apply the action if the top window did not change.
2227 if (getTopWindow() != view) {
2231 case R.id.open_context_menu_id:
2232 case R.id.view_image_context_menu_id:
2233 loadURL(getTopWindow(), url);
2235 case R.id.open_newtab_context_menu_id:
2236 final TabControl.Tab parent = mTabControl
2238 final TabControl.Tab newTab = openTab(url);
2239 if (newTab != parent) {
2240 parent.addChildTab(newTab);
2243 case R.id.bookmark_context_menu_id:
2244 Intent intent = new Intent(BrowserActivity.this,
2245 AddBookmarkPage.class);
2246 intent.putExtra("url", url);
2247 startActivity(intent);
2249 case R.id.share_link_context_menu_id:
2250 Browser.sendString(BrowserActivity.this, url);
2252 case R.id.copy_link_context_menu_id:
2255 case R.id.save_link_context_menu_id:
2256 case R.id.download_context_menu_id:
2257 onDownloadStartNoStream(url, null, null, null, -1);
2263 loadURL(getTopWindow(), (String) msg.obj);
2270 case CANCEL_CREDS_REQUEST:
2271 resumeAfterCredentials();
2274 case RELEASE_WAKELOCK:
2275 if (mWakeLock.isHeld()) {
2276 mWakeLock.release();
2283 private void updateScreenshot(WebView view) {
2284 // If this is a bookmarked site, add a screenshot to the database.
2285 // FIXME: When should we update? Every time?
2286 // FIXME: Would like to make sure there is actually something to
2287 // draw, but the API for that (WebViewCore.pictureReady()) is not
2288 // currently accessible here.
2289 ContentResolver cr = getContentResolver();
2290 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2291 cr, view.getOriginalUrl(), view.getUrl(), false);
2293 boolean succeed = c.moveToFirst();
2294 ContentValues values = null;
2296 if (values == null) {
2297 final ByteArrayOutputStream os
2298 = new ByteArrayOutputStream();
2299 Picture thumbnail = view.capturePicture();
2300 // Keep width and height in sync with BrowserBookmarksPage
2301 // and bookmark_thumb
2302 Bitmap bm = Bitmap.createBitmap(100, 80,
2303 Bitmap.Config.ARGB_4444);
2304 Canvas canvas = new Canvas(bm);
2305 // May need to tweak these values to determine what is the
2306 // best scale factor
2307 canvas.scale(.5f, .5f);
2308 thumbnail.draw(canvas);
2309 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2310 values = new ContentValues();
2311 values.put(Browser.BookmarkColumns.THUMBNAIL,
2314 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2315 c.getInt(0)), values, null, null);
2316 succeed = c.moveToNext();
2322 // -------------------------------------------------------------------------
2323 // WebViewClient implementation.
2324 //-------------------------------------------------------------------------
2326 // Use in overrideUrlLoading
2327 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2328 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2329 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2330 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2332 /* package */ WebViewClient getWebViewClient() {
2333 return mWebViewClient;
2336 private void updateIcon(WebView view, Bitmap icon) {
2338 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2344 private final WebViewClient mWebViewClient = new WebViewClient() {
2346 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2348 setUrlTitle(url, null);
2350 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2351 if (errorConsole != null) {
2352 errorConsole.clearErrorMessages();
2353 if (mShouldShowErrorConsole) {
2354 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2358 // Call updateIcon instead of setFavicon so the bookmark
2359 // database can be updated.
2360 updateIcon(view, favicon);
2362 if (mSettings.isTracing()) {
2365 WebAddress uri = new WebAddress(url);
2367 } catch (android.net.ParseException ex) {
2370 host = host.replace('.', '_');
2373 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2376 // Performance probe
2378 mStart = SystemClock.uptimeMillis();
2379 mProcessStart = Process.getElapsedCpuTime();
2380 long[] sysCpu = new long[7];
2381 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2383 mUserStart = sysCpu[0] + sysCpu[1];
2384 mSystemStart = sysCpu[2];
2385 mIdleStart = sysCpu[3];
2386 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2388 mUiStart = SystemClock.currentThreadTimeMillis();
2391 if (!mPageStarted) {
2392 mPageStarted = true;
2393 // if onResume() has been called, resumeWebViewTimers() does
2395 resumeWebViewTimers();
2398 // reset sync timer to avoid sync starts during loading a page
2399 CookieSyncManager.getInstance().resetSync();
2402 WebView currentWebView = mTabControl.getCurrentWebView();
2403 if (currentWebView == null || currentWebView.getScrollY() != 0) {
2404 // This page has begun to load, so show the title bar
2407 updateInLoadMenuItems();
2408 if (!mIsNetworkUp) {
2409 if ( mAlertDialog == null) {
2410 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2411 .setTitle(R.string.loadSuspendedTitle)
2412 .setMessage(R.string.loadSuspended)
2413 .setPositiveButton(R.string.ok, null)
2417 view.setNetworkAvailable(false);
2423 public void onPageFinished(WebView view, String url) {
2424 // Reset the title and icon in case we stopped a provisional
2426 resetTitleAndIcon(view);
2428 // Update the lock icon image only once we are done loading
2429 updateLockIconToLatest();
2430 updateScreenshot(view);
2432 // Performance probe
2434 long[] sysCpu = new long[7];
2435 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2437 String uiInfo = "UI thread used "
2438 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2441 Log.d(LOGTAG, uiInfo);
2443 //The string that gets written to the log
2444 String performanceString = "It took total "
2445 + (SystemClock.uptimeMillis() - mStart)
2446 + " ms clock time to load the page."
2447 + "\nbrowser process used "
2448 + (Process.getElapsedCpuTime() - mProcessStart)
2449 + " ms, user processes used "
2450 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2451 + " ms, kernel used "
2452 + (sysCpu[2] - mSystemStart) * 10
2453 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2454 + " ms and irq took "
2455 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2456 * 10 + " ms, " + uiInfo;
2458 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2461 // strip the url to maintain consistency
2462 String newUrl = new String(url);
2463 if (newUrl.startsWith("http://www.")) {
2464 newUrl = newUrl.substring(11);
2465 } else if (newUrl.startsWith("http://")) {
2466 newUrl = newUrl.substring(7);
2467 } else if (newUrl.startsWith("https://www.")) {
2468 newUrl = newUrl.substring(12);
2469 } else if (newUrl.startsWith("https://")) {
2470 newUrl = newUrl.substring(8);
2473 Log.d(LOGTAG, newUrl + " loaded");
2476 if (sWhiteList.contains(newUrl)) {
2477 // The string that gets pushed to the statistcs
2479 performanceString = performanceString
2483 + android.os.SystemProperties
2484 .get("gsm.sim.operator.alpha");
2485 if (mWebView != null
2486 && mWebView.getContext() != null
2487 && mWebView.getContext().getSystemService(
2488 Context.CONNECTIVITY_SERVICE) != null) {
2489 ConnectivityManager cManager =
2490 (ConnectivityManager) mWebView
2491 .getContext().getSystemService(
2492 Context.CONNECTIVITY_SERVICE);
2493 NetworkInfo nInfo = cManager
2494 .getActiveNetworkInfo();
2495 if (nInfo != null) {
2496 performanceString = performanceString
2497 + "\nNetwork Type: "
2498 + nInfo.getType().toString();
2501 Checkin.logEvent(mResolver,
2502 Checkin.Events.Tag.WEBPAGE_LOAD,
2504 Log.w(LOGTAG, "pushed to the statistics service");
2513 Debug.stopMethodTracing();
2517 mPageStarted = false;
2518 // pauseWebViewTimers() will do nothing and return false if
2519 // onPause() is not called yet.
2520 if (pauseWebViewTimers()) {
2521 if (mWakeLock.isHeld()) {
2522 mHandler.removeMessages(RELEASE_WAKELOCK);
2523 mWakeLock.release();
2529 // return true if want to hijack the url to let another app to handle it
2531 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2532 if (url.startsWith(SCHEME_WTAI)) {
2533 // wtai://wp/mc;number
2534 // number=string(phone-number)
2535 if (url.startsWith(SCHEME_WTAI_MC)) {
2536 Intent intent = new Intent(Intent.ACTION_VIEW,
2537 Uri.parse(WebView.SCHEME_TEL +
2538 url.substring(SCHEME_WTAI_MC.length())));
2539 startActivity(intent);
2542 // wtai://wp/sd;dtmf
2543 // dtmf=string(dialstring)
2544 if (url.startsWith(SCHEME_WTAI_SD)) {
2546 // only send when there is active voice connection
2549 // wtai://wp/ap;number;name
2550 // number=string(phone-number)
2552 if (url.startsWith(SCHEME_WTAI_AP)) {
2558 // The "about:" schemes are internal to the browser; don't
2559 // want these to be dispatched to other apps.
2560 if (url.startsWith("about:")) {
2566 // perform generic parsing of the URI to turn it into an Intent.
2568 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2569 } catch (URISyntaxException ex) {
2570 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2574 // check whether the intent can be resolved. If not, we will see
2575 // whether we can download it from the Market.
2576 if (getPackageManager().resolveActivity(intent, 0) == null) {
2577 String packagename = intent.getPackage();
2578 if (packagename != null) {
2579 intent = new Intent(Intent.ACTION_VIEW, Uri
2580 .parse("market://search?q=pname:" + packagename));
2581 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2582 startActivity(intent);
2589 // sanitize the Intent, ensuring web pages can not bypass browser
2590 // security (only access to BROWSABLE activities).
2591 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2592 intent.setComponent(null);
2594 if (startActivityIfNeeded(intent, -1)) {
2597 } catch (ActivityNotFoundException ex) {
2598 // ignore the error. If no application can handle the URL,
2599 // eg about:blank, assume the browser can handle it.
2612 * Updates the lock icon. This method is called when we discover another
2613 * resource to be loaded for this page (for example, javascript). While
2614 * we update the icon type, we do not update the lock icon itself until
2615 * we are done loading, it is slightly more secure this way.
2618 public void onLoadResource(WebView view, String url) {
2619 if (url != null && url.length() > 0) {
2620 // It is only if the page claims to be secure
2621 // that we may have to update the lock:
2622 if (mLockIconType == LOCK_ICON_SECURE) {
2623 // If NOT a 'safe' url, change the lock to mixed content!
2624 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2625 mLockIconType = LOCK_ICON_MIXED;
2627 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2628 " updated lock icon to " + mLockIconType + " due to " + url);
2636 * Show the dialog, asking the user if they would like to continue after
2637 * an excessive number of HTTP redirects.
2640 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2641 final Message continueMsg) {
2642 new AlertDialog.Builder(BrowserActivity.this)
2643 .setTitle(R.string.browserFrameRedirect)
2644 .setMessage(R.string.browserFrame307Post)
2645 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2646 public void onClick(DialogInterface dialog, int which) {
2647 continueMsg.sendToTarget();
2649 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2650 public void onClick(DialogInterface dialog, int which) {
2651 cancelMsg.sendToTarget();
2653 .setOnCancelListener(new OnCancelListener() {
2654 public void onCancel(DialogInterface dialog) {
2655 cancelMsg.sendToTarget();
2660 // Container class for the next error dialog that needs to be
2663 public final int mTitle;
2664 public final String mDescription;
2665 public final int mError;
2666 ErrorDialog(int title, String desc, int error) {
2668 mDescription = desc;
2673 private void processNextError() {
2674 if (mQueuedErrors == null) {
2677 // The first one is currently displayed so just remove it.
2678 mQueuedErrors.removeFirst();
2679 if (mQueuedErrors.size() == 0) {
2680 mQueuedErrors = null;
2683 showError(mQueuedErrors.getFirst());
2686 private DialogInterface.OnDismissListener mDialogListener =
2687 new DialogInterface.OnDismissListener() {
2688 public void onDismiss(DialogInterface d) {
2692 private LinkedList<ErrorDialog> mQueuedErrors;
2694 private void queueError(int err, String desc) {
2695 if (mQueuedErrors == null) {
2696 mQueuedErrors = new LinkedList<ErrorDialog>();
2698 for (ErrorDialog d : mQueuedErrors) {
2699 if (d.mError == err) {
2700 // Already saw a similar error, ignore the new one.
2704 ErrorDialog errDialog = new ErrorDialog(
2705 err == WebViewClient.ERROR_FILE_NOT_FOUND ?
2706 R.string.browserFrameFileErrorLabel :
2707 R.string.browserFrameNetworkErrorLabel,
2709 mQueuedErrors.addLast(errDialog);
2711 // Show the dialog now if the queue was empty.
2712 if (mQueuedErrors.size() == 1) {
2713 showError(errDialog);
2717 private void showError(ErrorDialog errDialog) {
2718 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
2719 .setTitle(errDialog.mTitle)
2720 .setMessage(errDialog.mDescription)
2721 .setPositiveButton(R.string.ok, null)
2723 d.setOnDismissListener(mDialogListener);
2728 * Show a dialog informing the user of the network error reported by
2732 public void onReceivedError(WebView view, int errorCode,
2733 String description, String failingUrl) {
2734 if (errorCode != WebViewClient.ERROR_HOST_LOOKUP &&
2735 errorCode != WebViewClient.ERROR_CONNECT &&
2736 errorCode != WebViewClient.ERROR_BAD_URL &&
2737 errorCode != WebViewClient.ERROR_UNSUPPORTED_SCHEME &&
2738 errorCode != WebViewClient.ERROR_FILE) {
2739 queueError(errorCode, description);
2741 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
2742 + " " + description);
2744 // We need to reset the title after an error.
2745 resetTitleAndRevertLockIcon();
2749 * Check with the user if it is ok to resend POST data as the page they
2750 * are trying to navigate to is the result of a POST.
2753 public void onFormResubmission(WebView view, final Message dontResend,
2754 final Message resend) {
2755 new AlertDialog.Builder(BrowserActivity.this)
2756 .setTitle(R.string.browserFrameFormResubmitLabel)
2757 .setMessage(R.string.browserFrameFormResubmitMessage)
2758 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2759 public void onClick(DialogInterface dialog, int which) {
2760 resend.sendToTarget();
2762 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2763 public void onClick(DialogInterface dialog, int which) {
2764 dontResend.sendToTarget();
2766 .setOnCancelListener(new OnCancelListener() {
2767 public void onCancel(DialogInterface dialog) {
2768 dontResend.sendToTarget();
2774 * Insert the url into the visited history database.
2775 * @param url The url to be inserted.
2776 * @param isReload True if this url is being reloaded.
2777 * FIXME: Not sure what to do when reloading the page.
2780 public void doUpdateVisitedHistory(WebView view, String url,
2782 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2785 // remove "client" before updating it to the history so that it wont
2786 // show up in the auto-complete list.
2787 int index = url.indexOf("client=ms-");
2788 if (index > 0 && url.contains(".google.")) {
2789 int end = url.indexOf('&', index);
2791 url = url.substring(0, index-1).concat(url.substring(end));
2793 url = url.substring(0, index-1);
2796 Browser.updateVisitedHistory(mResolver, url, true);
2797 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2801 * Displays SSL error(s) dialog to the user.
2804 public void onReceivedSslError(
2805 final WebView view, final SslErrorHandler handler, final SslError error) {
2807 if (mSettings.showSecurityWarnings()) {
2808 final LayoutInflater factory =
2809 LayoutInflater.from(BrowserActivity.this);
2810 final View warningsView =
2811 factory.inflate(R.layout.ssl_warnings, null);
2812 final LinearLayout placeholder =
2813 (LinearLayout)warningsView.findViewById(R.id.placeholder);
2815 if (error.hasError(SslError.SSL_UNTRUSTED)) {
2816 LinearLayout ll = (LinearLayout)factory
2817 .inflate(R.layout.ssl_warning, null);
2818 ((TextView)ll.findViewById(R.id.warning))
2819 .setText(R.string.ssl_untrusted);
2820 placeholder.addView(ll);
2823 if (error.hasError(SslError.SSL_IDMISMATCH)) {
2824 LinearLayout ll = (LinearLayout)factory
2825 .inflate(R.layout.ssl_warning, null);
2826 ((TextView)ll.findViewById(R.id.warning))
2827 .setText(R.string.ssl_mismatch);
2828 placeholder.addView(ll);
2831 if (error.hasError(SslError.SSL_EXPIRED)) {
2832 LinearLayout ll = (LinearLayout)factory
2833 .inflate(R.layout.ssl_warning, null);
2834 ((TextView)ll.findViewById(R.id.warning))
2835 .setText(R.string.ssl_expired);
2836 placeholder.addView(ll);
2839 if (error.hasError(SslError.SSL_NOTYETVALID)) {
2840 LinearLayout ll = (LinearLayout)factory
2841 .inflate(R.layout.ssl_warning, null);
2842 ((TextView)ll.findViewById(R.id.warning))
2843 .setText(R.string.ssl_not_yet_valid);
2844 placeholder.addView(ll);
2847 new AlertDialog.Builder(BrowserActivity.this)
2848 .setTitle(R.string.security_warning)
2849 .setIcon(android.R.drawable.ic_dialog_alert)
2850 .setView(warningsView)
2851 .setPositiveButton(R.string.ssl_continue,
2852 new DialogInterface.OnClickListener() {
2853 public void onClick(DialogInterface dialog, int whichButton) {
2857 .setNeutralButton(R.string.view_certificate,
2858 new DialogInterface.OnClickListener() {
2859 public void onClick(DialogInterface dialog, int whichButton) {
2860 showSSLCertificateOnError(view, handler, error);
2863 .setNegativeButton(R.string.cancel,
2864 new DialogInterface.OnClickListener() {
2865 public void onClick(DialogInterface dialog, int whichButton) {
2867 BrowserActivity.this.resetTitleAndRevertLockIcon();
2870 .setOnCancelListener(
2871 new DialogInterface.OnCancelListener() {
2872 public void onCancel(DialogInterface dialog) {
2874 BrowserActivity.this.resetTitleAndRevertLockIcon();
2884 * Handles an HTTP authentication request.
2886 * @param handler The authentication handler
2887 * @param host The host
2888 * @param realm The realm
2891 public void onReceivedHttpAuthRequest(WebView view,
2892 final HttpAuthHandler handler, final String host, final String realm) {
2893 String username = null;
2894 String password = null;
2896 boolean reuseHttpAuthUsernamePassword =
2897 handler.useHttpAuthUsernamePassword();
2899 if (reuseHttpAuthUsernamePassword &&
2900 (mTabControl.getCurrentWebView() != null)) {
2901 String[] credentials =
2902 mTabControl.getCurrentWebView()
2903 .getHttpAuthUsernamePassword(host, realm);
2904 if (credentials != null && credentials.length == 2) {
2905 username = credentials[0];
2906 password = credentials[1];
2910 if (username != null && password != null) {
2911 handler.proceed(username, password);
2913 showHttpAuthentication(handler, host, realm, null, null, null, 0);
2918 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
2920 // only check shortcut key when MENU is held
2921 return getWindow().isShortcutKey(event.getKeyCode(), event);
2928 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
2929 if (view != mTabControl.getCurrentTopWebView()) {
2932 if (event.isDown()) {
2933 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
2935 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
2940 //--------------------------------------------------------------------------
2941 // WebChromeClient implementation
2942 //--------------------------------------------------------------------------
2944 /* package */ WebChromeClient getWebChromeClient() {
2945 return mWebChromeClient;
2948 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
2949 // Helper method to create a new tab or sub window.
2950 private void createWindow(final boolean dialog, final Message msg) {
2952 mTabControl.createSubWindow();
2953 final TabControl.Tab t = mTabControl.getCurrentTab();
2955 WebView.WebViewTransport transport =
2956 (WebView.WebViewTransport) msg.obj;
2957 transport.setWebView(t.getSubWebView());
2960 final TabControl.Tab parent = mTabControl.getCurrentTab();
2961 final TabControl.Tab newTab
2962 = openTabAndShow(EMPTY_URL_DATA, false, null);
2963 if (newTab != parent) {
2964 parent.addChildTab(newTab);
2966 WebView.WebViewTransport transport =
2967 (WebView.WebViewTransport) msg.obj;
2968 transport.setWebView(mTabControl.getCurrentWebView());
2974 public boolean onCreateWindow(WebView view, final boolean dialog,
2975 final boolean userGesture, final Message resultMsg) {
2976 // Short-circuit if we can't create any more tabs or sub windows.
2977 if (dialog && mTabControl.getCurrentSubWindow() != null) {
2978 new AlertDialog.Builder(BrowserActivity.this)
2979 .setTitle(R.string.too_many_subwindows_dialog_title)
2980 .setIcon(android.R.drawable.ic_dialog_alert)
2981 .setMessage(R.string.too_many_subwindows_dialog_message)
2982 .setPositiveButton(R.string.ok, null)
2985 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
2986 new AlertDialog.Builder(BrowserActivity.this)
2987 .setTitle(R.string.too_many_windows_dialog_title)
2988 .setIcon(android.R.drawable.ic_dialog_alert)
2989 .setMessage(R.string.too_many_windows_dialog_message)
2990 .setPositiveButton(R.string.ok, null)
2995 // Short-circuit if this was a user gesture.
2997 createWindow(dialog, resultMsg);
3001 // Allow the popup and create the appropriate window.
3002 final AlertDialog.OnClickListener allowListener =
3003 new AlertDialog.OnClickListener() {
3004 public void onClick(DialogInterface d,
3006 createWindow(dialog, resultMsg);
3010 // Block the popup by returning a null WebView.
3011 final AlertDialog.OnClickListener blockListener =
3012 new AlertDialog.OnClickListener() {
3013 public void onClick(DialogInterface d, int which) {
3014 resultMsg.sendToTarget();
3018 // Build a confirmation dialog to display to the user.
3019 final AlertDialog d =
3020 new AlertDialog.Builder(BrowserActivity.this)
3021 .setTitle(R.string.attention)
3022 .setIcon(android.R.drawable.ic_dialog_alert)
3023 .setMessage(R.string.popup_window_attempt)
3024 .setPositiveButton(R.string.allow, allowListener)
3025 .setNegativeButton(R.string.block, blockListener)
3026 .setCancelable(false)
3029 // Show the confirmation dialog.
3035 public void onCloseWindow(WebView window) {
3036 final TabControl.Tab current = mTabControl.getCurrentTab();
3037 final TabControl.Tab parent = current.getParentTab();
3038 if (parent != null) {
3039 // JavaScript can only close popup window.
3040 switchToTab(mTabControl.getTabIndex(parent));
3041 // Now we need to close the window
3047 public void onProgressChanged(WebView view, int newProgress) {
3048 mTitleBar.setProgress(newProgress);
3049 if (mFakeTitleBar != null) {
3050 mFakeTitleBar.setProgress(newProgress);
3053 if (newProgress == 100) {
3054 // onProgressChanged() is called for sub-frame too while
3055 // onPageFinished() is only called for the main frame. sync
3056 // cookie and cache promptly here.
3057 CookieSyncManager.getInstance().sync();
3060 updateInLoadMenuItems();
3061 // If the options menu is open, leave the title bar
3062 if (!mOptionsMenuOpen || !mIconView) {
3066 } else if (!mInLoad) {
3067 // onPageFinished may have already been called but a subframe
3068 // is still loading and updating the progress. Reset mInLoad
3069 // and update the menu items.
3071 updateInLoadMenuItems();
3072 WebView currentWebView = mTabControl.getCurrentWebView();
3073 if ((currentWebView == null || currentWebView.getScrollY() != 0)
3074 && (!mOptionsMenuOpen || mIconView)) {
3075 // This page has begun to load, so show the title bar
3082 public void onReceivedTitle(WebView view, String title) {
3083 String url = view.getUrl();
3085 // here, if url is null, we want to reset the title
3086 setUrlTitle(url, title);
3089 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3092 // See if we can find the current url in our history database and
3093 // add the new title to it.
3094 if (url.startsWith("http://www.")) {
3095 url = url.substring(11);
3096 } else if (url.startsWith("http://")) {
3097 url = url.substring(4);
3101 String [] selArgs = new String[] { url };
3103 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3104 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3105 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3106 Browser.HISTORY_PROJECTION, where, selArgs, null);
3107 if (c.moveToFirst()) {
3108 // Current implementation of database only has one entry per
3110 ContentValues map = new ContentValues();
3111 map.put(Browser.BookmarkColumns.TITLE, title);
3112 mResolver.update(Browser.BOOKMARKS_URI, map,
3113 "_id = " + c.getInt(0), null);
3116 } catch (IllegalStateException e) {
3117 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3118 } catch (SQLiteException ex) {
3119 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3124 public void onReceivedIcon(WebView view, Bitmap icon) {
3125 updateIcon(view, icon);
3129 public void onReceivedTouchIconUrl(WebView view, String url) {
3130 final ContentResolver cr = getContentResolver();
3132 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
3133 view.getOriginalUrl(), view.getUrl(), true);
3135 if (c.getCount() > 0) {
3136 new DownloadTouchIcon(cr, c, view).execute(url);
3144 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
3145 if (mCustomView != null)
3148 // Add the custom view to its container.
3149 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3151 mCustomViewCallback = callback;
3152 // Save the menu state and set it to empty while the custom
3154 mOldMenuState = mMenuState;
3155 mMenuState = EMPTY_MENU;
3156 // Hide the content view.
3157 mContentView.setVisibility(View.GONE);
3158 // Finally show the custom view container.
3159 mCustomViewContainer.setVisibility(View.VISIBLE);
3160 mCustomViewContainer.bringToFront();
3164 public void onHideCustomView() {
3165 if (mCustomView == null)
3168 // Hide the custom view.
3169 mCustomView.setVisibility(View.GONE);
3170 // Remove the custom view from its container.
3171 mCustomViewContainer.removeView(mCustomView);
3173 // Reset the old menu state.
3174 mMenuState = mOldMenuState;
3175 mOldMenuState = EMPTY_MENU;
3176 mCustomViewContainer.setVisibility(View.GONE);
3177 mCustomViewCallback.onCustomViewHidden();
3178 // Show the content view.
3179 mContentView.setVisibility(View.VISIBLE);
3183 * The origin has exceeded its database quota.
3184 * @param url the URL that exceeded the quota
3185 * @param databaseIdentifier the identifier of the database on
3186 * which the transaction that caused the quota overflow was run
3187 * @param currentQuota the current quota for the origin.
3188 * @param estimatedSize the estimated size of the database.
3189 * @param totalUsedQuota is the sum of all origins' quota.
3190 * @param quotaUpdater The callback to run when a decision to allow or
3191 * deny quota has been made. Don't forget to call this!
3194 public void onExceededDatabaseQuota(String url,
3195 String databaseIdentifier, long currentQuota, long estimatedSize,
3196 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3197 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3198 url, databaseIdentifier, currentQuota, estimatedSize,
3199 totalUsedQuota, quotaUpdater);
3203 * The Application Cache has exceeded its max size.
3204 * @param spaceNeeded is the amount of disk space that would be needed
3205 * in order for the last appcache operation to succeed.
3206 * @param totalUsedQuota is the sum of all origins' quota.
3207 * @param quotaUpdater A callback to inform the WebCore thread that a new
3208 * app cache size is available. This callback must always be executed at
3209 * some point to ensure that the sleeping WebCore thread is woken up.
3212 public void onReachedMaxAppCacheSize(long spaceNeeded,
3213 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3214 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3215 spaceNeeded, totalUsedQuota, quotaUpdater);
3219 * Instructs the browser to show a prompt to ask the user to set the
3220 * Geolocation permission state for the specified origin.
3221 * @param origin The origin for which Geolocation permissions are
3223 * @param callback The callback to call once the user has set the
3224 * Geolocation permission state.
3227 public void onGeolocationPermissionsShowPrompt(String origin,
3228 GeolocationPermissions.Callback callback) {
3229 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3234 * Instructs the browser to hide the Geolocation permissions prompt.
3237 public void onGeolocationPermissionsHidePrompt() {
3238 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3241 /* Adds a JavaScript error message to the system log.
3242 * @param message The error message to report.
3243 * @param lineNumber The line number of the error.
3244 * @param sourceID The name of the source file that caused the error.
3247 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3248 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3249 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3250 if (mShouldShowErrorConsole &&
3251 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3252 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3254 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
3259 * Notify the host application a download should be done, or that
3260 * the data should be streamed if a streaming viewer is available.
3261 * @param url The full url to the content that should be downloaded
3262 * @param contentDisposition Content-disposition http header, if
3264 * @param mimetype The mimetype of the content reported by the server
3265 * @param contentLength The file size reported by the server
3267 public void onDownloadStart(String url, String userAgent,
3268 String contentDisposition, String mimetype, long contentLength) {
3269 // if we're dealing wih A/V content that's not explicitly marked
3270 // for download, check if it's streamable.
3271 if (contentDisposition == null
3272 || !contentDisposition.regionMatches(
3273 true, 0, "attachment", 0, 10)) {
3274 // query the package manager to see if there's a registered handler
3276 Intent intent = new Intent(Intent.ACTION_VIEW);
3277 intent.setDataAndType(Uri.parse(url), mimetype);
3278 ResolveInfo info = getPackageManager().resolveActivity(intent,
3279 PackageManager.MATCH_DEFAULT_ONLY);
3281 ComponentName myName = getComponentName();
3282 // If we resolved to ourselves, we don't want to attempt to
3283 // load the url only to try and download it again.
3284 if (!myName.getPackageName().equals(
3285 info.activityInfo.packageName)
3286 || !myName.getClassName().equals(
3287 info.activityInfo.name)) {
3288 // someone (other than us) knows how to handle this mime
3289 // type with this scheme, don't download.
3291 startActivity(intent);
3293 } catch (ActivityNotFoundException ex) {
3295 Log.d(LOGTAG, "activity not found for " + mimetype
3296 + " over " + Uri.parse(url).getScheme(),
3299 // Best behavior is to fall back to a download in this
3305 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3309 * Notify the host application a download should be done, even if there
3310 * is a streaming viewer available for thise type.
3311 * @param url The full url to the content that should be downloaded
3312 * @param contentDisposition Content-disposition http header, if
3314 * @param mimetype The mimetype of the content reported by the server
3315 * @param contentLength The file size reported by the server
3317 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3318 String contentDisposition, String mimetype, long contentLength) {
3320 String filename = URLUtil.guessFileName(url,
3321 contentDisposition, mimetype);
3323 // Check to see if we have an SDCard
3324 String status = Environment.getExternalStorageState();
3325 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3329 // Check to see if the SDCard is busy, same as the music app
3330 if (status.equals(Environment.MEDIA_SHARED)) {
3331 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3332 title = R.string.download_sdcard_busy_dlg_title;
3334 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3335 title = R.string.download_no_sdcard_dlg_title;
3338 new AlertDialog.Builder(this)
3340 .setIcon(android.R.drawable.ic_dialog_alert)
3342 .setPositiveButton(R.string.ok, null)
3347 // java.net.URI is a lot stricter than KURL so we have to undo
3348 // KURL's percent-encoding and redo the encoding using java.net.URI.
3351 // Undo the percent-encoding that KURL may have done.
3352 String newUrl = new String(URLUtil.decode(url.getBytes()));
3353 // Parse the url into pieces
3354 WebAddress w = new WebAddress(newUrl);
3356 String query = null;
3357 String path = w.mPath;
3358 // Break the path into path, query, and fragment
3359 if (path.length() > 0) {
3360 // Strip the fragment
3361 int idx = path.lastIndexOf('#');
3363 frag = path.substring(idx + 1);
3364 path = path.substring(0, idx);
3366 idx = path.lastIndexOf('?');
3368 query = path.substring(idx + 1);
3369 path = path.substring(0, idx);
3372 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3374 } catch (Exception e) {
3375 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3379 // XXX: Have to use the old url since the cookies were stored using the
3380 // old percent-encoded url.
3381 String cookies = CookieManager.getInstance().getCookie(url);
3383 ContentValues values = new ContentValues();
3384 values.put(Downloads.COLUMN_URI, uri.toString());
3385 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3386 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3387 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
3389 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
3390 BrowserDownloadPage.class.getCanonicalName());
3391 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3392 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3393 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3394 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
3395 if (contentLength > 0) {
3396 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
3398 if (mimetype == null) {
3399 // We must have long pressed on a link or image to download it. We
3400 // are not sure of the mimetype in this case, so do a head request
3401 new FetchUrlMimeType(this).execute(values);
3403 final Uri contentUri =
3404 getContentResolver().insert(Downloads.CONTENT_URI, values);
3405 viewDownloads(contentUri);
3411 * Resets the lock icon. This method is called when we start a new load and
3412 * know the url to be loaded.
3414 private void resetLockIcon(String url) {
3415 // Save the lock-icon state (we revert to it if the load gets cancelled)
3418 mLockIconType = LOCK_ICON_UNSECURE;
3419 if (URLUtil.isHttpsUrl(url)) {
3420 mLockIconType = LOCK_ICON_SECURE;
3422 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3423 " reset lock icon to " + mLockIconType);
3427 updateLockIconImage(LOCK_ICON_UNSECURE);
3431 * Resets the lock icon. This method is called when the icon needs to be
3432 * reset but we do not know whether we are loading a secure or not secure
3435 private void resetLockIcon() {
3436 // Save the lock-icon state (we revert to it if the load gets cancelled)
3439 mLockIconType = LOCK_ICON_UNSECURE;
3442 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3443 " reset lock icon to " + mLockIconType);
3446 updateLockIconImage(LOCK_ICON_UNSECURE);
3450 * Update the lock icon to correspond to our latest state.
3452 /* package */ void updateLockIconToLatest() {
3453 updateLockIconImage(mLockIconType);
3457 * Updates the lock-icon image in the title-bar.
3459 private void updateLockIconImage(int lockIconType) {
3461 if (lockIconType == LOCK_ICON_SECURE) {
3463 } else if (lockIconType == LOCK_ICON_MIXED) {
3466 mTitleBar.setLock(d);
3467 if (mFakeTitleBar != null) {
3468 mFakeTitleBar.setLock(d);
3473 * Displays a page-info dialog.
3474 * @param tab The tab to show info about
3475 * @param fromShowSSLCertificateOnError The flag that indicates whether
3476 * this dialog was opened from the SSL-certificate-on-error dialog or
3477 * not. This is important, since we need to know whether to return to
3478 * the parent dialog or simply dismiss.
3480 private void showPageInfo(final TabControl.Tab tab,
3481 final boolean fromShowSSLCertificateOnError) {
3482 final LayoutInflater factory = LayoutInflater
3485 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3487 final WebView view = tab.getWebView();
3490 String title = null;
3494 title = tab.getTitle();
3495 } else if (view == mTabControl.getCurrentWebView()) {
3496 // Use the cached title and url if this is the current WebView
3500 url = view.getUrl();
3501 title = view.getTitle();
3507 if (title == null) {
3511 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3512 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3514 mPageInfoView = tab;
3515 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3517 AlertDialog.Builder alertDialogBuilder =
3518 new AlertDialog.Builder(this)
3519 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3520 .setView(pageInfoView)
3523 new DialogInterface.OnClickListener() {
3524 public void onClick(DialogInterface dialog,
3526 mPageInfoDialog = null;
3527 mPageInfoView = null;
3528 mPageInfoFromShowSSLCertificateOnError = null;
3530 // if we came here from the SSL error dialog
3531 if (fromShowSSLCertificateOnError) {
3532 // go back to the SSL error dialog
3533 showSSLCertificateOnError(
3534 mSSLCertificateOnErrorView,
3535 mSSLCertificateOnErrorHandler,
3536 mSSLCertificateOnErrorError);
3540 .setOnCancelListener(
3541 new DialogInterface.OnCancelListener() {
3542 public void onCancel(DialogInterface dialog) {
3543 mPageInfoDialog = null;
3544 mPageInfoView = null;
3545 mPageInfoFromShowSSLCertificateOnError = null;
3547 // if we came here from the SSL error dialog
3548 if (fromShowSSLCertificateOnError) {
3549 // go back to the SSL error dialog
3550 showSSLCertificateOnError(
3551 mSSLCertificateOnErrorView,
3552 mSSLCertificateOnErrorHandler,
3553 mSSLCertificateOnErrorError);
3558 // if we have a main top-level page SSL certificate set or a certificate
3560 if (fromShowSSLCertificateOnError ||
3561 (view != null && view.getCertificate() != null)) {
3562 // add a 'View Certificate' button
3563 alertDialogBuilder.setNeutralButton(
3564 R.string.view_certificate,
3565 new DialogInterface.OnClickListener() {
3566 public void onClick(DialogInterface dialog,
3568 mPageInfoDialog = null;
3569 mPageInfoView = null;
3570 mPageInfoFromShowSSLCertificateOnError = null;
3572 // if we came here from the SSL error dialog
3573 if (fromShowSSLCertificateOnError) {
3574 // go back to the SSL error dialog
3575 showSSLCertificateOnError(
3576 mSSLCertificateOnErrorView,
3577 mSSLCertificateOnErrorHandler,
3578 mSSLCertificateOnErrorError);
3580 // otherwise, display the top-most certificate from
3582 if (view.getCertificate() != null) {
3583 showSSLCertificate(tab);
3590 mPageInfoDialog = alertDialogBuilder.show();
3594 * Displays the main top-level page SSL certificate dialog
3595 * (accessible from the Page-Info dialog).
3596 * @param tab The tab to show certificate for.
3598 private void showSSLCertificate(final TabControl.Tab tab) {
3599 final View certificateView =
3600 inflateCertificateView(tab.getWebView().getCertificate());
3601 if (certificateView == null) {
3605 LayoutInflater factory = LayoutInflater.from(this);
3607 final LinearLayout placeholder =
3608 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3610 LinearLayout ll = (LinearLayout) factory.inflate(
3611 R.layout.ssl_success, placeholder);
3612 ((TextView)ll.findViewById(R.id.success))
3613 .setText(R.string.ssl_certificate_is_valid);
3615 mSSLCertificateView = tab;
3616 mSSLCertificateDialog =
3617 new AlertDialog.Builder(this)
3618 .setTitle(R.string.ssl_certificate).setIcon(
3619 R.drawable.ic_dialog_browser_certificate_secure)
3620 .setView(certificateView)
3621 .setPositiveButton(R.string.ok,
3622 new DialogInterface.OnClickListener() {
3623 public void onClick(DialogInterface dialog,
3625 mSSLCertificateDialog = null;
3626 mSSLCertificateView = null;
3628 showPageInfo(tab, false);
3631 .setOnCancelListener(
3632 new DialogInterface.OnCancelListener() {
3633 public void onCancel(DialogInterface dialog) {
3634 mSSLCertificateDialog = null;
3635 mSSLCertificateView = null;
3637 showPageInfo(tab, false);
3644 * Displays the SSL error certificate dialog.
3645 * @param view The target web-view.
3646 * @param handler The SSL error handler responsible for cancelling the
3647 * connection that resulted in an SSL error or proceeding per user request.
3648 * @param error The SSL error object.
3650 private void showSSLCertificateOnError(
3651 final WebView view, final SslErrorHandler handler, final SslError error) {
3653 final View certificateView =
3654 inflateCertificateView(error.getCertificate());
3655 if (certificateView == null) {
3659 LayoutInflater factory = LayoutInflater.from(this);
3661 final LinearLayout placeholder =
3662 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3664 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3665 LinearLayout ll = (LinearLayout)factory
3666 .inflate(R.layout.ssl_warning, placeholder);
3667 ((TextView)ll.findViewById(R.id.warning))
3668 .setText(R.string.ssl_untrusted);
3671 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3672 LinearLayout ll = (LinearLayout)factory
3673 .inflate(R.layout.ssl_warning, placeholder);
3674 ((TextView)ll.findViewById(R.id.warning))
3675 .setText(R.string.ssl_mismatch);
3678 if (error.hasError(SslError.SSL_EXPIRED)) {
3679 LinearLayout ll = (LinearLayout)factory
3680 .inflate(R.layout.ssl_warning, placeholder);
3681 ((TextView)ll.findViewById(R.id.warning))
3682 .setText(R.string.ssl_expired);
3685 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3686 LinearLayout ll = (LinearLayout)factory
3687 .inflate(R.layout.ssl_warning, placeholder);
3688 ((TextView)ll.findViewById(R.id.warning))
3689 .setText(R.string.ssl_not_yet_valid);
3692 mSSLCertificateOnErrorHandler = handler;
3693 mSSLCertificateOnErrorView = view;
3694 mSSLCertificateOnErrorError = error;
3695 mSSLCertificateOnErrorDialog =
3696 new AlertDialog.Builder(this)
3697 .setTitle(R.string.ssl_certificate).setIcon(
3698 R.drawable.ic_dialog_browser_certificate_partially_secure)
3699 .setView(certificateView)
3700 .setPositiveButton(R.string.ok,
3701 new DialogInterface.OnClickListener() {
3702 public void onClick(DialogInterface dialog,
3704 mSSLCertificateOnErrorDialog = null;
3705 mSSLCertificateOnErrorView = null;
3706 mSSLCertificateOnErrorHandler = null;
3707 mSSLCertificateOnErrorError = null;
3709 mWebViewClient.onReceivedSslError(
3710 view, handler, error);
3713 .setNeutralButton(R.string.page_info_view,
3714 new DialogInterface.OnClickListener() {
3715 public void onClick(DialogInterface dialog,
3717 mSSLCertificateOnErrorDialog = null;
3719 // do not clear the dialog state: we will
3720 // need to show the dialog again once the
3721 // user is done exploring the page-info details
3723 showPageInfo(mTabControl.getTabFromView(view),
3727 .setOnCancelListener(
3728 new DialogInterface.OnCancelListener() {
3729 public void onCancel(DialogInterface dialog) {
3730 mSSLCertificateOnErrorDialog = null;
3731 mSSLCertificateOnErrorView = null;
3732 mSSLCertificateOnErrorHandler = null;
3733 mSSLCertificateOnErrorError = null;
3735 mWebViewClient.onReceivedSslError(
3736 view, handler, error);
3743 * Inflates the SSL certificate view (helper method).
3744 * @param certificate The SSL certificate.
3745 * @return The resultant certificate view with issued-to, issued-by,
3746 * issued-on, expires-on, and possibly other fields set.
3747 * If the input certificate is null, returns null.
3749 private View inflateCertificateView(SslCertificate certificate) {
3750 if (certificate == null) {
3754 LayoutInflater factory = LayoutInflater.from(this);
3756 View certificateView = factory.inflate(
3757 R.layout.ssl_certificate, null);
3760 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3761 if (issuedTo != null) {
3762 ((TextView) certificateView.findViewById(R.id.to_common))
3763 .setText(issuedTo.getCName());
3764 ((TextView) certificateView.findViewById(R.id.to_org))
3765 .setText(issuedTo.getOName());
3766 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3767 .setText(issuedTo.getUName());
3771 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3772 if (issuedBy != null) {
3773 ((TextView) certificateView.findViewById(R.id.by_common))
3774 .setText(issuedBy.getCName());
3775 ((TextView) certificateView.findViewById(R.id.by_org))
3776 .setText(issuedBy.getOName());
3777 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3778 .setText(issuedBy.getUName());
3782 String issuedOn = reformatCertificateDate(
3783 certificate.getValidNotBefore());
3784 ((TextView) certificateView.findViewById(R.id.issued_on))
3788 String expiresOn = reformatCertificateDate(
3789 certificate.getValidNotAfter());
3790 ((TextView) certificateView.findViewById(R.id.expires_on))
3791 .setText(expiresOn);
3793 return certificateView;
3797 * Re-formats the certificate date (Date.toString()) string to
3798 * a properly localized date string.
3799 * @return Properly localized version of the certificate date string and
3800 * the original certificate date string if fails to localize.
3801 * If the original string is null, returns an empty string "".
3803 private String reformatCertificateDate(String certificateDate) {
3804 String reformattedDate = null;
3806 if (certificateDate != null) {
3809 date = java.text.DateFormat.getInstance().parse(certificateDate);
3810 } catch (ParseException e) {
3816 DateFormat.getDateFormat(this).format(date);
3820 return reformattedDate != null ? reformattedDate :
3821 (certificateDate != null ? certificateDate : "");
3825 * Displays an http-authentication dialog.
3827 private void showHttpAuthentication(final HttpAuthHandler handler,
3828 final String host, final String realm, final String title,
3829 final String name, final String password, int focusId) {
3830 LayoutInflater factory = LayoutInflater.from(this);
3831 final View v = factory
3832 .inflate(R.layout.http_authentication, null);
3834 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3836 if (password != null) {
3837 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3840 String titleText = title;
3841 if (titleText == null) {
3842 titleText = getText(R.string.sign_in_to).toString().replace(
3843 "%s1", host).replace("%s2", realm);
3846 mHttpAuthHandler = handler;
3847 AlertDialog dialog = new AlertDialog.Builder(this)
3848 .setTitle(titleText)
3849 .setIcon(android.R.drawable.ic_dialog_alert)
3851 .setPositiveButton(R.string.action,
3852 new DialogInterface.OnClickListener() {
3853 public void onClick(DialogInterface dialog,
3855 String nm = ((EditText) v
3856 .findViewById(R.id.username_edit))
3857 .getText().toString();
3858 String pw = ((EditText) v
3859 .findViewById(R.id.password_edit))
3860 .getText().toString();
3861 BrowserActivity.this.setHttpAuthUsernamePassword
3862 (host, realm, nm, pw);
3863 handler.proceed(nm, pw);
3864 mHttpAuthenticationDialog = null;
3865 mHttpAuthHandler = null;
3867 .setNegativeButton(R.string.cancel,
3868 new DialogInterface.OnClickListener() {
3869 public void onClick(DialogInterface dialog,
3872 BrowserActivity.this.resetTitleAndRevertLockIcon();
3873 mHttpAuthenticationDialog = null;
3874 mHttpAuthHandler = null;
3876 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3877 public void onCancel(DialogInterface dialog) {
3879 BrowserActivity.this.resetTitleAndRevertLockIcon();
3880 mHttpAuthenticationDialog = null;
3881 mHttpAuthHandler = null;
3884 // Make the IME appear when the dialog is displayed if applicable.
3885 dialog.getWindow().setSoftInputMode(
3886 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3889 dialog.findViewById(focusId).requestFocus();
3891 v.findViewById(R.id.username_edit).requestFocus();
3893 mHttpAuthenticationDialog = dialog;
3896 public int getProgress() {
3897 WebView w = mTabControl.getCurrentWebView();
3899 return w.getProgress();
3906 * Set HTTP authentication password.
3908 * @param host The host for the password
3909 * @param realm The realm for the password
3910 * @param username The username for the password. If it is null, it means
3911 * password can't be saved.
3912 * @param password The password
3914 public void setHttpAuthUsernamePassword(String host, String realm,
3917 WebView w = mTabControl.getCurrentWebView();
3919 w.setHttpAuthUsernamePassword(host, realm, username, password);
3924 * connectivity manager says net has come or gone... inform the user
3925 * @param up true if net has come up, false if net has gone down
3927 public void onNetworkToggle(boolean up) {
3928 if (up == mIsNetworkUp) {
3931 mIsNetworkUp = true;
3932 if (mAlertDialog != null) {
3933 mAlertDialog.cancel();
3934 mAlertDialog = null;
3937 mIsNetworkUp = false;
3938 if (mInLoad && mAlertDialog == null) {
3939 mAlertDialog = new AlertDialog.Builder(this)
3940 .setTitle(R.string.loadSuspendedTitle)
3941 .setMessage(R.string.loadSuspended)
3942 .setPositiveButton(R.string.ok, null)
3946 WebView w = mTabControl.getCurrentWebView();
3948 w.setNetworkAvailable(up);
3953 protected void onActivityResult(int requestCode, int resultCode,
3955 switch (requestCode) {
3957 if (resultCode == RESULT_OK && intent != null) {
3958 String data = intent.getAction();
3959 Bundle extras = intent.getExtras();
3960 if (extras != null && extras.getBoolean("new_window", false)) {
3963 final TabControl.Tab currentTab =
3964 mTabControl.getCurrentTab();
3965 dismissSubWindow(currentTab);
3966 if (data != null && data.length() != 0) {
3967 getTopWindow().loadUrl(data);
3975 getTopWindow().requestFocus();
3979 * This method is called as a result of the user selecting the options
3980 * menu to see the download window, or when a download changes state. It
3981 * shows the download window ontop of the current window.
3983 /* package */ void viewDownloads(Uri downloadRecord) {
3984 Intent intent = new Intent(this,
3985 BrowserDownloadPage.class);
3986 intent.setData(downloadRecord);
3987 startActivityForResult(intent, this.DOWNLOAD_PAGE);
3993 * @param startWithHistory If true, open starting on the history tab.
3994 * Otherwise, start with the bookmarks tab.
3996 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3997 WebView current = mTabControl.getCurrentWebView();
3998 if (current == null) {
4001 Intent intent = new Intent(this,
4002 CombinedBookmarkHistoryActivity.class);
4003 String title = current.getTitle();
4004 String url = current.getUrl();
4005 // Just in case the user opens bookmarks before a page finishes loading
4006 // so the current history item, and therefore the page, is null.
4008 url = mLastEnteredUrl;
4011 url = mSettings.getHomePage();
4014 // In case the web page has not yet received its associated title.
4015 if (title == null) {
4018 intent.putExtra("title", title);
4019 intent.putExtra("url", url);
4020 // Disable opening in a new window if we have maxed out the windows
4021 intent.putExtra("disable_new_window", mTabControl.getTabCount()
4022 >= TabControl.MAX_TABS);
4023 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
4024 if (startWithHistory) {
4025 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4026 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4028 startActivityForResult(intent, COMBO_PAGE);
4031 // Called when loading from context menu or LOAD_URL message
4032 private void loadURL(WebView view, String url) {
4033 // In case the user enters nothing.
4034 if (url != null && url.length() != 0 && view != null) {
4035 url = smartUrlFilter(url);
4036 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4042 private String smartUrlFilter(Uri inUri) {
4043 if (inUri != null) {
4044 return smartUrlFilter(inUri.toString());
4052 int getWindowCount(){
4053 if(mTabControl != null){
4054 return mTabControl.getTabCount();
4059 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4060 "(?i)" + // switch on case insensitive matching
4061 "(" + // begin group for schema
4062 "(?:http|https|file):\\/\\/" +
4063 "|(?:inline|data|about|content|javascript):" +
4068 * Attempts to determine whether user input is a URL or search
4069 * terms. Anything with a space is passed to search.
4071 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4072 * "Http://" converts to "http://"
4074 * @return Original or modified URL
4077 String smartUrlFilter(String url) {
4079 String inUrl = url.trim();
4080 boolean hasSpace = inUrl.indexOf(' ') != -1;
4082 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4083 if (matcher.matches()) {
4084 // force scheme to lowercase
4085 String scheme = matcher.group(1);
4086 String lcScheme = scheme.toLowerCase();
4087 if (!lcScheme.equals(scheme)) {
4088 inUrl = lcScheme + matcher.group(2);
4091 inUrl = inUrl.replace(" ", "%20");
4096 // FIXME: Is this the correct place to add to searches?
4097 // what if someone else calls this function?
4098 int shortcut = parseUrlShortcut(inUrl);
4099 if (shortcut != SHORTCUT_INVALID) {
4100 Browser.addSearchUrl(mResolver, inUrl);
4101 String query = inUrl.substring(2);
4103 case SHORTCUT_GOOGLE_SEARCH:
4104 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
4105 case SHORTCUT_WIKIPEDIA_SEARCH:
4106 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4107 case SHORTCUT_DICTIONARY_SEARCH:
4108 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4109 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
4110 // FIXME: we need location in this case
4111 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
4115 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4116 return URLUtil.guessUrl(inUrl);
4120 Browser.addSearchUrl(mResolver, inUrl);
4121 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
4124 /* package */ void setShouldShowErrorConsole(boolean flag) {
4125 if (flag == mShouldShowErrorConsole) {
4130 mShouldShowErrorConsole = flag;
4132 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4135 // Setting the show state of the console will cause it's the layout to be inflated.
4136 if (errorConsole.numberOfErrors() > 0) {
4137 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4139 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4142 // Now we can add it to the main view.
4143 mErrorConsoleContainer.addView(errorConsole,
4144 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4145 ViewGroup.LayoutParams.WRAP_CONTENT));
4147 mErrorConsoleContainer.removeView(errorConsole);
4152 private final static int LOCK_ICON_UNSECURE = 0;
4153 private final static int LOCK_ICON_SECURE = 1;
4154 private final static int LOCK_ICON_MIXED = 2;
4156 private int mLockIconType = LOCK_ICON_UNSECURE;
4157 private int mPrevLockType = LOCK_ICON_UNSECURE;
4159 private BrowserSettings mSettings;
4160 private TabControl mTabControl;
4161 private ContentResolver mResolver;
4162 private FrameLayout mContentView;
4163 private View mCustomView;
4164 private FrameLayout mCustomViewContainer;
4165 private WebChromeClient.CustomViewCallback mCustomViewCallback;
4167 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4168 // view, we should rewrite this.
4169 private int mCurrentMenuState = 0;
4170 private int mMenuState = R.id.MAIN_MENU;
4171 private int mOldMenuState = EMPTY_MENU;
4172 private static final int EMPTY_MENU = -1;
4175 private FindDialog mFindDialog;
4176 // Used to prevent chording to result in firing two shortcuts immediately
4177 // one after another. Fixes bug 1211714.
4180 private boolean mInLoad;
4181 private boolean mIsNetworkUp;
4183 private boolean mPageStarted;
4184 private boolean mActivityInPause = true;
4186 private boolean mMenuIsDown;
4188 private final KeyTracker mKeyTracker = new KeyTracker(this);
4190 // As trackball doesn't send repeat down, we have to track it ourselves
4191 private boolean mTrackTrackball;
4193 private static boolean mInTrace;
4195 // Performance probe
4196 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4197 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4198 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4199 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4200 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4201 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4202 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4203 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4204 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4207 private long mStart;
4208 private long mProcessStart;
4209 private long mUserStart;
4210 private long mSystemStart;
4211 private long mIdleStart;
4212 private long mIrqStart;
4214 private long mUiStart;
4216 private Drawable mMixLockIcon;
4217 private Drawable mSecLockIcon;
4219 /* hold a ref so we can auto-cancel if necessary */
4220 private AlertDialog mAlertDialog;
4222 // Wait for credentials before loading google.com
4223 private ProgressDialog mCredsDlg;
4225 // The up-to-date URL and title (these can be different from those stored
4226 // in WebView, since it takes some time for the information in WebView to
4228 private String mUrl;
4229 private String mTitle;
4231 // As PageInfo has different style for landscape / portrait, we have
4232 // to re-open it when configuration changed
4233 private AlertDialog mPageInfoDialog;
4234 private TabControl.Tab mPageInfoView;
4235 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4236 // dialog, we should not just dismiss it, but should get back to the
4237 // SSL-certificate-on-error dialog. This flag is used to store this state
4238 private Boolean mPageInfoFromShowSSLCertificateOnError;
4240 // as SSLCertificateOnError has different style for landscape / portrait,
4241 // we have to re-open it when configuration changed
4242 private AlertDialog mSSLCertificateOnErrorDialog;
4243 private WebView mSSLCertificateOnErrorView;
4244 private SslErrorHandler mSSLCertificateOnErrorHandler;
4245 private SslError mSSLCertificateOnErrorError;
4247 // as SSLCertificate has different style for landscape / portrait, we
4248 // have to re-open it when configuration changed
4249 private AlertDialog mSSLCertificateDialog;
4250 private TabControl.Tab mSSLCertificateView;
4252 // as HttpAuthentication has different style for landscape / portrait, we
4253 // have to re-open it when configuration changed
4254 private AlertDialog mHttpAuthenticationDialog;
4255 private HttpAuthHandler mHttpAuthHandler;
4257 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4258 new FrameLayout.LayoutParams(
4259 ViewGroup.LayoutParams.FILL_PARENT,
4260 ViewGroup.LayoutParams.FILL_PARENT);
4261 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4262 new FrameLayout.LayoutParams(
4263 ViewGroup.LayoutParams.FILL_PARENT,
4264 ViewGroup.LayoutParams.FILL_PARENT,
4267 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4269 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4270 // Dictionary search
4271 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4272 // Google Mobile Local search
4273 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4275 final static String QUERY_PLACE_HOLDER = "%s";
4277 // "source" parameter for Google search through search key
4278 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4279 // "source" parameter for Google search through goto menu
4280 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4281 // "source" parameter for Google search through simplily type
4282 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4283 // "source" parameter for Google search suggested by the browser
4284 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4285 // "source" parameter for Google search from unknown source
4286 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4288 private final static String LOGTAG = "browser";
4290 private String mLastEnteredUrl;
4292 private PowerManager.WakeLock mWakeLock;
4293 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4295 private Toast mStopToast;
4297 private TitleBar mTitleBar;
4299 private LinearLayout mErrorConsoleContainer = null;
4300 private boolean mShouldShowErrorConsole = false;
4302 // As the ids are dynamically created, we can't guarantee that they will
4303 // be in sequence, so this static array maps ids to a window number.
4304 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4305 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4306 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4307 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4309 // monitor platform changes
4310 private IntentFilter mNetworkStateChangedFilter;
4311 private BroadcastReceiver mNetworkStateIntentReceiver;
4313 private BroadcastReceiver mPackageInstallationReceiver;
4315 // activity requestCode
4316 final static int COMBO_PAGE = 1;
4317 final static int DOWNLOAD_PAGE = 2;
4318 final static int PREFERENCES_PAGE = 3;
4321 * A UrlData class to abstract how the content will be set to WebView.
4322 * This base class uses loadUrl to show the content.
4324 private static class UrlData {
4328 UrlData(String url) {
4332 void setPostData(byte[] postData) {
4333 mPostData = postData;
4337 return mUrl == null || mUrl.length() == 0;
4340 public void loadIn(WebView webView) {
4341 if (mPostData != null) {
4342 webView.postUrl(mUrl, mPostData);
4344 webView.loadUrl(mUrl);
4350 * A subclass of UrlData class that can display inlined content using
4351 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4353 private static class InlinedUrlData extends UrlData {
4354 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4357 mMimeType = mimeType;
4358 mEncoding = encoding;
4365 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4369 public void loadIn(WebView webView) {
4370 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4374 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);