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.speech.RecognizerResultsIntent;
71 import android.text.IClipboard;
72 import android.text.TextUtils;
73 import android.text.format.DateFormat;
74 import android.util.AttributeSet;
75 import android.util.Log;
76 import android.view.ContextMenu;
77 import android.view.Gravity;
78 import android.view.KeyEvent;
79 import android.view.LayoutInflater;
80 import android.view.Menu;
81 import android.view.MenuInflater;
82 import android.view.MenuItem;
83 import android.view.View;
84 import android.view.ViewGroup;
85 import android.view.Window;
86 import android.view.WindowManager;
87 import android.view.ContextMenu.ContextMenuInfo;
88 import android.view.MenuItem.OnMenuItemClickListener;
89 import android.webkit.CookieManager;
90 import android.webkit.CookieSyncManager;
91 import android.webkit.DownloadListener;
92 import android.webkit.HttpAuthHandler;
93 import android.webkit.PluginManager;
94 import android.webkit.SslErrorHandler;
95 import android.webkit.URLUtil;
96 import android.webkit.ValueCallback;
97 import android.webkit.WebChromeClient;
98 import android.webkit.WebHistoryItem;
99 import android.webkit.WebIconDatabase;
100 import android.webkit.WebView;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.LinearLayout;
104 import android.widget.TextView;
105 import android.widget.Toast;
106 import android.accounts.Account;
107 import android.accounts.AccountManager;
108 import android.accounts.AccountManagerFuture;
109 import android.accounts.AuthenticatorException;
110 import android.accounts.OperationCanceledException;
111 import android.accounts.AccountManagerCallback;
113 import com.android.common.Patterns;
115 import com.google.android.gsf.GoogleLoginServiceConstants;
117 import java.io.ByteArrayOutputStream;
119 import java.io.IOException;
120 import java.io.InputStream;
121 import java.net.MalformedURLException;
123 import java.net.URISyntaxException;
125 import java.net.URLEncoder;
126 import java.text.ParseException;
127 import java.util.Date;
128 import java.util.HashMap;
129 import java.util.Iterator;
130 import java.util.Map;
131 import java.util.regex.Matcher;
132 import java.util.regex.Pattern;
134 public class BrowserActivity extends Activity
135 implements View.OnCreateContextMenuListener, DownloadListener,
136 AccountManagerCallback<Account[]> {
138 /* Define some aliases to make these debugging flags easier to refer to.
139 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
141 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
142 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
143 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
145 // These are single-character shortcuts for searching popular sources.
146 private static final int SHORTCUT_INVALID = 0;
147 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
148 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
149 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
150 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
152 private Account[] mAccountsGoogle;
153 private Account[] mAccountsPreferHosted;
155 private void startReadOfGoogleAccounts() {
156 mAccountsGoogle = null;
157 mAccountsPreferHosted = null;
159 AccountManager.get(this).getAccountsByTypeAndFeatures(
160 GoogleLoginServiceConstants.ACCOUNT_TYPE,
161 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
165 /** This implements AccountManagerCallback<Account[]> */
166 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
168 if (mAccountsGoogle == null) {
169 mAccountsGoogle = accountManagerFuture.getResult();
171 AccountManager.get(this).getAccountsByTypeAndFeatures(
172 GoogleLoginServiceConstants.ACCOUNT_TYPE,
173 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
176 mAccountsPreferHosted = accountManagerFuture.getResult();
179 } catch (OperationCanceledException e) {
181 } catch (IOException e) {
183 } catch (AuthenticatorException e) {
188 private void setupHomePage() {
189 // get the default home page
190 String homepage = mSettings.getHomePage();
192 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
195 // hostedUser == googleUser
196 // The device has only a google account
198 // hostedUser != googleUser
199 // The device has a hosted account and a google account
201 // hostedUser != null, googleUser == null
202 // The device has only a hosted account (so far)
203 String hostedUser = mAccountsPreferHosted.length == 0
205 : mAccountsPreferHosted[0].name;
206 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
208 // developers might have no accounts at all
209 if (hostedUser == null) return;
211 if (googleUser == null || !hostedUser.equals(googleUser)) {
212 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
213 homepage = homepage.replace("?", "/a/" + domain + "?");
217 mSettings.setHomePage(BrowserActivity.this, homepage);
218 resumeAfterCredentials();
221 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
223 public Void doInBackground(File... files) {
225 for (File f : files) {
227 Log.e(LOGTAG, f.getPath() + " was not deleted");
236 * This layout holds everything you see below the status bar, including the
237 * error console, the custom view container, and the webviews.
239 private FrameLayout mBrowserFrameLayout;
242 public void onCreate(Bundle icicle) {
244 Log.v(LOGTAG, this + " onStart");
246 super.onCreate(icicle);
247 // test the browser in OpenGL
248 // requestWindowFeature(Window.FEATURE_OPENGL);
250 // enable this to test the browser in 32bit
252 getWindow().setFormat(PixelFormat.RGBX_8888);
253 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
256 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
258 mResolver = getContentResolver();
260 // If this was a web search request, pass it on to the default web
261 // search provider and finish this activity.
262 if (handleWebSearchIntent(getIntent())) {
267 mSecLockIcon = Resources.getSystem().getDrawable(
268 android.R.drawable.ic_secure);
269 mMixLockIcon = Resources.getSystem().getDrawable(
270 android.R.drawable.ic_partial_secure);
272 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
273 .findViewById(com.android.internal.R.id.content);
274 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
275 .inflate(R.layout.custom_screen, null);
276 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
278 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
279 .findViewById(R.id.error_console);
280 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
281 .findViewById(R.id.fullscreen_custom_content);
282 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
283 mTitleBar = new TitleBar(this);
284 mFakeTitleBar = new TitleBar(this);
286 // Create the tab control and our initial tab
287 mTabControl = new TabControl(this);
289 // Open the icon database and retain all the bookmark urls for favicons
290 retainIconsOnStartup();
292 // Keep a settings instance handy.
293 mSettings = BrowserSettings.getInstance();
294 mSettings.setTabControl(mTabControl);
295 mSettings.loadFromDb(this);
297 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
298 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
300 /* enables registration for changes in network status from
302 mNetworkStateChangedFilter = new IntentFilter();
303 mNetworkStateChangedFilter.addAction(
304 ConnectivityManager.CONNECTIVITY_ACTION);
305 mNetworkStateIntentReceiver = new BroadcastReceiver() {
307 public void onReceive(Context context, Intent intent) {
308 if (intent.getAction().equals(
309 ConnectivityManager.CONNECTIVITY_ACTION)) {
310 boolean noConnectivity = intent.getBooleanExtra(
311 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
312 if (!noConnectivity) {
313 NetworkInfo info = intent.getParcelableExtra(
314 ConnectivityManager.EXTRA_NETWORK_INFO);
315 String typeName = info.getTypeName();
316 String subtypeName = info.getSubtypeName();
317 sendNetworkType(typeName.toLowerCase(),
318 (subtypeName != null ? subtypeName.toLowerCase() : ""));
320 onNetworkToggle(!noConnectivity);
325 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
326 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
327 filter.addDataScheme("package");
328 mPackageInstallationReceiver = new BroadcastReceiver() {
330 public void onReceive(Context context, Intent intent) {
331 final String action = intent.getAction();
332 final String packageName = intent.getData()
333 .getSchemeSpecificPart();
334 final boolean replacing = intent.getBooleanExtra(
335 Intent.EXTRA_REPLACING, false);
336 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
337 // if it is replacing, refreshPlugins() when adding
340 PackageManager pm = BrowserActivity.this.getPackageManager();
341 PackageInfo pkgInfo = null;
343 pkgInfo = pm.getPackageInfo(packageName,
344 PackageManager.GET_PERMISSIONS);
345 } catch (PackageManager.NameNotFoundException e) {
348 if (pkgInfo != null) {
349 String permissions[] = pkgInfo.requestedPermissions;
350 if (permissions == null) {
353 boolean permissionOk = false;
354 for (String permit : permissions) {
355 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
361 PluginManager.getInstance(BrowserActivity.this)
363 Intent.ACTION_PACKAGE_ADDED
369 registerReceiver(mPackageInstallationReceiver, filter);
371 if (!mTabControl.restoreState(icicle)) {
372 // clear up the thumbnail directory if we can't restore the state as
373 // none of the files in the directory are referenced any more.
374 new ClearThumbnails().execute(
375 mTabControl.getThumbnailDir().listFiles());
376 // there is no quit on Android. But if we can't restore the state,
377 // we can treat it as a new Browser, remove the old session cookies.
378 CookieManager.getInstance().removeSessionCookie();
379 final Intent intent = getIntent();
380 final Bundle extra = intent.getExtras();
381 // Create an initial tab.
382 // If the intent is ACTION_VIEW and data is not null, the Browser is
383 // invoked to view the content by another application. In this case,
384 // the tab will be close when exit.
385 UrlData urlData = getUrlDataFromIntent(intent);
387 String action = intent.getAction();
388 final Tab t = mTabControl.createNewTab(
389 (Intent.ACTION_VIEW.equals(action) &&
390 intent.getData() != null)
391 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
393 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
394 mTabControl.setCurrentTab(t);
395 attachTabToContentView(t);
396 WebView webView = t.getWebView();
398 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
399 if (scale > 0 && scale <= 1000) {
400 webView.setInitialScale(scale);
403 // If we are not restoring from an icicle, then there is a high
404 // likely hood this is the first run. So, check to see if the
405 // homepage needs to be configured and copy any plugins from our
406 // asset directory to the data partition.
407 if ((extra == null || !extra.getBoolean("testing"))
408 && !mSettings.isLoginInitialized()) {
409 startReadOfGoogleAccounts();
412 if (urlData.isEmpty()) {
413 if (mSettings.isLoginInitialized()) {
414 webView.loadUrl(mSettings.getHomePage());
416 waitForCredentials();
422 // TabControl.restoreState() will create a new tab even if
423 // restoring the state fails.
424 attachTabToContentView(mTabControl.getCurrentTab());
427 // Read JavaScript flags if it exists.
428 String jsFlags = mSettings.getJsFlags();
429 if (jsFlags.trim().length() != 0) {
430 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
435 * Feed the previously stored results strings to the BrowserProvider so that
436 * the SearchDialog will show them instead of the standard searches.
437 * @param result String to show on the editable line of the SearchDialog.
439 /* package */ void showVoiceSearchResults(String result) {
440 ContentProviderClient client = mResolver.acquireContentProviderClient(
441 Browser.BOOKMARKS_URI);
442 ContentProvider prov = client.getLocalContentProvider();
443 BrowserProvider bp = (BrowserProvider) prov;
444 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
447 startSearch(result, false,
448 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
453 protected void onNewIntent(Intent intent) {
454 Tab current = mTabControl.getCurrentTab();
455 // When a tab is closed on exit, the current tab index is set to -1.
456 // Reset before proceed as Browser requires the current tab to be set.
457 if (current == null) {
458 // Try to reset the tab in case the index was incorrect.
459 current = mTabControl.getTab(0);
460 if (current == null) {
461 // No tabs at all so just ignore this intent.
464 mTabControl.setCurrentTab(current);
465 attachTabToContentView(current);
466 resetTitleAndIcon(current.getWebView());
468 final String action = intent.getAction();
469 final int flags = intent.getFlags();
470 if (Intent.ACTION_MAIN.equals(action) ||
471 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
472 // just resume the browser
475 boolean activateVoiceSearch = RecognizerResultsIntent
476 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
477 if (Intent.ACTION_VIEW.equals(action)
478 || Intent.ACTION_SEARCH.equals(action)
479 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
480 || Intent.ACTION_WEB_SEARCH.equals(action)
481 || activateVoiceSearch) {
482 // If this was a search request (e.g. search query directly typed into the address bar),
483 // pass it on to the default web search provider.
484 if (handleWebSearchIntent(intent)) {
488 UrlData urlData = getUrlDataFromIntent(intent);
489 if (urlData.isEmpty()) {
490 urlData = new UrlData(mSettings.getHomePage());
493 final String appId = intent
494 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
495 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
496 && !getPackageName().equals(appId)
497 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
498 Tab appTab = mTabControl.getTabFromId(appId);
499 if (appTab != null) {
500 Log.i(LOGTAG, "Reusing tab for " + appId);
501 // Dismiss the subwindow if applicable.
502 dismissSubWindow(appTab);
503 // Since we might kill the WebView, remove it from the
504 // content view first.
505 removeTabFromContentView(appTab);
506 // Recreate the main WebView after destroying the old one.
507 // If the WebView has the same original url and is on that
508 // page, it can be reused.
510 mTabControl.recreateWebView(appTab, urlData.mUrl);
512 if (current != appTab) {
513 switchToTab(mTabControl.getTabIndex(appTab));
515 urlData.loadIn(appTab);
518 // If the tab was the current tab, we have to attach
519 // it to the view system again.
520 attachTabToContentView(appTab);
522 urlData.loadIn(appTab);
527 // No matching application tab, try to find a regular tab
528 // with a matching url.
529 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
530 if (appTab != null) {
531 if (current != appTab) {
532 switchToTab(mTabControl.getTabIndex(appTab));
534 // Otherwise, we are already viewing the correct tab.
536 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
537 // will be opened in a new tab unless we have reached
538 // MAX_TABS. Then the url will be opened in the current
539 // tab. If a new tab is created, it will have "true" for
541 openTabAndShow(urlData, true, appId);
545 if (!urlData.isEmpty()
546 && urlData.mUrl.startsWith("about:debug")) {
547 if ("about:debug.dom".equals(urlData.mUrl)) {
548 current.getWebView().dumpDomTree(false);
549 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
550 current.getWebView().dumpDomTree(true);
551 } else if ("about:debug.render".equals(urlData.mUrl)) {
552 current.getWebView().dumpRenderTree(false);
553 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
554 current.getWebView().dumpRenderTree(true);
555 } else if ("about:debug.display".equals(urlData.mUrl)) {
556 current.getWebView().dumpDisplayTree();
557 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
558 int index = urlData.mUrl.codePointAt(16) - '0';
559 if (index <= 0 || index > 9) {
560 current.getWebView().setDragTracker(null);
562 current.getWebView().setDragTracker(new MeshTracker(index));
565 mSettings.toggleDebugSettings();
569 // Get rid of the subwindow if it exists
570 dismissSubWindow(current);
571 urlData.loadIn(current);
576 private int parseUrlShortcut(String url) {
577 if (url == null) return SHORTCUT_INVALID;
579 // FIXME: quick search, need to be customized by setting
580 if (url.length() > 2 && url.charAt(1) == ' ') {
581 switch (url.charAt(0)) {
582 case 'g': return SHORTCUT_GOOGLE_SEARCH;
583 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
584 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
585 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
588 return SHORTCUT_INVALID;
592 * Launches the default web search activity with the query parameters if the given intent's data
593 * are identified as plain search terms and not URLs/shortcuts.
594 * @return true if the intent was handled and web search activity was launched, false if not.
596 private boolean handleWebSearchIntent(Intent intent) {
597 if (intent == null) return false;
600 final String action = intent.getAction();
601 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
605 if (Intent.ACTION_VIEW.equals(action)) {
606 Uri data = intent.getData();
607 if (data != null) url = data.toString();
608 } else if (Intent.ACTION_SEARCH.equals(action)
609 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
610 || Intent.ACTION_WEB_SEARCH.equals(action)) {
611 url = intent.getStringExtra(SearchManager.QUERY);
613 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
614 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
618 * Launches the default web search activity with the query parameters if the given url string
619 * was identified as plain search terms and not URL/shortcut.
620 * @return true if the request was handled and web search activity was launched, false if not.
622 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
623 if (inUrl == null) return false;
625 // In general, we shouldn't modify URL from Intent.
626 // But currently, we get the user-typed URL from search box as well.
627 String url = fixUrl(inUrl).trim();
629 // URLs and site specific search shortcuts are handled by the regular flow of control, so
631 if (Patterns.WEB_URL.matcher(url).matches()
632 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
633 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
637 Browser.updateVisitedHistory(mResolver, url, false);
638 Browser.addSearchUrl(mResolver, url);
640 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
641 intent.addCategory(Intent.CATEGORY_DEFAULT);
642 intent.putExtra(SearchManager.QUERY, url);
643 if (appData != null) {
644 intent.putExtra(SearchManager.APP_DATA, appData);
646 if (extraData != null) {
647 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
649 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
650 startActivity(intent);
655 private UrlData getUrlDataFromIntent(Intent intent) {
657 Map<String, String> headers = null;
658 if (intent != null) {
659 final String action = intent.getAction();
660 if (Intent.ACTION_VIEW.equals(action)) {
661 url = smartUrlFilter(intent.getData());
662 if (url != null && url.startsWith("content:")) {
663 /* Append mimetype so webview knows how to display */
664 String mimeType = intent.resolveType(getContentResolver());
665 if (mimeType != null) {
666 url += "?" + mimeType;
669 if (url != null && url.startsWith("http")) {
670 final Bundle pairs = intent
671 .getBundleExtra(Browser.EXTRA_HEADERS);
672 if (pairs != null && !pairs.isEmpty()) {
673 Iterator<String> iter = pairs.keySet().iterator();
674 headers = new HashMap<String, String>();
675 while (iter.hasNext()) {
676 String key = iter.next();
677 headers.put(key, pairs.getString(key));
681 } else if (Intent.ACTION_SEARCH.equals(action)
682 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
683 || Intent.ACTION_WEB_SEARCH.equals(action)) {
684 url = intent.getStringExtra(SearchManager.QUERY);
686 mLastEnteredUrl = url;
687 Browser.updateVisitedHistory(mResolver, url, false);
688 // In general, we shouldn't modify URL from Intent.
689 // But currently, we get the user-typed URL from search box as well.
691 url = smartUrlFilter(url);
692 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
693 if (url.contains(searchSource)) {
694 String source = null;
695 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
696 if (appData != null) {
697 source = appData.getString(SearchManager.SOURCE);
699 if (TextUtils.isEmpty(source)) {
700 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
702 url = url.replace(searchSource, "&source=android-"+source+"&");
707 return new UrlData(url, headers, intent);
709 /* package */ void showVoiceTitleBar(String title) {
710 mTitleBar.setInVoiceMode(true);
711 mFakeTitleBar.setInVoiceMode(true);
713 mTitleBar.setDisplayTitle(title);
714 mFakeTitleBar.setDisplayTitle(title);
716 /* package */ void revertVoiceTitleBar() {
717 mTitleBar.setInVoiceMode(false);
718 mFakeTitleBar.setInVoiceMode(false);
720 mTitleBar.setDisplayTitle(mTitle);
721 mFakeTitleBar.setDisplayTitle(mTitle);
723 /* package */ static String fixUrl(String inUrl) {
724 // FIXME: Converting the url to lower case
725 // duplicates functionality in smartUrlFilter().
726 // However, changing all current callers of fixUrl to
727 // call smartUrlFilter in addition may have unwanted
728 // consequences, and is deferred for now.
729 int colon = inUrl.indexOf(':');
730 boolean allLower = true;
731 for (int index = 0; index < colon; index++) {
732 char ch = inUrl.charAt(index);
733 if (!Character.isLetter(ch)) {
736 allLower &= Character.isLowerCase(ch);
737 if (index == colon - 1 && !allLower) {
738 inUrl = inUrl.substring(0, colon).toLowerCase()
739 + inUrl.substring(colon);
742 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
744 if (inUrl.startsWith("http:") ||
745 inUrl.startsWith("https:")) {
746 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
747 inUrl = inUrl.replaceFirst("/", "//");
748 } else inUrl = inUrl.replaceFirst(":", "://");
754 protected void onResume() {
757 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
760 if (!mActivityInPause) {
761 Log.e(LOGTAG, "BrowserActivity is already resumed.");
765 mTabControl.resumeCurrentTab();
766 mActivityInPause = false;
767 resumeWebViewTimers();
769 if (mWakeLock.isHeld()) {
770 mHandler.removeMessages(RELEASE_WAKELOCK);
774 if (mCredsDlg != null) {
775 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
776 // In case credential request never comes back
777 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
781 registerReceiver(mNetworkStateIntentReceiver,
782 mNetworkStateChangedFilter);
783 WebView.enablePlatformNotifications();
787 * Since the actual title bar is embedded in the WebView, and removing it
788 * would change its appearance, use a different TitleBar to show overlayed
789 * at the top of the screen, when the menu is open or the page is loading.
791 private TitleBar mFakeTitleBar;
794 * Holder for the fake title bar. It will have a foreground shadow, as well
795 * as a white background, so the fake title bar looks like the real one.
797 private ViewGroup mFakeTitleBarHolder;
800 * Layout parameters for the fake title bar within mFakeTitleBarHolder
802 private FrameLayout.LayoutParams mFakeTitleBarParams
803 = new FrameLayout.LayoutParams(
804 ViewGroup.LayoutParams.MATCH_PARENT,
805 ViewGroup.LayoutParams.WRAP_CONTENT);
807 * Keeps track of whether the options menu is open. This is important in
808 * determining whether to show or hide the title bar overlay.
810 private boolean mOptionsMenuOpen;
813 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
814 * of whether the configuration has changed. The first onMenuOpened call
815 * after a configuration change is simply a reopening of the same menu
816 * (i.e. mIconView did not change).
818 private boolean mConfigChanged;
821 * Whether or not the options menu is in its smaller, icon menu form. When
822 * true, we want the title bar overlay to be up. When false, we do not.
823 * Only meaningful if mOptionsMenuOpen is true.
825 private boolean mIconView;
828 public boolean onMenuOpened(int featureId, Menu menu) {
829 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
830 if (mOptionsMenuOpen) {
831 if (mConfigChanged) {
832 // We do not need to make any changes to the state of the
833 // title bar, since the only thing that happened was a
834 // change in orientation
835 mConfigChanged = false;
838 // Switching the menu to expanded view, so hide the
843 // Switching the menu back to icon view, so show the
844 // title bar once again.
850 // The options menu is closed, so open it, and show the title
852 mOptionsMenuOpen = true;
853 mConfigChanged = false;
861 * Special class used exclusively for the shadow drawn underneath the fake
862 * title bar. The shadow does not need to be drawn if the WebView
863 * underneath is scrolled to the top, because it will draw directly on top
864 * of the embedded shadow.
866 private static class Shadow extends View {
867 private WebView mWebView;
869 public Shadow(Context context, AttributeSet attrs) {
870 super(context, attrs);
873 public void setWebView(WebView view) {
878 public void draw(Canvas canvas) {
879 // In general onDraw is the method to override, but we care about
880 // whether or not the background gets drawn, which happens in draw()
881 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
884 // Need to invalidate so that if the scroll position changes, we
885 // still draw as appropriate.
890 private void showFakeTitleBar() {
891 final View decor = getWindow().peekDecorView();
892 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
893 && !mActivityInPause && decor != null
894 && decor.getWindowToken() != null) {
895 Rect visRect = new Rect();
896 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
898 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
903 WindowManager manager
904 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
906 // Add the title bar to the window manager so it can receive touches
907 // while the menu is up
908 WindowManager.LayoutParams params
909 = new WindowManager.LayoutParams(
910 ViewGroup.LayoutParams.MATCH_PARENT,
911 ViewGroup.LayoutParams.WRAP_CONTENT,
912 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
913 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
914 PixelFormat.TRANSLUCENT);
915 params.gravity = Gravity.TOP;
916 WebView mainView = mTabControl.getCurrentWebView();
917 boolean atTop = mainView != null && mainView.getScrollY() == 0;
918 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
919 // XXX : Without providing an offset, the fake title bar will be
920 // placed underneath the status bar. Use the global visible rect
921 // of mBrowserFrameLayout to determine the bottom of the status bar
922 params.y = visRect.top;
923 // Add a holder for the title bar. It also holds a shadow to show
924 // below the title bar.
925 if (mFakeTitleBarHolder == null) {
926 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
927 .inflate(R.layout.title_bar_bg, null);
929 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
931 shadow.setWebView(mainView);
932 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
933 manager.addView(mFakeTitleBarHolder, params);
938 public void onOptionsMenuClosed(Menu menu) {
939 mOptionsMenuOpen = false;
942 } else if (!mIconView) {
943 // The page is currently loading, and we are in expanded mode, so
944 // we were not showing the menu. Show it once again. It will be
945 // removed when the page finishes.
950 private void hideFakeTitleBar() {
951 if (mFakeTitleBar.getParent() == null) return;
952 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
953 mFakeTitleBarHolder.getLayoutParams();
954 WebView mainView = mTabControl.getCurrentWebView();
955 // Although we decided whether or not to animate based on the current
956 // scroll position, the scroll position may have changed since the
957 // fake title bar was displayed. Make sure it has the appropriate
958 // animation/lack thereof before removing.
959 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
960 ? 0 : R.style.TitleBar;
961 WindowManager manager
962 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
963 manager.updateViewLayout(mFakeTitleBarHolder, params);
964 mFakeTitleBarHolder.removeView(mFakeTitleBar);
965 manager.removeView(mFakeTitleBarHolder);
969 * Special method for the fake title bar to call when displaying its context
970 * menu, since it is in its own Window, and its parent does not show a
973 /* package */ void showTitleBarContextMenu() {
974 if (null == mTitleBar.getParent()) {
977 openContextMenu(mTitleBar);
981 public void onContextMenuClosed(Menu menu) {
982 super.onContextMenuClosed(menu);
989 * onSaveInstanceState(Bundle map)
990 * onSaveInstanceState is called right before onStop(). The map contains
994 protected void onSaveInstanceState(Bundle outState) {
996 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
998 // the default implementation requires each view to have an id. As the
999 // browser handles the state itself and it doesn't use id for the views,
1000 // don't call the default implementation. Otherwise it will trigger the
1001 // warning like this, "couldn't save which view has focus because the
1002 // focused view XXX has no id".
1004 // Save all the tabs
1005 mTabControl.saveState(outState);
1009 protected void onPause() {
1012 if (mActivityInPause) {
1013 Log.e(LOGTAG, "BrowserActivity is already paused.");
1017 mTabControl.pauseCurrentTab();
1018 mActivityInPause = true;
1019 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1020 mWakeLock.acquire();
1021 mHandler.sendMessageDelayed(mHandler
1022 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1025 // Clear the credentials toast if it is up
1026 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1027 mCredsDlg.dismiss();
1031 // FIXME: This removes the active tabs page and resets the menu to
1032 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1033 // but then we would need to save it in onSaveInstanceState and restore
1034 // it in onCreate/onRestoreInstanceState
1035 if (mActiveTabsPage != null) {
1036 removeActiveTabPage(true);
1041 // unregister network state listener
1042 unregisterReceiver(mNetworkStateIntentReceiver);
1043 WebView.disablePlatformNotifications();
1047 protected void onDestroy() {
1049 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1053 if (mUploadMessage != null) {
1054 mUploadMessage.onReceiveValue(null);
1055 mUploadMessage = null;
1058 if (mTabControl == null) return;
1060 // Remove the fake title bar if it is there
1063 // Remove the current tab and sub window
1064 Tab t = mTabControl.getCurrentTab();
1066 dismissSubWindow(t);
1067 removeTabFromContentView(t);
1069 // Destroy all the tabs
1070 mTabControl.destroy();
1071 WebIconDatabase.getInstance().close();
1073 unregisterReceiver(mPackageInstallationReceiver);
1077 public void onConfigurationChanged(Configuration newConfig) {
1078 mConfigChanged = true;
1079 super.onConfigurationChanged(newConfig);
1081 if (mPageInfoDialog != null) {
1082 mPageInfoDialog.dismiss();
1085 mPageInfoFromShowSSLCertificateOnError);
1087 if (mSSLCertificateDialog != null) {
1088 mSSLCertificateDialog.dismiss();
1090 mSSLCertificateView);
1092 if (mSSLCertificateOnErrorDialog != null) {
1093 mSSLCertificateOnErrorDialog.dismiss();
1094 showSSLCertificateOnError(
1095 mSSLCertificateOnErrorView,
1096 mSSLCertificateOnErrorHandler,
1097 mSSLCertificateOnErrorError);
1099 if (mHttpAuthenticationDialog != null) {
1100 String title = ((TextView) mHttpAuthenticationDialog
1101 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1103 String name = ((TextView) mHttpAuthenticationDialog
1104 .findViewById(R.id.username_edit)).getText().toString();
1105 String password = ((TextView) mHttpAuthenticationDialog
1106 .findViewById(R.id.password_edit)).getText().toString();
1107 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1109 mHttpAuthenticationDialog.dismiss();
1110 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1111 name, password, focusId);
1116 public void onLowMemory() {
1117 super.onLowMemory();
1118 mTabControl.freeMemory();
1121 private boolean resumeWebViewTimers() {
1122 Tab tab = mTabControl.getCurrentTab();
1123 boolean inLoad = tab.inLoad();
1124 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1125 CookieSyncManager.getInstance().startSync();
1126 WebView w = tab.getWebView();
1136 private boolean pauseWebViewTimers() {
1137 Tab tab = mTabControl.getCurrentTab();
1138 boolean inLoad = tab.inLoad();
1139 if (mActivityInPause && !inLoad) {
1140 CookieSyncManager.getInstance().stopSync();
1141 WebView w = mTabControl.getCurrentWebView();
1151 // FIXME: Do we want to call this when loading google for the first time?
1153 * This function is called when we are launching for the first time. We
1154 * are waiting for the login credentials before loading Google home
1155 * pages. This way the user will be logged in straight away.
1157 private void waitForCredentials() {
1159 mCredsDlg = new ProgressDialog(this);
1160 mCredsDlg.setIndeterminate(true);
1161 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1162 // If the user cancels the operation, then cancel the Google
1163 // Credentials request.
1164 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1167 // We set a timeout for the retrieval of credentials in onResume()
1168 // as that is when we have freed up some CPU time to get
1169 // the login credentials.
1173 * If we have received the credentials or we have timed out and we are
1174 * showing the credentials dialog, then it is time to move on.
1176 private void resumeAfterCredentials() {
1177 if (mCredsDlg == null) {
1182 if (mCredsDlg.isShowing()) {
1183 mCredsDlg.dismiss();
1187 // Clear any pending timeout
1188 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1191 WebView w = mTabControl.getCurrentWebView();
1193 w.loadUrl(mSettings.getHomePage());
1196 // Update the settings, need to do this last as it can take a moment
1197 // to persist the settings. In the mean time we could be loading
1199 mSettings.setLoginInitialized(this);
1202 // Open the icon database and retain all the icons for visited sites.
1203 private void retainIconsOnStartup() {
1204 final WebIconDatabase db = WebIconDatabase.getInstance();
1205 db.open(getDir("icons", 0).getPath());
1207 Cursor c = Browser.getAllBookmarks(mResolver);
1208 if (!c.moveToFirst()) {
1212 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1214 String url = c.getString(urlIndex);
1215 db.retainIconForPageUrl(url);
1216 } while (c.moveToNext());
1218 } catch (IllegalStateException e) {
1219 Log.e(LOGTAG, "retainIconsOnStartup", e);
1223 // Helper method for getting the top window.
1224 WebView getTopWindow() {
1225 return mTabControl.getCurrentTopWebView();
1228 TabControl getTabControl() {
1233 public boolean onCreateOptionsMenu(Menu menu) {
1234 super.onCreateOptionsMenu(menu);
1236 MenuInflater inflater = getMenuInflater();
1237 inflater.inflate(R.menu.browser, menu);
1239 updateInLoadMenuItems();
1244 * As the menu can be open when loading state changes
1245 * we must manually update the state of the stop/reload menu
1248 private void updateInLoadMenuItems() {
1249 if (mMenu == null) {
1252 MenuItem src = mInLoad ?
1253 mMenu.findItem(R.id.stop_menu_id):
1254 mMenu.findItem(R.id.reload_menu_id);
1255 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1256 dest.setIcon(src.getIcon());
1257 dest.setTitle(src.getTitle());
1261 public boolean onContextItemSelected(MenuItem item) {
1262 // chording is not an issue with context menus, but we use the same
1263 // options selector, so set mCanChord to true so we can access them.
1265 int id = item.getItemId();
1266 boolean result = true;
1268 // For the context menu from the title bar
1269 case R.id.title_bar_copy_page_url:
1270 Tab currentTab = mTabControl.getCurrentTab();
1271 if (null == currentTab) {
1275 WebView mainView = currentTab.getWebView();
1276 if (null == mainView) {
1280 copy(mainView.getUrl());
1282 // -- Browser context menu
1283 case R.id.open_context_menu_id:
1284 case R.id.open_newtab_context_menu_id:
1285 case R.id.bookmark_context_menu_id:
1286 case R.id.save_link_context_menu_id:
1287 case R.id.share_link_context_menu_id:
1288 case R.id.copy_link_context_menu_id:
1289 final WebView webView = getTopWindow();
1290 if (null == webView) {
1294 final HashMap hrefMap = new HashMap();
1295 hrefMap.put("webview", webView);
1296 final Message msg = mHandler.obtainMessage(
1297 FOCUS_NODE_HREF, id, 0, hrefMap);
1298 webView.requestFocusNodeHref(msg);
1302 // For other context menus
1303 result = onOptionsItemSelected(item);
1309 private Bundle createGoogleSearchSourceBundle(String source) {
1310 Bundle bundle = new Bundle();
1311 bundle.putString(SearchManager.SOURCE, source);
1316 * Overriding this to insert a local information bundle
1319 public boolean onSearchRequested() {
1320 if (mOptionsMenuOpen) closeOptionsMenu();
1321 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1322 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1323 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1328 public void startSearch(String initialQuery, boolean selectInitialQuery,
1329 Bundle appSearchData, boolean globalSearch) {
1330 if (appSearchData == null) {
1331 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1333 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1337 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1338 * results in changing tabs.
1339 * @param index Index of the tab to change to, as defined by
1340 * mTabControl.getTabIndex(Tab t).
1341 * @return boolean True if we successfully switched to a different tab. If
1342 * the indexth tab is null, or if that tab is the same as
1343 * the current one, return false.
1345 /* package */ boolean switchToTab(int index) {
1346 Tab tab = mTabControl.getTab(index);
1347 Tab currentTab = mTabControl.getCurrentTab();
1348 if (tab == null || tab == currentTab) {
1351 if (currentTab != null) {
1352 // currentTab may be null if it was just removed. In that case,
1353 // we do not need to remove it
1354 removeTabFromContentView(currentTab);
1356 mTabControl.setCurrentTab(tab);
1357 attachTabToContentView(tab);
1358 resetTitleIconAndProgress();
1359 updateLockIconToLatest();
1363 /* package */ Tab openTabToHomePage() {
1364 return openTabAndShow(mSettings.getHomePage(), false, null);
1367 /* package */ void closeCurrentWindow() {
1368 final Tab current = mTabControl.getCurrentTab();
1369 if (mTabControl.getTabCount() == 1) {
1370 // This is the last tab. Open a new one, with the home
1371 // page and close the current one.
1372 openTabToHomePage();
1376 final Tab parent = current.getParentTab();
1377 int indexToShow = -1;
1378 if (parent != null) {
1379 indexToShow = mTabControl.getTabIndex(parent);
1381 final int currentIndex = mTabControl.getCurrentIndex();
1382 // Try to move to the tab to the right
1383 indexToShow = currentIndex + 1;
1384 if (indexToShow > mTabControl.getTabCount() - 1) {
1385 // Try to move to the tab to the left
1386 indexToShow = currentIndex - 1;
1389 if (switchToTab(indexToShow)) {
1395 private ActiveTabsPage mActiveTabsPage;
1398 * Remove the active tabs page.
1399 * @param needToAttach If true, the active tabs page did not attach a tab
1400 * to the content view, so we need to do that here.
1402 /* package */ void removeActiveTabPage(boolean needToAttach) {
1403 mContentView.removeView(mActiveTabsPage);
1404 mActiveTabsPage = null;
1405 mMenuState = R.id.MAIN_MENU;
1407 attachTabToContentView(mTabControl.getCurrentTab());
1409 getTopWindow().requestFocus();
1413 public boolean onOptionsItemSelected(MenuItem item) {
1415 // The user has already fired a shortcut with this hold down of the
1419 if (null == getTopWindow()) {
1423 // The shortcut action consumes the MENU. Even if it is still down,
1424 // it won't trigger the next shortcut action. In the case of the
1425 // shortcut action triggering a new activity, like Bookmarks, we
1426 // won't get onKeyUp for MENU. So it is important to reset it here.
1427 mMenuIsDown = false;
1429 switch (item.getItemId()) {
1431 case R.id.new_tab_menu_id:
1432 openTabToHomePage();
1435 case R.id.goto_menu_id:
1436 onSearchRequested();
1439 case R.id.bookmarks_menu_id:
1440 bookmarksOrHistoryPicker(false);
1443 case R.id.active_tabs_menu_id:
1444 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1445 removeTabFromContentView(mTabControl.getCurrentTab());
1447 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1448 mActiveTabsPage.requestFocus();
1449 mMenuState = EMPTY_MENU;
1452 case R.id.add_bookmark_menu_id:
1453 Intent i = new Intent(BrowserActivity.this,
1454 AddBookmarkPage.class);
1455 WebView w = getTopWindow();
1456 i.putExtra("url", w.getUrl());
1457 i.putExtra("title", w.getTitle());
1458 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1459 i.putExtra("thumbnail", createScreenshot(w));
1463 case R.id.stop_reload_menu_id:
1467 getTopWindow().reload();
1471 case R.id.back_menu_id:
1472 getTopWindow().goBack();
1475 case R.id.forward_menu_id:
1476 getTopWindow().goForward();
1479 case R.id.close_menu_id:
1480 // Close the subwindow if it exists.
1481 if (mTabControl.getCurrentSubWindow() != null) {
1482 dismissSubWindow(mTabControl.getCurrentTab());
1485 closeCurrentWindow();
1488 case R.id.homepage_menu_id:
1489 Tab current = mTabControl.getCurrentTab();
1490 if (current != null) {
1491 dismissSubWindow(current);
1492 current.getWebView().loadUrl(mSettings.getHomePage());
1496 case R.id.preferences_menu_id:
1497 Intent intent = new Intent(this,
1498 BrowserPreferencesPage.class);
1499 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1500 getTopWindow().getUrl());
1501 startActivityForResult(intent, PREFERENCES_PAGE);
1504 case R.id.find_menu_id:
1505 if (null == mFindDialog) {
1506 mFindDialog = new FindDialog(this);
1508 mFindDialog.setWebView(getTopWindow());
1510 mMenuState = EMPTY_MENU;
1513 case R.id.select_text_id:
1514 getTopWindow().emulateShiftHeld();
1516 case R.id.page_info_menu_id:
1517 showPageInfo(mTabControl.getCurrentTab(), false);
1520 case R.id.classic_history_menu_id:
1521 bookmarksOrHistoryPicker(true);
1524 case R.id.title_bar_share_page_url:
1525 case R.id.share_page_menu_id:
1526 Tab currentTab = mTabControl.getCurrentTab();
1527 if (null == currentTab) {
1531 currentTab.populatePickerData();
1532 sharePage(this, currentTab.getTitle(),
1533 currentTab.getUrl(), currentTab.getFavicon(),
1534 createScreenshot(currentTab.getWebView()));
1537 case R.id.dump_nav_menu_id:
1538 getTopWindow().debugDump();
1541 case R.id.zoom_in_menu_id:
1542 getTopWindow().zoomIn();
1545 case R.id.zoom_out_menu_id:
1546 getTopWindow().zoomOut();
1549 case R.id.view_downloads_menu_id:
1550 viewDownloads(null);
1553 case R.id.window_one_menu_id:
1554 case R.id.window_two_menu_id:
1555 case R.id.window_three_menu_id:
1556 case R.id.window_four_menu_id:
1557 case R.id.window_five_menu_id:
1558 case R.id.window_six_menu_id:
1559 case R.id.window_seven_menu_id:
1560 case R.id.window_eight_menu_id:
1562 int menuid = item.getItemId();
1563 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1564 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1565 Tab desiredTab = mTabControl.getTab(id);
1566 if (desiredTab != null &&
1567 desiredTab != mTabControl.getCurrentTab()) {
1577 if (!super.onOptionsItemSelected(item)) {
1580 // Otherwise fall through.
1586 public void closeFind() {
1587 mMenuState = R.id.MAIN_MENU;
1591 public boolean onPrepareOptionsMenu(Menu menu) {
1592 // This happens when the user begins to hold down the menu key, so
1593 // allow them to chord to get a shortcut.
1595 // Note: setVisible will decide whether an item is visible; while
1596 // setEnabled() will decide whether an item is enabled, which also means
1597 // whether the matching shortcut key will function.
1598 super.onPrepareOptionsMenu(menu);
1599 switch (mMenuState) {
1601 if (mCurrentMenuState != mMenuState) {
1602 menu.setGroupVisible(R.id.MAIN_MENU, false);
1603 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1604 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1608 if (mCurrentMenuState != mMenuState) {
1609 menu.setGroupVisible(R.id.MAIN_MENU, true);
1610 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1611 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1613 final WebView w = getTopWindow();
1614 boolean canGoBack = false;
1615 boolean canGoForward = false;
1616 boolean isHome = false;
1618 canGoBack = w.canGoBack();
1619 canGoForward = w.canGoForward();
1620 isHome = mSettings.getHomePage().equals(w.getUrl());
1622 final MenuItem back = menu.findItem(R.id.back_menu_id);
1623 back.setEnabled(canGoBack);
1625 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1626 home.setEnabled(!isHome);
1628 menu.findItem(R.id.forward_menu_id)
1629 .setEnabled(canGoForward);
1631 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1632 mTabControl.canCreateNewTab());
1634 // decide whether to show the share link option
1635 PackageManager pm = getPackageManager();
1636 Intent send = new Intent(Intent.ACTION_SEND);
1637 send.setType("text/plain");
1638 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1639 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1641 boolean isNavDump = mSettings.isNavDump();
1642 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1643 nav.setVisible(isNavDump);
1644 nav.setEnabled(isNavDump);
1647 mCurrentMenuState = mMenuState;
1652 public void onCreateContextMenu(ContextMenu menu, View v,
1653 ContextMenuInfo menuInfo) {
1654 WebView webview = (WebView) v;
1655 WebView.HitTestResult result = webview.getHitTestResult();
1656 if (result == null) {
1660 int type = result.getType();
1661 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1663 "We should not show context menu when nothing is touched");
1666 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1667 // let TextView handles context menu
1671 // Note, http://b/issue?id=1106666 is requesting that
1672 // an inflated menu can be used again. This is not available
1673 // yet, so inflate each time (yuk!)
1674 MenuInflater inflater = getMenuInflater();
1675 inflater.inflate(R.menu.browsercontext, menu);
1677 // Show the correct menu group
1678 String extra = result.getExtra();
1679 menu.setGroupVisible(R.id.PHONE_MENU,
1680 type == WebView.HitTestResult.PHONE_TYPE);
1681 menu.setGroupVisible(R.id.EMAIL_MENU,
1682 type == WebView.HitTestResult.EMAIL_TYPE);
1683 menu.setGroupVisible(R.id.GEO_MENU,
1684 type == WebView.HitTestResult.GEO_TYPE);
1685 menu.setGroupVisible(R.id.IMAGE_MENU,
1686 type == WebView.HitTestResult.IMAGE_TYPE
1687 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1688 menu.setGroupVisible(R.id.ANCHOR_MENU,
1689 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1690 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1692 // Setup custom handling depending on the type
1694 case WebView.HitTestResult.PHONE_TYPE:
1695 menu.setHeaderTitle(Uri.decode(extra));
1696 menu.findItem(R.id.dial_context_menu_id).setIntent(
1697 new Intent(Intent.ACTION_VIEW, Uri
1698 .parse(WebView.SCHEME_TEL + extra)));
1699 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1700 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1701 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1702 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1704 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1708 case WebView.HitTestResult.EMAIL_TYPE:
1709 menu.setHeaderTitle(extra);
1710 menu.findItem(R.id.email_context_menu_id).setIntent(
1711 new Intent(Intent.ACTION_VIEW, Uri
1712 .parse(WebView.SCHEME_MAILTO + extra)));
1713 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1717 case WebView.HitTestResult.GEO_TYPE:
1718 menu.setHeaderTitle(extra);
1719 menu.findItem(R.id.map_context_menu_id).setIntent(
1720 new Intent(Intent.ACTION_VIEW, Uri
1721 .parse(WebView.SCHEME_GEO
1722 + URLEncoder.encode(extra))));
1723 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1727 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1728 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1729 TextView titleView = (TextView) LayoutInflater.from(this)
1730 .inflate(android.R.layout.browser_link_context_header,
1732 titleView.setText(extra);
1733 menu.setHeaderView(titleView);
1734 // decide whether to show the open link in new tab option
1735 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1736 mTabControl.canCreateNewTab());
1737 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1738 Bookmarks.urlHasAcceptableScheme(extra));
1739 PackageManager pm = getPackageManager();
1740 Intent send = new Intent(Intent.ACTION_SEND);
1741 send.setType("text/plain");
1742 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1743 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1744 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1747 // otherwise fall through to handle image part
1748 case WebView.HitTestResult.IMAGE_TYPE:
1749 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1750 menu.setHeaderTitle(extra);
1752 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1753 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1754 menu.findItem(R.id.download_context_menu_id).
1755 setOnMenuItemClickListener(new Download(extra));
1756 menu.findItem(R.id.set_wallpaper_context_menu_id).
1757 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1761 Log.w(LOGTAG, "We should not get here.");
1767 // Attach the given tab to the content view.
1768 // this should only be called for the current tab.
1769 private void attachTabToContentView(Tab t) {
1770 // Attach the container that contains the main WebView and any other UI
1771 // associated with the tab.
1772 t.attachTabToContentView(mContentView);
1774 if (mShouldShowErrorConsole) {
1775 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1776 if (errorConsole.numberOfErrors() == 0) {
1777 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1779 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1782 mErrorConsoleContainer.addView(errorConsole,
1783 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1784 ViewGroup.LayoutParams.WRAP_CONTENT));
1787 WebView view = t.getWebView();
1788 view.setEmbeddedTitleBar(mTitleBar);
1789 if (t.isInVoiceSearchMode()) {
1790 showVoiceTitleBar(t.getVoiceDisplayTitle());
1792 revertVoiceTitleBar();
1794 // Request focus on the top window.
1795 t.getTopWindow().requestFocus();
1798 // Attach a sub window to the main WebView of the given tab.
1799 void attachSubWindow(Tab t) {
1800 t.attachSubWindow(mContentView);
1801 getTopWindow().requestFocus();
1804 // Remove the given tab from the content view.
1805 private void removeTabFromContentView(Tab t) {
1806 // Remove the container that contains the main WebView.
1807 t.removeTabFromContentView(mContentView);
1809 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1810 if (errorConsole != null) {
1811 mErrorConsoleContainer.removeView(errorConsole);
1814 WebView view = t.getWebView();
1816 view.setEmbeddedTitleBar(null);
1820 // Remove the sub window if it exists. Also called by TabControl when the
1821 // user clicks the 'X' to dismiss a sub window.
1822 /* package */ void dismissSubWindow(Tab t) {
1823 t.removeSubWindow(mContentView);
1824 // dismiss the subwindow. This will destroy the WebView.
1825 t.dismissSubWindow();
1826 getTopWindow().requestFocus();
1829 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1830 // that accepts url as string.
1831 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1832 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1835 // This method does a ton of stuff. It will attempt to create a new tab
1836 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1837 // url isn't null, it will load the given url.
1838 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1840 final Tab currentTab = mTabControl.getCurrentTab();
1841 if (mTabControl.canCreateNewTab()) {
1842 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1844 WebView webview = tab.getWebView();
1845 // If the last tab was removed from the active tabs page, currentTab
1847 if (currentTab != null) {
1848 removeTabFromContentView(currentTab);
1850 // We must set the new tab as the current tab to reflect the old
1851 // animation behavior.
1852 mTabControl.setCurrentTab(tab);
1853 attachTabToContentView(tab);
1854 if (!urlData.isEmpty()) {
1855 urlData.loadIn(tab);
1859 // Get rid of the subwindow if it exists
1860 dismissSubWindow(currentTab);
1861 if (!urlData.isEmpty()) {
1862 // Load the given url.
1863 urlData.loadIn(currentTab);
1869 private Tab openTab(String url) {
1870 if (mSettings.openInBackground()) {
1871 Tab t = mTabControl.createNewTab();
1873 WebView view = t.getWebView();
1878 return openTabAndShow(url, false, null);
1882 private class Copy implements OnMenuItemClickListener {
1883 private CharSequence mText;
1885 public boolean onMenuItemClick(MenuItem item) {
1890 public Copy(CharSequence toCopy) {
1895 private class Download implements OnMenuItemClickListener {
1896 private String mText;
1898 public boolean onMenuItemClick(MenuItem item) {
1899 onDownloadStartNoStream(mText, null, null, null, -1);
1903 public Download(String toDownload) {
1908 private class SetAsWallpaper extends Thread implements
1909 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1911 private ProgressDialog mWallpaperProgress;
1912 private boolean mCanceled = false;
1914 public SetAsWallpaper(String url) {
1916 mUrl = new URL(url);
1917 } catch (MalformedURLException e) {
1922 public void onCancel(DialogInterface dialog) {
1926 public boolean onMenuItemClick(MenuItem item) {
1928 // The user may have tried to set a image with a large file size as their
1929 // background so it may take a few moments to perform the operation. Display
1930 // a progress spinner while it is working.
1931 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1932 mWallpaperProgress.setIndeterminate(true);
1933 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1934 mWallpaperProgress.setCancelable(true);
1935 mWallpaperProgress.setOnCancelListener(this);
1936 mWallpaperProgress.show();
1943 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1945 // TODO: This will cause the resource to be downloaded again, when we
1946 // should in most cases be able to grab it from the cache. To fix this
1947 // we should query WebCore to see if we can access a cached version and
1948 // instead open an input stream on that. This pattern could also be used
1949 // in the download manager where the same problem exists.
1950 InputStream inputstream = mUrl.openStream();
1951 if (inputstream != null) {
1952 setWallpaper(inputstream);
1954 } catch (IOException e) {
1955 Log.e(LOGTAG, "Unable to set new wallpaper");
1956 // Act as though the user canceled the operation so we try to
1957 // restore the old wallpaper.
1962 // Restore the old wallpaper if the user cancelled whilst we were setting
1963 // the new wallpaper.
1964 int width = oldWallpaper.getIntrinsicWidth();
1965 int height = oldWallpaper.getIntrinsicHeight();
1966 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1967 Canvas canvas = new Canvas(bm);
1968 oldWallpaper.setBounds(0, 0, width, height);
1969 oldWallpaper.draw(canvas);
1972 } catch (IOException e) {
1973 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1978 if (mWallpaperProgress.isShowing()) {
1979 mWallpaperProgress.dismiss();
1984 private void copy(CharSequence text) {
1986 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1988 clip.setClipboardText(text);
1990 } catch (android.os.RemoteException e) {
1991 Log.e(LOGTAG, "Copy failed", e);
1996 * Resets the browser title-view to whatever it must be
1997 * (for example, if we had a loading error)
1998 * When we have a new page, we call resetTitle, when we
1999 * have to reset the titlebar to whatever it used to be
2000 * (for example, if the user chose to stop loading), we
2001 * call resetTitleAndRevertLockIcon.
2003 /* package */ void resetTitleAndRevertLockIcon() {
2004 mTabControl.getCurrentTab().revertLockIcon();
2005 updateLockIconToLatest();
2006 resetTitleIconAndProgress();
2010 * Reset the title, favicon, and progress.
2012 private void resetTitleIconAndProgress() {
2013 WebView current = mTabControl.getCurrentWebView();
2014 if (current == null) {
2017 resetTitleAndIcon(current);
2018 int progress = current.getProgress();
2019 current.getWebChromeClient().onProgressChanged(current, progress);
2022 // Reset the title and the icon based on the given item.
2023 private void resetTitleAndIcon(WebView view) {
2024 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2026 setUrlTitle(item.getUrl(), item.getTitle());
2027 setFavicon(item.getFavicon());
2029 setUrlTitle(null, null);
2035 * Sets a title composed of the URL and the title string.
2036 * @param url The URL of the site being loaded.
2037 * @param title The title of the site being loaded.
2039 void setUrlTitle(String url, String title) {
2043 // If we are in voice search mode, the title has already been set.
2044 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2045 mTitleBar.setDisplayTitle(url);
2046 mFakeTitleBar.setDisplayTitle(url);
2050 * @param url The URL to build a title version of the URL from.
2051 * @return The title version of the URL or null if fails.
2052 * The title version of the URL can be either the URL hostname,
2053 * or the hostname with an "https://" prefix (for secure URLs),
2054 * or an empty string if, for example, the URL in question is a
2055 * file:// URL with no hostname.
2057 /* package */ static String buildTitleUrl(String url) {
2058 String titleUrl = null;
2062 // parse the url string
2063 URL urlObj = new URL(url);
2064 if (urlObj != null) {
2067 String protocol = urlObj.getProtocol();
2068 String host = urlObj.getHost();
2070 if (host != null && 0 < host.length()) {
2072 if (protocol != null) {
2073 // if a secure site, add an "https://" prefix!
2074 if (protocol.equalsIgnoreCase("https")) {
2075 titleUrl = protocol + "://" + host;
2080 } catch (MalformedURLException e) {}
2086 // Set the favicon in the title bar.
2087 void setFavicon(Bitmap icon) {
2088 mTitleBar.setFavicon(icon);
2089 mFakeTitleBar.setFavicon(icon);
2093 * Close the tab, remove its associated title bar, and adjust mTabControl's
2094 * current tab to a valid value.
2096 /* package */ void closeTab(Tab t) {
2097 int currentIndex = mTabControl.getCurrentIndex();
2098 int removeIndex = mTabControl.getTabIndex(t);
2099 mTabControl.removeTab(t);
2100 if (currentIndex >= removeIndex && currentIndex != 0) {
2103 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2104 resetTitleIconAndProgress();
2107 private void goBackOnePageOrQuit() {
2108 Tab current = mTabControl.getCurrentTab();
2109 if (current == null) {
2111 * Instead of finishing the activity, simply push this to the back
2112 * of the stack and let ActivityManager to choose the foreground
2113 * activity. As BrowserActivity is singleTask, it will be always the
2114 * root of the task. So we can use either true or false for
2117 moveTaskToBack(true);
2120 WebView w = current.getWebView();
2121 if (w.canGoBack()) {
2124 // Check to see if we are closing a window that was created by
2125 // another window. If so, we switch back to that window.
2126 Tab parent = current.getParentTab();
2127 if (parent != null) {
2128 switchToTab(mTabControl.getTabIndex(parent));
2129 // Now we close the other tab
2132 if (current.closeOnExit()) {
2133 // force the tab's inLoad() to be false as we are going to
2134 // either finish the activity or remove the tab. This will
2135 // ensure pauseWebViewTimers() taking action.
2136 mTabControl.getCurrentTab().clearInLoad();
2137 if (mTabControl.getTabCount() == 1) {
2141 // call pauseWebViewTimers() now, we won't be able to call
2142 // it in onPause() as the WebView won't be valid.
2143 // Temporarily change mActivityInPause to be true as
2144 // pauseWebViewTimers() will do nothing if mActivityInPause
2146 boolean savedState = mActivityInPause;
2148 Log.e(LOGTAG, "BrowserActivity is already paused "
2149 + "while handing goBackOnePageOrQuit.");
2151 mActivityInPause = true;
2152 pauseWebViewTimers();
2153 mActivityInPause = savedState;
2154 removeTabFromContentView(current);
2155 mTabControl.removeTab(current);
2158 * Instead of finishing the activity, simply push this to the back
2159 * of the stack and let ActivityManager to choose the foreground
2160 * activity. As BrowserActivity is singleTask, it will be always the
2161 * root of the task. So we can use either true or false for
2164 moveTaskToBack(true);
2169 boolean isMenuDown() {
2174 public boolean onKeyDown(int keyCode, KeyEvent event) {
2175 // Even if MENU is already held down, we need to call to super to open
2176 // the IME on long press.
2177 if (KeyEvent.KEYCODE_MENU == keyCode) {
2179 return super.onKeyDown(keyCode, event);
2181 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2182 // still down, we don't want to trigger the search. Pretend to consume
2183 // the key and do nothing.
2184 if (mMenuIsDown) return true;
2187 case KeyEvent.KEYCODE_SPACE:
2188 // WebView/WebTextView handle the keys in the KeyDown. As
2189 // the Activity's shortcut keys are only handled when WebView
2190 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2191 if (event.isShiftPressed()) {
2192 getTopWindow().pageUp(false);
2194 getTopWindow().pageDown(false);
2197 case KeyEvent.KEYCODE_BACK:
2198 if (event.getRepeatCount() == 0) {
2199 event.startTracking();
2201 } else if (mCustomView == null && mActiveTabsPage == null
2202 && event.isLongPress()) {
2203 bookmarksOrHistoryPicker(true);
2208 return super.onKeyDown(keyCode, event);
2212 public boolean onKeyUp(int keyCode, KeyEvent event) {
2214 case KeyEvent.KEYCODE_MENU:
2215 mMenuIsDown = false;
2217 case KeyEvent.KEYCODE_BACK:
2218 if (event.isTracking() && !event.isCanceled()) {
2219 if (mCustomView != null) {
2220 // if a custom view is showing, hide it
2221 mTabControl.getCurrentWebView().getWebChromeClient()
2222 .onHideCustomView();
2223 } else if (mActiveTabsPage != null) {
2224 // if tab page is showing, hide it
2225 removeActiveTabPage(true);
2227 WebView subwindow = mTabControl.getCurrentSubWindow();
2228 if (subwindow != null) {
2229 if (subwindow.canGoBack()) {
2232 dismissSubWindow(mTabControl.getCurrentTab());
2235 goBackOnePageOrQuit();
2242 return super.onKeyUp(keyCode, event);
2245 /* package */ void stopLoading() {
2246 mDidStopLoad = true;
2247 resetTitleAndRevertLockIcon();
2248 WebView w = getTopWindow();
2250 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2251 // same logic here. But for subwindow case, should we call into the main
2252 // WebView's onPageFinished as we never call its onPageStarted and if
2253 // the page finishes itself, we don't call onPageFinished.
2254 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2259 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2263 boolean didUserStopLoading() {
2264 return mDidStopLoad;
2267 private void cancelStopToast() {
2268 if (mStopToast != null) {
2269 mStopToast.cancel();
2274 // called by a UI or non-UI thread to post the message
2275 public void postMessage(int what, int arg1, int arg2, Object obj,
2277 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2281 // called by a UI or non-UI thread to remove the message
2282 void removeMessages(int what, Object object) {
2283 mHandler.removeMessages(what, object);
2286 // public message ids
2287 public final static int LOAD_URL = 1001;
2288 public final static int STOP_LOAD = 1002;
2291 private static final int FOCUS_NODE_HREF = 102;
2292 private static final int CANCEL_CREDS_REQUEST = 103;
2293 private static final int RELEASE_WAKELOCK = 107;
2295 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2297 // Private handler for handling javascript and saving passwords
2298 private Handler mHandler = new Handler() {
2300 public void handleMessage(Message msg) {
2302 case FOCUS_NODE_HREF:
2304 String url = (String) msg.getData().get("url");
2305 String title = (String) msg.getData().get("title");
2306 if (url == null || url.length() == 0) {
2309 HashMap focusNodeMap = (HashMap) msg.obj;
2310 WebView view = (WebView) focusNodeMap.get("webview");
2311 // Only apply the action if the top window did not change.
2312 if (getTopWindow() != view) {
2316 case R.id.open_context_menu_id:
2317 case R.id.view_image_context_menu_id:
2318 loadURL(getTopWindow(), url);
2320 case R.id.open_newtab_context_menu_id:
2321 final Tab parent = mTabControl.getCurrentTab();
2322 final Tab newTab = openTab(url);
2323 if (newTab != parent) {
2324 parent.addChildTab(newTab);
2327 case R.id.bookmark_context_menu_id:
2328 Intent intent = new Intent(BrowserActivity.this,
2329 AddBookmarkPage.class);
2330 intent.putExtra("url", url);
2331 intent.putExtra("title", title);
2332 startActivity(intent);
2334 case R.id.share_link_context_menu_id:
2335 // See if this site has been visited before
2336 StringBuilder sb = new StringBuilder(
2337 Browser.BookmarkColumns.URL + " = ");
2338 DatabaseUtils.appendEscapedSQLString(sb, url);
2339 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2340 Browser.HISTORY_PROJECTION,
2344 if (c.moveToFirst()) {
2345 // The site has been visited before, so grab the
2346 // info from the database.
2347 Bitmap favicon = null;
2348 Bitmap thumbnail = null;
2349 String linkTitle = c.getString(Browser.
2350 HISTORY_PROJECTION_TITLE_INDEX);
2351 byte[] data = c.getBlob(Browser.
2352 HISTORY_PROJECTION_FAVICON_INDEX);
2354 favicon = BitmapFactory.decodeByteArray(
2355 data, 0, data.length);
2357 data = c.getBlob(Browser.
2358 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2360 thumbnail = BitmapFactory.decodeByteArray(
2361 data, 0, data.length);
2363 sharePage(BrowserActivity.this,
2364 linkTitle, url, favicon, thumbnail);
2366 Browser.sendString(BrowserActivity.this, url,
2368 R.string.choosertitle_sharevia));
2371 case R.id.copy_link_context_menu_id:
2374 case R.id.save_link_context_menu_id:
2375 case R.id.download_context_menu_id:
2376 onDownloadStartNoStream(url, null, null, null, -1);
2383 loadURL(getTopWindow(), (String) msg.obj);
2390 case CANCEL_CREDS_REQUEST:
2391 resumeAfterCredentials();
2394 case RELEASE_WAKELOCK:
2395 if (mWakeLock.isHeld()) {
2396 mWakeLock.release();
2397 // if we reach here, Browser should be still in the
2398 // background loading after WAKELOCK_TIMEOUT (5-min).
2399 // To avoid burning the battery, stop loading.
2400 mTabControl.stopAllLoading();
2404 case UPDATE_BOOKMARK_THUMBNAIL:
2405 WebView view = (WebView) msg.obj;
2407 updateScreenshot(view);
2415 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2416 * an {@link Intent} to launch the Activity chooser.
2417 * @param c Context used to launch a new Activity.
2418 * @param title Title of the page. Stored in the Intent with
2419 * {@link Browser#EXTRA_SHARE_TITLE}
2420 * @param url URL of the page. Stored in the Intent with
2421 * {@link Intent#EXTRA_TEXT}
2422 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2423 * with {@link Browser#EXTRA_SHARE_FAVICON}
2424 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2425 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2427 public static final void sharePage(Context c, String title, String url,
2428 Bitmap favicon, Bitmap screenshot) {
2429 Intent send = new Intent(Intent.ACTION_SEND);
2430 send.setType("text/plain");
2431 send.putExtra(Intent.EXTRA_TEXT, url);
2432 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2433 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2434 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2436 c.startActivity(Intent.createChooser(send, c.getString(
2437 R.string.choosertitle_sharevia)));
2438 } catch(android.content.ActivityNotFoundException ex) {
2439 // if no app handles it, do nothing
2443 private void updateScreenshot(WebView view) {
2444 // If this is a bookmarked site, add a screenshot to the database.
2445 // FIXME: When should we update? Every time?
2446 // FIXME: Would like to make sure there is actually something to
2447 // draw, but the API for that (WebViewCore.pictureReady()) is not
2448 // currently accessible here.
2450 ContentResolver cr = getContentResolver();
2451 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2452 cr, view.getOriginalUrl(), view.getUrl(), true);
2454 boolean succeed = c.moveToFirst();
2455 ContentValues values = null;
2457 if (values == null) {
2458 final ByteArrayOutputStream os
2459 = new ByteArrayOutputStream();
2460 Bitmap bm = createScreenshot(view);
2465 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2466 values = new ContentValues();
2467 values.put(Browser.BookmarkColumns.THUMBNAIL,
2470 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2471 c.getInt(0)), values, null, null);
2472 succeed = c.moveToNext();
2479 * Values for the size of the thumbnail created when taking a screenshot.
2480 * Lazily initialized. Instead of using these directly, use
2481 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2483 private static int THUMBNAIL_WIDTH = 0;
2484 private static int THUMBNAIL_HEIGHT = 0;
2487 * Return the desired width for thumbnail screenshots, which are stored in
2488 * the database, and used on the bookmarks screen.
2489 * @param context Context for finding out the density of the screen.
2490 * @return int desired width for thumbnail screenshot.
2492 /* package */ static int getDesiredThumbnailWidth(Context context) {
2493 if (THUMBNAIL_WIDTH == 0) {
2494 float density = context.getResources().getDisplayMetrics().density;
2495 THUMBNAIL_WIDTH = (int) (90 * density);
2496 THUMBNAIL_HEIGHT = (int) (80 * density);
2498 return THUMBNAIL_WIDTH;
2502 * Return the desired height for thumbnail screenshots, which are stored in
2503 * the database, and used on the bookmarks screen.
2504 * @param context Context for finding out the density of the screen.
2505 * @return int desired height for thumbnail screenshot.
2507 /* package */ static int getDesiredThumbnailHeight(Context context) {
2508 // To ensure that they are both initialized.
2509 getDesiredThumbnailWidth(context);
2510 return THUMBNAIL_HEIGHT;
2513 private Bitmap createScreenshot(WebView view) {
2514 Picture thumbnail = view.capturePicture();
2515 if (thumbnail == null) {
2518 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2519 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2520 Canvas canvas = new Canvas(bm);
2521 // May need to tweak these values to determine what is the
2522 // best scale factor
2523 int thumbnailWidth = thumbnail.getWidth();
2524 int thumbnailHeight = thumbnail.getHeight();
2525 float scaleFactorX = 1.0f;
2526 float scaleFactorY = 1.0f;
2527 if (thumbnailWidth > 0) {
2528 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2529 (float)thumbnailWidth;
2534 if (view.getWidth() > view.getHeight() &&
2535 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2536 // If the device is in landscape and the page is shorter
2537 // than the height of the view, stretch the thumbnail to fill the
2539 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2540 (float)thumbnailHeight;
2542 // In the portrait case, this looks nice.
2543 scaleFactorY = scaleFactorX;
2546 canvas.scale(scaleFactorX, scaleFactorY);
2548 thumbnail.draw(canvas);
2552 // -------------------------------------------------------------------------
2553 // Helper function for WebViewClient.
2554 //-------------------------------------------------------------------------
2556 // Use in overrideUrlLoading
2557 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2558 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2559 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2560 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2562 void onPageStarted(WebView view, String url, Bitmap favicon) {
2563 // when BrowserActivity just starts, onPageStarted may be called before
2564 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2565 // to start the timer. As we won't switch tabs while an activity is in
2566 // pause state, we can ensure calling resume and pause in pair.
2567 if (mActivityInPause) resumeWebViewTimers();
2570 setUrlTitle(url, null);
2571 setFavicon(favicon);
2572 // Keep this initial progress in sync with initialProgressValue (* 100)
2573 // in ProgressTracker.cpp
2574 // Show some progress so that the user knows the page is beginning to
2576 onProgressChanged(view, 10);
2577 mDidStopLoad = false;
2578 if (!mIsNetworkUp) createAndShowNetworkDialog();
2580 if (mSettings.isTracing()) {
2583 WebAddress uri = new WebAddress(url);
2585 } catch (android.net.ParseException ex) {
2588 host = host.replace('.', '_');
2591 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2594 // Performance probe
2596 mStart = SystemClock.uptimeMillis();
2597 mProcessStart = Process.getElapsedCpuTime();
2598 long[] sysCpu = new long[7];
2599 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2601 mUserStart = sysCpu[0] + sysCpu[1];
2602 mSystemStart = sysCpu[2];
2603 mIdleStart = sysCpu[3];
2604 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2606 mUiStart = SystemClock.currentThreadTimeMillis();
2610 void onPageFinished(WebView view, String url) {
2611 // Reset the title and icon in case we stopped a provisional load.
2612 resetTitleAndIcon(view);
2613 // Update the lock icon image only once we are done loading
2614 updateLockIconToLatest();
2615 // pause the WebView timer and release the wake lock if it is finished
2616 // while BrowserActivity is in pause state.
2617 if (mActivityInPause && pauseWebViewTimers()) {
2618 if (mWakeLock.isHeld()) {
2619 mHandler.removeMessages(RELEASE_WAKELOCK);
2620 mWakeLock.release();
2624 // Performance probe
2626 long[] sysCpu = new long[7];
2627 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2629 String uiInfo = "UI thread used "
2630 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2633 Log.d(LOGTAG, uiInfo);
2635 //The string that gets written to the log
2636 String performanceString = "It took total "
2637 + (SystemClock.uptimeMillis() - mStart)
2638 + " ms clock time to load the page."
2639 + "\nbrowser process used "
2640 + (Process.getElapsedCpuTime() - mProcessStart)
2641 + " ms, user processes used "
2642 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2643 + " ms, kernel used "
2644 + (sysCpu[2] - mSystemStart) * 10
2645 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2646 + " ms and irq took "
2647 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2648 * 10 + " ms, " + uiInfo;
2650 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2653 // strip the url to maintain consistency
2654 String newUrl = new String(url);
2655 if (newUrl.startsWith("http://www.")) {
2656 newUrl = newUrl.substring(11);
2657 } else if (newUrl.startsWith("http://")) {
2658 newUrl = newUrl.substring(7);
2659 } else if (newUrl.startsWith("https://www.")) {
2660 newUrl = newUrl.substring(12);
2661 } else if (newUrl.startsWith("https://")) {
2662 newUrl = newUrl.substring(8);
2665 Log.d(LOGTAG, newUrl + " loaded");
2673 Debug.stopMethodTracing();
2677 boolean shouldOverrideUrlLoading(WebView view, String url) {
2678 if (url.startsWith(SCHEME_WTAI)) {
2679 // wtai://wp/mc;number
2680 // number=string(phone-number)
2681 if (url.startsWith(SCHEME_WTAI_MC)) {
2682 Intent intent = new Intent(Intent.ACTION_VIEW,
2683 Uri.parse(WebView.SCHEME_TEL +
2684 url.substring(SCHEME_WTAI_MC.length())));
2685 startActivity(intent);
2688 // wtai://wp/sd;dtmf
2689 // dtmf=string(dialstring)
2690 if (url.startsWith(SCHEME_WTAI_SD)) {
2691 // TODO: only send when there is active voice connection
2694 // wtai://wp/ap;number;name
2695 // number=string(phone-number)
2697 if (url.startsWith(SCHEME_WTAI_AP)) {
2703 // The "about:" schemes are internal to the browser; don't want these to
2704 // be dispatched to other apps.
2705 if (url.startsWith("about:")) {
2710 // perform generic parsing of the URI to turn it into an Intent.
2712 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2713 } catch (URISyntaxException ex) {
2714 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2718 // check whether the intent can be resolved. If not, we will see
2719 // whether we can download it from the Market.
2720 if (getPackageManager().resolveActivity(intent, 0) == null) {
2721 String packagename = intent.getPackage();
2722 if (packagename != null) {
2723 intent = new Intent(Intent.ACTION_VIEW, Uri
2724 .parse("market://search?q=pname:" + packagename));
2725 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2726 startActivity(intent);
2733 // sanitize the Intent, ensuring web pages can not bypass browser
2734 // security (only access to BROWSABLE activities).
2735 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2736 intent.setComponent(null);
2738 if (startActivityIfNeeded(intent, -1)) {
2741 } catch (ActivityNotFoundException ex) {
2742 // ignore the error. If no application can handle the URL,
2743 // eg about:blank, assume the browser can handle it.
2754 // -------------------------------------------------------------------------
2755 // Helper function for WebChromeClient
2756 // -------------------------------------------------------------------------
2758 void onProgressChanged(WebView view, int newProgress) {
2759 mTitleBar.setProgress(newProgress);
2760 mFakeTitleBar.setProgress(newProgress);
2762 if (newProgress == 100) {
2763 // onProgressChanged() may continue to be called after the main
2764 // frame has finished loading, as any remaining sub frames continue
2765 // to load. We'll only get called once though with newProgress as
2766 // 100 when everything is loaded. (onPageFinished is called once
2767 // when the main frame completes loading regardless of the state of
2768 // any sub frames so calls to onProgressChanges may continue after
2769 // onPageFinished has executed)
2772 updateInLoadMenuItems();
2773 // If the options menu is open, leave the title bar
2774 if (!mOptionsMenuOpen || !mIconView) {
2778 } else if (!mInLoad) {
2779 // onPageFinished may have already been called but a subframe is
2780 // still loading and updating the progress. Reset mInLoad and update
2783 updateInLoadMenuItems();
2784 if (!mOptionsMenuOpen || mIconView) {
2785 // This page has begun to load, so show the title bar
2791 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2792 // if a view already exists then immediately terminate the new one
2793 if (mCustomView != null) {
2794 callback.onCustomViewHidden();
2798 // Add the custom view to its container.
2799 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2801 mCustomViewCallback = callback;
2802 // Save the menu state and set it to empty while the custom
2804 mOldMenuState = mMenuState;
2805 mMenuState = EMPTY_MENU;
2806 // Hide the content view.
2807 mContentView.setVisibility(View.GONE);
2808 // Finally show the custom view container.
2809 setStatusBarVisibility(false);
2810 mCustomViewContainer.setVisibility(View.VISIBLE);
2811 mCustomViewContainer.bringToFront();
2814 void onHideCustomView() {
2815 if (mCustomView == null)
2818 // Hide the custom view.
2819 mCustomView.setVisibility(View.GONE);
2820 // Remove the custom view from its container.
2821 mCustomViewContainer.removeView(mCustomView);
2823 // Reset the old menu state.
2824 mMenuState = mOldMenuState;
2825 mOldMenuState = EMPTY_MENU;
2826 mCustomViewContainer.setVisibility(View.GONE);
2827 mCustomViewCallback.onCustomViewHidden();
2828 // Show the content view.
2829 setStatusBarVisibility(true);
2830 mContentView.setVisibility(View.VISIBLE);
2833 Bitmap getDefaultVideoPoster() {
2834 if (mDefaultVideoPoster == null) {
2835 mDefaultVideoPoster = BitmapFactory.decodeResource(
2836 getResources(), R.drawable.default_video_poster);
2838 return mDefaultVideoPoster;
2841 View getVideoLoadingProgressView() {
2842 if (mVideoProgressView == null) {
2843 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2844 mVideoProgressView = inflater.inflate(
2845 R.layout.video_loading_progress, null);
2847 return mVideoProgressView;
2851 * The Object used to inform the WebView of the file to upload.
2853 private ValueCallback<Uri> mUploadMessage;
2855 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2856 if (mUploadMessage != null) return;
2857 mUploadMessage = uploadMsg;
2858 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2859 i.addCategory(Intent.CATEGORY_OPENABLE);
2861 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2862 getString(R.string.choose_upload)), FILE_SELECTED);
2865 // -------------------------------------------------------------------------
2866 // Implement functions for DownloadListener
2867 // -------------------------------------------------------------------------
2870 * Notify the host application a download should be done, or that
2871 * the data should be streamed if a streaming viewer is available.
2872 * @param url The full url to the content that should be downloaded
2873 * @param contentDisposition Content-disposition http header, if
2875 * @param mimetype The mimetype of the content reported by the server
2876 * @param contentLength The file size reported by the server
2878 public void onDownloadStart(String url, String userAgent,
2879 String contentDisposition, String mimetype, long contentLength) {
2880 // if we're dealing wih A/V content that's not explicitly marked
2881 // for download, check if it's streamable.
2882 if (contentDisposition == null
2883 || !contentDisposition.regionMatches(
2884 true, 0, "attachment", 0, 10)) {
2885 // query the package manager to see if there's a registered handler
2887 Intent intent = new Intent(Intent.ACTION_VIEW);
2888 intent.setDataAndType(Uri.parse(url), mimetype);
2889 ResolveInfo info = getPackageManager().resolveActivity(intent,
2890 PackageManager.MATCH_DEFAULT_ONLY);
2892 ComponentName myName = getComponentName();
2893 // If we resolved to ourselves, we don't want to attempt to
2894 // load the url only to try and download it again.
2895 if (!myName.getPackageName().equals(
2896 info.activityInfo.packageName)
2897 || !myName.getClassName().equals(
2898 info.activityInfo.name)) {
2899 // someone (other than us) knows how to handle this mime
2900 // type with this scheme, don't download.
2902 startActivity(intent);
2904 } catch (ActivityNotFoundException ex) {
2906 Log.d(LOGTAG, "activity not found for " + mimetype
2907 + " over " + Uri.parse(url).getScheme(),
2910 // Best behavior is to fall back to a download in this
2916 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2920 * Notify the host application a download should be done, even if there
2921 * is a streaming viewer available for thise type.
2922 * @param url The full url to the content that should be downloaded
2923 * @param contentDisposition Content-disposition http header, if
2925 * @param mimetype The mimetype of the content reported by the server
2926 * @param contentLength The file size reported by the server
2928 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2929 String contentDisposition, String mimetype, long contentLength) {
2931 String filename = URLUtil.guessFileName(url,
2932 contentDisposition, mimetype);
2934 // Check to see if we have an SDCard
2935 String status = Environment.getExternalStorageState();
2936 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2940 // Check to see if the SDCard is busy, same as the music app
2941 if (status.equals(Environment.MEDIA_SHARED)) {
2942 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2943 title = R.string.download_sdcard_busy_dlg_title;
2945 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2946 title = R.string.download_no_sdcard_dlg_title;
2949 new AlertDialog.Builder(this)
2951 .setIcon(android.R.drawable.ic_dialog_alert)
2953 .setPositiveButton(R.string.ok, null)
2958 // java.net.URI is a lot stricter than KURL so we have to undo
2959 // KURL's percent-encoding and redo the encoding using java.net.URI.
2962 // Undo the percent-encoding that KURL may have done.
2963 String newUrl = new String(URLUtil.decode(url.getBytes()));
2964 // Parse the url into pieces
2965 WebAddress w = new WebAddress(newUrl);
2967 String query = null;
2968 String path = w.mPath;
2969 // Break the path into path, query, and fragment
2970 if (path.length() > 0) {
2971 // Strip the fragment
2972 int idx = path.lastIndexOf('#');
2974 frag = path.substring(idx + 1);
2975 path = path.substring(0, idx);
2977 idx = path.lastIndexOf('?');
2979 query = path.substring(idx + 1);
2980 path = path.substring(0, idx);
2983 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2985 } catch (Exception e) {
2986 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2990 // XXX: Have to use the old url since the cookies were stored using the
2991 // old percent-encoded url.
2992 String cookies = CookieManager.getInstance().getCookie(url);
2994 ContentValues values = new ContentValues();
2995 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2996 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2997 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2998 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
3000 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
3001 BrowserDownloadPage.class.getCanonicalName());
3002 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3003 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3004 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3005 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3006 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
3007 if (contentLength > 0) {
3008 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
3010 if (mimetype == null) {
3011 // We must have long pressed on a link or image to download it. We
3012 // are not sure of the mimetype in this case, so do a head request
3013 new FetchUrlMimeType(this).execute(values);
3015 final Uri contentUri =
3016 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
3021 // -------------------------------------------------------------------------
3024 * Resets the lock icon. This method is called when we start a new load and
3025 * know the url to be loaded.
3027 private void resetLockIcon(String url) {
3028 // Save the lock-icon state (we revert to it if the load gets cancelled)
3029 mTabControl.getCurrentTab().resetLockIcon(url);
3030 updateLockIconImage(LOCK_ICON_UNSECURE);
3034 * Update the lock icon to correspond to our latest state.
3036 private void updateLockIconToLatest() {
3037 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
3041 * Updates the lock-icon image in the title-bar.
3043 private void updateLockIconImage(int lockIconType) {
3045 if (lockIconType == LOCK_ICON_SECURE) {
3047 } else if (lockIconType == LOCK_ICON_MIXED) {
3050 mTitleBar.setLock(d);
3051 mFakeTitleBar.setLock(d);
3055 * Displays a page-info dialog.
3056 * @param tab The tab to show info about
3057 * @param fromShowSSLCertificateOnError The flag that indicates whether
3058 * this dialog was opened from the SSL-certificate-on-error dialog or
3059 * not. This is important, since we need to know whether to return to
3060 * the parent dialog or simply dismiss.
3062 private void showPageInfo(final Tab tab,
3063 final boolean fromShowSSLCertificateOnError) {
3064 final LayoutInflater factory = LayoutInflater
3067 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3069 final WebView view = tab.getWebView();
3072 String title = null;
3076 title = tab.getTitle();
3077 } else if (view == mTabControl.getCurrentWebView()) {
3078 // Use the cached title and url if this is the current WebView
3082 url = view.getUrl();
3083 title = view.getTitle();
3089 if (title == null) {
3093 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3094 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3096 mPageInfoView = tab;
3097 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3099 AlertDialog.Builder alertDialogBuilder =
3100 new AlertDialog.Builder(this)
3101 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3102 .setView(pageInfoView)
3105 new DialogInterface.OnClickListener() {
3106 public void onClick(DialogInterface dialog,
3108 mPageInfoDialog = null;
3109 mPageInfoView = null;
3111 // if we came here from the SSL error dialog
3112 if (fromShowSSLCertificateOnError) {
3113 // go back to the SSL error dialog
3114 showSSLCertificateOnError(
3115 mSSLCertificateOnErrorView,
3116 mSSLCertificateOnErrorHandler,
3117 mSSLCertificateOnErrorError);
3121 .setOnCancelListener(
3122 new DialogInterface.OnCancelListener() {
3123 public void onCancel(DialogInterface dialog) {
3124 mPageInfoDialog = null;
3125 mPageInfoView = null;
3127 // if we came here from the SSL error dialog
3128 if (fromShowSSLCertificateOnError) {
3129 // go back to the SSL error dialog
3130 showSSLCertificateOnError(
3131 mSSLCertificateOnErrorView,
3132 mSSLCertificateOnErrorHandler,
3133 mSSLCertificateOnErrorError);
3138 // if we have a main top-level page SSL certificate set or a certificate
3140 if (fromShowSSLCertificateOnError ||
3141 (view != null && view.getCertificate() != null)) {
3142 // add a 'View Certificate' button
3143 alertDialogBuilder.setNeutralButton(
3144 R.string.view_certificate,
3145 new DialogInterface.OnClickListener() {
3146 public void onClick(DialogInterface dialog,
3148 mPageInfoDialog = null;
3149 mPageInfoView = null;
3151 // if we came here from the SSL error dialog
3152 if (fromShowSSLCertificateOnError) {
3153 // go back to the SSL error dialog
3154 showSSLCertificateOnError(
3155 mSSLCertificateOnErrorView,
3156 mSSLCertificateOnErrorHandler,
3157 mSSLCertificateOnErrorError);
3159 // otherwise, display the top-most certificate from
3161 if (view.getCertificate() != null) {
3162 showSSLCertificate(tab);
3169 mPageInfoDialog = alertDialogBuilder.show();
3173 * Displays the main top-level page SSL certificate dialog
3174 * (accessible from the Page-Info dialog).
3175 * @param tab The tab to show certificate for.
3177 private void showSSLCertificate(final Tab tab) {
3178 final View certificateView =
3179 inflateCertificateView(tab.getWebView().getCertificate());
3180 if (certificateView == null) {
3184 LayoutInflater factory = LayoutInflater.from(this);
3186 final LinearLayout placeholder =
3187 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3189 LinearLayout ll = (LinearLayout) factory.inflate(
3190 R.layout.ssl_success, placeholder);
3191 ((TextView)ll.findViewById(R.id.success))
3192 .setText(R.string.ssl_certificate_is_valid);
3194 mSSLCertificateView = tab;
3195 mSSLCertificateDialog =
3196 new AlertDialog.Builder(this)
3197 .setTitle(R.string.ssl_certificate).setIcon(
3198 R.drawable.ic_dialog_browser_certificate_secure)
3199 .setView(certificateView)
3200 .setPositiveButton(R.string.ok,
3201 new DialogInterface.OnClickListener() {
3202 public void onClick(DialogInterface dialog,
3204 mSSLCertificateDialog = null;
3205 mSSLCertificateView = null;
3207 showPageInfo(tab, false);
3210 .setOnCancelListener(
3211 new DialogInterface.OnCancelListener() {
3212 public void onCancel(DialogInterface dialog) {
3213 mSSLCertificateDialog = null;
3214 mSSLCertificateView = null;
3216 showPageInfo(tab, false);
3223 * Displays the SSL error certificate dialog.
3224 * @param view The target web-view.
3225 * @param handler The SSL error handler responsible for cancelling the
3226 * connection that resulted in an SSL error or proceeding per user request.
3227 * @param error The SSL error object.
3229 void showSSLCertificateOnError(
3230 final WebView view, final SslErrorHandler handler, final SslError error) {
3232 final View certificateView =
3233 inflateCertificateView(error.getCertificate());
3234 if (certificateView == null) {
3238 LayoutInflater factory = LayoutInflater.from(this);
3240 final LinearLayout placeholder =
3241 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3243 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3244 LinearLayout ll = (LinearLayout)factory
3245 .inflate(R.layout.ssl_warning, placeholder);
3246 ((TextView)ll.findViewById(R.id.warning))
3247 .setText(R.string.ssl_untrusted);
3250 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3251 LinearLayout ll = (LinearLayout)factory
3252 .inflate(R.layout.ssl_warning, placeholder);
3253 ((TextView)ll.findViewById(R.id.warning))
3254 .setText(R.string.ssl_mismatch);
3257 if (error.hasError(SslError.SSL_EXPIRED)) {
3258 LinearLayout ll = (LinearLayout)factory
3259 .inflate(R.layout.ssl_warning, placeholder);
3260 ((TextView)ll.findViewById(R.id.warning))
3261 .setText(R.string.ssl_expired);
3264 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3265 LinearLayout ll = (LinearLayout)factory
3266 .inflate(R.layout.ssl_warning, placeholder);
3267 ((TextView)ll.findViewById(R.id.warning))
3268 .setText(R.string.ssl_not_yet_valid);
3271 mSSLCertificateOnErrorHandler = handler;
3272 mSSLCertificateOnErrorView = view;
3273 mSSLCertificateOnErrorError = error;
3274 mSSLCertificateOnErrorDialog =
3275 new AlertDialog.Builder(this)
3276 .setTitle(R.string.ssl_certificate).setIcon(
3277 R.drawable.ic_dialog_browser_certificate_partially_secure)
3278 .setView(certificateView)
3279 .setPositiveButton(R.string.ok,
3280 new DialogInterface.OnClickListener() {
3281 public void onClick(DialogInterface dialog,
3283 mSSLCertificateOnErrorDialog = null;
3284 mSSLCertificateOnErrorView = null;
3285 mSSLCertificateOnErrorHandler = null;
3286 mSSLCertificateOnErrorError = null;
3288 view.getWebViewClient().onReceivedSslError(
3289 view, handler, error);
3292 .setNeutralButton(R.string.page_info_view,
3293 new DialogInterface.OnClickListener() {
3294 public void onClick(DialogInterface dialog,
3296 mSSLCertificateOnErrorDialog = null;
3298 // do not clear the dialog state: we will
3299 // need to show the dialog again once the
3300 // user is done exploring the page-info details
3302 showPageInfo(mTabControl.getTabFromView(view),
3306 .setOnCancelListener(
3307 new DialogInterface.OnCancelListener() {
3308 public void onCancel(DialogInterface dialog) {
3309 mSSLCertificateOnErrorDialog = null;
3310 mSSLCertificateOnErrorView = null;
3311 mSSLCertificateOnErrorHandler = null;
3312 mSSLCertificateOnErrorError = null;
3314 view.getWebViewClient().onReceivedSslError(
3315 view, handler, error);
3322 * Inflates the SSL certificate view (helper method).
3323 * @param certificate The SSL certificate.
3324 * @return The resultant certificate view with issued-to, issued-by,
3325 * issued-on, expires-on, and possibly other fields set.
3326 * If the input certificate is null, returns null.
3328 private View inflateCertificateView(SslCertificate certificate) {
3329 if (certificate == null) {
3333 LayoutInflater factory = LayoutInflater.from(this);
3335 View certificateView = factory.inflate(
3336 R.layout.ssl_certificate, null);
3339 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3340 if (issuedTo != null) {
3341 ((TextView) certificateView.findViewById(R.id.to_common))
3342 .setText(issuedTo.getCName());
3343 ((TextView) certificateView.findViewById(R.id.to_org))
3344 .setText(issuedTo.getOName());
3345 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3346 .setText(issuedTo.getUName());
3350 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3351 if (issuedBy != null) {
3352 ((TextView) certificateView.findViewById(R.id.by_common))
3353 .setText(issuedBy.getCName());
3354 ((TextView) certificateView.findViewById(R.id.by_org))
3355 .setText(issuedBy.getOName());
3356 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3357 .setText(issuedBy.getUName());
3361 String issuedOn = reformatCertificateDate(
3362 certificate.getValidNotBefore());
3363 ((TextView) certificateView.findViewById(R.id.issued_on))
3367 String expiresOn = reformatCertificateDate(
3368 certificate.getValidNotAfter());
3369 ((TextView) certificateView.findViewById(R.id.expires_on))
3370 .setText(expiresOn);
3372 return certificateView;
3376 * Re-formats the certificate date (Date.toString()) string to
3377 * a properly localized date string.
3378 * @return Properly localized version of the certificate date string and
3379 * the original certificate date string if fails to localize.
3380 * If the original string is null, returns an empty string "".
3382 private String reformatCertificateDate(String certificateDate) {
3383 String reformattedDate = null;
3385 if (certificateDate != null) {
3388 date = java.text.DateFormat.getInstance().parse(certificateDate);
3389 } catch (ParseException e) {
3395 DateFormat.getDateFormat(this).format(date);
3399 return reformattedDate != null ? reformattedDate :
3400 (certificateDate != null ? certificateDate : "");
3404 * Displays an http-authentication dialog.
3406 void showHttpAuthentication(final HttpAuthHandler handler,
3407 final String host, final String realm, final String title,
3408 final String name, final String password, int focusId) {
3409 LayoutInflater factory = LayoutInflater.from(this);
3410 final View v = factory
3411 .inflate(R.layout.http_authentication, null);
3413 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3415 if (password != null) {
3416 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3419 String titleText = title;
3420 if (titleText == null) {
3421 titleText = getText(R.string.sign_in_to).toString().replace(
3422 "%s1", host).replace("%s2", realm);
3425 mHttpAuthHandler = handler;
3426 AlertDialog dialog = new AlertDialog.Builder(this)
3427 .setTitle(titleText)
3428 .setIcon(android.R.drawable.ic_dialog_alert)
3430 .setPositiveButton(R.string.action,
3431 new DialogInterface.OnClickListener() {
3432 public void onClick(DialogInterface dialog,
3434 String nm = ((EditText) v
3435 .findViewById(R.id.username_edit))
3436 .getText().toString();
3437 String pw = ((EditText) v
3438 .findViewById(R.id.password_edit))
3439 .getText().toString();
3440 BrowserActivity.this.setHttpAuthUsernamePassword
3441 (host, realm, nm, pw);
3442 handler.proceed(nm, pw);
3443 mHttpAuthenticationDialog = null;
3444 mHttpAuthHandler = null;
3446 .setNegativeButton(R.string.cancel,
3447 new DialogInterface.OnClickListener() {
3448 public void onClick(DialogInterface dialog,
3451 BrowserActivity.this.resetTitleAndRevertLockIcon();
3452 mHttpAuthenticationDialog = null;
3453 mHttpAuthHandler = null;
3455 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3456 public void onCancel(DialogInterface dialog) {
3458 BrowserActivity.this.resetTitleAndRevertLockIcon();
3459 mHttpAuthenticationDialog = null;
3460 mHttpAuthHandler = null;
3463 // Make the IME appear when the dialog is displayed if applicable.
3464 dialog.getWindow().setSoftInputMode(
3465 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3468 dialog.findViewById(focusId).requestFocus();
3470 v.findViewById(R.id.username_edit).requestFocus();
3472 mHttpAuthenticationDialog = dialog;
3475 public int getProgress() {
3476 WebView w = mTabControl.getCurrentWebView();
3478 return w.getProgress();
3485 * Set HTTP authentication password.
3487 * @param host The host for the password
3488 * @param realm The realm for the password
3489 * @param username The username for the password. If it is null, it means
3490 * password can't be saved.
3491 * @param password The password
3493 public void setHttpAuthUsernamePassword(String host, String realm,
3496 WebView w = mTabControl.getCurrentWebView();
3498 w.setHttpAuthUsernamePassword(host, realm, username, password);
3503 * connectivity manager says net has come or gone... inform the user
3504 * @param up true if net has come up, false if net has gone down
3506 public void onNetworkToggle(boolean up) {
3507 if (up == mIsNetworkUp) {
3510 mIsNetworkUp = true;
3511 if (mAlertDialog != null) {
3512 mAlertDialog.cancel();
3513 mAlertDialog = null;
3516 mIsNetworkUp = false;
3518 createAndShowNetworkDialog();
3521 WebView w = mTabControl.getCurrentWebView();
3523 w.setNetworkAvailable(up);
3527 boolean isNetworkUp() {
3528 return mIsNetworkUp;
3531 // This method shows the network dialog alerting the user that the net is
3532 // down. It will only show the dialog if mAlertDialog is null.
3533 private void createAndShowNetworkDialog() {
3534 if (mAlertDialog == null) {
3535 mAlertDialog = new AlertDialog.Builder(this)
3536 .setTitle(R.string.loadSuspendedTitle)
3537 .setMessage(R.string.loadSuspended)
3538 .setPositiveButton(R.string.ok, null)
3544 protected void onActivityResult(int requestCode, int resultCode,
3546 if (getTopWindow() == null) return;
3548 switch (requestCode) {
3550 if (resultCode == RESULT_OK && intent != null) {
3551 String data = intent.getAction();
3552 Bundle extras = intent.getExtras();
3553 if (extras != null && extras.getBoolean("new_window", false)) {
3556 final Tab currentTab =
3557 mTabControl.getCurrentTab();
3558 dismissSubWindow(currentTab);
3559 if (data != null && data.length() != 0) {
3560 getTopWindow().loadUrl(data);
3564 // Deliberately fall through to PREFERENCES_PAGE, since the
3565 // same extra may be attached to the COMBO_PAGE
3566 case PREFERENCES_PAGE:
3567 if (resultCode == RESULT_OK && intent != null) {
3568 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3569 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3570 mTabControl.removeParentChildRelationShips();
3574 // Choose a file from the file picker.
3576 if (null == mUploadMessage) break;
3577 Uri result = intent == null || resultCode != RESULT_OK ? null
3579 mUploadMessage.onReceiveValue(result);
3580 mUploadMessage = null;
3585 getTopWindow().requestFocus();
3589 * This method is called as a result of the user selecting the options
3590 * menu to see the download window. It shows the download window on top of
3591 * the current window.
3593 private void viewDownloads(Uri downloadRecord) {
3594 Intent intent = new Intent(this,
3595 BrowserDownloadPage.class);
3596 intent.setData(downloadRecord);
3597 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3603 * @param startWithHistory If true, open starting on the history tab.
3604 * Otherwise, start with the bookmarks tab.
3606 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3607 WebView current = mTabControl.getCurrentWebView();
3608 if (current == null) {
3611 Intent intent = new Intent(this,
3612 CombinedBookmarkHistoryActivity.class);
3613 String title = current.getTitle();
3614 String url = current.getUrl();
3615 Bitmap thumbnail = createScreenshot(current);
3617 // Just in case the user opens bookmarks before a page finishes loading
3618 // so the current history item, and therefore the page, is null.
3620 url = mLastEnteredUrl;
3623 url = mSettings.getHomePage();
3626 // In case the web page has not yet received its associated title.
3627 if (title == null) {
3630 intent.putExtra("title", title);
3631 intent.putExtra("url", url);
3632 intent.putExtra("thumbnail", thumbnail);
3633 // Disable opening in a new window if we have maxed out the windows
3634 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3635 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3636 if (startWithHistory) {
3637 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3638 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3640 startActivityForResult(intent, COMBO_PAGE);
3643 // Called when loading from context menu or LOAD_URL message
3644 private void loadURL(WebView view, String url) {
3645 // In case the user enters nothing.
3646 if (url != null && url.length() != 0 && view != null) {
3647 url = smartUrlFilter(url);
3648 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3654 private String smartUrlFilter(Uri inUri) {
3655 if (inUri != null) {
3656 return smartUrlFilter(inUri.toString());
3661 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3662 "(?i)" + // switch on case insensitive matching
3663 "(" + // begin group for schema
3664 "(?:http|https|file):\\/\\/" +
3665 "|(?:inline|data|about|content|javascript):" +
3670 * Attempts to determine whether user input is a URL or search
3671 * terms. Anything with a space is passed to search.
3673 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3674 * "Http://" converts to "http://"
3676 * @return Original or modified URL
3679 String smartUrlFilter(String url) {
3681 String inUrl = url.trim();
3682 boolean hasSpace = inUrl.indexOf(' ') != -1;
3684 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3685 if (matcher.matches()) {
3686 // force scheme to lowercase
3687 String scheme = matcher.group(1);
3688 String lcScheme = scheme.toLowerCase();
3689 if (!lcScheme.equals(scheme)) {
3690 inUrl = lcScheme + matcher.group(2);
3693 inUrl = inUrl.replace(" ", "%20");
3698 // FIXME: Is this the correct place to add to searches?
3699 // what if someone else calls this function?
3700 int shortcut = parseUrlShortcut(inUrl);
3701 if (shortcut != SHORTCUT_INVALID) {
3702 Browser.addSearchUrl(mResolver, inUrl);
3703 String query = inUrl.substring(2);
3705 case SHORTCUT_GOOGLE_SEARCH:
3706 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3707 case SHORTCUT_WIKIPEDIA_SEARCH:
3708 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3709 case SHORTCUT_DICTIONARY_SEARCH:
3710 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3711 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3712 // FIXME: we need location in this case
3713 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3717 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3718 return URLUtil.guessUrl(inUrl);
3722 Browser.addSearchUrl(mResolver, inUrl);
3723 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3726 /* package */ void setShouldShowErrorConsole(boolean flag) {
3727 if (flag == mShouldShowErrorConsole) {
3732 mShouldShowErrorConsole = flag;
3734 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3735 .getErrorConsole(true);
3738 // Setting the show state of the console will cause it's the layout to be inflated.
3739 if (errorConsole.numberOfErrors() > 0) {
3740 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3742 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3745 // Now we can add it to the main view.
3746 mErrorConsoleContainer.addView(errorConsole,
3747 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3748 ViewGroup.LayoutParams.WRAP_CONTENT));
3750 mErrorConsoleContainer.removeView(errorConsole);
3755 boolean shouldShowErrorConsole() {
3756 return mShouldShowErrorConsole;
3759 private void setStatusBarVisibility(boolean visible) {
3760 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3761 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3765 private void sendNetworkType(String type, String subtype) {
3766 WebView w = mTabControl.getCurrentWebView();
3768 w.setNetworkType(type, subtype);
3772 final static int LOCK_ICON_UNSECURE = 0;
3773 final static int LOCK_ICON_SECURE = 1;
3774 final static int LOCK_ICON_MIXED = 2;
3776 private BrowserSettings mSettings;
3777 private TabControl mTabControl;
3778 private ContentResolver mResolver;
3779 private FrameLayout mContentView;
3780 private View mCustomView;
3781 private FrameLayout mCustomViewContainer;
3782 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3784 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3785 // view, we should rewrite this.
3786 private int mCurrentMenuState = 0;
3787 private int mMenuState = R.id.MAIN_MENU;
3788 private int mOldMenuState = EMPTY_MENU;
3789 private static final int EMPTY_MENU = -1;
3792 private FindDialog mFindDialog;
3793 // Used to prevent chording to result in firing two shortcuts immediately
3794 // one after another. Fixes bug 1211714.
3797 private boolean mInLoad;
3798 private boolean mIsNetworkUp;
3799 private boolean mDidStopLoad;
3801 private boolean mActivityInPause = true;
3803 private boolean mMenuIsDown;
3805 private static boolean mInTrace;
3807 // Performance probe
3808 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3809 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3810 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3811 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3812 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3813 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3814 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3815 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3816 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3819 private long mStart;
3820 private long mProcessStart;
3821 private long mUserStart;
3822 private long mSystemStart;
3823 private long mIdleStart;
3824 private long mIrqStart;
3826 private long mUiStart;
3828 private Drawable mMixLockIcon;
3829 private Drawable mSecLockIcon;
3831 /* hold a ref so we can auto-cancel if necessary */
3832 private AlertDialog mAlertDialog;
3834 // Wait for credentials before loading google.com
3835 private ProgressDialog mCredsDlg;
3837 // The up-to-date URL and title (these can be different from those stored
3838 // in WebView, since it takes some time for the information in WebView to
3840 private String mUrl;
3841 private String mTitle;
3843 // As PageInfo has different style for landscape / portrait, we have
3844 // to re-open it when configuration changed
3845 private AlertDialog mPageInfoDialog;
3846 private Tab mPageInfoView;
3847 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3848 // dialog, we should not just dismiss it, but should get back to the
3849 // SSL-certificate-on-error dialog. This flag is used to store this state
3850 private boolean mPageInfoFromShowSSLCertificateOnError;
3852 // as SSLCertificateOnError has different style for landscape / portrait,
3853 // we have to re-open it when configuration changed
3854 private AlertDialog mSSLCertificateOnErrorDialog;
3855 private WebView mSSLCertificateOnErrorView;
3856 private SslErrorHandler mSSLCertificateOnErrorHandler;
3857 private SslError mSSLCertificateOnErrorError;
3859 // as SSLCertificate has different style for landscape / portrait, we
3860 // have to re-open it when configuration changed
3861 private AlertDialog mSSLCertificateDialog;
3862 private Tab mSSLCertificateView;
3864 // as HttpAuthentication has different style for landscape / portrait, we
3865 // have to re-open it when configuration changed
3866 private AlertDialog mHttpAuthenticationDialog;
3867 private HttpAuthHandler mHttpAuthHandler;
3869 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3870 new FrameLayout.LayoutParams(
3871 ViewGroup.LayoutParams.MATCH_PARENT,
3872 ViewGroup.LayoutParams.MATCH_PARENT);
3873 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3874 new FrameLayout.LayoutParams(
3875 ViewGroup.LayoutParams.MATCH_PARENT,
3876 ViewGroup.LayoutParams.MATCH_PARENT,
3879 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3881 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3882 // Dictionary search
3883 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3884 // Google Mobile Local search
3885 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3887 final static String QUERY_PLACE_HOLDER = "%s";
3889 // "source" parameter for Google search through search key
3890 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3891 // "source" parameter for Google search through goto menu
3892 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3893 // "source" parameter for Google search through simplily type
3894 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3895 // "source" parameter for Google search suggested by the browser
3896 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3897 // "source" parameter for Google search from unknown source
3898 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3900 private final static String LOGTAG = "browser";
3902 private String mLastEnteredUrl;
3904 private PowerManager.WakeLock mWakeLock;
3905 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3907 private Toast mStopToast;
3909 private TitleBar mTitleBar;
3911 private LinearLayout mErrorConsoleContainer = null;
3912 private boolean mShouldShowErrorConsole = false;
3914 // As the ids are dynamically created, we can't guarantee that they will
3915 // be in sequence, so this static array maps ids to a window number.
3916 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3917 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3918 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3919 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3921 // monitor platform changes
3922 private IntentFilter mNetworkStateChangedFilter;
3923 private BroadcastReceiver mNetworkStateIntentReceiver;
3925 private BroadcastReceiver mPackageInstallationReceiver;
3927 // activity requestCode
3928 final static int COMBO_PAGE = 1;
3929 final static int DOWNLOAD_PAGE = 2;
3930 final static int PREFERENCES_PAGE = 3;
3931 final static int FILE_SELECTED = 4;
3933 // the default <video> poster
3934 private Bitmap mDefaultVideoPoster;
3935 // the video progress view
3936 private View mVideoProgressView;
3939 * A UrlData class to abstract how the content will be set to WebView.
3940 * This base class uses loadUrl to show the content.
3942 private static class UrlData {
3944 final Map<String, String> mHeaders;
3945 final Intent mVoiceIntent;
3947 UrlData(String url) {
3949 this.mHeaders = null;
3950 this.mVoiceIntent = null;
3953 UrlData(String url, Map<String, String> headers, Intent intent) {
3955 this.mHeaders = headers;
3956 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3957 .equals(intent.getAction())) {
3958 this.mVoiceIntent = intent;
3960 this.mVoiceIntent = null;
3965 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
3968 public void loadIn(Tab t) {
3969 if (mVoiceIntent != null) {
3970 t.activateVoiceSearchMode(mVoiceIntent);
3972 t.getWebView().loadUrl(mUrl, mHeaders);
3977 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);