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.util.Patterns;
77 import android.view.ContextMenu;
78 import android.view.Gravity;
79 import android.view.KeyEvent;
80 import android.view.LayoutInflater;
81 import android.view.Menu;
82 import android.view.MenuInflater;
83 import android.view.MenuItem;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.Window;
87 import android.view.WindowManager;
88 import android.view.ContextMenu.ContextMenuInfo;
89 import android.view.MenuItem.OnMenuItemClickListener;
90 import android.webkit.CookieManager;
91 import android.webkit.CookieSyncManager;
92 import android.webkit.DownloadListener;
93 import android.webkit.HttpAuthHandler;
94 import android.webkit.PluginManager;
95 import android.webkit.SslErrorHandler;
96 import android.webkit.URLUtil;
97 import android.webkit.ValueCallback;
98 import android.webkit.WebChromeClient;
99 import android.webkit.WebHistoryItem;
100 import android.webkit.WebIconDatabase;
101 import android.webkit.WebView;
102 import android.widget.EditText;
103 import android.widget.FrameLayout;
104 import android.widget.LinearLayout;
105 import android.widget.TextView;
106 import android.widget.Toast;
107 import android.accounts.Account;
108 import android.accounts.AccountManager;
109 import android.accounts.AccountManagerFuture;
110 import android.accounts.AuthenticatorException;
111 import android.accounts.OperationCanceledException;
112 import android.accounts.AccountManagerCallback;
114 import com.android.common.Search;
115 import com.android.common.speech.LoggingEvents;
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.HashSet;
130 import java.util.Iterator;
131 import java.util.List;
132 import java.util.Map;
133 import java.util.Set;
134 import java.util.regex.Matcher;
135 import java.util.regex.Pattern;
137 public class BrowserActivity extends Activity
138 implements View.OnCreateContextMenuListener, DownloadListener,
139 AccountManagerCallback<Account[]> {
141 /* Define some aliases to make these debugging flags easier to refer to.
142 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
144 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
145 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
146 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
148 // These are single-character shortcuts for searching popular sources.
149 private static final int SHORTCUT_INVALID = 0;
150 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
151 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
152 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
153 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
155 private Account[] mAccountsGoogle;
156 private Account[] mAccountsPreferHosted;
158 // XXX: These constants should be exposed through some public api. Hardcode
159 // the values for now until some solution for gsf can be worked out.
160 // http://b/issue?id=2425179
161 private static final String ACCOUNT_TYPE = "com.google";
162 private static final String FEATURE_LEGACY_GOOGLE = "legacy_google";
163 private static final String FEATURE_LEGACY_HOSTED_OR_GOOGLE =
164 "legacy_hosted_or_google";
166 private void startReadOfGoogleAccounts() {
167 mAccountsGoogle = null;
168 mAccountsPreferHosted = null;
170 AccountManager.get(this).getAccountsByTypeAndFeatures(
171 ACCOUNT_TYPE, new String[]{ FEATURE_LEGACY_HOSTED_OR_GOOGLE },
175 /** This implements AccountManagerCallback<Account[]> */
176 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
178 if (mAccountsGoogle == null) {
179 mAccountsGoogle = accountManagerFuture.getResult();
181 AccountManager.get(this).getAccountsByTypeAndFeatures(
182 ACCOUNT_TYPE, new String[]{ FEATURE_LEGACY_GOOGLE },
185 mAccountsPreferHosted = accountManagerFuture.getResult();
188 } catch (OperationCanceledException e) {
190 } catch (IOException e) {
192 } catch (AuthenticatorException e) {
197 private void setupHomePage() {
198 // get the default home page
199 String homepage = mSettings.getHomePage();
201 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
204 // hostedUser == googleUser
205 // The device has only a google account
207 // hostedUser != googleUser
208 // The device has a hosted account and a google account
210 // hostedUser != null, googleUser == null
211 // The device has only a hosted account (so far)
212 String hostedUser = mAccountsPreferHosted.length == 0
214 : mAccountsPreferHosted[0].name;
215 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
217 // developers might have no accounts at all
218 if (hostedUser == null) return;
220 if (googleUser == null || !hostedUser.equals(googleUser)) {
221 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
222 homepage = homepage.replace("?", "/a/" + domain + "?");
226 mSettings.setHomePage(BrowserActivity.this, homepage);
227 resumeAfterCredentials();
230 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
232 public Void doInBackground(File... files) {
234 for (File f : files) {
236 Log.e(LOGTAG, f.getPath() + " was not deleted");
245 * This layout holds everything you see below the status bar, including the
246 * error console, the custom view container, and the webviews.
248 private FrameLayout mBrowserFrameLayout;
251 public void onCreate(Bundle icicle) {
253 Log.v(LOGTAG, this + " onStart");
255 super.onCreate(icicle);
256 // test the browser in OpenGL
257 // requestWindowFeature(Window.FEATURE_OPENGL);
259 // enable this to test the browser in 32bit
261 getWindow().setFormat(PixelFormat.RGBX_8888);
262 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
265 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
267 mResolver = getContentResolver();
269 // If this was a web search request, pass it on to the default web
270 // search provider and finish this activity.
271 if (handleWebSearchIntent(getIntent())) {
276 mSecLockIcon = Resources.getSystem().getDrawable(
277 android.R.drawable.ic_secure);
278 mMixLockIcon = Resources.getSystem().getDrawable(
279 android.R.drawable.ic_partial_secure);
281 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
282 .findViewById(com.android.internal.R.id.content);
283 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
284 .inflate(R.layout.custom_screen, null);
285 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
287 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
288 .findViewById(R.id.error_console);
289 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
290 .findViewById(R.id.fullscreen_custom_content);
291 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
292 mTitleBar = new TitleBar(this);
293 mFakeTitleBar = new TitleBar(this);
295 // Create the tab control and our initial tab
296 mTabControl = new TabControl(this);
298 // Open the icon database and retain all the bookmark urls for favicons
299 retainIconsOnStartup();
301 // Keep a settings instance handy.
302 mSettings = BrowserSettings.getInstance();
303 mSettings.setTabControl(mTabControl);
304 mSettings.loadFromDb(this);
306 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
307 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
309 /* enables registration for changes in network status from
311 mNetworkStateChangedFilter = new IntentFilter();
312 mNetworkStateChangedFilter.addAction(
313 ConnectivityManager.CONNECTIVITY_ACTION);
314 mNetworkStateIntentReceiver = new BroadcastReceiver() {
316 public void onReceive(Context context, Intent intent) {
317 if (intent.getAction().equals(
318 ConnectivityManager.CONNECTIVITY_ACTION)) {
320 NetworkInfo info = intent.getParcelableExtra(
321 ConnectivityManager.EXTRA_NETWORK_INFO);
322 String typeName = info.getTypeName();
323 String subtypeName = info.getSubtypeName();
324 sendNetworkType(typeName.toLowerCase(),
325 (subtypeName != null ? subtypeName.toLowerCase() : ""));
327 onNetworkToggle(info.isAvailable());
332 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
333 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
334 filter.addDataScheme("package");
335 mPackageInstallationReceiver = new BroadcastReceiver() {
337 public void onReceive(Context context, Intent intent) {
338 final String action = intent.getAction();
339 final String packageName = intent.getData()
340 .getSchemeSpecificPart();
341 final boolean replacing = intent.getBooleanExtra(
342 Intent.EXTRA_REPLACING, false);
343 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
344 // if it is replacing, refreshPlugins() when adding
348 if (sGoogleApps.contains(packageName)) {
349 BrowserActivity.this.packageChanged(packageName,
350 Intent.ACTION_PACKAGE_ADDED.equals(action));
353 PackageManager pm = BrowserActivity.this.getPackageManager();
354 PackageInfo pkgInfo = null;
356 pkgInfo = pm.getPackageInfo(packageName,
357 PackageManager.GET_PERMISSIONS);
358 } catch (PackageManager.NameNotFoundException e) {
361 if (pkgInfo != null) {
362 String permissions[] = pkgInfo.requestedPermissions;
363 if (permissions == null) {
366 boolean permissionOk = false;
367 for (String permit : permissions) {
368 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
374 PluginManager.getInstance(BrowserActivity.this)
376 Intent.ACTION_PACKAGE_ADDED
382 registerReceiver(mPackageInstallationReceiver, filter);
384 if (!mTabControl.restoreState(icicle)) {
385 // clear up the thumbnail directory if we can't restore the state as
386 // none of the files in the directory are referenced any more.
387 new ClearThumbnails().execute(
388 mTabControl.getThumbnailDir().listFiles());
389 // there is no quit on Android. But if we can't restore the state,
390 // we can treat it as a new Browser, remove the old session cookies.
391 CookieManager.getInstance().removeSessionCookie();
392 final Intent intent = getIntent();
393 final Bundle extra = intent.getExtras();
394 // Create an initial tab.
395 // If the intent is ACTION_VIEW and data is not null, the Browser is
396 // invoked to view the content by another application. In this case,
397 // the tab will be close when exit.
398 UrlData urlData = getUrlDataFromIntent(intent);
400 String action = intent.getAction();
401 final Tab t = mTabControl.createNewTab(
402 (Intent.ACTION_VIEW.equals(action) &&
403 intent.getData() != null)
404 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
406 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
407 mTabControl.setCurrentTab(t);
408 attachTabToContentView(t);
409 WebView webView = t.getWebView();
411 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
412 if (scale > 0 && scale <= 1000) {
413 webView.setInitialScale(scale);
416 // If we are not restoring from an icicle, then there is a high
417 // likely hood this is the first run. So, check to see if the
418 // homepage needs to be configured and copy any plugins from our
419 // asset directory to the data partition.
420 if ((extra == null || !extra.getBoolean("testing"))
421 && !mSettings.isLoginInitialized()) {
422 startReadOfGoogleAccounts();
425 if (urlData.isEmpty()) {
426 if (mSettings.isLoginInitialized()) {
427 loadUrl(webView, mSettings.getHomePage());
429 waitForCredentials();
432 loadUrlDataIn(t, urlData);
435 // TabControl.restoreState() will create a new tab even if
436 // restoring the state fails.
437 attachTabToContentView(mTabControl.getCurrentTab());
440 // Read JavaScript flags if it exists.
441 String jsFlags = mSettings.getJsFlags();
442 if (jsFlags.trim().length() != 0) {
443 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
445 // Work out which packages are installed on the system.
446 getInstalledPackages();
450 * Feed the previously stored results strings to the BrowserProvider so that
451 * the SearchDialog will show them instead of the standard searches.
452 * @param result String to show on the editable line of the SearchDialog.
454 /* package */ void showVoiceSearchResults(String result) {
455 ContentProviderClient client = mResolver.acquireContentProviderClient(
456 Browser.BOOKMARKS_URI);
457 ContentProvider prov = client.getLocalContentProvider();
458 BrowserProvider bp = (BrowserProvider) prov;
459 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
462 startSearch(result, false,
463 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
468 protected void onNewIntent(Intent intent) {
469 Tab current = mTabControl.getCurrentTab();
470 // When a tab is closed on exit, the current tab index is set to -1.
471 // Reset before proceed as Browser requires the current tab to be set.
472 if (current == null) {
473 // Try to reset the tab in case the index was incorrect.
474 current = mTabControl.getTab(0);
475 if (current == null) {
476 // No tabs at all so just ignore this intent.
479 mTabControl.setCurrentTab(current);
480 attachTabToContentView(current);
481 resetTitleAndIcon(current.getWebView());
483 final String action = intent.getAction();
484 final int flags = intent.getFlags();
485 if (Intent.ACTION_MAIN.equals(action) ||
486 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
487 // just resume the browser
490 boolean activateVoiceSearch = RecognizerResultsIntent
491 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
492 if (Intent.ACTION_VIEW.equals(action)
493 || Intent.ACTION_SEARCH.equals(action)
494 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
495 || Intent.ACTION_WEB_SEARCH.equals(action)
496 || activateVoiceSearch) {
497 if (current.isInVoiceSearchMode()) {
498 String title = current.getVoiceDisplayTitle();
499 if (title != null && title.equals(intent.getStringExtra(
500 SearchManager.QUERY))) {
501 // The user submitted the same search as the last voice
502 // search, so do nothing.
505 if (Intent.ACTION_SEARCH.equals(action)
506 && current.voiceSearchSourceIsGoogle()) {
507 Intent logIntent = new Intent(
508 LoggingEvents.ACTION_LOG_EVENT);
509 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
510 LoggingEvents.VoiceSearch.QUERY_UPDATED);
512 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
513 intent.getDataString());
514 sendBroadcast(logIntent);
515 // Note, onPageStarted will revert the voice title bar
516 // When http://b/issue?id=2379215 is fixed, we should update
517 // the title bar here.
520 // If this was a search request (e.g. search query directly typed into the address bar),
521 // pass it on to the default web search provider.
522 if (handleWebSearchIntent(intent)) {
526 UrlData urlData = getUrlDataFromIntent(intent);
527 if (urlData.isEmpty()) {
528 urlData = new UrlData(mSettings.getHomePage());
531 final String appId = intent
532 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
533 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
534 && !getPackageName().equals(appId)
535 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
536 Tab appTab = mTabControl.getTabFromId(appId);
537 if (appTab != null) {
538 Log.i(LOGTAG, "Reusing tab for " + appId);
539 // Dismiss the subwindow if applicable.
540 dismissSubWindow(appTab);
541 // Since we might kill the WebView, remove it from the
542 // content view first.
543 removeTabFromContentView(appTab);
544 // Recreate the main WebView after destroying the old one.
545 // If the WebView has the same original url and is on that
546 // page, it can be reused.
548 mTabControl.recreateWebView(appTab, urlData.mUrl);
550 if (current != appTab) {
551 switchToTab(mTabControl.getTabIndex(appTab));
553 loadUrlDataIn(appTab, urlData);
556 // If the tab was the current tab, we have to attach
557 // it to the view system again.
558 attachTabToContentView(appTab);
560 loadUrlDataIn(appTab, urlData);
565 // No matching application tab, try to find a regular tab
566 // with a matching url.
567 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
568 if (appTab != null) {
569 if (current != appTab) {
570 switchToTab(mTabControl.getTabIndex(appTab));
572 // Otherwise, we are already viewing the correct tab.
574 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
575 // will be opened in a new tab unless we have reached
576 // MAX_TABS. Then the url will be opened in the current
577 // tab. If a new tab is created, it will have "true" for
579 openTabAndShow(urlData, true, appId);
583 if (!urlData.isEmpty()
584 && urlData.mUrl.startsWith("about:debug")) {
585 if ("about:debug.dom".equals(urlData.mUrl)) {
586 current.getWebView().dumpDomTree(false);
587 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
588 current.getWebView().dumpDomTree(true);
589 } else if ("about:debug.render".equals(urlData.mUrl)) {
590 current.getWebView().dumpRenderTree(false);
591 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
592 current.getWebView().dumpRenderTree(true);
593 } else if ("about:debug.display".equals(urlData.mUrl)) {
594 current.getWebView().dumpDisplayTree();
595 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
596 int index = urlData.mUrl.codePointAt(16) - '0';
597 if (index <= 0 || index > 9) {
598 current.getWebView().setDragTracker(null);
600 current.getWebView().setDragTracker(new MeshTracker(index));
603 mSettings.toggleDebugSettings();
607 // Get rid of the subwindow if it exists
608 dismissSubWindow(current);
609 loadUrlDataIn(current, urlData);
614 private int parseUrlShortcut(String url) {
615 if (url == null) return SHORTCUT_INVALID;
617 // FIXME: quick search, need to be customized by setting
618 if (url.length() > 2 && url.charAt(1) == ' ') {
619 switch (url.charAt(0)) {
620 case 'g': return SHORTCUT_GOOGLE_SEARCH;
621 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
622 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
623 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
626 return SHORTCUT_INVALID;
630 * Launches the default web search activity with the query parameters if the given intent's data
631 * are identified as plain search terms and not URLs/shortcuts.
632 * @return true if the intent was handled and web search activity was launched, false if not.
634 private boolean handleWebSearchIntent(Intent intent) {
635 if (intent == null) return false;
638 final String action = intent.getAction();
639 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
643 if (Intent.ACTION_VIEW.equals(action)) {
644 Uri data = intent.getData();
645 if (data != null) url = data.toString();
646 } else if (Intent.ACTION_SEARCH.equals(action)
647 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
648 || Intent.ACTION_WEB_SEARCH.equals(action)) {
649 url = intent.getStringExtra(SearchManager.QUERY);
651 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
652 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
656 * Launches the default web search activity with the query parameters if the given url string
657 * was identified as plain search terms and not URL/shortcut.
658 * @return true if the request was handled and web search activity was launched, false if not.
660 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
661 if (inUrl == null) return false;
663 // In general, we shouldn't modify URL from Intent.
664 // But currently, we get the user-typed URL from search box as well.
665 String url = fixUrl(inUrl).trim();
667 // URLs and site specific search shortcuts are handled by the regular flow of control, so
669 if (Patterns.WEB_URL.matcher(url).matches()
670 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
671 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
675 Browser.updateVisitedHistory(mResolver, url, false);
676 Browser.addSearchUrl(mResolver, url);
678 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
679 intent.addCategory(Intent.CATEGORY_DEFAULT);
680 intent.putExtra(SearchManager.QUERY, url);
681 if (appData != null) {
682 intent.putExtra(SearchManager.APP_DATA, appData);
684 if (extraData != null) {
685 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
687 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
688 startActivity(intent);
693 private UrlData getUrlDataFromIntent(Intent intent) {
695 Map<String, String> headers = null;
696 if (intent != null) {
697 final String action = intent.getAction();
698 if (Intent.ACTION_VIEW.equals(action)) {
699 url = smartUrlFilter(intent.getData());
700 if (url != null && url.startsWith("content:")) {
701 /* Append mimetype so webview knows how to display */
702 String mimeType = intent.resolveType(getContentResolver());
703 if (mimeType != null) {
704 url += "?" + mimeType;
707 if (url != null && url.startsWith("http")) {
708 final Bundle pairs = intent
709 .getBundleExtra(Browser.EXTRA_HEADERS);
710 if (pairs != null && !pairs.isEmpty()) {
711 Iterator<String> iter = pairs.keySet().iterator();
712 headers = new HashMap<String, String>();
713 while (iter.hasNext()) {
714 String key = iter.next();
715 headers.put(key, pairs.getString(key));
719 } else if (Intent.ACTION_SEARCH.equals(action)
720 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
721 || Intent.ACTION_WEB_SEARCH.equals(action)) {
722 url = intent.getStringExtra(SearchManager.QUERY);
724 mLastEnteredUrl = url;
725 Browser.updateVisitedHistory(mResolver, url, false);
726 // In general, we shouldn't modify URL from Intent.
727 // But currently, we get the user-typed URL from search box as well.
729 url = smartUrlFilter(url);
730 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
731 if (url.contains(searchSource)) {
732 String source = null;
733 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
734 if (appData != null) {
735 source = appData.getString(Search.SOURCE);
737 if (TextUtils.isEmpty(source)) {
738 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
740 url = url.replace(searchSource, "&source=android-"+source+"&");
745 return new UrlData(url, headers, intent);
747 /* package */ void showVoiceTitleBar(String title) {
748 mTitleBar.setInVoiceMode(true);
749 mFakeTitleBar.setInVoiceMode(true);
751 mTitleBar.setDisplayTitle(title);
752 mFakeTitleBar.setDisplayTitle(title);
754 /* package */ void revertVoiceTitleBar() {
755 mTitleBar.setInVoiceMode(false);
756 mFakeTitleBar.setInVoiceMode(false);
758 mTitleBar.setDisplayTitle(mTitle);
759 mFakeTitleBar.setDisplayTitle(mTitle);
761 /* package */ static String fixUrl(String inUrl) {
762 // FIXME: Converting the url to lower case
763 // duplicates functionality in smartUrlFilter().
764 // However, changing all current callers of fixUrl to
765 // call smartUrlFilter in addition may have unwanted
766 // consequences, and is deferred for now.
767 int colon = inUrl.indexOf(':');
768 boolean allLower = true;
769 for (int index = 0; index < colon; index++) {
770 char ch = inUrl.charAt(index);
771 if (!Character.isLetter(ch)) {
774 allLower &= Character.isLowerCase(ch);
775 if (index == colon - 1 && !allLower) {
776 inUrl = inUrl.substring(0, colon).toLowerCase()
777 + inUrl.substring(colon);
780 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
782 if (inUrl.startsWith("http:") ||
783 inUrl.startsWith("https:")) {
784 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
785 inUrl = inUrl.replaceFirst("/", "//");
786 } else inUrl = inUrl.replaceFirst(":", "://");
792 protected void onResume() {
795 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
798 if (!mActivityInPause) {
799 Log.e(LOGTAG, "BrowserActivity is already resumed.");
803 mTabControl.resumeCurrentTab();
804 mActivityInPause = false;
805 resumeWebViewTimers();
807 if (mWakeLock.isHeld()) {
808 mHandler.removeMessages(RELEASE_WAKELOCK);
812 if (mCredsDlg != null) {
813 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
814 // In case credential request never comes back
815 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
819 registerReceiver(mNetworkStateIntentReceiver,
820 mNetworkStateChangedFilter);
821 WebView.enablePlatformNotifications();
825 * Since the actual title bar is embedded in the WebView, and removing it
826 * would change its appearance, use a different TitleBar to show overlayed
827 * at the top of the screen, when the menu is open or the page is loading.
829 private TitleBar mFakeTitleBar;
832 * Holder for the fake title bar. It will have a foreground shadow, as well
833 * as a white background, so the fake title bar looks like the real one.
835 private ViewGroup mFakeTitleBarHolder;
838 * Layout parameters for the fake title bar within mFakeTitleBarHolder
840 private FrameLayout.LayoutParams mFakeTitleBarParams
841 = new FrameLayout.LayoutParams(
842 ViewGroup.LayoutParams.MATCH_PARENT,
843 ViewGroup.LayoutParams.WRAP_CONTENT);
845 * Keeps track of whether the options menu is open. This is important in
846 * determining whether to show or hide the title bar overlay.
848 private boolean mOptionsMenuOpen;
851 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
852 * of whether the configuration has changed. The first onMenuOpened call
853 * after a configuration change is simply a reopening of the same menu
854 * (i.e. mIconView did not change).
856 private boolean mConfigChanged;
859 * Whether or not the options menu is in its smaller, icon menu form. When
860 * true, we want the title bar overlay to be up. When false, we do not.
861 * Only meaningful if mOptionsMenuOpen is true.
863 private boolean mIconView;
866 public boolean onMenuOpened(int featureId, Menu menu) {
867 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
868 if (mOptionsMenuOpen) {
869 if (mConfigChanged) {
870 // We do not need to make any changes to the state of the
871 // title bar, since the only thing that happened was a
872 // change in orientation
873 mConfigChanged = false;
876 // Switching the menu to expanded view, so hide the
881 // Switching the menu back to icon view, so show the
882 // title bar once again.
888 // The options menu is closed, so open it, and show the title
890 mOptionsMenuOpen = true;
891 mConfigChanged = false;
899 * Special class used exclusively for the shadow drawn underneath the fake
900 * title bar. The shadow does not need to be drawn if the WebView
901 * underneath is scrolled to the top, because it will draw directly on top
902 * of the embedded shadow.
904 private static class Shadow extends View {
905 private WebView mWebView;
907 public Shadow(Context context, AttributeSet attrs) {
908 super(context, attrs);
911 public void setWebView(WebView view) {
916 public void draw(Canvas canvas) {
917 // In general onDraw is the method to override, but we care about
918 // whether or not the background gets drawn, which happens in draw()
919 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
922 // Need to invalidate so that if the scroll position changes, we
923 // still draw as appropriate.
928 private void showFakeTitleBar() {
929 final View decor = getWindow().peekDecorView();
930 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
931 && !mActivityInPause && decor != null
932 && decor.getWindowToken() != null) {
933 Rect visRect = new Rect();
934 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
936 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
941 WindowManager manager
942 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
944 // Add the title bar to the window manager so it can receive touches
945 // while the menu is up
946 WindowManager.LayoutParams params
947 = new WindowManager.LayoutParams(
948 ViewGroup.LayoutParams.MATCH_PARENT,
949 ViewGroup.LayoutParams.WRAP_CONTENT,
950 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
951 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
952 PixelFormat.TRANSLUCENT);
953 params.gravity = Gravity.TOP;
954 WebView mainView = mTabControl.getCurrentWebView();
955 boolean atTop = mainView != null && mainView.getScrollY() == 0;
956 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
957 // XXX : Without providing an offset, the fake title bar will be
958 // placed underneath the status bar. Use the global visible rect
959 // of mBrowserFrameLayout to determine the bottom of the status bar
960 params.y = visRect.top;
961 // Add a holder for the title bar. It also holds a shadow to show
962 // below the title bar.
963 if (mFakeTitleBarHolder == null) {
964 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
965 .inflate(R.layout.title_bar_bg, null);
967 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
969 shadow.setWebView(mainView);
970 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
971 manager.addView(mFakeTitleBarHolder, params);
976 public void onOptionsMenuClosed(Menu menu) {
977 mOptionsMenuOpen = false;
980 } else if (!mIconView) {
981 // The page is currently loading, and we are in expanded mode, so
982 // we were not showing the menu. Show it once again. It will be
983 // removed when the page finishes.
988 private void hideFakeTitleBar() {
989 if (mFakeTitleBar.getParent() == null) return;
990 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
991 mFakeTitleBarHolder.getLayoutParams();
992 WebView mainView = mTabControl.getCurrentWebView();
993 // Although we decided whether or not to animate based on the current
994 // scroll position, the scroll position may have changed since the
995 // fake title bar was displayed. Make sure it has the appropriate
996 // animation/lack thereof before removing.
997 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
998 ? 0 : R.style.TitleBar;
999 WindowManager manager
1000 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1001 manager.updateViewLayout(mFakeTitleBarHolder, params);
1002 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1003 manager.removeView(mFakeTitleBarHolder);
1007 * Special method for the fake title bar to call when displaying its context
1008 * menu, since it is in its own Window, and its parent does not show a
1011 /* package */ void showTitleBarContextMenu() {
1012 if (null == mTitleBar.getParent()) {
1015 openContextMenu(mTitleBar);
1019 public void onContextMenuClosed(Menu menu) {
1020 super.onContextMenuClosed(menu);
1027 * onSaveInstanceState(Bundle map)
1028 * onSaveInstanceState is called right before onStop(). The map contains
1032 protected void onSaveInstanceState(Bundle outState) {
1034 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1036 // the default implementation requires each view to have an id. As the
1037 // browser handles the state itself and it doesn't use id for the views,
1038 // don't call the default implementation. Otherwise it will trigger the
1039 // warning like this, "couldn't save which view has focus because the
1040 // focused view XXX has no id".
1042 // Save all the tabs
1043 mTabControl.saveState(outState);
1047 protected void onPause() {
1050 if (mActivityInPause) {
1051 Log.e(LOGTAG, "BrowserActivity is already paused.");
1055 mTabControl.pauseCurrentTab();
1056 mActivityInPause = true;
1057 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1058 mWakeLock.acquire();
1059 mHandler.sendMessageDelayed(mHandler
1060 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1063 // Clear the credentials toast if it is up
1064 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1065 mCredsDlg.dismiss();
1069 // FIXME: This removes the active tabs page and resets the menu to
1070 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1071 // but then we would need to save it in onSaveInstanceState and restore
1072 // it in onCreate/onRestoreInstanceState
1073 if (mActiveTabsPage != null) {
1074 removeActiveTabPage(true);
1079 // unregister network state listener
1080 unregisterReceiver(mNetworkStateIntentReceiver);
1081 WebView.disablePlatformNotifications();
1085 protected void onDestroy() {
1087 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1091 if (mUploadMessage != null) {
1092 mUploadMessage.onReceiveValue(null);
1093 mUploadMessage = null;
1096 if (mTabControl == null) return;
1098 // Remove the fake title bar if it is there
1101 // Remove the current tab and sub window
1102 Tab t = mTabControl.getCurrentTab();
1104 dismissSubWindow(t);
1105 removeTabFromContentView(t);
1107 // Destroy all the tabs
1108 mTabControl.destroy();
1109 WebIconDatabase.getInstance().close();
1111 unregisterReceiver(mPackageInstallationReceiver);
1115 public void onConfigurationChanged(Configuration newConfig) {
1116 mConfigChanged = true;
1117 super.onConfigurationChanged(newConfig);
1119 if (mPageInfoDialog != null) {
1120 mPageInfoDialog.dismiss();
1123 mPageInfoFromShowSSLCertificateOnError);
1125 if (mSSLCertificateDialog != null) {
1126 mSSLCertificateDialog.dismiss();
1128 mSSLCertificateView);
1130 if (mSSLCertificateOnErrorDialog != null) {
1131 mSSLCertificateOnErrorDialog.dismiss();
1132 showSSLCertificateOnError(
1133 mSSLCertificateOnErrorView,
1134 mSSLCertificateOnErrorHandler,
1135 mSSLCertificateOnErrorError);
1137 if (mHttpAuthenticationDialog != null) {
1138 String title = ((TextView) mHttpAuthenticationDialog
1139 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1141 String name = ((TextView) mHttpAuthenticationDialog
1142 .findViewById(R.id.username_edit)).getText().toString();
1143 String password = ((TextView) mHttpAuthenticationDialog
1144 .findViewById(R.id.password_edit)).getText().toString();
1145 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1147 mHttpAuthenticationDialog.dismiss();
1148 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1149 name, password, focusId);
1154 public void onLowMemory() {
1155 super.onLowMemory();
1156 mTabControl.freeMemory();
1159 private boolean resumeWebViewTimers() {
1160 Tab tab = mTabControl.getCurrentTab();
1161 boolean inLoad = tab.inLoad();
1162 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1163 CookieSyncManager.getInstance().startSync();
1164 WebView w = tab.getWebView();
1174 private boolean pauseWebViewTimers() {
1175 Tab tab = mTabControl.getCurrentTab();
1176 boolean inLoad = tab.inLoad();
1177 if (mActivityInPause && !inLoad) {
1178 CookieSyncManager.getInstance().stopSync();
1179 WebView w = mTabControl.getCurrentWebView();
1189 // FIXME: Do we want to call this when loading google for the first time?
1191 * This function is called when we are launching for the first time. We
1192 * are waiting for the login credentials before loading Google home
1193 * pages. This way the user will be logged in straight away.
1195 private void waitForCredentials() {
1197 mCredsDlg = new ProgressDialog(this);
1198 mCredsDlg.setIndeterminate(true);
1199 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1200 // If the user cancels the operation, then cancel the Google
1201 // Credentials request.
1202 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1205 // We set a timeout for the retrieval of credentials in onResume()
1206 // as that is when we have freed up some CPU time to get
1207 // the login credentials.
1211 * If we have received the credentials or we have timed out and we are
1212 * showing the credentials dialog, then it is time to move on.
1214 private void resumeAfterCredentials() {
1215 if (mCredsDlg == null) {
1220 if (mCredsDlg.isShowing()) {
1221 mCredsDlg.dismiss();
1225 // Clear any pending timeout
1226 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1229 WebView w = mTabControl.getCurrentWebView();
1231 loadUrl(w, mSettings.getHomePage());
1234 // Update the settings, need to do this last as it can take a moment
1235 // to persist the settings. In the mean time we could be loading
1237 mSettings.setLoginInitialized(this);
1240 // Open the icon database and retain all the icons for visited sites.
1241 private void retainIconsOnStartup() {
1242 final WebIconDatabase db = WebIconDatabase.getInstance();
1243 db.open(getDir("icons", 0).getPath());
1245 Cursor c = Browser.getAllBookmarks(mResolver);
1246 if (!c.moveToFirst()) {
1250 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1252 String url = c.getString(urlIndex);
1253 db.retainIconForPageUrl(url);
1254 } while (c.moveToNext());
1256 } catch (IllegalStateException e) {
1257 Log.e(LOGTAG, "retainIconsOnStartup", e);
1261 // Helper method for getting the top window.
1262 WebView getTopWindow() {
1263 return mTabControl.getCurrentTopWebView();
1266 TabControl getTabControl() {
1271 public boolean onCreateOptionsMenu(Menu menu) {
1272 super.onCreateOptionsMenu(menu);
1274 MenuInflater inflater = getMenuInflater();
1275 inflater.inflate(R.menu.browser, menu);
1277 updateInLoadMenuItems();
1282 * As the menu can be open when loading state changes
1283 * we must manually update the state of the stop/reload menu
1286 private void updateInLoadMenuItems() {
1287 if (mMenu == null) {
1290 MenuItem src = mInLoad ?
1291 mMenu.findItem(R.id.stop_menu_id):
1292 mMenu.findItem(R.id.reload_menu_id);
1293 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1294 dest.setIcon(src.getIcon());
1295 dest.setTitle(src.getTitle());
1299 public boolean onContextItemSelected(MenuItem item) {
1300 // chording is not an issue with context menus, but we use the same
1301 // options selector, so set mCanChord to true so we can access them.
1303 int id = item.getItemId();
1304 boolean result = true;
1306 // For the context menu from the title bar
1307 case R.id.title_bar_copy_page_url:
1308 Tab currentTab = mTabControl.getCurrentTab();
1309 if (null == currentTab) {
1313 WebView mainView = currentTab.getWebView();
1314 if (null == mainView) {
1318 copy(mainView.getUrl());
1320 // -- Browser context menu
1321 case R.id.open_context_menu_id:
1322 case R.id.open_newtab_context_menu_id:
1323 case R.id.bookmark_context_menu_id:
1324 case R.id.save_link_context_menu_id:
1325 case R.id.share_link_context_menu_id:
1326 case R.id.copy_link_context_menu_id:
1327 final WebView webView = getTopWindow();
1328 if (null == webView) {
1332 final HashMap hrefMap = new HashMap();
1333 hrefMap.put("webview", webView);
1334 final Message msg = mHandler.obtainMessage(
1335 FOCUS_NODE_HREF, id, 0, hrefMap);
1336 webView.requestFocusNodeHref(msg);
1340 // For other context menus
1341 result = onOptionsItemSelected(item);
1347 private Bundle createGoogleSearchSourceBundle(String source) {
1348 Bundle bundle = new Bundle();
1349 bundle.putString(Search.SOURCE, source);
1353 /* package */ void editUrl() {
1354 if (mOptionsMenuOpen) closeOptionsMenu();
1355 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1356 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1361 * Overriding this to insert a local information bundle
1364 public void startSearch(String initialQuery, boolean selectInitialQuery,
1365 Bundle appSearchData, boolean globalSearch) {
1366 if (appSearchData == null) {
1367 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1369 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1373 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1374 * results in changing tabs.
1375 * @param index Index of the tab to change to, as defined by
1376 * mTabControl.getTabIndex(Tab t).
1377 * @return boolean True if we successfully switched to a different tab. If
1378 * the indexth tab is null, or if that tab is the same as
1379 * the current one, return false.
1381 /* package */ boolean switchToTab(int index) {
1382 Tab tab = mTabControl.getTab(index);
1383 Tab currentTab = mTabControl.getCurrentTab();
1384 if (tab == null || tab == currentTab) {
1387 if (currentTab != null) {
1388 // currentTab may be null if it was just removed. In that case,
1389 // we do not need to remove it
1390 removeTabFromContentView(currentTab);
1392 mTabControl.setCurrentTab(tab);
1393 attachTabToContentView(tab);
1394 resetTitleIconAndProgress();
1395 updateLockIconToLatest();
1399 /* package */ Tab openTabToHomePage() {
1400 return openTabAndShow(mSettings.getHomePage(), false, null);
1403 /* package */ void closeCurrentWindow() {
1404 final Tab current = mTabControl.getCurrentTab();
1405 if (mTabControl.getTabCount() == 1) {
1406 // This is the last tab. Open a new one, with the home
1407 // page and close the current one.
1408 openTabToHomePage();
1412 final Tab parent = current.getParentTab();
1413 int indexToShow = -1;
1414 if (parent != null) {
1415 indexToShow = mTabControl.getTabIndex(parent);
1417 final int currentIndex = mTabControl.getCurrentIndex();
1418 // Try to move to the tab to the right
1419 indexToShow = currentIndex + 1;
1420 if (indexToShow > mTabControl.getTabCount() - 1) {
1421 // Try to move to the tab to the left
1422 indexToShow = currentIndex - 1;
1425 if (switchToTab(indexToShow)) {
1431 private ActiveTabsPage mActiveTabsPage;
1434 * Remove the active tabs page.
1435 * @param needToAttach If true, the active tabs page did not attach a tab
1436 * to the content view, so we need to do that here.
1438 /* package */ void removeActiveTabPage(boolean needToAttach) {
1439 mContentView.removeView(mActiveTabsPage);
1440 mActiveTabsPage = null;
1441 mMenuState = R.id.MAIN_MENU;
1443 attachTabToContentView(mTabControl.getCurrentTab());
1445 getTopWindow().requestFocus();
1449 public boolean onOptionsItemSelected(MenuItem item) {
1451 // The user has already fired a shortcut with this hold down of the
1455 if (null == getTopWindow()) {
1459 // The shortcut action consumes the MENU. Even if it is still down,
1460 // it won't trigger the next shortcut action. In the case of the
1461 // shortcut action triggering a new activity, like Bookmarks, we
1462 // won't get onKeyUp for MENU. So it is important to reset it here.
1463 mMenuIsDown = false;
1465 switch (item.getItemId()) {
1467 case R.id.new_tab_menu_id:
1468 openTabToHomePage();
1471 case R.id.goto_menu_id:
1475 case R.id.bookmarks_menu_id:
1476 bookmarksOrHistoryPicker(false);
1479 case R.id.active_tabs_menu_id:
1480 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1481 removeTabFromContentView(mTabControl.getCurrentTab());
1483 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1484 mActiveTabsPage.requestFocus();
1485 mMenuState = EMPTY_MENU;
1488 case R.id.add_bookmark_menu_id:
1489 Intent i = new Intent(BrowserActivity.this,
1490 AddBookmarkPage.class);
1491 WebView w = getTopWindow();
1492 i.putExtra("url", w.getUrl());
1493 i.putExtra("title", w.getTitle());
1494 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1495 i.putExtra("thumbnail", createScreenshot(w));
1499 case R.id.stop_reload_menu_id:
1503 getTopWindow().reload();
1507 case R.id.back_menu_id:
1508 getTopWindow().goBack();
1511 case R.id.forward_menu_id:
1512 getTopWindow().goForward();
1515 case R.id.close_menu_id:
1516 // Close the subwindow if it exists.
1517 if (mTabControl.getCurrentSubWindow() != null) {
1518 dismissSubWindow(mTabControl.getCurrentTab());
1521 closeCurrentWindow();
1524 case R.id.homepage_menu_id:
1525 Tab current = mTabControl.getCurrentTab();
1526 if (current != null) {
1527 dismissSubWindow(current);
1528 loadUrl(current.getWebView(), mSettings.getHomePage());
1532 case R.id.preferences_menu_id:
1533 Intent intent = new Intent(this,
1534 BrowserPreferencesPage.class);
1535 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1536 getTopWindow().getUrl());
1537 startActivityForResult(intent, PREFERENCES_PAGE);
1540 case R.id.find_menu_id:
1541 if (null == mFindDialog) {
1542 mFindDialog = new FindDialog(this);
1544 mFindDialog.setWebView(getTopWindow());
1546 mMenuState = EMPTY_MENU;
1549 case R.id.select_text_id:
1550 getTopWindow().emulateShiftHeld();
1552 case R.id.page_info_menu_id:
1553 showPageInfo(mTabControl.getCurrentTab(), false);
1556 case R.id.classic_history_menu_id:
1557 bookmarksOrHistoryPicker(true);
1560 case R.id.title_bar_share_page_url:
1561 case R.id.share_page_menu_id:
1562 Tab currentTab = mTabControl.getCurrentTab();
1563 if (null == currentTab) {
1567 currentTab.populatePickerData();
1568 sharePage(this, currentTab.getTitle(),
1569 currentTab.getUrl(), currentTab.getFavicon(),
1570 createScreenshot(currentTab.getWebView()));
1573 case R.id.dump_nav_menu_id:
1574 getTopWindow().debugDump();
1577 case R.id.dump_counters_menu_id:
1578 getTopWindow().dumpV8Counters();
1581 case R.id.zoom_in_menu_id:
1582 getTopWindow().zoomIn();
1585 case R.id.zoom_out_menu_id:
1586 getTopWindow().zoomOut();
1589 case R.id.view_downloads_menu_id:
1590 viewDownloads(null);
1593 case R.id.window_one_menu_id:
1594 case R.id.window_two_menu_id:
1595 case R.id.window_three_menu_id:
1596 case R.id.window_four_menu_id:
1597 case R.id.window_five_menu_id:
1598 case R.id.window_six_menu_id:
1599 case R.id.window_seven_menu_id:
1600 case R.id.window_eight_menu_id:
1602 int menuid = item.getItemId();
1603 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1604 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1605 Tab desiredTab = mTabControl.getTab(id);
1606 if (desiredTab != null &&
1607 desiredTab != mTabControl.getCurrentTab()) {
1617 if (!super.onOptionsItemSelected(item)) {
1620 // Otherwise fall through.
1626 public void closeFind() {
1627 mMenuState = R.id.MAIN_MENU;
1631 public boolean onPrepareOptionsMenu(Menu menu) {
1632 // This happens when the user begins to hold down the menu key, so
1633 // allow them to chord to get a shortcut.
1635 // Note: setVisible will decide whether an item is visible; while
1636 // setEnabled() will decide whether an item is enabled, which also means
1637 // whether the matching shortcut key will function.
1638 super.onPrepareOptionsMenu(menu);
1639 switch (mMenuState) {
1641 if (mCurrentMenuState != mMenuState) {
1642 menu.setGroupVisible(R.id.MAIN_MENU, false);
1643 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1644 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1648 if (mCurrentMenuState != mMenuState) {
1649 menu.setGroupVisible(R.id.MAIN_MENU, true);
1650 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1651 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1653 final WebView w = getTopWindow();
1654 boolean canGoBack = false;
1655 boolean canGoForward = false;
1656 boolean isHome = false;
1658 canGoBack = w.canGoBack();
1659 canGoForward = w.canGoForward();
1660 isHome = mSettings.getHomePage().equals(w.getUrl());
1662 final MenuItem back = menu.findItem(R.id.back_menu_id);
1663 back.setEnabled(canGoBack);
1665 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1666 home.setEnabled(!isHome);
1668 menu.findItem(R.id.forward_menu_id)
1669 .setEnabled(canGoForward);
1671 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1672 mTabControl.canCreateNewTab());
1674 // decide whether to show the share link option
1675 PackageManager pm = getPackageManager();
1676 Intent send = new Intent(Intent.ACTION_SEND);
1677 send.setType("text/plain");
1678 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1679 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1681 boolean isNavDump = mSettings.isNavDump();
1682 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1683 nav.setVisible(isNavDump);
1684 nav.setEnabled(isNavDump);
1686 boolean showDebugSettings = mSettings.showDebugSettings();
1687 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1688 counter.setVisible(showDebugSettings);
1689 counter.setEnabled(showDebugSettings);
1693 mCurrentMenuState = mMenuState;
1698 public void onCreateContextMenu(ContextMenu menu, View v,
1699 ContextMenuInfo menuInfo) {
1700 if (v instanceof TitleBar) {
1703 WebView webview = (WebView) v;
1704 WebView.HitTestResult result = webview.getHitTestResult();
1705 if (result == null) {
1709 int type = result.getType();
1710 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1712 "We should not show context menu when nothing is touched");
1715 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1716 // let TextView handles context menu
1720 // Note, http://b/issue?id=1106666 is requesting that
1721 // an inflated menu can be used again. This is not available
1722 // yet, so inflate each time (yuk!)
1723 MenuInflater inflater = getMenuInflater();
1724 inflater.inflate(R.menu.browsercontext, menu);
1726 // Show the correct menu group
1727 String extra = result.getExtra();
1728 menu.setGroupVisible(R.id.PHONE_MENU,
1729 type == WebView.HitTestResult.PHONE_TYPE);
1730 menu.setGroupVisible(R.id.EMAIL_MENU,
1731 type == WebView.HitTestResult.EMAIL_TYPE);
1732 menu.setGroupVisible(R.id.GEO_MENU,
1733 type == WebView.HitTestResult.GEO_TYPE);
1734 menu.setGroupVisible(R.id.IMAGE_MENU,
1735 type == WebView.HitTestResult.IMAGE_TYPE
1736 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1737 menu.setGroupVisible(R.id.ANCHOR_MENU,
1738 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1739 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1741 // Setup custom handling depending on the type
1743 case WebView.HitTestResult.PHONE_TYPE:
1744 menu.setHeaderTitle(Uri.decode(extra));
1745 menu.findItem(R.id.dial_context_menu_id).setIntent(
1746 new Intent(Intent.ACTION_VIEW, Uri
1747 .parse(WebView.SCHEME_TEL + extra)));
1748 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1749 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1750 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1751 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1753 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1757 case WebView.HitTestResult.EMAIL_TYPE:
1758 menu.setHeaderTitle(extra);
1759 menu.findItem(R.id.email_context_menu_id).setIntent(
1760 new Intent(Intent.ACTION_VIEW, Uri
1761 .parse(WebView.SCHEME_MAILTO + extra)));
1762 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1766 case WebView.HitTestResult.GEO_TYPE:
1767 menu.setHeaderTitle(extra);
1768 menu.findItem(R.id.map_context_menu_id).setIntent(
1769 new Intent(Intent.ACTION_VIEW, Uri
1770 .parse(WebView.SCHEME_GEO
1771 + URLEncoder.encode(extra))));
1772 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1776 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1777 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1778 TextView titleView = (TextView) LayoutInflater.from(this)
1779 .inflate(android.R.layout.browser_link_context_header,
1781 titleView.setText(extra);
1782 menu.setHeaderView(titleView);
1783 // decide whether to show the open link in new tab option
1784 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1785 mTabControl.canCreateNewTab());
1786 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1787 Bookmarks.urlHasAcceptableScheme(extra));
1788 PackageManager pm = getPackageManager();
1789 Intent send = new Intent(Intent.ACTION_SEND);
1790 send.setType("text/plain");
1791 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1792 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1793 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1796 // otherwise fall through to handle image part
1797 case WebView.HitTestResult.IMAGE_TYPE:
1798 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1799 menu.setHeaderTitle(extra);
1801 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1802 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1803 menu.findItem(R.id.download_context_menu_id).
1804 setOnMenuItemClickListener(new Download(extra));
1805 menu.findItem(R.id.set_wallpaper_context_menu_id).
1806 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1810 Log.w(LOGTAG, "We should not get here.");
1816 // Attach the given tab to the content view.
1817 // this should only be called for the current tab.
1818 private void attachTabToContentView(Tab t) {
1819 // Attach the container that contains the main WebView and any other UI
1820 // associated with the tab.
1821 t.attachTabToContentView(mContentView);
1823 if (mShouldShowErrorConsole) {
1824 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1825 if (errorConsole.numberOfErrors() == 0) {
1826 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1828 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1831 mErrorConsoleContainer.addView(errorConsole,
1832 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1833 ViewGroup.LayoutParams.WRAP_CONTENT));
1836 WebView view = t.getWebView();
1837 view.setEmbeddedTitleBar(mTitleBar);
1838 if (t.isInVoiceSearchMode()) {
1839 showVoiceTitleBar(t.getVoiceDisplayTitle());
1841 revertVoiceTitleBar();
1843 // Request focus on the top window.
1844 t.getTopWindow().requestFocus();
1847 // Attach a sub window to the main WebView of the given tab.
1848 void attachSubWindow(Tab t) {
1849 t.attachSubWindow(mContentView);
1850 getTopWindow().requestFocus();
1853 // Remove the given tab from the content view.
1854 private void removeTabFromContentView(Tab t) {
1855 // Remove the container that contains the main WebView.
1856 t.removeTabFromContentView(mContentView);
1858 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1859 if (errorConsole != null) {
1860 mErrorConsoleContainer.removeView(errorConsole);
1863 WebView view = t.getWebView();
1865 view.setEmbeddedTitleBar(null);
1869 // Remove the sub window if it exists. Also called by TabControl when the
1870 // user clicks the 'X' to dismiss a sub window.
1871 /* package */ void dismissSubWindow(Tab t) {
1872 t.removeSubWindow(mContentView);
1873 // dismiss the subwindow. This will destroy the WebView.
1874 t.dismissSubWindow();
1875 getTopWindow().requestFocus();
1878 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1879 // that accepts url as string.
1880 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1881 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1884 // This method does a ton of stuff. It will attempt to create a new tab
1885 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1886 // url isn't null, it will load the given url.
1887 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1889 final Tab currentTab = mTabControl.getCurrentTab();
1890 if (mTabControl.canCreateNewTab()) {
1891 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1893 WebView webview = tab.getWebView();
1894 // If the last tab was removed from the active tabs page, currentTab
1896 if (currentTab != null) {
1897 removeTabFromContentView(currentTab);
1899 // We must set the new tab as the current tab to reflect the old
1900 // animation behavior.
1901 mTabControl.setCurrentTab(tab);
1902 attachTabToContentView(tab);
1903 if (!urlData.isEmpty()) {
1904 loadUrlDataIn(tab, urlData);
1908 // Get rid of the subwindow if it exists
1909 dismissSubWindow(currentTab);
1910 if (!urlData.isEmpty()) {
1911 // Load the given url.
1912 loadUrlDataIn(currentTab, urlData);
1918 private Tab openTab(String url) {
1919 if (mSettings.openInBackground()) {
1920 Tab t = mTabControl.createNewTab();
1922 WebView view = t.getWebView();
1927 return openTabAndShow(url, false, null);
1931 private class Copy implements OnMenuItemClickListener {
1932 private CharSequence mText;
1934 public boolean onMenuItemClick(MenuItem item) {
1939 public Copy(CharSequence toCopy) {
1944 private class Download implements OnMenuItemClickListener {
1945 private String mText;
1947 public boolean onMenuItemClick(MenuItem item) {
1948 onDownloadStartNoStream(mText, null, null, null, -1);
1952 public Download(String toDownload) {
1957 private class SetAsWallpaper extends Thread implements
1958 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1960 private ProgressDialog mWallpaperProgress;
1961 private boolean mCanceled = false;
1963 public SetAsWallpaper(String url) {
1965 mUrl = new URL(url);
1966 } catch (MalformedURLException e) {
1971 public void onCancel(DialogInterface dialog) {
1975 public boolean onMenuItemClick(MenuItem item) {
1977 // The user may have tried to set a image with a large file size as their
1978 // background so it may take a few moments to perform the operation. Display
1979 // a progress spinner while it is working.
1980 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1981 mWallpaperProgress.setIndeterminate(true);
1982 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1983 mWallpaperProgress.setCancelable(true);
1984 mWallpaperProgress.setOnCancelListener(this);
1985 mWallpaperProgress.show();
1992 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1994 // TODO: This will cause the resource to be downloaded again, when we
1995 // should in most cases be able to grab it from the cache. To fix this
1996 // we should query WebCore to see if we can access a cached version and
1997 // instead open an input stream on that. This pattern could also be used
1998 // in the download manager where the same problem exists.
1999 InputStream inputstream = mUrl.openStream();
2000 if (inputstream != null) {
2001 setWallpaper(inputstream);
2003 } catch (IOException e) {
2004 Log.e(LOGTAG, "Unable to set new wallpaper");
2005 // Act as though the user canceled the operation so we try to
2006 // restore the old wallpaper.
2011 // Restore the old wallpaper if the user cancelled whilst we were setting
2012 // the new wallpaper.
2013 int width = oldWallpaper.getIntrinsicWidth();
2014 int height = oldWallpaper.getIntrinsicHeight();
2015 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2016 Canvas canvas = new Canvas(bm);
2017 oldWallpaper.setBounds(0, 0, width, height);
2018 oldWallpaper.draw(canvas);
2021 } catch (IOException e) {
2022 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2027 if (mWallpaperProgress.isShowing()) {
2028 mWallpaperProgress.dismiss();
2033 private void copy(CharSequence text) {
2035 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2037 clip.setClipboardText(text);
2039 } catch (android.os.RemoteException e) {
2040 Log.e(LOGTAG, "Copy failed", e);
2045 * Resets the browser title-view to whatever it must be
2046 * (for example, if we had a loading error)
2047 * When we have a new page, we call resetTitle, when we
2048 * have to reset the titlebar to whatever it used to be
2049 * (for example, if the user chose to stop loading), we
2050 * call resetTitleAndRevertLockIcon.
2052 /* package */ void resetTitleAndRevertLockIcon() {
2053 mTabControl.getCurrentTab().revertLockIcon();
2054 updateLockIconToLatest();
2055 resetTitleIconAndProgress();
2059 * Reset the title, favicon, and progress.
2061 private void resetTitleIconAndProgress() {
2062 WebView current = mTabControl.getCurrentWebView();
2063 if (current == null) {
2066 resetTitleAndIcon(current);
2067 int progress = current.getProgress();
2068 current.getWebChromeClient().onProgressChanged(current, progress);
2071 // Reset the title and the icon based on the given item.
2072 private void resetTitleAndIcon(WebView view) {
2073 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2075 setUrlTitle(item.getUrl(), item.getTitle());
2076 setFavicon(item.getFavicon());
2078 setUrlTitle(null, null);
2084 * Sets a title composed of the URL and the title string.
2085 * @param url The URL of the site being loaded.
2086 * @param title The title of the site being loaded.
2088 void setUrlTitle(String url, String title) {
2092 // If we are in voice search mode, the title has already been set.
2093 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2094 mTitleBar.setDisplayTitle(url);
2095 mFakeTitleBar.setDisplayTitle(url);
2099 * @param url The URL to build a title version of the URL from.
2100 * @return The title version of the URL or null if fails.
2101 * The title version of the URL can be either the URL hostname,
2102 * or the hostname with an "https://" prefix (for secure URLs),
2103 * or an empty string if, for example, the URL in question is a
2104 * file:// URL with no hostname.
2106 /* package */ static String buildTitleUrl(String url) {
2107 String titleUrl = null;
2111 // parse the url string
2112 URL urlObj = new URL(url);
2113 if (urlObj != null) {
2116 String protocol = urlObj.getProtocol();
2117 String host = urlObj.getHost();
2119 if (host != null && 0 < host.length()) {
2121 if (protocol != null) {
2122 // if a secure site, add an "https://" prefix!
2123 if (protocol.equalsIgnoreCase("https")) {
2124 titleUrl = protocol + "://" + host;
2129 } catch (MalformedURLException e) {}
2135 // Set the favicon in the title bar.
2136 void setFavicon(Bitmap icon) {
2137 mTitleBar.setFavicon(icon);
2138 mFakeTitleBar.setFavicon(icon);
2142 * Close the tab, remove its associated title bar, and adjust mTabControl's
2143 * current tab to a valid value.
2145 /* package */ void closeTab(Tab t) {
2146 int currentIndex = mTabControl.getCurrentIndex();
2147 int removeIndex = mTabControl.getTabIndex(t);
2148 mTabControl.removeTab(t);
2149 if (currentIndex >= removeIndex && currentIndex != 0) {
2152 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2153 resetTitleIconAndProgress();
2156 /* package */ void goBackOnePageOrQuit() {
2157 Tab current = mTabControl.getCurrentTab();
2158 if (current == null) {
2160 * Instead of finishing the activity, simply push this to the back
2161 * of the stack and let ActivityManager to choose the foreground
2162 * activity. As BrowserActivity is singleTask, it will be always the
2163 * root of the task. So we can use either true or false for
2166 moveTaskToBack(true);
2169 WebView w = current.getWebView();
2170 if (w.canGoBack()) {
2173 // Check to see if we are closing a window that was created by
2174 // another window. If so, we switch back to that window.
2175 Tab parent = current.getParentTab();
2176 if (parent != null) {
2177 switchToTab(mTabControl.getTabIndex(parent));
2178 // Now we close the other tab
2181 if (current.closeOnExit()) {
2182 // force the tab's inLoad() to be false as we are going to
2183 // either finish the activity or remove the tab. This will
2184 // ensure pauseWebViewTimers() taking action.
2185 mTabControl.getCurrentTab().clearInLoad();
2186 if (mTabControl.getTabCount() == 1) {
2190 // call pauseWebViewTimers() now, we won't be able to call
2191 // it in onPause() as the WebView won't be valid.
2192 // Temporarily change mActivityInPause to be true as
2193 // pauseWebViewTimers() will do nothing if mActivityInPause
2195 boolean savedState = mActivityInPause;
2197 Log.e(LOGTAG, "BrowserActivity is already paused "
2198 + "while handing goBackOnePageOrQuit.");
2200 mActivityInPause = true;
2201 pauseWebViewTimers();
2202 mActivityInPause = savedState;
2203 removeTabFromContentView(current);
2204 mTabControl.removeTab(current);
2207 * Instead of finishing the activity, simply push this to the back
2208 * of the stack and let ActivityManager to choose the foreground
2209 * activity. As BrowserActivity is singleTask, it will be always the
2210 * root of the task. So we can use either true or false for
2213 moveTaskToBack(true);
2218 boolean isMenuDown() {
2223 public boolean onKeyDown(int keyCode, KeyEvent event) {
2224 // Even if MENU is already held down, we need to call to super to open
2225 // the IME on long press.
2226 if (KeyEvent.KEYCODE_MENU == keyCode) {
2228 return super.onKeyDown(keyCode, event);
2230 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2231 // still down, we don't want to trigger the search. Pretend to consume
2232 // the key and do nothing.
2233 if (mMenuIsDown) return true;
2236 case KeyEvent.KEYCODE_SPACE:
2237 // WebView/WebTextView handle the keys in the KeyDown. As
2238 // the Activity's shortcut keys are only handled when WebView
2239 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2240 if (event.isShiftPressed()) {
2241 getTopWindow().pageUp(false);
2243 getTopWindow().pageDown(false);
2246 case KeyEvent.KEYCODE_BACK:
2247 if (event.getRepeatCount() == 0) {
2248 event.startTracking();
2250 } else if (mCustomView == null && mActiveTabsPage == null
2251 && event.isLongPress()) {
2252 bookmarksOrHistoryPicker(true);
2257 return super.onKeyDown(keyCode, event);
2261 public boolean onKeyUp(int keyCode, KeyEvent event) {
2263 case KeyEvent.KEYCODE_MENU:
2264 mMenuIsDown = false;
2266 case KeyEvent.KEYCODE_BACK:
2267 if (event.isTracking() && !event.isCanceled()) {
2268 if (mCustomView != null) {
2269 // if a custom view is showing, hide it
2270 mTabControl.getCurrentWebView().getWebChromeClient()
2271 .onHideCustomView();
2272 } else if (mActiveTabsPage != null) {
2273 // if tab page is showing, hide it
2274 removeActiveTabPage(true);
2276 WebView subwindow = mTabControl.getCurrentSubWindow();
2277 if (subwindow != null) {
2278 if (subwindow.canGoBack()) {
2281 dismissSubWindow(mTabControl.getCurrentTab());
2284 goBackOnePageOrQuit();
2291 return super.onKeyUp(keyCode, event);
2294 /* package */ void stopLoading() {
2295 mDidStopLoad = true;
2296 resetTitleAndRevertLockIcon();
2297 WebView w = getTopWindow();
2299 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2300 // same logic here. But for subwindow case, should we call into the main
2301 // WebView's onPageFinished as we never call its onPageStarted and if
2302 // the page finishes itself, we don't call onPageFinished.
2303 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2308 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2312 boolean didUserStopLoading() {
2313 return mDidStopLoad;
2316 private void cancelStopToast() {
2317 if (mStopToast != null) {
2318 mStopToast.cancel();
2323 // called by a UI or non-UI thread to post the message
2324 public void postMessage(int what, int arg1, int arg2, Object obj,
2326 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2330 // called by a UI or non-UI thread to remove the message
2331 void removeMessages(int what, Object object) {
2332 mHandler.removeMessages(what, object);
2335 // public message ids
2336 public final static int LOAD_URL = 1001;
2337 public final static int STOP_LOAD = 1002;
2340 private static final int FOCUS_NODE_HREF = 102;
2341 private static final int CANCEL_CREDS_REQUEST = 103;
2342 private static final int RELEASE_WAKELOCK = 107;
2344 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2346 // Private handler for handling javascript and saving passwords
2347 private Handler mHandler = new Handler() {
2349 public void handleMessage(Message msg) {
2351 case FOCUS_NODE_HREF:
2353 String url = (String) msg.getData().get("url");
2354 String title = (String) msg.getData().get("title");
2355 if (url == null || url.length() == 0) {
2358 HashMap focusNodeMap = (HashMap) msg.obj;
2359 WebView view = (WebView) focusNodeMap.get("webview");
2360 // Only apply the action if the top window did not change.
2361 if (getTopWindow() != view) {
2365 case R.id.open_context_menu_id:
2366 case R.id.view_image_context_menu_id:
2367 loadUrlFromContext(getTopWindow(), url);
2369 case R.id.open_newtab_context_menu_id:
2370 final Tab parent = mTabControl.getCurrentTab();
2371 final Tab newTab = openTab(url);
2372 if (newTab != parent) {
2373 parent.addChildTab(newTab);
2376 case R.id.bookmark_context_menu_id:
2377 Intent intent = new Intent(BrowserActivity.this,
2378 AddBookmarkPage.class);
2379 intent.putExtra("url", url);
2380 intent.putExtra("title", title);
2381 startActivity(intent);
2383 case R.id.share_link_context_menu_id:
2384 // See if this site has been visited before
2385 StringBuilder sb = new StringBuilder(
2386 Browser.BookmarkColumns.URL + " = ");
2387 DatabaseUtils.appendEscapedSQLString(sb, url);
2388 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2389 Browser.HISTORY_PROJECTION,
2393 if (c.moveToFirst()) {
2394 // The site has been visited before, so grab the
2395 // info from the database.
2396 Bitmap favicon = null;
2397 Bitmap thumbnail = null;
2398 String linkTitle = c.getString(Browser.
2399 HISTORY_PROJECTION_TITLE_INDEX);
2400 byte[] data = c.getBlob(Browser.
2401 HISTORY_PROJECTION_FAVICON_INDEX);
2403 favicon = BitmapFactory.decodeByteArray(
2404 data, 0, data.length);
2406 data = c.getBlob(Browser.
2407 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2409 thumbnail = BitmapFactory.decodeByteArray(
2410 data, 0, data.length);
2412 sharePage(BrowserActivity.this,
2413 linkTitle, url, favicon, thumbnail);
2415 Browser.sendString(BrowserActivity.this, url,
2417 R.string.choosertitle_sharevia));
2420 case R.id.copy_link_context_menu_id:
2423 case R.id.save_link_context_menu_id:
2424 case R.id.download_context_menu_id:
2425 onDownloadStartNoStream(url, null, null, null, -1);
2432 loadUrlFromContext(getTopWindow(), (String) msg.obj);
2439 case CANCEL_CREDS_REQUEST:
2440 resumeAfterCredentials();
2443 case RELEASE_WAKELOCK:
2444 if (mWakeLock.isHeld()) {
2445 mWakeLock.release();
2446 // if we reach here, Browser should be still in the
2447 // background loading after WAKELOCK_TIMEOUT (5-min).
2448 // To avoid burning the battery, stop loading.
2449 mTabControl.stopAllLoading();
2453 case UPDATE_BOOKMARK_THUMBNAIL:
2454 WebView view = (WebView) msg.obj;
2456 updateScreenshot(view);
2464 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2465 * an {@link Intent} to launch the Activity chooser.
2466 * @param c Context used to launch a new Activity.
2467 * @param title Title of the page. Stored in the Intent with
2468 * {@link Intent#EXTRA_SUBJECT}
2469 * @param url URL of the page. Stored in the Intent with
2470 * {@link Intent#EXTRA_TEXT}
2471 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2472 * with {@link Browser#EXTRA_SHARE_FAVICON}
2473 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2474 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2476 public static final void sharePage(Context c, String title, String url,
2477 Bitmap favicon, Bitmap screenshot) {
2478 Intent send = new Intent(Intent.ACTION_SEND);
2479 send.setType("text/plain");
2480 send.putExtra(Intent.EXTRA_TEXT, url);
2481 send.putExtra(Intent.EXTRA_SUBJECT, title);
2482 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2483 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2485 c.startActivity(Intent.createChooser(send, c.getString(
2486 R.string.choosertitle_sharevia)));
2487 } catch(android.content.ActivityNotFoundException ex) {
2488 // if no app handles it, do nothing
2492 private void updateScreenshot(WebView view) {
2493 // If this is a bookmarked site, add a screenshot to the database.
2494 // FIXME: When should we update? Every time?
2495 // FIXME: Would like to make sure there is actually something to
2496 // draw, but the API for that (WebViewCore.pictureReady()) is not
2497 // currently accessible here.
2499 ContentResolver cr = getContentResolver();
2500 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2501 cr, view.getOriginalUrl(), view.getUrl(), true);
2503 boolean succeed = c.moveToFirst();
2504 ContentValues values = null;
2506 if (values == null) {
2507 final ByteArrayOutputStream os
2508 = new ByteArrayOutputStream();
2509 Bitmap bm = createScreenshot(view);
2514 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2515 values = new ContentValues();
2516 values.put(Browser.BookmarkColumns.THUMBNAIL,
2519 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2520 c.getInt(0)), values, null, null);
2521 succeed = c.moveToNext();
2528 * Values for the size of the thumbnail created when taking a screenshot.
2529 * Lazily initialized. Instead of using these directly, use
2530 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2532 private static int THUMBNAIL_WIDTH = 0;
2533 private static int THUMBNAIL_HEIGHT = 0;
2536 * Return the desired width for thumbnail screenshots, which are stored in
2537 * the database, and used on the bookmarks screen.
2538 * @param context Context for finding out the density of the screen.
2539 * @return int desired width for thumbnail screenshot.
2541 /* package */ static int getDesiredThumbnailWidth(Context context) {
2542 if (THUMBNAIL_WIDTH == 0) {
2543 float density = context.getResources().getDisplayMetrics().density;
2544 THUMBNAIL_WIDTH = (int) (90 * density);
2545 THUMBNAIL_HEIGHT = (int) (80 * density);
2547 return THUMBNAIL_WIDTH;
2551 * Return the desired height for thumbnail screenshots, which are stored in
2552 * the database, and used on the bookmarks screen.
2553 * @param context Context for finding out the density of the screen.
2554 * @return int desired height for thumbnail screenshot.
2556 /* package */ static int getDesiredThumbnailHeight(Context context) {
2557 // To ensure that they are both initialized.
2558 getDesiredThumbnailWidth(context);
2559 return THUMBNAIL_HEIGHT;
2562 private Bitmap createScreenshot(WebView view) {
2563 Picture thumbnail = view.capturePicture();
2564 if (thumbnail == null) {
2567 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2568 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2569 Canvas canvas = new Canvas(bm);
2570 // May need to tweak these values to determine what is the
2571 // best scale factor
2572 int thumbnailWidth = thumbnail.getWidth();
2573 int thumbnailHeight = thumbnail.getHeight();
2574 float scaleFactorX = 1.0f;
2575 float scaleFactorY = 1.0f;
2576 if (thumbnailWidth > 0) {
2577 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2578 (float)thumbnailWidth;
2583 if (view.getWidth() > view.getHeight() &&
2584 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2585 // If the device is in landscape and the page is shorter
2586 // than the height of the view, stretch the thumbnail to fill the
2588 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2589 (float)thumbnailHeight;
2591 // In the portrait case, this looks nice.
2592 scaleFactorY = scaleFactorX;
2595 canvas.scale(scaleFactorX, scaleFactorY);
2597 thumbnail.draw(canvas);
2601 // -------------------------------------------------------------------------
2602 // Helper function for WebViewClient.
2603 //-------------------------------------------------------------------------
2605 // Use in overrideUrlLoading
2606 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2607 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2608 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2609 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2611 // Keep this initial progress in sync with initialProgressValue (* 100)
2612 // in ProgressTracker.cpp
2613 private final static int INITIAL_PROGRESS = 10;
2615 void onPageStarted(WebView view, String url, Bitmap favicon) {
2616 // when BrowserActivity just starts, onPageStarted may be called before
2617 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2618 // to start the timer. As we won't switch tabs while an activity is in
2619 // pause state, we can ensure calling resume and pause in pair.
2620 if (mActivityInPause) resumeWebViewTimers();
2623 setUrlTitle(url, null);
2624 setFavicon(favicon);
2625 // Show some progress so that the user knows the page is beginning to
2627 onProgressChanged(view, INITIAL_PROGRESS);
2628 mDidStopLoad = false;
2629 if (!mIsNetworkUp) createAndShowNetworkDialog();
2631 if (mSettings.isTracing()) {
2634 WebAddress uri = new WebAddress(url);
2636 } catch (android.net.ParseException ex) {
2639 host = host.replace('.', '_');
2642 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2645 // Performance probe
2647 mStart = SystemClock.uptimeMillis();
2648 mProcessStart = Process.getElapsedCpuTime();
2649 long[] sysCpu = new long[7];
2650 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2652 mUserStart = sysCpu[0] + sysCpu[1];
2653 mSystemStart = sysCpu[2];
2654 mIdleStart = sysCpu[3];
2655 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2657 mUiStart = SystemClock.currentThreadTimeMillis();
2661 void onPageFinished(WebView view, String url) {
2662 // Reset the title and icon in case we stopped a provisional load.
2663 resetTitleAndIcon(view);
2664 // Update the lock icon image only once we are done loading
2665 updateLockIconToLatest();
2666 // pause the WebView timer and release the wake lock if it is finished
2667 // while BrowserActivity is in pause state.
2668 if (mActivityInPause && pauseWebViewTimers()) {
2669 if (mWakeLock.isHeld()) {
2670 mHandler.removeMessages(RELEASE_WAKELOCK);
2671 mWakeLock.release();
2675 // Performance probe
2677 long[] sysCpu = new long[7];
2678 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2680 String uiInfo = "UI thread used "
2681 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2684 Log.d(LOGTAG, uiInfo);
2686 //The string that gets written to the log
2687 String performanceString = "It took total "
2688 + (SystemClock.uptimeMillis() - mStart)
2689 + " ms clock time to load the page."
2690 + "\nbrowser process used "
2691 + (Process.getElapsedCpuTime() - mProcessStart)
2692 + " ms, user processes used "
2693 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2694 + " ms, kernel used "
2695 + (sysCpu[2] - mSystemStart) * 10
2696 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2697 + " ms and irq took "
2698 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2699 * 10 + " ms, " + uiInfo;
2701 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2704 // strip the url to maintain consistency
2705 String newUrl = new String(url);
2706 if (newUrl.startsWith("http://www.")) {
2707 newUrl = newUrl.substring(11);
2708 } else if (newUrl.startsWith("http://")) {
2709 newUrl = newUrl.substring(7);
2710 } else if (newUrl.startsWith("https://www.")) {
2711 newUrl = newUrl.substring(12);
2712 } else if (newUrl.startsWith("https://")) {
2713 newUrl = newUrl.substring(8);
2716 Log.d(LOGTAG, newUrl + " loaded");
2724 Debug.stopMethodTracing();
2728 boolean shouldOverrideUrlLoading(WebView view, String url) {
2729 if (url.startsWith(SCHEME_WTAI)) {
2730 // wtai://wp/mc;number
2731 // number=string(phone-number)
2732 if (url.startsWith(SCHEME_WTAI_MC)) {
2733 Intent intent = new Intent(Intent.ACTION_VIEW,
2734 Uri.parse(WebView.SCHEME_TEL +
2735 url.substring(SCHEME_WTAI_MC.length())));
2736 startActivity(intent);
2739 // wtai://wp/sd;dtmf
2740 // dtmf=string(dialstring)
2741 if (url.startsWith(SCHEME_WTAI_SD)) {
2742 // TODO: only send when there is active voice connection
2745 // wtai://wp/ap;number;name
2746 // number=string(phone-number)
2748 if (url.startsWith(SCHEME_WTAI_AP)) {
2754 // The "about:" schemes are internal to the browser; don't want these to
2755 // be dispatched to other apps.
2756 if (url.startsWith("about:")) {
2761 // perform generic parsing of the URI to turn it into an Intent.
2763 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2764 } catch (URISyntaxException ex) {
2765 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2769 // check whether the intent can be resolved. If not, we will see
2770 // whether we can download it from the Market.
2771 if (getPackageManager().resolveActivity(intent, 0) == null) {
2772 String packagename = intent.getPackage();
2773 if (packagename != null) {
2774 intent = new Intent(Intent.ACTION_VIEW, Uri
2775 .parse("market://search?q=pname:" + packagename));
2776 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2777 startActivity(intent);
2784 // sanitize the Intent, ensuring web pages can not bypass browser
2785 // security (only access to BROWSABLE activities).
2786 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2787 intent.setComponent(null);
2789 if (startActivityIfNeeded(intent, -1)) {
2792 } catch (ActivityNotFoundException ex) {
2793 // ignore the error. If no application can handle the URL,
2794 // eg about:blank, assume the browser can handle it.
2805 // -------------------------------------------------------------------------
2806 // Helper function for WebChromeClient
2807 // -------------------------------------------------------------------------
2809 void onProgressChanged(WebView view, int newProgress) {
2810 mTitleBar.setProgress(newProgress);
2811 mFakeTitleBar.setProgress(newProgress);
2813 if (newProgress == 100) {
2814 // onProgressChanged() may continue to be called after the main
2815 // frame has finished loading, as any remaining sub frames continue
2816 // to load. We'll only get called once though with newProgress as
2817 // 100 when everything is loaded. (onPageFinished is called once
2818 // when the main frame completes loading regardless of the state of
2819 // any sub frames so calls to onProgressChanges may continue after
2820 // onPageFinished has executed)
2823 updateInLoadMenuItems();
2824 // If the options menu is open, leave the title bar
2825 if (!mOptionsMenuOpen || !mIconView) {
2829 } else if (!mInLoad) {
2830 // onPageFinished may have already been called but a subframe is
2831 // still loading and updating the progress. Reset mInLoad and update
2834 updateInLoadMenuItems();
2835 if (!mOptionsMenuOpen || mIconView) {
2836 // This page has begun to load, so show the title bar
2842 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2843 // if a view already exists then immediately terminate the new one
2844 if (mCustomView != null) {
2845 callback.onCustomViewHidden();
2849 // Add the custom view to its container.
2850 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2852 mCustomViewCallback = callback;
2853 // Save the menu state and set it to empty while the custom
2855 mOldMenuState = mMenuState;
2856 mMenuState = EMPTY_MENU;
2857 // Hide the content view.
2858 mContentView.setVisibility(View.GONE);
2859 // Finally show the custom view container.
2860 setStatusBarVisibility(false);
2861 mCustomViewContainer.setVisibility(View.VISIBLE);
2862 mCustomViewContainer.bringToFront();
2865 void onHideCustomView() {
2866 if (mCustomView == null)
2869 // Hide the custom view.
2870 mCustomView.setVisibility(View.GONE);
2871 // Remove the custom view from its container.
2872 mCustomViewContainer.removeView(mCustomView);
2874 // Reset the old menu state.
2875 mMenuState = mOldMenuState;
2876 mOldMenuState = EMPTY_MENU;
2877 mCustomViewContainer.setVisibility(View.GONE);
2878 mCustomViewCallback.onCustomViewHidden();
2879 // Show the content view.
2880 setStatusBarVisibility(true);
2881 mContentView.setVisibility(View.VISIBLE);
2884 Bitmap getDefaultVideoPoster() {
2885 if (mDefaultVideoPoster == null) {
2886 mDefaultVideoPoster = BitmapFactory.decodeResource(
2887 getResources(), R.drawable.default_video_poster);
2889 return mDefaultVideoPoster;
2892 View getVideoLoadingProgressView() {
2893 if (mVideoProgressView == null) {
2894 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2895 mVideoProgressView = inflater.inflate(
2896 R.layout.video_loading_progress, null);
2898 return mVideoProgressView;
2902 * The Object used to inform the WebView of the file to upload.
2904 private ValueCallback<Uri> mUploadMessage;
2906 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2907 if (mUploadMessage != null) return;
2908 mUploadMessage = uploadMsg;
2909 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2910 i.addCategory(Intent.CATEGORY_OPENABLE);
2912 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2913 getString(R.string.choose_upload)), FILE_SELECTED);
2916 // -------------------------------------------------------------------------
2917 // Implement functions for DownloadListener
2918 // -------------------------------------------------------------------------
2921 * Notify the host application a download should be done, or that
2922 * the data should be streamed if a streaming viewer is available.
2923 * @param url The full url to the content that should be downloaded
2924 * @param contentDisposition Content-disposition http header, if
2926 * @param mimetype The mimetype of the content reported by the server
2927 * @param contentLength The file size reported by the server
2929 public void onDownloadStart(String url, String userAgent,
2930 String contentDisposition, String mimetype, long contentLength) {
2931 // if we're dealing wih A/V content that's not explicitly marked
2932 // for download, check if it's streamable.
2933 if (contentDisposition == null
2934 || !contentDisposition.regionMatches(
2935 true, 0, "attachment", 0, 10)) {
2936 // query the package manager to see if there's a registered handler
2938 Intent intent = new Intent(Intent.ACTION_VIEW);
2939 intent.setDataAndType(Uri.parse(url), mimetype);
2940 ResolveInfo info = getPackageManager().resolveActivity(intent,
2941 PackageManager.MATCH_DEFAULT_ONLY);
2943 ComponentName myName = getComponentName();
2944 // If we resolved to ourselves, we don't want to attempt to
2945 // load the url only to try and download it again.
2946 if (!myName.getPackageName().equals(
2947 info.activityInfo.packageName)
2948 || !myName.getClassName().equals(
2949 info.activityInfo.name)) {
2950 // someone (other than us) knows how to handle this mime
2951 // type with this scheme, don't download.
2953 startActivity(intent);
2955 } catch (ActivityNotFoundException ex) {
2957 Log.d(LOGTAG, "activity not found for " + mimetype
2958 + " over " + Uri.parse(url).getScheme(),
2961 // Best behavior is to fall back to a download in this
2967 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2971 * Notify the host application a download should be done, even if there
2972 * is a streaming viewer available for thise type.
2973 * @param url The full url to the content that should be downloaded
2974 * @param contentDisposition Content-disposition http header, if
2976 * @param mimetype The mimetype of the content reported by the server
2977 * @param contentLength The file size reported by the server
2979 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2980 String contentDisposition, String mimetype, long contentLength) {
2982 String filename = URLUtil.guessFileName(url,
2983 contentDisposition, mimetype);
2985 // Check to see if we have an SDCard
2986 String status = Environment.getExternalStorageState();
2987 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2991 // Check to see if the SDCard is busy, same as the music app
2992 if (status.equals(Environment.MEDIA_SHARED)) {
2993 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2994 title = R.string.download_sdcard_busy_dlg_title;
2996 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2997 title = R.string.download_no_sdcard_dlg_title;
3000 new AlertDialog.Builder(this)
3002 .setIcon(android.R.drawable.ic_dialog_alert)
3004 .setPositiveButton(R.string.ok, null)
3009 // java.net.URI is a lot stricter than KURL so we have to undo
3010 // KURL's percent-encoding and redo the encoding using java.net.URI.
3013 // Undo the percent-encoding that KURL may have done.
3014 String newUrl = new String(URLUtil.decode(url.getBytes()));
3015 // Parse the url into pieces
3016 WebAddress w = new WebAddress(newUrl);
3018 String query = null;
3019 String path = w.mPath;
3020 // Break the path into path, query, and fragment
3021 if (path.length() > 0) {
3022 // Strip the fragment
3023 int idx = path.lastIndexOf('#');
3025 frag = path.substring(idx + 1);
3026 path = path.substring(0, idx);
3028 idx = path.lastIndexOf('?');
3030 query = path.substring(idx + 1);
3031 path = path.substring(0, idx);
3034 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3036 } catch (Exception e) {
3037 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3041 // XXX: Have to use the old url since the cookies were stored using the
3042 // old percent-encoded url.
3043 String cookies = CookieManager.getInstance().getCookie(url);
3045 ContentValues values = new ContentValues();
3046 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3047 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3048 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3049 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
3051 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
3052 BrowserDownloadPage.class.getCanonicalName());
3053 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3054 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3055 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3056 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3057 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
3058 if (contentLength > 0) {
3059 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
3061 if (mimetype == null) {
3062 // We must have long pressed on a link or image to download it. We
3063 // are not sure of the mimetype in this case, so do a head request
3064 new FetchUrlMimeType(this).execute(values);
3066 final Uri contentUri =
3067 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
3072 // -------------------------------------------------------------------------
3075 * Resets the lock icon. This method is called when we start a new load and
3076 * know the url to be loaded.
3078 private void resetLockIcon(String url) {
3079 // Save the lock-icon state (we revert to it if the load gets cancelled)
3080 mTabControl.getCurrentTab().resetLockIcon(url);
3081 updateLockIconImage(LOCK_ICON_UNSECURE);
3085 * Update the lock icon to correspond to our latest state.
3087 private void updateLockIconToLatest() {
3088 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
3092 * Updates the lock-icon image in the title-bar.
3094 private void updateLockIconImage(int lockIconType) {
3096 if (lockIconType == LOCK_ICON_SECURE) {
3098 } else if (lockIconType == LOCK_ICON_MIXED) {
3101 mTitleBar.setLock(d);
3102 mFakeTitleBar.setLock(d);
3106 * Displays a page-info dialog.
3107 * @param tab The tab to show info about
3108 * @param fromShowSSLCertificateOnError The flag that indicates whether
3109 * this dialog was opened from the SSL-certificate-on-error dialog or
3110 * not. This is important, since we need to know whether to return to
3111 * the parent dialog or simply dismiss.
3113 private void showPageInfo(final Tab tab,
3114 final boolean fromShowSSLCertificateOnError) {
3115 final LayoutInflater factory = LayoutInflater
3118 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3120 final WebView view = tab.getWebView();
3123 String title = null;
3127 title = tab.getTitle();
3128 } else if (view == mTabControl.getCurrentWebView()) {
3129 // Use the cached title and url if this is the current WebView
3133 url = view.getUrl();
3134 title = view.getTitle();
3140 if (title == null) {
3144 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3145 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3147 mPageInfoView = tab;
3148 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3150 AlertDialog.Builder alertDialogBuilder =
3151 new AlertDialog.Builder(this)
3152 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3153 .setView(pageInfoView)
3156 new DialogInterface.OnClickListener() {
3157 public void onClick(DialogInterface dialog,
3159 mPageInfoDialog = null;
3160 mPageInfoView = null;
3162 // if we came here from the SSL error dialog
3163 if (fromShowSSLCertificateOnError) {
3164 // go back to the SSL error dialog
3165 showSSLCertificateOnError(
3166 mSSLCertificateOnErrorView,
3167 mSSLCertificateOnErrorHandler,
3168 mSSLCertificateOnErrorError);
3172 .setOnCancelListener(
3173 new DialogInterface.OnCancelListener() {
3174 public void onCancel(DialogInterface dialog) {
3175 mPageInfoDialog = null;
3176 mPageInfoView = null;
3178 // if we came here from the SSL error dialog
3179 if (fromShowSSLCertificateOnError) {
3180 // go back to the SSL error dialog
3181 showSSLCertificateOnError(
3182 mSSLCertificateOnErrorView,
3183 mSSLCertificateOnErrorHandler,
3184 mSSLCertificateOnErrorError);
3189 // if we have a main top-level page SSL certificate set or a certificate
3191 if (fromShowSSLCertificateOnError ||
3192 (view != null && view.getCertificate() != null)) {
3193 // add a 'View Certificate' button
3194 alertDialogBuilder.setNeutralButton(
3195 R.string.view_certificate,
3196 new DialogInterface.OnClickListener() {
3197 public void onClick(DialogInterface dialog,
3199 mPageInfoDialog = null;
3200 mPageInfoView = null;
3202 // if we came here from the SSL error dialog
3203 if (fromShowSSLCertificateOnError) {
3204 // go back to the SSL error dialog
3205 showSSLCertificateOnError(
3206 mSSLCertificateOnErrorView,
3207 mSSLCertificateOnErrorHandler,
3208 mSSLCertificateOnErrorError);
3210 // otherwise, display the top-most certificate from
3212 if (view.getCertificate() != null) {
3213 showSSLCertificate(tab);
3220 mPageInfoDialog = alertDialogBuilder.show();
3224 * Displays the main top-level page SSL certificate dialog
3225 * (accessible from the Page-Info dialog).
3226 * @param tab The tab to show certificate for.
3228 private void showSSLCertificate(final Tab tab) {
3229 final View certificateView =
3230 inflateCertificateView(tab.getWebView().getCertificate());
3231 if (certificateView == null) {
3235 LayoutInflater factory = LayoutInflater.from(this);
3237 final LinearLayout placeholder =
3238 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3240 LinearLayout ll = (LinearLayout) factory.inflate(
3241 R.layout.ssl_success, placeholder);
3242 ((TextView)ll.findViewById(R.id.success))
3243 .setText(R.string.ssl_certificate_is_valid);
3245 mSSLCertificateView = tab;
3246 mSSLCertificateDialog =
3247 new AlertDialog.Builder(this)
3248 .setTitle(R.string.ssl_certificate).setIcon(
3249 R.drawable.ic_dialog_browser_certificate_secure)
3250 .setView(certificateView)
3251 .setPositiveButton(R.string.ok,
3252 new DialogInterface.OnClickListener() {
3253 public void onClick(DialogInterface dialog,
3255 mSSLCertificateDialog = null;
3256 mSSLCertificateView = null;
3258 showPageInfo(tab, false);
3261 .setOnCancelListener(
3262 new DialogInterface.OnCancelListener() {
3263 public void onCancel(DialogInterface dialog) {
3264 mSSLCertificateDialog = null;
3265 mSSLCertificateView = null;
3267 showPageInfo(tab, false);
3274 * Displays the SSL error certificate dialog.
3275 * @param view The target web-view.
3276 * @param handler The SSL error handler responsible for cancelling the
3277 * connection that resulted in an SSL error or proceeding per user request.
3278 * @param error The SSL error object.
3280 void showSSLCertificateOnError(
3281 final WebView view, final SslErrorHandler handler, final SslError error) {
3283 final View certificateView =
3284 inflateCertificateView(error.getCertificate());
3285 if (certificateView == null) {
3289 LayoutInflater factory = LayoutInflater.from(this);
3291 final LinearLayout placeholder =
3292 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3294 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3295 LinearLayout ll = (LinearLayout)factory
3296 .inflate(R.layout.ssl_warning, placeholder);
3297 ((TextView)ll.findViewById(R.id.warning))
3298 .setText(R.string.ssl_untrusted);
3301 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3302 LinearLayout ll = (LinearLayout)factory
3303 .inflate(R.layout.ssl_warning, placeholder);
3304 ((TextView)ll.findViewById(R.id.warning))
3305 .setText(R.string.ssl_mismatch);
3308 if (error.hasError(SslError.SSL_EXPIRED)) {
3309 LinearLayout ll = (LinearLayout)factory
3310 .inflate(R.layout.ssl_warning, placeholder);
3311 ((TextView)ll.findViewById(R.id.warning))
3312 .setText(R.string.ssl_expired);
3315 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3316 LinearLayout ll = (LinearLayout)factory
3317 .inflate(R.layout.ssl_warning, placeholder);
3318 ((TextView)ll.findViewById(R.id.warning))
3319 .setText(R.string.ssl_not_yet_valid);
3322 mSSLCertificateOnErrorHandler = handler;
3323 mSSLCertificateOnErrorView = view;
3324 mSSLCertificateOnErrorError = error;
3325 mSSLCertificateOnErrorDialog =
3326 new AlertDialog.Builder(this)
3327 .setTitle(R.string.ssl_certificate).setIcon(
3328 R.drawable.ic_dialog_browser_certificate_partially_secure)
3329 .setView(certificateView)
3330 .setPositiveButton(R.string.ok,
3331 new DialogInterface.OnClickListener() {
3332 public void onClick(DialogInterface dialog,
3334 mSSLCertificateOnErrorDialog = null;
3335 mSSLCertificateOnErrorView = null;
3336 mSSLCertificateOnErrorHandler = null;
3337 mSSLCertificateOnErrorError = null;
3339 view.getWebViewClient().onReceivedSslError(
3340 view, handler, error);
3343 .setNeutralButton(R.string.page_info_view,
3344 new DialogInterface.OnClickListener() {
3345 public void onClick(DialogInterface dialog,
3347 mSSLCertificateOnErrorDialog = null;
3349 // do not clear the dialog state: we will
3350 // need to show the dialog again once the
3351 // user is done exploring the page-info details
3353 showPageInfo(mTabControl.getTabFromView(view),
3357 .setOnCancelListener(
3358 new DialogInterface.OnCancelListener() {
3359 public void onCancel(DialogInterface dialog) {
3360 mSSLCertificateOnErrorDialog = null;
3361 mSSLCertificateOnErrorView = null;
3362 mSSLCertificateOnErrorHandler = null;
3363 mSSLCertificateOnErrorError = null;
3365 view.getWebViewClient().onReceivedSslError(
3366 view, handler, error);
3373 * Inflates the SSL certificate view (helper method).
3374 * @param certificate The SSL certificate.
3375 * @return The resultant certificate view with issued-to, issued-by,
3376 * issued-on, expires-on, and possibly other fields set.
3377 * If the input certificate is null, returns null.
3379 private View inflateCertificateView(SslCertificate certificate) {
3380 if (certificate == null) {
3384 LayoutInflater factory = LayoutInflater.from(this);
3386 View certificateView = factory.inflate(
3387 R.layout.ssl_certificate, null);
3390 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3391 if (issuedTo != null) {
3392 ((TextView) certificateView.findViewById(R.id.to_common))
3393 .setText(issuedTo.getCName());
3394 ((TextView) certificateView.findViewById(R.id.to_org))
3395 .setText(issuedTo.getOName());
3396 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3397 .setText(issuedTo.getUName());
3401 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3402 if (issuedBy != null) {
3403 ((TextView) certificateView.findViewById(R.id.by_common))
3404 .setText(issuedBy.getCName());
3405 ((TextView) certificateView.findViewById(R.id.by_org))
3406 .setText(issuedBy.getOName());
3407 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3408 .setText(issuedBy.getUName());
3412 String issuedOn = reformatCertificateDate(
3413 certificate.getValidNotBefore());
3414 ((TextView) certificateView.findViewById(R.id.issued_on))
3418 String expiresOn = reformatCertificateDate(
3419 certificate.getValidNotAfter());
3420 ((TextView) certificateView.findViewById(R.id.expires_on))
3421 .setText(expiresOn);
3423 return certificateView;
3427 * Re-formats the certificate date (Date.toString()) string to
3428 * a properly localized date string.
3429 * @return Properly localized version of the certificate date string and
3430 * the original certificate date string if fails to localize.
3431 * If the original string is null, returns an empty string "".
3433 private String reformatCertificateDate(String certificateDate) {
3434 String reformattedDate = null;
3436 if (certificateDate != null) {
3439 date = java.text.DateFormat.getInstance().parse(certificateDate);
3440 } catch (ParseException e) {
3446 DateFormat.getDateFormat(this).format(date);
3450 return reformattedDate != null ? reformattedDate :
3451 (certificateDate != null ? certificateDate : "");
3455 * Displays an http-authentication dialog.
3457 void showHttpAuthentication(final HttpAuthHandler handler,
3458 final String host, final String realm, final String title,
3459 final String name, final String password, int focusId) {
3460 LayoutInflater factory = LayoutInflater.from(this);
3461 final View v = factory
3462 .inflate(R.layout.http_authentication, null);
3464 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3466 if (password != null) {
3467 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3470 String titleText = title;
3471 if (titleText == null) {
3472 titleText = getText(R.string.sign_in_to).toString().replace(
3473 "%s1", host).replace("%s2", realm);
3476 mHttpAuthHandler = handler;
3477 AlertDialog dialog = new AlertDialog.Builder(this)
3478 .setTitle(titleText)
3479 .setIcon(android.R.drawable.ic_dialog_alert)
3481 .setPositiveButton(R.string.action,
3482 new DialogInterface.OnClickListener() {
3483 public void onClick(DialogInterface dialog,
3485 String nm = ((EditText) v
3486 .findViewById(R.id.username_edit))
3487 .getText().toString();
3488 String pw = ((EditText) v
3489 .findViewById(R.id.password_edit))
3490 .getText().toString();
3491 BrowserActivity.this.setHttpAuthUsernamePassword
3492 (host, realm, nm, pw);
3493 handler.proceed(nm, pw);
3494 mHttpAuthenticationDialog = null;
3495 mHttpAuthHandler = null;
3497 .setNegativeButton(R.string.cancel,
3498 new DialogInterface.OnClickListener() {
3499 public void onClick(DialogInterface dialog,
3502 BrowserActivity.this.resetTitleAndRevertLockIcon();
3503 mHttpAuthenticationDialog = null;
3504 mHttpAuthHandler = null;
3506 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3507 public void onCancel(DialogInterface dialog) {
3509 BrowserActivity.this.resetTitleAndRevertLockIcon();
3510 mHttpAuthenticationDialog = null;
3511 mHttpAuthHandler = null;
3514 // Make the IME appear when the dialog is displayed if applicable.
3515 dialog.getWindow().setSoftInputMode(
3516 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3519 dialog.findViewById(focusId).requestFocus();
3521 v.findViewById(R.id.username_edit).requestFocus();
3523 mHttpAuthenticationDialog = dialog;
3526 public int getProgress() {
3527 WebView w = mTabControl.getCurrentWebView();
3529 return w.getProgress();
3536 * Set HTTP authentication password.
3538 * @param host The host for the password
3539 * @param realm The realm for the password
3540 * @param username The username for the password. If it is null, it means
3541 * password can't be saved.
3542 * @param password The password
3544 public void setHttpAuthUsernamePassword(String host, String realm,
3547 WebView w = mTabControl.getCurrentWebView();
3549 w.setHttpAuthUsernamePassword(host, realm, username, password);
3554 * connectivity manager says net has come or gone... inform the user
3555 * @param up true if net has come up, false if net has gone down
3557 public void onNetworkToggle(boolean up) {
3558 if (up == mIsNetworkUp) {
3561 mIsNetworkUp = true;
3562 if (mAlertDialog != null) {
3563 mAlertDialog.cancel();
3564 mAlertDialog = null;
3567 mIsNetworkUp = false;
3569 createAndShowNetworkDialog();
3572 WebView w = mTabControl.getCurrentWebView();
3574 w.setNetworkAvailable(up);
3578 boolean isNetworkUp() {
3579 return mIsNetworkUp;
3582 // This method shows the network dialog alerting the user that the net is
3583 // down. It will only show the dialog if mAlertDialog is null.
3584 private void createAndShowNetworkDialog() {
3585 if (mAlertDialog == null) {
3586 mAlertDialog = new AlertDialog.Builder(this)
3587 .setTitle(R.string.loadSuspendedTitle)
3588 .setMessage(R.string.loadSuspended)
3589 .setPositiveButton(R.string.ok, null)
3595 protected void onActivityResult(int requestCode, int resultCode,
3597 if (getTopWindow() == null) return;
3599 switch (requestCode) {
3601 if (resultCode == RESULT_OK && intent != null) {
3602 String data = intent.getAction();
3603 Bundle extras = intent.getExtras();
3604 if (extras != null && extras.getBoolean("new_window", false)) {
3607 final Tab currentTab =
3608 mTabControl.getCurrentTab();
3609 dismissSubWindow(currentTab);
3610 if (data != null && data.length() != 0) {
3611 loadUrl(getTopWindow(), data);
3615 // Deliberately fall through to PREFERENCES_PAGE, since the
3616 // same extra may be attached to the COMBO_PAGE
3617 case PREFERENCES_PAGE:
3618 if (resultCode == RESULT_OK && intent != null) {
3619 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3620 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3621 mTabControl.removeParentChildRelationShips();
3625 // Choose a file from the file picker.
3627 if (null == mUploadMessage) break;
3628 Uri result = intent == null || resultCode != RESULT_OK ? null
3630 mUploadMessage.onReceiveValue(result);
3631 mUploadMessage = null;
3636 getTopWindow().requestFocus();
3640 * This method is called as a result of the user selecting the options
3641 * menu to see the download window. It shows the download window on top of
3642 * the current window.
3644 private void viewDownloads(Uri downloadRecord) {
3645 Intent intent = new Intent(this,
3646 BrowserDownloadPage.class);
3647 intent.setData(downloadRecord);
3648 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3654 * @param startWithHistory If true, open starting on the history tab.
3655 * Otherwise, start with the bookmarks tab.
3657 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3658 WebView current = mTabControl.getCurrentWebView();
3659 if (current == null) {
3662 Intent intent = new Intent(this,
3663 CombinedBookmarkHistoryActivity.class);
3664 String title = current.getTitle();
3665 String url = current.getUrl();
3666 Bitmap thumbnail = createScreenshot(current);
3668 // Just in case the user opens bookmarks before a page finishes loading
3669 // so the current history item, and therefore the page, is null.
3671 url = mLastEnteredUrl;
3674 url = mSettings.getHomePage();
3677 // In case the web page has not yet received its associated title.
3678 if (title == null) {
3681 intent.putExtra("title", title);
3682 intent.putExtra("url", url);
3683 intent.putExtra("thumbnail", thumbnail);
3684 // Disable opening in a new window if we have maxed out the windows
3685 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3686 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3687 if (startWithHistory) {
3688 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3689 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3691 startActivityForResult(intent, COMBO_PAGE);
3694 // Called when loading from context menu or LOAD_URL message
3695 private void loadUrlFromContext(WebView view, String url) {
3696 // In case the user enters nothing.
3697 if (url != null && url.length() != 0 && view != null) {
3698 url = smartUrlFilter(url);
3699 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3706 * Load the URL into the given WebView and update the title bar
3707 * to reflect the new load. Call this instead of WebView.loadUrl
3709 * @param view The WebView used to load url.
3710 * @param url The URL to load.
3712 private void loadUrl(WebView view, String url) {
3713 updateTitleBarForNewLoad(view, url);
3718 * Load UrlData into a Tab and update the title bar to reflect the new
3719 * load. Call this instead of UrlData.loadIn directly.
3720 * @param t The Tab used to load.
3721 * @param data The UrlData being loaded.
3723 private void loadUrlDataIn(Tab t, UrlData data) {
3724 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3729 * If the WebView is the top window, update the title bar to reflect
3730 * loading the new URL. i.e. set its text, clear the favicon (which
3731 * will be set once the page begins loading), and set the progress to
3732 * INITIAL_PROGRESS to show that the page has begun to load. Called
3733 * by loadUrl and loadUrlDataIn.
3734 * @param view The WebView that is starting a load.
3735 * @param url The URL that is being loaded.
3737 private void updateTitleBarForNewLoad(WebView view, String url) {
3738 if (view == getTopWindow()) {
3739 setUrlTitle(url, null);
3741 onProgressChanged(view, INITIAL_PROGRESS);
3745 private String smartUrlFilter(Uri inUri) {
3746 if (inUri != null) {
3747 return smartUrlFilter(inUri.toString());
3752 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3753 "(?i)" + // switch on case insensitive matching
3754 "(" + // begin group for schema
3755 "(?:http|https|file):\\/\\/" +
3756 "|(?:inline|data|about|content|javascript):" +
3761 * Attempts to determine whether user input is a URL or search
3762 * terms. Anything with a space is passed to search.
3764 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3765 * "Http://" converts to "http://"
3767 * @return Original or modified URL
3770 String smartUrlFilter(String url) {
3772 String inUrl = url.trim();
3773 boolean hasSpace = inUrl.indexOf(' ') != -1;
3775 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3776 if (matcher.matches()) {
3777 // force scheme to lowercase
3778 String scheme = matcher.group(1);
3779 String lcScheme = scheme.toLowerCase();
3780 if (!lcScheme.equals(scheme)) {
3781 inUrl = lcScheme + matcher.group(2);
3784 inUrl = inUrl.replace(" ", "%20");
3789 // FIXME: Is this the correct place to add to searches?
3790 // what if someone else calls this function?
3791 int shortcut = parseUrlShortcut(inUrl);
3792 if (shortcut != SHORTCUT_INVALID) {
3793 Browser.addSearchUrl(mResolver, inUrl);
3794 String query = inUrl.substring(2);
3796 case SHORTCUT_GOOGLE_SEARCH:
3797 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3798 case SHORTCUT_WIKIPEDIA_SEARCH:
3799 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3800 case SHORTCUT_DICTIONARY_SEARCH:
3801 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3802 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3803 // FIXME: we need location in this case
3804 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3808 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3809 return URLUtil.guessUrl(inUrl);
3813 Browser.addSearchUrl(mResolver, inUrl);
3814 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3817 /* package */ void setShouldShowErrorConsole(boolean flag) {
3818 if (flag == mShouldShowErrorConsole) {
3823 mShouldShowErrorConsole = flag;
3825 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3826 .getErrorConsole(true);
3829 // Setting the show state of the console will cause it's the layout to be inflated.
3830 if (errorConsole.numberOfErrors() > 0) {
3831 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3833 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3836 // Now we can add it to the main view.
3837 mErrorConsoleContainer.addView(errorConsole,
3838 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3839 ViewGroup.LayoutParams.WRAP_CONTENT));
3841 mErrorConsoleContainer.removeView(errorConsole);
3846 boolean shouldShowErrorConsole() {
3847 return mShouldShowErrorConsole;
3850 private void setStatusBarVisibility(boolean visible) {
3851 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3852 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3856 private void sendNetworkType(String type, String subtype) {
3857 WebView w = mTabControl.getCurrentWebView();
3859 w.setNetworkType(type, subtype);
3863 private void packageChanged(String packageName, boolean wasAdded) {
3864 WebView w = mTabControl.getCurrentWebView();
3870 w.addPackageName(packageName);
3872 w.removePackageName(packageName);
3876 private void addPackageNames(Set<String> packageNames) {
3877 WebView w = mTabControl.getCurrentWebView();
3882 w.addPackageNames(packageNames);
3885 private void getInstalledPackages() {
3886 AsyncTask<Void, Void, Set<String> > task =
3887 new AsyncTask<Void, Void, Set<String> >() {
3888 protected Set<String> doInBackground(Void... unused) {
3889 Set<String> installedPackages = new HashSet<String>();
3890 PackageManager pm = BrowserActivity.this.getPackageManager();
3892 List<PackageInfo> packages = pm.getInstalledPackages(0);
3893 for (PackageInfo p : packages) {
3894 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3895 installedPackages.add(p.packageName);
3900 return installedPackages;
3903 // Executes on the UI thread
3904 protected void onPostExecute(Set<String> installedPackages) {
3905 addPackageNames(installedPackages);
3911 final static int LOCK_ICON_UNSECURE = 0;
3912 final static int LOCK_ICON_SECURE = 1;
3913 final static int LOCK_ICON_MIXED = 2;
3915 private BrowserSettings mSettings;
3916 private TabControl mTabControl;
3917 private ContentResolver mResolver;
3918 private FrameLayout mContentView;
3919 private View mCustomView;
3920 private FrameLayout mCustomViewContainer;
3921 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3923 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3924 // view, we should rewrite this.
3925 private int mCurrentMenuState = 0;
3926 private int mMenuState = R.id.MAIN_MENU;
3927 private int mOldMenuState = EMPTY_MENU;
3928 private static final int EMPTY_MENU = -1;
3931 private FindDialog mFindDialog;
3932 // Used to prevent chording to result in firing two shortcuts immediately
3933 // one after another. Fixes bug 1211714.
3936 private boolean mInLoad;
3937 private boolean mIsNetworkUp;
3938 private boolean mDidStopLoad;
3940 private boolean mActivityInPause = true;
3942 private boolean mMenuIsDown;
3944 private static boolean mInTrace;
3946 // Performance probe
3947 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3948 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3949 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3950 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3951 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3952 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3953 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3954 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3955 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3958 private long mStart;
3959 private long mProcessStart;
3960 private long mUserStart;
3961 private long mSystemStart;
3962 private long mIdleStart;
3963 private long mIrqStart;
3965 private long mUiStart;
3967 private Drawable mMixLockIcon;
3968 private Drawable mSecLockIcon;
3970 /* hold a ref so we can auto-cancel if necessary */
3971 private AlertDialog mAlertDialog;
3973 // Wait for credentials before loading google.com
3974 private ProgressDialog mCredsDlg;
3976 // The up-to-date URL and title (these can be different from those stored
3977 // in WebView, since it takes some time for the information in WebView to
3979 private String mUrl;
3980 private String mTitle;
3982 // As PageInfo has different style for landscape / portrait, we have
3983 // to re-open it when configuration changed
3984 private AlertDialog mPageInfoDialog;
3985 private Tab mPageInfoView;
3986 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3987 // dialog, we should not just dismiss it, but should get back to the
3988 // SSL-certificate-on-error dialog. This flag is used to store this state
3989 private boolean mPageInfoFromShowSSLCertificateOnError;
3991 // as SSLCertificateOnError has different style for landscape / portrait,
3992 // we have to re-open it when configuration changed
3993 private AlertDialog mSSLCertificateOnErrorDialog;
3994 private WebView mSSLCertificateOnErrorView;
3995 private SslErrorHandler mSSLCertificateOnErrorHandler;
3996 private SslError mSSLCertificateOnErrorError;
3998 // as SSLCertificate has different style for landscape / portrait, we
3999 // have to re-open it when configuration changed
4000 private AlertDialog mSSLCertificateDialog;
4001 private Tab mSSLCertificateView;
4003 // as HttpAuthentication has different style for landscape / portrait, we
4004 // have to re-open it when configuration changed
4005 private AlertDialog mHttpAuthenticationDialog;
4006 private HttpAuthHandler mHttpAuthHandler;
4008 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4009 new FrameLayout.LayoutParams(
4010 ViewGroup.LayoutParams.MATCH_PARENT,
4011 ViewGroup.LayoutParams.MATCH_PARENT);
4012 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4013 new FrameLayout.LayoutParams(
4014 ViewGroup.LayoutParams.MATCH_PARENT,
4015 ViewGroup.LayoutParams.MATCH_PARENT,
4018 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4020 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4021 // Dictionary search
4022 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4023 // Google Mobile Local search
4024 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4026 final static String QUERY_PLACE_HOLDER = "%s";
4028 // "source" parameter for Google search through search key
4029 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4030 // "source" parameter for Google search through goto menu
4031 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4032 // "source" parameter for Google search through simplily type
4033 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4034 // "source" parameter for Google search suggested by the browser
4035 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4036 // "source" parameter for Google search from unknown source
4037 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4039 private final static String LOGTAG = "browser";
4041 private String mLastEnteredUrl;
4043 private PowerManager.WakeLock mWakeLock;
4044 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4046 private Toast mStopToast;
4048 private TitleBar mTitleBar;
4050 private LinearLayout mErrorConsoleContainer = null;
4051 private boolean mShouldShowErrorConsole = false;
4053 // As the ids are dynamically created, we can't guarantee that they will
4054 // be in sequence, so this static array maps ids to a window number.
4055 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4056 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4057 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4058 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4060 // monitor platform changes
4061 private IntentFilter mNetworkStateChangedFilter;
4062 private BroadcastReceiver mNetworkStateIntentReceiver;
4064 private BroadcastReceiver mPackageInstallationReceiver;
4066 // activity requestCode
4067 final static int COMBO_PAGE = 1;
4068 final static int DOWNLOAD_PAGE = 2;
4069 final static int PREFERENCES_PAGE = 3;
4070 final static int FILE_SELECTED = 4;
4072 // the default <video> poster
4073 private Bitmap mDefaultVideoPoster;
4074 // the video progress view
4075 private View mVideoProgressView;
4077 // The Google packages we monitor for the navigator.isApplicationInstalled()
4078 // API. Add as needed.
4079 private static Set<String> sGoogleApps;
4081 sGoogleApps = new HashSet<String>();
4082 sGoogleApps.add("com.google.android.youtube");
4086 * A UrlData class to abstract how the content will be set to WebView.
4087 * This base class uses loadUrl to show the content.
4089 private static class UrlData {
4091 final Map<String, String> mHeaders;
4092 final Intent mVoiceIntent;
4094 UrlData(String url) {
4096 this.mHeaders = null;
4097 this.mVoiceIntent = null;
4100 UrlData(String url, Map<String, String> headers, Intent intent) {
4102 this.mHeaders = headers;
4103 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4104 .equals(intent.getAction())) {
4105 this.mVoiceIntent = intent;
4107 this.mVoiceIntent = null;
4112 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
4116 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4117 * the title bar as well.
4119 public void loadIn(Tab t) {
4120 if (mVoiceIntent != null) {
4121 t.activateVoiceSearchMode(mVoiceIntent);
4123 t.getWebView().loadUrl(mUrl, mHeaders);
4128 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);