2 * Copyright (C) 2006 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 package com.android.browser;
19 import android.app.Activity;
20 import android.app.AlertDialog;
21 import android.app.ProgressDialog;
22 import android.app.SearchManager;
23 import android.content.ActivityNotFoundException;
24 import android.content.BroadcastReceiver;
25 import android.content.ComponentName;
26 import android.content.ContentProvider;
27 import android.content.ContentProviderClient;
28 import android.content.ContentResolver;
29 import android.content.ContentUris;
30 import android.content.ContentValues;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.Intent;
34 import android.content.IntentFilter;
35 import android.content.pm.PackageInfo;
36 import android.content.pm.PackageManager;
37 import android.content.pm.ResolveInfo;
38 import android.content.res.Configuration;
39 import android.content.res.Resources;
40 import android.database.Cursor;
41 import android.database.DatabaseUtils;
42 import android.graphics.Bitmap;
43 import android.graphics.BitmapFactory;
44 import android.graphics.Canvas;
45 import android.graphics.Picture;
46 import android.graphics.PixelFormat;
47 import android.graphics.Rect;
48 import android.graphics.drawable.Drawable;
49 import android.net.ConnectivityManager;
50 import android.net.NetworkInfo;
51 import android.net.Uri;
52 import android.net.WebAddress;
53 import android.net.http.SslCertificate;
54 import android.net.http.SslError;
55 import android.os.AsyncTask;
56 import android.os.Bundle;
57 import android.os.Debug;
58 import android.os.Environment;
59 import android.os.Handler;
60 import android.os.Message;
61 import android.os.PowerManager;
62 import android.os.Process;
63 import android.os.ServiceManager;
64 import android.os.SystemClock;
65 import android.provider.Browser;
66 import android.provider.ContactsContract;
67 import android.provider.ContactsContract.Intents.Insert;
68 import android.provider.Downloads;
69 import android.provider.MediaStore;
70 import android.speech.RecognizerResultsIntent;
71 import android.text.IClipboard;
72 import android.text.TextUtils;
73 import android.text.format.DateFormat;
74 import android.util.AttributeSet;
75 import android.util.Log;
76 import android.util.Patterns;
77 import android.view.ContextMenu;
78 import android.view.Gravity;
79 import android.view.KeyEvent;
80 import android.view.LayoutInflater;
81 import android.view.Menu;
82 import android.view.MenuInflater;
83 import android.view.MenuItem;
84 import android.view.View;
85 import android.view.ViewGroup;
86 import android.view.Window;
87 import android.view.WindowManager;
88 import android.view.ContextMenu.ContextMenuInfo;
89 import android.view.MenuItem.OnMenuItemClickListener;
90 import android.webkit.CookieManager;
91 import android.webkit.CookieSyncManager;
92 import android.webkit.DownloadListener;
93 import android.webkit.HttpAuthHandler;
94 import android.webkit.PluginManager;
95 import android.webkit.SslErrorHandler;
96 import android.webkit.URLUtil;
97 import android.webkit.ValueCallback;
98 import android.webkit.WebChromeClient;
99 import android.webkit.WebHistoryItem;
100 import android.webkit.WebIconDatabase;
101 import android.webkit.WebView;
102 import android.widget.EditText;
103 import android.widget.FrameLayout;
104 import android.widget.LinearLayout;
105 import android.widget.TextView;
106 import android.widget.Toast;
107 import android.accounts.Account;
108 import android.accounts.AccountManager;
109 import android.accounts.AccountManagerFuture;
110 import android.accounts.AuthenticatorException;
111 import android.accounts.OperationCanceledException;
112 import android.accounts.AccountManagerCallback;
114 import com.android.common.Search;
115 import com.android.common.speech.LoggingEvents;
117 import java.io.ByteArrayOutputStream;
119 import java.io.IOException;
120 import java.io.InputStream;
121 import java.net.MalformedURLException;
123 import java.net.URISyntaxException;
125 import java.net.URLEncoder;
126 import java.text.ParseException;
127 import java.util.Date;
128 import java.util.HashMap;
129 import java.util.HashSet;
130 import java.util.Iterator;
131 import java.util.List;
132 import java.util.Map;
133 import java.util.Set;
134 import java.util.regex.Matcher;
135 import java.util.regex.Pattern;
137 public class BrowserActivity extends Activity
138 implements View.OnCreateContextMenuListener, DownloadListener,
139 AccountManagerCallback<Account[]> {
141 /* Define some aliases to make these debugging flags easier to refer to.
142 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
144 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
145 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
146 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
148 // These are single-character shortcuts for searching popular sources.
149 private static final int SHORTCUT_INVALID = 0;
150 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
151 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
152 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
153 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
155 private Account[] mAccountsGoogle;
156 private Account[] mAccountsPreferHosted;
158 // XXX: These constants should be exposed through some public api. Hardcode
159 // the values for now until some solution for gsf can be worked out.
160 // http://b/issue?id=2425179
161 private static final String ACCOUNT_TYPE = "com.google";
162 private static final String FEATURE_LEGACY_GOOGLE = "legacy_google";
163 private static final String FEATURE_LEGACY_HOSTED_OR_GOOGLE =
164 "legacy_hosted_or_google";
166 private void startReadOfGoogleAccounts() {
167 mAccountsGoogle = null;
168 mAccountsPreferHosted = null;
170 AccountManager.get(this).getAccountsByTypeAndFeatures(
171 ACCOUNT_TYPE, new String[]{ FEATURE_LEGACY_HOSTED_OR_GOOGLE },
175 /** This implements AccountManagerCallback<Account[]> */
176 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
178 if (mAccountsGoogle == null) {
179 mAccountsGoogle = accountManagerFuture.getResult();
181 AccountManager.get(this).getAccountsByTypeAndFeatures(
182 ACCOUNT_TYPE, new String[]{ FEATURE_LEGACY_GOOGLE },
185 mAccountsPreferHosted = accountManagerFuture.getResult();
188 } catch (OperationCanceledException e) {
190 } catch (IOException e) {
192 } catch (AuthenticatorException e) {
197 private void setupHomePage() {
198 // get the default home page
199 String homepage = mSettings.getHomePage();
201 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
204 // hostedUser == googleUser
205 // The device has only a google account
207 // hostedUser != googleUser
208 // The device has a hosted account and a google account
210 // hostedUser != null, googleUser == null
211 // The device has only a hosted account (so far)
212 String hostedUser = mAccountsPreferHosted.length == 0
214 : mAccountsPreferHosted[0].name;
215 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
217 // developers might have no accounts at all
218 if (hostedUser == null) return;
220 if (googleUser == null || !hostedUser.equals(googleUser)) {
221 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
222 homepage = homepage.replace("?", "/a/" + domain + "?");
226 mSettings.setHomePage(BrowserActivity.this, homepage);
227 resumeAfterCredentials();
230 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
232 public Void doInBackground(File... files) {
234 for (File f : files) {
236 Log.e(LOGTAG, f.getPath() + " was not deleted");
245 * This layout holds everything you see below the status bar, including the
246 * error console, the custom view container, and the webviews.
248 private FrameLayout mBrowserFrameLayout;
251 public void onCreate(Bundle icicle) {
253 Log.v(LOGTAG, this + " onStart");
255 super.onCreate(icicle);
256 // test the browser in OpenGL
257 // requestWindowFeature(Window.FEATURE_OPENGL);
259 // enable this to test the browser in 32bit
261 getWindow().setFormat(PixelFormat.RGBX_8888);
262 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
265 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
267 mResolver = getContentResolver();
269 // If this was a web search request, pass it on to the default web
270 // search provider and finish this activity.
271 if (handleWebSearchIntent(getIntent())) {
276 mSecLockIcon = Resources.getSystem().getDrawable(
277 android.R.drawable.ic_secure);
278 mMixLockIcon = Resources.getSystem().getDrawable(
279 android.R.drawable.ic_partial_secure);
281 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
282 .findViewById(com.android.internal.R.id.content);
283 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
284 .inflate(R.layout.custom_screen, null);
285 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
287 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
288 .findViewById(R.id.error_console);
289 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
290 .findViewById(R.id.fullscreen_custom_content);
291 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
292 mTitleBar = new TitleBar(this);
293 mFakeTitleBar = new TitleBar(this);
295 // Create the tab control and our initial tab
296 mTabControl = new TabControl(this);
298 // Open the icon database and retain all the bookmark urls for favicons
299 retainIconsOnStartup();
301 // Keep a settings instance handy.
302 mSettings = BrowserSettings.getInstance();
303 mSettings.setTabControl(mTabControl);
304 mSettings.loadFromDb(this);
306 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
307 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
309 // Find out if the network is currently up.
310 ConnectivityManager cm = (ConnectivityManager) getSystemService(
311 Context.CONNECTIVITY_SERVICE);
312 NetworkInfo info = cm.getActiveNetworkInfo();
314 mIsNetworkUp = info.isAvailable();
317 /* enables registration for changes in network status from
319 mNetworkStateChangedFilter = new IntentFilter();
320 mNetworkStateChangedFilter.addAction(
321 ConnectivityManager.CONNECTIVITY_ACTION);
322 mNetworkStateIntentReceiver = new BroadcastReceiver() {
324 public void onReceive(Context context, Intent intent) {
325 if (intent.getAction().equals(
326 ConnectivityManager.CONNECTIVITY_ACTION)) {
328 NetworkInfo info = intent.getParcelableExtra(
329 ConnectivityManager.EXTRA_NETWORK_INFO);
330 String typeName = info.getTypeName();
331 String subtypeName = info.getSubtypeName();
332 sendNetworkType(typeName.toLowerCase(),
333 (subtypeName != null ? subtypeName.toLowerCase() : ""));
335 onNetworkToggle(info.isAvailable());
340 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
341 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
342 filter.addDataScheme("package");
343 mPackageInstallationReceiver = new BroadcastReceiver() {
345 public void onReceive(Context context, Intent intent) {
346 final String action = intent.getAction();
347 final String packageName = intent.getData()
348 .getSchemeSpecificPart();
349 final boolean replacing = intent.getBooleanExtra(
350 Intent.EXTRA_REPLACING, false);
351 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
352 // if it is replacing, refreshPlugins() when adding
356 if (sGoogleApps.contains(packageName)) {
357 BrowserActivity.this.packageChanged(packageName,
358 Intent.ACTION_PACKAGE_ADDED.equals(action));
361 PackageManager pm = BrowserActivity.this.getPackageManager();
362 PackageInfo pkgInfo = null;
364 pkgInfo = pm.getPackageInfo(packageName,
365 PackageManager.GET_PERMISSIONS);
366 } catch (PackageManager.NameNotFoundException e) {
369 if (pkgInfo != null) {
370 String permissions[] = pkgInfo.requestedPermissions;
371 if (permissions == null) {
374 boolean permissionOk = false;
375 for (String permit : permissions) {
376 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
382 PluginManager.getInstance(BrowserActivity.this)
384 Intent.ACTION_PACKAGE_ADDED
390 registerReceiver(mPackageInstallationReceiver, filter);
392 if (!mTabControl.restoreState(icicle)) {
393 // clear up the thumbnail directory if we can't restore the state as
394 // none of the files in the directory are referenced any more.
395 new ClearThumbnails().execute(
396 mTabControl.getThumbnailDir().listFiles());
397 // there is no quit on Android. But if we can't restore the state,
398 // we can treat it as a new Browser, remove the old session cookies.
399 CookieManager.getInstance().removeSessionCookie();
400 final Intent intent = getIntent();
401 final Bundle extra = intent.getExtras();
402 // Create an initial tab.
403 // If the intent is ACTION_VIEW and data is not null, the Browser is
404 // invoked to view the content by another application. In this case,
405 // the tab will be close when exit.
406 UrlData urlData = getUrlDataFromIntent(intent);
408 String action = intent.getAction();
409 final Tab t = mTabControl.createNewTab(
410 (Intent.ACTION_VIEW.equals(action) &&
411 intent.getData() != null)
412 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
414 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
415 mTabControl.setCurrentTab(t);
416 attachTabToContentView(t);
417 WebView webView = t.getWebView();
419 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
420 if (scale > 0 && scale <= 1000) {
421 webView.setInitialScale(scale);
424 // If we are not restoring from an icicle, then there is a high
425 // likely hood this is the first run. So, check to see if the
426 // homepage needs to be configured and copy any plugins from our
427 // asset directory to the data partition.
428 if ((extra == null || !extra.getBoolean("testing"))
429 && !mSettings.isLoginInitialized()) {
430 startReadOfGoogleAccounts();
433 if (urlData.isEmpty()) {
434 if (mSettings.isLoginInitialized()) {
435 loadUrl(webView, mSettings.getHomePage());
437 waitForCredentials();
440 loadUrlDataIn(t, urlData);
443 // TabControl.restoreState() will create a new tab even if
444 // restoring the state fails.
445 attachTabToContentView(mTabControl.getCurrentTab());
448 // Read JavaScript flags if it exists.
449 String jsFlags = mSettings.getJsFlags();
450 if (jsFlags.trim().length() != 0) {
451 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
453 // Work out which packages are installed on the system.
454 getInstalledPackages();
458 * Feed the previously stored results strings to the BrowserProvider so that
459 * the SearchDialog will show them instead of the standard searches.
460 * @param result String to show on the editable line of the SearchDialog.
462 /* package */ void showVoiceSearchResults(String result) {
463 ContentProviderClient client = mResolver.acquireContentProviderClient(
464 Browser.BOOKMARKS_URI);
465 ContentProvider prov = client.getLocalContentProvider();
466 BrowserProvider bp = (BrowserProvider) prov;
467 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
470 startSearch(result, false,
471 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY),
476 protected void onNewIntent(Intent intent) {
477 Tab current = mTabControl.getCurrentTab();
478 // When a tab is closed on exit, the current tab index is set to -1.
479 // Reset before proceed as Browser requires the current tab to be set.
480 if (current == null) {
481 // Try to reset the tab in case the index was incorrect.
482 current = mTabControl.getTab(0);
483 if (current == null) {
484 // No tabs at all so just ignore this intent.
487 mTabControl.setCurrentTab(current);
488 attachTabToContentView(current);
489 resetTitleAndIcon(current.getWebView());
491 final String action = intent.getAction();
492 final int flags = intent.getFlags();
493 if (Intent.ACTION_MAIN.equals(action) ||
494 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
495 // just resume the browser
498 boolean activateVoiceSearch = RecognizerResultsIntent
499 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
500 if (Intent.ACTION_VIEW.equals(action)
501 || Intent.ACTION_SEARCH.equals(action)
502 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
503 || Intent.ACTION_WEB_SEARCH.equals(action)
504 || activateVoiceSearch) {
505 if (current.isInVoiceSearchMode()) {
506 String title = current.getVoiceDisplayTitle();
507 if (title != null && title.equals(intent.getStringExtra(
508 SearchManager.QUERY))) {
509 // The user submitted the same search as the last voice
510 // search, so do nothing.
513 if (Intent.ACTION_SEARCH.equals(action)
514 && current.voiceSearchSourceIsGoogle()) {
515 Intent logIntent = new Intent(
516 LoggingEvents.ACTION_LOG_EVENT);
517 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
518 LoggingEvents.VoiceSearch.QUERY_UPDATED);
520 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
521 intent.getDataString());
522 sendBroadcast(logIntent);
523 // Note, onPageStarted will revert the voice title bar
524 // When http://b/issue?id=2379215 is fixed, we should update
525 // the title bar here.
528 // If this was a search request (e.g. search query directly typed into the address bar),
529 // pass it on to the default web search provider.
530 if (handleWebSearchIntent(intent)) {
534 UrlData urlData = getUrlDataFromIntent(intent);
535 if (urlData.isEmpty()) {
536 urlData = new UrlData(mSettings.getHomePage());
539 final String appId = intent
540 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
541 if ((Intent.ACTION_VIEW.equals(action) || activateVoiceSearch)
542 && !getPackageName().equals(appId)
543 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
544 Tab appTab = mTabControl.getTabFromId(appId);
545 if (appTab != null) {
546 Log.i(LOGTAG, "Reusing tab for " + appId);
547 // Dismiss the subwindow if applicable.
548 dismissSubWindow(appTab);
549 // Since we might kill the WebView, remove it from the
550 // content view first.
551 removeTabFromContentView(appTab);
552 // Recreate the main WebView after destroying the old one.
553 // If the WebView has the same original url and is on that
554 // page, it can be reused.
556 mTabControl.recreateWebView(appTab, urlData.mUrl);
558 if (current != appTab) {
559 switchToTab(mTabControl.getTabIndex(appTab));
561 loadUrlDataIn(appTab, urlData);
564 // If the tab was the current tab, we have to attach
565 // it to the view system again.
566 attachTabToContentView(appTab);
568 loadUrlDataIn(appTab, urlData);
573 // No matching application tab, try to find a regular tab
574 // with a matching url.
575 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
576 if (appTab != null) {
577 if (current != appTab) {
578 switchToTab(mTabControl.getTabIndex(appTab));
580 // Otherwise, we are already viewing the correct tab.
582 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
583 // will be opened in a new tab unless we have reached
584 // MAX_TABS. Then the url will be opened in the current
585 // tab. If a new tab is created, it will have "true" for
587 openTabAndShow(urlData, true, appId);
591 if (!urlData.isEmpty()
592 && urlData.mUrl.startsWith("about:debug")) {
593 if ("about:debug.dom".equals(urlData.mUrl)) {
594 current.getWebView().dumpDomTree(false);
595 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
596 current.getWebView().dumpDomTree(true);
597 } else if ("about:debug.render".equals(urlData.mUrl)) {
598 current.getWebView().dumpRenderTree(false);
599 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
600 current.getWebView().dumpRenderTree(true);
601 } else if ("about:debug.display".equals(urlData.mUrl)) {
602 current.getWebView().dumpDisplayTree();
603 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
604 int index = urlData.mUrl.codePointAt(16) - '0';
605 if (index <= 0 || index > 9) {
606 current.getWebView().setDragTracker(null);
608 current.getWebView().setDragTracker(new MeshTracker(index));
611 mSettings.toggleDebugSettings();
615 // Get rid of the subwindow if it exists
616 dismissSubWindow(current);
617 loadUrlDataIn(current, urlData);
622 private int parseUrlShortcut(String url) {
623 if (url == null) return SHORTCUT_INVALID;
625 // FIXME: quick search, need to be customized by setting
626 if (url.length() > 2 && url.charAt(1) == ' ') {
627 switch (url.charAt(0)) {
628 case 'g': return SHORTCUT_GOOGLE_SEARCH;
629 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
630 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
631 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
634 return SHORTCUT_INVALID;
638 * Launches the default web search activity with the query parameters if the given intent's data
639 * are identified as plain search terms and not URLs/shortcuts.
640 * @return true if the intent was handled and web search activity was launched, false if not.
642 private boolean handleWebSearchIntent(Intent intent) {
643 if (intent == null) return false;
646 final String action = intent.getAction();
647 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
651 if (Intent.ACTION_VIEW.equals(action)) {
652 Uri data = intent.getData();
653 if (data != null) url = data.toString();
654 } else if (Intent.ACTION_SEARCH.equals(action)
655 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
656 || Intent.ACTION_WEB_SEARCH.equals(action)) {
657 url = intent.getStringExtra(SearchManager.QUERY);
659 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
660 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
664 * Launches the default web search activity with the query parameters if the given url string
665 * was identified as plain search terms and not URL/shortcut.
666 * @return true if the request was handled and web search activity was launched, false if not.
668 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
669 if (inUrl == null) return false;
671 // In general, we shouldn't modify URL from Intent.
672 // But currently, we get the user-typed URL from search box as well.
673 String url = fixUrl(inUrl).trim();
675 // URLs and site specific search shortcuts are handled by the regular flow of control, so
677 if (Patterns.WEB_URL.matcher(url).matches()
678 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
679 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
683 Browser.updateVisitedHistory(mResolver, url, false);
684 Browser.addSearchUrl(mResolver, url);
686 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
687 intent.addCategory(Intent.CATEGORY_DEFAULT);
688 intent.putExtra(SearchManager.QUERY, url);
689 if (appData != null) {
690 intent.putExtra(SearchManager.APP_DATA, appData);
692 if (extraData != null) {
693 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
695 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
696 startActivity(intent);
701 private UrlData getUrlDataFromIntent(Intent intent) {
703 Map<String, String> headers = null;
704 if (intent != null) {
705 final String action = intent.getAction();
706 if (Intent.ACTION_VIEW.equals(action)) {
707 url = smartUrlFilter(intent.getData());
708 if (url != null && url.startsWith("content:")) {
709 /* Append mimetype so webview knows how to display */
710 String mimeType = intent.resolveType(getContentResolver());
711 if (mimeType != null) {
712 url += "?" + mimeType;
715 if (url != null && url.startsWith("http")) {
716 final Bundle pairs = intent
717 .getBundleExtra(Browser.EXTRA_HEADERS);
718 if (pairs != null && !pairs.isEmpty()) {
719 Iterator<String> iter = pairs.keySet().iterator();
720 headers = new HashMap<String, String>();
721 while (iter.hasNext()) {
722 String key = iter.next();
723 headers.put(key, pairs.getString(key));
727 } else if (Intent.ACTION_SEARCH.equals(action)
728 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
729 || Intent.ACTION_WEB_SEARCH.equals(action)) {
730 url = intent.getStringExtra(SearchManager.QUERY);
732 mLastEnteredUrl = url;
733 // In general, we shouldn't modify URL from Intent.
734 // But currently, we get the user-typed URL from search box as well.
736 url = smartUrlFilter(url);
737 Browser.updateVisitedHistory(mResolver, url, false);
738 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
739 if (url.contains(searchSource)) {
740 String source = null;
741 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
742 if (appData != null) {
743 source = appData.getString(Search.SOURCE);
745 if (TextUtils.isEmpty(source)) {
746 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
748 url = url.replace(searchSource, "&source=android-"+source+"&");
753 return new UrlData(url, headers, intent);
755 /* package */ void showVoiceTitleBar(String title) {
756 mTitleBar.setInVoiceMode(true);
757 mFakeTitleBar.setInVoiceMode(true);
759 mTitleBar.setDisplayTitle(title);
760 mFakeTitleBar.setDisplayTitle(title);
762 /* package */ void revertVoiceTitleBar() {
763 mTitleBar.setInVoiceMode(false);
764 mFakeTitleBar.setInVoiceMode(false);
766 mTitleBar.setDisplayTitle(mUrl);
767 mFakeTitleBar.setDisplayTitle(mUrl);
769 /* package */ static String fixUrl(String inUrl) {
770 // FIXME: Converting the url to lower case
771 // duplicates functionality in smartUrlFilter().
772 // However, changing all current callers of fixUrl to
773 // call smartUrlFilter in addition may have unwanted
774 // consequences, and is deferred for now.
775 int colon = inUrl.indexOf(':');
776 boolean allLower = true;
777 for (int index = 0; index < colon; index++) {
778 char ch = inUrl.charAt(index);
779 if (!Character.isLetter(ch)) {
782 allLower &= Character.isLowerCase(ch);
783 if (index == colon - 1 && !allLower) {
784 inUrl = inUrl.substring(0, colon).toLowerCase()
785 + inUrl.substring(colon);
788 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
790 if (inUrl.startsWith("http:") ||
791 inUrl.startsWith("https:")) {
792 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
793 inUrl = inUrl.replaceFirst("/", "//");
794 } else inUrl = inUrl.replaceFirst(":", "://");
800 protected void onResume() {
803 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
806 if (!mActivityInPause) {
807 Log.e(LOGTAG, "BrowserActivity is already resumed.");
811 mTabControl.resumeCurrentTab();
812 mActivityInPause = false;
813 resumeWebViewTimers();
815 if (mWakeLock.isHeld()) {
816 mHandler.removeMessages(RELEASE_WAKELOCK);
820 if (mCredsDlg != null) {
821 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
822 // In case credential request never comes back
823 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
827 registerReceiver(mNetworkStateIntentReceiver,
828 mNetworkStateChangedFilter);
829 WebView.enablePlatformNotifications();
833 * Since the actual title bar is embedded in the WebView, and removing it
834 * would change its appearance, use a different TitleBar to show overlayed
835 * at the top of the screen, when the menu is open or the page is loading.
837 private TitleBar mFakeTitleBar;
840 * Holder for the fake title bar. It will have a foreground shadow, as well
841 * as a white background, so the fake title bar looks like the real one.
843 private ViewGroup mFakeTitleBarHolder;
846 * Layout parameters for the fake title bar within mFakeTitleBarHolder
848 private FrameLayout.LayoutParams mFakeTitleBarParams
849 = new FrameLayout.LayoutParams(
850 ViewGroup.LayoutParams.MATCH_PARENT,
851 ViewGroup.LayoutParams.WRAP_CONTENT);
853 * Keeps track of whether the options menu is open. This is important in
854 * determining whether to show or hide the title bar overlay.
856 private boolean mOptionsMenuOpen;
859 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
860 * of whether the configuration has changed. The first onMenuOpened call
861 * after a configuration change is simply a reopening of the same menu
862 * (i.e. mIconView did not change).
864 private boolean mConfigChanged;
867 * Whether or not the options menu is in its smaller, icon menu form. When
868 * true, we want the title bar overlay to be up. When false, we do not.
869 * Only meaningful if mOptionsMenuOpen is true.
871 private boolean mIconView;
874 public boolean onMenuOpened(int featureId, Menu menu) {
875 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
876 if (mOptionsMenuOpen) {
877 if (mConfigChanged) {
878 // We do not need to make any changes to the state of the
879 // title bar, since the only thing that happened was a
880 // change in orientation
881 mConfigChanged = false;
884 // Switching the menu to expanded view, so hide the
889 // Switching the menu back to icon view, so show the
890 // title bar once again.
896 // The options menu is closed, so open it, and show the title
898 mOptionsMenuOpen = true;
899 mConfigChanged = false;
907 * Special class used exclusively for the shadow drawn underneath the fake
908 * title bar. The shadow does not need to be drawn if the WebView
909 * underneath is scrolled to the top, because it will draw directly on top
910 * of the embedded shadow.
912 private static class Shadow extends View {
913 private WebView mWebView;
915 public Shadow(Context context, AttributeSet attrs) {
916 super(context, attrs);
919 public void setWebView(WebView view) {
924 public void draw(Canvas canvas) {
925 // In general onDraw is the method to override, but we care about
926 // whether or not the background gets drawn, which happens in draw()
927 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
930 // Need to invalidate so that if the scroll position changes, we
931 // still draw as appropriate.
936 private void showFakeTitleBar() {
937 final View decor = getWindow().peekDecorView();
938 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
939 && !mActivityInPause && decor != null
940 && decor.getWindowToken() != null) {
941 Rect visRect = new Rect();
942 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
944 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
949 WindowManager manager
950 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
952 // Add the title bar to the window manager so it can receive touches
953 // while the menu is up
954 WindowManager.LayoutParams params
955 = new WindowManager.LayoutParams(
956 ViewGroup.LayoutParams.MATCH_PARENT,
957 ViewGroup.LayoutParams.WRAP_CONTENT,
958 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
959 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
960 PixelFormat.TRANSLUCENT);
961 params.gravity = Gravity.TOP;
962 WebView mainView = mTabControl.getCurrentWebView();
963 boolean atTop = mainView != null && mainView.getScrollY() == 0;
964 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
965 // XXX : Without providing an offset, the fake title bar will be
966 // placed underneath the status bar. Use the global visible rect
967 // of mBrowserFrameLayout to determine the bottom of the status bar
968 params.y = visRect.top;
969 // Add a holder for the title bar. It also holds a shadow to show
970 // below the title bar.
971 if (mFakeTitleBarHolder == null) {
972 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
973 .inflate(R.layout.title_bar_bg, null);
975 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
977 shadow.setWebView(mainView);
978 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
979 manager.addView(mFakeTitleBarHolder, params);
984 public void onOptionsMenuClosed(Menu menu) {
985 mOptionsMenuOpen = false;
988 } else if (!mIconView) {
989 // The page is currently loading, and we are in expanded mode, so
990 // we were not showing the menu. Show it once again. It will be
991 // removed when the page finishes.
996 private void hideFakeTitleBar() {
997 if (mFakeTitleBar.getParent() == null) return;
998 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
999 mFakeTitleBarHolder.getLayoutParams();
1000 WebView mainView = mTabControl.getCurrentWebView();
1001 // Although we decided whether or not to animate based on the current
1002 // scroll position, the scroll position may have changed since the
1003 // fake title bar was displayed. Make sure it has the appropriate
1004 // animation/lack thereof before removing.
1005 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
1006 ? 0 : R.style.TitleBar;
1007 WindowManager manager
1008 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
1009 manager.updateViewLayout(mFakeTitleBarHolder, params);
1010 mFakeTitleBarHolder.removeView(mFakeTitleBar);
1011 manager.removeView(mFakeTitleBarHolder);
1015 * Special method for the fake title bar to call when displaying its context
1016 * menu, since it is in its own Window, and its parent does not show a
1019 /* package */ void showTitleBarContextMenu() {
1020 if (null == mTitleBar.getParent()) {
1023 openContextMenu(mTitleBar);
1027 public void onContextMenuClosed(Menu menu) {
1028 super.onContextMenuClosed(menu);
1035 * onSaveInstanceState(Bundle map)
1036 * onSaveInstanceState is called right before onStop(). The map contains
1040 protected void onSaveInstanceState(Bundle outState) {
1042 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1044 // the default implementation requires each view to have an id. As the
1045 // browser handles the state itself and it doesn't use id for the views,
1046 // don't call the default implementation. Otherwise it will trigger the
1047 // warning like this, "couldn't save which view has focus because the
1048 // focused view XXX has no id".
1050 // Save all the tabs
1051 mTabControl.saveState(outState);
1055 protected void onPause() {
1058 if (mActivityInPause) {
1059 Log.e(LOGTAG, "BrowserActivity is already paused.");
1063 mTabControl.pauseCurrentTab();
1064 mActivityInPause = true;
1065 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
1066 mWakeLock.acquire();
1067 mHandler.sendMessageDelayed(mHandler
1068 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1071 // Clear the credentials toast if it is up
1072 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1073 mCredsDlg.dismiss();
1077 // FIXME: This removes the active tabs page and resets the menu to
1078 // MAIN_MENU. A better solution might be to do this work in onNewIntent
1079 // but then we would need to save it in onSaveInstanceState and restore
1080 // it in onCreate/onRestoreInstanceState
1081 if (mActiveTabsPage != null) {
1082 removeActiveTabPage(true);
1087 // unregister network state listener
1088 unregisterReceiver(mNetworkStateIntentReceiver);
1089 WebView.disablePlatformNotifications();
1093 protected void onDestroy() {
1095 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1099 if (mUploadMessage != null) {
1100 mUploadMessage.onReceiveValue(null);
1101 mUploadMessage = null;
1104 if (mTabControl == null) return;
1106 // Remove the fake title bar if it is there
1109 // Remove the current tab and sub window
1110 Tab t = mTabControl.getCurrentTab();
1112 dismissSubWindow(t);
1113 removeTabFromContentView(t);
1115 // Destroy all the tabs
1116 mTabControl.destroy();
1117 WebIconDatabase.getInstance().close();
1119 unregisterReceiver(mPackageInstallationReceiver);
1123 public void onConfigurationChanged(Configuration newConfig) {
1124 mConfigChanged = true;
1125 super.onConfigurationChanged(newConfig);
1127 if (mPageInfoDialog != null) {
1128 mPageInfoDialog.dismiss();
1131 mPageInfoFromShowSSLCertificateOnError);
1133 if (mSSLCertificateDialog != null) {
1134 mSSLCertificateDialog.dismiss();
1136 mSSLCertificateView);
1138 if (mSSLCertificateOnErrorDialog != null) {
1139 mSSLCertificateOnErrorDialog.dismiss();
1140 showSSLCertificateOnError(
1141 mSSLCertificateOnErrorView,
1142 mSSLCertificateOnErrorHandler,
1143 mSSLCertificateOnErrorError);
1145 if (mHttpAuthenticationDialog != null) {
1146 String title = ((TextView) mHttpAuthenticationDialog
1147 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1149 String name = ((TextView) mHttpAuthenticationDialog
1150 .findViewById(R.id.username_edit)).getText().toString();
1151 String password = ((TextView) mHttpAuthenticationDialog
1152 .findViewById(R.id.password_edit)).getText().toString();
1153 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1155 mHttpAuthenticationDialog.dismiss();
1156 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1157 name, password, focusId);
1162 public void onLowMemory() {
1163 super.onLowMemory();
1164 mTabControl.freeMemory();
1167 private boolean resumeWebViewTimers() {
1168 Tab tab = mTabControl.getCurrentTab();
1169 boolean inLoad = tab.inLoad();
1170 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1171 CookieSyncManager.getInstance().startSync();
1172 WebView w = tab.getWebView();
1182 private boolean pauseWebViewTimers() {
1183 Tab tab = mTabControl.getCurrentTab();
1184 boolean inLoad = tab.inLoad();
1185 if (mActivityInPause && !inLoad) {
1186 CookieSyncManager.getInstance().stopSync();
1187 WebView w = mTabControl.getCurrentWebView();
1197 // FIXME: Do we want to call this when loading google for the first time?
1199 * This function is called when we are launching for the first time. We
1200 * are waiting for the login credentials before loading Google home
1201 * pages. This way the user will be logged in straight away.
1203 private void waitForCredentials() {
1205 mCredsDlg = new ProgressDialog(this);
1206 mCredsDlg.setIndeterminate(true);
1207 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1208 // If the user cancels the operation, then cancel the Google
1209 // Credentials request.
1210 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1213 // We set a timeout for the retrieval of credentials in onResume()
1214 // as that is when we have freed up some CPU time to get
1215 // the login credentials.
1219 * If we have received the credentials or we have timed out and we are
1220 * showing the credentials dialog, then it is time to move on.
1222 private void resumeAfterCredentials() {
1223 if (mCredsDlg == null) {
1228 if (mCredsDlg.isShowing()) {
1229 mCredsDlg.dismiss();
1233 // Clear any pending timeout
1234 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1237 WebView w = mTabControl.getCurrentWebView();
1239 loadUrl(w, mSettings.getHomePage());
1242 // Update the settings, need to do this last as it can take a moment
1243 // to persist the settings. In the mean time we could be loading
1245 mSettings.setLoginInitialized(this);
1248 // Open the icon database and retain all the icons for visited sites.
1249 private void retainIconsOnStartup() {
1250 final WebIconDatabase db = WebIconDatabase.getInstance();
1251 db.open(getDir("icons", 0).getPath());
1253 Cursor c = Browser.getAllBookmarks(mResolver);
1254 if (!c.moveToFirst()) {
1258 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1260 String url = c.getString(urlIndex);
1261 db.retainIconForPageUrl(url);
1262 } while (c.moveToNext());
1264 } catch (IllegalStateException e) {
1265 Log.e(LOGTAG, "retainIconsOnStartup", e);
1269 // Helper method for getting the top window.
1270 WebView getTopWindow() {
1271 return mTabControl.getCurrentTopWebView();
1274 TabControl getTabControl() {
1279 public boolean onCreateOptionsMenu(Menu menu) {
1280 super.onCreateOptionsMenu(menu);
1282 MenuInflater inflater = getMenuInflater();
1283 inflater.inflate(R.menu.browser, menu);
1285 updateInLoadMenuItems();
1290 * As the menu can be open when loading state changes
1291 * we must manually update the state of the stop/reload menu
1294 private void updateInLoadMenuItems() {
1295 if (mMenu == null) {
1298 MenuItem src = mInLoad ?
1299 mMenu.findItem(R.id.stop_menu_id):
1300 mMenu.findItem(R.id.reload_menu_id);
1301 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1302 dest.setIcon(src.getIcon());
1303 dest.setTitle(src.getTitle());
1307 public boolean onContextItemSelected(MenuItem item) {
1308 // chording is not an issue with context menus, but we use the same
1309 // options selector, so set mCanChord to true so we can access them.
1311 int id = item.getItemId();
1312 boolean result = true;
1314 // For the context menu from the title bar
1315 case R.id.title_bar_copy_page_url:
1316 Tab currentTab = mTabControl.getCurrentTab();
1317 if (null == currentTab) {
1321 WebView mainView = currentTab.getWebView();
1322 if (null == mainView) {
1326 copy(mainView.getUrl());
1328 // -- Browser context menu
1329 case R.id.open_context_menu_id:
1330 case R.id.open_newtab_context_menu_id:
1331 case R.id.bookmark_context_menu_id:
1332 case R.id.save_link_context_menu_id:
1333 case R.id.share_link_context_menu_id:
1334 case R.id.copy_link_context_menu_id:
1335 final WebView webView = getTopWindow();
1336 if (null == webView) {
1340 final HashMap hrefMap = new HashMap();
1341 hrefMap.put("webview", webView);
1342 final Message msg = mHandler.obtainMessage(
1343 FOCUS_NODE_HREF, id, 0, hrefMap);
1344 webView.requestFocusNodeHref(msg);
1348 // For other context menus
1349 result = onOptionsItemSelected(item);
1355 private Bundle createGoogleSearchSourceBundle(String source) {
1356 Bundle bundle = new Bundle();
1357 bundle.putString(Search.SOURCE, source);
1361 /* package */ void editUrl() {
1362 if (mOptionsMenuOpen) closeOptionsMenu();
1363 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1364 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1369 * Overriding this to insert a local information bundle
1372 public void startSearch(String initialQuery, boolean selectInitialQuery,
1373 Bundle appSearchData, boolean globalSearch) {
1374 if (appSearchData == null) {
1375 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1377 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1381 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1382 * results in changing tabs.
1383 * @param index Index of the tab to change to, as defined by
1384 * mTabControl.getTabIndex(Tab t).
1385 * @return boolean True if we successfully switched to a different tab. If
1386 * the indexth tab is null, or if that tab is the same as
1387 * the current one, return false.
1389 /* package */ boolean switchToTab(int index) {
1390 Tab tab = mTabControl.getTab(index);
1391 Tab currentTab = mTabControl.getCurrentTab();
1392 if (tab == null || tab == currentTab) {
1395 if (currentTab != null) {
1396 // currentTab may be null if it was just removed. In that case,
1397 // we do not need to remove it
1398 removeTabFromContentView(currentTab);
1400 mTabControl.setCurrentTab(tab);
1401 attachTabToContentView(tab);
1402 resetTitleIconAndProgress();
1403 updateLockIconToLatest();
1407 /* package */ Tab openTabToHomePage() {
1408 return openTabAndShow(mSettings.getHomePage(), false, null);
1411 /* package */ void closeCurrentWindow() {
1412 final Tab current = mTabControl.getCurrentTab();
1413 if (mTabControl.getTabCount() == 1) {
1414 // This is the last tab. Open a new one, with the home
1415 // page and close the current one.
1416 openTabToHomePage();
1420 final Tab parent = current.getParentTab();
1421 int indexToShow = -1;
1422 if (parent != null) {
1423 indexToShow = mTabControl.getTabIndex(parent);
1425 final int currentIndex = mTabControl.getCurrentIndex();
1426 // Try to move to the tab to the right
1427 indexToShow = currentIndex + 1;
1428 if (indexToShow > mTabControl.getTabCount() - 1) {
1429 // Try to move to the tab to the left
1430 indexToShow = currentIndex - 1;
1433 if (switchToTab(indexToShow)) {
1439 private ActiveTabsPage mActiveTabsPage;
1442 * Remove the active tabs page.
1443 * @param needToAttach If true, the active tabs page did not attach a tab
1444 * to the content view, so we need to do that here.
1446 /* package */ void removeActiveTabPage(boolean needToAttach) {
1447 mContentView.removeView(mActiveTabsPage);
1448 mActiveTabsPage = null;
1449 mMenuState = R.id.MAIN_MENU;
1451 attachTabToContentView(mTabControl.getCurrentTab());
1453 getTopWindow().requestFocus();
1457 public boolean onOptionsItemSelected(MenuItem item) {
1459 // The user has already fired a shortcut with this hold down of the
1463 if (null == getTopWindow()) {
1467 // The shortcut action consumes the MENU. Even if it is still down,
1468 // it won't trigger the next shortcut action. In the case of the
1469 // shortcut action triggering a new activity, like Bookmarks, we
1470 // won't get onKeyUp for MENU. So it is important to reset it here.
1471 mMenuIsDown = false;
1473 switch (item.getItemId()) {
1475 case R.id.new_tab_menu_id:
1476 openTabToHomePage();
1479 case R.id.goto_menu_id:
1483 case R.id.bookmarks_menu_id:
1484 bookmarksOrHistoryPicker(false);
1487 case R.id.active_tabs_menu_id:
1488 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1489 removeTabFromContentView(mTabControl.getCurrentTab());
1491 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1492 mActiveTabsPage.requestFocus();
1493 mMenuState = EMPTY_MENU;
1496 case R.id.add_bookmark_menu_id:
1497 Intent i = new Intent(BrowserActivity.this,
1498 AddBookmarkPage.class);
1499 WebView w = getTopWindow();
1500 i.putExtra("url", w.getUrl());
1501 i.putExtra("title", w.getTitle());
1502 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1503 i.putExtra("thumbnail", createScreenshot(w));
1507 case R.id.stop_reload_menu_id:
1511 getTopWindow().reload();
1515 case R.id.back_menu_id:
1516 getTopWindow().goBack();
1519 case R.id.forward_menu_id:
1520 getTopWindow().goForward();
1523 case R.id.close_menu_id:
1524 // Close the subwindow if it exists.
1525 if (mTabControl.getCurrentSubWindow() != null) {
1526 dismissSubWindow(mTabControl.getCurrentTab());
1529 closeCurrentWindow();
1532 case R.id.homepage_menu_id:
1533 Tab current = mTabControl.getCurrentTab();
1534 if (current != null) {
1535 dismissSubWindow(current);
1536 loadUrl(current.getWebView(), mSettings.getHomePage());
1540 case R.id.preferences_menu_id:
1541 Intent intent = new Intent(this,
1542 BrowserPreferencesPage.class);
1543 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1544 getTopWindow().getUrl());
1545 startActivityForResult(intent, PREFERENCES_PAGE);
1548 case R.id.find_menu_id:
1549 if (null == mFindDialog) {
1550 mFindDialog = new FindDialog(this);
1552 mFindDialog.setWebView(getTopWindow());
1554 getTopWindow().setFindIsUp(true);
1555 mMenuState = EMPTY_MENU;
1558 case R.id.select_text_id:
1559 getTopWindow().emulateShiftHeld();
1561 case R.id.page_info_menu_id:
1562 showPageInfo(mTabControl.getCurrentTab(), false);
1565 case R.id.classic_history_menu_id:
1566 bookmarksOrHistoryPicker(true);
1569 case R.id.title_bar_share_page_url:
1570 case R.id.share_page_menu_id:
1571 Tab currentTab = mTabControl.getCurrentTab();
1572 if (null == currentTab) {
1576 currentTab.populatePickerData();
1577 sharePage(this, currentTab.getTitle(),
1578 currentTab.getUrl(), currentTab.getFavicon(),
1579 createScreenshot(currentTab.getWebView()));
1582 case R.id.dump_nav_menu_id:
1583 getTopWindow().debugDump();
1586 case R.id.dump_counters_menu_id:
1587 getTopWindow().dumpV8Counters();
1590 case R.id.zoom_in_menu_id:
1591 getTopWindow().zoomIn();
1594 case R.id.zoom_out_menu_id:
1595 getTopWindow().zoomOut();
1598 case R.id.view_downloads_menu_id:
1599 viewDownloads(null);
1602 case R.id.window_one_menu_id:
1603 case R.id.window_two_menu_id:
1604 case R.id.window_three_menu_id:
1605 case R.id.window_four_menu_id:
1606 case R.id.window_five_menu_id:
1607 case R.id.window_six_menu_id:
1608 case R.id.window_seven_menu_id:
1609 case R.id.window_eight_menu_id:
1611 int menuid = item.getItemId();
1612 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1613 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1614 Tab desiredTab = mTabControl.getTab(id);
1615 if (desiredTab != null &&
1616 desiredTab != mTabControl.getCurrentTab()) {
1626 if (!super.onOptionsItemSelected(item)) {
1629 // Otherwise fall through.
1635 public void closeFind() {
1636 mMenuState = R.id.MAIN_MENU;
1640 public boolean onPrepareOptionsMenu(Menu menu) {
1641 // This happens when the user begins to hold down the menu key, so
1642 // allow them to chord to get a shortcut.
1644 // Note: setVisible will decide whether an item is visible; while
1645 // setEnabled() will decide whether an item is enabled, which also means
1646 // whether the matching shortcut key will function.
1647 super.onPrepareOptionsMenu(menu);
1648 switch (mMenuState) {
1650 if (mCurrentMenuState != mMenuState) {
1651 menu.setGroupVisible(R.id.MAIN_MENU, false);
1652 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1653 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1657 if (mCurrentMenuState != mMenuState) {
1658 menu.setGroupVisible(R.id.MAIN_MENU, true);
1659 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1660 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1662 final WebView w = getTopWindow();
1663 boolean canGoBack = false;
1664 boolean canGoForward = false;
1665 boolean isHome = false;
1667 canGoBack = w.canGoBack();
1668 canGoForward = w.canGoForward();
1669 isHome = mSettings.getHomePage().equals(w.getUrl());
1671 final MenuItem back = menu.findItem(R.id.back_menu_id);
1672 back.setEnabled(canGoBack);
1674 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1675 home.setEnabled(!isHome);
1677 menu.findItem(R.id.forward_menu_id)
1678 .setEnabled(canGoForward);
1680 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1681 mTabControl.canCreateNewTab());
1683 // decide whether to show the share link option
1684 PackageManager pm = getPackageManager();
1685 Intent send = new Intent(Intent.ACTION_SEND);
1686 send.setType("text/plain");
1687 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1688 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1690 boolean isNavDump = mSettings.isNavDump();
1691 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1692 nav.setVisible(isNavDump);
1693 nav.setEnabled(isNavDump);
1695 boolean showDebugSettings = mSettings.showDebugSettings();
1696 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1697 counter.setVisible(showDebugSettings);
1698 counter.setEnabled(showDebugSettings);
1702 mCurrentMenuState = mMenuState;
1707 public void onCreateContextMenu(ContextMenu menu, View v,
1708 ContextMenuInfo menuInfo) {
1709 if (v instanceof TitleBar) {
1712 WebView webview = (WebView) v;
1713 WebView.HitTestResult result = webview.getHitTestResult();
1714 if (result == null) {
1718 int type = result.getType();
1719 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1721 "We should not show context menu when nothing is touched");
1724 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1725 // let TextView handles context menu
1729 // Note, http://b/issue?id=1106666 is requesting that
1730 // an inflated menu can be used again. This is not available
1731 // yet, so inflate each time (yuk!)
1732 MenuInflater inflater = getMenuInflater();
1733 inflater.inflate(R.menu.browsercontext, menu);
1735 // Show the correct menu group
1736 String extra = result.getExtra();
1737 menu.setGroupVisible(R.id.PHONE_MENU,
1738 type == WebView.HitTestResult.PHONE_TYPE);
1739 menu.setGroupVisible(R.id.EMAIL_MENU,
1740 type == WebView.HitTestResult.EMAIL_TYPE);
1741 menu.setGroupVisible(R.id.GEO_MENU,
1742 type == WebView.HitTestResult.GEO_TYPE);
1743 menu.setGroupVisible(R.id.IMAGE_MENU,
1744 type == WebView.HitTestResult.IMAGE_TYPE
1745 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1746 menu.setGroupVisible(R.id.ANCHOR_MENU,
1747 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1748 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1750 // Setup custom handling depending on the type
1752 case WebView.HitTestResult.PHONE_TYPE:
1753 menu.setHeaderTitle(Uri.decode(extra));
1754 menu.findItem(R.id.dial_context_menu_id).setIntent(
1755 new Intent(Intent.ACTION_VIEW, Uri
1756 .parse(WebView.SCHEME_TEL + extra)));
1757 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1758 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1759 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1760 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1762 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1766 case WebView.HitTestResult.EMAIL_TYPE:
1767 menu.setHeaderTitle(extra);
1768 menu.findItem(R.id.email_context_menu_id).setIntent(
1769 new Intent(Intent.ACTION_VIEW, Uri
1770 .parse(WebView.SCHEME_MAILTO + extra)));
1771 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1775 case WebView.HitTestResult.GEO_TYPE:
1776 menu.setHeaderTitle(extra);
1777 menu.findItem(R.id.map_context_menu_id).setIntent(
1778 new Intent(Intent.ACTION_VIEW, Uri
1779 .parse(WebView.SCHEME_GEO
1780 + URLEncoder.encode(extra))));
1781 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1785 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1786 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1787 TextView titleView = (TextView) LayoutInflater.from(this)
1788 .inflate(android.R.layout.browser_link_context_header,
1790 titleView.setText(extra);
1791 menu.setHeaderView(titleView);
1792 // decide whether to show the open link in new tab option
1793 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1794 mTabControl.canCreateNewTab());
1795 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1796 Bookmarks.urlHasAcceptableScheme(extra));
1797 PackageManager pm = getPackageManager();
1798 Intent send = new Intent(Intent.ACTION_SEND);
1799 send.setType("text/plain");
1800 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1801 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1802 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1805 // otherwise fall through to handle image part
1806 case WebView.HitTestResult.IMAGE_TYPE:
1807 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1808 menu.setHeaderTitle(extra);
1810 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1811 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1812 menu.findItem(R.id.download_context_menu_id).
1813 setOnMenuItemClickListener(new Download(extra));
1814 menu.findItem(R.id.set_wallpaper_context_menu_id).
1815 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1819 Log.w(LOGTAG, "We should not get here.");
1825 // Attach the given tab to the content view.
1826 // this should only be called for the current tab.
1827 private void attachTabToContentView(Tab t) {
1828 // Attach the container that contains the main WebView and any other UI
1829 // associated with the tab.
1830 t.attachTabToContentView(mContentView);
1832 if (mShouldShowErrorConsole) {
1833 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1834 if (errorConsole.numberOfErrors() == 0) {
1835 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1837 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1840 mErrorConsoleContainer.addView(errorConsole,
1841 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1842 ViewGroup.LayoutParams.WRAP_CONTENT));
1845 WebView view = t.getWebView();
1846 view.setEmbeddedTitleBar(mTitleBar);
1847 if (t.isInVoiceSearchMode()) {
1848 showVoiceTitleBar(t.getVoiceDisplayTitle());
1850 revertVoiceTitleBar();
1852 // Request focus on the top window.
1853 t.getTopWindow().requestFocus();
1856 // Attach a sub window to the main WebView of the given tab.
1857 void attachSubWindow(Tab t) {
1858 t.attachSubWindow(mContentView);
1859 getTopWindow().requestFocus();
1862 // Remove the given tab from the content view.
1863 private void removeTabFromContentView(Tab t) {
1864 // Remove the container that contains the main WebView.
1865 t.removeTabFromContentView(mContentView);
1867 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1868 if (errorConsole != null) {
1869 mErrorConsoleContainer.removeView(errorConsole);
1872 WebView view = t.getWebView();
1874 view.setEmbeddedTitleBar(null);
1878 // Remove the sub window if it exists. Also called by TabControl when the
1879 // user clicks the 'X' to dismiss a sub window.
1880 /* package */ void dismissSubWindow(Tab t) {
1881 t.removeSubWindow(mContentView);
1882 // dismiss the subwindow. This will destroy the WebView.
1883 t.dismissSubWindow();
1884 getTopWindow().requestFocus();
1887 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1888 // that accepts url as string.
1889 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1890 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1893 // This method does a ton of stuff. It will attempt to create a new tab
1894 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1895 // url isn't null, it will load the given url.
1896 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1898 final Tab currentTab = mTabControl.getCurrentTab();
1899 if (mTabControl.canCreateNewTab()) {
1900 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1902 WebView webview = tab.getWebView();
1903 // If the last tab was removed from the active tabs page, currentTab
1905 if (currentTab != null) {
1906 removeTabFromContentView(currentTab);
1908 // We must set the new tab as the current tab to reflect the old
1909 // animation behavior.
1910 mTabControl.setCurrentTab(tab);
1911 attachTabToContentView(tab);
1912 if (!urlData.isEmpty()) {
1913 loadUrlDataIn(tab, urlData);
1917 // Get rid of the subwindow if it exists
1918 dismissSubWindow(currentTab);
1919 if (!urlData.isEmpty()) {
1920 // Load the given url.
1921 loadUrlDataIn(currentTab, urlData);
1927 private Tab openTab(String url) {
1928 if (mSettings.openInBackground()) {
1929 Tab t = mTabControl.createNewTab();
1931 WebView view = t.getWebView();
1936 return openTabAndShow(url, false, null);
1940 private class Copy implements OnMenuItemClickListener {
1941 private CharSequence mText;
1943 public boolean onMenuItemClick(MenuItem item) {
1948 public Copy(CharSequence toCopy) {
1953 private class Download implements OnMenuItemClickListener {
1954 private String mText;
1956 public boolean onMenuItemClick(MenuItem item) {
1957 onDownloadStartNoStream(mText, null, null, null, -1);
1961 public Download(String toDownload) {
1966 private class SetAsWallpaper extends Thread implements
1967 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1969 private ProgressDialog mWallpaperProgress;
1970 private boolean mCanceled = false;
1972 public SetAsWallpaper(String url) {
1974 mUrl = new URL(url);
1975 } catch (MalformedURLException e) {
1980 public void onCancel(DialogInterface dialog) {
1984 public boolean onMenuItemClick(MenuItem item) {
1986 // The user may have tried to set a image with a large file size as their
1987 // background so it may take a few moments to perform the operation. Display
1988 // a progress spinner while it is working.
1989 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1990 mWallpaperProgress.setIndeterminate(true);
1991 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1992 mWallpaperProgress.setCancelable(true);
1993 mWallpaperProgress.setOnCancelListener(this);
1994 mWallpaperProgress.show();
2001 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
2003 // TODO: This will cause the resource to be downloaded again, when we
2004 // should in most cases be able to grab it from the cache. To fix this
2005 // we should query WebCore to see if we can access a cached version and
2006 // instead open an input stream on that. This pattern could also be used
2007 // in the download manager where the same problem exists.
2008 InputStream inputstream = mUrl.openStream();
2009 if (inputstream != null) {
2010 setWallpaper(inputstream);
2012 } catch (IOException e) {
2013 Log.e(LOGTAG, "Unable to set new wallpaper");
2014 // Act as though the user canceled the operation so we try to
2015 // restore the old wallpaper.
2020 // Restore the old wallpaper if the user cancelled whilst we were setting
2021 // the new wallpaper.
2022 int width = oldWallpaper.getIntrinsicWidth();
2023 int height = oldWallpaper.getIntrinsicHeight();
2024 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
2025 Canvas canvas = new Canvas(bm);
2026 oldWallpaper.setBounds(0, 0, width, height);
2027 oldWallpaper.draw(canvas);
2030 } catch (IOException e) {
2031 Log.e(LOGTAG, "Unable to restore old wallpaper.");
2036 if (mWallpaperProgress.isShowing()) {
2037 mWallpaperProgress.dismiss();
2042 private void copy(CharSequence text) {
2044 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2046 clip.setClipboardText(text);
2048 } catch (android.os.RemoteException e) {
2049 Log.e(LOGTAG, "Copy failed", e);
2054 * Resets the browser title-view to whatever it must be
2055 * (for example, if we had a loading error)
2056 * When we have a new page, we call resetTitle, when we
2057 * have to reset the titlebar to whatever it used to be
2058 * (for example, if the user chose to stop loading), we
2059 * call resetTitleAndRevertLockIcon.
2061 /* package */ void resetTitleAndRevertLockIcon() {
2062 mTabControl.getCurrentTab().revertLockIcon();
2063 updateLockIconToLatest();
2064 resetTitleIconAndProgress();
2068 * Reset the title, favicon, and progress.
2070 private void resetTitleIconAndProgress() {
2071 WebView current = mTabControl.getCurrentWebView();
2072 if (current == null) {
2075 resetTitleAndIcon(current);
2076 int progress = current.getProgress();
2077 current.getWebChromeClient().onProgressChanged(current, progress);
2080 // Reset the title and the icon based on the given item.
2081 private void resetTitleAndIcon(WebView view) {
2082 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2084 setUrlTitle(item.getUrl(), item.getTitle());
2085 setFavicon(item.getFavicon());
2087 setUrlTitle(null, null);
2093 * Sets a title composed of the URL and the title string.
2094 * @param url The URL of the site being loaded.
2095 * @param title The title of the site being loaded.
2097 void setUrlTitle(String url, String title) {
2101 // If we are in voice search mode, the title has already been set.
2102 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
2103 mTitleBar.setDisplayTitle(url);
2104 mFakeTitleBar.setDisplayTitle(url);
2108 * @param url The URL to build a title version of the URL from.
2109 * @return The title version of the URL or null if fails.
2110 * The title version of the URL can be either the URL hostname,
2111 * or the hostname with an "https://" prefix (for secure URLs),
2112 * or an empty string if, for example, the URL in question is a
2113 * file:// URL with no hostname.
2115 /* package */ static String buildTitleUrl(String url) {
2116 String titleUrl = null;
2120 // parse the url string
2121 URL urlObj = new URL(url);
2122 if (urlObj != null) {
2125 String protocol = urlObj.getProtocol();
2126 String host = urlObj.getHost();
2128 if (host != null && 0 < host.length()) {
2130 if (protocol != null) {
2131 // if a secure site, add an "https://" prefix!
2132 if (protocol.equalsIgnoreCase("https")) {
2133 titleUrl = protocol + "://" + host;
2138 } catch (MalformedURLException e) {}
2144 // Set the favicon in the title bar.
2145 void setFavicon(Bitmap icon) {
2146 mTitleBar.setFavicon(icon);
2147 mFakeTitleBar.setFavicon(icon);
2151 * Close the tab, remove its associated title bar, and adjust mTabControl's
2152 * current tab to a valid value.
2154 /* package */ void closeTab(Tab t) {
2155 int currentIndex = mTabControl.getCurrentIndex();
2156 int removeIndex = mTabControl.getTabIndex(t);
2157 mTabControl.removeTab(t);
2158 if (currentIndex >= removeIndex && currentIndex != 0) {
2161 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2162 resetTitleIconAndProgress();
2165 /* package */ void goBackOnePageOrQuit() {
2166 Tab current = mTabControl.getCurrentTab();
2167 if (current == null) {
2169 * Instead of finishing the activity, simply push this to the back
2170 * of the stack and let ActivityManager to choose the foreground
2171 * activity. As BrowserActivity is singleTask, it will be always the
2172 * root of the task. So we can use either true or false for
2175 moveTaskToBack(true);
2178 WebView w = current.getWebView();
2179 if (w.canGoBack()) {
2182 // Check to see if we are closing a window that was created by
2183 // another window. If so, we switch back to that window.
2184 Tab parent = current.getParentTab();
2185 if (parent != null) {
2186 switchToTab(mTabControl.getTabIndex(parent));
2187 // Now we close the other tab
2190 if (current.closeOnExit()) {
2191 // force the tab's inLoad() to be false as we are going to
2192 // either finish the activity or remove the tab. This will
2193 // ensure pauseWebViewTimers() taking action.
2194 mTabControl.getCurrentTab().clearInLoad();
2195 if (mTabControl.getTabCount() == 1) {
2199 // call pauseWebViewTimers() now, we won't be able to call
2200 // it in onPause() as the WebView won't be valid.
2201 // Temporarily change mActivityInPause to be true as
2202 // pauseWebViewTimers() will do nothing if mActivityInPause
2204 boolean savedState = mActivityInPause;
2206 Log.e(LOGTAG, "BrowserActivity is already paused "
2207 + "while handing goBackOnePageOrQuit.");
2209 mActivityInPause = true;
2210 pauseWebViewTimers();
2211 mActivityInPause = savedState;
2212 removeTabFromContentView(current);
2213 mTabControl.removeTab(current);
2216 * Instead of finishing the activity, simply push this to the back
2217 * of the stack and let ActivityManager to choose the foreground
2218 * activity. As BrowserActivity is singleTask, it will be always the
2219 * root of the task. So we can use either true or false for
2222 moveTaskToBack(true);
2227 boolean isMenuDown() {
2232 public boolean onKeyDown(int keyCode, KeyEvent event) {
2233 // Even if MENU is already held down, we need to call to super to open
2234 // the IME on long press.
2235 if (KeyEvent.KEYCODE_MENU == keyCode) {
2237 return super.onKeyDown(keyCode, event);
2239 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2240 // still down, we don't want to trigger the search. Pretend to consume
2241 // the key and do nothing.
2242 if (mMenuIsDown) return true;
2245 case KeyEvent.KEYCODE_SPACE:
2246 // WebView/WebTextView handle the keys in the KeyDown. As
2247 // the Activity's shortcut keys are only handled when WebView
2248 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2249 if (event.isShiftPressed()) {
2250 getTopWindow().pageUp(false);
2252 getTopWindow().pageDown(false);
2255 case KeyEvent.KEYCODE_BACK:
2256 if (event.getRepeatCount() == 0) {
2257 event.startTracking();
2259 } else if (mCustomView == null && mActiveTabsPage == null
2260 && event.isLongPress()) {
2261 bookmarksOrHistoryPicker(true);
2266 return super.onKeyDown(keyCode, event);
2270 public boolean onKeyUp(int keyCode, KeyEvent event) {
2272 case KeyEvent.KEYCODE_MENU:
2273 mMenuIsDown = false;
2275 case KeyEvent.KEYCODE_BACK:
2276 if (event.isTracking() && !event.isCanceled()) {
2277 if (mCustomView != null) {
2278 // if a custom view is showing, hide it
2279 mTabControl.getCurrentWebView().getWebChromeClient()
2280 .onHideCustomView();
2281 } else if (mActiveTabsPage != null) {
2282 // if tab page is showing, hide it
2283 removeActiveTabPage(true);
2285 WebView subwindow = mTabControl.getCurrentSubWindow();
2286 if (subwindow != null) {
2287 if (subwindow.canGoBack()) {
2290 dismissSubWindow(mTabControl.getCurrentTab());
2293 goBackOnePageOrQuit();
2300 return super.onKeyUp(keyCode, event);
2303 /* package */ void stopLoading() {
2304 mDidStopLoad = true;
2305 resetTitleAndRevertLockIcon();
2306 WebView w = getTopWindow();
2308 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2309 // same logic here. But for subwindow case, should we call into the main
2310 // WebView's onPageFinished as we never call its onPageStarted and if
2311 // the page finishes itself, we don't call onPageFinished.
2312 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2317 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2321 boolean didUserStopLoading() {
2322 return mDidStopLoad;
2325 private void cancelStopToast() {
2326 if (mStopToast != null) {
2327 mStopToast.cancel();
2332 // called by a UI or non-UI thread to post the message
2333 public void postMessage(int what, int arg1, int arg2, Object obj,
2335 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2339 // called by a UI or non-UI thread to remove the message
2340 void removeMessages(int what, Object object) {
2341 mHandler.removeMessages(what, object);
2344 // public message ids
2345 public final static int LOAD_URL = 1001;
2346 public final static int STOP_LOAD = 1002;
2349 private static final int FOCUS_NODE_HREF = 102;
2350 private static final int CANCEL_CREDS_REQUEST = 103;
2351 private static final int RELEASE_WAKELOCK = 107;
2353 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2355 // Private handler for handling javascript and saving passwords
2356 private Handler mHandler = new Handler() {
2358 public void handleMessage(Message msg) {
2360 case FOCUS_NODE_HREF:
2362 String url = (String) msg.getData().get("url");
2363 String title = (String) msg.getData().get("title");
2364 if (url == null || url.length() == 0) {
2367 HashMap focusNodeMap = (HashMap) msg.obj;
2368 WebView view = (WebView) focusNodeMap.get("webview");
2369 // Only apply the action if the top window did not change.
2370 if (getTopWindow() != view) {
2374 case R.id.open_context_menu_id:
2375 case R.id.view_image_context_menu_id:
2376 loadUrlFromContext(getTopWindow(), url);
2378 case R.id.open_newtab_context_menu_id:
2379 final Tab parent = mTabControl.getCurrentTab();
2380 final Tab newTab = openTab(url);
2381 if (newTab != parent) {
2382 parent.addChildTab(newTab);
2385 case R.id.bookmark_context_menu_id:
2386 Intent intent = new Intent(BrowserActivity.this,
2387 AddBookmarkPage.class);
2388 intent.putExtra("url", url);
2389 intent.putExtra("title", title);
2390 startActivity(intent);
2392 case R.id.share_link_context_menu_id:
2393 // See if this site has been visited before
2394 StringBuilder sb = new StringBuilder(
2395 Browser.BookmarkColumns.URL + " = ");
2396 DatabaseUtils.appendEscapedSQLString(sb, url);
2397 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2398 Browser.HISTORY_PROJECTION,
2402 if (c.moveToFirst()) {
2403 // The site has been visited before, so grab the
2404 // info from the database.
2405 Bitmap favicon = null;
2406 Bitmap thumbnail = null;
2407 String linkTitle = c.getString(Browser.
2408 HISTORY_PROJECTION_TITLE_INDEX);
2409 byte[] data = c.getBlob(Browser.
2410 HISTORY_PROJECTION_FAVICON_INDEX);
2412 favicon = BitmapFactory.decodeByteArray(
2413 data, 0, data.length);
2415 data = c.getBlob(Browser.
2416 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2418 thumbnail = BitmapFactory.decodeByteArray(
2419 data, 0, data.length);
2421 sharePage(BrowserActivity.this,
2422 linkTitle, url, favicon, thumbnail);
2424 Browser.sendString(BrowserActivity.this, url,
2426 R.string.choosertitle_sharevia));
2429 case R.id.copy_link_context_menu_id:
2432 case R.id.save_link_context_menu_id:
2433 case R.id.download_context_menu_id:
2434 onDownloadStartNoStream(url, null, null, null, -1);
2441 loadUrlFromContext(getTopWindow(), (String) msg.obj);
2448 case CANCEL_CREDS_REQUEST:
2449 resumeAfterCredentials();
2452 case RELEASE_WAKELOCK:
2453 if (mWakeLock.isHeld()) {
2454 mWakeLock.release();
2455 // if we reach here, Browser should be still in the
2456 // background loading after WAKELOCK_TIMEOUT (5-min).
2457 // To avoid burning the battery, stop loading.
2458 mTabControl.stopAllLoading();
2462 case UPDATE_BOOKMARK_THUMBNAIL:
2463 WebView view = (WebView) msg.obj;
2465 updateScreenshot(view);
2473 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2474 * an {@link Intent} to launch the Activity chooser.
2475 * @param c Context used to launch a new Activity.
2476 * @param title Title of the page. Stored in the Intent with
2477 * {@link Intent#EXTRA_SUBJECT}
2478 * @param url URL of the page. Stored in the Intent with
2479 * {@link Intent#EXTRA_TEXT}
2480 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2481 * with {@link Browser#EXTRA_SHARE_FAVICON}
2482 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2483 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2485 public static final void sharePage(Context c, String title, String url,
2486 Bitmap favicon, Bitmap screenshot) {
2487 Intent send = new Intent(Intent.ACTION_SEND);
2488 send.setType("text/plain");
2489 send.putExtra(Intent.EXTRA_TEXT, url);
2490 send.putExtra(Intent.EXTRA_SUBJECT, title);
2491 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2492 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2494 c.startActivity(Intent.createChooser(send, c.getString(
2495 R.string.choosertitle_sharevia)));
2496 } catch(android.content.ActivityNotFoundException ex) {
2497 // if no app handles it, do nothing
2501 private void updateScreenshot(WebView view) {
2502 // If this is a bookmarked site, add a screenshot to the database.
2503 // FIXME: When should we update? Every time?
2504 // FIXME: Would like to make sure there is actually something to
2505 // draw, but the API for that (WebViewCore.pictureReady()) is not
2506 // currently accessible here.
2508 ContentResolver cr = getContentResolver();
2509 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2510 cr, view.getOriginalUrl(), view.getUrl(), true);
2512 boolean succeed = c.moveToFirst();
2513 ContentValues values = null;
2515 if (values == null) {
2516 final ByteArrayOutputStream os
2517 = new ByteArrayOutputStream();
2518 Bitmap bm = createScreenshot(view);
2523 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2524 values = new ContentValues();
2525 values.put(Browser.BookmarkColumns.THUMBNAIL,
2528 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2529 c.getInt(0)), values, null, null);
2530 succeed = c.moveToNext();
2537 * Values for the size of the thumbnail created when taking a screenshot.
2538 * Lazily initialized. Instead of using these directly, use
2539 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2541 private static int THUMBNAIL_WIDTH = 0;
2542 private static int THUMBNAIL_HEIGHT = 0;
2545 * Return the desired width for thumbnail screenshots, which are stored in
2546 * the database, and used on the bookmarks screen.
2547 * @param context Context for finding out the density of the screen.
2548 * @return int desired width for thumbnail screenshot.
2550 /* package */ static int getDesiredThumbnailWidth(Context context) {
2551 if (THUMBNAIL_WIDTH == 0) {
2552 float density = context.getResources().getDisplayMetrics().density;
2553 THUMBNAIL_WIDTH = (int) (90 * density);
2554 THUMBNAIL_HEIGHT = (int) (80 * density);
2556 return THUMBNAIL_WIDTH;
2560 * Return the desired height for thumbnail screenshots, which are stored in
2561 * the database, and used on the bookmarks screen.
2562 * @param context Context for finding out the density of the screen.
2563 * @return int desired height for thumbnail screenshot.
2565 /* package */ static int getDesiredThumbnailHeight(Context context) {
2566 // To ensure that they are both initialized.
2567 getDesiredThumbnailWidth(context);
2568 return THUMBNAIL_HEIGHT;
2571 private Bitmap createScreenshot(WebView view) {
2572 Picture thumbnail = view.capturePicture();
2573 if (thumbnail == null) {
2576 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2577 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2578 Canvas canvas = new Canvas(bm);
2579 // May need to tweak these values to determine what is the
2580 // best scale factor
2581 int thumbnailWidth = thumbnail.getWidth();
2582 int thumbnailHeight = thumbnail.getHeight();
2583 float scaleFactorX = 1.0f;
2584 float scaleFactorY = 1.0f;
2585 if (thumbnailWidth > 0) {
2586 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2587 (float)thumbnailWidth;
2592 if (view.getWidth() > view.getHeight() &&
2593 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2594 // If the device is in landscape and the page is shorter
2595 // than the height of the view, stretch the thumbnail to fill the
2597 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2598 (float)thumbnailHeight;
2600 // In the portrait case, this looks nice.
2601 scaleFactorY = scaleFactorX;
2604 canvas.scale(scaleFactorX, scaleFactorY);
2606 thumbnail.draw(canvas);
2610 // -------------------------------------------------------------------------
2611 // Helper function for WebViewClient.
2612 //-------------------------------------------------------------------------
2614 // Use in overrideUrlLoading
2615 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2616 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2617 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2618 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2620 // Keep this initial progress in sync with initialProgressValue (* 100)
2621 // in ProgressTracker.cpp
2622 private final static int INITIAL_PROGRESS = 10;
2624 void onPageStarted(WebView view, String url, Bitmap favicon) {
2625 // when BrowserActivity just starts, onPageStarted may be called before
2626 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2627 // to start the timer. As we won't switch tabs while an activity is in
2628 // pause state, we can ensure calling resume and pause in pair.
2629 if (mActivityInPause) resumeWebViewTimers();
2632 setUrlTitle(url, null);
2633 setFavicon(favicon);
2634 // Show some progress so that the user knows the page is beginning to
2636 onProgressChanged(view, INITIAL_PROGRESS);
2637 mDidStopLoad = false;
2638 if (!mIsNetworkUp) createAndShowNetworkDialog();
2640 if (mSettings.isTracing()) {
2643 WebAddress uri = new WebAddress(url);
2645 } catch (android.net.ParseException ex) {
2648 host = host.replace('.', '_');
2651 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2654 // Performance probe
2656 mStart = SystemClock.uptimeMillis();
2657 mProcessStart = Process.getElapsedCpuTime();
2658 long[] sysCpu = new long[7];
2659 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2661 mUserStart = sysCpu[0] + sysCpu[1];
2662 mSystemStart = sysCpu[2];
2663 mIdleStart = sysCpu[3];
2664 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2666 mUiStart = SystemClock.currentThreadTimeMillis();
2670 void onPageFinished(WebView view, String url) {
2671 // Reset the title and icon in case we stopped a provisional load.
2672 resetTitleAndIcon(view);
2673 // Update the lock icon image only once we are done loading
2674 updateLockIconToLatest();
2675 // pause the WebView timer and release the wake lock if it is finished
2676 // while BrowserActivity is in pause state.
2677 if (mActivityInPause && pauseWebViewTimers()) {
2678 if (mWakeLock.isHeld()) {
2679 mHandler.removeMessages(RELEASE_WAKELOCK);
2680 mWakeLock.release();
2684 // Performance probe
2686 long[] sysCpu = new long[7];
2687 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2689 String uiInfo = "UI thread used "
2690 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2693 Log.d(LOGTAG, uiInfo);
2695 //The string that gets written to the log
2696 String performanceString = "It took total "
2697 + (SystemClock.uptimeMillis() - mStart)
2698 + " ms clock time to load the page."
2699 + "\nbrowser process used "
2700 + (Process.getElapsedCpuTime() - mProcessStart)
2701 + " ms, user processes used "
2702 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2703 + " ms, kernel used "
2704 + (sysCpu[2] - mSystemStart) * 10
2705 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2706 + " ms and irq took "
2707 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2708 * 10 + " ms, " + uiInfo;
2710 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2713 // strip the url to maintain consistency
2714 String newUrl = new String(url);
2715 if (newUrl.startsWith("http://www.")) {
2716 newUrl = newUrl.substring(11);
2717 } else if (newUrl.startsWith("http://")) {
2718 newUrl = newUrl.substring(7);
2719 } else if (newUrl.startsWith("https://www.")) {
2720 newUrl = newUrl.substring(12);
2721 } else if (newUrl.startsWith("https://")) {
2722 newUrl = newUrl.substring(8);
2725 Log.d(LOGTAG, newUrl + " loaded");
2733 Debug.stopMethodTracing();
2737 boolean shouldOverrideUrlLoading(WebView view, String url) {
2738 if (url.startsWith(SCHEME_WTAI)) {
2739 // wtai://wp/mc;number
2740 // number=string(phone-number)
2741 if (url.startsWith(SCHEME_WTAI_MC)) {
2742 Intent intent = new Intent(Intent.ACTION_VIEW,
2743 Uri.parse(WebView.SCHEME_TEL +
2744 url.substring(SCHEME_WTAI_MC.length())));
2745 startActivity(intent);
2748 // wtai://wp/sd;dtmf
2749 // dtmf=string(dialstring)
2750 if (url.startsWith(SCHEME_WTAI_SD)) {
2751 // TODO: only send when there is active voice connection
2754 // wtai://wp/ap;number;name
2755 // number=string(phone-number)
2757 if (url.startsWith(SCHEME_WTAI_AP)) {
2763 // The "about:" schemes are internal to the browser; don't want these to
2764 // be dispatched to other apps.
2765 if (url.startsWith("about:")) {
2770 // perform generic parsing of the URI to turn it into an Intent.
2772 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2773 } catch (URISyntaxException ex) {
2774 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2778 // check whether the intent can be resolved. If not, we will see
2779 // whether we can download it from the Market.
2780 if (getPackageManager().resolveActivity(intent, 0) == null) {
2781 String packagename = intent.getPackage();
2782 if (packagename != null) {
2783 intent = new Intent(Intent.ACTION_VIEW, Uri
2784 .parse("market://search?q=pname:" + packagename));
2785 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2786 startActivity(intent);
2793 // sanitize the Intent, ensuring web pages can not bypass browser
2794 // security (only access to BROWSABLE activities).
2795 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2796 intent.setComponent(null);
2798 if (startActivityIfNeeded(intent, -1)) {
2801 } catch (ActivityNotFoundException ex) {
2802 // ignore the error. If no application can handle the URL,
2803 // eg about:blank, assume the browser can handle it.
2814 // -------------------------------------------------------------------------
2815 // Helper function for WebChromeClient
2816 // -------------------------------------------------------------------------
2818 void onProgressChanged(WebView view, int newProgress) {
2819 mTitleBar.setProgress(newProgress);
2820 mFakeTitleBar.setProgress(newProgress);
2822 if (newProgress == 100) {
2823 // onProgressChanged() may continue to be called after the main
2824 // frame has finished loading, as any remaining sub frames continue
2825 // to load. We'll only get called once though with newProgress as
2826 // 100 when everything is loaded. (onPageFinished is called once
2827 // when the main frame completes loading regardless of the state of
2828 // any sub frames so calls to onProgressChanges may continue after
2829 // onPageFinished has executed)
2832 updateInLoadMenuItems();
2833 // If the options menu is open, leave the title bar
2834 if (!mOptionsMenuOpen || !mIconView) {
2840 // onPageFinished may have already been called but a subframe is
2841 // still loading and updating the progress. Reset mInLoad and
2842 // update the menu items.
2844 updateInLoadMenuItems();
2846 // When the page first begins to load, the Activity may still be
2847 // paused, in which case showFakeTitleBar will do nothing. Call
2848 // again as the page continues to load so that it will be shown.
2849 // (Calling it will the fake title bar is already showing will also
2851 if (!mOptionsMenuOpen || mIconView) {
2852 // This page has begun to load, so show the title bar
2858 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2859 // if a view already exists then immediately terminate the new one
2860 if (mCustomView != null) {
2861 callback.onCustomViewHidden();
2865 // Add the custom view to its container.
2866 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2868 mCustomViewCallback = callback;
2869 // Save the menu state and set it to empty while the custom
2871 mOldMenuState = mMenuState;
2872 mMenuState = EMPTY_MENU;
2873 // Hide the content view.
2874 mContentView.setVisibility(View.GONE);
2875 // Finally show the custom view container.
2876 setStatusBarVisibility(false);
2877 mCustomViewContainer.setVisibility(View.VISIBLE);
2878 mCustomViewContainer.bringToFront();
2881 void onHideCustomView() {
2882 if (mCustomView == null)
2885 // Hide the custom view.
2886 mCustomView.setVisibility(View.GONE);
2887 // Remove the custom view from its container.
2888 mCustomViewContainer.removeView(mCustomView);
2890 // Reset the old menu state.
2891 mMenuState = mOldMenuState;
2892 mOldMenuState = EMPTY_MENU;
2893 mCustomViewContainer.setVisibility(View.GONE);
2894 mCustomViewCallback.onCustomViewHidden();
2895 // Show the content view.
2896 setStatusBarVisibility(true);
2897 mContentView.setVisibility(View.VISIBLE);
2900 Bitmap getDefaultVideoPoster() {
2901 if (mDefaultVideoPoster == null) {
2902 mDefaultVideoPoster = BitmapFactory.decodeResource(
2903 getResources(), R.drawable.default_video_poster);
2905 return mDefaultVideoPoster;
2908 View getVideoLoadingProgressView() {
2909 if (mVideoProgressView == null) {
2910 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2911 mVideoProgressView = inflater.inflate(
2912 R.layout.video_loading_progress, null);
2914 return mVideoProgressView;
2918 * The Object used to inform the WebView of the file to upload.
2920 private ValueCallback<Uri> mUploadMessage;
2922 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2923 if (mUploadMessage != null) return;
2924 mUploadMessage = uploadMsg;
2925 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2926 i.addCategory(Intent.CATEGORY_OPENABLE);
2928 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2929 getString(R.string.choose_upload)), FILE_SELECTED);
2932 // -------------------------------------------------------------------------
2933 // Implement functions for DownloadListener
2934 // -------------------------------------------------------------------------
2937 * Notify the host application a download should be done, or that
2938 * the data should be streamed if a streaming viewer is available.
2939 * @param url The full url to the content that should be downloaded
2940 * @param contentDisposition Content-disposition http header, if
2942 * @param mimetype The mimetype of the content reported by the server
2943 * @param contentLength The file size reported by the server
2945 public void onDownloadStart(String url, String userAgent,
2946 String contentDisposition, String mimetype, long contentLength) {
2947 // if we're dealing wih A/V content that's not explicitly marked
2948 // for download, check if it's streamable.
2949 if (contentDisposition == null
2950 || !contentDisposition.regionMatches(
2951 true, 0, "attachment", 0, 10)) {
2952 // query the package manager to see if there's a registered handler
2954 Intent intent = new Intent(Intent.ACTION_VIEW);
2955 intent.setDataAndType(Uri.parse(url), mimetype);
2956 ResolveInfo info = getPackageManager().resolveActivity(intent,
2957 PackageManager.MATCH_DEFAULT_ONLY);
2959 ComponentName myName = getComponentName();
2960 // If we resolved to ourselves, we don't want to attempt to
2961 // load the url only to try and download it again.
2962 if (!myName.getPackageName().equals(
2963 info.activityInfo.packageName)
2964 || !myName.getClassName().equals(
2965 info.activityInfo.name)) {
2966 // someone (other than us) knows how to handle this mime
2967 // type with this scheme, don't download.
2969 startActivity(intent);
2971 } catch (ActivityNotFoundException ex) {
2973 Log.d(LOGTAG, "activity not found for " + mimetype
2974 + " over " + Uri.parse(url).getScheme(),
2977 // Best behavior is to fall back to a download in this
2983 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2987 * Notify the host application a download should be done, even if there
2988 * is a streaming viewer available for thise type.
2989 * @param url The full url to the content that should be downloaded
2990 * @param contentDisposition Content-disposition http header, if
2992 * @param mimetype The mimetype of the content reported by the server
2993 * @param contentLength The file size reported by the server
2995 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2996 String contentDisposition, String mimetype, long contentLength) {
2998 String filename = URLUtil.guessFileName(url,
2999 contentDisposition, mimetype);
3001 // Check to see if we have an SDCard
3002 String status = Environment.getExternalStorageState();
3003 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3007 // Check to see if the SDCard is busy, same as the music app
3008 if (status.equals(Environment.MEDIA_SHARED)) {
3009 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3010 title = R.string.download_sdcard_busy_dlg_title;
3012 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3013 title = R.string.download_no_sdcard_dlg_title;
3016 new AlertDialog.Builder(this)
3018 .setIcon(android.R.drawable.ic_dialog_alert)
3020 .setPositiveButton(R.string.ok, null)
3025 // java.net.URI is a lot stricter than KURL so we have to undo
3026 // KURL's percent-encoding and redo the encoding using java.net.URI.
3029 // Undo the percent-encoding that KURL may have done.
3030 String newUrl = new String(URLUtil.decode(url.getBytes()));
3031 // Parse the url into pieces
3032 WebAddress w = new WebAddress(newUrl);
3034 String query = null;
3035 String path = w.mPath;
3036 // Break the path into path, query, and fragment
3037 if (path.length() > 0) {
3038 // Strip the fragment
3039 int idx = path.lastIndexOf('#');
3041 frag = path.substring(idx + 1);
3042 path = path.substring(0, idx);
3044 idx = path.lastIndexOf('?');
3046 query = path.substring(idx + 1);
3047 path = path.substring(0, idx);
3050 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3052 } catch (Exception e) {
3053 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3057 // XXX: Have to use the old url since the cookies were stored using the
3058 // old percent-encoded url.
3059 String cookies = CookieManager.getInstance().getCookie(url);
3061 ContentValues values = new ContentValues();
3062 values.put(Downloads.Impl.COLUMN_URI, uri.toString());
3063 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
3064 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
3065 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
3067 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
3068 BrowserDownloadPage.class.getCanonicalName());
3069 values.put(Downloads.Impl.COLUMN_VISIBILITY,
3070 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3071 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
3072 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
3073 values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
3074 if (contentLength > 0) {
3075 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
3077 if (mimetype == null) {
3078 // We must have long pressed on a link or image to download it. We
3079 // are not sure of the mimetype in this case, so do a head request
3080 new FetchUrlMimeType(this).execute(values);
3082 final Uri contentUri =
3083 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
3088 // -------------------------------------------------------------------------
3091 * Resets the lock icon. This method is called when we start a new load and
3092 * know the url to be loaded.
3094 private void resetLockIcon(String url) {
3095 // Save the lock-icon state (we revert to it if the load gets cancelled)
3096 mTabControl.getCurrentTab().resetLockIcon(url);
3097 updateLockIconImage(LOCK_ICON_UNSECURE);
3101 * Update the lock icon to correspond to our latest state.
3103 private void updateLockIconToLatest() {
3104 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
3108 * Updates the lock-icon image in the title-bar.
3110 private void updateLockIconImage(int lockIconType) {
3112 if (lockIconType == LOCK_ICON_SECURE) {
3114 } else if (lockIconType == LOCK_ICON_MIXED) {
3117 mTitleBar.setLock(d);
3118 mFakeTitleBar.setLock(d);
3122 * Displays a page-info dialog.
3123 * @param tab The tab to show info about
3124 * @param fromShowSSLCertificateOnError The flag that indicates whether
3125 * this dialog was opened from the SSL-certificate-on-error dialog or
3126 * not. This is important, since we need to know whether to return to
3127 * the parent dialog or simply dismiss.
3129 private void showPageInfo(final Tab tab,
3130 final boolean fromShowSSLCertificateOnError) {
3131 final LayoutInflater factory = LayoutInflater
3134 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3136 final WebView view = tab.getWebView();
3139 String title = null;
3143 title = tab.getTitle();
3144 } else if (view == mTabControl.getCurrentWebView()) {
3145 // Use the cached title and url if this is the current WebView
3149 url = view.getUrl();
3150 title = view.getTitle();
3156 if (title == null) {
3160 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3161 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3163 mPageInfoView = tab;
3164 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3166 AlertDialog.Builder alertDialogBuilder =
3167 new AlertDialog.Builder(this)
3168 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3169 .setView(pageInfoView)
3172 new DialogInterface.OnClickListener() {
3173 public void onClick(DialogInterface dialog,
3175 mPageInfoDialog = null;
3176 mPageInfoView = null;
3178 // if we came here from the SSL error dialog
3179 if (fromShowSSLCertificateOnError) {
3180 // go back to the SSL error dialog
3181 showSSLCertificateOnError(
3182 mSSLCertificateOnErrorView,
3183 mSSLCertificateOnErrorHandler,
3184 mSSLCertificateOnErrorError);
3188 .setOnCancelListener(
3189 new DialogInterface.OnCancelListener() {
3190 public void onCancel(DialogInterface dialog) {
3191 mPageInfoDialog = null;
3192 mPageInfoView = null;
3194 // if we came here from the SSL error dialog
3195 if (fromShowSSLCertificateOnError) {
3196 // go back to the SSL error dialog
3197 showSSLCertificateOnError(
3198 mSSLCertificateOnErrorView,
3199 mSSLCertificateOnErrorHandler,
3200 mSSLCertificateOnErrorError);
3205 // if we have a main top-level page SSL certificate set or a certificate
3207 if (fromShowSSLCertificateOnError ||
3208 (view != null && view.getCertificate() != null)) {
3209 // add a 'View Certificate' button
3210 alertDialogBuilder.setNeutralButton(
3211 R.string.view_certificate,
3212 new DialogInterface.OnClickListener() {
3213 public void onClick(DialogInterface dialog,
3215 mPageInfoDialog = null;
3216 mPageInfoView = null;
3218 // if we came here from the SSL error dialog
3219 if (fromShowSSLCertificateOnError) {
3220 // go back to the SSL error dialog
3221 showSSLCertificateOnError(
3222 mSSLCertificateOnErrorView,
3223 mSSLCertificateOnErrorHandler,
3224 mSSLCertificateOnErrorError);
3226 // otherwise, display the top-most certificate from
3228 if (view.getCertificate() != null) {
3229 showSSLCertificate(tab);
3236 mPageInfoDialog = alertDialogBuilder.show();
3240 * Displays the main top-level page SSL certificate dialog
3241 * (accessible from the Page-Info dialog).
3242 * @param tab The tab to show certificate for.
3244 private void showSSLCertificate(final Tab tab) {
3245 final View certificateView =
3246 inflateCertificateView(tab.getWebView().getCertificate());
3247 if (certificateView == null) {
3251 LayoutInflater factory = LayoutInflater.from(this);
3253 final LinearLayout placeholder =
3254 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3256 LinearLayout ll = (LinearLayout) factory.inflate(
3257 R.layout.ssl_success, placeholder);
3258 ((TextView)ll.findViewById(R.id.success))
3259 .setText(R.string.ssl_certificate_is_valid);
3261 mSSLCertificateView = tab;
3262 mSSLCertificateDialog =
3263 new AlertDialog.Builder(this)
3264 .setTitle(R.string.ssl_certificate).setIcon(
3265 R.drawable.ic_dialog_browser_certificate_secure)
3266 .setView(certificateView)
3267 .setPositiveButton(R.string.ok,
3268 new DialogInterface.OnClickListener() {
3269 public void onClick(DialogInterface dialog,
3271 mSSLCertificateDialog = null;
3272 mSSLCertificateView = null;
3274 showPageInfo(tab, false);
3277 .setOnCancelListener(
3278 new DialogInterface.OnCancelListener() {
3279 public void onCancel(DialogInterface dialog) {
3280 mSSLCertificateDialog = null;
3281 mSSLCertificateView = null;
3283 showPageInfo(tab, false);
3290 * Displays the SSL error certificate dialog.
3291 * @param view The target web-view.
3292 * @param handler The SSL error handler responsible for cancelling the
3293 * connection that resulted in an SSL error or proceeding per user request.
3294 * @param error The SSL error object.
3296 void showSSLCertificateOnError(
3297 final WebView view, final SslErrorHandler handler, final SslError error) {
3299 final View certificateView =
3300 inflateCertificateView(error.getCertificate());
3301 if (certificateView == null) {
3305 LayoutInflater factory = LayoutInflater.from(this);
3307 final LinearLayout placeholder =
3308 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3310 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3311 LinearLayout ll = (LinearLayout)factory
3312 .inflate(R.layout.ssl_warning, placeholder);
3313 ((TextView)ll.findViewById(R.id.warning))
3314 .setText(R.string.ssl_untrusted);
3317 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3318 LinearLayout ll = (LinearLayout)factory
3319 .inflate(R.layout.ssl_warning, placeholder);
3320 ((TextView)ll.findViewById(R.id.warning))
3321 .setText(R.string.ssl_mismatch);
3324 if (error.hasError(SslError.SSL_EXPIRED)) {
3325 LinearLayout ll = (LinearLayout)factory
3326 .inflate(R.layout.ssl_warning, placeholder);
3327 ((TextView)ll.findViewById(R.id.warning))
3328 .setText(R.string.ssl_expired);
3331 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3332 LinearLayout ll = (LinearLayout)factory
3333 .inflate(R.layout.ssl_warning, placeholder);
3334 ((TextView)ll.findViewById(R.id.warning))
3335 .setText(R.string.ssl_not_yet_valid);
3338 mSSLCertificateOnErrorHandler = handler;
3339 mSSLCertificateOnErrorView = view;
3340 mSSLCertificateOnErrorError = error;
3341 mSSLCertificateOnErrorDialog =
3342 new AlertDialog.Builder(this)
3343 .setTitle(R.string.ssl_certificate).setIcon(
3344 R.drawable.ic_dialog_browser_certificate_partially_secure)
3345 .setView(certificateView)
3346 .setPositiveButton(R.string.ok,
3347 new DialogInterface.OnClickListener() {
3348 public void onClick(DialogInterface dialog,
3350 mSSLCertificateOnErrorDialog = null;
3351 mSSLCertificateOnErrorView = null;
3352 mSSLCertificateOnErrorHandler = null;
3353 mSSLCertificateOnErrorError = null;
3355 view.getWebViewClient().onReceivedSslError(
3356 view, handler, error);
3359 .setNeutralButton(R.string.page_info_view,
3360 new DialogInterface.OnClickListener() {
3361 public void onClick(DialogInterface dialog,
3363 mSSLCertificateOnErrorDialog = null;
3365 // do not clear the dialog state: we will
3366 // need to show the dialog again once the
3367 // user is done exploring the page-info details
3369 showPageInfo(mTabControl.getTabFromView(view),
3373 .setOnCancelListener(
3374 new DialogInterface.OnCancelListener() {
3375 public void onCancel(DialogInterface dialog) {
3376 mSSLCertificateOnErrorDialog = null;
3377 mSSLCertificateOnErrorView = null;
3378 mSSLCertificateOnErrorHandler = null;
3379 mSSLCertificateOnErrorError = null;
3381 view.getWebViewClient().onReceivedSslError(
3382 view, handler, error);
3389 * Inflates the SSL certificate view (helper method).
3390 * @param certificate The SSL certificate.
3391 * @return The resultant certificate view with issued-to, issued-by,
3392 * issued-on, expires-on, and possibly other fields set.
3393 * If the input certificate is null, returns null.
3395 private View inflateCertificateView(SslCertificate certificate) {
3396 if (certificate == null) {
3400 LayoutInflater factory = LayoutInflater.from(this);
3402 View certificateView = factory.inflate(
3403 R.layout.ssl_certificate, null);
3406 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3407 if (issuedTo != null) {
3408 ((TextView) certificateView.findViewById(R.id.to_common))
3409 .setText(issuedTo.getCName());
3410 ((TextView) certificateView.findViewById(R.id.to_org))
3411 .setText(issuedTo.getOName());
3412 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3413 .setText(issuedTo.getUName());
3417 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3418 if (issuedBy != null) {
3419 ((TextView) certificateView.findViewById(R.id.by_common))
3420 .setText(issuedBy.getCName());
3421 ((TextView) certificateView.findViewById(R.id.by_org))
3422 .setText(issuedBy.getOName());
3423 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3424 .setText(issuedBy.getUName());
3428 String issuedOn = formatCertificateDate(
3429 certificate.getValidNotBeforeDate());
3430 ((TextView) certificateView.findViewById(R.id.issued_on))
3434 String expiresOn = formatCertificateDate(
3435 certificate.getValidNotAfterDate());
3436 ((TextView) certificateView.findViewById(R.id.expires_on))
3437 .setText(expiresOn);
3439 return certificateView;
3443 * Formats the certificate date to a properly localized date string.
3444 * @return Properly localized version of the certificate date string and
3445 * the "" if it fails to localize.
3447 private String formatCertificateDate(Date certificateDate) {
3448 if (certificateDate == null) {
3451 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3452 if (formattedDate == null) {
3455 return formattedDate;
3459 * Displays an http-authentication dialog.
3461 void showHttpAuthentication(final HttpAuthHandler handler,
3462 final String host, final String realm, final String title,
3463 final String name, final String password, int focusId) {
3464 LayoutInflater factory = LayoutInflater.from(this);
3465 final View v = factory
3466 .inflate(R.layout.http_authentication, null);
3468 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3470 if (password != null) {
3471 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3474 String titleText = title;
3475 if (titleText == null) {
3476 titleText = getText(R.string.sign_in_to).toString().replace(
3477 "%s1", host).replace("%s2", realm);
3480 mHttpAuthHandler = handler;
3481 AlertDialog dialog = new AlertDialog.Builder(this)
3482 .setTitle(titleText)
3483 .setIcon(android.R.drawable.ic_dialog_alert)
3485 .setPositiveButton(R.string.action,
3486 new DialogInterface.OnClickListener() {
3487 public void onClick(DialogInterface dialog,
3489 String nm = ((EditText) v
3490 .findViewById(R.id.username_edit))
3491 .getText().toString();
3492 String pw = ((EditText) v
3493 .findViewById(R.id.password_edit))
3494 .getText().toString();
3495 BrowserActivity.this.setHttpAuthUsernamePassword
3496 (host, realm, nm, pw);
3497 handler.proceed(nm, pw);
3498 mHttpAuthenticationDialog = null;
3499 mHttpAuthHandler = null;
3501 .setNegativeButton(R.string.cancel,
3502 new DialogInterface.OnClickListener() {
3503 public void onClick(DialogInterface dialog,
3506 BrowserActivity.this.resetTitleAndRevertLockIcon();
3507 mHttpAuthenticationDialog = null;
3508 mHttpAuthHandler = null;
3510 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3511 public void onCancel(DialogInterface dialog) {
3513 BrowserActivity.this.resetTitleAndRevertLockIcon();
3514 mHttpAuthenticationDialog = null;
3515 mHttpAuthHandler = null;
3518 // Make the IME appear when the dialog is displayed if applicable.
3519 dialog.getWindow().setSoftInputMode(
3520 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3523 dialog.findViewById(focusId).requestFocus();
3525 v.findViewById(R.id.username_edit).requestFocus();
3527 mHttpAuthenticationDialog = dialog;
3530 public int getProgress() {
3531 WebView w = mTabControl.getCurrentWebView();
3533 return w.getProgress();
3540 * Set HTTP authentication password.
3542 * @param host The host for the password
3543 * @param realm The realm for the password
3544 * @param username The username for the password. If it is null, it means
3545 * password can't be saved.
3546 * @param password The password
3548 public void setHttpAuthUsernamePassword(String host, String realm,
3551 WebView w = mTabControl.getCurrentWebView();
3553 w.setHttpAuthUsernamePassword(host, realm, username, password);
3558 * connectivity manager says net has come or gone... inform the user
3559 * @param up true if net has come up, false if net has gone down
3561 public void onNetworkToggle(boolean up) {
3562 if (up == mIsNetworkUp) {
3565 mIsNetworkUp = true;
3566 if (mAlertDialog != null) {
3567 mAlertDialog.cancel();
3568 mAlertDialog = null;
3571 mIsNetworkUp = false;
3573 createAndShowNetworkDialog();
3576 WebView w = mTabControl.getCurrentWebView();
3578 w.setNetworkAvailable(up);
3582 boolean isNetworkUp() {
3583 return mIsNetworkUp;
3586 // This method shows the network dialog alerting the user that the net is
3587 // down. It will only show the dialog if mAlertDialog is null.
3588 private void createAndShowNetworkDialog() {
3589 if (mAlertDialog == null) {
3590 mAlertDialog = new AlertDialog.Builder(this)
3591 .setTitle(R.string.loadSuspendedTitle)
3592 .setMessage(R.string.loadSuspended)
3593 .setPositiveButton(R.string.ok, null)
3599 protected void onActivityResult(int requestCode, int resultCode,
3601 if (getTopWindow() == null) return;
3603 switch (requestCode) {
3605 if (resultCode == RESULT_OK && intent != null) {
3606 String data = intent.getAction();
3607 Bundle extras = intent.getExtras();
3608 if (extras != null && extras.getBoolean("new_window", false)) {
3611 final Tab currentTab =
3612 mTabControl.getCurrentTab();
3613 dismissSubWindow(currentTab);
3614 if (data != null && data.length() != 0) {
3615 loadUrl(getTopWindow(), data);
3619 // Deliberately fall through to PREFERENCES_PAGE, since the
3620 // same extra may be attached to the COMBO_PAGE
3621 case PREFERENCES_PAGE:
3622 if (resultCode == RESULT_OK && intent != null) {
3623 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3624 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3625 mTabControl.removeParentChildRelationShips();
3629 // Choose a file from the file picker.
3631 if (null == mUploadMessage) break;
3632 Uri result = intent == null || resultCode != RESULT_OK ? null
3634 mUploadMessage.onReceiveValue(result);
3635 mUploadMessage = null;
3640 getTopWindow().requestFocus();
3644 * This method is called as a result of the user selecting the options
3645 * menu to see the download window. It shows the download window on top of
3646 * the current window.
3648 private void viewDownloads(Uri downloadRecord) {
3649 Intent intent = new Intent(this,
3650 BrowserDownloadPage.class);
3651 intent.setData(downloadRecord);
3652 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3658 * @param startWithHistory If true, open starting on the history tab.
3659 * Otherwise, start with the bookmarks tab.
3661 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3662 WebView current = mTabControl.getCurrentWebView();
3663 if (current == null) {
3666 Intent intent = new Intent(this,
3667 CombinedBookmarkHistoryActivity.class);
3668 String title = current.getTitle();
3669 String url = current.getUrl();
3670 Bitmap thumbnail = createScreenshot(current);
3672 // Just in case the user opens bookmarks before a page finishes loading
3673 // so the current history item, and therefore the page, is null.
3675 url = mLastEnteredUrl;
3678 url = mSettings.getHomePage();
3681 // In case the web page has not yet received its associated title.
3682 if (title == null) {
3685 intent.putExtra("title", title);
3686 intent.putExtra("url", url);
3687 intent.putExtra("thumbnail", thumbnail);
3688 // Disable opening in a new window if we have maxed out the windows
3689 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3690 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3691 if (startWithHistory) {
3692 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3693 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3695 startActivityForResult(intent, COMBO_PAGE);
3698 // Called when loading from context menu or LOAD_URL message
3699 private void loadUrlFromContext(WebView view, String url) {
3700 // In case the user enters nothing.
3701 if (url != null && url.length() != 0 && view != null) {
3702 url = smartUrlFilter(url);
3703 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3710 * Load the URL into the given WebView and update the title bar
3711 * to reflect the new load. Call this instead of WebView.loadUrl
3713 * @param view The WebView used to load url.
3714 * @param url The URL to load.
3716 private void loadUrl(WebView view, String url) {
3717 updateTitleBarForNewLoad(view, url);
3722 * Load UrlData into a Tab and update the title bar to reflect the new
3723 * load. Call this instead of UrlData.loadIn directly.
3724 * @param t The Tab used to load.
3725 * @param data The UrlData being loaded.
3727 private void loadUrlDataIn(Tab t, UrlData data) {
3728 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3733 * If the WebView is the top window, update the title bar to reflect
3734 * loading the new URL. i.e. set its text, clear the favicon (which
3735 * will be set once the page begins loading), and set the progress to
3736 * INITIAL_PROGRESS to show that the page has begun to load. Called
3737 * by loadUrl and loadUrlDataIn.
3738 * @param view The WebView that is starting a load.
3739 * @param url The URL that is being loaded.
3741 private void updateTitleBarForNewLoad(WebView view, String url) {
3742 if (view == getTopWindow()) {
3743 setUrlTitle(url, null);
3745 onProgressChanged(view, INITIAL_PROGRESS);
3749 private String smartUrlFilter(Uri inUri) {
3750 if (inUri != null) {
3751 return smartUrlFilter(inUri.toString());
3756 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3757 "(?i)" + // switch on case insensitive matching
3758 "(" + // begin group for schema
3759 "(?:http|https|file):\\/\\/" +
3760 "|(?:inline|data|about|content|javascript):" +
3765 * Attempts to determine whether user input is a URL or search
3766 * terms. Anything with a space is passed to search.
3768 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3769 * "Http://" converts to "http://"
3771 * @return Original or modified URL
3774 String smartUrlFilter(String url) {
3776 String inUrl = url.trim();
3777 boolean hasSpace = inUrl.indexOf(' ') != -1;
3779 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3780 if (matcher.matches()) {
3781 // force scheme to lowercase
3782 String scheme = matcher.group(1);
3783 String lcScheme = scheme.toLowerCase();
3784 if (!lcScheme.equals(scheme)) {
3785 inUrl = lcScheme + matcher.group(2);
3788 inUrl = inUrl.replace(" ", "%20");
3793 // FIXME: Is this the correct place to add to searches?
3794 // what if someone else calls this function?
3795 int shortcut = parseUrlShortcut(inUrl);
3796 if (shortcut != SHORTCUT_INVALID) {
3797 Browser.addSearchUrl(mResolver, inUrl);
3798 String query = inUrl.substring(2);
3800 case SHORTCUT_GOOGLE_SEARCH:
3801 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3802 case SHORTCUT_WIKIPEDIA_SEARCH:
3803 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3804 case SHORTCUT_DICTIONARY_SEARCH:
3805 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3806 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3807 // FIXME: we need location in this case
3808 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3812 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3813 return URLUtil.guessUrl(inUrl);
3817 Browser.addSearchUrl(mResolver, inUrl);
3818 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3821 /* package */ void setShouldShowErrorConsole(boolean flag) {
3822 if (flag == mShouldShowErrorConsole) {
3827 mShouldShowErrorConsole = flag;
3829 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3830 .getErrorConsole(true);
3833 // Setting the show state of the console will cause it's the layout to be inflated.
3834 if (errorConsole.numberOfErrors() > 0) {
3835 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3837 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3840 // Now we can add it to the main view.
3841 mErrorConsoleContainer.addView(errorConsole,
3842 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3843 ViewGroup.LayoutParams.WRAP_CONTENT));
3845 mErrorConsoleContainer.removeView(errorConsole);
3850 boolean shouldShowErrorConsole() {
3851 return mShouldShowErrorConsole;
3854 private void setStatusBarVisibility(boolean visible) {
3855 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3856 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3860 private void sendNetworkType(String type, String subtype) {
3861 WebView w = mTabControl.getCurrentWebView();
3863 w.setNetworkType(type, subtype);
3867 private void packageChanged(String packageName, boolean wasAdded) {
3868 WebView w = mTabControl.getCurrentWebView();
3874 w.addPackageName(packageName);
3876 w.removePackageName(packageName);
3880 private void addPackageNames(Set<String> packageNames) {
3881 WebView w = mTabControl.getCurrentWebView();
3886 w.addPackageNames(packageNames);
3889 private void getInstalledPackages() {
3890 AsyncTask<Void, Void, Set<String> > task =
3891 new AsyncTask<Void, Void, Set<String> >() {
3892 protected Set<String> doInBackground(Void... unused) {
3893 Set<String> installedPackages = new HashSet<String>();
3894 PackageManager pm = BrowserActivity.this.getPackageManager();
3896 List<PackageInfo> packages = pm.getInstalledPackages(0);
3897 for (PackageInfo p : packages) {
3898 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3899 installedPackages.add(p.packageName);
3904 return installedPackages;
3907 // Executes on the UI thread
3908 protected void onPostExecute(Set<String> installedPackages) {
3909 addPackageNames(installedPackages);
3915 final static int LOCK_ICON_UNSECURE = 0;
3916 final static int LOCK_ICON_SECURE = 1;
3917 final static int LOCK_ICON_MIXED = 2;
3919 private BrowserSettings mSettings;
3920 private TabControl mTabControl;
3921 private ContentResolver mResolver;
3922 private FrameLayout mContentView;
3923 private View mCustomView;
3924 private FrameLayout mCustomViewContainer;
3925 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3927 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3928 // view, we should rewrite this.
3929 private int mCurrentMenuState = 0;
3930 private int mMenuState = R.id.MAIN_MENU;
3931 private int mOldMenuState = EMPTY_MENU;
3932 private static final int EMPTY_MENU = -1;
3935 private FindDialog mFindDialog;
3936 // Used to prevent chording to result in firing two shortcuts immediately
3937 // one after another. Fixes bug 1211714.
3940 private boolean mInLoad;
3941 private boolean mIsNetworkUp;
3942 private boolean mDidStopLoad;
3944 private boolean mActivityInPause = true;
3946 private boolean mMenuIsDown;
3948 private static boolean mInTrace;
3950 // Performance probe
3951 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3952 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3953 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3954 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3955 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3956 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3957 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3958 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3959 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3962 private long mStart;
3963 private long mProcessStart;
3964 private long mUserStart;
3965 private long mSystemStart;
3966 private long mIdleStart;
3967 private long mIrqStart;
3969 private long mUiStart;
3971 private Drawable mMixLockIcon;
3972 private Drawable mSecLockIcon;
3974 /* hold a ref so we can auto-cancel if necessary */
3975 private AlertDialog mAlertDialog;
3977 // Wait for credentials before loading google.com
3978 private ProgressDialog mCredsDlg;
3980 // The up-to-date URL and title (these can be different from those stored
3981 // in WebView, since it takes some time for the information in WebView to
3983 private String mUrl;
3984 private String mTitle;
3986 // As PageInfo has different style for landscape / portrait, we have
3987 // to re-open it when configuration changed
3988 private AlertDialog mPageInfoDialog;
3989 private Tab mPageInfoView;
3990 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3991 // dialog, we should not just dismiss it, but should get back to the
3992 // SSL-certificate-on-error dialog. This flag is used to store this state
3993 private boolean mPageInfoFromShowSSLCertificateOnError;
3995 // as SSLCertificateOnError has different style for landscape / portrait,
3996 // we have to re-open it when configuration changed
3997 private AlertDialog mSSLCertificateOnErrorDialog;
3998 private WebView mSSLCertificateOnErrorView;
3999 private SslErrorHandler mSSLCertificateOnErrorHandler;
4000 private SslError mSSLCertificateOnErrorError;
4002 // as SSLCertificate has different style for landscape / portrait, we
4003 // have to re-open it when configuration changed
4004 private AlertDialog mSSLCertificateDialog;
4005 private Tab mSSLCertificateView;
4007 // as HttpAuthentication has different style for landscape / portrait, we
4008 // have to re-open it when configuration changed
4009 private AlertDialog mHttpAuthenticationDialog;
4010 private HttpAuthHandler mHttpAuthHandler;
4012 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4013 new FrameLayout.LayoutParams(
4014 ViewGroup.LayoutParams.MATCH_PARENT,
4015 ViewGroup.LayoutParams.MATCH_PARENT);
4016 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
4017 new FrameLayout.LayoutParams(
4018 ViewGroup.LayoutParams.MATCH_PARENT,
4019 ViewGroup.LayoutParams.MATCH_PARENT,
4022 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
4024 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4025 // Dictionary search
4026 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4027 // Google Mobile Local search
4028 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4030 final static String QUERY_PLACE_HOLDER = "%s";
4032 // "source" parameter for Google search through search key
4033 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4034 // "source" parameter for Google search through goto menu
4035 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4036 // "source" parameter for Google search through simplily type
4037 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4038 // "source" parameter for Google search suggested by the browser
4039 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4040 // "source" parameter for Google search from unknown source
4041 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4043 private final static String LOGTAG = "browser";
4045 private String mLastEnteredUrl;
4047 private PowerManager.WakeLock mWakeLock;
4048 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4050 private Toast mStopToast;
4052 private TitleBar mTitleBar;
4054 private LinearLayout mErrorConsoleContainer = null;
4055 private boolean mShouldShowErrorConsole = false;
4057 // As the ids are dynamically created, we can't guarantee that they will
4058 // be in sequence, so this static array maps ids to a window number.
4059 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4060 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4061 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4062 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4064 // monitor platform changes
4065 private IntentFilter mNetworkStateChangedFilter;
4066 private BroadcastReceiver mNetworkStateIntentReceiver;
4068 private BroadcastReceiver mPackageInstallationReceiver;
4070 // activity requestCode
4071 final static int COMBO_PAGE = 1;
4072 final static int DOWNLOAD_PAGE = 2;
4073 final static int PREFERENCES_PAGE = 3;
4074 final static int FILE_SELECTED = 4;
4076 // the default <video> poster
4077 private Bitmap mDefaultVideoPoster;
4078 // the video progress view
4079 private View mVideoProgressView;
4081 // The Google packages we monitor for the navigator.isApplicationInstalled()
4082 // API. Add as needed.
4083 private static Set<String> sGoogleApps;
4085 sGoogleApps = new HashSet<String>();
4086 sGoogleApps.add("com.google.android.youtube");
4090 * A UrlData class to abstract how the content will be set to WebView.
4091 * This base class uses loadUrl to show the content.
4093 private static class UrlData {
4095 final Map<String, String> mHeaders;
4096 final Intent mVoiceIntent;
4098 UrlData(String url) {
4100 this.mHeaders = null;
4101 this.mVoiceIntent = null;
4104 UrlData(String url, Map<String, String> headers, Intent intent) {
4106 this.mHeaders = headers;
4107 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
4108 .equals(intent.getAction())) {
4109 this.mVoiceIntent = intent;
4111 this.mVoiceIntent = null;
4116 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
4120 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
4121 * the title bar as well.
4123 public void loadIn(Tab t) {
4124 if (mVoiceIntent != null) {
4125 t.activateVoiceSearchMode(mVoiceIntent);
4127 t.getWebView().loadUrl(mUrl, mHeaders);
4132 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);