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 {
140 /* Define some aliases to make these debugging flags easier to refer to.
141 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
143 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
144 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
145 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
147 // These are single-character shortcuts for searching popular sources.
148 private static final int SHORTCUT_INVALID = 0;
149 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
150 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
151 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
152 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
154 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
156 public Void doInBackground(File... files) {
158 for (File f : files) {
160 Log.e(LOGTAG, f.getPath() + " was not deleted");
169 * This layout holds everything you see below the status bar, including the
170 * error console, the custom view container, and the webviews.
172 private FrameLayout mBrowserFrameLayout;
175 public void onCreate(Bundle icicle) {
177 Log.v(LOGTAG, this + " onStart");
179 super.onCreate(icicle);
180 // test the browser in OpenGL
181 // requestWindowFeature(Window.FEATURE_OPENGL);
183 // enable this to test the browser in 32bit
185 getWindow().setFormat(PixelFormat.RGBX_8888);
186 BitmapFactory.setDefaultConfig(Bitmap.Config.ARGB_8888);
189 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
191 mResolver = getContentResolver();
193 // If this was a web search request, pass it on to the default web
194 // search provider and finish this activity.
195 if (handleWebSearchIntent(getIntent())) {
200 mSecLockIcon = Resources.getSystem().getDrawable(
201 android.R.drawable.ic_secure);
202 mMixLockIcon = Resources.getSystem().getDrawable(
203 android.R.drawable.ic_partial_secure);
205 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
206 .findViewById(com.android.internal.R.id.content);
207 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
208 .inflate(R.layout.custom_screen, null);
209 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
211 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
212 .findViewById(R.id.error_console);
213 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
214 .findViewById(R.id.fullscreen_custom_content);
215 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
216 mTitleBar = new TitleBar(this);
217 // mTitleBar will be always shown in the fully loaded mode
218 mTitleBar.setProgress(100);
219 mFakeTitleBar = new TitleBar(this);
221 // Create the tab control and our initial tab
222 mTabControl = new TabControl(this);
224 // Open the icon database and retain all the bookmark urls for favicons
225 retainIconsOnStartup();
227 // Keep a settings instance handy.
228 mSettings = BrowserSettings.getInstance();
229 mSettings.setTabControl(mTabControl);
231 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
232 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
234 // Find out if the network is currently up.
235 ConnectivityManager cm = (ConnectivityManager) getSystemService(
236 Context.CONNECTIVITY_SERVICE);
237 NetworkInfo info = cm.getActiveNetworkInfo();
239 mIsNetworkUp = info.isAvailable();
242 /* enables registration for changes in network status from
244 mNetworkStateChangedFilter = new IntentFilter();
245 mNetworkStateChangedFilter.addAction(
246 ConnectivityManager.CONNECTIVITY_ACTION);
247 mNetworkStateIntentReceiver = new BroadcastReceiver() {
249 public void onReceive(Context context, Intent intent) {
250 if (intent.getAction().equals(
251 ConnectivityManager.CONNECTIVITY_ACTION)) {
253 NetworkInfo info = intent.getParcelableExtra(
254 ConnectivityManager.EXTRA_NETWORK_INFO);
255 String typeName = info.getTypeName();
256 String subtypeName = info.getSubtypeName();
257 sendNetworkType(typeName.toLowerCase(),
258 (subtypeName != null ? subtypeName.toLowerCase() : ""));
260 onNetworkToggle(info.isAvailable());
265 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
266 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
267 filter.addDataScheme("package");
268 mPackageInstallationReceiver = new BroadcastReceiver() {
270 public void onReceive(Context context, Intent intent) {
271 final String action = intent.getAction();
272 final String packageName = intent.getData()
273 .getSchemeSpecificPart();
274 final boolean replacing = intent.getBooleanExtra(
275 Intent.EXTRA_REPLACING, false);
276 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
277 // if it is replacing, refreshPlugins() when adding
281 if (sGoogleApps.contains(packageName)) {
282 BrowserActivity.this.packageChanged(packageName,
283 Intent.ACTION_PACKAGE_ADDED.equals(action));
286 PackageManager pm = BrowserActivity.this.getPackageManager();
287 PackageInfo pkgInfo = null;
289 pkgInfo = pm.getPackageInfo(packageName,
290 PackageManager.GET_PERMISSIONS);
291 } catch (PackageManager.NameNotFoundException e) {
294 if (pkgInfo != null) {
295 String permissions[] = pkgInfo.requestedPermissions;
296 if (permissions == null) {
299 boolean permissionOk = false;
300 for (String permit : permissions) {
301 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
307 PluginManager.getInstance(BrowserActivity.this)
309 Intent.ACTION_PACKAGE_ADDED
315 registerReceiver(mPackageInstallationReceiver, filter);
317 if (!mTabControl.restoreState(icicle)) {
318 // clear up the thumbnail directory if we can't restore the state as
319 // none of the files in the directory are referenced any more.
320 new ClearThumbnails().execute(
321 mTabControl.getThumbnailDir().listFiles());
322 // there is no quit on Android. But if we can't restore the state,
323 // we can treat it as a new Browser, remove the old session cookies.
324 CookieManager.getInstance().removeSessionCookie();
325 final Intent intent = getIntent();
326 final Bundle extra = intent.getExtras();
327 // Create an initial tab.
328 // If the intent is ACTION_VIEW and data is not null, the Browser is
329 // invoked to view the content by another application. In this case,
330 // the tab will be close when exit.
331 UrlData urlData = getUrlDataFromIntent(intent);
333 String action = intent.getAction();
334 final Tab t = mTabControl.createNewTab(
335 (Intent.ACTION_VIEW.equals(action) &&
336 intent.getData() != null)
337 || RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
339 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
340 mTabControl.setCurrentTab(t);
341 attachTabToContentView(t);
342 WebView webView = t.getWebView();
344 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
345 if (scale > 0 && scale <= 1000) {
346 webView.setInitialScale(scale);
350 if (urlData.isEmpty()) {
351 loadUrl(webView, mSettings.getHomePage());
353 loadUrlDataIn(t, urlData);
356 // TabControl.restoreState() will create a new tab even if
357 // restoring the state fails.
358 attachTabToContentView(mTabControl.getCurrentTab());
361 // Read JavaScript flags if it exists.
362 String jsFlags = mSettings.getJsFlags();
363 if (jsFlags.trim().length() != 0) {
364 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
366 // Work out which packages are installed on the system.
367 getInstalledPackages();
369 // Start watching the default geolocation permissions
370 mSystemAllowGeolocationOrigins
371 = new SystemAllowGeolocationOrigins(getApplicationContext());
372 mSystemAllowGeolocationOrigins.start();
376 * Feed the previously stored results strings to the BrowserProvider so that
377 * the SearchDialog will show them instead of the standard searches.
378 * @param result String to show on the editable line of the SearchDialog.
380 /* package */ void showVoiceSearchResults(String result) {
381 ContentProviderClient client = mResolver.acquireContentProviderClient(
382 Browser.BOOKMARKS_URI);
383 ContentProvider prov = client.getLocalContentProvider();
384 BrowserProvider bp = (BrowserProvider) prov;
385 bp.setQueryResults(mTabControl.getCurrentTab().getVoiceSearchResults());
388 Bundle bundle = createGoogleSearchSourceBundle(
389 GOOGLE_SEARCH_SOURCE_SEARCHKEY);
390 bundle.putBoolean(SearchManager.CONTEXT_IS_VOICE, true);
391 startSearch(result, false, bundle, false);
395 protected void onNewIntent(Intent intent) {
396 Tab current = mTabControl.getCurrentTab();
397 // When a tab is closed on exit, the current tab index is set to -1.
398 // Reset before proceed as Browser requires the current tab to be set.
399 if (current == null) {
400 // Try to reset the tab in case the index was incorrect.
401 current = mTabControl.getTab(0);
402 if (current == null) {
403 // No tabs at all so just ignore this intent.
406 mTabControl.setCurrentTab(current);
407 attachTabToContentView(current);
408 resetTitleAndIcon(current.getWebView());
410 final String action = intent.getAction();
411 final int flags = intent.getFlags();
412 if (Intent.ACTION_MAIN.equals(action) ||
413 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
414 // just resume the browser
417 // In case the SearchDialog is open.
418 ((SearchManager) getSystemService(Context.SEARCH_SERVICE))
420 boolean activateVoiceSearch = RecognizerResultsIntent
421 .ACTION_VOICE_SEARCH_RESULTS.equals(action);
422 if (Intent.ACTION_VIEW.equals(action)
423 || Intent.ACTION_SEARCH.equals(action)
424 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
425 || Intent.ACTION_WEB_SEARCH.equals(action)
426 || activateVoiceSearch) {
427 if (current.isInVoiceSearchMode()) {
428 String title = current.getVoiceDisplayTitle();
429 if (title != null && title.equals(intent.getStringExtra(
430 SearchManager.QUERY))) {
431 // The user submitted the same search as the last voice
432 // search, so do nothing.
435 if (Intent.ACTION_SEARCH.equals(action)
436 && current.voiceSearchSourceIsGoogle()) {
437 Intent logIntent = new Intent(
438 LoggingEvents.ACTION_LOG_EVENT);
439 logIntent.putExtra(LoggingEvents.EXTRA_EVENT,
440 LoggingEvents.VoiceSearch.QUERY_UPDATED);
442 LoggingEvents.VoiceSearch.EXTRA_QUERY_UPDATED_VALUE,
443 intent.getDataString());
444 sendBroadcast(logIntent);
445 // Note, onPageStarted will revert the voice title bar
446 // When http://b/issue?id=2379215 is fixed, we should update
447 // the title bar here.
450 // If this was a search request (e.g. search query directly typed into the address bar),
451 // pass it on to the default web search provider.
452 if (handleWebSearchIntent(intent)) {
456 UrlData urlData = getUrlDataFromIntent(intent);
457 if (urlData.isEmpty()) {
458 urlData = new UrlData(mSettings.getHomePage());
461 final String appId = intent
462 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
463 if ((Intent.ACTION_VIEW.equals(action)
464 // If a voice search has no appId, it means that it came
465 // from the browser. In that case, reuse the current tab.
466 || (activateVoiceSearch && appId != null))
467 && !getPackageName().equals(appId)
468 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
469 Tab appTab = mTabControl.getTabFromId(appId);
470 if (appTab != null) {
471 Log.i(LOGTAG, "Reusing tab for " + appId);
472 // Dismiss the subwindow if applicable.
473 dismissSubWindow(appTab);
474 // Since we might kill the WebView, remove it from the
475 // content view first.
476 removeTabFromContentView(appTab);
477 // Recreate the main WebView after destroying the old one.
478 // If the WebView has the same original url and is on that
479 // page, it can be reused.
481 mTabControl.recreateWebView(appTab, urlData);
483 if (current != appTab) {
484 switchToTab(mTabControl.getTabIndex(appTab));
486 loadUrlDataIn(appTab, urlData);
489 // If the tab was the current tab, we have to attach
490 // it to the view system again.
491 attachTabToContentView(appTab);
493 loadUrlDataIn(appTab, urlData);
498 // No matching application tab, try to find a regular tab
499 // with a matching url.
500 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
501 if (appTab != null) {
502 if (current != appTab) {
503 switchToTab(mTabControl.getTabIndex(appTab));
505 // Otherwise, we are already viewing the correct tab.
507 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
508 // will be opened in a new tab unless we have reached
509 // MAX_TABS. Then the url will be opened in the current
510 // tab. If a new tab is created, it will have "true" for
512 openTabAndShow(urlData, true, appId);
516 if (!urlData.isEmpty()
517 && urlData.mUrl.startsWith("about:debug")) {
518 if ("about:debug.dom".equals(urlData.mUrl)) {
519 current.getWebView().dumpDomTree(false);
520 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
521 current.getWebView().dumpDomTree(true);
522 } else if ("about:debug.render".equals(urlData.mUrl)) {
523 current.getWebView().dumpRenderTree(false);
524 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
525 current.getWebView().dumpRenderTree(true);
526 } else if ("about:debug.display".equals(urlData.mUrl)) {
527 current.getWebView().dumpDisplayTree();
528 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
529 int index = urlData.mUrl.codePointAt(16) - '0';
530 if (index <= 0 || index > 9) {
531 current.getWebView().setDragTracker(null);
533 current.getWebView().setDragTracker(new MeshTracker(index));
536 mSettings.toggleDebugSettings();
540 // Get rid of the subwindow if it exists
541 dismissSubWindow(current);
542 loadUrlDataIn(current, urlData);
547 private int parseUrlShortcut(String url) {
548 if (url == null) return SHORTCUT_INVALID;
550 // FIXME: quick search, need to be customized by setting
551 if (url.length() > 2 && url.charAt(1) == ' ') {
552 switch (url.charAt(0)) {
553 case 'g': return SHORTCUT_GOOGLE_SEARCH;
554 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
555 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
556 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
559 return SHORTCUT_INVALID;
563 * Launches the default web search activity with the query parameters if the given intent's data
564 * are identified as plain search terms and not URLs/shortcuts.
565 * @return true if the intent was handled and web search activity was launched, false if not.
567 private boolean handleWebSearchIntent(Intent intent) {
568 if (intent == null) return false;
571 final String action = intent.getAction();
572 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
576 if (Intent.ACTION_VIEW.equals(action)) {
577 Uri data = intent.getData();
578 if (data != null) url = data.toString();
579 } else if (Intent.ACTION_SEARCH.equals(action)
580 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
581 || Intent.ACTION_WEB_SEARCH.equals(action)) {
582 url = intent.getStringExtra(SearchManager.QUERY);
584 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
585 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
589 * Launches the default web search activity with the query parameters if the given url string
590 * was identified as plain search terms and not URL/shortcut.
591 * @return true if the request was handled and web search activity was launched, false if not.
593 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
594 if (inUrl == null) return false;
596 // In general, we shouldn't modify URL from Intent.
597 // But currently, we get the user-typed URL from search box as well.
598 String url = fixUrl(inUrl).trim();
600 // URLs and site specific search shortcuts are handled by the regular flow of control, so
602 if (Patterns.WEB_URL.matcher(url).matches()
603 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
604 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
608 final ContentResolver cr = mResolver;
609 final String newUrl = url;
610 new AsyncTask<Void, Void, Void>() {
611 protected Void doInBackground(Void... unused) {
612 Browser.updateVisitedHistory(cr, newUrl, false);
613 Browser.addSearchUrl(cr, newUrl);
618 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
619 intent.addCategory(Intent.CATEGORY_DEFAULT);
620 intent.putExtra(SearchManager.QUERY, url);
621 if (appData != null) {
622 intent.putExtra(SearchManager.APP_DATA, appData);
624 if (extraData != null) {
625 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
627 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
628 startActivity(intent);
633 private UrlData getUrlDataFromIntent(Intent intent) {
635 Map<String, String> headers = null;
636 if (intent != null) {
637 final String action = intent.getAction();
638 if (Intent.ACTION_VIEW.equals(action)) {
639 url = smartUrlFilter(intent.getData());
640 if (url != null && url.startsWith("content:")) {
641 /* Append mimetype so webview knows how to display */
642 String mimeType = intent.resolveType(getContentResolver());
643 if (mimeType != null) {
644 url += "?" + mimeType;
647 if (url != null && url.startsWith("http")) {
648 final Bundle pairs = intent
649 .getBundleExtra(Browser.EXTRA_HEADERS);
650 if (pairs != null && !pairs.isEmpty()) {
651 Iterator<String> iter = pairs.keySet().iterator();
652 headers = new HashMap<String, String>();
653 while (iter.hasNext()) {
654 String key = iter.next();
655 headers.put(key, pairs.getString(key));
659 } else if (Intent.ACTION_SEARCH.equals(action)
660 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
661 || Intent.ACTION_WEB_SEARCH.equals(action)) {
662 url = intent.getStringExtra(SearchManager.QUERY);
664 mLastEnteredUrl = url;
665 // In general, we shouldn't modify URL from Intent.
666 // But currently, we get the user-typed URL from search box as well.
668 url = smartUrlFilter(url);
669 final ContentResolver cr = mResolver;
670 final String newUrl = url;
671 new AsyncTask<Void, Void, Void>() {
672 protected Void doInBackground(Void... unused) {
673 Browser.updateVisitedHistory(cr, newUrl, false);
677 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
678 if (url.contains(searchSource)) {
679 String source = null;
680 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
681 if (appData != null) {
682 source = appData.getString(Search.SOURCE);
684 if (TextUtils.isEmpty(source)) {
685 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
687 url = url.replace(searchSource, "&source=android-"+source+"&");
692 return new UrlData(url, headers, intent);
694 /* package */ void showVoiceTitleBar(String title) {
695 mTitleBar.setInVoiceMode(true);
696 mFakeTitleBar.setInVoiceMode(true);
698 mTitleBar.setDisplayTitle(title);
699 mFakeTitleBar.setDisplayTitle(title);
701 /* package */ void revertVoiceTitleBar() {
702 mTitleBar.setInVoiceMode(false);
703 mFakeTitleBar.setInVoiceMode(false);
705 mTitleBar.setDisplayTitle(mUrl);
706 mFakeTitleBar.setDisplayTitle(mUrl);
708 /* package */ static String fixUrl(String inUrl) {
709 // FIXME: Converting the url to lower case
710 // duplicates functionality in smartUrlFilter().
711 // However, changing all current callers of fixUrl to
712 // call smartUrlFilter in addition may have unwanted
713 // consequences, and is deferred for now.
714 int colon = inUrl.indexOf(':');
715 boolean allLower = true;
716 for (int index = 0; index < colon; index++) {
717 char ch = inUrl.charAt(index);
718 if (!Character.isLetter(ch)) {
721 allLower &= Character.isLowerCase(ch);
722 if (index == colon - 1 && !allLower) {
723 inUrl = inUrl.substring(0, colon).toLowerCase()
724 + inUrl.substring(colon);
727 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
729 if (inUrl.startsWith("http:") ||
730 inUrl.startsWith("https:")) {
731 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
732 inUrl = inUrl.replaceFirst("/", "//");
733 } else inUrl = inUrl.replaceFirst(":", "://");
739 protected void onResume() {
742 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
745 if (!mActivityInPause) {
746 Log.e(LOGTAG, "BrowserActivity is already resumed.");
750 mTabControl.resumeCurrentTab();
751 mActivityInPause = false;
752 resumeWebViewTimers();
754 if (mWakeLock.isHeld()) {
755 mHandler.removeMessages(RELEASE_WAKELOCK);
759 registerReceiver(mNetworkStateIntentReceiver,
760 mNetworkStateChangedFilter);
761 WebView.enablePlatformNotifications();
765 * Since the actual title bar is embedded in the WebView, and removing it
766 * would change its appearance, use a different TitleBar to show overlayed
767 * at the top of the screen, when the menu is open or the page is loading.
769 private TitleBar mFakeTitleBar;
772 * Keeps track of whether the options menu is open. This is important in
773 * determining whether to show or hide the title bar overlay.
775 private boolean mOptionsMenuOpen;
778 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
779 * of whether the configuration has changed. The first onMenuOpened call
780 * after a configuration change is simply a reopening of the same menu
781 * (i.e. mIconView did not change).
783 private boolean mConfigChanged;
786 * Whether or not the options menu is in its smaller, icon menu form. When
787 * true, we want the title bar overlay to be up. When false, we do not.
788 * Only meaningful if mOptionsMenuOpen is true.
790 private boolean mIconView;
793 public boolean onMenuOpened(int featureId, Menu menu) {
794 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
795 if (mOptionsMenuOpen) {
796 if (mConfigChanged) {
797 // We do not need to make any changes to the state of the
798 // title bar, since the only thing that happened was a
799 // change in orientation
800 mConfigChanged = false;
803 // Switching the menu to expanded view, so hide the
808 // Switching the menu back to icon view, so show the
809 // title bar once again.
815 // The options menu is closed, so open it, and show the title
817 mOptionsMenuOpen = true;
818 mConfigChanged = false;
825 private void showFakeTitleBar() {
826 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
827 && !mActivityInPause) {
828 WebView mainView = mTabControl.getCurrentWebView();
829 // if there is no current WebView, don't show the faked title bar;
830 if (mainView == null) {
834 WindowManager manager
835 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
837 // Add the title bar to the window manager so it can receive touches
838 // while the menu is up
839 WindowManager.LayoutParams params
840 = new WindowManager.LayoutParams(
841 ViewGroup.LayoutParams.MATCH_PARENT,
842 ViewGroup.LayoutParams.WRAP_CONTENT,
843 WindowManager.LayoutParams.TYPE_APPLICATION,
844 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
845 PixelFormat.TRANSLUCENT);
846 params.gravity = Gravity.TOP;
847 boolean atTop = mainView.getScrollY() == 0;
848 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
849 manager.addView(mFakeTitleBar, params);
854 public void onOptionsMenuClosed(Menu menu) {
855 mOptionsMenuOpen = false;
858 } else if (!mIconView) {
859 // The page is currently loading, and we are in expanded mode, so
860 // we were not showing the menu. Show it once again. It will be
861 // removed when the page finishes.
866 private void hideFakeTitleBar() {
867 if (mFakeTitleBar.getParent() == null) return;
868 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
869 mFakeTitleBar.getLayoutParams();
870 WebView mainView = mTabControl.getCurrentWebView();
871 // Although we decided whether or not to animate based on the current
872 // scroll position, the scroll position may have changed since the
873 // fake title bar was displayed. Make sure it has the appropriate
874 // animation/lack thereof before removing.
875 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
876 ? 0 : R.style.TitleBar;
877 WindowManager manager
878 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
879 manager.updateViewLayout(mFakeTitleBar, params);
880 manager.removeView(mFakeTitleBar);
884 * Special method for the fake title bar to call when displaying its context
885 * menu, since it is in its own Window, and its parent does not show a
888 /* package */ void showTitleBarContextMenu() {
889 if (null == mTitleBar.getParent()) {
892 openContextMenu(mTitleBar);
896 public void onContextMenuClosed(Menu menu) {
897 super.onContextMenuClosed(menu);
904 * onSaveInstanceState(Bundle map)
905 * onSaveInstanceState is called right before onStop(). The map contains
909 protected void onSaveInstanceState(Bundle outState) {
911 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
913 // the default implementation requires each view to have an id. As the
914 // browser handles the state itself and it doesn't use id for the views,
915 // don't call the default implementation. Otherwise it will trigger the
916 // warning like this, "couldn't save which view has focus because the
917 // focused view XXX has no id".
920 mTabControl.saveState(outState);
924 protected void onPause() {
927 if (mActivityInPause) {
928 Log.e(LOGTAG, "BrowserActivity is already paused.");
932 mTabControl.pauseCurrentTab();
933 mActivityInPause = true;
934 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
936 mHandler.sendMessageDelayed(mHandler
937 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
940 // FIXME: This removes the active tabs page and resets the menu to
941 // MAIN_MENU. A better solution might be to do this work in onNewIntent
942 // but then we would need to save it in onSaveInstanceState and restore
943 // it in onCreate/onRestoreInstanceState
944 if (mActiveTabsPage != null) {
945 removeActiveTabPage(true);
950 // unregister network state listener
951 unregisterReceiver(mNetworkStateIntentReceiver);
952 WebView.disablePlatformNotifications();
956 protected void onDestroy() {
958 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
962 if (mUploadMessage != null) {
963 mUploadMessage.onReceiveValue(null);
964 mUploadMessage = null;
967 if (mTabControl == null) return;
969 // Remove the fake title bar if it is there
972 // Remove the current tab and sub window
973 Tab t = mTabControl.getCurrentTab();
976 removeTabFromContentView(t);
978 // Destroy all the tabs
979 mTabControl.destroy();
980 WebIconDatabase.getInstance().close();
982 unregisterReceiver(mPackageInstallationReceiver);
984 // Stop watching the default geolocation permissions
985 mSystemAllowGeolocationOrigins.stop();
986 mSystemAllowGeolocationOrigins = null;
990 public void onConfigurationChanged(Configuration newConfig) {
991 mConfigChanged = true;
992 super.onConfigurationChanged(newConfig);
994 if (mPageInfoDialog != null) {
995 mPageInfoDialog.dismiss();
998 mPageInfoFromShowSSLCertificateOnError);
1000 if (mSSLCertificateDialog != null) {
1001 mSSLCertificateDialog.dismiss();
1003 mSSLCertificateView);
1005 if (mSSLCertificateOnErrorDialog != null) {
1006 mSSLCertificateOnErrorDialog.dismiss();
1007 showSSLCertificateOnError(
1008 mSSLCertificateOnErrorView,
1009 mSSLCertificateOnErrorHandler,
1010 mSSLCertificateOnErrorError);
1012 if (mHttpAuthenticationDialog != null) {
1013 String title = ((TextView) mHttpAuthenticationDialog
1014 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1016 String name = ((TextView) mHttpAuthenticationDialog
1017 .findViewById(R.id.username_edit)).getText().toString();
1018 String password = ((TextView) mHttpAuthenticationDialog
1019 .findViewById(R.id.password_edit)).getText().toString();
1020 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1022 mHttpAuthenticationDialog.dismiss();
1023 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1024 name, password, focusId);
1029 public void onLowMemory() {
1030 super.onLowMemory();
1031 mTabControl.freeMemory();
1034 private void resumeWebViewTimers() {
1035 Tab tab = mTabControl.getCurrentTab();
1036 if (tab == null) return; // monkey can trigger this
1037 boolean inLoad = tab.inLoad();
1038 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1039 CookieSyncManager.getInstance().startSync();
1040 WebView w = tab.getWebView();
1047 private boolean pauseWebViewTimers() {
1048 Tab tab = mTabControl.getCurrentTab();
1049 boolean inLoad = tab.inLoad();
1050 if (mActivityInPause && !inLoad) {
1051 CookieSyncManager.getInstance().stopSync();
1052 WebView w = mTabControl.getCurrentWebView();
1062 // Open the icon database and retain all the icons for visited sites.
1063 private void retainIconsOnStartup() {
1064 final WebIconDatabase db = WebIconDatabase.getInstance();
1065 db.open(getDir("icons", 0).getPath());
1068 c = Browser.getAllBookmarks(mResolver);
1069 if (c.moveToFirst()) {
1070 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1072 String url = c.getString(urlIndex);
1073 db.retainIconForPageUrl(url);
1074 } while (c.moveToNext());
1076 } catch (IllegalStateException e) {
1077 Log.e(LOGTAG, "retainIconsOnStartup", e);
1079 if (c!= null) c.close();
1083 // Helper method for getting the top window.
1084 WebView getTopWindow() {
1085 return mTabControl.getCurrentTopWebView();
1088 TabControl getTabControl() {
1093 public boolean onCreateOptionsMenu(Menu menu) {
1094 super.onCreateOptionsMenu(menu);
1096 MenuInflater inflater = getMenuInflater();
1097 inflater.inflate(R.menu.browser, menu);
1099 updateInLoadMenuItems();
1104 * As the menu can be open when loading state changes
1105 * we must manually update the state of the stop/reload menu
1108 private void updateInLoadMenuItems() {
1109 if (mMenu == null) {
1112 MenuItem src = mInLoad ?
1113 mMenu.findItem(R.id.stop_menu_id):
1114 mMenu.findItem(R.id.reload_menu_id);
1115 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1116 dest.setIcon(src.getIcon());
1117 dest.setTitle(src.getTitle());
1121 public boolean onContextItemSelected(MenuItem item) {
1122 // chording is not an issue with context menus, but we use the same
1123 // options selector, so set mCanChord to true so we can access them.
1125 int id = item.getItemId();
1126 boolean result = true;
1128 // For the context menu from the title bar
1129 case R.id.title_bar_copy_page_url:
1130 Tab currentTab = mTabControl.getCurrentTab();
1131 if (null == currentTab) {
1135 WebView mainView = currentTab.getWebView();
1136 if (null == mainView) {
1140 copy(mainView.getUrl());
1142 // -- Browser context menu
1143 case R.id.open_context_menu_id:
1144 case R.id.open_newtab_context_menu_id:
1145 case R.id.bookmark_context_menu_id:
1146 case R.id.save_link_context_menu_id:
1147 case R.id.share_link_context_menu_id:
1148 case R.id.copy_link_context_menu_id:
1149 final WebView webView = getTopWindow();
1150 if (null == webView) {
1154 final HashMap hrefMap = new HashMap();
1155 hrefMap.put("webview", webView);
1156 final Message msg = mHandler.obtainMessage(
1157 FOCUS_NODE_HREF, id, 0, hrefMap);
1158 webView.requestFocusNodeHref(msg);
1162 // For other context menus
1163 result = onOptionsItemSelected(item);
1169 private Bundle createGoogleSearchSourceBundle(String source) {
1170 Bundle bundle = new Bundle();
1171 bundle.putString(Search.SOURCE, source);
1175 /* package */ void editUrl() {
1176 if (mOptionsMenuOpen) closeOptionsMenu();
1177 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1178 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1183 * Overriding this to insert a local information bundle
1186 public void startSearch(String initialQuery, boolean selectInitialQuery,
1187 Bundle appSearchData, boolean globalSearch) {
1188 if (appSearchData == null) {
1189 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1191 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1195 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1196 * results in changing tabs.
1197 * @param index Index of the tab to change to, as defined by
1198 * mTabControl.getTabIndex(Tab t).
1199 * @return boolean True if we successfully switched to a different tab. If
1200 * the indexth tab is null, or if that tab is the same as
1201 * the current one, return false.
1203 /* package */ boolean switchToTab(int index) {
1204 Tab tab = mTabControl.getTab(index);
1205 Tab currentTab = mTabControl.getCurrentTab();
1206 if (tab == null || tab == currentTab) {
1209 if (currentTab != null) {
1210 // currentTab may be null if it was just removed. In that case,
1211 // we do not need to remove it
1212 removeTabFromContentView(currentTab);
1214 mTabControl.setCurrentTab(tab);
1215 attachTabToContentView(tab);
1216 resetTitleIconAndProgress();
1217 updateLockIconToLatest();
1221 /* package */ Tab openTabToHomePage() {
1222 return openTabAndShow(mSettings.getHomePage(), false, null);
1225 /* package */ void closeCurrentWindow() {
1226 final Tab current = mTabControl.getCurrentTab();
1227 if (mTabControl.getTabCount() == 1) {
1228 // This is the last tab. Open a new one, with the home
1229 // page and close the current one.
1230 openTabToHomePage();
1234 final Tab parent = current.getParentTab();
1235 int indexToShow = -1;
1236 if (parent != null) {
1237 indexToShow = mTabControl.getTabIndex(parent);
1239 final int currentIndex = mTabControl.getCurrentIndex();
1240 // Try to move to the tab to the right
1241 indexToShow = currentIndex + 1;
1242 if (indexToShow > mTabControl.getTabCount() - 1) {
1243 // Try to move to the tab to the left
1244 indexToShow = currentIndex - 1;
1247 if (switchToTab(indexToShow)) {
1253 private ActiveTabsPage mActiveTabsPage;
1256 * Remove the active tabs page.
1257 * @param needToAttach If true, the active tabs page did not attach a tab
1258 * to the content view, so we need to do that here.
1260 /* package */ void removeActiveTabPage(boolean needToAttach) {
1261 mContentView.removeView(mActiveTabsPage);
1262 mActiveTabsPage = null;
1263 mMenuState = R.id.MAIN_MENU;
1265 attachTabToContentView(mTabControl.getCurrentTab());
1267 getTopWindow().requestFocus();
1271 public boolean onOptionsItemSelected(MenuItem item) {
1273 // The user has already fired a shortcut with this hold down of the
1277 if (null == getTopWindow()) {
1281 // The shortcut action consumes the MENU. Even if it is still down,
1282 // it won't trigger the next shortcut action. In the case of the
1283 // shortcut action triggering a new activity, like Bookmarks, we
1284 // won't get onKeyUp for MENU. So it is important to reset it here.
1285 mMenuIsDown = false;
1287 switch (item.getItemId()) {
1289 case R.id.new_tab_menu_id:
1290 openTabToHomePage();
1293 case R.id.goto_menu_id:
1297 case R.id.bookmarks_menu_id:
1298 bookmarksOrHistoryPicker(false);
1301 case R.id.active_tabs_menu_id:
1302 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1303 removeTabFromContentView(mTabControl.getCurrentTab());
1305 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1306 mActiveTabsPage.requestFocus();
1307 mMenuState = EMPTY_MENU;
1310 case R.id.add_bookmark_menu_id:
1311 Intent i = new Intent(BrowserActivity.this,
1312 AddBookmarkPage.class);
1313 WebView w = getTopWindow();
1314 i.putExtra("url", w.getUrl());
1315 i.putExtra("title", w.getTitle());
1316 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1317 i.putExtra("thumbnail", createScreenshot(w));
1321 case R.id.stop_reload_menu_id:
1325 getTopWindow().reload();
1329 case R.id.back_menu_id:
1330 getTopWindow().goBack();
1333 case R.id.forward_menu_id:
1334 getTopWindow().goForward();
1337 case R.id.close_menu_id:
1338 // Close the subwindow if it exists.
1339 if (mTabControl.getCurrentSubWindow() != null) {
1340 dismissSubWindow(mTabControl.getCurrentTab());
1343 closeCurrentWindow();
1346 case R.id.homepage_menu_id:
1347 Tab current = mTabControl.getCurrentTab();
1348 if (current != null) {
1349 dismissSubWindow(current);
1350 loadUrl(current.getWebView(), mSettings.getHomePage());
1354 case R.id.preferences_menu_id:
1355 Intent intent = new Intent(this,
1356 BrowserPreferencesPage.class);
1357 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1358 getTopWindow().getUrl());
1359 startActivityForResult(intent, PREFERENCES_PAGE);
1362 case R.id.find_menu_id:
1363 if (null == mFindDialog) {
1364 mFindDialog = new FindDialog(this);
1366 mFindDialog.setWebView(getTopWindow());
1368 getTopWindow().setFindIsUp(true);
1369 mMenuState = EMPTY_MENU;
1372 case R.id.select_text_id:
1373 getTopWindow().emulateShiftHeld();
1375 case R.id.page_info_menu_id:
1376 showPageInfo(mTabControl.getCurrentTab(), false);
1379 case R.id.classic_history_menu_id:
1380 bookmarksOrHistoryPicker(true);
1383 case R.id.title_bar_share_page_url:
1384 case R.id.share_page_menu_id:
1385 Tab currentTab = mTabControl.getCurrentTab();
1386 if (null == currentTab) {
1390 currentTab.populatePickerData();
1391 sharePage(this, currentTab.getTitle(),
1392 currentTab.getUrl(), currentTab.getFavicon(),
1393 createScreenshot(currentTab.getWebView()));
1396 case R.id.dump_nav_menu_id:
1397 getTopWindow().debugDump();
1400 case R.id.dump_counters_menu_id:
1401 getTopWindow().dumpV8Counters();
1404 case R.id.zoom_in_menu_id:
1405 getTopWindow().zoomIn();
1408 case R.id.zoom_out_menu_id:
1409 getTopWindow().zoomOut();
1412 case R.id.view_downloads_menu_id:
1413 viewDownloads(null);
1416 case R.id.window_one_menu_id:
1417 case R.id.window_two_menu_id:
1418 case R.id.window_three_menu_id:
1419 case R.id.window_four_menu_id:
1420 case R.id.window_five_menu_id:
1421 case R.id.window_six_menu_id:
1422 case R.id.window_seven_menu_id:
1423 case R.id.window_eight_menu_id:
1425 int menuid = item.getItemId();
1426 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1427 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1428 Tab desiredTab = mTabControl.getTab(id);
1429 if (desiredTab != null &&
1430 desiredTab != mTabControl.getCurrentTab()) {
1440 if (!super.onOptionsItemSelected(item)) {
1443 // Otherwise fall through.
1449 public void closeFind() {
1450 mMenuState = R.id.MAIN_MENU;
1454 public boolean onPrepareOptionsMenu(Menu menu) {
1455 // This happens when the user begins to hold down the menu key, so
1456 // allow them to chord to get a shortcut.
1458 // Note: setVisible will decide whether an item is visible; while
1459 // setEnabled() will decide whether an item is enabled, which also means
1460 // whether the matching shortcut key will function.
1461 super.onPrepareOptionsMenu(menu);
1462 switch (mMenuState) {
1464 if (mCurrentMenuState != mMenuState) {
1465 menu.setGroupVisible(R.id.MAIN_MENU, false);
1466 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1467 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1471 if (mCurrentMenuState != mMenuState) {
1472 menu.setGroupVisible(R.id.MAIN_MENU, true);
1473 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1474 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1476 final WebView w = getTopWindow();
1477 boolean canGoBack = false;
1478 boolean canGoForward = false;
1479 boolean isHome = false;
1481 canGoBack = w.canGoBack();
1482 canGoForward = w.canGoForward();
1483 isHome = mSettings.getHomePage().equals(w.getUrl());
1485 final MenuItem back = menu.findItem(R.id.back_menu_id);
1486 back.setEnabled(canGoBack);
1488 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1489 home.setEnabled(!isHome);
1491 menu.findItem(R.id.forward_menu_id)
1492 .setEnabled(canGoForward);
1494 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1495 mTabControl.canCreateNewTab());
1497 // decide whether to show the share link option
1498 PackageManager pm = getPackageManager();
1499 Intent send = new Intent(Intent.ACTION_SEND);
1500 send.setType("text/plain");
1501 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1502 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1504 boolean isNavDump = mSettings.isNavDump();
1505 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1506 nav.setVisible(isNavDump);
1507 nav.setEnabled(isNavDump);
1509 boolean showDebugSettings = mSettings.showDebugSettings();
1510 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1511 counter.setVisible(showDebugSettings);
1512 counter.setEnabled(showDebugSettings);
1516 mCurrentMenuState = mMenuState;
1521 public void onCreateContextMenu(ContextMenu menu, View v,
1522 ContextMenuInfo menuInfo) {
1523 if (v instanceof TitleBar) {
1526 WebView webview = (WebView) v;
1527 WebView.HitTestResult result = webview.getHitTestResult();
1528 if (result == null) {
1532 int type = result.getType();
1533 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1535 "We should not show context menu when nothing is touched");
1538 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1539 // let TextView handles context menu
1543 // Note, http://b/issue?id=1106666 is requesting that
1544 // an inflated menu can be used again. This is not available
1545 // yet, so inflate each time (yuk!)
1546 MenuInflater inflater = getMenuInflater();
1547 inflater.inflate(R.menu.browsercontext, menu);
1549 // Show the correct menu group
1550 String extra = result.getExtra();
1551 menu.setGroupVisible(R.id.PHONE_MENU,
1552 type == WebView.HitTestResult.PHONE_TYPE);
1553 menu.setGroupVisible(R.id.EMAIL_MENU,
1554 type == WebView.HitTestResult.EMAIL_TYPE);
1555 menu.setGroupVisible(R.id.GEO_MENU,
1556 type == WebView.HitTestResult.GEO_TYPE);
1557 menu.setGroupVisible(R.id.IMAGE_MENU,
1558 type == WebView.HitTestResult.IMAGE_TYPE
1559 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1560 menu.setGroupVisible(R.id.ANCHOR_MENU,
1561 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1562 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1564 // Setup custom handling depending on the type
1566 case WebView.HitTestResult.PHONE_TYPE:
1567 menu.setHeaderTitle(Uri.decode(extra));
1568 menu.findItem(R.id.dial_context_menu_id).setIntent(
1569 new Intent(Intent.ACTION_VIEW, Uri
1570 .parse(WebView.SCHEME_TEL + extra)));
1571 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1572 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1573 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1574 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1576 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1580 case WebView.HitTestResult.EMAIL_TYPE:
1581 menu.setHeaderTitle(extra);
1582 menu.findItem(R.id.email_context_menu_id).setIntent(
1583 new Intent(Intent.ACTION_VIEW, Uri
1584 .parse(WebView.SCHEME_MAILTO + extra)));
1585 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1589 case WebView.HitTestResult.GEO_TYPE:
1590 menu.setHeaderTitle(extra);
1591 menu.findItem(R.id.map_context_menu_id).setIntent(
1592 new Intent(Intent.ACTION_VIEW, Uri
1593 .parse(WebView.SCHEME_GEO
1594 + URLEncoder.encode(extra))));
1595 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1599 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1600 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1601 TextView titleView = (TextView) LayoutInflater.from(this)
1602 .inflate(android.R.layout.browser_link_context_header,
1604 titleView.setText(extra);
1605 menu.setHeaderView(titleView);
1606 // decide whether to show the open link in new tab option
1607 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1608 mTabControl.canCreateNewTab());
1609 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1610 Bookmarks.urlHasAcceptableScheme(extra));
1611 PackageManager pm = getPackageManager();
1612 Intent send = new Intent(Intent.ACTION_SEND);
1613 send.setType("text/plain");
1614 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1615 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1616 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1619 // otherwise fall through to handle image part
1620 case WebView.HitTestResult.IMAGE_TYPE:
1621 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1622 menu.setHeaderTitle(extra);
1624 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1625 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1626 menu.findItem(R.id.download_context_menu_id).
1627 setOnMenuItemClickListener(new Download(extra));
1628 menu.findItem(R.id.set_wallpaper_context_menu_id).
1629 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1633 Log.w(LOGTAG, "We should not get here.");
1639 // Attach the given tab to the content view.
1640 // this should only be called for the current tab.
1641 private void attachTabToContentView(Tab t) {
1642 // Attach the container that contains the main WebView and any other UI
1643 // associated with the tab.
1644 t.attachTabToContentView(mContentView);
1646 if (mShouldShowErrorConsole) {
1647 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1648 if (errorConsole.numberOfErrors() == 0) {
1649 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1651 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1654 mErrorConsoleContainer.addView(errorConsole,
1655 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1656 ViewGroup.LayoutParams.WRAP_CONTENT));
1659 WebView view = t.getWebView();
1660 view.setEmbeddedTitleBar(mTitleBar);
1661 if (t.isInVoiceSearchMode()) {
1662 showVoiceTitleBar(t.getVoiceDisplayTitle());
1664 revertVoiceTitleBar();
1666 // Request focus on the top window.
1667 t.getTopWindow().requestFocus();
1670 // Attach a sub window to the main WebView of the given tab.
1671 void attachSubWindow(Tab t) {
1672 t.attachSubWindow(mContentView);
1673 getTopWindow().requestFocus();
1676 // Remove the given tab from the content view.
1677 private void removeTabFromContentView(Tab t) {
1678 // Remove the container that contains the main WebView.
1679 t.removeTabFromContentView(mContentView);
1681 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1682 if (errorConsole != null) {
1683 mErrorConsoleContainer.removeView(errorConsole);
1686 WebView view = t.getWebView();
1688 view.setEmbeddedTitleBar(null);
1692 // Remove the sub window if it exists. Also called by TabControl when the
1693 // user clicks the 'X' to dismiss a sub window.
1694 /* package */ void dismissSubWindow(Tab t) {
1695 t.removeSubWindow(mContentView);
1696 // dismiss the subwindow. This will destroy the WebView.
1697 t.dismissSubWindow();
1698 getTopWindow().requestFocus();
1701 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1702 // that accepts url as string.
1703 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1704 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1707 // This method does a ton of stuff. It will attempt to create a new tab
1708 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1709 // url isn't null, it will load the given url.
1710 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1712 final Tab currentTab = mTabControl.getCurrentTab();
1713 if (mTabControl.canCreateNewTab()) {
1714 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1716 WebView webview = tab.getWebView();
1717 // If the last tab was removed from the active tabs page, currentTab
1719 if (currentTab != null) {
1720 removeTabFromContentView(currentTab);
1722 // We must set the new tab as the current tab to reflect the old
1723 // animation behavior.
1724 mTabControl.setCurrentTab(tab);
1725 attachTabToContentView(tab);
1726 if (!urlData.isEmpty()) {
1727 loadUrlDataIn(tab, urlData);
1731 // Get rid of the subwindow if it exists
1732 dismissSubWindow(currentTab);
1733 if (!urlData.isEmpty()) {
1734 // Load the given url.
1735 loadUrlDataIn(currentTab, urlData);
1741 private Tab openTab(String url) {
1742 if (mSettings.openInBackground()) {
1743 Tab t = mTabControl.createNewTab();
1745 WebView view = t.getWebView();
1750 return openTabAndShow(url, false, null);
1754 private class Copy implements OnMenuItemClickListener {
1755 private CharSequence mText;
1757 public boolean onMenuItemClick(MenuItem item) {
1762 public Copy(CharSequence toCopy) {
1767 private class Download implements OnMenuItemClickListener {
1768 private String mText;
1770 public boolean onMenuItemClick(MenuItem item) {
1771 onDownloadStartNoStream(mText, null, null, null, -1);
1775 public Download(String toDownload) {
1780 private class SetAsWallpaper extends Thread implements
1781 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1783 private ProgressDialog mWallpaperProgress;
1784 private boolean mCanceled = false;
1786 public SetAsWallpaper(String url) {
1788 mUrl = new URL(url);
1789 } catch (MalformedURLException e) {
1794 public void onCancel(DialogInterface dialog) {
1798 public boolean onMenuItemClick(MenuItem item) {
1800 // The user may have tried to set a image with a large file size as their
1801 // background so it may take a few moments to perform the operation. Display
1802 // a progress spinner while it is working.
1803 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1804 mWallpaperProgress.setIndeterminate(true);
1805 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1806 mWallpaperProgress.setCancelable(true);
1807 mWallpaperProgress.setOnCancelListener(this);
1808 mWallpaperProgress.show();
1815 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1817 // TODO: This will cause the resource to be downloaded again, when we
1818 // should in most cases be able to grab it from the cache. To fix this
1819 // we should query WebCore to see if we can access a cached version and
1820 // instead open an input stream on that. This pattern could also be used
1821 // in the download manager where the same problem exists.
1822 InputStream inputstream = mUrl.openStream();
1823 if (inputstream != null) {
1824 setWallpaper(inputstream);
1826 } catch (IOException e) {
1827 Log.e(LOGTAG, "Unable to set new wallpaper");
1828 // Act as though the user canceled the operation so we try to
1829 // restore the old wallpaper.
1834 // Restore the old wallpaper if the user cancelled whilst we were setting
1835 // the new wallpaper.
1836 int width = oldWallpaper.getIntrinsicWidth();
1837 int height = oldWallpaper.getIntrinsicHeight();
1838 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1839 Canvas canvas = new Canvas(bm);
1840 oldWallpaper.setBounds(0, 0, width, height);
1841 oldWallpaper.draw(canvas);
1844 } catch (IOException e) {
1845 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1850 if (mWallpaperProgress.isShowing()) {
1851 mWallpaperProgress.dismiss();
1856 private void copy(CharSequence text) {
1858 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1860 clip.setClipboardText(text);
1862 } catch (android.os.RemoteException e) {
1863 Log.e(LOGTAG, "Copy failed", e);
1868 * Resets the browser title-view to whatever it must be
1869 * (for example, if we had a loading error)
1870 * When we have a new page, we call resetTitle, when we
1871 * have to reset the titlebar to whatever it used to be
1872 * (for example, if the user chose to stop loading), we
1873 * call resetTitleAndRevertLockIcon.
1875 /* package */ void resetTitleAndRevertLockIcon() {
1876 mTabControl.getCurrentTab().revertLockIcon();
1877 updateLockIconToLatest();
1878 resetTitleIconAndProgress();
1882 * Reset the title, favicon, and progress.
1884 private void resetTitleIconAndProgress() {
1885 WebView current = mTabControl.getCurrentWebView();
1886 if (current == null) {
1889 resetTitleAndIcon(current);
1890 int progress = current.getProgress();
1891 current.getWebChromeClient().onProgressChanged(current, progress);
1894 // Reset the title and the icon based on the given item.
1895 private void resetTitleAndIcon(WebView view) {
1896 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1898 setUrlTitle(item.getUrl(), item.getTitle());
1899 setFavicon(item.getFavicon());
1901 setUrlTitle(null, null);
1907 * Sets a title composed of the URL and the title string.
1908 * @param url The URL of the site being loaded.
1909 * @param title The title of the site being loaded.
1911 void setUrlTitle(String url, String title) {
1915 // If we are in voice search mode, the title has already been set.
1916 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1917 mTitleBar.setDisplayTitle(url);
1918 mFakeTitleBar.setDisplayTitle(url);
1922 * @param url The URL to build a title version of the URL from.
1923 * @return The title version of the URL or null if fails.
1924 * The title version of the URL can be either the URL hostname,
1925 * or the hostname with an "https://" prefix (for secure URLs),
1926 * or an empty string if, for example, the URL in question is a
1927 * file:// URL with no hostname.
1929 /* package */ static String buildTitleUrl(String url) {
1930 String titleUrl = null;
1934 // parse the url string
1935 URL urlObj = new URL(url);
1936 if (urlObj != null) {
1939 String protocol = urlObj.getProtocol();
1940 String host = urlObj.getHost();
1942 if (host != null && 0 < host.length()) {
1944 if (protocol != null) {
1945 // if a secure site, add an "https://" prefix!
1946 if (protocol.equalsIgnoreCase("https")) {
1947 titleUrl = protocol + "://" + host;
1952 } catch (MalformedURLException e) {}
1958 // Set the favicon in the title bar.
1959 void setFavicon(Bitmap icon) {
1960 mTitleBar.setFavicon(icon);
1961 mFakeTitleBar.setFavicon(icon);
1965 * Close the tab, remove its associated title bar, and adjust mTabControl's
1966 * current tab to a valid value.
1968 /* package */ void closeTab(Tab t) {
1969 int currentIndex = mTabControl.getCurrentIndex();
1970 int removeIndex = mTabControl.getTabIndex(t);
1971 mTabControl.removeTab(t);
1972 if (currentIndex >= removeIndex && currentIndex != 0) {
1975 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
1976 resetTitleIconAndProgress();
1979 /* package */ void goBackOnePageOrQuit() {
1980 Tab current = mTabControl.getCurrentTab();
1981 if (current == null) {
1983 * Instead of finishing the activity, simply push this to the back
1984 * of the stack and let ActivityManager to choose the foreground
1985 * activity. As BrowserActivity is singleTask, it will be always the
1986 * root of the task. So we can use either true or false for
1989 moveTaskToBack(true);
1992 WebView w = current.getWebView();
1993 if (w.canGoBack()) {
1996 // Check to see if we are closing a window that was created by
1997 // another window. If so, we switch back to that window.
1998 Tab parent = current.getParentTab();
1999 if (parent != null) {
2000 switchToTab(mTabControl.getTabIndex(parent));
2001 // Now we close the other tab
2004 if (current.closeOnExit()) {
2005 // force the tab's inLoad() to be false as we are going to
2006 // either finish the activity or remove the tab. This will
2007 // ensure pauseWebViewTimers() taking action.
2008 mTabControl.getCurrentTab().clearInLoad();
2009 if (mTabControl.getTabCount() == 1) {
2013 // call pauseWebViewTimers() now, we won't be able to call
2014 // it in onPause() as the WebView won't be valid.
2015 // Temporarily change mActivityInPause to be true as
2016 // pauseWebViewTimers() will do nothing if mActivityInPause
2018 boolean savedState = mActivityInPause;
2020 Log.e(LOGTAG, "BrowserActivity is already paused "
2021 + "while handing goBackOnePageOrQuit.");
2023 mActivityInPause = true;
2024 pauseWebViewTimers();
2025 mActivityInPause = savedState;
2026 removeTabFromContentView(current);
2027 mTabControl.removeTab(current);
2030 * Instead of finishing the activity, simply push this to the back
2031 * of the stack and let ActivityManager to choose the foreground
2032 * activity. As BrowserActivity is singleTask, it will be always the
2033 * root of the task. So we can use either true or false for
2036 moveTaskToBack(true);
2041 boolean isMenuDown() {
2046 public boolean onKeyDown(int keyCode, KeyEvent event) {
2047 // Even if MENU is already held down, we need to call to super to open
2048 // the IME on long press.
2049 if (KeyEvent.KEYCODE_MENU == keyCode) {
2051 return super.onKeyDown(keyCode, event);
2053 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2054 // still down, we don't want to trigger the search. Pretend to consume
2055 // the key and do nothing.
2056 if (mMenuIsDown) return true;
2059 case KeyEvent.KEYCODE_SPACE:
2060 // WebView/WebTextView handle the keys in the KeyDown. As
2061 // the Activity's shortcut keys are only handled when WebView
2062 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2063 if (event.isShiftPressed()) {
2064 getTopWindow().pageUp(false);
2066 getTopWindow().pageDown(false);
2069 case KeyEvent.KEYCODE_BACK:
2070 if (event.getRepeatCount() == 0) {
2071 event.startTracking();
2073 } else if (mCustomView == null && mActiveTabsPage == null
2074 && event.isLongPress()) {
2075 bookmarksOrHistoryPicker(true);
2080 return super.onKeyDown(keyCode, event);
2084 public boolean onKeyUp(int keyCode, KeyEvent event) {
2086 case KeyEvent.KEYCODE_MENU:
2087 mMenuIsDown = false;
2089 case KeyEvent.KEYCODE_BACK:
2090 if (event.isTracking() && !event.isCanceled()) {
2091 if (mCustomView != null) {
2092 // if a custom view is showing, hide it
2093 mTabControl.getCurrentWebView().getWebChromeClient()
2094 .onHideCustomView();
2095 } else if (mActiveTabsPage != null) {
2096 // if tab page is showing, hide it
2097 removeActiveTabPage(true);
2099 WebView subwindow = mTabControl.getCurrentSubWindow();
2100 if (subwindow != null) {
2101 if (subwindow.canGoBack()) {
2104 dismissSubWindow(mTabControl.getCurrentTab());
2107 goBackOnePageOrQuit();
2114 return super.onKeyUp(keyCode, event);
2117 /* package */ void stopLoading() {
2118 mDidStopLoad = true;
2119 resetTitleAndRevertLockIcon();
2120 WebView w = getTopWindow();
2122 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2123 // same logic here. But for subwindow case, should we call into the main
2124 // WebView's onPageFinished as we never call its onPageStarted and if
2125 // the page finishes itself, we don't call onPageFinished.
2126 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2131 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2135 boolean didUserStopLoading() {
2136 return mDidStopLoad;
2139 private void cancelStopToast() {
2140 if (mStopToast != null) {
2141 mStopToast.cancel();
2146 // called by a UI or non-UI thread to post the message
2147 public void postMessage(int what, int arg1, int arg2, Object obj,
2149 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2153 // called by a UI or non-UI thread to remove the message
2154 void removeMessages(int what, Object object) {
2155 mHandler.removeMessages(what, object);
2158 // public message ids
2159 public final static int LOAD_URL = 1001;
2160 public final static int STOP_LOAD = 1002;
2163 private static final int FOCUS_NODE_HREF = 102;
2164 private static final int RELEASE_WAKELOCK = 107;
2166 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2168 // Private handler for handling javascript and saving passwords
2169 private Handler mHandler = new Handler() {
2171 public void handleMessage(Message msg) {
2173 case FOCUS_NODE_HREF:
2175 String url = (String) msg.getData().get("url");
2176 String title = (String) msg.getData().get("title");
2177 if (url == null || url.length() == 0) {
2180 HashMap focusNodeMap = (HashMap) msg.obj;
2181 WebView view = (WebView) focusNodeMap.get("webview");
2182 // Only apply the action if the top window did not change.
2183 if (getTopWindow() != view) {
2187 case R.id.open_context_menu_id:
2188 case R.id.view_image_context_menu_id:
2189 loadUrlFromContext(getTopWindow(), url);
2191 case R.id.open_newtab_context_menu_id:
2192 final Tab parent = mTabControl.getCurrentTab();
2193 final Tab newTab = openTab(url);
2194 if (newTab != parent) {
2195 parent.addChildTab(newTab);
2198 case R.id.bookmark_context_menu_id:
2199 Intent intent = new Intent(BrowserActivity.this,
2200 AddBookmarkPage.class);
2201 intent.putExtra("url", url);
2202 intent.putExtra("title", title);
2203 startActivity(intent);
2205 case R.id.share_link_context_menu_id:
2206 // See if this site has been visited before
2207 StringBuilder sb = new StringBuilder(
2208 Browser.BookmarkColumns.URL + " = ");
2209 DatabaseUtils.appendEscapedSQLString(sb, url);
2210 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2211 Browser.HISTORY_PROJECTION,
2215 if (c.moveToFirst()) {
2216 // The site has been visited before, so grab the
2217 // info from the database.
2218 Bitmap favicon = null;
2219 Bitmap thumbnail = null;
2220 String linkTitle = c.getString(Browser.
2221 HISTORY_PROJECTION_TITLE_INDEX);
2222 byte[] data = c.getBlob(Browser.
2223 HISTORY_PROJECTION_FAVICON_INDEX);
2225 favicon = BitmapFactory.decodeByteArray(
2226 data, 0, data.length);
2228 data = c.getBlob(Browser.
2229 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2231 thumbnail = BitmapFactory.decodeByteArray(
2232 data, 0, data.length);
2234 sharePage(BrowserActivity.this,
2235 linkTitle, url, favicon, thumbnail);
2237 Browser.sendString(BrowserActivity.this, url,
2239 R.string.choosertitle_sharevia));
2242 case R.id.copy_link_context_menu_id:
2245 case R.id.save_link_context_menu_id:
2246 case R.id.download_context_menu_id:
2247 onDownloadStartNoStream(url, null, null, null, -1);
2254 loadUrlFromContext(getTopWindow(), (String) msg.obj);
2261 case RELEASE_WAKELOCK:
2262 if (mWakeLock.isHeld()) {
2263 mWakeLock.release();
2264 // if we reach here, Browser should be still in the
2265 // background loading after WAKELOCK_TIMEOUT (5-min).
2266 // To avoid burning the battery, stop loading.
2267 mTabControl.stopAllLoading();
2271 case UPDATE_BOOKMARK_THUMBNAIL:
2272 WebView view = (WebView) msg.obj;
2274 updateScreenshot(view);
2282 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2283 * an {@link Intent} to launch the Activity chooser.
2284 * @param c Context used to launch a new Activity.
2285 * @param title Title of the page. Stored in the Intent with
2286 * {@link Intent#EXTRA_SUBJECT}
2287 * @param url URL of the page. Stored in the Intent with
2288 * {@link Intent#EXTRA_TEXT}
2289 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2290 * with {@link Browser#EXTRA_SHARE_FAVICON}
2291 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2292 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2294 public static final void sharePage(Context c, String title, String url,
2295 Bitmap favicon, Bitmap screenshot) {
2296 Intent send = new Intent(Intent.ACTION_SEND);
2297 send.setType("text/plain");
2298 send.putExtra(Intent.EXTRA_TEXT, url);
2299 send.putExtra(Intent.EXTRA_SUBJECT, title);
2300 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2301 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2303 c.startActivity(Intent.createChooser(send, c.getString(
2304 R.string.choosertitle_sharevia)));
2305 } catch(android.content.ActivityNotFoundException ex) {
2306 // if no app handles it, do nothing
2310 private void updateScreenshot(WebView view) {
2311 // If this is a bookmarked site, add a screenshot to the database.
2312 // FIXME: When should we update? Every time?
2313 // FIXME: Would like to make sure there is actually something to
2314 // draw, but the API for that (WebViewCore.pictureReady()) is not
2315 // currently accessible here.
2317 final Bitmap bm = createScreenshot(view);
2322 final ContentResolver cr = getContentResolver();
2323 final String url = view.getUrl();
2324 final String originalUrl = view.getOriginalUrl();
2326 new AsyncTask<Void, Void, Void>() {
2328 protected Void doInBackground(Void... unused) {
2331 c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2332 cr, originalUrl, url, true);
2334 if (c.moveToFirst()) {
2335 ContentValues values = new ContentValues();
2336 final ByteArrayOutputStream os
2337 = new ByteArrayOutputStream();
2338 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2339 values.put(Browser.BookmarkColumns.THUMBNAIL,
2342 cr.update(ContentUris.withAppendedId(
2343 Browser.BOOKMARKS_URI, c.getInt(0)),
2344 values, null, null);
2345 } while (c.moveToNext());
2348 } catch (IllegalStateException e) {
2351 if (c != null) c.close();
2359 * Values for the size of the thumbnail created when taking a screenshot.
2360 * Lazily initialized. Instead of using these directly, use
2361 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2363 private static int THUMBNAIL_WIDTH = 0;
2364 private static int THUMBNAIL_HEIGHT = 0;
2367 * Return the desired width for thumbnail screenshots, which are stored in
2368 * the database, and used on the bookmarks screen.
2369 * @param context Context for finding out the density of the screen.
2370 * @return int desired width for thumbnail screenshot.
2372 /* package */ static int getDesiredThumbnailWidth(Context context) {
2373 if (THUMBNAIL_WIDTH == 0) {
2374 float density = context.getResources().getDisplayMetrics().density;
2375 THUMBNAIL_WIDTH = (int) (90 * density);
2376 THUMBNAIL_HEIGHT = (int) (80 * density);
2378 return THUMBNAIL_WIDTH;
2382 * Return the desired height for thumbnail screenshots, which are stored in
2383 * the database, and used on the bookmarks screen.
2384 * @param context Context for finding out the density of the screen.
2385 * @return int desired height for thumbnail screenshot.
2387 /* package */ static int getDesiredThumbnailHeight(Context context) {
2388 // To ensure that they are both initialized.
2389 getDesiredThumbnailWidth(context);
2390 return THUMBNAIL_HEIGHT;
2393 private Bitmap createScreenshot(WebView view) {
2394 Picture thumbnail = view.capturePicture();
2395 if (thumbnail == null) {
2398 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2399 getDesiredThumbnailHeight(this), Bitmap.Config.RGB_565);
2400 Canvas canvas = new Canvas(bm);
2401 // May need to tweak these values to determine what is the
2402 // best scale factor
2403 int thumbnailWidth = thumbnail.getWidth();
2404 int thumbnailHeight = thumbnail.getHeight();
2405 float scaleFactorX = 1.0f;
2406 float scaleFactorY = 1.0f;
2407 if (thumbnailWidth > 0) {
2408 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2409 (float)thumbnailWidth;
2414 if (view.getWidth() > view.getHeight() &&
2415 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2416 // If the device is in landscape and the page is shorter
2417 // than the height of the view, stretch the thumbnail to fill the
2419 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2420 (float)thumbnailHeight;
2422 // In the portrait case, this looks nice.
2423 scaleFactorY = scaleFactorX;
2426 canvas.scale(scaleFactorX, scaleFactorY);
2428 thumbnail.draw(canvas);
2432 // -------------------------------------------------------------------------
2433 // Helper function for WebViewClient.
2434 //-------------------------------------------------------------------------
2436 // Use in overrideUrlLoading
2437 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2438 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2439 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2440 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2442 // Keep this initial progress in sync with initialProgressValue (* 100)
2443 // in ProgressTracker.cpp
2444 private final static int INITIAL_PROGRESS = 10;
2446 void onPageStarted(WebView view, String url, Bitmap favicon) {
2447 // when BrowserActivity just starts, onPageStarted may be called before
2448 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2449 // to start the timer. As we won't switch tabs while an activity is in
2450 // pause state, we can ensure calling resume and pause in pair.
2451 if (mActivityInPause) resumeWebViewTimers();
2454 setUrlTitle(url, null);
2455 setFavicon(favicon);
2456 // Show some progress so that the user knows the page is beginning to
2458 onProgressChanged(view, INITIAL_PROGRESS);
2459 mDidStopLoad = false;
2460 if (!mIsNetworkUp) createAndShowNetworkDialog();
2462 if (mSettings.isTracing()) {
2465 WebAddress uri = new WebAddress(url);
2467 } catch (android.net.ParseException ex) {
2470 host = host.replace('.', '_');
2473 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2476 // Performance probe
2478 mStart = SystemClock.uptimeMillis();
2479 mProcessStart = Process.getElapsedCpuTime();
2480 long[] sysCpu = new long[7];
2481 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2483 mUserStart = sysCpu[0] + sysCpu[1];
2484 mSystemStart = sysCpu[2];
2485 mIdleStart = sysCpu[3];
2486 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2488 mUiStart = SystemClock.currentThreadTimeMillis();
2492 void onPageFinished(WebView view, String url) {
2493 // Reset the title and icon in case we stopped a provisional load.
2494 resetTitleAndIcon(view);
2495 // Update the lock icon image only once we are done loading
2496 updateLockIconToLatest();
2497 // pause the WebView timer and release the wake lock if it is finished
2498 // while BrowserActivity is in pause state.
2499 if (mActivityInPause && pauseWebViewTimers()) {
2500 if (mWakeLock.isHeld()) {
2501 mHandler.removeMessages(RELEASE_WAKELOCK);
2502 mWakeLock.release();
2506 // Performance probe
2508 long[] sysCpu = new long[7];
2509 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2511 String uiInfo = "UI thread used "
2512 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2515 Log.d(LOGTAG, uiInfo);
2517 //The string that gets written to the log
2518 String performanceString = "It took total "
2519 + (SystemClock.uptimeMillis() - mStart)
2520 + " ms clock time to load the page."
2521 + "\nbrowser process used "
2522 + (Process.getElapsedCpuTime() - mProcessStart)
2523 + " ms, user processes used "
2524 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2525 + " ms, kernel used "
2526 + (sysCpu[2] - mSystemStart) * 10
2527 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2528 + " ms and irq took "
2529 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2530 * 10 + " ms, " + uiInfo;
2532 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2535 // strip the url to maintain consistency
2536 String newUrl = new String(url);
2537 if (newUrl.startsWith("http://www.")) {
2538 newUrl = newUrl.substring(11);
2539 } else if (newUrl.startsWith("http://")) {
2540 newUrl = newUrl.substring(7);
2541 } else if (newUrl.startsWith("https://www.")) {
2542 newUrl = newUrl.substring(12);
2543 } else if (newUrl.startsWith("https://")) {
2544 newUrl = newUrl.substring(8);
2547 Log.d(LOGTAG, newUrl + " loaded");
2555 Debug.stopMethodTracing();
2559 boolean shouldOverrideUrlLoading(WebView view, String url) {
2560 if (url.startsWith(SCHEME_WTAI)) {
2561 // wtai://wp/mc;number
2562 // number=string(phone-number)
2563 if (url.startsWith(SCHEME_WTAI_MC)) {
2564 Intent intent = new Intent(Intent.ACTION_VIEW,
2565 Uri.parse(WebView.SCHEME_TEL +
2566 url.substring(SCHEME_WTAI_MC.length())));
2567 startActivity(intent);
2570 // wtai://wp/sd;dtmf
2571 // dtmf=string(dialstring)
2572 if (url.startsWith(SCHEME_WTAI_SD)) {
2573 // TODO: only send when there is active voice connection
2576 // wtai://wp/ap;number;name
2577 // number=string(phone-number)
2579 if (url.startsWith(SCHEME_WTAI_AP)) {
2585 // The "about:" schemes are internal to the browser; don't want these to
2586 // be dispatched to other apps.
2587 if (url.startsWith("about:")) {
2592 // perform generic parsing of the URI to turn it into an Intent.
2594 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2595 } catch (URISyntaxException ex) {
2596 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2600 // check whether the intent can be resolved. If not, we will see
2601 // whether we can download it from the Market.
2602 if (getPackageManager().resolveActivity(intent, 0) == null) {
2603 String packagename = intent.getPackage();
2604 if (packagename != null) {
2605 intent = new Intent(Intent.ACTION_VIEW, Uri
2606 .parse("market://search?q=pname:" + packagename));
2607 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2608 startActivity(intent);
2615 // sanitize the Intent, ensuring web pages can not bypass browser
2616 // security (only access to BROWSABLE activities).
2617 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2618 intent.setComponent(null);
2620 if (startActivityIfNeeded(intent, -1)) {
2623 } catch (ActivityNotFoundException ex) {
2624 // ignore the error. If no application can handle the URL,
2625 // eg about:blank, assume the browser can handle it.
2636 // -------------------------------------------------------------------------
2637 // Helper function for WebChromeClient
2638 // -------------------------------------------------------------------------
2640 void onProgressChanged(WebView view, int newProgress) {
2641 mFakeTitleBar.setProgress(newProgress);
2643 if (newProgress == 100) {
2644 // onProgressChanged() may continue to be called after the main
2645 // frame has finished loading, as any remaining sub frames continue
2646 // to load. We'll only get called once though with newProgress as
2647 // 100 when everything is loaded. (onPageFinished is called once
2648 // when the main frame completes loading regardless of the state of
2649 // any sub frames so calls to onProgressChanges may continue after
2650 // onPageFinished has executed)
2653 updateInLoadMenuItems();
2654 // If the options menu is open, leave the title bar
2655 if (!mOptionsMenuOpen || !mIconView) {
2661 // onPageFinished may have already been called but a subframe is
2662 // still loading and updating the progress. Reset mInLoad and
2663 // update the menu items.
2665 updateInLoadMenuItems();
2667 // When the page first begins to load, the Activity may still be
2668 // paused, in which case showFakeTitleBar will do nothing. Call
2669 // again as the page continues to load so that it will be shown.
2670 // (Calling it will the fake title bar is already showing will also
2672 if (!mOptionsMenuOpen || mIconView) {
2673 // This page has begun to load, so show the title bar
2679 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2680 // if a view already exists then immediately terminate the new one
2681 if (mCustomView != null) {
2682 callback.onCustomViewHidden();
2686 // Add the custom view to its container.
2687 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2689 mCustomViewCallback = callback;
2690 // Save the menu state and set it to empty while the custom
2692 mOldMenuState = mMenuState;
2693 mMenuState = EMPTY_MENU;
2694 // Hide the content view.
2695 mContentView.setVisibility(View.GONE);
2696 // Finally show the custom view container.
2697 setStatusBarVisibility(false);
2698 mCustomViewContainer.setVisibility(View.VISIBLE);
2699 mCustomViewContainer.bringToFront();
2702 void onHideCustomView() {
2703 if (mCustomView == null)
2706 // Hide the custom view.
2707 mCustomView.setVisibility(View.GONE);
2708 // Remove the custom view from its container.
2709 mCustomViewContainer.removeView(mCustomView);
2711 // Reset the old menu state.
2712 mMenuState = mOldMenuState;
2713 mOldMenuState = EMPTY_MENU;
2714 mCustomViewContainer.setVisibility(View.GONE);
2715 mCustomViewCallback.onCustomViewHidden();
2716 // Show the content view.
2717 setStatusBarVisibility(true);
2718 mContentView.setVisibility(View.VISIBLE);
2721 Bitmap getDefaultVideoPoster() {
2722 if (mDefaultVideoPoster == null) {
2723 mDefaultVideoPoster = BitmapFactory.decodeResource(
2724 getResources(), R.drawable.default_video_poster);
2726 return mDefaultVideoPoster;
2729 View getVideoLoadingProgressView() {
2730 if (mVideoProgressView == null) {
2731 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2732 mVideoProgressView = inflater.inflate(
2733 R.layout.video_loading_progress, null);
2735 return mVideoProgressView;
2739 * The Object used to inform the WebView of the file to upload.
2741 private ValueCallback<Uri> mUploadMessage;
2743 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2744 if (mUploadMessage != null) return;
2745 mUploadMessage = uploadMsg;
2746 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2747 i.addCategory(Intent.CATEGORY_OPENABLE);
2749 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2750 getString(R.string.choose_upload)), FILE_SELECTED);
2753 // -------------------------------------------------------------------------
2754 // Implement functions for DownloadListener
2755 // -------------------------------------------------------------------------
2758 * Notify the host application a download should be done, or that
2759 * the data should be streamed if a streaming viewer is available.
2760 * @param url The full url to the content that should be downloaded
2761 * @param contentDisposition Content-disposition http header, if
2763 * @param mimetype The mimetype of the content reported by the server
2764 * @param contentLength The file size reported by the server
2766 public void onDownloadStart(String url, String userAgent,
2767 String contentDisposition, String mimetype, long contentLength) {
2768 // if we're dealing wih A/V content that's not explicitly marked
2769 // for download, check if it's streamable.
2770 if (contentDisposition == null
2771 || !contentDisposition.regionMatches(
2772 true, 0, "attachment", 0, 10)) {
2773 // query the package manager to see if there's a registered handler
2775 Intent intent = new Intent(Intent.ACTION_VIEW);
2776 intent.setDataAndType(Uri.parse(url), mimetype);
2777 ResolveInfo info = getPackageManager().resolveActivity(intent,
2778 PackageManager.MATCH_DEFAULT_ONLY);
2780 ComponentName myName = getComponentName();
2781 // If we resolved to ourselves, we don't want to attempt to
2782 // load the url only to try and download it again.
2783 if (!myName.getPackageName().equals(
2784 info.activityInfo.packageName)
2785 || !myName.getClassName().equals(
2786 info.activityInfo.name)) {
2787 // someone (other than us) knows how to handle this mime
2788 // type with this scheme, don't download.
2790 startActivity(intent);
2792 } catch (ActivityNotFoundException ex) {
2794 Log.d(LOGTAG, "activity not found for " + mimetype
2795 + " over " + Uri.parse(url).getScheme(),
2798 // Best behavior is to fall back to a download in this
2804 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2807 // This is to work around the fact that java.net.URI throws Exceptions
2808 // instead of just encoding URL's properly
2809 // Helper method for onDownloadStartNoStream
2810 private static String encodePath(String path) {
2811 char[] chars = path.toCharArray();
2813 boolean needed = false;
2814 for (char c : chars) {
2815 if (c == '[' || c == ']') {
2820 if (needed == false) {
2824 StringBuilder sb = new StringBuilder("");
2825 for (char c : chars) {
2826 if (c == '[' || c == ']') {
2828 sb.append(Integer.toHexString(c));
2834 return sb.toString();
2838 * Notify the host application a download should be done, even if there
2839 * is a streaming viewer available for thise type.
2840 * @param url The full url to the content that should be downloaded
2841 * @param contentDisposition Content-disposition http header, if
2843 * @param mimetype The mimetype of the content reported by the server
2844 * @param contentLength The file size reported by the server
2846 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2847 String contentDisposition, String mimetype, long contentLength) {
2849 String filename = URLUtil.guessFileName(url,
2850 contentDisposition, mimetype);
2852 // Check to see if we have an SDCard
2853 String status = Environment.getExternalStorageState();
2854 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2858 // Check to see if the SDCard is busy, same as the music app
2859 if (status.equals(Environment.MEDIA_SHARED)) {
2860 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2861 title = R.string.download_sdcard_busy_dlg_title;
2863 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2864 title = R.string.download_no_sdcard_dlg_title;
2867 new AlertDialog.Builder(this)
2869 .setIcon(android.R.drawable.ic_dialog_alert)
2871 .setPositiveButton(R.string.ok, null)
2876 // java.net.URI is a lot stricter than KURL so we have to encode some
2877 // extra characters. Fix for b 2538060 and b 1634719
2878 WebAddress webAddress;
2880 webAddress = new WebAddress(url);
2881 webAddress.mPath = encodePath(webAddress.mPath);
2882 } catch (Exception e) {
2883 // This only happens for very bad urls, we want to chatch the
2885 Log.e(LOGTAG, "Exception trying to parse url:" + url);
2889 // XXX: Have to use the old url since the cookies were stored using the
2890 // old percent-encoded url.
2891 String cookies = CookieManager.getInstance().getCookie(url);
2893 ContentValues values = new ContentValues();
2894 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
2895 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2896 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2897 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
2899 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
2900 BrowserDownloadPage.class.getCanonicalName());
2901 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2902 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2903 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2904 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2905 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
2906 if (contentLength > 0) {
2907 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
2909 if (mimetype == null) {
2910 // We must have long pressed on a link or image to download it. We
2911 // are not sure of the mimetype in this case, so do a head request
2912 new FetchUrlMimeType(this).execute(values);
2914 final Uri contentUri =
2915 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
2917 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2921 // -------------------------------------------------------------------------
2924 * Resets the lock icon. This method is called when we start a new load and
2925 * know the url to be loaded.
2927 private void resetLockIcon(String url) {
2928 // Save the lock-icon state (we revert to it if the load gets cancelled)
2929 mTabControl.getCurrentTab().resetLockIcon(url);
2930 updateLockIconImage(LOCK_ICON_UNSECURE);
2934 * Update the lock icon to correspond to our latest state.
2936 private void updateLockIconToLatest() {
2937 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
2941 * Updates the lock-icon image in the title-bar.
2943 private void updateLockIconImage(int lockIconType) {
2945 if (lockIconType == LOCK_ICON_SECURE) {
2947 } else if (lockIconType == LOCK_ICON_MIXED) {
2950 mTitleBar.setLock(d);
2951 mFakeTitleBar.setLock(d);
2955 * Displays a page-info dialog.
2956 * @param tab The tab to show info about
2957 * @param fromShowSSLCertificateOnError The flag that indicates whether
2958 * this dialog was opened from the SSL-certificate-on-error dialog or
2959 * not. This is important, since we need to know whether to return to
2960 * the parent dialog or simply dismiss.
2962 private void showPageInfo(final Tab tab,
2963 final boolean fromShowSSLCertificateOnError) {
2964 final LayoutInflater factory = LayoutInflater
2967 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2969 final WebView view = tab.getWebView();
2972 String title = null;
2976 title = tab.getTitle();
2977 } else if (view == mTabControl.getCurrentWebView()) {
2978 // Use the cached title and url if this is the current WebView
2982 url = view.getUrl();
2983 title = view.getTitle();
2989 if (title == null) {
2993 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2994 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2996 mPageInfoView = tab;
2997 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
2999 AlertDialog.Builder alertDialogBuilder =
3000 new AlertDialog.Builder(this)
3001 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3002 .setView(pageInfoView)
3005 new DialogInterface.OnClickListener() {
3006 public void onClick(DialogInterface dialog,
3008 mPageInfoDialog = null;
3009 mPageInfoView = null;
3011 // if we came here from the SSL error dialog
3012 if (fromShowSSLCertificateOnError) {
3013 // go back to the SSL error dialog
3014 showSSLCertificateOnError(
3015 mSSLCertificateOnErrorView,
3016 mSSLCertificateOnErrorHandler,
3017 mSSLCertificateOnErrorError);
3021 .setOnCancelListener(
3022 new DialogInterface.OnCancelListener() {
3023 public void onCancel(DialogInterface dialog) {
3024 mPageInfoDialog = null;
3025 mPageInfoView = null;
3027 // if we came here from the SSL error dialog
3028 if (fromShowSSLCertificateOnError) {
3029 // go back to the SSL error dialog
3030 showSSLCertificateOnError(
3031 mSSLCertificateOnErrorView,
3032 mSSLCertificateOnErrorHandler,
3033 mSSLCertificateOnErrorError);
3038 // if we have a main top-level page SSL certificate set or a certificate
3040 if (fromShowSSLCertificateOnError ||
3041 (view != null && view.getCertificate() != null)) {
3042 // add a 'View Certificate' button
3043 alertDialogBuilder.setNeutralButton(
3044 R.string.view_certificate,
3045 new DialogInterface.OnClickListener() {
3046 public void onClick(DialogInterface dialog,
3048 mPageInfoDialog = null;
3049 mPageInfoView = null;
3051 // if we came here from the SSL error dialog
3052 if (fromShowSSLCertificateOnError) {
3053 // go back to the SSL error dialog
3054 showSSLCertificateOnError(
3055 mSSLCertificateOnErrorView,
3056 mSSLCertificateOnErrorHandler,
3057 mSSLCertificateOnErrorError);
3059 // otherwise, display the top-most certificate from
3061 if (view.getCertificate() != null) {
3062 showSSLCertificate(tab);
3069 mPageInfoDialog = alertDialogBuilder.show();
3073 * Displays the main top-level page SSL certificate dialog
3074 * (accessible from the Page-Info dialog).
3075 * @param tab The tab to show certificate for.
3077 private void showSSLCertificate(final Tab tab) {
3078 final View certificateView =
3079 inflateCertificateView(tab.getWebView().getCertificate());
3080 if (certificateView == null) {
3084 LayoutInflater factory = LayoutInflater.from(this);
3086 final LinearLayout placeholder =
3087 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3089 LinearLayout ll = (LinearLayout) factory.inflate(
3090 R.layout.ssl_success, placeholder);
3091 ((TextView)ll.findViewById(R.id.success))
3092 .setText(R.string.ssl_certificate_is_valid);
3094 mSSLCertificateView = tab;
3095 mSSLCertificateDialog =
3096 new AlertDialog.Builder(this)
3097 .setTitle(R.string.ssl_certificate).setIcon(
3098 R.drawable.ic_dialog_browser_certificate_secure)
3099 .setView(certificateView)
3100 .setPositiveButton(R.string.ok,
3101 new DialogInterface.OnClickListener() {
3102 public void onClick(DialogInterface dialog,
3104 mSSLCertificateDialog = null;
3105 mSSLCertificateView = null;
3107 showPageInfo(tab, false);
3110 .setOnCancelListener(
3111 new DialogInterface.OnCancelListener() {
3112 public void onCancel(DialogInterface dialog) {
3113 mSSLCertificateDialog = null;
3114 mSSLCertificateView = null;
3116 showPageInfo(tab, false);
3123 * Displays the SSL error certificate dialog.
3124 * @param view The target web-view.
3125 * @param handler The SSL error handler responsible for cancelling the
3126 * connection that resulted in an SSL error or proceeding per user request.
3127 * @param error The SSL error object.
3129 void showSSLCertificateOnError(
3130 final WebView view, final SslErrorHandler handler, final SslError error) {
3132 final View certificateView =
3133 inflateCertificateView(error.getCertificate());
3134 if (certificateView == null) {
3138 LayoutInflater factory = LayoutInflater.from(this);
3140 final LinearLayout placeholder =
3141 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3143 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3144 LinearLayout ll = (LinearLayout)factory
3145 .inflate(R.layout.ssl_warning, placeholder);
3146 ((TextView)ll.findViewById(R.id.warning))
3147 .setText(R.string.ssl_untrusted);
3150 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3151 LinearLayout ll = (LinearLayout)factory
3152 .inflate(R.layout.ssl_warning, placeholder);
3153 ((TextView)ll.findViewById(R.id.warning))
3154 .setText(R.string.ssl_mismatch);
3157 if (error.hasError(SslError.SSL_EXPIRED)) {
3158 LinearLayout ll = (LinearLayout)factory
3159 .inflate(R.layout.ssl_warning, placeholder);
3160 ((TextView)ll.findViewById(R.id.warning))
3161 .setText(R.string.ssl_expired);
3164 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3165 LinearLayout ll = (LinearLayout)factory
3166 .inflate(R.layout.ssl_warning, placeholder);
3167 ((TextView)ll.findViewById(R.id.warning))
3168 .setText(R.string.ssl_not_yet_valid);
3171 mSSLCertificateOnErrorHandler = handler;
3172 mSSLCertificateOnErrorView = view;
3173 mSSLCertificateOnErrorError = error;
3174 mSSLCertificateOnErrorDialog =
3175 new AlertDialog.Builder(this)
3176 .setTitle(R.string.ssl_certificate).setIcon(
3177 R.drawable.ic_dialog_browser_certificate_partially_secure)
3178 .setView(certificateView)
3179 .setPositiveButton(R.string.ok,
3180 new DialogInterface.OnClickListener() {
3181 public void onClick(DialogInterface dialog,
3183 mSSLCertificateOnErrorDialog = null;
3184 mSSLCertificateOnErrorView = null;
3185 mSSLCertificateOnErrorHandler = null;
3186 mSSLCertificateOnErrorError = null;
3188 view.getWebViewClient().onReceivedSslError(
3189 view, handler, error);
3192 .setNeutralButton(R.string.page_info_view,
3193 new DialogInterface.OnClickListener() {
3194 public void onClick(DialogInterface dialog,
3196 mSSLCertificateOnErrorDialog = null;
3198 // do not clear the dialog state: we will
3199 // need to show the dialog again once the
3200 // user is done exploring the page-info details
3202 showPageInfo(mTabControl.getTabFromView(view),
3206 .setOnCancelListener(
3207 new DialogInterface.OnCancelListener() {
3208 public void onCancel(DialogInterface dialog) {
3209 mSSLCertificateOnErrorDialog = null;
3210 mSSLCertificateOnErrorView = null;
3211 mSSLCertificateOnErrorHandler = null;
3212 mSSLCertificateOnErrorError = null;
3214 view.getWebViewClient().onReceivedSslError(
3215 view, handler, error);
3222 * Inflates the SSL certificate view (helper method).
3223 * @param certificate The SSL certificate.
3224 * @return The resultant certificate view with issued-to, issued-by,
3225 * issued-on, expires-on, and possibly other fields set.
3226 * If the input certificate is null, returns null.
3228 private View inflateCertificateView(SslCertificate certificate) {
3229 if (certificate == null) {
3233 LayoutInflater factory = LayoutInflater.from(this);
3235 View certificateView = factory.inflate(
3236 R.layout.ssl_certificate, null);
3239 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3240 if (issuedTo != null) {
3241 ((TextView) certificateView.findViewById(R.id.to_common))
3242 .setText(issuedTo.getCName());
3243 ((TextView) certificateView.findViewById(R.id.to_org))
3244 .setText(issuedTo.getOName());
3245 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3246 .setText(issuedTo.getUName());
3250 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3251 if (issuedBy != null) {
3252 ((TextView) certificateView.findViewById(R.id.by_common))
3253 .setText(issuedBy.getCName());
3254 ((TextView) certificateView.findViewById(R.id.by_org))
3255 .setText(issuedBy.getOName());
3256 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3257 .setText(issuedBy.getUName());
3261 String issuedOn = formatCertificateDate(
3262 certificate.getValidNotBeforeDate());
3263 ((TextView) certificateView.findViewById(R.id.issued_on))
3267 String expiresOn = formatCertificateDate(
3268 certificate.getValidNotAfterDate());
3269 ((TextView) certificateView.findViewById(R.id.expires_on))
3270 .setText(expiresOn);
3272 return certificateView;
3276 * Formats the certificate date to a properly localized date string.
3277 * @return Properly localized version of the certificate date string and
3278 * the "" if it fails to localize.
3280 private String formatCertificateDate(Date certificateDate) {
3281 if (certificateDate == null) {
3284 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3285 if (formattedDate == null) {
3288 return formattedDate;
3292 * Displays an http-authentication dialog.
3294 void showHttpAuthentication(final HttpAuthHandler handler,
3295 final String host, final String realm, final String title,
3296 final String name, final String password, int focusId) {
3297 LayoutInflater factory = LayoutInflater.from(this);
3298 final View v = factory
3299 .inflate(R.layout.http_authentication, null);
3301 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3303 if (password != null) {
3304 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3307 String titleText = title;
3308 if (titleText == null) {
3309 titleText = getText(R.string.sign_in_to).toString().replace(
3310 "%s1", host).replace("%s2", realm);
3313 mHttpAuthHandler = handler;
3314 AlertDialog dialog = new AlertDialog.Builder(this)
3315 .setTitle(titleText)
3316 .setIcon(android.R.drawable.ic_dialog_alert)
3318 .setPositiveButton(R.string.action,
3319 new DialogInterface.OnClickListener() {
3320 public void onClick(DialogInterface dialog,
3322 String nm = ((EditText) v
3323 .findViewById(R.id.username_edit))
3324 .getText().toString();
3325 String pw = ((EditText) v
3326 .findViewById(R.id.password_edit))
3327 .getText().toString();
3328 BrowserActivity.this.setHttpAuthUsernamePassword
3329 (host, realm, nm, pw);
3330 handler.proceed(nm, pw);
3331 mHttpAuthenticationDialog = null;
3332 mHttpAuthHandler = null;
3334 .setNegativeButton(R.string.cancel,
3335 new DialogInterface.OnClickListener() {
3336 public void onClick(DialogInterface dialog,
3339 BrowserActivity.this.resetTitleAndRevertLockIcon();
3340 mHttpAuthenticationDialog = null;
3341 mHttpAuthHandler = null;
3343 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3344 public void onCancel(DialogInterface dialog) {
3346 BrowserActivity.this.resetTitleAndRevertLockIcon();
3347 mHttpAuthenticationDialog = null;
3348 mHttpAuthHandler = null;
3351 // Make the IME appear when the dialog is displayed if applicable.
3352 dialog.getWindow().setSoftInputMode(
3353 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3356 dialog.findViewById(focusId).requestFocus();
3358 v.findViewById(R.id.username_edit).requestFocus();
3360 mHttpAuthenticationDialog = dialog;
3363 public int getProgress() {
3364 WebView w = mTabControl.getCurrentWebView();
3366 return w.getProgress();
3373 * Set HTTP authentication password.
3375 * @param host The host for the password
3376 * @param realm The realm for the password
3377 * @param username The username for the password. If it is null, it means
3378 * password can't be saved.
3379 * @param password The password
3381 public void setHttpAuthUsernamePassword(String host, String realm,
3384 WebView w = getTopWindow();
3386 w.setHttpAuthUsernamePassword(host, realm, username, password);
3391 * connectivity manager says net has come or gone... inform the user
3392 * @param up true if net has come up, false if net has gone down
3394 public void onNetworkToggle(boolean up) {
3395 if (up == mIsNetworkUp) {
3398 mIsNetworkUp = true;
3399 if (mAlertDialog != null) {
3400 mAlertDialog.cancel();
3401 mAlertDialog = null;
3404 mIsNetworkUp = false;
3406 createAndShowNetworkDialog();
3409 WebView w = mTabControl.getCurrentWebView();
3411 w.setNetworkAvailable(up);
3415 boolean isNetworkUp() {
3416 return mIsNetworkUp;
3419 // This method shows the network dialog alerting the user that the net is
3420 // down. It will only show the dialog if mAlertDialog is null.
3421 private void createAndShowNetworkDialog() {
3422 if (mAlertDialog == null) {
3423 mAlertDialog = new AlertDialog.Builder(this)
3424 .setTitle(R.string.loadSuspendedTitle)
3425 .setMessage(R.string.loadSuspended)
3426 .setPositiveButton(R.string.ok, null)
3432 protected void onActivityResult(int requestCode, int resultCode,
3434 if (getTopWindow() == null) return;
3436 switch (requestCode) {
3438 if (resultCode == RESULT_OK && intent != null) {
3439 String data = intent.getAction();
3440 Bundle extras = intent.getExtras();
3441 if (extras != null && extras.getBoolean("new_window", false)) {
3444 final Tab currentTab =
3445 mTabControl.getCurrentTab();
3446 dismissSubWindow(currentTab);
3447 if (data != null && data.length() != 0) {
3448 loadUrl(getTopWindow(), data);
3452 // Deliberately fall through to PREFERENCES_PAGE, since the
3453 // same extra may be attached to the COMBO_PAGE
3454 case PREFERENCES_PAGE:
3455 if (resultCode == RESULT_OK && intent != null) {
3456 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3457 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3458 mTabControl.removeParentChildRelationShips();
3462 // Choose a file from the file picker.
3464 if (null == mUploadMessage) break;
3465 Uri result = intent == null || resultCode != RESULT_OK ? null
3467 mUploadMessage.onReceiveValue(result);
3468 mUploadMessage = null;
3473 getTopWindow().requestFocus();
3477 * This method is called as a result of the user selecting the options
3478 * menu to see the download window. It shows the download window on top of
3479 * the current window.
3481 private void viewDownloads(Uri downloadRecord) {
3482 Intent intent = new Intent(this,
3483 BrowserDownloadPage.class);
3484 intent.setData(downloadRecord);
3485 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3491 * @param startWithHistory If true, open starting on the history tab.
3492 * Otherwise, start with the bookmarks tab.
3494 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3495 WebView current = mTabControl.getCurrentWebView();
3496 if (current == null) {
3499 Intent intent = new Intent(this,
3500 CombinedBookmarkHistoryActivity.class);
3501 String title = current.getTitle();
3502 String url = current.getUrl();
3503 Bitmap thumbnail = createScreenshot(current);
3505 // Just in case the user opens bookmarks before a page finishes loading
3506 // so the current history item, and therefore the page, is null.
3508 url = mLastEnteredUrl;
3511 url = mSettings.getHomePage();
3514 // In case the web page has not yet received its associated title.
3515 if (title == null) {
3518 intent.putExtra("title", title);
3519 intent.putExtra("url", url);
3520 intent.putExtra("thumbnail", thumbnail);
3521 // Disable opening in a new window if we have maxed out the windows
3522 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3523 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3524 if (startWithHistory) {
3525 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3526 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3528 startActivityForResult(intent, COMBO_PAGE);
3531 // Called when loading from context menu or LOAD_URL message
3532 private void loadUrlFromContext(WebView view, String url) {
3533 // In case the user enters nothing.
3534 if (url != null && url.length() != 0 && view != null) {
3535 url = smartUrlFilter(url);
3536 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3543 * Load the URL into the given WebView and update the title bar
3544 * to reflect the new load. Call this instead of WebView.loadUrl
3546 * @param view The WebView used to load url.
3547 * @param url The URL to load.
3549 private void loadUrl(WebView view, String url) {
3550 updateTitleBarForNewLoad(view, url);
3555 * Load UrlData into a Tab and update the title bar to reflect the new
3556 * load. Call this instead of UrlData.loadIn directly.
3557 * @param t The Tab used to load.
3558 * @param data The UrlData being loaded.
3560 private void loadUrlDataIn(Tab t, UrlData data) {
3561 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3566 * If the WebView is the top window, update the title bar to reflect
3567 * loading the new URL. i.e. set its text, clear the favicon (which
3568 * will be set once the page begins loading), and set the progress to
3569 * INITIAL_PROGRESS to show that the page has begun to load. Called
3570 * by loadUrl and loadUrlDataIn.
3571 * @param view The WebView that is starting a load.
3572 * @param url The URL that is being loaded.
3574 private void updateTitleBarForNewLoad(WebView view, String url) {
3575 if (view == getTopWindow()) {
3576 setUrlTitle(url, null);
3578 onProgressChanged(view, INITIAL_PROGRESS);
3582 private String smartUrlFilter(Uri inUri) {
3583 if (inUri != null) {
3584 return smartUrlFilter(inUri.toString());
3589 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3590 "(?i)" + // switch on case insensitive matching
3591 "(" + // begin group for schema
3592 "(?:http|https|file):\\/\\/" +
3593 "|(?:inline|data|about|content|javascript):" +
3598 * Attempts to determine whether user input is a URL or search
3599 * terms. Anything with a space is passed to search.
3601 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3602 * "Http://" converts to "http://"
3604 * @return Original or modified URL
3607 String smartUrlFilter(String url) {
3609 String inUrl = url.trim();
3610 boolean hasSpace = inUrl.indexOf(' ') != -1;
3612 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3613 if (matcher.matches()) {
3614 // force scheme to lowercase
3615 String scheme = matcher.group(1);
3616 String lcScheme = scheme.toLowerCase();
3617 if (!lcScheme.equals(scheme)) {
3618 inUrl = lcScheme + matcher.group(2);
3621 inUrl = inUrl.replace(" ", "%20");
3626 // FIXME: Is this the correct place to add to searches?
3627 // what if someone else calls this function?
3628 int shortcut = parseUrlShortcut(inUrl);
3629 if (shortcut != SHORTCUT_INVALID) {
3630 Browser.addSearchUrl(mResolver, inUrl);
3631 String query = inUrl.substring(2);
3633 case SHORTCUT_GOOGLE_SEARCH:
3634 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3635 case SHORTCUT_WIKIPEDIA_SEARCH:
3636 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3637 case SHORTCUT_DICTIONARY_SEARCH:
3638 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3639 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3640 // FIXME: we need location in this case
3641 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3645 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3646 return URLUtil.guessUrl(inUrl);
3650 Browser.addSearchUrl(mResolver, inUrl);
3651 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3654 /* package */ void setShouldShowErrorConsole(boolean flag) {
3655 if (flag == mShouldShowErrorConsole) {
3660 mShouldShowErrorConsole = flag;
3662 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3663 .getErrorConsole(true);
3666 // Setting the show state of the console will cause it's the layout to be inflated.
3667 if (errorConsole.numberOfErrors() > 0) {
3668 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3670 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3673 // Now we can add it to the main view.
3674 mErrorConsoleContainer.addView(errorConsole,
3675 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3676 ViewGroup.LayoutParams.WRAP_CONTENT));
3678 mErrorConsoleContainer.removeView(errorConsole);
3683 boolean shouldShowErrorConsole() {
3684 return mShouldShowErrorConsole;
3687 private void setStatusBarVisibility(boolean visible) {
3688 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3689 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3693 private void sendNetworkType(String type, String subtype) {
3694 WebView w = mTabControl.getCurrentWebView();
3696 w.setNetworkType(type, subtype);
3700 private void packageChanged(String packageName, boolean wasAdded) {
3701 WebView w = mTabControl.getCurrentWebView();
3707 w.addPackageName(packageName);
3709 w.removePackageName(packageName);
3713 private void addPackageNames(Set<String> packageNames) {
3714 WebView w = mTabControl.getCurrentWebView();
3719 w.addPackageNames(packageNames);
3722 private void getInstalledPackages() {
3723 AsyncTask<Void, Void, Set<String> > task =
3724 new AsyncTask<Void, Void, Set<String> >() {
3725 protected Set<String> doInBackground(Void... unused) {
3726 Set<String> installedPackages = new HashSet<String>();
3727 PackageManager pm = BrowserActivity.this.getPackageManager();
3729 List<PackageInfo> packages = pm.getInstalledPackages(0);
3730 for (PackageInfo p : packages) {
3731 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3732 installedPackages.add(p.packageName);
3737 return installedPackages;
3740 // Executes on the UI thread
3741 protected void onPostExecute(Set<String> installedPackages) {
3742 addPackageNames(installedPackages);
3748 final static int LOCK_ICON_UNSECURE = 0;
3749 final static int LOCK_ICON_SECURE = 1;
3750 final static int LOCK_ICON_MIXED = 2;
3752 private BrowserSettings mSettings;
3753 private TabControl mTabControl;
3754 private ContentResolver mResolver;
3755 private FrameLayout mContentView;
3756 private View mCustomView;
3757 private FrameLayout mCustomViewContainer;
3758 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3760 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3761 // view, we should rewrite this.
3762 private int mCurrentMenuState = 0;
3763 private int mMenuState = R.id.MAIN_MENU;
3764 private int mOldMenuState = EMPTY_MENU;
3765 private static final int EMPTY_MENU = -1;
3768 private FindDialog mFindDialog;
3769 // Used to prevent chording to result in firing two shortcuts immediately
3770 // one after another. Fixes bug 1211714.
3773 private boolean mInLoad;
3774 private boolean mIsNetworkUp;
3775 private boolean mDidStopLoad;
3777 /* package */ boolean mActivityInPause = true;
3779 private boolean mMenuIsDown;
3781 private static boolean mInTrace;
3783 // Performance probe
3784 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3785 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3786 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3787 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3788 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3789 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3790 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3791 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3792 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3795 private long mStart;
3796 private long mProcessStart;
3797 private long mUserStart;
3798 private long mSystemStart;
3799 private long mIdleStart;
3800 private long mIrqStart;
3802 private long mUiStart;
3804 private Drawable mMixLockIcon;
3805 private Drawable mSecLockIcon;
3807 /* hold a ref so we can auto-cancel if necessary */
3808 private AlertDialog mAlertDialog;
3810 // The up-to-date URL and title (these can be different from those stored
3811 // in WebView, since it takes some time for the information in WebView to
3813 private String mUrl;
3814 private String mTitle;
3816 // As PageInfo has different style for landscape / portrait, we have
3817 // to re-open it when configuration changed
3818 private AlertDialog mPageInfoDialog;
3819 private Tab mPageInfoView;
3820 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3821 // dialog, we should not just dismiss it, but should get back to the
3822 // SSL-certificate-on-error dialog. This flag is used to store this state
3823 private boolean mPageInfoFromShowSSLCertificateOnError;
3825 // as SSLCertificateOnError has different style for landscape / portrait,
3826 // we have to re-open it when configuration changed
3827 private AlertDialog mSSLCertificateOnErrorDialog;
3828 private WebView mSSLCertificateOnErrorView;
3829 private SslErrorHandler mSSLCertificateOnErrorHandler;
3830 private SslError mSSLCertificateOnErrorError;
3832 // as SSLCertificate has different style for landscape / portrait, we
3833 // have to re-open it when configuration changed
3834 private AlertDialog mSSLCertificateDialog;
3835 private Tab mSSLCertificateView;
3837 // as HttpAuthentication has different style for landscape / portrait, we
3838 // have to re-open it when configuration changed
3839 private AlertDialog mHttpAuthenticationDialog;
3840 private HttpAuthHandler mHttpAuthHandler;
3842 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3843 new FrameLayout.LayoutParams(
3844 ViewGroup.LayoutParams.MATCH_PARENT,
3845 ViewGroup.LayoutParams.MATCH_PARENT);
3846 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3847 new FrameLayout.LayoutParams(
3848 ViewGroup.LayoutParams.MATCH_PARENT,
3849 ViewGroup.LayoutParams.MATCH_PARENT,
3852 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3854 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3855 // Dictionary search
3856 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3857 // Google Mobile Local search
3858 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3860 final static String QUERY_PLACE_HOLDER = "%s";
3862 // "source" parameter for Google search through search key
3863 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3864 // "source" parameter for Google search through goto menu
3865 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3866 // "source" parameter for Google search through simplily type
3867 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3868 // "source" parameter for Google search suggested by the browser
3869 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3870 // "source" parameter for Google search from unknown source
3871 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3873 private final static String LOGTAG = "browser";
3875 private String mLastEnteredUrl;
3877 private PowerManager.WakeLock mWakeLock;
3878 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3880 private Toast mStopToast;
3882 private TitleBar mTitleBar;
3884 private LinearLayout mErrorConsoleContainer = null;
3885 private boolean mShouldShowErrorConsole = false;
3887 // As the ids are dynamically created, we can't guarantee that they will
3888 // be in sequence, so this static array maps ids to a window number.
3889 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3890 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3891 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3892 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3894 // monitor platform changes
3895 private IntentFilter mNetworkStateChangedFilter;
3896 private BroadcastReceiver mNetworkStateIntentReceiver;
3898 private BroadcastReceiver mPackageInstallationReceiver;
3900 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3902 // activity requestCode
3903 final static int COMBO_PAGE = 1;
3904 final static int DOWNLOAD_PAGE = 2;
3905 final static int PREFERENCES_PAGE = 3;
3906 final static int FILE_SELECTED = 4;
3908 // the default <video> poster
3909 private Bitmap mDefaultVideoPoster;
3910 // the video progress view
3911 private View mVideoProgressView;
3913 // The Google packages we monitor for the navigator.isApplicationInstalled()
3914 // API. Add as needed.
3915 private static Set<String> sGoogleApps;
3917 sGoogleApps = new HashSet<String>();
3918 sGoogleApps.add("com.google.android.youtube");
3922 * A UrlData class to abstract how the content will be set to WebView.
3923 * This base class uses loadUrl to show the content.
3925 /* package */ static class UrlData {
3927 final Map<String, String> mHeaders;
3928 final Intent mVoiceIntent;
3930 UrlData(String url) {
3932 this.mHeaders = null;
3933 this.mVoiceIntent = null;
3936 UrlData(String url, Map<String, String> headers, Intent intent) {
3938 this.mHeaders = headers;
3939 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3940 .equals(intent.getAction())) {
3941 this.mVoiceIntent = intent;
3943 this.mVoiceIntent = null;
3948 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
3952 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3953 * the title bar as well.
3955 public void loadIn(Tab t) {
3956 if (mVoiceIntent != null) {
3957 t.activateVoiceSearchMode(mVoiceIntent);
3959 t.getWebView().loadUrl(mUrl, mHeaders);
3964 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);