2 * Copyright (C) 2006 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.browser;
19 import android.app.Activity;
20 import android.app.AlertDialog;
21 import android.app.ProgressDialog;
22 import android.app.SearchManager;
23 import android.content.ActivityNotFoundException;
24 import android.content.BroadcastReceiver;
25 import android.content.ComponentName;
26 import android.content.ContentProvider;
27 import android.content.ContentProviderClient;
28 import android.content.ContentResolver;
29 import android.content.ContentUris;
30 import android.content.ContentValues;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.pm.PackageInfo;
36 import android.content.pm.PackageManager;
37 import android.content.pm.ResolveInfo;
38 import android.content.res.Configuration;
39 import android.content.res.Resources;
40 import android.database.Cursor;
41 import android.database.DatabaseUtils;
42 import android.graphics.Bitmap;
43 import android.graphics.BitmapFactory;
44 import android.graphics.Canvas;
45 import android.graphics.Picture;
46 import android.graphics.PixelFormat;
47 import android.graphics.Rect;
48 import android.graphics.drawable.Drawable;
49 import android.net.ConnectivityManager;
50 import android.net.NetworkInfo;
51 import android.net.Uri;
52 import android.net.WebAddress;
53 import android.net.http.SslCertificate;
54 import android.net.http.SslError;
55 import android.os.AsyncTask;
56 import android.os.Bundle;
57 import android.os.Debug;
58 import android.os.Environment;
59 import android.os.Handler;
60 import android.os.Message;
61 import android.os.PowerManager;
62 import android.os.Process;
63 import android.os.ServiceManager;
64 import android.os.SystemClock;
65 import android.provider.Browser;
66 import android.provider.ContactsContract;
67 import android.provider.ContactsContract.Intents.Insert;
68 import android.provider.Downloads;
69 import android.provider.MediaStore;
70 import android.speech.RecognizerResultsIntent;
71 import android.text.IClipboard;
72 import android.text.TextUtils;
73 import android.text.format.DateFormat;
74 import android.util.AttributeSet;
75 import android.util.Log;
76 import android.view.ContextMenu;
77 import android.view.Gravity;
78 import android.view.KeyEvent;
79 import android.view.LayoutInflater;
80 import android.view.Menu;
81 import android.view.MenuInflater;
82 import android.view.MenuItem;
83 import android.view.View;
84 import android.view.ViewGroup;
85 import android.view.Window;
86 import android.view.WindowManager;
87 import android.view.ContextMenu.ContextMenuInfo;
88 import android.view.MenuItem.OnMenuItemClickListener;
89 import android.webkit.CookieManager;
90 import android.webkit.CookieSyncManager;
91 import android.webkit.DownloadListener;
92 import android.webkit.HttpAuthHandler;
93 import android.webkit.PluginManager;
94 import android.webkit.SslErrorHandler;
95 import android.webkit.URLUtil;
96 import android.webkit.ValueCallback;
97 import android.webkit.WebChromeClient;
98 import android.webkit.WebHistoryItem;
99 import android.webkit.WebIconDatabase;
100 import android.webkit.WebView;
101 import android.widget.EditText;
102 import android.widget.FrameLayout;
103 import android.widget.LinearLayout;
104 import android.widget.TextView;
105 import android.widget.Toast;
106 import android.accounts.Account;
107 import android.accounts.AccountManager;
108 import android.accounts.AccountManagerFuture;
109 import android.accounts.AuthenticatorException;
110 import android.accounts.OperationCanceledException;
111 import android.accounts.AccountManagerCallback;
113 import com.android.common.Patterns;
114 import com.android.common.Search;
115 import com.android.common.speech.LoggingEvents;
117 import com.google.android.gsf.GoogleLoginServiceConstants;
119 import java.io.ByteArrayOutputStream;
121 import java.io.IOException;
122 import java.io.InputStream;
123 import java.net.MalformedURLException;
125 import java.net.URISyntaxException;
127 import java.net.URLEncoder;
128 import java.text.ParseException;
129 import java.util.Date;
130 import java.util.HashMap;
131 import java.util.HashSet;
132 import java.util.Iterator;
133 import java.util.List;
134 import java.util.Map;
135 import java.util.Set;
136 import java.util.regex.Matcher;
137 import java.util.regex.Pattern;
139 public class BrowserActivity extends Activity
140 implements View.OnCreateContextMenuListener, DownloadListener,
141 AccountManagerCallback<Account[]> {
143 /* Define some aliases to make these debugging flags easier to refer to.
144 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
146 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
147 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
148 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
150 // These are single-character shortcuts for searching popular sources.
151 private static final int SHORTCUT_INVALID = 0;
152 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
153 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
154 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
155 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
157 private Account[] mAccountsGoogle;
158 private Account[] mAccountsPreferHosted;
160 private void startReadOfGoogleAccounts() {
161 mAccountsGoogle = null;
162 mAccountsPreferHosted = null;
164 AccountManager.get(this).getAccountsByTypeAndFeatures(
165 GoogleLoginServiceConstants.ACCOUNT_TYPE,
166 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
170 /** This implements AccountManagerCallback<Account[]> */
171 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
173 if (mAccountsGoogle == null) {
174 mAccountsGoogle = accountManagerFuture.getResult();
176 AccountManager.get(this).getAccountsByTypeAndFeatures(
177 GoogleLoginServiceConstants.ACCOUNT_TYPE,
178 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
181 mAccountsPreferHosted = accountManagerFuture.getResult();
184 } catch (OperationCanceledException e) {
186 } catch (IOException e) {
188 } catch (AuthenticatorException e) {
193 private void setupHomePage() {
194 // get the default home page
195 String homepage = mSettings.getHomePage();
197 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
200 // hostedUser == googleUser
201 // The device has only a google account
203 // hostedUser != googleUser
204 // The device has a hosted account and a google account
206 // hostedUser != null, googleUser == null
207 // The device has only a hosted account (so far)
208 String hostedUser = mAccountsPreferHosted.length == 0
210 : mAccountsPreferHosted[0].name;
211 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
213 // developers might have no accounts at all
214 if (hostedUser == null) return;
216 if (googleUser == null || !hostedUser.equals(googleUser)) {
217 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
218 homepage = homepage.replace("?", "/a/" + domain + "?");
222 mSettings.setHomePage(BrowserActivity.this, homepage);
223 resumeAfterCredentials();
226 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
228 public Void doInBackground(File... files) {
230 for (File f : files) {
232 Log.e(LOGTAG, f.getPath() + " was not deleted");
241 * This layout holds everything you see below the status bar, including the
242 * error console, the custom view container, and the webviews.
244 private FrameLayout mBrowserFrameLayout;
247 public void onCreate(Bundle icicle) {
249 Log.v(LOGTAG, this + " onStart");
251 super.onCreate(icicle);
252 // test the browser in OpenGL
253 // requestWindowFeature(Window.FEATURE_OPENGL);
255 // enable this to test the browser in 32bit
257 getWindow().setFormat(PixelFormat.RGBX_8888);
258 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
261 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
263 mResolver = getContentResolver();
265 // If this was a web search request, pass it on to the default web
266 // search provider and finish this activity.
267 if (handleWebSearchIntent(getIntent())) {
272 mSecLockIcon = Resources.getSystem().getDrawable(
273 android.R.drawable.ic_secure);
274 mMixLockIcon = Resources.getSystem().getDrawable(
275 android.R.drawable.ic_partial_secure);
277 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
278 .findViewById(com.android.internal.R.id.content);
279 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
280 .inflate(R.layout.custom_screen, null);
281 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
283 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
284 .findViewById(R.id.error_console);
285 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
286 .findViewById(R.id.fullscreen_custom_content);
287 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
288 mTitleBar = new TitleBar(this);
289 mFakeTitleBar = new TitleBar(this);
291 // Create the tab control and our initial tab
292 mTabControl = new TabControl(this);
294 // Open the icon database and retain all the bookmark urls for favicons
295 retainIconsOnStartup();
297 // Keep a settings instance handy.
298 mSettings = BrowserSettings.getInstance();
299 mSettings.setTabControl(mTabControl);
300 mSettings.loadFromDb(this);
302 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
303 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
305 /* enables registration for changes in network status from
307 mNetworkStateChangedFilter = new IntentFilter();
308 mNetworkStateChangedFilter.addAction(
309 ConnectivityManager.CONNECTIVITY_ACTION);
310 mNetworkStateIntentReceiver = new BroadcastReceiver() {
312 public void onReceive(Context context, Intent intent) {
313 if (intent.getAction().equals(
314 ConnectivityManager.CONNECTIVITY_ACTION)) {
315 boolean noConnectivity = intent.getBooleanExtra(
316 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
317 if (!noConnectivity) {
318 NetworkInfo info = intent.getParcelableExtra(
319 ConnectivityManager.EXTRA_NETWORK_INFO);
320 String typeName = info.getTypeName();
321 String subtypeName = info.getSubtypeName();
322 sendNetworkType(typeName.toLowerCase(),
323 (subtypeName != null ? subtypeName.toLowerCase() : ""));
325 onNetworkToggle(!noConnectivity);
330 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
331 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
332 filter.addDataScheme("package");
333 mPackageInstallationReceiver = new BroadcastReceiver() {
335 public void onReceive(Context context, Intent intent) {
336 final String action = intent.getAction();
337 final String packageName = intent.getData()
338 .getSchemeSpecificPart();
339 final boolean replacing = intent.getBooleanExtra(
340 Intent.EXTRA_REPLACING, false);
341 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
342 // if it is replacing, refreshPlugins() when adding
346 if (sGoogleApps.contains(packageName)) {
347 BrowserActivity.this.packageChanged(packageName,
348 Intent.ACTION_PACKAGE_ADDED.equals(action));
351 PackageManager pm = BrowserActivity.this.getPackageManager();
352 PackageInfo pkgInfo = null;
354 pkgInfo = pm.getPackageInfo(packageName,
355 PackageManager.GET_PERMISSIONS);
356 } catch (PackageManager.NameNotFoundException e) {
359 if (pkgInfo != null) {
360 String permissions[] = pkgInfo.requestedPermissions;
361 if (permissions == null) {
364 boolean permissionOk = false;
365 for (String permit : permissions) {
366 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
372 PluginManager.getInstance(BrowserActivity.this)
374 Intent.ACTION_PACKAGE_ADDED
380 registerReceiver(mPackageInstallationReceiver, filter);
382 if (!mTabControl.restoreState(icicle)) {
383 // clear up the thumbnail directory if we can't restore the state as
384 // none of the files in the directory are referenced any more.
385 new ClearThumbnails().execute(
386 mTabControl.getThumbnailDir().listFiles());
387 // there is no quit on Android. But if we can't restore the state,
388 // we can treat it as a new Browser, remove the old session cookies.
389 CookieManager.getInstance().removeSessionCookie();
390 final Intent intent = getIntent();
391 final Bundle extra = intent.getExtras();
392 // Create an initial tab.
393 // If the intent is ACTION_VIEW and data is not null, the Browser is
394 // invoked to view the content by another application. In this case,
395 // the tab will be close when exit.
396 UrlData urlData = getUrlDataFromIntent(intent);
398 String action = intent.getAction();
399 final Tab t = mTabControl.createNewTab(
400 (Intent.ACTION_VIEW.equals(action) &&
401 intent.getData() != null)
402 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
404 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
405 mTabControl.setCurrentTab(t);
406 attachTabToContentView(t);
407 WebView webView = t.getWebView();
409 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
410 if (scale > 0 && scale <= 1000) {
411 webView.setInitialScale(scale);
414 // If we are not restoring from an icicle, then there is a high
415 // likely hood this is the first run. So, check to see if the
416 // homepage needs to be configured and copy any plugins from our
417 // asset directory to the data partition.
418 if ((extra == null || !extra.getBoolean("testing"))
419 && !mSettings.isLoginInitialized()) {
420 startReadOfGoogleAccounts();
423 if (urlData.isEmpty()) {
424 if (mSettings.isLoginInitialized()) {
425 loadUrl(webView, mSettings.getHomePage());
427 waitForCredentials();
430 loadUrlDataIn(t, urlData);
433 // TabControl.restoreState() will create a new tab even if
434 // restoring the state fails.
435 attachTabToContentView(mTabControl.getCurrentTab());
438 // Read JavaScript flags if it exists.
439 String jsFlags = mSettings.getJsFlags();
440 if (jsFlags.trim().length() != 0) {
441 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
443 // Work out which packages are installed on the system.
444 getInstalledPackages();
448 * Feed the previously stored results strings to the BrowserProvider so that
449 * the SearchDialog will show them instead of the standard searches.
450 * @param result String to show on the editable line of the SearchDialog.
452 /* package */ void showVoiceSearchResults(String result) {
453 ContentProviderClient client = mResolver.acquireContentProviderClient(
454 Browser.BOOKMARKS_URI);
455 ContentProvider prov = client.getLocalContentProvider();
456 BrowserProvider bp = (BrowserProvider) prov;
457 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
460 startSearch(result, false,
461 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
466 protected void onNewIntent(Intent intent) {
467 Tab current = mTabControl.getCurrentTab();
468 // When a tab is closed on exit, the current tab index is set to -1.
469 // Reset before proceed as Browser requires the current tab to be set.
470 if (current == null) {
471 // Try to reset the tab in case the index was incorrect.
472 current = mTabControl.getTab(0);
473 if (current == null) {
474 // No tabs at all so just ignore this intent.
477 mTabControl.setCurrentTab(current);
478 attachTabToContentView(current);
479 resetTitleAndIcon(current.getWebView());
481 final String action = intent.getAction();
482 final int flags = intent.getFlags();
483 if (Intent.ACTION_MAIN.equals(action) ||
484 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
485 // just resume the browser
488 boolean activateVoiceSearch = RecognizerResultsIntent
489 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
490 if (Intent.ACTION_VIEW.equals(action)
491 || Intent.ACTION_SEARCH.equals(action)
492 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
493 || Intent.ACTION_WEB_SEARCH.equals(action)
494 || activateVoiceSearch) {
495 if (current.isInVoiceSearchMode()) {
496 String title = current.getVoiceDisplayTitle();
497 if (title != null && title.equals(intent.getStringExtra(
498 SearchManager.QUERY))) {
499 // The user submitted the same search as the last voice
500 // search, so do nothing.
503 if (Intent.ACTION_SEARCH.equals(action)
504 && current.voiceSearchSourceIsGoogle()) {
505 Intent logIntent = new Intent(
506 LoggingEvents.ACTION_LOG_EVENT);
507 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
508 LoggingEvents.VoiceSearch.QUERY_UPDATED);
510 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
511 intent.getDataString());
512 sendBroadcast(logIntent);
513 // Note, onPageStarted will revert the voice title bar
514 // When http://b/issue?id=2379215 is fixed, we should update
515 // the title bar here.
518 // If this was a search request (e.g. search query directly typed into the address bar),
519 // pass it on to the default web search provider.
520 if (handleWebSearchIntent(intent)) {
524 UrlData urlData = getUrlDataFromIntent(intent);
525 if (urlData.isEmpty()) {
526 urlData = new UrlData(mSettings.getHomePage());
529 final String appId = intent
530 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
531 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
532 && !getPackageName().equals(appId)
533 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
534 Tab appTab = mTabControl.getTabFromId(appId);
535 if (appTab != null) {
536 Log.i(LOGTAG, "Reusing tab for " + appId);
537 // Dismiss the subwindow if applicable.
538 dismissSubWindow(appTab);
539 // Since we might kill the WebView, remove it from the
540 // content view first.
541 removeTabFromContentView(appTab);
542 // Recreate the main WebView after destroying the old one.
543 // If the WebView has the same original url and is on that
544 // page, it can be reused.
546 mTabControl.recreateWebView(appTab, urlData.mUrl);
548 if (current != appTab) {
549 switchToTab(mTabControl.getTabIndex(appTab));
551 loadUrlDataIn(appTab, urlData);
554 // If the tab was the current tab, we have to attach
555 // it to the view system again.
556 attachTabToContentView(appTab);
558 loadUrlDataIn(appTab, urlData);
563 // No matching application tab, try to find a regular tab
564 // with a matching url.
565 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
566 if (appTab != null) {
567 if (current != appTab) {
568 switchToTab(mTabControl.getTabIndex(appTab));
570 // Otherwise, we are already viewing the correct tab.
572 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
573 // will be opened in a new tab unless we have reached
574 // MAX_TABS. Then the url will be opened in the current
575 // tab. If a new tab is created, it will have "true" for
577 openTabAndShow(urlData, true, appId);
581 if (!urlData.isEmpty()
582 && urlData.mUrl.startsWith("about:debug")) {
583 if ("about:debug.dom".equals(urlData.mUrl)) {
584 current.getWebView().dumpDomTree(false);
585 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
586 current.getWebView().dumpDomTree(true);
587 } else if ("about:debug.render".equals(urlData.mUrl)) {
588 current.getWebView().dumpRenderTree(false);
589 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
590 current.getWebView().dumpRenderTree(true);
591 } else if ("about:debug.display".equals(urlData.mUrl)) {
592 current.getWebView().dumpDisplayTree();
593 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
594 int index = urlData.mUrl.codePointAt(16) - '0';
595 if (index <= 0 || index > 9) {
596 current.getWebView().setDragTracker(null);
598 current.getWebView().setDragTracker(new MeshTracker(index));
601 mSettings.toggleDebugSettings();
605 // Get rid of the subwindow if it exists
606 dismissSubWindow(current);
607 loadUrlDataIn(current, urlData);
612 private int parseUrlShortcut(String url) {
613 if (url == null) return SHORTCUT_INVALID;
615 // FIXME: quick search, need to be customized by setting
616 if (url.length() > 2 && url.charAt(1) == ' ') {
617 switch (url.charAt(0)) {
618 case 'g': return SHORTCUT_GOOGLE_SEARCH;
619 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
620 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
621 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
624 return SHORTCUT_INVALID;
628 * Launches the default web search activity with the query parameters if the given intent's data
629 * are identified as plain search terms and not URLs/shortcuts.
630 * @return true if the intent was handled and web search activity was launched, false if not.
632 private boolean handleWebSearchIntent(Intent intent) {
633 if (intent == null) return false;
636 final String action = intent.getAction();
637 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
641 if (Intent.ACTION_VIEW.equals(action)) {
642 Uri data = intent.getData();
643 if (data != null) url = data.toString();
644 } else if (Intent.ACTION_SEARCH.equals(action)
645 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
646 || Intent.ACTION_WEB_SEARCH.equals(action)) {
647 url = intent.getStringExtra(SearchManager.QUERY);
649 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
650 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
654 * Launches the default web search activity with the query parameters if the given url string
655 * was identified as plain search terms and not URL/shortcut.
656 * @return true if the request was handled and web search activity was launched, false if not.
658 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
659 if (inUrl == null) return false;
661 // In general, we shouldn't modify URL from Intent.
662 // But currently, we get the user-typed URL from search box as well.
663 String url = fixUrl(inUrl).trim();
665 // URLs and site specific search shortcuts are handled by the regular flow of control, so
667 if (Patterns.WEB_URL.matcher(url).matches()
668 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
669 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
673 Browser.updateVisitedHistory(mResolver, url, false);
674 Browser.addSearchUrl(mResolver, url);
676 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
677 intent.addCategory(Intent.CATEGORY_DEFAULT);
678 intent.putExtra(SearchManager.QUERY, url);
679 if (appData != null) {
680 intent.putExtra(SearchManager.APP_DATA, appData);
682 if (extraData != null) {
683 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
685 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
686 startActivity(intent);
691 private UrlData getUrlDataFromIntent(Intent intent) {
693 Map<String, String> headers = null;
694 if (intent != null) {
695 final String action = intent.getAction();
696 if (Intent.ACTION_VIEW.equals(action)) {
697 url = smartUrlFilter(intent.getData());
698 if (url != null && url.startsWith("content:")) {
699 /* Append mimetype so webview knows how to display */
700 String mimeType = intent.resolveType(getContentResolver());
701 if (mimeType != null) {
702 url += "?" + mimeType;
705 if (url != null && url.startsWith("http")) {
706 final Bundle pairs = intent
707 .getBundleExtra(Browser.EXTRA_HEADERS);
708 if (pairs != null && !pairs.isEmpty()) {
709 Iterator<String> iter = pairs.keySet().iterator();
710 headers = new HashMap<String, String>();
711 while (iter.hasNext()) {
712 String key = iter.next();
713 headers.put(key, pairs.getString(key));
717 } else if (Intent.ACTION_SEARCH.equals(action)
718 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
719 || Intent.ACTION_WEB_SEARCH.equals(action)) {
720 url = intent.getStringExtra(SearchManager.QUERY);
722 mLastEnteredUrl = url;
723 Browser.updateVisitedHistory(mResolver, url, false);
724 // In general, we shouldn't modify URL from Intent.
725 // But currently, we get the user-typed URL from search box as well.
727 url = smartUrlFilter(url);
728 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
729 if (url.contains(searchSource)) {
730 String source = null;
731 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
732 if (appData != null) {
733 source = appData.getString(Search.SOURCE);
735 if (TextUtils.isEmpty(source)) {
736 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
738 url = url.replace(searchSource, "&source=android-"+source+"&");
743 return new UrlData(url, headers, intent);
745 /* package */ void showVoiceTitleBar(String title) {
746 mTitleBar.setInVoiceMode(true);
747 mFakeTitleBar.setInVoiceMode(true);
749 mTitleBar.setDisplayTitle(title);
750 mFakeTitleBar.setDisplayTitle(title);
752 /* package */ void revertVoiceTitleBar() {
753 mTitleBar.setInVoiceMode(false);
754 mFakeTitleBar.setInVoiceMode(false);
756 mTitleBar.setDisplayTitle(mTitle);
757 mFakeTitleBar.setDisplayTitle(mTitle);
759 /* package */ static String fixUrl(String inUrl) {
760 // FIXME: Converting the url to lower case
761 // duplicates functionality in smartUrlFilter().
762 // However, changing all current callers of fixUrl to
763 // call smartUrlFilter in addition may have unwanted
764 // consequences, and is deferred for now.
765 int colon = inUrl.indexOf(':');
766 boolean allLower = true;
767 for (int index = 0; index < colon; index++) {
768 char ch = inUrl.charAt(index);
769 if (!Character.isLetter(ch)) {
772 allLower &= Character.isLowerCase(ch);
773 if (index == colon - 1 && !allLower) {
774 inUrl = inUrl.substring(0, colon).toLowerCase()
775 + inUrl.substring(colon);
778 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
780 if (inUrl.startsWith("http:") ||
781 inUrl.startsWith("https:")) {
782 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
783 inUrl = inUrl.replaceFirst("/", "//");
784 } else inUrl = inUrl.replaceFirst(":", "://");
790 protected void onResume() {
793 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
796 if (!mActivityInPause) {
797 Log.e(LOGTAG, "BrowserActivity is already resumed.");
801 mTabControl.resumeCurrentTab();
802 mActivityInPause = false;
803 resumeWebViewTimers();
805 if (mWakeLock.isHeld()) {
806 mHandler.removeMessages(RELEASE_WAKELOCK);
810 if (mCredsDlg != null) {
811 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
812 // In case credential request never comes back
813 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
817 registerReceiver(mNetworkStateIntentReceiver,
818 mNetworkStateChangedFilter);
819 WebView.enablePlatformNotifications();
823 * Since the actual title bar is embedded in the WebView, and removing it
824 * would change its appearance, use a different TitleBar to show overlayed
825 * at the top of the screen, when the menu is open or the page is loading.
827 private TitleBar mFakeTitleBar;
830 * Holder for the fake title bar. It will have a foreground shadow, as well
831 * as a white background, so the fake title bar looks like the real one.
833 private ViewGroup mFakeTitleBarHolder;
836 * Layout parameters for the fake title bar within mFakeTitleBarHolder
838 private FrameLayout.LayoutParams mFakeTitleBarParams
839 = new FrameLayout.LayoutParams(
840 ViewGroup.LayoutParams.MATCH_PARENT,
841 ViewGroup.LayoutParams.WRAP_CONTENT);
843 * Keeps track of whether the options menu is open. This is important in
844 * determining whether to show or hide the title bar overlay.
846 private boolean mOptionsMenuOpen;
849 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
850 * of whether the configuration has changed. The first onMenuOpened call
851 * after a configuration change is simply a reopening of the same menu
852 * (i.e. mIconView did not change).
854 private boolean mConfigChanged;
857 * Whether or not the options menu is in its smaller, icon menu form. When
858 * true, we want the title bar overlay to be up. When false, we do not.
859 * Only meaningful if mOptionsMenuOpen is true.
861 private boolean mIconView;
864 public boolean onMenuOpened(int featureId, Menu menu) {
865 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
866 if (mOptionsMenuOpen) {
867 if (mConfigChanged) {
868 // We do not need to make any changes to the state of the
869 // title bar, since the only thing that happened was a
870 // change in orientation
871 mConfigChanged = false;
874 // Switching the menu to expanded view, so hide the
879 // Switching the menu back to icon view, so show the
880 // title bar once again.
886 // The options menu is closed, so open it, and show the title
888 mOptionsMenuOpen = true;
889 mConfigChanged = false;
897 * Special class used exclusively for the shadow drawn underneath the fake
898 * title bar. The shadow does not need to be drawn if the WebView
899 * underneath is scrolled to the top, because it will draw directly on top
900 * of the embedded shadow.
902 private static class Shadow extends View {
903 private WebView mWebView;
905 public Shadow(Context context, AttributeSet attrs) {
906 super(context, attrs);
909 public void setWebView(WebView view) {
914 public void draw(Canvas canvas) {
915 // In general onDraw is the method to override, but we care about
916 // whether or not the background gets drawn, which happens in draw()
917 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
920 // Need to invalidate so that if the scroll position changes, we
921 // still draw as appropriate.
926 private void showFakeTitleBar() {
927 final View decor = getWindow().peekDecorView();
928 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
929 && !mActivityInPause && decor != null
930 && decor.getWindowToken() != null) {
931 Rect visRect = new Rect();
932 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
934 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
939 WindowManager manager
940 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
942 // Add the title bar to the window manager so it can receive touches
943 // while the menu is up
944 WindowManager.LayoutParams params
945 = new WindowManager.LayoutParams(
946 ViewGroup.LayoutParams.MATCH_PARENT,
947 ViewGroup.LayoutParams.WRAP_CONTENT,
948 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
949 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
950 PixelFormat.TRANSLUCENT);
951 params.gravity = Gravity.TOP;
952 WebView mainView = mTabControl.getCurrentWebView();
953 boolean atTop = mainView != null && mainView.getScrollY() == 0;
954 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
955 // XXX : Without providing an offset, the fake title bar will be
956 // placed underneath the status bar. Use the global visible rect
957 // of mBrowserFrameLayout to determine the bottom of the status bar
958 params.y = visRect.top;
959 // Add a holder for the title bar. It also holds a shadow to show
960 // below the title bar.
961 if (mFakeTitleBarHolder == null) {
962 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
963 .inflate(R.layout.title_bar_bg, null);
965 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
967 shadow.setWebView(mainView);
968 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
969 manager.addView(mFakeTitleBarHolder, params);
974 public void onOptionsMenuClosed(Menu menu) {
975 mOptionsMenuOpen = false;
978 } else if (!mIconView) {
979 // The page is currently loading, and we are in expanded mode, so
980 // we were not showing the menu. Show it once again. It will be
981 // removed when the page finishes.
986 private void hideFakeTitleBar() {
987 if (mFakeTitleBar.getParent() == null) return;
988 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
989 mFakeTitleBarHolder.getLayoutParams();
990 WebView mainView = mTabControl.getCurrentWebView();
991 // Although we decided whether or not to animate based on the current
992 // scroll position, the scroll position may have changed since the
993 // fake title bar was displayed. Make sure it has the appropriate
994 // animation/lack thereof before removing.
995 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
996 ? 0 : R.style.TitleBar;
997 WindowManager manager
998 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
999 manager.updateViewLayout(mFakeTitleBarHolder, params);
1000 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1001 manager.removeView(mFakeTitleBarHolder);
1005 * Special method for the fake title bar to call when displaying its context
1006 * menu, since it is in its own Window, and its parent does not show a
1009 /* package */ void showTitleBarContextMenu() {
1010 if (null == mTitleBar.getParent()) {
1013 openContextMenu(mTitleBar);
1017 public void onContextMenuClosed(Menu menu) {
1018 super.onContextMenuClosed(menu);
1025 * onSaveInstanceState(Bundle map)
1026 * onSaveInstanceState is called right before onStop(). The map contains
1030 protected void onSaveInstanceState(Bundle outState) {
1032 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1034 // the default implementation requires each view to have an id. As the
1035 // browser handles the state itself and it doesn't use id for the views,
1036 // don't call the default implementation. Otherwise it will trigger the
1037 // warning like this, "couldn't save which view has focus because the
1038 // focused view XXX has no id".
1040 // Save all the tabs
1041 mTabControl.saveState(outState);
1045 protected void onPause() {
1048 if (mActivityInPause) {
1049 Log.e(LOGTAG, "BrowserActivity is already paused.");
1053 mTabControl.pauseCurrentTab();
1054 mActivityInPause = true;
1055 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1056 mWakeLock.acquire();
1057 mHandler.sendMessageDelayed(mHandler
1058 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1061 // Clear the credentials toast if it is up
1062 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1063 mCredsDlg.dismiss();
1067 // FIXME: This removes the active tabs page and resets the menu to
1068 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1069 // but then we would need to save it in onSaveInstanceState and restore
1070 // it in onCreate/onRestoreInstanceState
1071 if (mActiveTabsPage != null) {
1072 removeActiveTabPage(true);
1077 // unregister network state listener
1078 unregisterReceiver(mNetworkStateIntentReceiver);
1079 WebView.disablePlatformNotifications();
1083 protected void onDestroy() {
1085 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1089 if (mUploadMessage != null) {
1090 mUploadMessage.onReceiveValue(null);
1091 mUploadMessage = null;
1094 if (mTabControl == null) return;
1096 // Remove the fake title bar if it is there
1099 // Remove the current tab and sub window
1100 Tab t = mTabControl.getCurrentTab();
1102 dismissSubWindow(t);
1103 removeTabFromContentView(t);
1105 // Destroy all the tabs
1106 mTabControl.destroy();
1107 WebIconDatabase.getInstance().close();
1109 unregisterReceiver(mPackageInstallationReceiver);
1113 public void onConfigurationChanged(Configuration newConfig) {
1114 mConfigChanged = true;
1115 super.onConfigurationChanged(newConfig);
1117 if (mPageInfoDialog != null) {
1118 mPageInfoDialog.dismiss();
1121 mPageInfoFromShowSSLCertificateOnError);
1123 if (mSSLCertificateDialog != null) {
1124 mSSLCertificateDialog.dismiss();
1126 mSSLCertificateView);
1128 if (mSSLCertificateOnErrorDialog != null) {
1129 mSSLCertificateOnErrorDialog.dismiss();
1130 showSSLCertificateOnError(
1131 mSSLCertificateOnErrorView,
1132 mSSLCertificateOnErrorHandler,
1133 mSSLCertificateOnErrorError);
1135 if (mHttpAuthenticationDialog != null) {
1136 String title = ((TextView) mHttpAuthenticationDialog
1137 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1139 String name = ((TextView) mHttpAuthenticationDialog
1140 .findViewById(R.id.username_edit)).getText().toString();
1141 String password = ((TextView) mHttpAuthenticationDialog
1142 .findViewById(R.id.password_edit)).getText().toString();
1143 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1145 mHttpAuthenticationDialog.dismiss();
1146 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1147 name, password, focusId);
1152 public void onLowMemory() {
1153 super.onLowMemory();
1154 mTabControl.freeMemory();
1157 private boolean resumeWebViewTimers() {
1158 Tab tab = mTabControl.getCurrentTab();
1159 boolean inLoad = tab.inLoad();
1160 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1161 CookieSyncManager.getInstance().startSync();
1162 WebView w = tab.getWebView();
1172 private boolean pauseWebViewTimers() {
1173 Tab tab = mTabControl.getCurrentTab();
1174 boolean inLoad = tab.inLoad();
1175 if (mActivityInPause && !inLoad) {
1176 CookieSyncManager.getInstance().stopSync();
1177 WebView w = mTabControl.getCurrentWebView();
1187 // FIXME: Do we want to call this when loading google for the first time?
1189 * This function is called when we are launching for the first time. We
1190 * are waiting for the login credentials before loading Google home
1191 * pages. This way the user will be logged in straight away.
1193 private void waitForCredentials() {
1195 mCredsDlg = new ProgressDialog(this);
1196 mCredsDlg.setIndeterminate(true);
1197 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1198 // If the user cancels the operation, then cancel the Google
1199 // Credentials request.
1200 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1203 // We set a timeout for the retrieval of credentials in onResume()
1204 // as that is when we have freed up some CPU time to get
1205 // the login credentials.
1209 * If we have received the credentials or we have timed out and we are
1210 * showing the credentials dialog, then it is time to move on.
1212 private void resumeAfterCredentials() {
1213 if (mCredsDlg == null) {
1218 if (mCredsDlg.isShowing()) {
1219 mCredsDlg.dismiss();
1223 // Clear any pending timeout
1224 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1227 WebView w = mTabControl.getCurrentWebView();
1229 loadUrl(w, mSettings.getHomePage());
1232 // Update the settings, need to do this last as it can take a moment
1233 // to persist the settings. In the mean time we could be loading
1235 mSettings.setLoginInitialized(this);
1238 // Open the icon database and retain all the icons for visited sites.
1239 private void retainIconsOnStartup() {
1240 final WebIconDatabase db = WebIconDatabase.getInstance();
1241 db.open(getDir("icons", 0).getPath());
1243 Cursor c = Browser.getAllBookmarks(mResolver);
1244 if (!c.moveToFirst()) {
1248 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1250 String url = c.getString(urlIndex);
1251 db.retainIconForPageUrl(url);
1252 } while (c.moveToNext());
1254 } catch (IllegalStateException e) {
1255 Log.e(LOGTAG, "retainIconsOnStartup", e);
1259 // Helper method for getting the top window.
1260 WebView getTopWindow() {
1261 return mTabControl.getCurrentTopWebView();
1264 TabControl getTabControl() {
1269 public boolean onCreateOptionsMenu(Menu menu) {
1270 super.onCreateOptionsMenu(menu);
1272 MenuInflater inflater = getMenuInflater();
1273 inflater.inflate(R.menu.browser, menu);
1275 updateInLoadMenuItems();
1280 * As the menu can be open when loading state changes
1281 * we must manually update the state of the stop/reload menu
1284 private void updateInLoadMenuItems() {
1285 if (mMenu == null) {
1288 MenuItem src = mInLoad ?
1289 mMenu.findItem(R.id.stop_menu_id):
1290 mMenu.findItem(R.id.reload_menu_id);
1291 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1292 dest.setIcon(src.getIcon());
1293 dest.setTitle(src.getTitle());
1297 public boolean onContextItemSelected(MenuItem item) {
1298 // chording is not an issue with context menus, but we use the same
1299 // options selector, so set mCanChord to true so we can access them.
1301 int id = item.getItemId();
1302 boolean result = true;
1304 // For the context menu from the title bar
1305 case R.id.title_bar_copy_page_url:
1306 Tab currentTab = mTabControl.getCurrentTab();
1307 if (null == currentTab) {
1311 WebView mainView = currentTab.getWebView();
1312 if (null == mainView) {
1316 copy(mainView.getUrl());
1318 // -- Browser context menu
1319 case R.id.open_context_menu_id:
1320 case R.id.open_newtab_context_menu_id:
1321 case R.id.bookmark_context_menu_id:
1322 case R.id.save_link_context_menu_id:
1323 case R.id.share_link_context_menu_id:
1324 case R.id.copy_link_context_menu_id:
1325 final WebView webView = getTopWindow();
1326 if (null == webView) {
1330 final HashMap hrefMap = new HashMap();
1331 hrefMap.put("webview", webView);
1332 final Message msg = mHandler.obtainMessage(
1333 FOCUS_NODE_HREF, id, 0, hrefMap);
1334 webView.requestFocusNodeHref(msg);
1338 // For other context menus
1339 result = onOptionsItemSelected(item);
1345 private Bundle createGoogleSearchSourceBundle(String source) {
1346 Bundle bundle = new Bundle();
1347 bundle.putString(Search.SOURCE, source);
1351 /* package */ void editUrl() {
1352 if (mOptionsMenuOpen) closeOptionsMenu();
1353 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1354 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1359 * Overriding this to insert a local information bundle
1362 public void startSearch(String initialQuery, boolean selectInitialQuery,
1363 Bundle appSearchData, boolean globalSearch) {
1364 if (appSearchData == null) {
1365 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1367 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1371 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1372 * results in changing tabs.
1373 * @param index Index of the tab to change to, as defined by
1374 * mTabControl.getTabIndex(Tab t).
1375 * @return boolean True if we successfully switched to a different tab. If
1376 * the indexth tab is null, or if that tab is the same as
1377 * the current one, return false.
1379 /* package */ boolean switchToTab(int index) {
1380 Tab tab = mTabControl.getTab(index);
1381 Tab currentTab = mTabControl.getCurrentTab();
1382 if (tab == null || tab == currentTab) {
1385 if (currentTab != null) {
1386 // currentTab may be null if it was just removed. In that case,
1387 // we do not need to remove it
1388 removeTabFromContentView(currentTab);
1390 mTabControl.setCurrentTab(tab);
1391 attachTabToContentView(tab);
1392 resetTitleIconAndProgress();
1393 updateLockIconToLatest();
1397 /* package */ Tab openTabToHomePage() {
1398 return openTabAndShow(mSettings.getHomePage(), false, null);
1401 /* package */ void closeCurrentWindow() {
1402 final Tab current = mTabControl.getCurrentTab();
1403 if (mTabControl.getTabCount() == 1) {
1404 // This is the last tab. Open a new one, with the home
1405 // page and close the current one.
1406 openTabToHomePage();
1410 final Tab parent = current.getParentTab();
1411 int indexToShow = -1;
1412 if (parent != null) {
1413 indexToShow = mTabControl.getTabIndex(parent);
1415 final int currentIndex = mTabControl.getCurrentIndex();
1416 // Try to move to the tab to the right
1417 indexToShow = currentIndex + 1;
1418 if (indexToShow > mTabControl.getTabCount() - 1) {
1419 // Try to move to the tab to the left
1420 indexToShow = currentIndex - 1;
1423 if (switchToTab(indexToShow)) {
1429 private ActiveTabsPage mActiveTabsPage;
1432 * Remove the active tabs page.
1433 * @param needToAttach If true, the active tabs page did not attach a tab
1434 * to the content view, so we need to do that here.
1436 /* package */ void removeActiveTabPage(boolean needToAttach) {
1437 mContentView.removeView(mActiveTabsPage);
1438 mActiveTabsPage = null;
1439 mMenuState = R.id.MAIN_MENU;
1441 attachTabToContentView(mTabControl.getCurrentTab());
1443 getTopWindow().requestFocus();
1447 public boolean onOptionsItemSelected(MenuItem item) {
1449 // The user has already fired a shortcut with this hold down of the
1453 if (null == getTopWindow()) {
1457 // The shortcut action consumes the MENU. Even if it is still down,
1458 // it won't trigger the next shortcut action. In the case of the
1459 // shortcut action triggering a new activity, like Bookmarks, we
1460 // won't get onKeyUp for MENU. So it is important to reset it here.
1461 mMenuIsDown = false;
1463 switch (item.getItemId()) {
1465 case R.id.new_tab_menu_id:
1466 openTabToHomePage();
1469 case R.id.goto_menu_id:
1473 case R.id.bookmarks_menu_id:
1474 bookmarksOrHistoryPicker(false);
1477 case R.id.active_tabs_menu_id:
1478 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1479 removeTabFromContentView(mTabControl.getCurrentTab());
1481 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1482 mActiveTabsPage.requestFocus();
1483 mMenuState = EMPTY_MENU;
1486 case R.id.add_bookmark_menu_id:
1487 Intent i = new Intent(BrowserActivity.this,
1488 AddBookmarkPage.class);
1489 WebView w = getTopWindow();
1490 i.putExtra("url", w.getUrl());
1491 i.putExtra("title", w.getTitle());
1492 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1493 i.putExtra("thumbnail", createScreenshot(w));
1497 case R.id.stop_reload_menu_id:
1501 getTopWindow().reload();
1505 case R.id.back_menu_id:
1506 getTopWindow().goBack();
1509 case R.id.forward_menu_id:
1510 getTopWindow().goForward();
1513 case R.id.close_menu_id:
1514 // Close the subwindow if it exists.
1515 if (mTabControl.getCurrentSubWindow() != null) {
1516 dismissSubWindow(mTabControl.getCurrentTab());
1519 closeCurrentWindow();
1522 case R.id.homepage_menu_id:
1523 Tab current = mTabControl.getCurrentTab();
1524 if (current != null) {
1525 dismissSubWindow(current);
1526 loadUrl(current.getWebView(), mSettings.getHomePage());
1530 case R.id.preferences_menu_id:
1531 Intent intent = new Intent(this,
1532 BrowserPreferencesPage.class);
1533 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1534 getTopWindow().getUrl());
1535 startActivityForResult(intent, PREFERENCES_PAGE);
1538 case R.id.find_menu_id:
1539 if (null == mFindDialog) {
1540 mFindDialog = new FindDialog(this);
1542 mFindDialog.setWebView(getTopWindow());
1544 mMenuState = EMPTY_MENU;
1547 case R.id.select_text_id:
1548 getTopWindow().emulateShiftHeld();
1550 case R.id.page_info_menu_id:
1551 showPageInfo(mTabControl.getCurrentTab(), false);
1554 case R.id.classic_history_menu_id:
1555 bookmarksOrHistoryPicker(true);
1558 case R.id.title_bar_share_page_url:
1559 case R.id.share_page_menu_id:
1560 Tab currentTab = mTabControl.getCurrentTab();
1561 if (null == currentTab) {
1565 currentTab.populatePickerData();
1566 sharePage(this, currentTab.getTitle(),
1567 currentTab.getUrl(), currentTab.getFavicon(),
1568 createScreenshot(currentTab.getWebView()));
1571 case R.id.dump_nav_menu_id:
1572 getTopWindow().debugDump();
1575 case R.id.dump_counters_menu_id:
1576 getTopWindow().dumpV8Counters();
1579 case R.id.zoom_in_menu_id:
1580 getTopWindow().zoomIn();
1583 case R.id.zoom_out_menu_id:
1584 getTopWindow().zoomOut();
1587 case R.id.view_downloads_menu_id:
1588 viewDownloads(null);
1591 case R.id.window_one_menu_id:
1592 case R.id.window_two_menu_id:
1593 case R.id.window_three_menu_id:
1594 case R.id.window_four_menu_id:
1595 case R.id.window_five_menu_id:
1596 case R.id.window_six_menu_id:
1597 case R.id.window_seven_menu_id:
1598 case R.id.window_eight_menu_id:
1600 int menuid = item.getItemId();
1601 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1602 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1603 Tab desiredTab = mTabControl.getTab(id);
1604 if (desiredTab != null &&
1605 desiredTab != mTabControl.getCurrentTab()) {
1615 if (!super.onOptionsItemSelected(item)) {
1618 // Otherwise fall through.
1624 public void closeFind() {
1625 mMenuState = R.id.MAIN_MENU;
1629 public boolean onPrepareOptionsMenu(Menu menu) {
1630 // This happens when the user begins to hold down the menu key, so
1631 // allow them to chord to get a shortcut.
1633 // Note: setVisible will decide whether an item is visible; while
1634 // setEnabled() will decide whether an item is enabled, which also means
1635 // whether the matching shortcut key will function.
1636 super.onPrepareOptionsMenu(menu);
1637 switch (mMenuState) {
1639 if (mCurrentMenuState != mMenuState) {
1640 menu.setGroupVisible(R.id.MAIN_MENU, false);
1641 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1642 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1646 if (mCurrentMenuState != mMenuState) {
1647 menu.setGroupVisible(R.id.MAIN_MENU, true);
1648 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1649 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1651 final WebView w = getTopWindow();
1652 boolean canGoBack = false;
1653 boolean canGoForward = false;
1654 boolean isHome = false;
1656 canGoBack = w.canGoBack();
1657 canGoForward = w.canGoForward();
1658 isHome = mSettings.getHomePage().equals(w.getUrl());
1660 final MenuItem back = menu.findItem(R.id.back_menu_id);
1661 back.setEnabled(canGoBack);
1663 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1664 home.setEnabled(!isHome);
1666 menu.findItem(R.id.forward_menu_id)
1667 .setEnabled(canGoForward);
1669 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1670 mTabControl.canCreateNewTab());
1672 // decide whether to show the share link option
1673 PackageManager pm = getPackageManager();
1674 Intent send = new Intent(Intent.ACTION_SEND);
1675 send.setType("text/plain");
1676 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1677 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1679 boolean isNavDump = mSettings.isNavDump();
1680 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1681 nav.setVisible(isNavDump);
1682 nav.setEnabled(isNavDump);
1684 boolean showDebugSettings = mSettings.showDebugSettings();
1685 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1686 counter.setVisible(showDebugSettings);
1687 counter.setEnabled(showDebugSettings);
1691 mCurrentMenuState = mMenuState;
1696 public void onCreateContextMenu(ContextMenu menu, View v,
1697 ContextMenuInfo menuInfo) {
1698 WebView webview = (WebView) v;
1699 WebView.HitTestResult result = webview.getHitTestResult();
1700 if (result == null) {
1704 int type = result.getType();
1705 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1707 "We should not show context menu when nothing is touched");
1710 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1711 // let TextView handles context menu
1715 // Note, http://b/issue?id=1106666 is requesting that
1716 // an inflated menu can be used again. This is not available
1717 // yet, so inflate each time (yuk!)
1718 MenuInflater inflater = getMenuInflater();
1719 inflater.inflate(R.menu.browsercontext, menu);
1721 // Show the correct menu group
1722 String extra = result.getExtra();
1723 menu.setGroupVisible(R.id.PHONE_MENU,
1724 type == WebView.HitTestResult.PHONE_TYPE);
1725 menu.setGroupVisible(R.id.EMAIL_MENU,
1726 type == WebView.HitTestResult.EMAIL_TYPE);
1727 menu.setGroupVisible(R.id.GEO_MENU,
1728 type == WebView.HitTestResult.GEO_TYPE);
1729 menu.setGroupVisible(R.id.IMAGE_MENU,
1730 type == WebView.HitTestResult.IMAGE_TYPE
1731 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1732 menu.setGroupVisible(R.id.ANCHOR_MENU,
1733 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1734 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1736 // Setup custom handling depending on the type
1738 case WebView.HitTestResult.PHONE_TYPE:
1739 menu.setHeaderTitle(Uri.decode(extra));
1740 menu.findItem(R.id.dial_context_menu_id).setIntent(
1741 new Intent(Intent.ACTION_VIEW, Uri
1742 .parse(WebView.SCHEME_TEL + extra)));
1743 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1744 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1745 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1746 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1748 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1752 case WebView.HitTestResult.EMAIL_TYPE:
1753 menu.setHeaderTitle(extra);
1754 menu.findItem(R.id.email_context_menu_id).setIntent(
1755 new Intent(Intent.ACTION_VIEW, Uri
1756 .parse(WebView.SCHEME_MAILTO + extra)));
1757 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1761 case WebView.HitTestResult.GEO_TYPE:
1762 menu.setHeaderTitle(extra);
1763 menu.findItem(R.id.map_context_menu_id).setIntent(
1764 new Intent(Intent.ACTION_VIEW, Uri
1765 .parse(WebView.SCHEME_GEO
1766 + URLEncoder.encode(extra))));
1767 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1771 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1772 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1773 TextView titleView = (TextView) LayoutInflater.from(this)
1774 .inflate(android.R.layout.browser_link_context_header,
1776 titleView.setText(extra);
1777 menu.setHeaderView(titleView);
1778 // decide whether to show the open link in new tab option
1779 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1780 mTabControl.canCreateNewTab());
1781 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1782 Bookmarks.urlHasAcceptableScheme(extra));
1783 PackageManager pm = getPackageManager();
1784 Intent send = new Intent(Intent.ACTION_SEND);
1785 send.setType("text/plain");
1786 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1787 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1788 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1791 // otherwise fall through to handle image part
1792 case WebView.HitTestResult.IMAGE_TYPE:
1793 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1794 menu.setHeaderTitle(extra);
1796 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1797 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1798 menu.findItem(R.id.download_context_menu_id).
1799 setOnMenuItemClickListener(new Download(extra));
1800 menu.findItem(R.id.set_wallpaper_context_menu_id).
1801 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1805 Log.w(LOGTAG, "We should not get here.");
1811 // Attach the given tab to the content view.
1812 // this should only be called for the current tab.
1813 private void attachTabToContentView(Tab t) {
1814 // Attach the container that contains the main WebView and any other UI
1815 // associated with the tab.
1816 t.attachTabToContentView(mContentView);
1818 if (mShouldShowErrorConsole) {
1819 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1820 if (errorConsole.numberOfErrors() == 0) {
1821 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1823 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1826 mErrorConsoleContainer.addView(errorConsole,
1827 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1828 ViewGroup.LayoutParams.WRAP_CONTENT));
1831 WebView view = t.getWebView();
1832 view.setEmbeddedTitleBar(mTitleBar);
1833 if (t.isInVoiceSearchMode()) {
1834 showVoiceTitleBar(t.getVoiceDisplayTitle());
1836 revertVoiceTitleBar();
1838 // Request focus on the top window.
1839 t.getTopWindow().requestFocus();
1842 // Attach a sub window to the main WebView of the given tab.
1843 void attachSubWindow(Tab t) {
1844 t.attachSubWindow(mContentView);
1845 getTopWindow().requestFocus();
1848 // Remove the given tab from the content view.
1849 private void removeTabFromContentView(Tab t) {
1850 // Remove the container that contains the main WebView.
1851 t.removeTabFromContentView(mContentView);
1853 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1854 if (errorConsole != null) {
1855 mErrorConsoleContainer.removeView(errorConsole);
1858 WebView view = t.getWebView();
1860 view.setEmbeddedTitleBar(null);
1864 // Remove the sub window if it exists. Also called by TabControl when the
1865 // user clicks the 'X' to dismiss a sub window.
1866 /* package */ void dismissSubWindow(Tab t) {
1867 t.removeSubWindow(mContentView);
1868 // dismiss the subwindow. This will destroy the WebView.
1869 t.dismissSubWindow();
1870 getTopWindow().requestFocus();
1873 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1874 // that accepts url as string.
1875 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1876 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1879 // This method does a ton of stuff. It will attempt to create a new tab
1880 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1881 // url isn't null, it will load the given url.
1882 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1884 final Tab currentTab = mTabControl.getCurrentTab();
1885 if (mTabControl.canCreateNewTab()) {
1886 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1888 WebView webview = tab.getWebView();
1889 // If the last tab was removed from the active tabs page, currentTab
1891 if (currentTab != null) {
1892 removeTabFromContentView(currentTab);
1894 // We must set the new tab as the current tab to reflect the old
1895 // animation behavior.
1896 mTabControl.setCurrentTab(tab);
1897 attachTabToContentView(tab);
1898 if (!urlData.isEmpty()) {
1899 loadUrlDataIn(tab, urlData);
1903 // Get rid of the subwindow if it exists
1904 dismissSubWindow(currentTab);
1905 if (!urlData.isEmpty()) {
1906 // Load the given url.
1907 loadUrlDataIn(currentTab, urlData);
1913 private Tab openTab(String url) {
1914 if (mSettings.openInBackground()) {
1915 Tab t = mTabControl.createNewTab();
1917 WebView view = t.getWebView();
1922 return openTabAndShow(url, false, null);
1926 private class Copy implements OnMenuItemClickListener {
1927 private CharSequence mText;
1929 public boolean onMenuItemClick(MenuItem item) {
1934 public Copy(CharSequence toCopy) {
1939 private class Download implements OnMenuItemClickListener {
1940 private String mText;
1942 public boolean onMenuItemClick(MenuItem item) {
1943 onDownloadStartNoStream(mText, null, null, null, -1);
1947 public Download(String toDownload) {
1952 private class SetAsWallpaper extends Thread implements
1953 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1955 private ProgressDialog mWallpaperProgress;
1956 private boolean mCanceled = false;
1958 public SetAsWallpaper(String url) {
1960 mUrl = new URL(url);
1961 } catch (MalformedURLException e) {
1966 public void onCancel(DialogInterface dialog) {
1970 public boolean onMenuItemClick(MenuItem item) {
1972 // The user may have tried to set a image with a large file size as their
1973 // background so it may take a few moments to perform the operation. Display
1974 // a progress spinner while it is working.
1975 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1976 mWallpaperProgress.setIndeterminate(true);
1977 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1978 mWallpaperProgress.setCancelable(true);
1979 mWallpaperProgress.setOnCancelListener(this);
1980 mWallpaperProgress.show();
1987 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1989 // TODO: This will cause the resource to be downloaded again, when we
1990 // should in most cases be able to grab it from the cache. To fix this
1991 // we should query WebCore to see if we can access a cached version and
1992 // instead open an input stream on that. This pattern could also be used
1993 // in the download manager where the same problem exists.
1994 InputStream inputstream = mUrl.openStream();
1995 if (inputstream != null) {
1996 setWallpaper(inputstream);
1998 } catch (IOException e) {
1999 Log.e(LOGTAG, "Unable to set new wallpaper");
2000 // Act as though the user canceled the operation so we try to
2001 // restore the old wallpaper.
2006 // Restore the old wallpaper if the user cancelled whilst we were setting
2007 // the new wallpaper.
2008 int width = oldWallpaper.getIntrinsicWidth();
2009 int height = oldWallpaper.getIntrinsicHeight();
2010 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2011 Canvas canvas = new Canvas(bm);
2012 oldWallpaper.setBounds(0, 0, width, height);
2013 oldWallpaper.draw(canvas);
2016 } catch (IOException e) {
2017 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2022 if (mWallpaperProgress.isShowing()) {
2023 mWallpaperProgress.dismiss();
2028 private void copy(CharSequence text) {
2030 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2032 clip.setClipboardText(text);
2034 } catch (android.os.RemoteException e) {
2035 Log.e(LOGTAG, "Copy failed", e);
2040 * Resets the browser title-view to whatever it must be
2041 * (for example, if we had a loading error)
2042 * When we have a new page, we call resetTitle, when we
2043 * have to reset the titlebar to whatever it used to be
2044 * (for example, if the user chose to stop loading), we
2045 * call resetTitleAndRevertLockIcon.
2047 /* package */ void resetTitleAndRevertLockIcon() {
2048 mTabControl.getCurrentTab().revertLockIcon();
2049 updateLockIconToLatest();
2050 resetTitleIconAndProgress();
2054 * Reset the title, favicon, and progress.
2056 private void resetTitleIconAndProgress() {
2057 WebView current = mTabControl.getCurrentWebView();
2058 if (current == null) {
2061 resetTitleAndIcon(current);
2062 int progress = current.getProgress();
2063 current.getWebChromeClient().onProgressChanged(current, progress);
2066 // Reset the title and the icon based on the given item.
2067 private void resetTitleAndIcon(WebView view) {
2068 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2070 setUrlTitle(item.getUrl(), item.getTitle());
2071 setFavicon(item.getFavicon());
2073 setUrlTitle(null, null);
2079 * Sets a title composed of the URL and the title string.
2080 * @param url The URL of the site being loaded.
2081 * @param title The title of the site being loaded.
2083 void setUrlTitle(String url, String title) {
2087 // If we are in voice search mode, the title has already been set.
2088 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2089 mTitleBar.setDisplayTitle(url);
2090 mFakeTitleBar.setDisplayTitle(url);
2094 * @param url The URL to build a title version of the URL from.
2095 * @return The title version of the URL or null if fails.
2096 * The title version of the URL can be either the URL hostname,
2097 * or the hostname with an "https://" prefix (for secure URLs),
2098 * or an empty string if, for example, the URL in question is a
2099 * file:// URL with no hostname.
2101 /* package */ static String buildTitleUrl(String url) {
2102 String titleUrl = null;
2106 // parse the url string
2107 URL urlObj = new URL(url);
2108 if (urlObj != null) {
2111 String protocol = urlObj.getProtocol();
2112 String host = urlObj.getHost();
2114 if (host != null && 0 < host.length()) {
2116 if (protocol != null) {
2117 // if a secure site, add an "https://" prefix!
2118 if (protocol.equalsIgnoreCase("https")) {
2119 titleUrl = protocol + "://" + host;
2124 } catch (MalformedURLException e) {}
2130 // Set the favicon in the title bar.
2131 void setFavicon(Bitmap icon) {
2132 mTitleBar.setFavicon(icon);
2133 mFakeTitleBar.setFavicon(icon);
2137 * Close the tab, remove its associated title bar, and adjust mTabControl's
2138 * current tab to a valid value.
2140 /* package */ void closeTab(Tab t) {
2141 int currentIndex = mTabControl.getCurrentIndex();
2142 int removeIndex = mTabControl.getTabIndex(t);
2143 mTabControl.removeTab(t);
2144 if (currentIndex >= removeIndex && currentIndex != 0) {
2147 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2148 resetTitleIconAndProgress();
2151 private void goBackOnePageOrQuit() {
2152 Tab current = mTabControl.getCurrentTab();
2153 if (current == null) {
2155 * Instead of finishing the activity, simply push this to the back
2156 * of the stack and let ActivityManager to choose the foreground
2157 * activity. As BrowserActivity is singleTask, it will be always the
2158 * root of the task. So we can use either true or false for
2161 moveTaskToBack(true);
2164 WebView w = current.getWebView();
2165 if (w.canGoBack()) {
2168 // Check to see if we are closing a window that was created by
2169 // another window. If so, we switch back to that window.
2170 Tab parent = current.getParentTab();
2171 if (parent != null) {
2172 switchToTab(mTabControl.getTabIndex(parent));
2173 // Now we close the other tab
2176 if (current.closeOnExit()) {
2177 // force the tab's inLoad() to be false as we are going to
2178 // either finish the activity or remove the tab. This will
2179 // ensure pauseWebViewTimers() taking action.
2180 mTabControl.getCurrentTab().clearInLoad();
2181 if (mTabControl.getTabCount() == 1) {
2185 // call pauseWebViewTimers() now, we won't be able to call
2186 // it in onPause() as the WebView won't be valid.
2187 // Temporarily change mActivityInPause to be true as
2188 // pauseWebViewTimers() will do nothing if mActivityInPause
2190 boolean savedState = mActivityInPause;
2192 Log.e(LOGTAG, "BrowserActivity is already paused "
2193 + "while handing goBackOnePageOrQuit.");
2195 mActivityInPause = true;
2196 pauseWebViewTimers();
2197 mActivityInPause = savedState;
2198 removeTabFromContentView(current);
2199 mTabControl.removeTab(current);
2202 * Instead of finishing the activity, simply push this to the back
2203 * of the stack and let ActivityManager to choose the foreground
2204 * activity. As BrowserActivity is singleTask, it will be always the
2205 * root of the task. So we can use either true or false for
2208 moveTaskToBack(true);
2213 boolean isMenuDown() {
2218 public boolean onKeyDown(int keyCode, KeyEvent event) {
2219 // Even if MENU is already held down, we need to call to super to open
2220 // the IME on long press.
2221 if (KeyEvent.KEYCODE_MENU == keyCode) {
2223 return super.onKeyDown(keyCode, event);
2225 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2226 // still down, we don't want to trigger the search. Pretend to consume
2227 // the key and do nothing.
2228 if (mMenuIsDown) return true;
2231 case KeyEvent.KEYCODE_SPACE:
2232 // WebView/WebTextView handle the keys in the KeyDown. As
2233 // the Activity's shortcut keys are only handled when WebView
2234 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2235 if (event.isShiftPressed()) {
2236 getTopWindow().pageUp(false);
2238 getTopWindow().pageDown(false);
2241 case KeyEvent.KEYCODE_BACK:
2242 if (event.getRepeatCount() == 0) {
2243 event.startTracking();
2245 } else if (mCustomView == null && mActiveTabsPage == null
2246 && event.isLongPress()) {
2247 bookmarksOrHistoryPicker(true);
2252 return super.onKeyDown(keyCode, event);
2256 public boolean onKeyUp(int keyCode, KeyEvent event) {
2258 case KeyEvent.KEYCODE_MENU:
2259 mMenuIsDown = false;
2261 case KeyEvent.KEYCODE_BACK:
2262 if (event.isTracking() && !event.isCanceled()) {
2263 if (mCustomView != null) {
2264 // if a custom view is showing, hide it
2265 mTabControl.getCurrentWebView().getWebChromeClient()
2266 .onHideCustomView();
2267 } else if (mActiveTabsPage != null) {
2268 // if tab page is showing, hide it
2269 removeActiveTabPage(true);
2271 WebView subwindow = mTabControl.getCurrentSubWindow();
2272 if (subwindow != null) {
2273 if (subwindow.canGoBack()) {
2276 dismissSubWindow(mTabControl.getCurrentTab());
2279 goBackOnePageOrQuit();
2286 return super.onKeyUp(keyCode, event);
2289 /* package */ void stopLoading() {
2290 mDidStopLoad = true;
2291 resetTitleAndRevertLockIcon();
2292 WebView w = getTopWindow();
2294 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2295 // same logic here. But for subwindow case, should we call into the main
2296 // WebView's onPageFinished as we never call its onPageStarted and if
2297 // the page finishes itself, we don't call onPageFinished.
2298 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2303 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2307 boolean didUserStopLoading() {
2308 return mDidStopLoad;
2311 private void cancelStopToast() {
2312 if (mStopToast != null) {
2313 mStopToast.cancel();
2318 // called by a UI or non-UI thread to post the message
2319 public void postMessage(int what, int arg1, int arg2, Object obj,
2321 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2325 // called by a UI or non-UI thread to remove the message
2326 void removeMessages(int what, Object object) {
2327 mHandler.removeMessages(what, object);
2330 // public message ids
2331 public final static int LOAD_URL = 1001;
2332 public final static int STOP_LOAD = 1002;
2335 private static final int FOCUS_NODE_HREF = 102;
2336 private static final int CANCEL_CREDS_REQUEST = 103;
2337 private static final int RELEASE_WAKELOCK = 107;
2339 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2341 // Private handler for handling javascript and saving passwords
2342 private Handler mHandler = new Handler() {
2344 public void handleMessage(Message msg) {
2346 case FOCUS_NODE_HREF:
2348 String url = (String) msg.getData().get("url");
2349 String title = (String) msg.getData().get("title");
2350 if (url == null || url.length() == 0) {
2353 HashMap focusNodeMap = (HashMap) msg.obj;
2354 WebView view = (WebView) focusNodeMap.get("webview");
2355 // Only apply the action if the top window did not change.
2356 if (getTopWindow() != view) {
2360 case R.id.open_context_menu_id:
2361 case R.id.view_image_context_menu_id:
2362 loadUrlFromContext(getTopWindow(), url);
2364 case R.id.open_newtab_context_menu_id:
2365 final Tab parent = mTabControl.getCurrentTab();
2366 final Tab newTab = openTab(url);
2367 if (newTab != parent) {
2368 parent.addChildTab(newTab);
2371 case R.id.bookmark_context_menu_id:
2372 Intent intent = new Intent(BrowserActivity.this,
2373 AddBookmarkPage.class);
2374 intent.putExtra("url", url);
2375 intent.putExtra("title", title);
2376 startActivity(intent);
2378 case R.id.share_link_context_menu_id:
2379 // See if this site has been visited before
2380 StringBuilder sb = new StringBuilder(
2381 Browser.BookmarkColumns.URL + " = ");
2382 DatabaseUtils.appendEscapedSQLString(sb, url);
2383 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2384 Browser.HISTORY_PROJECTION,
2388 if (c.moveToFirst()) {
2389 // The site has been visited before, so grab the
2390 // info from the database.
2391 Bitmap favicon = null;
2392 Bitmap thumbnail = null;
2393 String linkTitle = c.getString(Browser.
2394 HISTORY_PROJECTION_TITLE_INDEX);
2395 byte[] data = c.getBlob(Browser.
2396 HISTORY_PROJECTION_FAVICON_INDEX);
2398 favicon = BitmapFactory.decodeByteArray(
2399 data, 0, data.length);
2401 data = c.getBlob(Browser.
2402 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2404 thumbnail = BitmapFactory.decodeByteArray(
2405 data, 0, data.length);
2407 sharePage(BrowserActivity.this,
2408 linkTitle, url, favicon, thumbnail);
2410 Browser.sendString(BrowserActivity.this, url,
2412 R.string.choosertitle_sharevia));
2415 case R.id.copy_link_context_menu_id:
2418 case R.id.save_link_context_menu_id:
2419 case R.id.download_context_menu_id:
2420 onDownloadStartNoStream(url, null, null, null, -1);
2427 loadUrlFromContext(getTopWindow(), (String) msg.obj);
2434 case CANCEL_CREDS_REQUEST:
2435 resumeAfterCredentials();
2438 case RELEASE_WAKELOCK:
2439 if (mWakeLock.isHeld()) {
2440 mWakeLock.release();
2441 // if we reach here, Browser should be still in the
2442 // background loading after WAKELOCK_TIMEOUT (5-min).
2443 // To avoid burning the battery, stop loading.
2444 mTabControl.stopAllLoading();
2448 case UPDATE_BOOKMARK_THUMBNAIL:
2449 WebView view = (WebView) msg.obj;
2451 updateScreenshot(view);
2459 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2460 * an {@link Intent} to launch the Activity chooser.
2461 * @param c Context used to launch a new Activity.
2462 * @param title Title of the page. Stored in the Intent with
2463 * {@link Browser#EXTRA_SHARE_TITLE}
2464 * @param url URL of the page. Stored in the Intent with
2465 * {@link Intent#EXTRA_TEXT}
2466 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2467 * with {@link Browser#EXTRA_SHARE_FAVICON}
2468 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2469 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2471 public static final void sharePage(Context c, String title, String url,
2472 Bitmap favicon, Bitmap screenshot) {
2473 Intent send = new Intent(Intent.ACTION_SEND);
2474 send.setType("text/plain");
2475 send.putExtra(Intent.EXTRA_TEXT, url);
2476 send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2477 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2478 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2480 c.startActivity(Intent.createChooser(send, c.getString(
2481 R.string.choosertitle_sharevia)));
2482 } catch(android.content.ActivityNotFoundException ex) {
2483 // if no app handles it, do nothing
2487 private void updateScreenshot(WebView view) {
2488 // If this is a bookmarked site, add a screenshot to the database.
2489 // FIXME: When should we update? Every time?
2490 // FIXME: Would like to make sure there is actually something to
2491 // draw, but the API for that (WebViewCore.pictureReady()) is not
2492 // currently accessible here.
2494 ContentResolver cr = getContentResolver();
2495 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2496 cr, view.getOriginalUrl(), view.getUrl(), true);
2498 boolean succeed = c.moveToFirst();
2499 ContentValues values = null;
2501 if (values == null) {
2502 final ByteArrayOutputStream os
2503 = new ByteArrayOutputStream();
2504 Bitmap bm = createScreenshot(view);
2509 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2510 values = new ContentValues();
2511 values.put(Browser.BookmarkColumns.THUMBNAIL,
2514 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2515 c.getInt(0)), values, null, null);
2516 succeed = c.moveToNext();
2523 * Values for the size of the thumbnail created when taking a screenshot.
2524 * Lazily initialized. Instead of using these directly, use
2525 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2527 private static int THUMBNAIL_WIDTH = 0;
2528 private static int THUMBNAIL_HEIGHT = 0;
2531 * Return the desired width for thumbnail screenshots, which are stored in
2532 * the database, and used on the bookmarks screen.
2533 * @param context Context for finding out the density of the screen.
2534 * @return int desired width for thumbnail screenshot.
2536 /* package */ static int getDesiredThumbnailWidth(Context context) {
2537 if (THUMBNAIL_WIDTH == 0) {
2538 float density = context.getResources().getDisplayMetrics().density;
2539 THUMBNAIL_WIDTH = (int) (90 * density);
2540 THUMBNAIL_HEIGHT = (int) (80 * density);
2542 return THUMBNAIL_WIDTH;
2546 * Return the desired height for thumbnail screenshots, which are stored in
2547 * the database, and used on the bookmarks screen.
2548 * @param context Context for finding out the density of the screen.
2549 * @return int desired height for thumbnail screenshot.
2551 /* package */ static int getDesiredThumbnailHeight(Context context) {
2552 // To ensure that they are both initialized.
2553 getDesiredThumbnailWidth(context);
2554 return THUMBNAIL_HEIGHT;
2557 private Bitmap createScreenshot(WebView view) {
2558 Picture thumbnail = view.capturePicture();
2559 if (thumbnail == null) {
2562 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2563 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2564 Canvas canvas = new Canvas(bm);
2565 // May need to tweak these values to determine what is the
2566 // best scale factor
2567 int thumbnailWidth = thumbnail.getWidth();
2568 int thumbnailHeight = thumbnail.getHeight();
2569 float scaleFactorX = 1.0f;
2570 float scaleFactorY = 1.0f;
2571 if (thumbnailWidth > 0) {
2572 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2573 (float)thumbnailWidth;
2578 if (view.getWidth() > view.getHeight() &&
2579 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2580 // If the device is in landscape and the page is shorter
2581 // than the height of the view, stretch the thumbnail to fill the
2583 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2584 (float)thumbnailHeight;
2586 // In the portrait case, this looks nice.
2587 scaleFactorY = scaleFactorX;
2590 canvas.scale(scaleFactorX, scaleFactorY);
2592 thumbnail.draw(canvas);
2596 // -------------------------------------------------------------------------
2597 // Helper function for WebViewClient.
2598 //-------------------------------------------------------------------------
2600 // Use in overrideUrlLoading
2601 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2602 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2603 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2604 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2606 // Keep this initial progress in sync with initialProgressValue (* 100)
2607 // in ProgressTracker.cpp
2608 private final static int INITIAL_PROGRESS = 10;
2610 void onPageStarted(WebView view, String url, Bitmap favicon) {
2611 // when BrowserActivity just starts, onPageStarted may be called before
2612 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2613 // to start the timer. As we won't switch tabs while an activity is in
2614 // pause state, we can ensure calling resume and pause in pair.
2615 if (mActivityInPause) resumeWebViewTimers();
2618 setUrlTitle(url, null);
2619 setFavicon(favicon);
2620 // Show some progress so that the user knows the page is beginning to
2622 onProgressChanged(view, INITIAL_PROGRESS);
2623 mDidStopLoad = false;
2624 if (!mIsNetworkUp) createAndShowNetworkDialog();
2626 if (mSettings.isTracing()) {
2629 WebAddress uri = new WebAddress(url);
2631 } catch (android.net.ParseException ex) {
2634 host = host.replace('.', '_');
2637 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2640 // Performance probe
2642 mStart = SystemClock.uptimeMillis();
2643 mProcessStart = Process.getElapsedCpuTime();
2644 long[] sysCpu = new long[7];
2645 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2647 mUserStart = sysCpu[0] + sysCpu[1];
2648 mSystemStart = sysCpu[2];
2649 mIdleStart = sysCpu[3];
2650 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2652 mUiStart = SystemClock.currentThreadTimeMillis();
2656 void onPageFinished(WebView view, String url) {
2657 // Reset the title and icon in case we stopped a provisional load.
2658 resetTitleAndIcon(view);
2659 // Update the lock icon image only once we are done loading
2660 updateLockIconToLatest();
2661 // pause the WebView timer and release the wake lock if it is finished
2662 // while BrowserActivity is in pause state.
2663 if (mActivityInPause && pauseWebViewTimers()) {
2664 if (mWakeLock.isHeld()) {
2665 mHandler.removeMessages(RELEASE_WAKELOCK);
2666 mWakeLock.release();
2670 // Performance probe
2672 long[] sysCpu = new long[7];
2673 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2675 String uiInfo = "UI thread used "
2676 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2679 Log.d(LOGTAG, uiInfo);
2681 //The string that gets written to the log
2682 String performanceString = "It took total "
2683 + (SystemClock.uptimeMillis() - mStart)
2684 + " ms clock time to load the page."
2685 + "\nbrowser process used "
2686 + (Process.getElapsedCpuTime() - mProcessStart)
2687 + " ms, user processes used "
2688 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2689 + " ms, kernel used "
2690 + (sysCpu[2] - mSystemStart) * 10
2691 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2692 + " ms and irq took "
2693 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2694 * 10 + " ms, " + uiInfo;
2696 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2699 // strip the url to maintain consistency
2700 String newUrl = new String(url);
2701 if (newUrl.startsWith("http://www.")) {
2702 newUrl = newUrl.substring(11);
2703 } else if (newUrl.startsWith("http://")) {
2704 newUrl = newUrl.substring(7);
2705 } else if (newUrl.startsWith("https://www.")) {
2706 newUrl = newUrl.substring(12);
2707 } else if (newUrl.startsWith("https://")) {
2708 newUrl = newUrl.substring(8);
2711 Log.d(LOGTAG, newUrl + " loaded");
2719 Debug.stopMethodTracing();
2723 boolean shouldOverrideUrlLoading(WebView view, String url) {
2724 if (url.startsWith(SCHEME_WTAI)) {
2725 // wtai://wp/mc;number
2726 // number=string(phone-number)
2727 if (url.startsWith(SCHEME_WTAI_MC)) {
2728 Intent intent = new Intent(Intent.ACTION_VIEW,
2729 Uri.parse(WebView.SCHEME_TEL +
2730 url.substring(SCHEME_WTAI_MC.length())));
2731 startActivity(intent);
2734 // wtai://wp/sd;dtmf
2735 // dtmf=string(dialstring)
2736 if (url.startsWith(SCHEME_WTAI_SD)) {
2737 // TODO: only send when there is active voice connection
2740 // wtai://wp/ap;number;name
2741 // number=string(phone-number)
2743 if (url.startsWith(SCHEME_WTAI_AP)) {
2749 // The "about:" schemes are internal to the browser; don't want these to
2750 // be dispatched to other apps.
2751 if (url.startsWith("about:")) {
2756 // perform generic parsing of the URI to turn it into an Intent.
2758 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2759 } catch (URISyntaxException ex) {
2760 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2764 // check whether the intent can be resolved. If not, we will see
2765 // whether we can download it from the Market.
2766 if (getPackageManager().resolveActivity(intent, 0) == null) {
2767 String packagename = intent.getPackage();
2768 if (packagename != null) {
2769 intent = new Intent(Intent.ACTION_VIEW, Uri
2770 .parse("market://search?q=pname:" + packagename));
2771 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2772 startActivity(intent);
2779 // sanitize the Intent, ensuring web pages can not bypass browser
2780 // security (only access to BROWSABLE activities).
2781 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2782 intent.setComponent(null);
2784 if (startActivityIfNeeded(intent, -1)) {
2787 } catch (ActivityNotFoundException ex) {
2788 // ignore the error. If no application can handle the URL,
2789 // eg about:blank, assume the browser can handle it.
2800 // -------------------------------------------------------------------------
2801 // Helper function for WebChromeClient
2802 // -------------------------------------------------------------------------
2804 void onProgressChanged(WebView view, int newProgress) {
2805 mTitleBar.setProgress(newProgress);
2806 mFakeTitleBar.setProgress(newProgress);
2808 if (newProgress == 100) {
2809 // onProgressChanged() may continue to be called after the main
2810 // frame has finished loading, as any remaining sub frames continue
2811 // to load. We'll only get called once though with newProgress as
2812 // 100 when everything is loaded. (onPageFinished is called once
2813 // when the main frame completes loading regardless of the state of
2814 // any sub frames so calls to onProgressChanges may continue after
2815 // onPageFinished has executed)
2818 updateInLoadMenuItems();
2819 // If the options menu is open, leave the title bar
2820 if (!mOptionsMenuOpen || !mIconView) {
2824 } else if (!mInLoad) {
2825 // onPageFinished may have already been called but a subframe is
2826 // still loading and updating the progress. Reset mInLoad and update
2829 updateInLoadMenuItems();
2830 if (!mOptionsMenuOpen || mIconView) {
2831 // This page has begun to load, so show the title bar
2837 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2838 // if a view already exists then immediately terminate the new one
2839 if (mCustomView != null) {
2840 callback.onCustomViewHidden();
2844 // Add the custom view to its container.
2845 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2847 mCustomViewCallback = callback;
2848 // Save the menu state and set it to empty while the custom
2850 mOldMenuState = mMenuState;
2851 mMenuState = EMPTY_MENU;
2852 // Hide the content view.
2853 mContentView.setVisibility(View.GONE);
2854 // Finally show the custom view container.
2855 setStatusBarVisibility(false);
2856 mCustomViewContainer.setVisibility(View.VISIBLE);
2857 mCustomViewContainer.bringToFront();
2860 void onHideCustomView() {
2861 if (mCustomView == null)
2864 // Hide the custom view.
2865 mCustomView.setVisibility(View.GONE);
2866 // Remove the custom view from its container.
2867 mCustomViewContainer.removeView(mCustomView);
2869 // Reset the old menu state.
2870 mMenuState = mOldMenuState;
2871 mOldMenuState = EMPTY_MENU;
2872 mCustomViewContainer.setVisibility(View.GONE);
2873 mCustomViewCallback.onCustomViewHidden();
2874 // Show the content view.
2875 setStatusBarVisibility(true);
2876 mContentView.setVisibility(View.VISIBLE);
2879 Bitmap getDefaultVideoPoster() {
2880 if (mDefaultVideoPoster == null) {
2881 mDefaultVideoPoster = BitmapFactory.decodeResource(
2882 getResources(), R.drawable.default_video_poster);
2884 return mDefaultVideoPoster;
2887 View getVideoLoadingProgressView() {
2888 if (mVideoProgressView == null) {
2889 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2890 mVideoProgressView = inflater.inflate(
2891 R.layout.video_loading_progress, null);
2893 return mVideoProgressView;
2897 * The Object used to inform the WebView of the file to upload.
2899 private ValueCallback<Uri> mUploadMessage;
2901 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2902 if (mUploadMessage != null) return;
2903 mUploadMessage = uploadMsg;
2904 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2905 i.addCategory(Intent.CATEGORY_OPENABLE);
2907 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2908 getString(R.string.choose_upload)), FILE_SELECTED);
2911 // -------------------------------------------------------------------------
2912 // Implement functions for DownloadListener
2913 // -------------------------------------------------------------------------
2916 * Notify the host application a download should be done, or that
2917 * the data should be streamed if a streaming viewer is available.
2918 * @param url The full url to the content that should be downloaded
2919 * @param contentDisposition Content-disposition http header, if
2921 * @param mimetype The mimetype of the content reported by the server
2922 * @param contentLength The file size reported by the server
2924 public void onDownloadStart(String url, String userAgent,
2925 String contentDisposition, String mimetype, long contentLength) {
2926 // if we're dealing wih A/V content that's not explicitly marked
2927 // for download, check if it's streamable.
2928 if (contentDisposition == null
2929 || !contentDisposition.regionMatches(
2930 true, 0, "attachment", 0, 10)) {
2931 // query the package manager to see if there's a registered handler
2933 Intent intent = new Intent(Intent.ACTION_VIEW);
2934 intent.setDataAndType(Uri.parse(url), mimetype);
2935 ResolveInfo info = getPackageManager().resolveActivity(intent,
2936 PackageManager.MATCH_DEFAULT_ONLY);
2938 ComponentName myName = getComponentName();
2939 // If we resolved to ourselves, we don't want to attempt to
2940 // load the url only to try and download it again.
2941 if (!myName.getPackageName().equals(
2942 info.activityInfo.packageName)
2943 || !myName.getClassName().equals(
2944 info.activityInfo.name)) {
2945 // someone (other than us) knows how to handle this mime
2946 // type with this scheme, don't download.
2948 startActivity(intent);
2950 } catch (ActivityNotFoundException ex) {
2952 Log.d(LOGTAG, "activity not found for " + mimetype
2953 + " over " + Uri.parse(url).getScheme(),
2956 // Best behavior is to fall back to a download in this
2962 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2966 * Notify the host application a download should be done, even if there
2967 * is a streaming viewer available for thise type.
2968 * @param url The full url to the content that should be downloaded
2969 * @param contentDisposition Content-disposition http header, if
2971 * @param mimetype The mimetype of the content reported by the server
2972 * @param contentLength The file size reported by the server
2974 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2975 String contentDisposition, String mimetype, long contentLength) {
2977 String filename = URLUtil.guessFileName(url,
2978 contentDisposition, mimetype);
2980 // Check to see if we have an SDCard
2981 String status = Environment.getExternalStorageState();
2982 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2986 // Check to see if the SDCard is busy, same as the music app
2987 if (status.equals(Environment.MEDIA_SHARED)) {
2988 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2989 title = R.string.download_sdcard_busy_dlg_title;
2991 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2992 title = R.string.download_no_sdcard_dlg_title;
2995 new AlertDialog.Builder(this)
2997 .setIcon(android.R.drawable.ic_dialog_alert)
2999 .setPositiveButton(R.string.ok, null)
3004 // java.net.URI is a lot stricter than KURL so we have to undo
3005 // KURL's percent-encoding and redo the encoding using java.net.URI.
3008 // Undo the percent-encoding that KURL may have done.
3009 String newUrl = new String(URLUtil.decode(url.getBytes()));
3010 // Parse the url into pieces
3011 WebAddress w = new WebAddress(newUrl);
3013 String query = null;
3014 String path = w.mPath;
3015 // Break the path into path, query, and fragment
3016 if (path.length() > 0) {
3017 // Strip the fragment
3018 int idx = path.lastIndexOf('#');
3020 frag = path.substring(idx + 1);
3021 path = path.substring(0, idx);
3023 idx = path.lastIndexOf('?');
3025 query = path.substring(idx + 1);
3026 path = path.substring(0, idx);
3029 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3031 } catch (Exception e) {
3032 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3036 // XXX: Have to use the old url since the cookies were stored using the
3037 // old percent-encoded url.
3038 String cookies = CookieManager.getInstance().getCookie(url);
3040 ContentValues values = new ContentValues();
3041 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3042 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3043 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3044 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
3046 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
3047 BrowserDownloadPage.class.getCanonicalName());
3048 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3049 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3050 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3051 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3052 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
3053 if (contentLength > 0) {
3054 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
3056 if (mimetype == null) {
3057 // We must have long pressed on a link or image to download it. We
3058 // are not sure of the mimetype in this case, so do a head request
3059 new FetchUrlMimeType(this).execute(values);
3061 final Uri contentUri =
3062 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
3067 // -------------------------------------------------------------------------
3070 * Resets the lock icon. This method is called when we start a new load and
3071 * know the url to be loaded.
3073 private void resetLockIcon(String url) {
3074 // Save the lock-icon state (we revert to it if the load gets cancelled)
3075 mTabControl.getCurrentTab().resetLockIcon(url);
3076 updateLockIconImage(LOCK_ICON_UNSECURE);
3080 * Update the lock icon to correspond to our latest state.
3082 private void updateLockIconToLatest() {
3083 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
3087 * Updates the lock-icon image in the title-bar.
3089 private void updateLockIconImage(int lockIconType) {
3091 if (lockIconType == LOCK_ICON_SECURE) {
3093 } else if (lockIconType == LOCK_ICON_MIXED) {
3096 mTitleBar.setLock(d);
3097 mFakeTitleBar.setLock(d);
3101 * Displays a page-info dialog.
3102 * @param tab The tab to show info about
3103 * @param fromShowSSLCertificateOnError The flag that indicates whether
3104 * this dialog was opened from the SSL-certificate-on-error dialog or
3105 * not. This is important, since we need to know whether to return to
3106 * the parent dialog or simply dismiss.
3108 private void showPageInfo(final Tab tab,
3109 final boolean fromShowSSLCertificateOnError) {
3110 final LayoutInflater factory = LayoutInflater
3113 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3115 final WebView view = tab.getWebView();
3118 String title = null;
3122 title = tab.getTitle();
3123 } else if (view == mTabControl.getCurrentWebView()) {
3124 // Use the cached title and url if this is the current WebView
3128 url = view.getUrl();
3129 title = view.getTitle();
3135 if (title == null) {
3139 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3140 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3142 mPageInfoView = tab;
3143 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3145 AlertDialog.Builder alertDialogBuilder =
3146 new AlertDialog.Builder(this)
3147 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3148 .setView(pageInfoView)
3151 new DialogInterface.OnClickListener() {
3152 public void onClick(DialogInterface dialog,
3154 mPageInfoDialog = null;
3155 mPageInfoView = null;
3157 // if we came here from the SSL error dialog
3158 if (fromShowSSLCertificateOnError) {
3159 // go back to the SSL error dialog
3160 showSSLCertificateOnError(
3161 mSSLCertificateOnErrorView,
3162 mSSLCertificateOnErrorHandler,
3163 mSSLCertificateOnErrorError);
3167 .setOnCancelListener(
3168 new DialogInterface.OnCancelListener() {
3169 public void onCancel(DialogInterface dialog) {
3170 mPageInfoDialog = null;
3171 mPageInfoView = null;
3173 // if we came here from the SSL error dialog
3174 if (fromShowSSLCertificateOnError) {
3175 // go back to the SSL error dialog
3176 showSSLCertificateOnError(
3177 mSSLCertificateOnErrorView,
3178 mSSLCertificateOnErrorHandler,
3179 mSSLCertificateOnErrorError);
3184 // if we have a main top-level page SSL certificate set or a certificate
3186 if (fromShowSSLCertificateOnError ||
3187 (view != null && view.getCertificate() != null)) {
3188 // add a 'View Certificate' button
3189 alertDialogBuilder.setNeutralButton(
3190 R.string.view_certificate,
3191 new DialogInterface.OnClickListener() {
3192 public void onClick(DialogInterface dialog,
3194 mPageInfoDialog = null;
3195 mPageInfoView = null;
3197 // if we came here from the SSL error dialog
3198 if (fromShowSSLCertificateOnError) {
3199 // go back to the SSL error dialog
3200 showSSLCertificateOnError(
3201 mSSLCertificateOnErrorView,
3202 mSSLCertificateOnErrorHandler,
3203 mSSLCertificateOnErrorError);
3205 // otherwise, display the top-most certificate from
3207 if (view.getCertificate() != null) {
3208 showSSLCertificate(tab);
3215 mPageInfoDialog = alertDialogBuilder.show();
3219 * Displays the main top-level page SSL certificate dialog
3220 * (accessible from the Page-Info dialog).
3221 * @param tab The tab to show certificate for.
3223 private void showSSLCertificate(final Tab tab) {
3224 final View certificateView =
3225 inflateCertificateView(tab.getWebView().getCertificate());
3226 if (certificateView == null) {
3230 LayoutInflater factory = LayoutInflater.from(this);
3232 final LinearLayout placeholder =
3233 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3235 LinearLayout ll = (LinearLayout) factory.inflate(
3236 R.layout.ssl_success, placeholder);
3237 ((TextView)ll.findViewById(R.id.success))
3238 .setText(R.string.ssl_certificate_is_valid);
3240 mSSLCertificateView = tab;
3241 mSSLCertificateDialog =
3242 new AlertDialog.Builder(this)
3243 .setTitle(R.string.ssl_certificate).setIcon(
3244 R.drawable.ic_dialog_browser_certificate_secure)
3245 .setView(certificateView)
3246 .setPositiveButton(R.string.ok,
3247 new DialogInterface.OnClickListener() {
3248 public void onClick(DialogInterface dialog,
3250 mSSLCertificateDialog = null;
3251 mSSLCertificateView = null;
3253 showPageInfo(tab, false);
3256 .setOnCancelListener(
3257 new DialogInterface.OnCancelListener() {
3258 public void onCancel(DialogInterface dialog) {
3259 mSSLCertificateDialog = null;
3260 mSSLCertificateView = null;
3262 showPageInfo(tab, false);
3269 * Displays the SSL error certificate dialog.
3270 * @param view The target web-view.
3271 * @param handler The SSL error handler responsible for cancelling the
3272 * connection that resulted in an SSL error or proceeding per user request.
3273 * @param error The SSL error object.
3275 void showSSLCertificateOnError(
3276 final WebView view, final SslErrorHandler handler, final SslError error) {
3278 final View certificateView =
3279 inflateCertificateView(error.getCertificate());
3280 if (certificateView == null) {
3284 LayoutInflater factory = LayoutInflater.from(this);
3286 final LinearLayout placeholder =
3287 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3289 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3290 LinearLayout ll = (LinearLayout)factory
3291 .inflate(R.layout.ssl_warning, placeholder);
3292 ((TextView)ll.findViewById(R.id.warning))
3293 .setText(R.string.ssl_untrusted);
3296 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3297 LinearLayout ll = (LinearLayout)factory
3298 .inflate(R.layout.ssl_warning, placeholder);
3299 ((TextView)ll.findViewById(R.id.warning))
3300 .setText(R.string.ssl_mismatch);
3303 if (error.hasError(SslError.SSL_EXPIRED)) {
3304 LinearLayout ll = (LinearLayout)factory
3305 .inflate(R.layout.ssl_warning, placeholder);
3306 ((TextView)ll.findViewById(R.id.warning))
3307 .setText(R.string.ssl_expired);
3310 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3311 LinearLayout ll = (LinearLayout)factory
3312 .inflate(R.layout.ssl_warning, placeholder);
3313 ((TextView)ll.findViewById(R.id.warning))
3314 .setText(R.string.ssl_not_yet_valid);
3317 mSSLCertificateOnErrorHandler = handler;
3318 mSSLCertificateOnErrorView = view;
3319 mSSLCertificateOnErrorError = error;
3320 mSSLCertificateOnErrorDialog =
3321 new AlertDialog.Builder(this)
3322 .setTitle(R.string.ssl_certificate).setIcon(
3323 R.drawable.ic_dialog_browser_certificate_partially_secure)
3324 .setView(certificateView)
3325 .setPositiveButton(R.string.ok,
3326 new DialogInterface.OnClickListener() {
3327 public void onClick(DialogInterface dialog,
3329 mSSLCertificateOnErrorDialog = null;
3330 mSSLCertificateOnErrorView = null;
3331 mSSLCertificateOnErrorHandler = null;
3332 mSSLCertificateOnErrorError = null;
3334 view.getWebViewClient().onReceivedSslError(
3335 view, handler, error);
3338 .setNeutralButton(R.string.page_info_view,
3339 new DialogInterface.OnClickListener() {
3340 public void onClick(DialogInterface dialog,
3342 mSSLCertificateOnErrorDialog = null;
3344 // do not clear the dialog state: we will
3345 // need to show the dialog again once the
3346 // user is done exploring the page-info details
3348 showPageInfo(mTabControl.getTabFromView(view),
3352 .setOnCancelListener(
3353 new DialogInterface.OnCancelListener() {
3354 public void onCancel(DialogInterface dialog) {
3355 mSSLCertificateOnErrorDialog = null;
3356 mSSLCertificateOnErrorView = null;
3357 mSSLCertificateOnErrorHandler = null;
3358 mSSLCertificateOnErrorError = null;
3360 view.getWebViewClient().onReceivedSslError(
3361 view, handler, error);
3368 * Inflates the SSL certificate view (helper method).
3369 * @param certificate The SSL certificate.
3370 * @return The resultant certificate view with issued-to, issued-by,
3371 * issued-on, expires-on, and possibly other fields set.
3372 * If the input certificate is null, returns null.
3374 private View inflateCertificateView(SslCertificate certificate) {
3375 if (certificate == null) {
3379 LayoutInflater factory = LayoutInflater.from(this);
3381 View certificateView = factory.inflate(
3382 R.layout.ssl_certificate, null);
3385 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3386 if (issuedTo != null) {
3387 ((TextView) certificateView.findViewById(R.id.to_common))
3388 .setText(issuedTo.getCName());
3389 ((TextView) certificateView.findViewById(R.id.to_org))
3390 .setText(issuedTo.getOName());
3391 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3392 .setText(issuedTo.getUName());
3396 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3397 if (issuedBy != null) {
3398 ((TextView) certificateView.findViewById(R.id.by_common))
3399 .setText(issuedBy.getCName());
3400 ((TextView) certificateView.findViewById(R.id.by_org))
3401 .setText(issuedBy.getOName());
3402 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3403 .setText(issuedBy.getUName());
3407 String issuedOn = reformatCertificateDate(
3408 certificate.getValidNotBefore());
3409 ((TextView) certificateView.findViewById(R.id.issued_on))
3413 String expiresOn = reformatCertificateDate(
3414 certificate.getValidNotAfter());
3415 ((TextView) certificateView.findViewById(R.id.expires_on))
3416 .setText(expiresOn);
3418 return certificateView;
3422 * Re-formats the certificate date (Date.toString()) string to
3423 * a properly localized date string.
3424 * @return Properly localized version of the certificate date string and
3425 * the original certificate date string if fails to localize.
3426 * If the original string is null, returns an empty string "".
3428 private String reformatCertificateDate(String certificateDate) {
3429 String reformattedDate = null;
3431 if (certificateDate != null) {
3434 date = java.text.DateFormat.getInstance().parse(certificateDate);
3435 } catch (ParseException e) {
3441 DateFormat.getDateFormat(this).format(date);
3445 return reformattedDate != null ? reformattedDate :
3446 (certificateDate != null ? certificateDate : "");
3450 * Displays an http-authentication dialog.
3452 void showHttpAuthentication(final HttpAuthHandler handler,
3453 final String host, final String realm, final String title,
3454 final String name, final String password, int focusId) {
3455 LayoutInflater factory = LayoutInflater.from(this);
3456 final View v = factory
3457 .inflate(R.layout.http_authentication, null);
3459 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3461 if (password != null) {
3462 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3465 String titleText = title;
3466 if (titleText == null) {
3467 titleText = getText(R.string.sign_in_to).toString().replace(
3468 "%s1", host).replace("%s2", realm);
3471 mHttpAuthHandler = handler;
3472 AlertDialog dialog = new AlertDialog.Builder(this)
3473 .setTitle(titleText)
3474 .setIcon(android.R.drawable.ic_dialog_alert)
3476 .setPositiveButton(R.string.action,
3477 new DialogInterface.OnClickListener() {
3478 public void onClick(DialogInterface dialog,
3480 String nm = ((EditText) v
3481 .findViewById(R.id.username_edit))
3482 .getText().toString();
3483 String pw = ((EditText) v
3484 .findViewById(R.id.password_edit))
3485 .getText().toString();
3486 BrowserActivity.this.setHttpAuthUsernamePassword
3487 (host, realm, nm, pw);
3488 handler.proceed(nm, pw);
3489 mHttpAuthenticationDialog = null;
3490 mHttpAuthHandler = null;
3492 .setNegativeButton(R.string.cancel,
3493 new DialogInterface.OnClickListener() {
3494 public void onClick(DialogInterface dialog,
3497 BrowserActivity.this.resetTitleAndRevertLockIcon();
3498 mHttpAuthenticationDialog = null;
3499 mHttpAuthHandler = null;
3501 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3502 public void onCancel(DialogInterface dialog) {
3504 BrowserActivity.this.resetTitleAndRevertLockIcon();
3505 mHttpAuthenticationDialog = null;
3506 mHttpAuthHandler = null;
3509 // Make the IME appear when the dialog is displayed if applicable.
3510 dialog.getWindow().setSoftInputMode(
3511 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3514 dialog.findViewById(focusId).requestFocus();
3516 v.findViewById(R.id.username_edit).requestFocus();
3518 mHttpAuthenticationDialog = dialog;
3521 public int getProgress() {
3522 WebView w = mTabControl.getCurrentWebView();
3524 return w.getProgress();
3531 * Set HTTP authentication password.
3533 * @param host The host for the password
3534 * @param realm The realm for the password
3535 * @param username The username for the password. If it is null, it means
3536 * password can't be saved.
3537 * @param password The password
3539 public void setHttpAuthUsernamePassword(String host, String realm,
3542 WebView w = mTabControl.getCurrentWebView();
3544 w.setHttpAuthUsernamePassword(host, realm, username, password);
3549 * connectivity manager says net has come or gone... inform the user
3550 * @param up true if net has come up, false if net has gone down
3552 public void onNetworkToggle(boolean up) {
3553 if (up == mIsNetworkUp) {
3556 mIsNetworkUp = true;
3557 if (mAlertDialog != null) {
3558 mAlertDialog.cancel();
3559 mAlertDialog = null;
3562 mIsNetworkUp = false;
3564 createAndShowNetworkDialog();
3567 WebView w = mTabControl.getCurrentWebView();
3569 w.setNetworkAvailable(up);
3573 boolean isNetworkUp() {
3574 return mIsNetworkUp;
3577 // This method shows the network dialog alerting the user that the net is
3578 // down. It will only show the dialog if mAlertDialog is null.
3579 private void createAndShowNetworkDialog() {
3580 if (mAlertDialog == null) {
3581 mAlertDialog = new AlertDialog.Builder(this)
3582 .setTitle(R.string.loadSuspendedTitle)
3583 .setMessage(R.string.loadSuspended)
3584 .setPositiveButton(R.string.ok, null)
3590 protected void onActivityResult(int requestCode, int resultCode,
3592 if (getTopWindow() == null) return;
3594 switch (requestCode) {
3596 if (resultCode == RESULT_OK && intent != null) {
3597 String data = intent.getAction();
3598 Bundle extras = intent.getExtras();
3599 if (extras != null && extras.getBoolean("new_window", false)) {
3602 final Tab currentTab =
3603 mTabControl.getCurrentTab();
3604 dismissSubWindow(currentTab);
3605 if (data != null && data.length() != 0) {
3606 loadUrl(getTopWindow(), data);
3610 // Deliberately fall through to PREFERENCES_PAGE, since the
3611 // same extra may be attached to the COMBO_PAGE
3612 case PREFERENCES_PAGE:
3613 if (resultCode == RESULT_OK && intent != null) {
3614 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3615 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3616 mTabControl.removeParentChildRelationShips();
3620 // Choose a file from the file picker.
3622 if (null == mUploadMessage) break;
3623 Uri result = intent == null || resultCode != RESULT_OK ? null
3625 mUploadMessage.onReceiveValue(result);
3626 mUploadMessage = null;
3631 getTopWindow().requestFocus();
3635 * This method is called as a result of the user selecting the options
3636 * menu to see the download window. It shows the download window on top of
3637 * the current window.
3639 private void viewDownloads(Uri downloadRecord) {
3640 Intent intent = new Intent(this,
3641 BrowserDownloadPage.class);
3642 intent.setData(downloadRecord);
3643 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3649 * @param startWithHistory If true, open starting on the history tab.
3650 * Otherwise, start with the bookmarks tab.
3652 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3653 WebView current = mTabControl.getCurrentWebView();
3654 if (current == null) {
3657 Intent intent = new Intent(this,
3658 CombinedBookmarkHistoryActivity.class);
3659 String title = current.getTitle();
3660 String url = current.getUrl();
3661 Bitmap thumbnail = createScreenshot(current);
3663 // Just in case the user opens bookmarks before a page finishes loading
3664 // so the current history item, and therefore the page, is null.
3666 url = mLastEnteredUrl;
3669 url = mSettings.getHomePage();
3672 // In case the web page has not yet received its associated title.
3673 if (title == null) {
3676 intent.putExtra("title", title);
3677 intent.putExtra("url", url);
3678 intent.putExtra("thumbnail", thumbnail);
3679 // Disable opening in a new window if we have maxed out the windows
3680 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3681 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3682 if (startWithHistory) {
3683 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3684 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3686 startActivityForResult(intent, COMBO_PAGE);
3689 // Called when loading from context menu or LOAD_URL message
3690 private void loadUrlFromContext(WebView view, String url) {
3691 // In case the user enters nothing.
3692 if (url != null && url.length() != 0 && view != null) {
3693 url = smartUrlFilter(url);
3694 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3701 * Load the URL into the given WebView and update the title bar
3702 * to reflect the new load. Call this instead of WebView.loadUrl
3704 * @param view The WebView used to load url.
3705 * @param url The URL to load.
3707 private void loadUrl(WebView view, String url) {
3708 updateTitleBarForNewLoad(view, url);
3713 * Load UrlData into a Tab and update the title bar to reflect the new
3714 * load. Call this instead of UrlData.loadIn directly.
3715 * @param t The Tab used to load.
3716 * @param data The UrlData being loaded.
3718 private void loadUrlDataIn(Tab t, UrlData data) {
3719 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3724 * If the WebView is the top window, update the title bar to reflect
3725 * loading the new URL. i.e. set its text, clear the favicon (which
3726 * will be set once the page begins loading), and set the progress to
3727 * INITIAL_PROGRESS to show that the page has begun to load. Called
3728 * by loadUrl and loadUrlDataIn.
3729 * @param view The WebView that is starting a load.
3730 * @param url The URL that is being loaded.
3732 private void updateTitleBarForNewLoad(WebView view, String url) {
3733 if (view == getTopWindow()) {
3734 setUrlTitle(url, null);
3736 onProgressChanged(view, INITIAL_PROGRESS);
3740 private String smartUrlFilter(Uri inUri) {
3741 if (inUri != null) {
3742 return smartUrlFilter(inUri.toString());
3747 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3748 "(?i)" + // switch on case insensitive matching
3749 "(" + // begin group for schema
3750 "(?:http|https|file):\\/\\/" +
3751 "|(?:inline|data|about|content|javascript):" +
3756 * Attempts to determine whether user input is a URL or search
3757 * terms. Anything with a space is passed to search.
3759 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3760 * "Http://" converts to "http://"
3762 * @return Original or modified URL
3765 String smartUrlFilter(String url) {
3767 String inUrl = url.trim();
3768 boolean hasSpace = inUrl.indexOf(' ') != -1;
3770 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3771 if (matcher.matches()) {
3772 // force scheme to lowercase
3773 String scheme = matcher.group(1);
3774 String lcScheme = scheme.toLowerCase();
3775 if (!lcScheme.equals(scheme)) {
3776 inUrl = lcScheme + matcher.group(2);
3779 inUrl = inUrl.replace(" ", "%20");
3784 // FIXME: Is this the correct place to add to searches?
3785 // what if someone else calls this function?
3786 int shortcut = parseUrlShortcut(inUrl);
3787 if (shortcut != SHORTCUT_INVALID) {
3788 Browser.addSearchUrl(mResolver, inUrl);
3789 String query = inUrl.substring(2);
3791 case SHORTCUT_GOOGLE_SEARCH:
3792 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3793 case SHORTCUT_WIKIPEDIA_SEARCH:
3794 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3795 case SHORTCUT_DICTIONARY_SEARCH:
3796 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3797 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3798 // FIXME: we need location in this case
3799 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3803 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3804 return URLUtil.guessUrl(inUrl);
3808 Browser.addSearchUrl(mResolver, inUrl);
3809 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3812 /* package */ void setShouldShowErrorConsole(boolean flag) {
3813 if (flag == mShouldShowErrorConsole) {
3818 mShouldShowErrorConsole = flag;
3820 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3821 .getErrorConsole(true);
3824 // Setting the show state of the console will cause it's the layout to be inflated.
3825 if (errorConsole.numberOfErrors() > 0) {
3826 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3828 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3831 // Now we can add it to the main view.
3832 mErrorConsoleContainer.addView(errorConsole,
3833 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3834 ViewGroup.LayoutParams.WRAP_CONTENT));
3836 mErrorConsoleContainer.removeView(errorConsole);
3841 boolean shouldShowErrorConsole() {
3842 return mShouldShowErrorConsole;
3845 private void setStatusBarVisibility(boolean visible) {
3846 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3847 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3851 private void sendNetworkType(String type, String subtype) {
3852 WebView w = mTabControl.getCurrentWebView();
3854 w.setNetworkType(type, subtype);
3858 private void packageChanged(String packageName, boolean wasAdded) {
3859 WebView w = mTabControl.getCurrentWebView();
3865 w.addPackageName(packageName);
3867 w.removePackageName(packageName);
3871 private void addPackageNames(Set<String> packageNames) {
3872 WebView w = mTabControl.getCurrentWebView();
3877 w.addPackageNames(packageNames);
3880 private void getInstalledPackages() {
3881 AsyncTask<Void, Void, Set<String> > task =
3882 new AsyncTask<Void, Void, Set<String> >() {
3883 protected Set<String> doInBackground(Void... unused) {
3884 Set<String> installedPackages = new HashSet<String>();
3885 PackageManager pm = BrowserActivity.this.getPackageManager();
3887 List<PackageInfo> packages = pm.getInstalledPackages(0);
3888 for (PackageInfo p : packages) {
3889 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3890 installedPackages.add(p.packageName);
3895 return installedPackages;
3898 // Executes on the UI thread
3899 protected void onPostExecute(Set<String> installedPackages) {
3900 addPackageNames(installedPackages);
3906 final static int LOCK_ICON_UNSECURE = 0;
3907 final static int LOCK_ICON_SECURE = 1;
3908 final static int LOCK_ICON_MIXED = 2;
3910 private BrowserSettings mSettings;
3911 private TabControl mTabControl;
3912 private ContentResolver mResolver;
3913 private FrameLayout mContentView;
3914 private View mCustomView;
3915 private FrameLayout mCustomViewContainer;
3916 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3918 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3919 // view, we should rewrite this.
3920 private int mCurrentMenuState = 0;
3921 private int mMenuState = R.id.MAIN_MENU;
3922 private int mOldMenuState = EMPTY_MENU;
3923 private static final int EMPTY_MENU = -1;
3926 private FindDialog mFindDialog;
3927 // Used to prevent chording to result in firing two shortcuts immediately
3928 // one after another. Fixes bug 1211714.
3931 private boolean mInLoad;
3932 private boolean mIsNetworkUp;
3933 private boolean mDidStopLoad;
3935 private boolean mActivityInPause = true;
3937 private boolean mMenuIsDown;
3939 private static boolean mInTrace;
3941 // Performance probe
3942 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3943 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3944 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3945 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3946 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3947 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3948 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3949 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3950 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3953 private long mStart;
3954 private long mProcessStart;
3955 private long mUserStart;
3956 private long mSystemStart;
3957 private long mIdleStart;
3958 private long mIrqStart;
3960 private long mUiStart;
3962 private Drawable mMixLockIcon;
3963 private Drawable mSecLockIcon;
3965 /* hold a ref so we can auto-cancel if necessary */
3966 private AlertDialog mAlertDialog;
3968 // Wait for credentials before loading google.com
3969 private ProgressDialog mCredsDlg;
3971 // The up-to-date URL and title (these can be different from those stored
3972 // in WebView, since it takes some time for the information in WebView to
3974 private String mUrl;
3975 private String mTitle;
3977 // As PageInfo has different style for landscape / portrait, we have
3978 // to re-open it when configuration changed
3979 private AlertDialog mPageInfoDialog;
3980 private Tab mPageInfoView;
3981 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3982 // dialog, we should not just dismiss it, but should get back to the
3983 // SSL-certificate-on-error dialog. This flag is used to store this state
3984 private boolean mPageInfoFromShowSSLCertificateOnError;
3986 // as SSLCertificateOnError has different style for landscape / portrait,
3987 // we have to re-open it when configuration changed
3988 private AlertDialog mSSLCertificateOnErrorDialog;
3989 private WebView mSSLCertificateOnErrorView;
3990 private SslErrorHandler mSSLCertificateOnErrorHandler;
3991 private SslError mSSLCertificateOnErrorError;
3993 // as SSLCertificate has different style for landscape / portrait, we
3994 // have to re-open it when configuration changed
3995 private AlertDialog mSSLCertificateDialog;
3996 private Tab mSSLCertificateView;
3998 // as HttpAuthentication has different style for landscape / portrait, we
3999 // have to re-open it when configuration changed
4000 private AlertDialog mHttpAuthenticationDialog;
4001 private HttpAuthHandler mHttpAuthHandler;
4003 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4004 new FrameLayout.LayoutParams(
4005 ViewGroup.LayoutParams.MATCH_PARENT,
4006 ViewGroup.LayoutParams.MATCH_PARENT);
4007 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4008 new FrameLayout.LayoutParams(
4009 ViewGroup.LayoutParams.MATCH_PARENT,
4010 ViewGroup.LayoutParams.MATCH_PARENT,
4013 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4015 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4016 // Dictionary search
4017 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4018 // Google Mobile Local search
4019 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4021 final static String QUERY_PLACE_HOLDER = "%s";
4023 // "source" parameter for Google search through search key
4024 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4025 // "source" parameter for Google search through goto menu
4026 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4027 // "source" parameter for Google search through simplily type
4028 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4029 // "source" parameter for Google search suggested by the browser
4030 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4031 // "source" parameter for Google search from unknown source
4032 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4034 private final static String LOGTAG = "browser";
4036 private String mLastEnteredUrl;
4038 private PowerManager.WakeLock mWakeLock;
4039 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4041 private Toast mStopToast;
4043 private TitleBar mTitleBar;
4045 private LinearLayout mErrorConsoleContainer = null;
4046 private boolean mShouldShowErrorConsole = false;
4048 // As the ids are dynamically created, we can't guarantee that they will
4049 // be in sequence, so this static array maps ids to a window number.
4050 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4051 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4052 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4053 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4055 // monitor platform changes
4056 private IntentFilter mNetworkStateChangedFilter;
4057 private BroadcastReceiver mNetworkStateIntentReceiver;
4059 private BroadcastReceiver mPackageInstallationReceiver;
4061 // activity requestCode
4062 final static int COMBO_PAGE = 1;
4063 final static int DOWNLOAD_PAGE = 2;
4064 final static int PREFERENCES_PAGE = 3;
4065 final static int FILE_SELECTED = 4;
4067 // the default <video> poster
4068 private Bitmap mDefaultVideoPoster;
4069 // the video progress view
4070 private View mVideoProgressView;
4072 // The Google packages we monitor for the navigator.isApplicationInstalled()
4073 // API. Add as needed.
4074 private static Set<String> sGoogleApps;
4076 sGoogleApps = new HashSet<String>();
4077 sGoogleApps.add("com.google.android.youtube");
4081 * A UrlData class to abstract how the content will be set to WebView.
4082 * This base class uses loadUrl to show the content.
4084 private static class UrlData {
4086 final Map<String, String> mHeaders;
4087 final Intent mVoiceIntent;
4089 UrlData(String url) {
4091 this.mHeaders = null;
4092 this.mVoiceIntent = null;
4095 UrlData(String url, Map<String, String> headers, Intent intent) {
4097 this.mHeaders = headers;
4098 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4099 .equals(intent.getAction())) {
4100 this.mVoiceIntent = intent;
4102 this.mVoiceIntent = null;
4107 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
4111 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4112 * the title bar as well.
4114 public void loadIn(Tab t) {
4115 if (mVoiceIntent != null) {
4116 t.activateVoiceSearchMode(mVoiceIntent);
4118 t.getWebView().loadUrl(mUrl, mHeaders);
4123 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);