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 android.app.Activity;
20 import android.app.AlertDialog;
21 import android.app.ProgressDialog;
22 import android.app.SearchManager;
23 import android.content.ActivityNotFoundException;
24 import android.content.BroadcastReceiver;
25 import android.content.ComponentName;
26 import android.content.ContentProvider;
27 import android.content.ContentProviderClient;
28 import android.content.ContentResolver;
29 import android.content.ContentUris;
30 import android.content.ContentValues;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.pm.PackageInfo;
36 import android.content.pm.PackageManager;
37 import android.content.pm.ResolveInfo;
38 import android.content.res.Configuration;
39 import android.content.res.Resources;
40 import android.database.Cursor;
41 import android.database.DatabaseUtils;
42 import android.graphics.Bitmap;
43 import android.graphics.BitmapFactory;
44 import android.graphics.Canvas;
45 import android.graphics.Picture;
46 import android.graphics.PixelFormat;
47 import android.graphics.Rect;
48 import android.graphics.drawable.Drawable;
49 import android.net.ConnectivityManager;
50 import android.net.NetworkInfo;
51 import android.net.Uri;
52 import android.net.WebAddress;
53 import android.net.http.SslCertificate;
54 import android.net.http.SslError;
55 import android.os.AsyncTask;
56 import android.os.Bundle;
57 import android.os.Debug;
58 import android.os.Environment;
59 import android.os.Handler;
60 import android.os.Message;
61 import android.os.PowerManager;
62 import android.os.Process;
63 import android.os.ServiceManager;
64 import android.os.SystemClock;
65 import android.provider.Browser;
66 import android.provider.ContactsContract;
67 import android.provider.ContactsContract.Intents.Insert;
68 import android.provider.Downloads;
69 import android.provider.MediaStore;
70 import android.text.IClipboard;
71 import android.text.TextUtils;
72 import android.text.format.DateFormat;
73 import android.util.AttributeSet;
74 import android.util.Log;
75 import android.view.ContextMenu;
76 import android.view.Gravity;
77 import android.view.KeyEvent;
78 import android.view.LayoutInflater;
79 import android.view.Menu;
80 import android.view.MenuInflater;
81 import android.view.MenuItem;
82 import android.view.View;
83 import android.view.ViewGroup;
84 import android.view.Window;
85 import android.view.WindowManager;
86 import android.view.ContextMenu.ContextMenuInfo;
87 import android.view.MenuItem.OnMenuItemClickListener;
88 import android.webkit.CookieManager;
89 import android.webkit.CookieSyncManager;
90 import android.webkit.DownloadListener;
91 import android.webkit.HttpAuthHandler;
92 import android.webkit.PluginManager;
93 import android.webkit.SslErrorHandler;
94 import android.webkit.URLUtil;
95 import android.webkit.ValueCallback;
96 import android.webkit.WebChromeClient;
97 import android.webkit.WebHistoryItem;
98 import android.webkit.WebIconDatabase;
99 import android.webkit.WebView;
100 import android.widget.EditText;
101 import android.widget.FrameLayout;
102 import android.widget.LinearLayout;
103 import android.widget.TextView;
104 import android.widget.Toast;
105 import android.accounts.Account;
106 import android.accounts.AccountManager;
107 import android.accounts.AccountManagerFuture;
108 import android.accounts.AuthenticatorException;
109 import android.accounts.OperationCanceledException;
110 import android.accounts.AccountManagerCallback;
112 import com.android.common.Patterns;
114 import com.google.android.gsf.GoogleLoginServiceConstants;
116 import java.io.ByteArrayOutputStream;
118 import java.io.IOException;
119 import java.io.InputStream;
120 import java.net.MalformedURLException;
122 import java.net.URISyntaxException;
124 import java.net.URLEncoder;
125 import java.text.ParseException;
126 import java.util.Date;
127 import java.util.HashMap;
128 import java.util.Iterator;
129 import java.util.Map;
130 import java.util.regex.Matcher;
131 import java.util.regex.Pattern;
133 public class BrowserActivity extends Activity
134 implements View.OnCreateContextMenuListener, DownloadListener,
135 AccountManagerCallback<Account[]> {
137 /* Define some aliases to make these debugging flags easier to refer to.
138 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
140 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
141 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
142 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
144 // These are single-character shortcuts for searching popular sources.
145 private static final int SHORTCUT_INVALID = 0;
146 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
147 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
148 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
149 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
151 private Account[] mAccountsGoogle;
152 private Account[] mAccountsPreferHosted;
154 private void startReadOfGoogleAccounts() {
155 mAccountsGoogle = null;
156 mAccountsPreferHosted = null;
158 AccountManager.get(this).getAccountsByTypeAndFeatures(
159 GoogleLoginServiceConstants.ACCOUNT_TYPE,
160 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
164 /** This implements AccountManagerCallback<Account[]> */
165 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
167 if (mAccountsGoogle == null) {
168 mAccountsGoogle = accountManagerFuture.getResult();
170 AccountManager.get(this).getAccountsByTypeAndFeatures(
171 GoogleLoginServiceConstants.ACCOUNT_TYPE,
172 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
175 mAccountsPreferHosted = accountManagerFuture.getResult();
178 } catch (OperationCanceledException e) {
180 } catch (IOException e) {
182 } catch (AuthenticatorException e) {
187 private void setupHomePage() {
188 // get the default home page
189 String homepage = mSettings.getHomePage();
191 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
194 // hostedUser == googleUser
195 // The device has only a google account
197 // hostedUser != googleUser
198 // The device has a hosted account and a google account
200 // hostedUser != null, googleUser == null
201 // The device has only a hosted account (so far)
202 String hostedUser = mAccountsPreferHosted.length == 0
204 : mAccountsPreferHosted[0].name;
205 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
207 // developers might have no accounts at all
208 if (hostedUser == null) return;
210 if (googleUser == null || !hostedUser.equals(googleUser)) {
211 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
212 homepage = homepage.replace("?", "/a/" + domain + "?");
216 mSettings.setHomePage(BrowserActivity.this, homepage);
217 resumeAfterCredentials();
220 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
222 public Void doInBackground(File... files) {
224 for (File f : files) {
226 Log.e(LOGTAG, f.getPath() + " was not deleted");
235 * This layout holds everything you see below the status bar, including the
236 * error console, the custom view container, and the webviews.
238 private FrameLayout mBrowserFrameLayout;
241 public void onCreate(Bundle icicle) {
243 Log.v(LOGTAG, this + " onStart");
245 super.onCreate(icicle);
246 // test the browser in OpenGL
247 // requestWindowFeature(Window.FEATURE_OPENGL);
249 // enable this to test the browser in 32bit
251 getWindow().setFormat(PixelFormat.RGBX_8888);
252 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
255 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
257 mResolver = getContentResolver();
259 // If this was a web search request, pass it on to the default web
260 // search provider and finish this activity.
261 if (handleWebSearchIntent(getIntent())) {
266 mSecLockIcon = Resources.getSystem().getDrawable(
267 android.R.drawable.ic_secure);
268 mMixLockIcon = Resources.getSystem().getDrawable(
269 android.R.drawable.ic_partial_secure);
271 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
272 .findViewById(com.android.internal.R.id.content);
273 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
274 .inflate(R.layout.custom_screen, null);
275 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
277 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
278 .findViewById(R.id.error_console);
279 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
280 .findViewById(R.id.fullscreen_custom_content);
281 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
282 mTitleBar = new TitleBar(this);
283 mFakeTitleBar = new TitleBar(this);
285 // Create the tab control and our initial tab
286 mTabControl = new TabControl(this);
288 // Open the icon database and retain all the bookmark urls for favicons
289 retainIconsOnStartup();
291 // Keep a settings instance handy.
292 mSettings = BrowserSettings.getInstance();
293 mSettings.setTabControl(mTabControl);
294 mSettings.loadFromDb(this);
296 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
297 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
299 /* enables registration for changes in network status from
301 mNetworkStateChangedFilter = new IntentFilter();
302 mNetworkStateChangedFilter.addAction(
303 ConnectivityManager.CONNECTIVITY_ACTION);
304 mNetworkStateIntentReceiver = new BroadcastReceiver() {
306 public void onReceive(Context context, Intent intent) {
307 if (intent.getAction().equals(
308 ConnectivityManager.CONNECTIVITY_ACTION)) {
309 boolean noConnectivity = intent.getBooleanExtra(
310 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
311 if (!noConnectivity) {
312 NetworkInfo info = intent.getParcelableExtra(
313 ConnectivityManager.EXTRA_NETWORK_INFO);
314 String typeName = info.getTypeName();
315 String subtypeName = info.getSubtypeName();
316 sendNetworkType(typeName.toLowerCase(),
317 (subtypeName != null ? subtypeName.toLowerCase() : ""));
319 onNetworkToggle(!noConnectivity);
324 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
325 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
326 filter.addDataScheme("package");
327 mPackageInstallationReceiver = new BroadcastReceiver() {
329 public void onReceive(Context context, Intent intent) {
330 final String action = intent.getAction();
331 final String packageName = intent.getData()
332 .getSchemeSpecificPart();
333 final boolean replacing = intent.getBooleanExtra(
334 Intent.EXTRA_REPLACING, false);
335 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
336 // if it is replacing, refreshPlugins() when adding
339 PackageManager pm = BrowserActivity.this.getPackageManager();
340 PackageInfo pkgInfo = null;
342 pkgInfo = pm.getPackageInfo(packageName,
343 PackageManager.GET_PERMISSIONS);
344 } catch (PackageManager.NameNotFoundException e) {
347 if (pkgInfo != null) {
348 String permissions[] = pkgInfo.requestedPermissions;
349 if (permissions == null) {
352 boolean permissionOk = false;
353 for (String permit : permissions) {
354 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
360 PluginManager.getInstance(BrowserActivity.this)
362 Intent.ACTION_PACKAGE_ADDED
368 registerReceiver(mPackageInstallationReceiver, filter);
370 if (!mTabControl.restoreState(icicle)) {
371 // clear up the thumbnail directory if we can't restore the state as
372 // none of the files in the directory are referenced any more.
373 new ClearThumbnails().execute(
374 mTabControl.getThumbnailDir().listFiles());
375 // there is no quit on Android. But if we can't restore the state,
376 // we can treat it as a new Browser, remove the old session cookies.
377 CookieManager.getInstance().removeSessionCookie();
378 final Intent intent = getIntent();
379 final Bundle extra = intent.getExtras();
380 // Create an initial tab.
381 // If the intent is ACTION_VIEW and data is not null, the Browser is
382 // invoked to view the content by another application. In this case,
383 // the tab will be close when exit.
384 UrlData urlData = getUrlDataFromIntent(intent);
386 String action = intent.getAction();
387 final Tab t = mTabControl.createNewTab(
388 (Intent.ACTION_VIEW.equals(action) &&
389 intent.getData() != null)
390 || Tab.VoiceSearchData.VOICE_SEARCH_RESULTS.equals(action),
391 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
392 mTabControl.setCurrentTab(t);
393 attachTabToContentView(t);
394 WebView webView = t.getWebView();
396 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
397 if (scale > 0 && scale <= 1000) {
398 webView.setInitialScale(scale);
401 // If we are not restoring from an icicle, then there is a high
402 // likely hood this is the first run. So, check to see if the
403 // homepage needs to be configured and copy any plugins from our
404 // asset directory to the data partition.
405 if ((extra == null || !extra.getBoolean("testing"))
406 && !mSettings.isLoginInitialized()) {
407 startReadOfGoogleAccounts();
410 if (urlData.isEmpty()) {
411 if (mSettings.isLoginInitialized()) {
412 webView.loadUrl(mSettings.getHomePage());
414 waitForCredentials();
420 // TabControl.restoreState() will create a new tab even if
421 // restoring the state fails.
422 attachTabToContentView(mTabControl.getCurrentTab());
425 // Read JavaScript flags if it exists.
426 String jsFlags = mSettings.getJsFlags();
427 if (jsFlags.trim().length() != 0) {
428 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
433 * Feed the previously stored results strings to the BrowserProvider so that
434 * the SearchDialog will show them instead of the standard searches.
435 * @param result String to show on the editable line of the SearchDialog.
437 /* package */ void showVoiceSearchResults(String result) {
438 ContentProviderClient client = mResolver.acquireContentProviderClient(
439 Browser.BOOKMARKS_URI);
440 ContentProvider prov = client.getLocalContentProvider();
441 BrowserProvider bp = (BrowserProvider) prov;
442 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
445 startSearch(result, false,
446 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
451 protected void onNewIntent(Intent intent) {
452 Tab current = mTabControl.getCurrentTab();
453 // When a tab is closed on exit, the current tab index is set to -1.
454 // Reset before proceed as Browser requires the current tab to be set.
455 if (current == null) {
456 // Try to reset the tab in case the index was incorrect.
457 current = mTabControl.getTab(0);
458 if (current == null) {
459 // No tabs at all so just ignore this intent.
462 mTabControl.setCurrentTab(current);
463 attachTabToContentView(current);
464 resetTitleAndIcon(current.getWebView());
466 final String action = intent.getAction();
467 final int flags = intent.getFlags();
468 if (Intent.ACTION_MAIN.equals(action) ||
469 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
470 // just resume the browser
473 boolean activateVoiceSearch = Tab.VoiceSearchData.VOICE_SEARCH_RESULTS
475 if (Intent.ACTION_VIEW.equals(action)
476 || Intent.ACTION_SEARCH.equals(action)
477 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
478 || Intent.ACTION_WEB_SEARCH.equals(action)
479 || activateVoiceSearch) {
480 // If this was a search request (e.g. search query directly typed into the address bar),
481 // pass it on to the default web search provider.
482 if (handleWebSearchIntent(intent)) {
486 UrlData urlData = getUrlDataFromIntent(intent);
487 if (urlData.isEmpty()) {
488 urlData = new UrlData(mSettings.getHomePage());
491 final String appId = intent
492 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
493 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
494 && !getPackageName().equals(appId)
495 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
496 Tab appTab = mTabControl.getTabFromId(appId);
497 if (appTab != null) {
498 Log.i(LOGTAG, "Reusing tab for " + appId);
499 // Dismiss the subwindow if applicable.
500 dismissSubWindow(appTab);
501 // Since we might kill the WebView, remove it from the
502 // content view first.
503 removeTabFromContentView(appTab);
504 // Recreate the main WebView after destroying the old one.
505 // If the WebView has the same original url and is on that
506 // page, it can be reused.
508 mTabControl.recreateWebView(appTab, urlData.mUrl);
510 if (current != appTab) {
511 switchToTab(mTabControl.getTabIndex(appTab));
513 urlData.loadIn(appTab);
516 // If the tab was the current tab, we have to attach
517 // it to the view system again.
518 attachTabToContentView(appTab);
520 urlData.loadIn(appTab);
525 // No matching application tab, try to find a regular tab
526 // with a matching url.
527 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
528 if (appTab != null) {
529 if (current != appTab) {
530 switchToTab(mTabControl.getTabIndex(appTab));
532 // Otherwise, we are already viewing the correct tab.
534 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
535 // will be opened in a new tab unless we have reached
536 // MAX_TABS. Then the url will be opened in the current
537 // tab. If a new tab is created, it will have "true" for
539 openTabAndShow(urlData, true, appId);
543 if (!urlData.isEmpty()
544 && urlData.mUrl.startsWith("about:debug")) {
545 if ("about:debug.dom".equals(urlData.mUrl)) {
546 current.getWebView().dumpDomTree(false);
547 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
548 current.getWebView().dumpDomTree(true);
549 } else if ("about:debug.render".equals(urlData.mUrl)) {
550 current.getWebView().dumpRenderTree(false);
551 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
552 current.getWebView().dumpRenderTree(true);
553 } else if ("about:debug.display".equals(urlData.mUrl)) {
554 current.getWebView().dumpDisplayTree();
555 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
556 int index = urlData.mUrl.codePointAt(16) - '0';
557 if (index <= 0 || index > 9) {
558 current.getWebView().setDragTracker(null);
560 current.getWebView().setDragTracker(new MeshTracker(index));
563 mSettings.toggleDebugSettings();
567 // Get rid of the subwindow if it exists
568 dismissSubWindow(current);
569 urlData.loadIn(current);
574 private int parseUrlShortcut(String url) {
575 if (url == null) return SHORTCUT_INVALID;
577 // FIXME: quick search, need to be customized by setting
578 if (url.length() > 2 && url.charAt(1) == ' ') {
579 switch (url.charAt(0)) {
580 case 'g': return SHORTCUT_GOOGLE_SEARCH;
581 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
582 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
583 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
586 return SHORTCUT_INVALID;
590 * Launches the default web search activity with the query parameters if the given intent's data
591 * are identified as plain search terms and not URLs/shortcuts.
592 * @return true if the intent was handled and web search activity was launched, false if not.
594 private boolean handleWebSearchIntent(Intent intent) {
595 if (intent == null) return false;
598 final String action = intent.getAction();
599 if (Tab.VoiceSearchData.VOICE_SEARCH_RESULTS.equals(action)) {
602 if (Intent.ACTION_VIEW.equals(action)) {
603 Uri data = intent.getData();
604 if (data != null) url = data.toString();
605 } else if (Intent.ACTION_SEARCH.equals(action)
606 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
607 || Intent.ACTION_WEB_SEARCH.equals(action)) {
608 url = intent.getStringExtra(SearchManager.QUERY);
610 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
611 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
615 * Launches the default web search activity with the query parameters if the given url string
616 * was identified as plain search terms and not URL/shortcut.
617 * @return true if the request was handled and web search activity was launched, false if not.
619 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
620 if (inUrl == null) return false;
622 // In general, we shouldn't modify URL from Intent.
623 // But currently, we get the user-typed URL from search box as well.
624 String url = fixUrl(inUrl).trim();
626 // URLs and site specific search shortcuts are handled by the regular flow of control, so
628 if (Patterns.WEB_URL.matcher(url).matches()
629 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
630 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
634 Browser.updateVisitedHistory(mResolver, url, false);
635 Browser.addSearchUrl(mResolver, url);
637 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
638 intent.addCategory(Intent.CATEGORY_DEFAULT);
639 intent.putExtra(SearchManager.QUERY, url);
640 if (appData != null) {
641 intent.putExtra(SearchManager.APP_DATA, appData);
643 if (extraData != null) {
644 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
646 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
647 startActivity(intent);
652 private UrlData getUrlDataFromIntent(Intent intent) {
654 Map<String, String> headers = null;
655 if (intent != null) {
656 final String action = intent.getAction();
657 if (Intent.ACTION_VIEW.equals(action)) {
658 url = smartUrlFilter(intent.getData());
659 if (url != null && url.startsWith("content:")) {
660 /* Append mimetype so webview knows how to display */
661 String mimeType = intent.resolveType(getContentResolver());
662 if (mimeType != null) {
663 url += "?" + mimeType;
666 if (url != null && url.startsWith("http")) {
667 final Bundle pairs = intent
668 .getBundleExtra(Browser.EXTRA_HEADERS);
669 if (pairs != null && !pairs.isEmpty()) {
670 Iterator<String> iter = pairs.keySet().iterator();
671 headers = new HashMap<String, String>();
672 while (iter.hasNext()) {
673 String key = iter.next();
674 headers.put(key, pairs.getString(key));
678 } else if (Intent.ACTION_SEARCH.equals(action)
679 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
680 || Intent.ACTION_WEB_SEARCH.equals(action)) {
681 url = intent.getStringExtra(SearchManager.QUERY);
683 mLastEnteredUrl = url;
684 Browser.updateVisitedHistory(mResolver, url, false);
685 // In general, we shouldn't modify URL from Intent.
686 // But currently, we get the user-typed URL from search box as well.
688 url = smartUrlFilter(url);
689 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
690 if (url.contains(searchSource)) {
691 String source = null;
692 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
693 if (appData != null) {
694 source = appData.getString(SearchManager.SOURCE);
696 if (TextUtils.isEmpty(source)) {
697 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
699 url = url.replace(searchSource, "&source=android-"+source+"&");
704 return new UrlData(url, headers, intent);
706 /* package */ void showVoiceTitleBar(String title) {
707 mTitleBar.setInVoiceMode(true);
708 mFakeTitleBar.setInVoiceMode(true);
710 mTitleBar.setDisplayTitle(title);
711 mFakeTitleBar.setDisplayTitle(title);
713 /* package */ void revertVoiceTitleBar() {
714 mTitleBar.setInVoiceMode(false);
715 mFakeTitleBar.setInVoiceMode(false);
717 mTitleBar.setDisplayTitle(mTitle);
718 mFakeTitleBar.setDisplayTitle(mTitle);
720 /* package */ static String fixUrl(String inUrl) {
721 // FIXME: Converting the url to lower case
722 // duplicates functionality in smartUrlFilter().
723 // However, changing all current callers of fixUrl to
724 // call smartUrlFilter in addition may have unwanted
725 // consequences, and is deferred for now.
726 int colon = inUrl.indexOf(':');
727 boolean allLower = true;
728 for (int index = 0; index < colon; index++) {
729 char ch = inUrl.charAt(index);
730 if (!Character.isLetter(ch)) {
733 allLower &= Character.isLowerCase(ch);
734 if (index == colon - 1 && !allLower) {
735 inUrl = inUrl.substring(0, colon).toLowerCase()
736 + inUrl.substring(colon);
739 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
741 if (inUrl.startsWith("http:") ||
742 inUrl.startsWith("https:")) {
743 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
744 inUrl = inUrl.replaceFirst("/", "//");
745 } else inUrl = inUrl.replaceFirst(":", "://");
751 protected void onResume() {
754 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
757 if (!mActivityInPause) {
758 Log.e(LOGTAG, "BrowserActivity is already resumed.");
762 mTabControl.resumeCurrentTab();
763 mActivityInPause = false;
764 resumeWebViewTimers();
766 if (mWakeLock.isHeld()) {
767 mHandler.removeMessages(RELEASE_WAKELOCK);
771 if (mCredsDlg != null) {
772 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
773 // In case credential request never comes back
774 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
778 registerReceiver(mNetworkStateIntentReceiver,
779 mNetworkStateChangedFilter);
780 WebView.enablePlatformNotifications();
784 * Since the actual title bar is embedded in the WebView, and removing it
785 * would change its appearance, use a different TitleBar to show overlayed
786 * at the top of the screen, when the menu is open or the page is loading.
788 private TitleBar mFakeTitleBar;
791 * Holder for the fake title bar. It will have a foreground shadow, as well
792 * as a white background, so the fake title bar looks like the real one.
794 private ViewGroup mFakeTitleBarHolder;
797 * Layout parameters for the fake title bar within mFakeTitleBarHolder
799 private FrameLayout.LayoutParams mFakeTitleBarParams
800 = new FrameLayout.LayoutParams(
801 ViewGroup.LayoutParams.MATCH_PARENT,
802 ViewGroup.LayoutParams.WRAP_CONTENT);
804 * Keeps track of whether the options menu is open. This is important in
805 * determining whether to show or hide the title bar overlay.
807 private boolean mOptionsMenuOpen;
810 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
811 * of whether the configuration has changed. The first onMenuOpened call
812 * after a configuration change is simply a reopening of the same menu
813 * (i.e. mIconView did not change).
815 private boolean mConfigChanged;
818 * Whether or not the options menu is in its smaller, icon menu form. When
819 * true, we want the title bar overlay to be up. When false, we do not.
820 * Only meaningful if mOptionsMenuOpen is true.
822 private boolean mIconView;
825 public boolean onMenuOpened(int featureId, Menu menu) {
826 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
827 if (mOptionsMenuOpen) {
828 if (mConfigChanged) {
829 // We do not need to make any changes to the state of the
830 // title bar, since the only thing that happened was a
831 // change in orientation
832 mConfigChanged = false;
835 // Switching the menu to expanded view, so hide the
840 // Switching the menu back to icon view, so show the
841 // title bar once again.
847 // The options menu is closed, so open it, and show the title
849 mOptionsMenuOpen = true;
850 mConfigChanged = false;
858 * Special class used exclusively for the shadow drawn underneath the fake
859 * title bar. The shadow does not need to be drawn if the WebView
860 * underneath is scrolled to the top, because it will draw directly on top
861 * of the embedded shadow.
863 private static class Shadow extends View {
864 private WebView mWebView;
866 public Shadow(Context context, AttributeSet attrs) {
867 super(context, attrs);
870 public void setWebView(WebView view) {
875 public void draw(Canvas canvas) {
876 // In general onDraw is the method to override, but we care about
877 // whether or not the background gets drawn, which happens in draw()
878 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
881 // Need to invalidate so that if the scroll position changes, we
882 // still draw as appropriate.
887 private void showFakeTitleBar() {
888 final View decor = getWindow().peekDecorView();
889 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
890 && !mActivityInPause && decor != null
891 && decor.getWindowToken() != null) {
892 Rect visRect = new Rect();
893 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
895 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
900 WindowManager manager
901 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
903 // Add the title bar to the window manager so it can receive touches
904 // while the menu is up
905 WindowManager.LayoutParams params
906 = new WindowManager.LayoutParams(
907 ViewGroup.LayoutParams.MATCH_PARENT,
908 ViewGroup.LayoutParams.WRAP_CONTENT,
909 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
910 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
911 PixelFormat.TRANSLUCENT);
912 params.gravity = Gravity.TOP;
913 WebView mainView = mTabControl.getCurrentWebView();
914 boolean atTop = mainView != null && mainView.getScrollY() == 0;
915 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
916 // XXX : Without providing an offset, the fake title bar will be
917 // placed underneath the status bar. Use the global visible rect
918 // of mBrowserFrameLayout to determine the bottom of the status bar
919 params.y = visRect.top;
920 // Add a holder for the title bar. It also holds a shadow to show
921 // below the title bar.
922 if (mFakeTitleBarHolder == null) {
923 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
924 .inflate(R.layout.title_bar_bg, null);
926 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
928 shadow.setWebView(mainView);
929 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
930 manager.addView(mFakeTitleBarHolder, params);
935 public void onOptionsMenuClosed(Menu menu) {
936 mOptionsMenuOpen = false;
939 } else if (!mIconView) {
940 // The page is currently loading, and we are in expanded mode, so
941 // we were not showing the menu. Show it once again. It will be
942 // removed when the page finishes.
947 private void hideFakeTitleBar() {
948 if (mFakeTitleBar.getParent() == null) return;
949 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
950 mFakeTitleBarHolder.getLayoutParams();
951 WebView mainView = mTabControl.getCurrentWebView();
952 // Although we decided whether or not to animate based on the current
953 // scroll position, the scroll position may have changed since the
954 // fake title bar was displayed. Make sure it has the appropriate
955 // animation/lack thereof before removing.
956 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
957 ? 0 : R.style.TitleBar;
958 WindowManager manager
959 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
960 manager.updateViewLayout(mFakeTitleBarHolder, params);
961 mFakeTitleBarHolder.removeView(mFakeTitleBar);
962 manager.removeView(mFakeTitleBarHolder);
966 * Special method for the fake title bar to call when displaying its context
967 * menu, since it is in its own Window, and its parent does not show a
970 /* package */ void showTitleBarContextMenu() {
971 if (null == mTitleBar.getParent()) {
974 openContextMenu(mTitleBar);
978 public void onContextMenuClosed(Menu menu) {
979 super.onContextMenuClosed(menu);
986 * onSaveInstanceState(Bundle map)
987 * onSaveInstanceState is called right before onStop(). The map contains
991 protected void onSaveInstanceState(Bundle outState) {
993 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
995 // the default implementation requires each view to have an id. As the
996 // browser handles the state itself and it doesn't use id for the views,
997 // don't call the default implementation. Otherwise it will trigger the
998 // warning like this, "couldn't save which view has focus because the
999 // focused view XXX has no id".
1001 // Save all the tabs
1002 mTabControl.saveState(outState);
1006 protected void onPause() {
1009 if (mActivityInPause) {
1010 Log.e(LOGTAG, "BrowserActivity is already paused.");
1014 mTabControl.pauseCurrentTab();
1015 mActivityInPause = true;
1016 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1017 mWakeLock.acquire();
1018 mHandler.sendMessageDelayed(mHandler
1019 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1022 // Clear the credentials toast if it is up
1023 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1024 mCredsDlg.dismiss();
1028 // FIXME: This removes the active tabs page and resets the menu to
1029 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1030 // but then we would need to save it in onSaveInstanceState and restore
1031 // it in onCreate/onRestoreInstanceState
1032 if (mActiveTabsPage != null) {
1033 removeActiveTabPage(true);
1038 // unregister network state listener
1039 unregisterReceiver(mNetworkStateIntentReceiver);
1040 WebView.disablePlatformNotifications();
1044 protected void onDestroy() {
1046 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1050 if (mUploadMessage != null) {
1051 mUploadMessage.onReceiveValue(null);
1052 mUploadMessage = null;
1055 if (mTabControl == null) return;
1057 // Remove the fake title bar if it is there
1060 // Remove the current tab and sub window
1061 Tab t = mTabControl.getCurrentTab();
1063 dismissSubWindow(t);
1064 removeTabFromContentView(t);
1066 // Destroy all the tabs
1067 mTabControl.destroy();
1068 WebIconDatabase.getInstance().close();
1070 unregisterReceiver(mPackageInstallationReceiver);
1074 public void onConfigurationChanged(Configuration newConfig) {
1075 mConfigChanged = true;
1076 super.onConfigurationChanged(newConfig);
1078 if (mPageInfoDialog != null) {
1079 mPageInfoDialog.dismiss();
1082 mPageInfoFromShowSSLCertificateOnError);
1084 if (mSSLCertificateDialog != null) {
1085 mSSLCertificateDialog.dismiss();
1087 mSSLCertificateView);
1089 if (mSSLCertificateOnErrorDialog != null) {
1090 mSSLCertificateOnErrorDialog.dismiss();
1091 showSSLCertificateOnError(
1092 mSSLCertificateOnErrorView,
1093 mSSLCertificateOnErrorHandler,
1094 mSSLCertificateOnErrorError);
1096 if (mHttpAuthenticationDialog != null) {
1097 String title = ((TextView) mHttpAuthenticationDialog
1098 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1100 String name = ((TextView) mHttpAuthenticationDialog
1101 .findViewById(R.id.username_edit)).getText().toString();
1102 String password = ((TextView) mHttpAuthenticationDialog
1103 .findViewById(R.id.password_edit)).getText().toString();
1104 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1106 mHttpAuthenticationDialog.dismiss();
1107 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1108 name, password, focusId);
1113 public void onLowMemory() {
1114 super.onLowMemory();
1115 mTabControl.freeMemory();
1118 private boolean resumeWebViewTimers() {
1119 Tab tab = mTabControl.getCurrentTab();
1120 boolean inLoad = tab.inLoad();
1121 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1122 CookieSyncManager.getInstance().startSync();
1123 WebView w = tab.getWebView();
1133 private boolean pauseWebViewTimers() {
1134 Tab tab = mTabControl.getCurrentTab();
1135 boolean inLoad = tab.inLoad();
1136 if (mActivityInPause && !inLoad) {
1137 CookieSyncManager.getInstance().stopSync();
1138 WebView w = mTabControl.getCurrentWebView();
1148 // FIXME: Do we want to call this when loading google for the first time?
1150 * This function is called when we are launching for the first time. We
1151 * are waiting for the login credentials before loading Google home
1152 * pages. This way the user will be logged in straight away.
1154 private void waitForCredentials() {
1156 mCredsDlg = new ProgressDialog(this);
1157 mCredsDlg.setIndeterminate(true);
1158 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1159 // If the user cancels the operation, then cancel the Google
1160 // Credentials request.
1161 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1164 // We set a timeout for the retrieval of credentials in onResume()
1165 // as that is when we have freed up some CPU time to get
1166 // the login credentials.
1170 * If we have received the credentials or we have timed out and we are
1171 * showing the credentials dialog, then it is time to move on.
1173 private void resumeAfterCredentials() {
1174 if (mCredsDlg == null) {
1179 if (mCredsDlg.isShowing()) {
1180 mCredsDlg.dismiss();
1184 // Clear any pending timeout
1185 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1188 WebView w = mTabControl.getCurrentWebView();
1190 w.loadUrl(mSettings.getHomePage());
1193 // Update the settings, need to do this last as it can take a moment
1194 // to persist the settings. In the mean time we could be loading
1196 mSettings.setLoginInitialized(this);
1199 // Open the icon database and retain all the icons for visited sites.
1200 private void retainIconsOnStartup() {
1201 final WebIconDatabase db = WebIconDatabase.getInstance();
1202 db.open(getDir("icons", 0).getPath());
1204 Cursor c = Browser.getAllBookmarks(mResolver);
1205 if (!c.moveToFirst()) {
1209 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1211 String url = c.getString(urlIndex);
1212 db.retainIconForPageUrl(url);
1213 } while (c.moveToNext());
1215 } catch (IllegalStateException e) {
1216 Log.e(LOGTAG, "retainIconsOnStartup", e);
1220 // Helper method for getting the top window.
1221 WebView getTopWindow() {
1222 return mTabControl.getCurrentTopWebView();
1225 TabControl getTabControl() {
1230 public boolean onCreateOptionsMenu(Menu menu) {
1231 super.onCreateOptionsMenu(menu);
1233 MenuInflater inflater = getMenuInflater();
1234 inflater.inflate(R.menu.browser, menu);
1236 updateInLoadMenuItems();
1241 * As the menu can be open when loading state changes
1242 * we must manually update the state of the stop/reload menu
1245 private void updateInLoadMenuItems() {
1246 if (mMenu == null) {
1249 MenuItem src = mInLoad ?
1250 mMenu.findItem(R.id.stop_menu_id):
1251 mMenu.findItem(R.id.reload_menu_id);
1252 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1253 dest.setIcon(src.getIcon());
1254 dest.setTitle(src.getTitle());
1258 public boolean onContextItemSelected(MenuItem item) {
1259 // chording is not an issue with context menus, but we use the same
1260 // options selector, so set mCanChord to true so we can access them.
1262 int id = item.getItemId();
1263 boolean result = true;
1265 // For the context menu from the title bar
1266 case R.id.title_bar_copy_page_url:
1267 Tab currentTab = mTabControl.getCurrentTab();
1268 if (null == currentTab) {
1272 WebView mainView = currentTab.getWebView();
1273 if (null == mainView) {
1277 copy(mainView.getUrl());
1279 // -- Browser context menu
1280 case R.id.open_context_menu_id:
1281 case R.id.open_newtab_context_menu_id:
1282 case R.id.bookmark_context_menu_id:
1283 case R.id.save_link_context_menu_id:
1284 case R.id.share_link_context_menu_id:
1285 case R.id.copy_link_context_menu_id:
1286 final WebView webView = getTopWindow();
1287 if (null == webView) {
1291 final HashMap hrefMap = new HashMap();
1292 hrefMap.put("webview", webView);
1293 final Message msg = mHandler.obtainMessage(
1294 FOCUS_NODE_HREF, id, 0, hrefMap);
1295 webView.requestFocusNodeHref(msg);
1299 // For other context menus
1300 result = onOptionsItemSelected(item);
1306 private Bundle createGoogleSearchSourceBundle(String source) {
1307 Bundle bundle = new Bundle();
1308 bundle.putString(SearchManager.SOURCE, source);
1313 * Overriding this to insert a local information bundle
1316 public boolean onSearchRequested() {
1317 if (mOptionsMenuOpen) closeOptionsMenu();
1318 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1319 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1320 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1325 public void startSearch(String initialQuery, boolean selectInitialQuery,
1326 Bundle appSearchData, boolean globalSearch) {
1327 if (appSearchData == null) {
1328 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1330 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1334 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1335 * results in changing tabs.
1336 * @param index Index of the tab to change to, as defined by
1337 * mTabControl.getTabIndex(Tab t).
1338 * @return boolean True if we successfully switched to a different tab. If
1339 * the indexth tab is null, or if that tab is the same as
1340 * the current one, return false.
1342 /* package */ boolean switchToTab(int index) {
1343 Tab tab = mTabControl.getTab(index);
1344 Tab currentTab = mTabControl.getCurrentTab();
1345 if (tab == null || tab == currentTab) {
1348 if (currentTab != null) {
1349 // currentTab may be null if it was just removed. In that case,
1350 // we do not need to remove it
1351 removeTabFromContentView(currentTab);
1353 mTabControl.setCurrentTab(tab);
1354 attachTabToContentView(tab);
1355 resetTitleIconAndProgress();
1356 updateLockIconToLatest();
1360 /* package */ Tab openTabToHomePage() {
1361 return openTabAndShow(mSettings.getHomePage(), false, null);
1364 /* package */ void closeCurrentWindow() {
1365 final Tab current = mTabControl.getCurrentTab();
1366 if (mTabControl.getTabCount() == 1) {
1367 // This is the last tab. Open a new one, with the home
1368 // page and close the current one.
1369 openTabToHomePage();
1373 final Tab parent = current.getParentTab();
1374 int indexToShow = -1;
1375 if (parent != null) {
1376 indexToShow = mTabControl.getTabIndex(parent);
1378 final int currentIndex = mTabControl.getCurrentIndex();
1379 // Try to move to the tab to the right
1380 indexToShow = currentIndex + 1;
1381 if (indexToShow > mTabControl.getTabCount() - 1) {
1382 // Try to move to the tab to the left
1383 indexToShow = currentIndex - 1;
1386 if (switchToTab(indexToShow)) {
1392 private ActiveTabsPage mActiveTabsPage;
1395 * Remove the active tabs page.
1396 * @param needToAttach If true, the active tabs page did not attach a tab
1397 * to the content view, so we need to do that here.
1399 /* package */ void removeActiveTabPage(boolean needToAttach) {
1400 mContentView.removeView(mActiveTabsPage);
1401 mActiveTabsPage = null;
1402 mMenuState = R.id.MAIN_MENU;
1404 attachTabToContentView(mTabControl.getCurrentTab());
1406 getTopWindow().requestFocus();
1410 public boolean onOptionsItemSelected(MenuItem item) {
1412 // The user has already fired a shortcut with this hold down of the
1416 if (null == getTopWindow()) {
1420 // The shortcut action consumes the MENU. Even if it is still down,
1421 // it won't trigger the next shortcut action. In the case of the
1422 // shortcut action triggering a new activity, like Bookmarks, we
1423 // won't get onKeyUp for MENU. So it is important to reset it here.
1424 mMenuIsDown = false;
1426 switch (item.getItemId()) {
1428 case R.id.new_tab_menu_id:
1429 openTabToHomePage();
1432 case R.id.goto_menu_id:
1433 onSearchRequested();
1436 case R.id.bookmarks_menu_id:
1437 bookmarksOrHistoryPicker(false);
1440 case R.id.active_tabs_menu_id:
1441 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1442 removeTabFromContentView(mTabControl.getCurrentTab());
1444 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1445 mActiveTabsPage.requestFocus();
1446 mMenuState = EMPTY_MENU;
1449 case R.id.add_bookmark_menu_id:
1450 Intent i = new Intent(BrowserActivity.this,
1451 AddBookmarkPage.class);
1452 WebView w = getTopWindow();
1453 i.putExtra("url", w.getUrl());
1454 i.putExtra("title", w.getTitle());
1455 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1456 i.putExtra("thumbnail", createScreenshot(w));
1460 case R.id.stop_reload_menu_id:
1464 getTopWindow().reload();
1468 case R.id.back_menu_id:
1469 getTopWindow().goBack();
1472 case R.id.forward_menu_id:
1473 getTopWindow().goForward();
1476 case R.id.close_menu_id:
1477 // Close the subwindow if it exists.
1478 if (mTabControl.getCurrentSubWindow() != null) {
1479 dismissSubWindow(mTabControl.getCurrentTab());
1482 closeCurrentWindow();
1485 case R.id.homepage_menu_id:
1486 Tab current = mTabControl.getCurrentTab();
1487 if (current != null) {
1488 dismissSubWindow(current);
1489 current.getWebView().loadUrl(mSettings.getHomePage());
1493 case R.id.preferences_menu_id:
1494 Intent intent = new Intent(this,
1495 BrowserPreferencesPage.class);
1496 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1497 getTopWindow().getUrl());
1498 startActivityForResult(intent, PREFERENCES_PAGE);
1501 case R.id.find_menu_id:
1502 if (null == mFindDialog) {
1503 mFindDialog = new FindDialog(this);
1505 mFindDialog.setWebView(getTopWindow());
1507 mMenuState = EMPTY_MENU;
1510 case R.id.select_text_id:
1511 getTopWindow().emulateShiftHeld();
1513 case R.id.page_info_menu_id:
1514 showPageInfo(mTabControl.getCurrentTab(), false);
1517 case R.id.classic_history_menu_id:
1518 bookmarksOrHistoryPicker(true);
1521 case R.id.title_bar_share_page_url:
1522 case R.id.share_page_menu_id:
1523 Tab currentTab = mTabControl.getCurrentTab();
1524 if (null == currentTab) {
1528 currentTab.populatePickerData();
1529 sharePage(this, currentTab.getTitle(),
1530 currentTab.getUrl(), currentTab.getFavicon(),
1531 createScreenshot(currentTab.getWebView()));
1534 case R.id.dump_nav_menu_id:
1535 getTopWindow().debugDump();
1538 case R.id.zoom_in_menu_id:
1539 getTopWindow().zoomIn();
1542 case R.id.zoom_out_menu_id:
1543 getTopWindow().zoomOut();
1546 case R.id.view_downloads_menu_id:
1547 viewDownloads(null);
1550 case R.id.window_one_menu_id:
1551 case R.id.window_two_menu_id:
1552 case R.id.window_three_menu_id:
1553 case R.id.window_four_menu_id:
1554 case R.id.window_five_menu_id:
1555 case R.id.window_six_menu_id:
1556 case R.id.window_seven_menu_id:
1557 case R.id.window_eight_menu_id:
1559 int menuid = item.getItemId();
1560 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1561 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1562 Tab desiredTab = mTabControl.getTab(id);
1563 if (desiredTab != null &&
1564 desiredTab != mTabControl.getCurrentTab()) {
1574 if (!super.onOptionsItemSelected(item)) {
1577 // Otherwise fall through.
1583 public void closeFind() {
1584 mMenuState = R.id.MAIN_MENU;
1588 public boolean onPrepareOptionsMenu(Menu menu) {
1589 // This happens when the user begins to hold down the menu key, so
1590 // allow them to chord to get a shortcut.
1592 // Note: setVisible will decide whether an item is visible; while
1593 // setEnabled() will decide whether an item is enabled, which also means
1594 // whether the matching shortcut key will function.
1595 super.onPrepareOptionsMenu(menu);
1596 switch (mMenuState) {
1598 if (mCurrentMenuState != mMenuState) {
1599 menu.setGroupVisible(R.id.MAIN_MENU, false);
1600 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1601 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1605 if (mCurrentMenuState != mMenuState) {
1606 menu.setGroupVisible(R.id.MAIN_MENU, true);
1607 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1608 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1610 final WebView w = getTopWindow();
1611 boolean canGoBack = false;
1612 boolean canGoForward = false;
1613 boolean isHome = false;
1615 canGoBack = w.canGoBack();
1616 canGoForward = w.canGoForward();
1617 isHome = mSettings.getHomePage().equals(w.getUrl());
1619 final MenuItem back = menu.findItem(R.id.back_menu_id);
1620 back.setEnabled(canGoBack);
1622 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1623 home.setEnabled(!isHome);
1625 menu.findItem(R.id.forward_menu_id)
1626 .setEnabled(canGoForward);
1628 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1629 mTabControl.canCreateNewTab());
1631 // decide whether to show the share link option
1632 PackageManager pm = getPackageManager();
1633 Intent send = new Intent(Intent.ACTION_SEND);
1634 send.setType("text/plain");
1635 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1636 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1638 boolean isNavDump = mSettings.isNavDump();
1639 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1640 nav.setVisible(isNavDump);
1641 nav.setEnabled(isNavDump);
1644 mCurrentMenuState = mMenuState;
1649 public void onCreateContextMenu(ContextMenu menu, View v,
1650 ContextMenuInfo menuInfo) {
1651 WebView webview = (WebView) v;
1652 WebView.HitTestResult result = webview.getHitTestResult();
1653 if (result == null) {
1657 int type = result.getType();
1658 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1660 "We should not show context menu when nothing is touched");
1663 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1664 // let TextView handles context menu
1668 // Note, http://b/issue?id=1106666 is requesting that
1669 // an inflated menu can be used again. This is not available
1670 // yet, so inflate each time (yuk!)
1671 MenuInflater inflater = getMenuInflater();
1672 inflater.inflate(R.menu.browsercontext, menu);
1674 // Show the correct menu group
1675 String extra = result.getExtra();
1676 menu.setGroupVisible(R.id.PHONE_MENU,
1677 type == WebView.HitTestResult.PHONE_TYPE);
1678 menu.setGroupVisible(R.id.EMAIL_MENU,
1679 type == WebView.HitTestResult.EMAIL_TYPE);
1680 menu.setGroupVisible(R.id.GEO_MENU,
1681 type == WebView.HitTestResult.GEO_TYPE);
1682 menu.setGroupVisible(R.id.IMAGE_MENU,
1683 type == WebView.HitTestResult.IMAGE_TYPE
1684 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1685 menu.setGroupVisible(R.id.ANCHOR_MENU,
1686 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1687 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1689 // Setup custom handling depending on the type
1691 case WebView.HitTestResult.PHONE_TYPE:
1692 menu.setHeaderTitle(Uri.decode(extra));
1693 menu.findItem(R.id.dial_context_menu_id).setIntent(
1694 new Intent(Intent.ACTION_VIEW, Uri
1695 .parse(WebView.SCHEME_TEL + extra)));
1696 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1697 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1698 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1699 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1701 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1705 case WebView.HitTestResult.EMAIL_TYPE:
1706 menu.setHeaderTitle(extra);
1707 menu.findItem(R.id.email_context_menu_id).setIntent(
1708 new Intent(Intent.ACTION_VIEW, Uri
1709 .parse(WebView.SCHEME_MAILTO + extra)));
1710 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1714 case WebView.HitTestResult.GEO_TYPE:
1715 menu.setHeaderTitle(extra);
1716 menu.findItem(R.id.map_context_menu_id).setIntent(
1717 new Intent(Intent.ACTION_VIEW, Uri
1718 .parse(WebView.SCHEME_GEO
1719 + URLEncoder.encode(extra))));
1720 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1724 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1725 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1726 TextView titleView = (TextView) LayoutInflater.from(this)
1727 .inflate(android.R.layout.browser_link_context_header,
1729 titleView.setText(extra);
1730 menu.setHeaderView(titleView);
1731 // decide whether to show the open link in new tab option
1732 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1733 mTabControl.canCreateNewTab());
1734 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1735 Bookmarks.urlHasAcceptableScheme(extra));
1736 PackageManager pm = getPackageManager();
1737 Intent send = new Intent(Intent.ACTION_SEND);
1738 send.setType("text/plain");
1739 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1740 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1741 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1744 // otherwise fall through to handle image part
1745 case WebView.HitTestResult.IMAGE_TYPE:
1746 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1747 menu.setHeaderTitle(extra);
1749 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1750 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1751 menu.findItem(R.id.download_context_menu_id).
1752 setOnMenuItemClickListener(new Download(extra));
1753 menu.findItem(R.id.set_wallpaper_context_menu_id).
1754 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1758 Log.w(LOGTAG, "We should not get here.");
1764 // Attach the given tab to the content view.
1765 // this should only be called for the current tab.
1766 private void attachTabToContentView(Tab t) {
1767 // Attach the container that contains the main WebView and any other UI
1768 // associated with the tab.
1769 t.attachTabToContentView(mContentView);
1771 if (mShouldShowErrorConsole) {
1772 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1773 if (errorConsole.numberOfErrors() == 0) {
1774 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1776 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1779 mErrorConsoleContainer.addView(errorConsole,
1780 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1781 ViewGroup.LayoutParams.WRAP_CONTENT));
1784 WebView view = t.getWebView();
1785 view.setEmbeddedTitleBar(mTitleBar);
1786 if (t.isInVoiceSearchMode()) {
1787 showVoiceTitleBar(t.getVoiceDisplayTitle());
1789 revertVoiceTitleBar();
1791 // Request focus on the top window.
1792 t.getTopWindow().requestFocus();
1795 // Attach a sub window to the main WebView of the given tab.
1796 void attachSubWindow(Tab t) {
1797 t.attachSubWindow(mContentView);
1798 getTopWindow().requestFocus();
1801 // Remove the given tab from the content view.
1802 private void removeTabFromContentView(Tab t) {
1803 // Remove the container that contains the main WebView.
1804 t.removeTabFromContentView(mContentView);
1806 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1807 if (errorConsole != null) {
1808 mErrorConsoleContainer.removeView(errorConsole);
1811 WebView view = t.getWebView();
1813 view.setEmbeddedTitleBar(null);
1817 // Remove the sub window if it exists. Also called by TabControl when the
1818 // user clicks the 'X' to dismiss a sub window.
1819 /* package */ void dismissSubWindow(Tab t) {
1820 t.removeSubWindow(mContentView);
1821 // dismiss the subwindow. This will destroy the WebView.
1822 t.dismissSubWindow();
1823 getTopWindow().requestFocus();
1826 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1827 // that accepts url as string.
1828 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1829 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1832 // This method does a ton of stuff. It will attempt to create a new tab
1833 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1834 // url isn't null, it will load the given url.
1835 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1837 final Tab currentTab = mTabControl.getCurrentTab();
1838 if (mTabControl.canCreateNewTab()) {
1839 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1841 WebView webview = tab.getWebView();
1842 // If the last tab was removed from the active tabs page, currentTab
1844 if (currentTab != null) {
1845 removeTabFromContentView(currentTab);
1847 // We must set the new tab as the current tab to reflect the old
1848 // animation behavior.
1849 mTabControl.setCurrentTab(tab);
1850 attachTabToContentView(tab);
1851 if (!urlData.isEmpty()) {
1852 urlData.loadIn(tab);
1856 // Get rid of the subwindow if it exists
1857 dismissSubWindow(currentTab);
1858 if (!urlData.isEmpty()) {
1859 // Load the given url.
1860 urlData.loadIn(currentTab);
1866 private Tab openTab(String url) {
1867 if (mSettings.openInBackground()) {
1868 Tab t = mTabControl.createNewTab();
1870 WebView view = t.getWebView();
1875 return openTabAndShow(url, false, null);
1879 private class Copy implements OnMenuItemClickListener {
1880 private CharSequence mText;
1882 public boolean onMenuItemClick(MenuItem item) {
1887 public Copy(CharSequence toCopy) {
1892 private class Download implements OnMenuItemClickListener {
1893 private String mText;
1895 public boolean onMenuItemClick(MenuItem item) {
1896 onDownloadStartNoStream(mText, null, null, null, -1);
1900 public Download(String toDownload) {
1905 private class SetAsWallpaper extends Thread implements
1906 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1908 private ProgressDialog mWallpaperProgress;
1909 private boolean mCanceled = false;
1911 public SetAsWallpaper(String url) {
1913 mUrl = new URL(url);
1914 } catch (MalformedURLException e) {
1919 public void onCancel(DialogInterface dialog) {
1923 public boolean onMenuItemClick(MenuItem item) {
1925 // The user may have tried to set a image with a large file size as their
1926 // background so it may take a few moments to perform the operation. Display
1927 // a progress spinner while it is working.
1928 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1929 mWallpaperProgress.setIndeterminate(true);
1930 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1931 mWallpaperProgress.setCancelable(true);
1932 mWallpaperProgress.setOnCancelListener(this);
1933 mWallpaperProgress.show();
1940 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1942 // TODO: This will cause the resource to be downloaded again, when we
1943 // should in most cases be able to grab it from the cache. To fix this
1944 // we should query WebCore to see if we can access a cached version and
1945 // instead open an input stream on that. This pattern could also be used
1946 // in the download manager where the same problem exists.
1947 InputStream inputstream = mUrl.openStream();
1948 if (inputstream != null) {
1949 setWallpaper(inputstream);
1951 } catch (IOException e) {
1952 Log.e(LOGTAG, "Unable to set new wallpaper");
1953 // Act as though the user canceled the operation so we try to
1954 // restore the old wallpaper.
1959 // Restore the old wallpaper if the user cancelled whilst we were setting
1960 // the new wallpaper.
1961 int width = oldWallpaper.getIntrinsicWidth();
1962 int height = oldWallpaper.getIntrinsicHeight();
1963 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1964 Canvas canvas = new Canvas(bm);
1965 oldWallpaper.setBounds(0, 0, width, height);
1966 oldWallpaper.draw(canvas);
1969 } catch (IOException e) {
1970 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1975 if (mWallpaperProgress.isShowing()) {
1976 mWallpaperProgress.dismiss();
1981 private void copy(CharSequence text) {
1983 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1985 clip.setClipboardText(text);
1987 } catch (android.os.RemoteException e) {
1988 Log.e(LOGTAG, "Copy failed", e);
1993 * Resets the browser title-view to whatever it must be
1994 * (for example, if we had a loading error)
1995 * When we have a new page, we call resetTitle, when we
1996 * have to reset the titlebar to whatever it used to be
1997 * (for example, if the user chose to stop loading), we
1998 * call resetTitleAndRevertLockIcon.
2000 /* package */ void resetTitleAndRevertLockIcon() {
2001 mTabControl.getCurrentTab().revertLockIcon();
2002 updateLockIconToLatest();
2003 resetTitleIconAndProgress();
2007 * Reset the title, favicon, and progress.
2009 private void resetTitleIconAndProgress() {
2010 WebView current = mTabControl.getCurrentWebView();
2011 if (current == null) {
2014 resetTitleAndIcon(current);
2015 int progress = current.getProgress();
2016 current.getWebChromeClient().onProgressChanged(current, progress);
2019 // Reset the title and the icon based on the given item.
2020 private void resetTitleAndIcon(WebView view) {
2021 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2023 setUrlTitle(item.getUrl(), item.getTitle());
2024 setFavicon(item.getFavicon());
2026 setUrlTitle(null, null);
2032 * Sets a title composed of the URL and the title string.
2033 * @param url The URL of the site being loaded.
2034 * @param title The title of the site being loaded.
2036 void setUrlTitle(String url, String title) {
2040 // If we are in voice search mode, the title has already been set.
2041 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2042 mTitleBar.setDisplayTitle(url);
2043 mFakeTitleBar.setDisplayTitle(url);
2047 * @param url The URL to build a title version of the URL from.
2048 * @return The title version of the URL or null if fails.
2049 * The title version of the URL can be either the URL hostname,
2050 * or the hostname with an "https://" prefix (for secure URLs),
2051 * or an empty string if, for example, the URL in question is a
2052 * file:// URL with no hostname.
2054 /* package */ static String buildTitleUrl(String url) {
2055 String titleUrl = null;
2059 // parse the url string
2060 URL urlObj = new URL(url);
2061 if (urlObj != null) {
2064 String protocol = urlObj.getProtocol();
2065 String host = urlObj.getHost();
2067 if (host != null && 0 < host.length()) {
2069 if (protocol != null) {
2070 // if a secure site, add an "https://" prefix!
2071 if (protocol.equalsIgnoreCase("https")) {
2072 titleUrl = protocol + "://" + host;
2077 } catch (MalformedURLException e) {}
2083 // Set the favicon in the title bar.
2084 void setFavicon(Bitmap icon) {
2085 mTitleBar.setFavicon(icon);
2086 mFakeTitleBar.setFavicon(icon);
2090 * Close the tab, remove its associated title bar, and adjust mTabControl's
2091 * current tab to a valid value.
2093 /* package */ void closeTab(Tab t) {
2094 int currentIndex = mTabControl.getCurrentIndex();
2095 int removeIndex = mTabControl.getTabIndex(t);
2096 mTabControl.removeTab(t);
2097 if (currentIndex >= removeIndex && currentIndex != 0) {
2100 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2101 resetTitleIconAndProgress();
2104 private void goBackOnePageOrQuit() {
2105 Tab current = mTabControl.getCurrentTab();
2106 if (current == null) {
2108 * Instead of finishing the activity, simply push this to the back
2109 * of the stack and let ActivityManager to choose the foreground
2110 * activity. As BrowserActivity is singleTask, it will be always the
2111 * root of the task. So we can use either true or false for
2114 moveTaskToBack(true);
2117 WebView w = current.getWebView();
2118 if (w.canGoBack()) {
2121 // Check to see if we are closing a window that was created by
2122 // another window. If so, we switch back to that window.
2123 Tab parent = current.getParentTab();
2124 if (parent != null) {
2125 switchToTab(mTabControl.getTabIndex(parent));
2126 // Now we close the other tab
2129 if (current.closeOnExit()) {
2130 // force the tab's inLoad() to be false as we are going to
2131 // either finish the activity or remove the tab. This will
2132 // ensure pauseWebViewTimers() taking action.
2133 mTabControl.getCurrentTab().clearInLoad();
2134 if (mTabControl.getTabCount() == 1) {
2138 // call pauseWebViewTimers() now, we won't be able to call
2139 // it in onPause() as the WebView won't be valid.
2140 // Temporarily change mActivityInPause to be true as
2141 // pauseWebViewTimers() will do nothing if mActivityInPause
2143 boolean savedState = mActivityInPause;
2145 Log.e(LOGTAG, "BrowserActivity is already paused "
2146 + "while handing goBackOnePageOrQuit.");
2148 mActivityInPause = true;
2149 pauseWebViewTimers();
2150 mActivityInPause = savedState;
2151 removeTabFromContentView(current);
2152 mTabControl.removeTab(current);
2155 * Instead of finishing the activity, simply push this to the back
2156 * of the stack and let ActivityManager to choose the foreground
2157 * activity. As BrowserActivity is singleTask, it will be always the
2158 * root of the task. So we can use either true or false for
2161 moveTaskToBack(true);
2166 boolean isMenuDown() {
2171 public boolean onKeyDown(int keyCode, KeyEvent event) {
2172 // Even if MENU is already held down, we need to call to super to open
2173 // the IME on long press.
2174 if (KeyEvent.KEYCODE_MENU == keyCode) {
2176 return super.onKeyDown(keyCode, event);
2178 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2179 // still down, we don't want to trigger the search. Pretend to consume
2180 // the key and do nothing.
2181 if (mMenuIsDown) return true;
2184 case KeyEvent.KEYCODE_SPACE:
2185 // WebView/WebTextView handle the keys in the KeyDown. As
2186 // the Activity's shortcut keys are only handled when WebView
2187 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2188 if (event.isShiftPressed()) {
2189 getTopWindow().pageUp(false);
2191 getTopWindow().pageDown(false);
2194 case KeyEvent.KEYCODE_BACK:
2195 if (event.getRepeatCount() == 0) {
2196 event.startTracking();
2198 } else if (mCustomView == null && mActiveTabsPage == null
2199 && event.isLongPress()) {
2200 bookmarksOrHistoryPicker(true);
2205 return super.onKeyDown(keyCode, event);
2209 public boolean onKeyUp(int keyCode, KeyEvent event) {
2211 case KeyEvent.KEYCODE_MENU:
2212 mMenuIsDown = false;
2214 case KeyEvent.KEYCODE_BACK:
2215 if (event.isTracking() && !event.isCanceled()) {
2216 if (mCustomView != null) {
2217 // if a custom view is showing, hide it
2218 mTabControl.getCurrentWebView().getWebChromeClient()
2219 .onHideCustomView();
2220 } else if (mActiveTabsPage != null) {
2221 // if tab page is showing, hide it
2222 removeActiveTabPage(true);
2224 WebView subwindow = mTabControl.getCurrentSubWindow();
2225 if (subwindow != null) {
2226 if (subwindow.canGoBack()) {
2229 dismissSubWindow(mTabControl.getCurrentTab());
2232 goBackOnePageOrQuit();
2239 return super.onKeyUp(keyCode, event);
2242 /* package */ void stopLoading() {
2243 mDidStopLoad = true;
2244 resetTitleAndRevertLockIcon();
2245 WebView w = getTopWindow();
2247 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2248 // same logic here. But for subwindow case, should we call into the main
2249 // WebView's onPageFinished as we never call its onPageStarted and if
2250 // the page finishes itself, we don't call onPageFinished.
2251 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2256 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2260 boolean didUserStopLoading() {
2261 return mDidStopLoad;
2264 private void cancelStopToast() {
2265 if (mStopToast != null) {
2266 mStopToast.cancel();
2271 // called by a UI or non-UI thread to post the message
2272 public void postMessage(int what, int arg1, int arg2, Object obj,
2274 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2278 // called by a UI or non-UI thread to remove the message
2279 void removeMessages(int what, Object object) {
2280 mHandler.removeMessages(what, object);
2283 // public message ids
2284 public final static int LOAD_URL = 1001;
2285 public final static int STOP_LOAD = 1002;
2288 private static final int FOCUS_NODE_HREF = 102;
2289 private static final int CANCEL_CREDS_REQUEST = 103;
2290 private static final int RELEASE_WAKELOCK = 107;
2292 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2294 // Private handler for handling javascript and saving passwords
2295 private Handler mHandler = new Handler() {
2297 public void handleMessage(Message msg) {
2299 case FOCUS_NODE_HREF:
2301 String url = (String) msg.getData().get("url");
2302 String title = (String) msg.getData().get("title");
2303 if (url == null || url.length() == 0) {
2306 HashMap focusNodeMap = (HashMap) msg.obj;
2307 WebView view = (WebView) focusNodeMap.get("webview");
2308 // Only apply the action if the top window did not change.
2309 if (getTopWindow() != view) {
2313 case R.id.open_context_menu_id:
2314 case R.id.view_image_context_menu_id:
2315 loadURL(getTopWindow(), url);
2317 case R.id.open_newtab_context_menu_id:
2318 final Tab parent = mTabControl.getCurrentTab();
2319 final Tab newTab = openTab(url);
2320 if (newTab != parent) {
2321 parent.addChildTab(newTab);
2324 case R.id.bookmark_context_menu_id:
2325 Intent intent = new Intent(BrowserActivity.this,
2326 AddBookmarkPage.class);
2327 intent.putExtra("url", url);
2328 intent.putExtra("title", title);
2329 startActivity(intent);
2331 case R.id.share_link_context_menu_id:
2332 // See if this site has been visited before
2333 StringBuilder sb = new StringBuilder(
2334 Browser.BookmarkColumns.URL + " = ");
2335 DatabaseUtils.appendEscapedSQLString(sb, url);
2336 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2337 Browser.HISTORY_PROJECTION,
2341 if (c.moveToFirst()) {
2342 // The site has been visited before, so grab the
2343 // info from the database.
2344 Bitmap favicon = null;
2345 Bitmap thumbnail = null;
2346 String linkTitle = c.getString(Browser.
2347 HISTORY_PROJECTION_TITLE_INDEX);
2348 byte[] data = c.getBlob(Browser.
2349 HISTORY_PROJECTION_FAVICON_INDEX);
2351 favicon = BitmapFactory.decodeByteArray(
2352 data, 0, data.length);
2354 data = c.getBlob(Browser.
2355 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2357 thumbnail = BitmapFactory.decodeByteArray(
2358 data, 0, data.length);
2360 sharePage(BrowserActivity.this,
2361 linkTitle, url, favicon, thumbnail);
2363 Browser.sendString(BrowserActivity.this, url,
2365 R.string.choosertitle_sharevia));
2368 case R.id.copy_link_context_menu_id:
2371 case R.id.save_link_context_menu_id:
2372 case R.id.download_context_menu_id:
2373 onDownloadStartNoStream(url, null, null, null, -1);
2380 loadURL(getTopWindow(), (String) msg.obj);
2387 case CANCEL_CREDS_REQUEST:
2388 resumeAfterCredentials();
2391 case RELEASE_WAKELOCK:
2392 if (mWakeLock.isHeld()) {
2393 mWakeLock.release();
2394 // if we reach here, Browser should be still in the
2395 // background loading after WAKELOCK_TIMEOUT (5-min).
2396 // To avoid burning the battery, stop loading.
2397 mTabControl.stopAllLoading();
2401 case UPDATE_BOOKMARK_THUMBNAIL:
2402 WebView view = (WebView) msg.obj;
2404 updateScreenshot(view);
2412 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2413 * an {@link Intent} to launch the Activity chooser.
2414 * @param c Context used to launch a new Activity.
2415 * @param title Title of the page. Stored in the Intent with
2416 * {@link Browser#EXTRA_SHARE_TITLE}
2417 * @param url URL of the page. Stored in the Intent with
2418 * {@link Intent#EXTRA_TEXT}
2419 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2420 * with {@link Browser#EXTRA_SHARE_FAVICON}
2421 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2422 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2424 public static final void sharePage(Context c, String title, String url,
2425 Bitmap favicon, Bitmap screenshot) {
2426 Intent send = new Intent(Intent.ACTION_SEND);
2427 send.setType("text/plain");
2428 send.putExtra(Intent.EXTRA_TEXT, url);
2429 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2430 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2431 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2433 c.startActivity(Intent.createChooser(send, c.getString(
2434 R.string.choosertitle_sharevia)));
2435 } catch(android.content.ActivityNotFoundException ex) {
2436 // if no app handles it, do nothing
2440 private void updateScreenshot(WebView view) {
2441 // If this is a bookmarked site, add a screenshot to the database.
2442 // FIXME: When should we update? Every time?
2443 // FIXME: Would like to make sure there is actually something to
2444 // draw, but the API for that (WebViewCore.pictureReady()) is not
2445 // currently accessible here.
2447 ContentResolver cr = getContentResolver();
2448 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2449 cr, view.getOriginalUrl(), view.getUrl(), true);
2451 boolean succeed = c.moveToFirst();
2452 ContentValues values = null;
2454 if (values == null) {
2455 final ByteArrayOutputStream os
2456 = new ByteArrayOutputStream();
2457 Bitmap bm = createScreenshot(view);
2462 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2463 values = new ContentValues();
2464 values.put(Browser.BookmarkColumns.THUMBNAIL,
2467 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2468 c.getInt(0)), values, null, null);
2469 succeed = c.moveToNext();
2476 * Values for the size of the thumbnail created when taking a screenshot.
2477 * Lazily initialized. Instead of using these directly, use
2478 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2480 private static int THUMBNAIL_WIDTH = 0;
2481 private static int THUMBNAIL_HEIGHT = 0;
2484 * Return the desired width for thumbnail screenshots, which are stored in
2485 * the database, and used on the bookmarks screen.
2486 * @param context Context for finding out the density of the screen.
2487 * @return int desired width for thumbnail screenshot.
2489 /* package */ static int getDesiredThumbnailWidth(Context context) {
2490 if (THUMBNAIL_WIDTH == 0) {
2491 float density = context.getResources().getDisplayMetrics().density;
2492 THUMBNAIL_WIDTH = (int) (90 * density);
2493 THUMBNAIL_HEIGHT = (int) (80 * density);
2495 return THUMBNAIL_WIDTH;
2499 * Return the desired height for thumbnail screenshots, which are stored in
2500 * the database, and used on the bookmarks screen.
2501 * @param context Context for finding out the density of the screen.
2502 * @return int desired height for thumbnail screenshot.
2504 /* package */ static int getDesiredThumbnailHeight(Context context) {
2505 // To ensure that they are both initialized.
2506 getDesiredThumbnailWidth(context);
2507 return THUMBNAIL_HEIGHT;
2510 private Bitmap createScreenshot(WebView view) {
2511 Picture thumbnail = view.capturePicture();
2512 if (thumbnail == null) {
2515 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2516 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2517 Canvas canvas = new Canvas(bm);
2518 // May need to tweak these values to determine what is the
2519 // best scale factor
2520 int thumbnailWidth = thumbnail.getWidth();
2521 int thumbnailHeight = thumbnail.getHeight();
2522 float scaleFactorX = 1.0f;
2523 float scaleFactorY = 1.0f;
2524 if (thumbnailWidth > 0) {
2525 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2526 (float)thumbnailWidth;
2531 if (view.getWidth() > view.getHeight() &&
2532 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2533 // If the device is in landscape and the page is shorter
2534 // than the height of the view, stretch the thumbnail to fill the
2536 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2537 (float)thumbnailHeight;
2539 // In the portrait case, this looks nice.
2540 scaleFactorY = scaleFactorX;
2543 canvas.scale(scaleFactorX, scaleFactorY);
2545 thumbnail.draw(canvas);
2549 // -------------------------------------------------------------------------
2550 // Helper function for WebViewClient.
2551 //-------------------------------------------------------------------------
2553 // Use in overrideUrlLoading
2554 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2555 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2556 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2557 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2559 void onPageStarted(WebView view, String url, Bitmap favicon) {
2560 // when BrowserActivity just starts, onPageStarted may be called before
2561 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2562 // to start the timer. As we won't switch tabs while an activity is in
2563 // pause state, we can ensure calling resume and pause in pair.
2564 if (mActivityInPause) resumeWebViewTimers();
2567 setUrlTitle(url, null);
2568 setFavicon(favicon);
2569 // Keep this initial progress in sync with initialProgressValue (* 100)
2570 // in ProgressTracker.cpp
2571 // Show some progress so that the user knows the page is beginning to
2573 onProgressChanged(view, 10);
2574 mDidStopLoad = false;
2575 if (!mIsNetworkUp) createAndShowNetworkDialog();
2577 if (mSettings.isTracing()) {
2580 WebAddress uri = new WebAddress(url);
2582 } catch (android.net.ParseException ex) {
2585 host = host.replace('.', '_');
2588 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2591 // Performance probe
2593 mStart = SystemClock.uptimeMillis();
2594 mProcessStart = Process.getElapsedCpuTime();
2595 long[] sysCpu = new long[7];
2596 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2598 mUserStart = sysCpu[0] + sysCpu[1];
2599 mSystemStart = sysCpu[2];
2600 mIdleStart = sysCpu[3];
2601 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2603 mUiStart = SystemClock.currentThreadTimeMillis();
2607 void onPageFinished(WebView view, String url) {
2608 // Reset the title and icon in case we stopped a provisional load.
2609 resetTitleAndIcon(view);
2610 // Update the lock icon image only once we are done loading
2611 updateLockIconToLatest();
2612 // pause the WebView timer and release the wake lock if it is finished
2613 // while BrowserActivity is in pause state.
2614 if (mActivityInPause && pauseWebViewTimers()) {
2615 if (mWakeLock.isHeld()) {
2616 mHandler.removeMessages(RELEASE_WAKELOCK);
2617 mWakeLock.release();
2621 // Performance probe
2623 long[] sysCpu = new long[7];
2624 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2626 String uiInfo = "UI thread used "
2627 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2630 Log.d(LOGTAG, uiInfo);
2632 //The string that gets written to the log
2633 String performanceString = "It took total "
2634 + (SystemClock.uptimeMillis() - mStart)
2635 + " ms clock time to load the page."
2636 + "\nbrowser process used "
2637 + (Process.getElapsedCpuTime() - mProcessStart)
2638 + " ms, user processes used "
2639 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2640 + " ms, kernel used "
2641 + (sysCpu[2] - mSystemStart) * 10
2642 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2643 + " ms and irq took "
2644 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2645 * 10 + " ms, " + uiInfo;
2647 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2650 // strip the url to maintain consistency
2651 String newUrl = new String(url);
2652 if (newUrl.startsWith("http://www.")) {
2653 newUrl = newUrl.substring(11);
2654 } else if (newUrl.startsWith("http://")) {
2655 newUrl = newUrl.substring(7);
2656 } else if (newUrl.startsWith("https://www.")) {
2657 newUrl = newUrl.substring(12);
2658 } else if (newUrl.startsWith("https://")) {
2659 newUrl = newUrl.substring(8);
2662 Log.d(LOGTAG, newUrl + " loaded");
2670 Debug.stopMethodTracing();
2674 boolean shouldOverrideUrlLoading(WebView view, String url) {
2675 if (url.startsWith(SCHEME_WTAI)) {
2676 // wtai://wp/mc;number
2677 // number=string(phone-number)
2678 if (url.startsWith(SCHEME_WTAI_MC)) {
2679 Intent intent = new Intent(Intent.ACTION_VIEW,
2680 Uri.parse(WebView.SCHEME_TEL +
2681 url.substring(SCHEME_WTAI_MC.length())));
2682 startActivity(intent);
2685 // wtai://wp/sd;dtmf
2686 // dtmf=string(dialstring)
2687 if (url.startsWith(SCHEME_WTAI_SD)) {
2688 // TODO: only send when there is active voice connection
2691 // wtai://wp/ap;number;name
2692 // number=string(phone-number)
2694 if (url.startsWith(SCHEME_WTAI_AP)) {
2700 // The "about:" schemes are internal to the browser; don't want these to
2701 // be dispatched to other apps.
2702 if (url.startsWith("about:")) {
2707 // perform generic parsing of the URI to turn it into an Intent.
2709 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2710 } catch (URISyntaxException ex) {
2711 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2715 // check whether the intent can be resolved. If not, we will see
2716 // whether we can download it from the Market.
2717 if (getPackageManager().resolveActivity(intent, 0) == null) {
2718 String packagename = intent.getPackage();
2719 if (packagename != null) {
2720 intent = new Intent(Intent.ACTION_VIEW, Uri
2721 .parse("market://search?q=pname:" + packagename));
2722 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2723 startActivity(intent);
2730 // sanitize the Intent, ensuring web pages can not bypass browser
2731 // security (only access to BROWSABLE activities).
2732 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2733 intent.setComponent(null);
2735 if (startActivityIfNeeded(intent, -1)) {
2738 } catch (ActivityNotFoundException ex) {
2739 // ignore the error. If no application can handle the URL,
2740 // eg about:blank, assume the browser can handle it.
2751 // -------------------------------------------------------------------------
2752 // Helper function for WebChromeClient
2753 // -------------------------------------------------------------------------
2755 void onProgressChanged(WebView view, int newProgress) {
2756 mTitleBar.setProgress(newProgress);
2757 mFakeTitleBar.setProgress(newProgress);
2759 if (newProgress == 100) {
2760 // onProgressChanged() may continue to be called after the main
2761 // frame has finished loading, as any remaining sub frames continue
2762 // to load. We'll only get called once though with newProgress as
2763 // 100 when everything is loaded. (onPageFinished is called once
2764 // when the main frame completes loading regardless of the state of
2765 // any sub frames so calls to onProgressChanges may continue after
2766 // onPageFinished has executed)
2769 updateInLoadMenuItems();
2770 // If the options menu is open, leave the title bar
2771 if (!mOptionsMenuOpen || !mIconView) {
2775 } else if (!mInLoad) {
2776 // onPageFinished may have already been called but a subframe is
2777 // still loading and updating the progress. Reset mInLoad and update
2780 updateInLoadMenuItems();
2781 if (!mOptionsMenuOpen || mIconView) {
2782 // This page has begun to load, so show the title bar
2788 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2789 // if a view already exists then immediately terminate the new one
2790 if (mCustomView != null) {
2791 callback.onCustomViewHidden();
2795 // Add the custom view to its container.
2796 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2798 mCustomViewCallback = callback;
2799 // Save the menu state and set it to empty while the custom
2801 mOldMenuState = mMenuState;
2802 mMenuState = EMPTY_MENU;
2803 // Hide the content view.
2804 mContentView.setVisibility(View.GONE);
2805 // Finally show the custom view container.
2806 setStatusBarVisibility(false);
2807 mCustomViewContainer.setVisibility(View.VISIBLE);
2808 mCustomViewContainer.bringToFront();
2811 void onHideCustomView() {
2812 if (mCustomView == null)
2815 // Hide the custom view.
2816 mCustomView.setVisibility(View.GONE);
2817 // Remove the custom view from its container.
2818 mCustomViewContainer.removeView(mCustomView);
2820 // Reset the old menu state.
2821 mMenuState = mOldMenuState;
2822 mOldMenuState = EMPTY_MENU;
2823 mCustomViewContainer.setVisibility(View.GONE);
2824 mCustomViewCallback.onCustomViewHidden();
2825 // Show the content view.
2826 setStatusBarVisibility(true);
2827 mContentView.setVisibility(View.VISIBLE);
2830 Bitmap getDefaultVideoPoster() {
2831 if (mDefaultVideoPoster == null) {
2832 mDefaultVideoPoster = BitmapFactory.decodeResource(
2833 getResources(), R.drawable.default_video_poster);
2835 return mDefaultVideoPoster;
2838 View getVideoLoadingProgressView() {
2839 if (mVideoProgressView == null) {
2840 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2841 mVideoProgressView = inflater.inflate(
2842 R.layout.video_loading_progress, null);
2844 return mVideoProgressView;
2848 * The Object used to inform the WebView of the file to upload.
2850 private ValueCallback<Uri> mUploadMessage;
2852 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2853 if (mUploadMessage != null) return;
2854 mUploadMessage = uploadMsg;
2855 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2856 i.addCategory(Intent.CATEGORY_OPENABLE);
2858 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2859 getString(R.string.choose_upload)), FILE_SELECTED);
2862 // -------------------------------------------------------------------------
2863 // Implement functions for DownloadListener
2864 // -------------------------------------------------------------------------
2867 * Notify the host application a download should be done, or that
2868 * the data should be streamed if a streaming viewer is available.
2869 * @param url The full url to the content that should be downloaded
2870 * @param contentDisposition Content-disposition http header, if
2872 * @param mimetype The mimetype of the content reported by the server
2873 * @param contentLength The file size reported by the server
2875 public void onDownloadStart(String url, String userAgent,
2876 String contentDisposition, String mimetype, long contentLength) {
2877 // if we're dealing wih A/V content that's not explicitly marked
2878 // for download, check if it's streamable.
2879 if (contentDisposition == null
2880 || !contentDisposition.regionMatches(
2881 true, 0, "attachment", 0, 10)) {
2882 // query the package manager to see if there's a registered handler
2884 Intent intent = new Intent(Intent.ACTION_VIEW);
2885 intent.setDataAndType(Uri.parse(url), mimetype);
2886 ResolveInfo info = getPackageManager().resolveActivity(intent,
2887 PackageManager.MATCH_DEFAULT_ONLY);
2889 ComponentName myName = getComponentName();
2890 // If we resolved to ourselves, we don't want to attempt to
2891 // load the url only to try and download it again.
2892 if (!myName.getPackageName().equals(
2893 info.activityInfo.packageName)
2894 || !myName.getClassName().equals(
2895 info.activityInfo.name)) {
2896 // someone (other than us) knows how to handle this mime
2897 // type with this scheme, don't download.
2899 startActivity(intent);
2901 } catch (ActivityNotFoundException ex) {
2903 Log.d(LOGTAG, "activity not found for " + mimetype
2904 + " over " + Uri.parse(url).getScheme(),
2907 // Best behavior is to fall back to a download in this
2913 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2917 * Notify the host application a download should be done, even if there
2918 * is a streaming viewer available for thise type.
2919 * @param url The full url to the content that should be downloaded
2920 * @param contentDisposition Content-disposition http header, if
2922 * @param mimetype The mimetype of the content reported by the server
2923 * @param contentLength The file size reported by the server
2925 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2926 String contentDisposition, String mimetype, long contentLength) {
2928 String filename = URLUtil.guessFileName(url,
2929 contentDisposition, mimetype);
2931 // Check to see if we have an SDCard
2932 String status = Environment.getExternalStorageState();
2933 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2937 // Check to see if the SDCard is busy, same as the music app
2938 if (status.equals(Environment.MEDIA_SHARED)) {
2939 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2940 title = R.string.download_sdcard_busy_dlg_title;
2942 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2943 title = R.string.download_no_sdcard_dlg_title;
2946 new AlertDialog.Builder(this)
2948 .setIcon(android.R.drawable.ic_dialog_alert)
2950 .setPositiveButton(R.string.ok, null)
2955 // java.net.URI is a lot stricter than KURL so we have to undo
2956 // KURL's percent-encoding and redo the encoding using java.net.URI.
2959 // Undo the percent-encoding that KURL may have done.
2960 String newUrl = new String(URLUtil.decode(url.getBytes()));
2961 // Parse the url into pieces
2962 WebAddress w = new WebAddress(newUrl);
2964 String query = null;
2965 String path = w.mPath;
2966 // Break the path into path, query, and fragment
2967 if (path.length() > 0) {
2968 // Strip the fragment
2969 int idx = path.lastIndexOf('#');
2971 frag = path.substring(idx + 1);
2972 path = path.substring(0, idx);
2974 idx = path.lastIndexOf('?');
2976 query = path.substring(idx + 1);
2977 path = path.substring(0, idx);
2980 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2982 } catch (Exception e) {
2983 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2987 // XXX: Have to use the old url since the cookies were stored using the
2988 // old percent-encoded url.
2989 String cookies = CookieManager.getInstance().getCookie(url);
2991 ContentValues values = new ContentValues();
2992 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2993 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2994 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2995 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
2997 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
2998 BrowserDownloadPage.class.getCanonicalName());
2999 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3000 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3001 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3002 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3003 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
3004 if (contentLength > 0) {
3005 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
3007 if (mimetype == null) {
3008 // We must have long pressed on a link or image to download it. We
3009 // are not sure of the mimetype in this case, so do a head request
3010 new FetchUrlMimeType(this).execute(values);
3012 final Uri contentUri =
3013 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
3018 // -------------------------------------------------------------------------
3021 * Resets the lock icon. This method is called when we start a new load and
3022 * know the url to be loaded.
3024 private void resetLockIcon(String url) {
3025 // Save the lock-icon state (we revert to it if the load gets cancelled)
3026 mTabControl.getCurrentTab().resetLockIcon(url);
3027 updateLockIconImage(LOCK_ICON_UNSECURE);
3031 * Update the lock icon to correspond to our latest state.
3033 private void updateLockIconToLatest() {
3034 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
3038 * Updates the lock-icon image in the title-bar.
3040 private void updateLockIconImage(int lockIconType) {
3042 if (lockIconType == LOCK_ICON_SECURE) {
3044 } else if (lockIconType == LOCK_ICON_MIXED) {
3047 mTitleBar.setLock(d);
3048 mFakeTitleBar.setLock(d);
3052 * Displays a page-info dialog.
3053 * @param tab The tab to show info about
3054 * @param fromShowSSLCertificateOnError The flag that indicates whether
3055 * this dialog was opened from the SSL-certificate-on-error dialog or
3056 * not. This is important, since we need to know whether to return to
3057 * the parent dialog or simply dismiss.
3059 private void showPageInfo(final Tab tab,
3060 final boolean fromShowSSLCertificateOnError) {
3061 final LayoutInflater factory = LayoutInflater
3064 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3066 final WebView view = tab.getWebView();
3069 String title = null;
3073 title = tab.getTitle();
3074 } else if (view == mTabControl.getCurrentWebView()) {
3075 // Use the cached title and url if this is the current WebView
3079 url = view.getUrl();
3080 title = view.getTitle();
3086 if (title == null) {
3090 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3091 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3093 mPageInfoView = tab;
3094 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3096 AlertDialog.Builder alertDialogBuilder =
3097 new AlertDialog.Builder(this)
3098 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3099 .setView(pageInfoView)
3102 new DialogInterface.OnClickListener() {
3103 public void onClick(DialogInterface dialog,
3105 mPageInfoDialog = null;
3106 mPageInfoView = null;
3108 // if we came here from the SSL error dialog
3109 if (fromShowSSLCertificateOnError) {
3110 // go back to the SSL error dialog
3111 showSSLCertificateOnError(
3112 mSSLCertificateOnErrorView,
3113 mSSLCertificateOnErrorHandler,
3114 mSSLCertificateOnErrorError);
3118 .setOnCancelListener(
3119 new DialogInterface.OnCancelListener() {
3120 public void onCancel(DialogInterface dialog) {
3121 mPageInfoDialog = null;
3122 mPageInfoView = null;
3124 // if we came here from the SSL error dialog
3125 if (fromShowSSLCertificateOnError) {
3126 // go back to the SSL error dialog
3127 showSSLCertificateOnError(
3128 mSSLCertificateOnErrorView,
3129 mSSLCertificateOnErrorHandler,
3130 mSSLCertificateOnErrorError);
3135 // if we have a main top-level page SSL certificate set or a certificate
3137 if (fromShowSSLCertificateOnError ||
3138 (view != null && view.getCertificate() != null)) {
3139 // add a 'View Certificate' button
3140 alertDialogBuilder.setNeutralButton(
3141 R.string.view_certificate,
3142 new DialogInterface.OnClickListener() {
3143 public void onClick(DialogInterface dialog,
3145 mPageInfoDialog = null;
3146 mPageInfoView = null;
3148 // if we came here from the SSL error dialog
3149 if (fromShowSSLCertificateOnError) {
3150 // go back to the SSL error dialog
3151 showSSLCertificateOnError(
3152 mSSLCertificateOnErrorView,
3153 mSSLCertificateOnErrorHandler,
3154 mSSLCertificateOnErrorError);
3156 // otherwise, display the top-most certificate from
3158 if (view.getCertificate() != null) {
3159 showSSLCertificate(tab);
3166 mPageInfoDialog = alertDialogBuilder.show();
3170 * Displays the main top-level page SSL certificate dialog
3171 * (accessible from the Page-Info dialog).
3172 * @param tab The tab to show certificate for.
3174 private void showSSLCertificate(final Tab tab) {
3175 final View certificateView =
3176 inflateCertificateView(tab.getWebView().getCertificate());
3177 if (certificateView == null) {
3181 LayoutInflater factory = LayoutInflater.from(this);
3183 final LinearLayout placeholder =
3184 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3186 LinearLayout ll = (LinearLayout) factory.inflate(
3187 R.layout.ssl_success, placeholder);
3188 ((TextView)ll.findViewById(R.id.success))
3189 .setText(R.string.ssl_certificate_is_valid);
3191 mSSLCertificateView = tab;
3192 mSSLCertificateDialog =
3193 new AlertDialog.Builder(this)
3194 .setTitle(R.string.ssl_certificate).setIcon(
3195 R.drawable.ic_dialog_browser_certificate_secure)
3196 .setView(certificateView)
3197 .setPositiveButton(R.string.ok,
3198 new DialogInterface.OnClickListener() {
3199 public void onClick(DialogInterface dialog,
3201 mSSLCertificateDialog = null;
3202 mSSLCertificateView = null;
3204 showPageInfo(tab, false);
3207 .setOnCancelListener(
3208 new DialogInterface.OnCancelListener() {
3209 public void onCancel(DialogInterface dialog) {
3210 mSSLCertificateDialog = null;
3211 mSSLCertificateView = null;
3213 showPageInfo(tab, false);
3220 * Displays the SSL error certificate dialog.
3221 * @param view The target web-view.
3222 * @param handler The SSL error handler responsible for cancelling the
3223 * connection that resulted in an SSL error or proceeding per user request.
3224 * @param error The SSL error object.
3226 void showSSLCertificateOnError(
3227 final WebView view, final SslErrorHandler handler, final SslError error) {
3229 final View certificateView =
3230 inflateCertificateView(error.getCertificate());
3231 if (certificateView == null) {
3235 LayoutInflater factory = LayoutInflater.from(this);
3237 final LinearLayout placeholder =
3238 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3240 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3241 LinearLayout ll = (LinearLayout)factory
3242 .inflate(R.layout.ssl_warning, placeholder);
3243 ((TextView)ll.findViewById(R.id.warning))
3244 .setText(R.string.ssl_untrusted);
3247 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3248 LinearLayout ll = (LinearLayout)factory
3249 .inflate(R.layout.ssl_warning, placeholder);
3250 ((TextView)ll.findViewById(R.id.warning))
3251 .setText(R.string.ssl_mismatch);
3254 if (error.hasError(SslError.SSL_EXPIRED)) {
3255 LinearLayout ll = (LinearLayout)factory
3256 .inflate(R.layout.ssl_warning, placeholder);
3257 ((TextView)ll.findViewById(R.id.warning))
3258 .setText(R.string.ssl_expired);
3261 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3262 LinearLayout ll = (LinearLayout)factory
3263 .inflate(R.layout.ssl_warning, placeholder);
3264 ((TextView)ll.findViewById(R.id.warning))
3265 .setText(R.string.ssl_not_yet_valid);
3268 mSSLCertificateOnErrorHandler = handler;
3269 mSSLCertificateOnErrorView = view;
3270 mSSLCertificateOnErrorError = error;
3271 mSSLCertificateOnErrorDialog =
3272 new AlertDialog.Builder(this)
3273 .setTitle(R.string.ssl_certificate).setIcon(
3274 R.drawable.ic_dialog_browser_certificate_partially_secure)
3275 .setView(certificateView)
3276 .setPositiveButton(R.string.ok,
3277 new DialogInterface.OnClickListener() {
3278 public void onClick(DialogInterface dialog,
3280 mSSLCertificateOnErrorDialog = null;
3281 mSSLCertificateOnErrorView = null;
3282 mSSLCertificateOnErrorHandler = null;
3283 mSSLCertificateOnErrorError = null;
3285 view.getWebViewClient().onReceivedSslError(
3286 view, handler, error);
3289 .setNeutralButton(R.string.page_info_view,
3290 new DialogInterface.OnClickListener() {
3291 public void onClick(DialogInterface dialog,
3293 mSSLCertificateOnErrorDialog = null;
3295 // do not clear the dialog state: we will
3296 // need to show the dialog again once the
3297 // user is done exploring the page-info details
3299 showPageInfo(mTabControl.getTabFromView(view),
3303 .setOnCancelListener(
3304 new DialogInterface.OnCancelListener() {
3305 public void onCancel(DialogInterface dialog) {
3306 mSSLCertificateOnErrorDialog = null;
3307 mSSLCertificateOnErrorView = null;
3308 mSSLCertificateOnErrorHandler = null;
3309 mSSLCertificateOnErrorError = null;
3311 view.getWebViewClient().onReceivedSslError(
3312 view, handler, error);
3319 * Inflates the SSL certificate view (helper method).
3320 * @param certificate The SSL certificate.
3321 * @return The resultant certificate view with issued-to, issued-by,
3322 * issued-on, expires-on, and possibly other fields set.
3323 * If the input certificate is null, returns null.
3325 private View inflateCertificateView(SslCertificate certificate) {
3326 if (certificate == null) {
3330 LayoutInflater factory = LayoutInflater.from(this);
3332 View certificateView = factory.inflate(
3333 R.layout.ssl_certificate, null);
3336 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3337 if (issuedTo != null) {
3338 ((TextView) certificateView.findViewById(R.id.to_common))
3339 .setText(issuedTo.getCName());
3340 ((TextView) certificateView.findViewById(R.id.to_org))
3341 .setText(issuedTo.getOName());
3342 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3343 .setText(issuedTo.getUName());
3347 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3348 if (issuedBy != null) {
3349 ((TextView) certificateView.findViewById(R.id.by_common))
3350 .setText(issuedBy.getCName());
3351 ((TextView) certificateView.findViewById(R.id.by_org))
3352 .setText(issuedBy.getOName());
3353 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3354 .setText(issuedBy.getUName());
3358 String issuedOn = reformatCertificateDate(
3359 certificate.getValidNotBefore());
3360 ((TextView) certificateView.findViewById(R.id.issued_on))
3364 String expiresOn = reformatCertificateDate(
3365 certificate.getValidNotAfter());
3366 ((TextView) certificateView.findViewById(R.id.expires_on))
3367 .setText(expiresOn);
3369 return certificateView;
3373 * Re-formats the certificate date (Date.toString()) string to
3374 * a properly localized date string.
3375 * @return Properly localized version of the certificate date string and
3376 * the original certificate date string if fails to localize.
3377 * If the original string is null, returns an empty string "".
3379 private String reformatCertificateDate(String certificateDate) {
3380 String reformattedDate = null;
3382 if (certificateDate != null) {
3385 date = java.text.DateFormat.getInstance().parse(certificateDate);
3386 } catch (ParseException e) {
3392 DateFormat.getDateFormat(this).format(date);
3396 return reformattedDate != null ? reformattedDate :
3397 (certificateDate != null ? certificateDate : "");
3401 * Displays an http-authentication dialog.
3403 void showHttpAuthentication(final HttpAuthHandler handler,
3404 final String host, final String realm, final String title,
3405 final String name, final String password, int focusId) {
3406 LayoutInflater factory = LayoutInflater.from(this);
3407 final View v = factory
3408 .inflate(R.layout.http_authentication, null);
3410 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3412 if (password != null) {
3413 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3416 String titleText = title;
3417 if (titleText == null) {
3418 titleText = getText(R.string.sign_in_to).toString().replace(
3419 "%s1", host).replace("%s2", realm);
3422 mHttpAuthHandler = handler;
3423 AlertDialog dialog = new AlertDialog.Builder(this)
3424 .setTitle(titleText)
3425 .setIcon(android.R.drawable.ic_dialog_alert)
3427 .setPositiveButton(R.string.action,
3428 new DialogInterface.OnClickListener() {
3429 public void onClick(DialogInterface dialog,
3431 String nm = ((EditText) v
3432 .findViewById(R.id.username_edit))
3433 .getText().toString();
3434 String pw = ((EditText) v
3435 .findViewById(R.id.password_edit))
3436 .getText().toString();
3437 BrowserActivity.this.setHttpAuthUsernamePassword
3438 (host, realm, nm, pw);
3439 handler.proceed(nm, pw);
3440 mHttpAuthenticationDialog = null;
3441 mHttpAuthHandler = null;
3443 .setNegativeButton(R.string.cancel,
3444 new DialogInterface.OnClickListener() {
3445 public void onClick(DialogInterface dialog,
3448 BrowserActivity.this.resetTitleAndRevertLockIcon();
3449 mHttpAuthenticationDialog = null;
3450 mHttpAuthHandler = null;
3452 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3453 public void onCancel(DialogInterface dialog) {
3455 BrowserActivity.this.resetTitleAndRevertLockIcon();
3456 mHttpAuthenticationDialog = null;
3457 mHttpAuthHandler = null;
3460 // Make the IME appear when the dialog is displayed if applicable.
3461 dialog.getWindow().setSoftInputMode(
3462 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3465 dialog.findViewById(focusId).requestFocus();
3467 v.findViewById(R.id.username_edit).requestFocus();
3469 mHttpAuthenticationDialog = dialog;
3472 public int getProgress() {
3473 WebView w = mTabControl.getCurrentWebView();
3475 return w.getProgress();
3482 * Set HTTP authentication password.
3484 * @param host The host for the password
3485 * @param realm The realm for the password
3486 * @param username The username for the password. If it is null, it means
3487 * password can't be saved.
3488 * @param password The password
3490 public void setHttpAuthUsernamePassword(String host, String realm,
3493 WebView w = mTabControl.getCurrentWebView();
3495 w.setHttpAuthUsernamePassword(host, realm, username, password);
3500 * connectivity manager says net has come or gone... inform the user
3501 * @param up true if net has come up, false if net has gone down
3503 public void onNetworkToggle(boolean up) {
3504 if (up == mIsNetworkUp) {
3507 mIsNetworkUp = true;
3508 if (mAlertDialog != null) {
3509 mAlertDialog.cancel();
3510 mAlertDialog = null;
3513 mIsNetworkUp = false;
3515 createAndShowNetworkDialog();
3518 WebView w = mTabControl.getCurrentWebView();
3520 w.setNetworkAvailable(up);
3524 boolean isNetworkUp() {
3525 return mIsNetworkUp;
3528 // This method shows the network dialog alerting the user that the net is
3529 // down. It will only show the dialog if mAlertDialog is null.
3530 private void createAndShowNetworkDialog() {
3531 if (mAlertDialog == null) {
3532 mAlertDialog = new AlertDialog.Builder(this)
3533 .setTitle(R.string.loadSuspendedTitle)
3534 .setMessage(R.string.loadSuspended)
3535 .setPositiveButton(R.string.ok, null)
3541 protected void onActivityResult(int requestCode, int resultCode,
3543 if (getTopWindow() == null) return;
3545 switch (requestCode) {
3547 if (resultCode == RESULT_OK && intent != null) {
3548 String data = intent.getAction();
3549 Bundle extras = intent.getExtras();
3550 if (extras != null && extras.getBoolean("new_window", false)) {
3553 final Tab currentTab =
3554 mTabControl.getCurrentTab();
3555 dismissSubWindow(currentTab);
3556 if (data != null && data.length() != 0) {
3557 getTopWindow().loadUrl(data);
3561 // Deliberately fall through to PREFERENCES_PAGE, since the
3562 // same extra may be attached to the COMBO_PAGE
3563 case PREFERENCES_PAGE:
3564 if (resultCode == RESULT_OK && intent != null) {
3565 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3566 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3567 mTabControl.removeParentChildRelationShips();
3571 // Choose a file from the file picker.
3573 if (null == mUploadMessage) break;
3574 Uri result = intent == null || resultCode != RESULT_OK ? null
3576 mUploadMessage.onReceiveValue(result);
3577 mUploadMessage = null;
3582 getTopWindow().requestFocus();
3586 * This method is called as a result of the user selecting the options
3587 * menu to see the download window. It shows the download window on top of
3588 * the current window.
3590 private void viewDownloads(Uri downloadRecord) {
3591 Intent intent = new Intent(this,
3592 BrowserDownloadPage.class);
3593 intent.setData(downloadRecord);
3594 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3600 * @param startWithHistory If true, open starting on the history tab.
3601 * Otherwise, start with the bookmarks tab.
3603 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3604 WebView current = mTabControl.getCurrentWebView();
3605 if (current == null) {
3608 Intent intent = new Intent(this,
3609 CombinedBookmarkHistoryActivity.class);
3610 String title = current.getTitle();
3611 String url = current.getUrl();
3612 Bitmap thumbnail = createScreenshot(current);
3614 // Just in case the user opens bookmarks before a page finishes loading
3615 // so the current history item, and therefore the page, is null.
3617 url = mLastEnteredUrl;
3620 url = mSettings.getHomePage();
3623 // In case the web page has not yet received its associated title.
3624 if (title == null) {
3627 intent.putExtra("title", title);
3628 intent.putExtra("url", url);
3629 intent.putExtra("thumbnail", thumbnail);
3630 // Disable opening in a new window if we have maxed out the windows
3631 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3632 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3633 if (startWithHistory) {
3634 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3635 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3637 startActivityForResult(intent, COMBO_PAGE);
3640 // Called when loading from context menu or LOAD_URL message
3641 private void loadURL(WebView view, String url) {
3642 // In case the user enters nothing.
3643 if (url != null && url.length() != 0 && view != null) {
3644 url = smartUrlFilter(url);
3645 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3651 private String smartUrlFilter(Uri inUri) {
3652 if (inUri != null) {
3653 return smartUrlFilter(inUri.toString());
3658 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3659 "(?i)" + // switch on case insensitive matching
3660 "(" + // begin group for schema
3661 "(?:http|https|file):\\/\\/" +
3662 "|(?:inline|data|about|content|javascript):" +
3667 * Attempts to determine whether user input is a URL or search
3668 * terms. Anything with a space is passed to search.
3670 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3671 * "Http://" converts to "http://"
3673 * @return Original or modified URL
3676 String smartUrlFilter(String url) {
3678 String inUrl = url.trim();
3679 boolean hasSpace = inUrl.indexOf(' ') != -1;
3681 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3682 if (matcher.matches()) {
3683 // force scheme to lowercase
3684 String scheme = matcher.group(1);
3685 String lcScheme = scheme.toLowerCase();
3686 if (!lcScheme.equals(scheme)) {
3687 inUrl = lcScheme + matcher.group(2);
3690 inUrl = inUrl.replace(" ", "%20");
3695 // FIXME: Is this the correct place to add to searches?
3696 // what if someone else calls this function?
3697 int shortcut = parseUrlShortcut(inUrl);
3698 if (shortcut != SHORTCUT_INVALID) {
3699 Browser.addSearchUrl(mResolver, inUrl);
3700 String query = inUrl.substring(2);
3702 case SHORTCUT_GOOGLE_SEARCH:
3703 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3704 case SHORTCUT_WIKIPEDIA_SEARCH:
3705 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3706 case SHORTCUT_DICTIONARY_SEARCH:
3707 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3708 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3709 // FIXME: we need location in this case
3710 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3714 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3715 return URLUtil.guessUrl(inUrl);
3719 Browser.addSearchUrl(mResolver, inUrl);
3720 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3723 /* package */ void setShouldShowErrorConsole(boolean flag) {
3724 if (flag == mShouldShowErrorConsole) {
3729 mShouldShowErrorConsole = flag;
3731 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3732 .getErrorConsole(true);
3735 // Setting the show state of the console will cause it's the layout to be inflated.
3736 if (errorConsole.numberOfErrors() > 0) {
3737 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3739 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3742 // Now we can add it to the main view.
3743 mErrorConsoleContainer.addView(errorConsole,
3744 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3745 ViewGroup.LayoutParams.WRAP_CONTENT));
3747 mErrorConsoleContainer.removeView(errorConsole);
3752 boolean shouldShowErrorConsole() {
3753 return mShouldShowErrorConsole;
3756 private void setStatusBarVisibility(boolean visible) {
3757 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3758 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3762 private void sendNetworkType(String type, String subtype) {
3763 WebView w = mTabControl.getCurrentWebView();
3765 w.setNetworkType(type, subtype);
3769 final static int LOCK_ICON_UNSECURE = 0;
3770 final static int LOCK_ICON_SECURE = 1;
3771 final static int LOCK_ICON_MIXED = 2;
3773 private BrowserSettings mSettings;
3774 private TabControl mTabControl;
3775 private ContentResolver mResolver;
3776 private FrameLayout mContentView;
3777 private View mCustomView;
3778 private FrameLayout mCustomViewContainer;
3779 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3781 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3782 // view, we should rewrite this.
3783 private int mCurrentMenuState = 0;
3784 private int mMenuState = R.id.MAIN_MENU;
3785 private int mOldMenuState = EMPTY_MENU;
3786 private static final int EMPTY_MENU = -1;
3789 private FindDialog mFindDialog;
3790 // Used to prevent chording to result in firing two shortcuts immediately
3791 // one after another. Fixes bug 1211714.
3794 private boolean mInLoad;
3795 private boolean mIsNetworkUp;
3796 private boolean mDidStopLoad;
3798 private boolean mActivityInPause = true;
3800 private boolean mMenuIsDown;
3802 private static boolean mInTrace;
3804 // Performance probe
3805 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3806 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3807 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3808 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3809 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3810 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3811 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3812 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3813 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3816 private long mStart;
3817 private long mProcessStart;
3818 private long mUserStart;
3819 private long mSystemStart;
3820 private long mIdleStart;
3821 private long mIrqStart;
3823 private long mUiStart;
3825 private Drawable mMixLockIcon;
3826 private Drawable mSecLockIcon;
3828 /* hold a ref so we can auto-cancel if necessary */
3829 private AlertDialog mAlertDialog;
3831 // Wait for credentials before loading google.com
3832 private ProgressDialog mCredsDlg;
3834 // The up-to-date URL and title (these can be different from those stored
3835 // in WebView, since it takes some time for the information in WebView to
3837 private String mUrl;
3838 private String mTitle;
3840 // As PageInfo has different style for landscape / portrait, we have
3841 // to re-open it when configuration changed
3842 private AlertDialog mPageInfoDialog;
3843 private Tab mPageInfoView;
3844 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3845 // dialog, we should not just dismiss it, but should get back to the
3846 // SSL-certificate-on-error dialog. This flag is used to store this state
3847 private boolean mPageInfoFromShowSSLCertificateOnError;
3849 // as SSLCertificateOnError has different style for landscape / portrait,
3850 // we have to re-open it when configuration changed
3851 private AlertDialog mSSLCertificateOnErrorDialog;
3852 private WebView mSSLCertificateOnErrorView;
3853 private SslErrorHandler mSSLCertificateOnErrorHandler;
3854 private SslError mSSLCertificateOnErrorError;
3856 // as SSLCertificate has different style for landscape / portrait, we
3857 // have to re-open it when configuration changed
3858 private AlertDialog mSSLCertificateDialog;
3859 private Tab mSSLCertificateView;
3861 // as HttpAuthentication has different style for landscape / portrait, we
3862 // have to re-open it when configuration changed
3863 private AlertDialog mHttpAuthenticationDialog;
3864 private HttpAuthHandler mHttpAuthHandler;
3866 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3867 new FrameLayout.LayoutParams(
3868 ViewGroup.LayoutParams.MATCH_PARENT,
3869 ViewGroup.LayoutParams.MATCH_PARENT);
3870 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3871 new FrameLayout.LayoutParams(
3872 ViewGroup.LayoutParams.MATCH_PARENT,
3873 ViewGroup.LayoutParams.MATCH_PARENT,
3876 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3878 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3879 // Dictionary search
3880 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3881 // Google Mobile Local search
3882 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3884 final static String QUERY_PLACE_HOLDER = "%s";
3886 // "source" parameter for Google search through search key
3887 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3888 // "source" parameter for Google search through goto menu
3889 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3890 // "source" parameter for Google search through simplily type
3891 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3892 // "source" parameter for Google search suggested by the browser
3893 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3894 // "source" parameter for Google search from unknown source
3895 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3897 private final static String LOGTAG = "browser";
3899 private String mLastEnteredUrl;
3901 private PowerManager.WakeLock mWakeLock;
3902 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3904 private Toast mStopToast;
3906 private TitleBar mTitleBar;
3908 private LinearLayout mErrorConsoleContainer = null;
3909 private boolean mShouldShowErrorConsole = false;
3911 // As the ids are dynamically created, we can't guarantee that they will
3912 // be in sequence, so this static array maps ids to a window number.
3913 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3914 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3915 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3916 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3918 // monitor platform changes
3919 private IntentFilter mNetworkStateChangedFilter;
3920 private BroadcastReceiver mNetworkStateIntentReceiver;
3922 private BroadcastReceiver mPackageInstallationReceiver;
3924 // activity requestCode
3925 final static int COMBO_PAGE = 1;
3926 final static int DOWNLOAD_PAGE = 2;
3927 final static int PREFERENCES_PAGE = 3;
3928 final static int FILE_SELECTED = 4;
3930 // the default <video> poster
3931 private Bitmap mDefaultVideoPoster;
3932 // the video progress view
3933 private View mVideoProgressView;
3936 * A UrlData class to abstract how the content will be set to WebView.
3937 * This base class uses loadUrl to show the content.
3939 private static class UrlData {
3941 final Map<String, String> mHeaders;
3942 final Intent mVoiceIntent;
3944 UrlData(String url) {
3946 this.mHeaders = null;
3947 this.mVoiceIntent = null;
3950 UrlData(String url, Map<String, String> headers, Intent intent) {
3952 this.mHeaders = headers;
3953 if (Tab.VoiceSearchData.VOICE_SEARCH_RESULTS.equals(
3954 intent.getAction())) {
3955 this.mVoiceIntent = intent;
3957 this.mVoiceIntent = null;
3962 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
3965 public void loadIn(Tab t) {
3966 if (mVoiceIntent != null) {
3967 t.activateVoiceSearchMode(mVoiceIntent);
3969 t.getWebView().loadUrl(mUrl, mHeaders);
3974 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);