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) || activateVoiceSearch)
464 && !getPackageName().equals(appId)
465 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
466 Tab appTab = mTabControl.getTabFromId(appId);
467 if (appTab != null) {
468 Log.i(LOGTAG, "Reusing tab for " + appId);
469 // Dismiss the subwindow if applicable.
470 dismissSubWindow(appTab);
471 // Since we might kill the WebView, remove it from the
472 // content view first.
473 removeTabFromContentView(appTab);
474 // Recreate the main WebView after destroying the old one.
475 // If the WebView has the same original url and is on that
476 // page, it can be reused.
478 mTabControl.recreateWebView(appTab, urlData);
480 if (current != appTab) {
481 switchToTab(mTabControl.getTabIndex(appTab));
483 loadUrlDataIn(appTab, urlData);
486 // If the tab was the current tab, we have to attach
487 // it to the view system again.
488 attachTabToContentView(appTab);
490 loadUrlDataIn(appTab, urlData);
495 // No matching application tab, try to find a regular tab
496 // with a matching url.
497 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
498 if (appTab != null) {
499 if (current != appTab) {
500 switchToTab(mTabControl.getTabIndex(appTab));
502 // Otherwise, we are already viewing the correct tab.
504 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
505 // will be opened in a new tab unless we have reached
506 // MAX_TABS. Then the url will be opened in the current
507 // tab. If a new tab is created, it will have "true" for
509 openTabAndShow(urlData, true, appId);
513 if (!urlData.isEmpty()
514 && urlData.mUrl.startsWith("about:debug")) {
515 if ("about:debug.dom".equals(urlData.mUrl)) {
516 current.getWebView().dumpDomTree(false);
517 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
518 current.getWebView().dumpDomTree(true);
519 } else if ("about:debug.render".equals(urlData.mUrl)) {
520 current.getWebView().dumpRenderTree(false);
521 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
522 current.getWebView().dumpRenderTree(true);
523 } else if ("about:debug.display".equals(urlData.mUrl)) {
524 current.getWebView().dumpDisplayTree();
525 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
526 int index = urlData.mUrl.codePointAt(16) - '0';
527 if (index <= 0 || index > 9) {
528 current.getWebView().setDragTracker(null);
530 current.getWebView().setDragTracker(new MeshTracker(index));
533 mSettings.toggleDebugSettings();
537 // Get rid of the subwindow if it exists
538 dismissSubWindow(current);
539 loadUrlDataIn(current, urlData);
544 private int parseUrlShortcut(String url) {
545 if (url == null) return SHORTCUT_INVALID;
547 // FIXME: quick search, need to be customized by setting
548 if (url.length() > 2 && url.charAt(1) == ' ') {
549 switch (url.charAt(0)) {
550 case 'g': return SHORTCUT_GOOGLE_SEARCH;
551 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
552 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
553 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
556 return SHORTCUT_INVALID;
560 * Launches the default web search activity with the query parameters if the given intent's data
561 * are identified as plain search terms and not URLs/shortcuts.
562 * @return true if the intent was handled and web search activity was launched, false if not.
564 private boolean handleWebSearchIntent(Intent intent) {
565 if (intent == null) return false;
568 final String action = intent.getAction();
569 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS.equals(
573 if (Intent.ACTION_VIEW.equals(action)) {
574 Uri data = intent.getData();
575 if (data != null) url = data.toString();
576 } else if (Intent.ACTION_SEARCH.equals(action)
577 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
578 || Intent.ACTION_WEB_SEARCH.equals(action)) {
579 url = intent.getStringExtra(SearchManager.QUERY);
581 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
582 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
586 * Launches the default web search activity with the query parameters if the given url string
587 * was identified as plain search terms and not URL/shortcut.
588 * @return true if the request was handled and web search activity was launched, false if not.
590 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
591 if (inUrl == null) return false;
593 // In general, we shouldn't modify URL from Intent.
594 // But currently, we get the user-typed URL from search box as well.
595 String url = fixUrl(inUrl).trim();
597 // URLs and site specific search shortcuts are handled by the regular flow of control, so
599 if (Patterns.WEB_URL.matcher(url).matches()
600 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
601 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
605 final ContentResolver cr = mResolver;
606 final String newUrl = url;
607 new AsyncTask<Void, Void, Void>() {
608 protected Void doInBackground(Void... unused) {
609 Browser.updateVisitedHistory(cr, newUrl, false);
610 Browser.addSearchUrl(cr, newUrl);
615 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
616 intent.addCategory(Intent.CATEGORY_DEFAULT);
617 intent.putExtra(SearchManager.QUERY, url);
618 if (appData != null) {
619 intent.putExtra(SearchManager.APP_DATA, appData);
621 if (extraData != null) {
622 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
624 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
625 startActivity(intent);
630 private UrlData getUrlDataFromIntent(Intent intent) {
632 Map<String, String> headers = null;
633 if (intent != null) {
634 final String action = intent.getAction();
635 if (Intent.ACTION_VIEW.equals(action)) {
636 url = smartUrlFilter(intent.getData());
637 if (url != null && url.startsWith("content:")) {
638 /* Append mimetype so webview knows how to display */
639 String mimeType = intent.resolveType(getContentResolver());
640 if (mimeType != null) {
641 url += "?" + mimeType;
644 if (url != null && url.startsWith("http")) {
645 final Bundle pairs = intent
646 .getBundleExtra(Browser.EXTRA_HEADERS);
647 if (pairs != null && !pairs.isEmpty()) {
648 Iterator<String> iter = pairs.keySet().iterator();
649 headers = new HashMap<String, String>();
650 while (iter.hasNext()) {
651 String key = iter.next();
652 headers.put(key, pairs.getString(key));
656 } else if (Intent.ACTION_SEARCH.equals(action)
657 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
658 || Intent.ACTION_WEB_SEARCH.equals(action)) {
659 url = intent.getStringExtra(SearchManager.QUERY);
661 mLastEnteredUrl = url;
662 // In general, we shouldn't modify URL from Intent.
663 // But currently, we get the user-typed URL from search box as well.
665 url = smartUrlFilter(url);
666 final ContentResolver cr = mResolver;
667 final String newUrl = url;
668 new AsyncTask<Void, Void, Void>() {
669 protected Void doInBackground(Void... unused) {
670 Browser.updateVisitedHistory(cr, newUrl, false);
674 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
675 if (url.contains(searchSource)) {
676 String source = null;
677 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
678 if (appData != null) {
679 source = appData.getString(Search.SOURCE);
681 if (TextUtils.isEmpty(source)) {
682 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
684 url = url.replace(searchSource, "&source=android-"+source+"&");
689 return new UrlData(url, headers, intent);
691 /* package */ void showVoiceTitleBar(String title) {
692 mTitleBar.setInVoiceMode(true);
693 mFakeTitleBar.setInVoiceMode(true);
695 mTitleBar.setDisplayTitle(title);
696 mFakeTitleBar.setDisplayTitle(title);
698 /* package */ void revertVoiceTitleBar() {
699 mTitleBar.setInVoiceMode(false);
700 mFakeTitleBar.setInVoiceMode(false);
702 mTitleBar.setDisplayTitle(mUrl);
703 mFakeTitleBar.setDisplayTitle(mUrl);
705 /* package */ static String fixUrl(String inUrl) {
706 // FIXME: Converting the url to lower case
707 // duplicates functionality in smartUrlFilter().
708 // However, changing all current callers of fixUrl to
709 // call smartUrlFilter in addition may have unwanted
710 // consequences, and is deferred for now.
711 int colon = inUrl.indexOf(':');
712 boolean allLower = true;
713 for (int index = 0; index < colon; index++) {
714 char ch = inUrl.charAt(index);
715 if (!Character.isLetter(ch)) {
718 allLower &= Character.isLowerCase(ch);
719 if (index == colon - 1 && !allLower) {
720 inUrl = inUrl.substring(0, colon).toLowerCase()
721 + inUrl.substring(colon);
724 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
726 if (inUrl.startsWith("http:") ||
727 inUrl.startsWith("https:")) {
728 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
729 inUrl = inUrl.replaceFirst("/", "//");
730 } else inUrl = inUrl.replaceFirst(":", "://");
736 protected void onResume() {
739 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
742 if (!mActivityInPause) {
743 Log.e(LOGTAG, "BrowserActivity is already resumed.");
747 mTabControl.resumeCurrentTab();
748 mActivityInPause = false;
749 resumeWebViewTimers();
751 if (mWakeLock.isHeld()) {
752 mHandler.removeMessages(RELEASE_WAKELOCK);
756 registerReceiver(mNetworkStateIntentReceiver,
757 mNetworkStateChangedFilter);
758 WebView.enablePlatformNotifications();
762 * Since the actual title bar is embedded in the WebView, and removing it
763 * would change its appearance, use a different TitleBar to show overlayed
764 * at the top of the screen, when the menu is open or the page is loading.
766 private TitleBar mFakeTitleBar;
769 * Keeps track of whether the options menu is open. This is important in
770 * determining whether to show or hide the title bar overlay.
772 private boolean mOptionsMenuOpen;
775 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
776 * of whether the configuration has changed. The first onMenuOpened call
777 * after a configuration change is simply a reopening of the same menu
778 * (i.e. mIconView did not change).
780 private boolean mConfigChanged;
783 * Whether or not the options menu is in its smaller, icon menu form. When
784 * true, we want the title bar overlay to be up. When false, we do not.
785 * Only meaningful if mOptionsMenuOpen is true.
787 private boolean mIconView;
790 public boolean onMenuOpened(int featureId, Menu menu) {
791 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
792 if (mOptionsMenuOpen) {
793 if (mConfigChanged) {
794 // We do not need to make any changes to the state of the
795 // title bar, since the only thing that happened was a
796 // change in orientation
797 mConfigChanged = false;
800 // Switching the menu to expanded view, so hide the
805 // Switching the menu back to icon view, so show the
806 // title bar once again.
812 // The options menu is closed, so open it, and show the title
814 mOptionsMenuOpen = true;
815 mConfigChanged = false;
822 private void showFakeTitleBar() {
823 final View decor = getWindow().peekDecorView();
824 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
825 && !mActivityInPause && decor != null
826 && decor.getWindowToken() != null) {
827 Rect visRect = new Rect();
828 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
830 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
835 WindowManager manager
836 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
838 // Add the title bar to the window manager so it can receive touches
839 // while the menu is up
840 WindowManager.LayoutParams params
841 = new WindowManager.LayoutParams(
842 ViewGroup.LayoutParams.MATCH_PARENT,
843 ViewGroup.LayoutParams.WRAP_CONTENT,
844 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
845 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
846 PixelFormat.TRANSLUCENT);
847 params.gravity = Gravity.TOP;
848 WebView mainView = mTabControl.getCurrentWebView();
849 boolean atTop = mainView != null && mainView.getScrollY() == 0;
850 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
851 // XXX : Without providing an offset, the fake title bar will be
852 // placed underneath the status bar. Use the global visible rect
853 // of mBrowserFrameLayout to determine the bottom of the status bar
854 params.y = visRect.top;
855 manager.addView(mFakeTitleBar, params);
860 public void onOptionsMenuClosed(Menu menu) {
861 mOptionsMenuOpen = false;
864 } else if (!mIconView) {
865 // The page is currently loading, and we are in expanded mode, so
866 // we were not showing the menu. Show it once again. It will be
867 // removed when the page finishes.
872 private void hideFakeTitleBar() {
873 if (mFakeTitleBar.getParent() == null) return;
874 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
875 mFakeTitleBar.getLayoutParams();
876 WebView mainView = mTabControl.getCurrentWebView();
877 // Although we decided whether or not to animate based on the current
878 // scroll position, the scroll position may have changed since the
879 // fake title bar was displayed. Make sure it has the appropriate
880 // animation/lack thereof before removing.
881 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
882 ? 0 : R.style.TitleBar;
883 WindowManager manager
884 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
885 manager.updateViewLayout(mFakeTitleBar, params);
886 manager.removeView(mFakeTitleBar);
890 * Special method for the fake title bar to call when displaying its context
891 * menu, since it is in its own Window, and its parent does not show a
894 /* package */ void showTitleBarContextMenu() {
895 if (null == mTitleBar.getParent()) {
898 openContextMenu(mTitleBar);
902 public void onContextMenuClosed(Menu menu) {
903 super.onContextMenuClosed(menu);
910 * onSaveInstanceState(Bundle map)
911 * onSaveInstanceState is called right before onStop(). The map contains
915 protected void onSaveInstanceState(Bundle outState) {
917 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
919 // the default implementation requires each view to have an id. As the
920 // browser handles the state itself and it doesn't use id for the views,
921 // don't call the default implementation. Otherwise it will trigger the
922 // warning like this, "couldn't save which view has focus because the
923 // focused view XXX has no id".
926 mTabControl.saveState(outState);
930 protected void onPause() {
933 if (mActivityInPause) {
934 Log.e(LOGTAG, "BrowserActivity is already paused.");
938 mTabControl.pauseCurrentTab();
939 mActivityInPause = true;
940 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
942 mHandler.sendMessageDelayed(mHandler
943 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
946 // FIXME: This removes the active tabs page and resets the menu to
947 // MAIN_MENU. A better solution might be to do this work in onNewIntent
948 // but then we would need to save it in onSaveInstanceState and restore
949 // it in onCreate/onRestoreInstanceState
950 if (mActiveTabsPage != null) {
951 removeActiveTabPage(true);
956 // unregister network state listener
957 unregisterReceiver(mNetworkStateIntentReceiver);
958 WebView.disablePlatformNotifications();
962 protected void onDestroy() {
964 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
968 if (mUploadMessage != null) {
969 mUploadMessage.onReceiveValue(null);
970 mUploadMessage = null;
973 if (mTabControl == null) return;
975 // Remove the fake title bar if it is there
978 // Remove the current tab and sub window
979 Tab t = mTabControl.getCurrentTab();
982 removeTabFromContentView(t);
984 // Destroy all the tabs
985 mTabControl.destroy();
986 WebIconDatabase.getInstance().close();
988 unregisterReceiver(mPackageInstallationReceiver);
990 // Stop watching the default geolocation permissions
991 mSystemAllowGeolocationOrigins.stop();
992 mSystemAllowGeolocationOrigins = null;
996 public void onConfigurationChanged(Configuration newConfig) {
997 mConfigChanged = true;
998 super.onConfigurationChanged(newConfig);
1000 if (mPageInfoDialog != null) {
1001 mPageInfoDialog.dismiss();
1004 mPageInfoFromShowSSLCertificateOnError);
1006 if (mSSLCertificateDialog != null) {
1007 mSSLCertificateDialog.dismiss();
1009 mSSLCertificateView);
1011 if (mSSLCertificateOnErrorDialog != null) {
1012 mSSLCertificateOnErrorDialog.dismiss();
1013 showSSLCertificateOnError(
1014 mSSLCertificateOnErrorView,
1015 mSSLCertificateOnErrorHandler,
1016 mSSLCertificateOnErrorError);
1018 if (mHttpAuthenticationDialog != null) {
1019 String title = ((TextView) mHttpAuthenticationDialog
1020 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1022 String name = ((TextView) mHttpAuthenticationDialog
1023 .findViewById(R.id.username_edit)).getText().toString();
1024 String password = ((TextView) mHttpAuthenticationDialog
1025 .findViewById(R.id.password_edit)).getText().toString();
1026 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1028 mHttpAuthenticationDialog.dismiss();
1029 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1030 name, password, focusId);
1035 public void onLowMemory() {
1036 super.onLowMemory();
1037 mTabControl.freeMemory();
1040 private void resumeWebViewTimers() {
1041 Tab tab = mTabControl.getCurrentTab();
1042 if (tab == null) return; // monkey can trigger this
1043 boolean inLoad = tab.inLoad();
1044 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1045 CookieSyncManager.getInstance().startSync();
1046 WebView w = tab.getWebView();
1053 private boolean pauseWebViewTimers() {
1054 Tab tab = mTabControl.getCurrentTab();
1055 boolean inLoad = tab.inLoad();
1056 if (mActivityInPause && !inLoad) {
1057 CookieSyncManager.getInstance().stopSync();
1058 WebView w = mTabControl.getCurrentWebView();
1068 // Open the icon database and retain all the icons for visited sites.
1069 private void retainIconsOnStartup() {
1070 final WebIconDatabase db = WebIconDatabase.getInstance();
1071 db.open(getDir("icons", 0).getPath());
1074 c = Browser.getAllBookmarks(mResolver);
1075 if (c.moveToFirst()) {
1076 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1078 String url = c.getString(urlIndex);
1079 db.retainIconForPageUrl(url);
1080 } while (c.moveToNext());
1082 } catch (IllegalStateException e) {
1083 Log.e(LOGTAG, "retainIconsOnStartup", e);
1085 if (c!= null) c.close();
1089 // Helper method for getting the top window.
1090 WebView getTopWindow() {
1091 return mTabControl.getCurrentTopWebView();
1094 TabControl getTabControl() {
1099 public boolean onCreateOptionsMenu(Menu menu) {
1100 super.onCreateOptionsMenu(menu);
1102 MenuInflater inflater = getMenuInflater();
1103 inflater.inflate(R.menu.browser, menu);
1105 updateInLoadMenuItems();
1110 * As the menu can be open when loading state changes
1111 * we must manually update the state of the stop/reload menu
1114 private void updateInLoadMenuItems() {
1115 if (mMenu == null) {
1118 MenuItem src = mInLoad ?
1119 mMenu.findItem(R.id.stop_menu_id):
1120 mMenu.findItem(R.id.reload_menu_id);
1121 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1122 dest.setIcon(src.getIcon());
1123 dest.setTitle(src.getTitle());
1127 public boolean onContextItemSelected(MenuItem item) {
1128 // chording is not an issue with context menus, but we use the same
1129 // options selector, so set mCanChord to true so we can access them.
1131 int id = item.getItemId();
1132 boolean result = true;
1134 // For the context menu from the title bar
1135 case R.id.title_bar_copy_page_url:
1136 Tab currentTab = mTabControl.getCurrentTab();
1137 if (null == currentTab) {
1141 WebView mainView = currentTab.getWebView();
1142 if (null == mainView) {
1146 copy(mainView.getUrl());
1148 // -- Browser context menu
1149 case R.id.open_context_menu_id:
1150 case R.id.open_newtab_context_menu_id:
1151 case R.id.bookmark_context_menu_id:
1152 case R.id.save_link_context_menu_id:
1153 case R.id.share_link_context_menu_id:
1154 case R.id.copy_link_context_menu_id:
1155 final WebView webView = getTopWindow();
1156 if (null == webView) {
1160 final HashMap hrefMap = new HashMap();
1161 hrefMap.put("webview", webView);
1162 final Message msg = mHandler.obtainMessage(
1163 FOCUS_NODE_HREF, id, 0, hrefMap);
1164 webView.requestFocusNodeHref(msg);
1168 // For other context menus
1169 result = onOptionsItemSelected(item);
1175 private Bundle createGoogleSearchSourceBundle(String source) {
1176 Bundle bundle = new Bundle();
1177 bundle.putString(Search.SOURCE, source);
1181 /* package */ void editUrl() {
1182 if (mOptionsMenuOpen) closeOptionsMenu();
1183 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1184 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1189 * Overriding this to insert a local information bundle
1192 public void startSearch(String initialQuery, boolean selectInitialQuery,
1193 Bundle appSearchData, boolean globalSearch) {
1194 if (appSearchData == null) {
1195 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1197 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1201 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1202 * results in changing tabs.
1203 * @param index Index of the tab to change to, as defined by
1204 * mTabControl.getTabIndex(Tab t).
1205 * @return boolean True if we successfully switched to a different tab. If
1206 * the indexth tab is null, or if that tab is the same as
1207 * the current one, return false.
1209 /* package */ boolean switchToTab(int index) {
1210 Tab tab = mTabControl.getTab(index);
1211 Tab currentTab = mTabControl.getCurrentTab();
1212 if (tab == null || tab == currentTab) {
1215 if (currentTab != null) {
1216 // currentTab may be null if it was just removed. In that case,
1217 // we do not need to remove it
1218 removeTabFromContentView(currentTab);
1220 mTabControl.setCurrentTab(tab);
1221 attachTabToContentView(tab);
1222 resetTitleIconAndProgress();
1223 updateLockIconToLatest();
1227 /* package */ Tab openTabToHomePage() {
1228 return openTabAndShow(mSettings.getHomePage(), false, null);
1231 /* package */ void closeCurrentWindow() {
1232 final Tab current = mTabControl.getCurrentTab();
1233 if (mTabControl.getTabCount() == 1) {
1234 // This is the last tab. Open a new one, with the home
1235 // page and close the current one.
1236 openTabToHomePage();
1240 final Tab parent = current.getParentTab();
1241 int indexToShow = -1;
1242 if (parent != null) {
1243 indexToShow = mTabControl.getTabIndex(parent);
1245 final int currentIndex = mTabControl.getCurrentIndex();
1246 // Try to move to the tab to the right
1247 indexToShow = currentIndex + 1;
1248 if (indexToShow > mTabControl.getTabCount() - 1) {
1249 // Try to move to the tab to the left
1250 indexToShow = currentIndex - 1;
1253 if (switchToTab(indexToShow)) {
1259 private ActiveTabsPage mActiveTabsPage;
1262 * Remove the active tabs page.
1263 * @param needToAttach If true, the active tabs page did not attach a tab
1264 * to the content view, so we need to do that here.
1266 /* package */ void removeActiveTabPage(boolean needToAttach) {
1267 mContentView.removeView(mActiveTabsPage);
1268 mActiveTabsPage = null;
1269 mMenuState = R.id.MAIN_MENU;
1271 attachTabToContentView(mTabControl.getCurrentTab());
1273 getTopWindow().requestFocus();
1277 public boolean onOptionsItemSelected(MenuItem item) {
1279 // The user has already fired a shortcut with this hold down of the
1283 if (null == getTopWindow()) {
1287 // The shortcut action consumes the MENU. Even if it is still down,
1288 // it won't trigger the next shortcut action. In the case of the
1289 // shortcut action triggering a new activity, like Bookmarks, we
1290 // won't get onKeyUp for MENU. So it is important to reset it here.
1291 mMenuIsDown = false;
1293 switch (item.getItemId()) {
1295 case R.id.new_tab_menu_id:
1296 openTabToHomePage();
1299 case R.id.goto_menu_id:
1303 case R.id.bookmarks_menu_id:
1304 bookmarksOrHistoryPicker(false);
1307 case R.id.active_tabs_menu_id:
1308 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1309 removeTabFromContentView(mTabControl.getCurrentTab());
1311 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1312 mActiveTabsPage.requestFocus();
1313 mMenuState = EMPTY_MENU;
1316 case R.id.add_bookmark_menu_id:
1317 Intent i = new Intent(BrowserActivity.this,
1318 AddBookmarkPage.class);
1319 WebView w = getTopWindow();
1320 i.putExtra("url", w.getUrl());
1321 i.putExtra("title", w.getTitle());
1322 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1323 i.putExtra("thumbnail", createScreenshot(w));
1327 case R.id.stop_reload_menu_id:
1331 getTopWindow().reload();
1335 case R.id.back_menu_id:
1336 getTopWindow().goBack();
1339 case R.id.forward_menu_id:
1340 getTopWindow().goForward();
1343 case R.id.close_menu_id:
1344 // Close the subwindow if it exists.
1345 if (mTabControl.getCurrentSubWindow() != null) {
1346 dismissSubWindow(mTabControl.getCurrentTab());
1349 closeCurrentWindow();
1352 case R.id.homepage_menu_id:
1353 Tab current = mTabControl.getCurrentTab();
1354 if (current != null) {
1355 dismissSubWindow(current);
1356 loadUrl(current.getWebView(), mSettings.getHomePage());
1360 case R.id.preferences_menu_id:
1361 Intent intent = new Intent(this,
1362 BrowserPreferencesPage.class);
1363 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1364 getTopWindow().getUrl());
1365 startActivityForResult(intent, PREFERENCES_PAGE);
1368 case R.id.find_menu_id:
1369 if (null == mFindDialog) {
1370 mFindDialog = new FindDialog(this);
1372 mFindDialog.setWebView(getTopWindow());
1374 getTopWindow().setFindIsUp(true);
1375 mMenuState = EMPTY_MENU;
1378 case R.id.select_text_id:
1379 getTopWindow().emulateShiftHeld();
1381 case R.id.page_info_menu_id:
1382 showPageInfo(mTabControl.getCurrentTab(), false);
1385 case R.id.classic_history_menu_id:
1386 bookmarksOrHistoryPicker(true);
1389 case R.id.title_bar_share_page_url:
1390 case R.id.share_page_menu_id:
1391 Tab currentTab = mTabControl.getCurrentTab();
1392 if (null == currentTab) {
1396 currentTab.populatePickerData();
1397 sharePage(this, currentTab.getTitle(),
1398 currentTab.getUrl(), currentTab.getFavicon(),
1399 createScreenshot(currentTab.getWebView()));
1402 case R.id.dump_nav_menu_id:
1403 getTopWindow().debugDump();
1406 case R.id.dump_counters_menu_id:
1407 getTopWindow().dumpV8Counters();
1410 case R.id.zoom_in_menu_id:
1411 getTopWindow().zoomIn();
1414 case R.id.zoom_out_menu_id:
1415 getTopWindow().zoomOut();
1418 case R.id.view_downloads_menu_id:
1419 viewDownloads(null);
1422 case R.id.window_one_menu_id:
1423 case R.id.window_two_menu_id:
1424 case R.id.window_three_menu_id:
1425 case R.id.window_four_menu_id:
1426 case R.id.window_five_menu_id:
1427 case R.id.window_six_menu_id:
1428 case R.id.window_seven_menu_id:
1429 case R.id.window_eight_menu_id:
1431 int menuid = item.getItemId();
1432 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1433 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1434 Tab desiredTab = mTabControl.getTab(id);
1435 if (desiredTab != null &&
1436 desiredTab != mTabControl.getCurrentTab()) {
1446 if (!super.onOptionsItemSelected(item)) {
1449 // Otherwise fall through.
1455 public void closeFind() {
1456 mMenuState = R.id.MAIN_MENU;
1460 public boolean onPrepareOptionsMenu(Menu menu) {
1461 // This happens when the user begins to hold down the menu key, so
1462 // allow them to chord to get a shortcut.
1464 // Note: setVisible will decide whether an item is visible; while
1465 // setEnabled() will decide whether an item is enabled, which also means
1466 // whether the matching shortcut key will function.
1467 super.onPrepareOptionsMenu(menu);
1468 switch (mMenuState) {
1470 if (mCurrentMenuState != mMenuState) {
1471 menu.setGroupVisible(R.id.MAIN_MENU, false);
1472 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1473 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1477 if (mCurrentMenuState != mMenuState) {
1478 menu.setGroupVisible(R.id.MAIN_MENU, true);
1479 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1480 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1482 final WebView w = getTopWindow();
1483 boolean canGoBack = false;
1484 boolean canGoForward = false;
1485 boolean isHome = false;
1487 canGoBack = w.canGoBack();
1488 canGoForward = w.canGoForward();
1489 isHome = mSettings.getHomePage().equals(w.getUrl());
1491 final MenuItem back = menu.findItem(R.id.back_menu_id);
1492 back.setEnabled(canGoBack);
1494 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1495 home.setEnabled(!isHome);
1497 menu.findItem(R.id.forward_menu_id)
1498 .setEnabled(canGoForward);
1500 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1501 mTabControl.canCreateNewTab());
1503 // decide whether to show the share link option
1504 PackageManager pm = getPackageManager();
1505 Intent send = new Intent(Intent.ACTION_SEND);
1506 send.setType("text/plain");
1507 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1508 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1510 boolean isNavDump = mSettings.isNavDump();
1511 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1512 nav.setVisible(isNavDump);
1513 nav.setEnabled(isNavDump);
1515 boolean showDebugSettings = mSettings.showDebugSettings();
1516 final MenuItem counter = menu.findItem(R.id.dump_counters_menu_id);
1517 counter.setVisible(showDebugSettings);
1518 counter.setEnabled(showDebugSettings);
1522 mCurrentMenuState = mMenuState;
1527 public void onCreateContextMenu(ContextMenu menu, View v,
1528 ContextMenuInfo menuInfo) {
1529 if (v instanceof TitleBar) {
1532 WebView webview = (WebView) v;
1533 WebView.HitTestResult result = webview.getHitTestResult();
1534 if (result == null) {
1538 int type = result.getType();
1539 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1541 "We should not show context menu when nothing is touched");
1544 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1545 // let TextView handles context menu
1549 // Note, http://b/issue?id=1106666 is requesting that
1550 // an inflated menu can be used again. This is not available
1551 // yet, so inflate each time (yuk!)
1552 MenuInflater inflater = getMenuInflater();
1553 inflater.inflate(R.menu.browsercontext, menu);
1555 // Show the correct menu group
1556 String extra = result.getExtra();
1557 menu.setGroupVisible(R.id.PHONE_MENU,
1558 type == WebView.HitTestResult.PHONE_TYPE);
1559 menu.setGroupVisible(R.id.EMAIL_MENU,
1560 type == WebView.HitTestResult.EMAIL_TYPE);
1561 menu.setGroupVisible(R.id.GEO_MENU,
1562 type == WebView.HitTestResult.GEO_TYPE);
1563 menu.setGroupVisible(R.id.IMAGE_MENU,
1564 type == WebView.HitTestResult.IMAGE_TYPE
1565 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1566 menu.setGroupVisible(R.id.ANCHOR_MENU,
1567 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1568 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1570 // Setup custom handling depending on the type
1572 case WebView.HitTestResult.PHONE_TYPE:
1573 menu.setHeaderTitle(Uri.decode(extra));
1574 menu.findItem(R.id.dial_context_menu_id).setIntent(
1575 new Intent(Intent.ACTION_VIEW, Uri
1576 .parse(WebView.SCHEME_TEL + extra)));
1577 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1578 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1579 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1580 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1582 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1586 case WebView.HitTestResult.EMAIL_TYPE:
1587 menu.setHeaderTitle(extra);
1588 menu.findItem(R.id.email_context_menu_id).setIntent(
1589 new Intent(Intent.ACTION_VIEW, Uri
1590 .parse(WebView.SCHEME_MAILTO + extra)));
1591 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1595 case WebView.HitTestResult.GEO_TYPE:
1596 menu.setHeaderTitle(extra);
1597 menu.findItem(R.id.map_context_menu_id).setIntent(
1598 new Intent(Intent.ACTION_VIEW, Uri
1599 .parse(WebView.SCHEME_GEO
1600 + URLEncoder.encode(extra))));
1601 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1605 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1606 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1607 TextView titleView = (TextView) LayoutInflater.from(this)
1608 .inflate(android.R.layout.browser_link_context_header,
1610 titleView.setText(extra);
1611 menu.setHeaderView(titleView);
1612 // decide whether to show the open link in new tab option
1613 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1614 mTabControl.canCreateNewTab());
1615 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1616 Bookmarks.urlHasAcceptableScheme(extra));
1617 PackageManager pm = getPackageManager();
1618 Intent send = new Intent(Intent.ACTION_SEND);
1619 send.setType("text/plain");
1620 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1621 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1622 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1625 // otherwise fall through to handle image part
1626 case WebView.HitTestResult.IMAGE_TYPE:
1627 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1628 menu.setHeaderTitle(extra);
1630 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1631 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1632 menu.findItem(R.id.download_context_menu_id).
1633 setOnMenuItemClickListener(new Download(extra));
1634 menu.findItem(R.id.set_wallpaper_context_menu_id).
1635 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1639 Log.w(LOGTAG, "We should not get here.");
1645 // Attach the given tab to the content view.
1646 // this should only be called for the current tab.
1647 private void attachTabToContentView(Tab t) {
1648 // Attach the container that contains the main WebView and any other UI
1649 // associated with the tab.
1650 t.attachTabToContentView(mContentView);
1652 if (mShouldShowErrorConsole) {
1653 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1654 if (errorConsole.numberOfErrors() == 0) {
1655 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1657 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1660 mErrorConsoleContainer.addView(errorConsole,
1661 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1662 ViewGroup.LayoutParams.WRAP_CONTENT));
1665 WebView view = t.getWebView();
1666 view.setEmbeddedTitleBar(mTitleBar);
1667 if (t.isInVoiceSearchMode()) {
1668 showVoiceTitleBar(t.getVoiceDisplayTitle());
1670 revertVoiceTitleBar();
1672 // Request focus on the top window.
1673 t.getTopWindow().requestFocus();
1676 // Attach a sub window to the main WebView of the given tab.
1677 void attachSubWindow(Tab t) {
1678 t.attachSubWindow(mContentView);
1679 getTopWindow().requestFocus();
1682 // Remove the given tab from the content view.
1683 private void removeTabFromContentView(Tab t) {
1684 // Remove the container that contains the main WebView.
1685 t.removeTabFromContentView(mContentView);
1687 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1688 if (errorConsole != null) {
1689 mErrorConsoleContainer.removeView(errorConsole);
1692 WebView view = t.getWebView();
1694 view.setEmbeddedTitleBar(null);
1698 // Remove the sub window if it exists. Also called by TabControl when the
1699 // user clicks the 'X' to dismiss a sub window.
1700 /* package */ void dismissSubWindow(Tab t) {
1701 t.removeSubWindow(mContentView);
1702 // dismiss the subwindow. This will destroy the WebView.
1703 t.dismissSubWindow();
1704 getTopWindow().requestFocus();
1707 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1708 // that accepts url as string.
1709 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1710 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1713 // This method does a ton of stuff. It will attempt to create a new tab
1714 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1715 // url isn't null, it will load the given url.
1716 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1718 final Tab currentTab = mTabControl.getCurrentTab();
1719 if (mTabControl.canCreateNewTab()) {
1720 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1722 WebView webview = tab.getWebView();
1723 // If the last tab was removed from the active tabs page, currentTab
1725 if (currentTab != null) {
1726 removeTabFromContentView(currentTab);
1728 // We must set the new tab as the current tab to reflect the old
1729 // animation behavior.
1730 mTabControl.setCurrentTab(tab);
1731 attachTabToContentView(tab);
1732 if (!urlData.isEmpty()) {
1733 loadUrlDataIn(tab, urlData);
1737 // Get rid of the subwindow if it exists
1738 dismissSubWindow(currentTab);
1739 if (!urlData.isEmpty()) {
1740 // Load the given url.
1741 loadUrlDataIn(currentTab, urlData);
1747 private Tab openTab(String url) {
1748 if (mSettings.openInBackground()) {
1749 Tab t = mTabControl.createNewTab();
1751 WebView view = t.getWebView();
1756 return openTabAndShow(url, false, null);
1760 private class Copy implements OnMenuItemClickListener {
1761 private CharSequence mText;
1763 public boolean onMenuItemClick(MenuItem item) {
1768 public Copy(CharSequence toCopy) {
1773 private class Download implements OnMenuItemClickListener {
1774 private String mText;
1776 public boolean onMenuItemClick(MenuItem item) {
1777 onDownloadStartNoStream(mText, null, null, null, -1);
1781 public Download(String toDownload) {
1786 private class SetAsWallpaper extends Thread implements
1787 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1789 private ProgressDialog mWallpaperProgress;
1790 private boolean mCanceled = false;
1792 public SetAsWallpaper(String url) {
1794 mUrl = new URL(url);
1795 } catch (MalformedURLException e) {
1800 public void onCancel(DialogInterface dialog) {
1804 public boolean onMenuItemClick(MenuItem item) {
1806 // The user may have tried to set a image with a large file size as their
1807 // background so it may take a few moments to perform the operation. Display
1808 // a progress spinner while it is working.
1809 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1810 mWallpaperProgress.setIndeterminate(true);
1811 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1812 mWallpaperProgress.setCancelable(true);
1813 mWallpaperProgress.setOnCancelListener(this);
1814 mWallpaperProgress.show();
1821 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1823 // TODO: This will cause the resource to be downloaded again, when we
1824 // should in most cases be able to grab it from the cache. To fix this
1825 // we should query WebCore to see if we can access a cached version and
1826 // instead open an input stream on that. This pattern could also be used
1827 // in the download manager where the same problem exists.
1828 InputStream inputstream = mUrl.openStream();
1829 if (inputstream != null) {
1830 setWallpaper(inputstream);
1832 } catch (IOException e) {
1833 Log.e(LOGTAG, "Unable to set new wallpaper");
1834 // Act as though the user canceled the operation so we try to
1835 // restore the old wallpaper.
1840 // Restore the old wallpaper if the user cancelled whilst we were setting
1841 // the new wallpaper.
1842 int width = oldWallpaper.getIntrinsicWidth();
1843 int height = oldWallpaper.getIntrinsicHeight();
1844 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1845 Canvas canvas = new Canvas(bm);
1846 oldWallpaper.setBounds(0, 0, width, height);
1847 oldWallpaper.draw(canvas);
1850 } catch (IOException e) {
1851 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1856 if (mWallpaperProgress.isShowing()) {
1857 mWallpaperProgress.dismiss();
1862 private void copy(CharSequence text) {
1864 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1866 clip.setClipboardText(text);
1868 } catch (android.os.RemoteException e) {
1869 Log.e(LOGTAG, "Copy failed", e);
1874 * Resets the browser title-view to whatever it must be
1875 * (for example, if we had a loading error)
1876 * When we have a new page, we call resetTitle, when we
1877 * have to reset the titlebar to whatever it used to be
1878 * (for example, if the user chose to stop loading), we
1879 * call resetTitleAndRevertLockIcon.
1881 /* package */ void resetTitleAndRevertLockIcon() {
1882 mTabControl.getCurrentTab().revertLockIcon();
1883 updateLockIconToLatest();
1884 resetTitleIconAndProgress();
1888 * Reset the title, favicon, and progress.
1890 private void resetTitleIconAndProgress() {
1891 WebView current = mTabControl.getCurrentWebView();
1892 if (current == null) {
1895 resetTitleAndIcon(current);
1896 int progress = current.getProgress();
1897 current.getWebChromeClient().onProgressChanged(current, progress);
1900 // Reset the title and the icon based on the given item.
1901 private void resetTitleAndIcon(WebView view) {
1902 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1904 setUrlTitle(item.getUrl(), item.getTitle());
1905 setFavicon(item.getFavicon());
1907 setUrlTitle(null, null);
1913 * Sets a title composed of the URL and the title string.
1914 * @param url The URL of the site being loaded.
1915 * @param title The title of the site being loaded.
1917 void setUrlTitle(String url, String title) {
1921 // If we are in voice search mode, the title has already been set.
1922 if (mTabControl.getCurrentTab().isInVoiceSearchMode()) return;
1923 mTitleBar.setDisplayTitle(url);
1924 mFakeTitleBar.setDisplayTitle(url);
1928 * @param url The URL to build a title version of the URL from.
1929 * @return The title version of the URL or null if fails.
1930 * The title version of the URL can be either the URL hostname,
1931 * or the hostname with an "https://" prefix (for secure URLs),
1932 * or an empty string if, for example, the URL in question is a
1933 * file:// URL with no hostname.
1935 /* package */ static String buildTitleUrl(String url) {
1936 String titleUrl = null;
1940 // parse the url string
1941 URL urlObj = new URL(url);
1942 if (urlObj != null) {
1945 String protocol = urlObj.getProtocol();
1946 String host = urlObj.getHost();
1948 if (host != null && 0 < host.length()) {
1950 if (protocol != null) {
1951 // if a secure site, add an "https://" prefix!
1952 if (protocol.equalsIgnoreCase("https")) {
1953 titleUrl = protocol + "://" + host;
1958 } catch (MalformedURLException e) {}
1964 // Set the favicon in the title bar.
1965 void setFavicon(Bitmap icon) {
1966 mTitleBar.setFavicon(icon);
1967 mFakeTitleBar.setFavicon(icon);
1971 * Close the tab, remove its associated title bar, and adjust mTabControl's
1972 * current tab to a valid value.
1974 /* package */ void closeTab(Tab t) {
1975 int currentIndex = mTabControl.getCurrentIndex();
1976 int removeIndex = mTabControl.getTabIndex(t);
1977 mTabControl.removeTab(t);
1978 if (currentIndex >= removeIndex && currentIndex != 0) {
1981 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
1982 resetTitleIconAndProgress();
1985 /* package */ void goBackOnePageOrQuit() {
1986 Tab current = mTabControl.getCurrentTab();
1987 if (current == null) {
1989 * Instead of finishing the activity, simply push this to the back
1990 * of the stack and let ActivityManager to choose the foreground
1991 * activity. As BrowserActivity is singleTask, it will be always the
1992 * root of the task. So we can use either true or false for
1995 moveTaskToBack(true);
1998 WebView w = current.getWebView();
1999 if (w.canGoBack()) {
2002 // Check to see if we are closing a window that was created by
2003 // another window. If so, we switch back to that window.
2004 Tab parent = current.getParentTab();
2005 if (parent != null) {
2006 switchToTab(mTabControl.getTabIndex(parent));
2007 // Now we close the other tab
2010 if (current.closeOnExit()) {
2011 // force the tab's inLoad() to be false as we are going to
2012 // either finish the activity or remove the tab. This will
2013 // ensure pauseWebViewTimers() taking action.
2014 mTabControl.getCurrentTab().clearInLoad();
2015 if (mTabControl.getTabCount() == 1) {
2019 // call pauseWebViewTimers() now, we won't be able to call
2020 // it in onPause() as the WebView won't be valid.
2021 // Temporarily change mActivityInPause to be true as
2022 // pauseWebViewTimers() will do nothing if mActivityInPause
2024 boolean savedState = mActivityInPause;
2026 Log.e(LOGTAG, "BrowserActivity is already paused "
2027 + "while handing goBackOnePageOrQuit.");
2029 mActivityInPause = true;
2030 pauseWebViewTimers();
2031 mActivityInPause = savedState;
2032 removeTabFromContentView(current);
2033 mTabControl.removeTab(current);
2036 * Instead of finishing the activity, simply push this to the back
2037 * of the stack and let ActivityManager to choose the foreground
2038 * activity. As BrowserActivity is singleTask, it will be always the
2039 * root of the task. So we can use either true or false for
2042 moveTaskToBack(true);
2047 boolean isMenuDown() {
2052 public boolean onKeyDown(int keyCode, KeyEvent event) {
2053 // Even if MENU is already held down, we need to call to super to open
2054 // the IME on long press.
2055 if (KeyEvent.KEYCODE_MENU == keyCode) {
2057 return super.onKeyDown(keyCode, event);
2059 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2060 // still down, we don't want to trigger the search. Pretend to consume
2061 // the key and do nothing.
2062 if (mMenuIsDown) return true;
2065 case KeyEvent.KEYCODE_SPACE:
2066 // WebView/WebTextView handle the keys in the KeyDown. As
2067 // the Activity's shortcut keys are only handled when WebView
2068 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2069 if (event.isShiftPressed()) {
2070 getTopWindow().pageUp(false);
2072 getTopWindow().pageDown(false);
2075 case KeyEvent.KEYCODE_BACK:
2076 if (event.getRepeatCount() == 0) {
2077 event.startTracking();
2079 } else if (mCustomView == null && mActiveTabsPage == null
2080 && event.isLongPress()) {
2081 bookmarksOrHistoryPicker(true);
2086 return super.onKeyDown(keyCode, event);
2090 public boolean onKeyUp(int keyCode, KeyEvent event) {
2092 case KeyEvent.KEYCODE_MENU:
2093 mMenuIsDown = false;
2095 case KeyEvent.KEYCODE_BACK:
2096 if (event.isTracking() && !event.isCanceled()) {
2097 if (mCustomView != null) {
2098 // if a custom view is showing, hide it
2099 mTabControl.getCurrentWebView().getWebChromeClient()
2100 .onHideCustomView();
2101 } else if (mActiveTabsPage != null) {
2102 // if tab page is showing, hide it
2103 removeActiveTabPage(true);
2105 WebView subwindow = mTabControl.getCurrentSubWindow();
2106 if (subwindow != null) {
2107 if (subwindow.canGoBack()) {
2110 dismissSubWindow(mTabControl.getCurrentTab());
2113 goBackOnePageOrQuit();
2120 return super.onKeyUp(keyCode, event);
2123 /* package */ void stopLoading() {
2124 mDidStopLoad = true;
2125 resetTitleAndRevertLockIcon();
2126 WebView w = getTopWindow();
2128 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2129 // same logic here. But for subwindow case, should we call into the main
2130 // WebView's onPageFinished as we never call its onPageStarted and if
2131 // the page finishes itself, we don't call onPageFinished.
2132 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2137 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2141 boolean didUserStopLoading() {
2142 return mDidStopLoad;
2145 private void cancelStopToast() {
2146 if (mStopToast != null) {
2147 mStopToast.cancel();
2152 // called by a UI or non-UI thread to post the message
2153 public void postMessage(int what, int arg1, int arg2, Object obj,
2155 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2159 // called by a UI or non-UI thread to remove the message
2160 void removeMessages(int what, Object object) {
2161 mHandler.removeMessages(what, object);
2164 // public message ids
2165 public final static int LOAD_URL = 1001;
2166 public final static int STOP_LOAD = 1002;
2169 private static final int FOCUS_NODE_HREF = 102;
2170 private static final int RELEASE_WAKELOCK = 107;
2172 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2174 // Private handler for handling javascript and saving passwords
2175 private Handler mHandler = new Handler() {
2177 public void handleMessage(Message msg) {
2179 case FOCUS_NODE_HREF:
2181 String url = (String) msg.getData().get("url");
2182 String title = (String) msg.getData().get("title");
2183 if (url == null || url.length() == 0) {
2186 HashMap focusNodeMap = (HashMap) msg.obj;
2187 WebView view = (WebView) focusNodeMap.get("webview");
2188 // Only apply the action if the top window did not change.
2189 if (getTopWindow() != view) {
2193 case R.id.open_context_menu_id:
2194 case R.id.view_image_context_menu_id:
2195 loadUrlFromContext(getTopWindow(), url);
2197 case R.id.open_newtab_context_menu_id:
2198 final Tab parent = mTabControl.getCurrentTab();
2199 final Tab newTab = openTab(url);
2200 if (newTab != parent) {
2201 parent.addChildTab(newTab);
2204 case R.id.bookmark_context_menu_id:
2205 Intent intent = new Intent(BrowserActivity.this,
2206 AddBookmarkPage.class);
2207 intent.putExtra("url", url);
2208 intent.putExtra("title", title);
2209 startActivity(intent);
2211 case R.id.share_link_context_menu_id:
2212 // See if this site has been visited before
2213 StringBuilder sb = new StringBuilder(
2214 Browser.BookmarkColumns.URL + " = ");
2215 DatabaseUtils.appendEscapedSQLString(sb, url);
2216 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2217 Browser.HISTORY_PROJECTION,
2221 if (c.moveToFirst()) {
2222 // The site has been visited before, so grab the
2223 // info from the database.
2224 Bitmap favicon = null;
2225 Bitmap thumbnail = null;
2226 String linkTitle = c.getString(Browser.
2227 HISTORY_PROJECTION_TITLE_INDEX);
2228 byte[] data = c.getBlob(Browser.
2229 HISTORY_PROJECTION_FAVICON_INDEX);
2231 favicon = BitmapFactory.decodeByteArray(
2232 data, 0, data.length);
2234 data = c.getBlob(Browser.
2235 HISTORY_PROJECTION_THUMBNAIL_INDEX);
2237 thumbnail = BitmapFactory.decodeByteArray(
2238 data, 0, data.length);
2240 sharePage(BrowserActivity.this,
2241 linkTitle, url, favicon, thumbnail);
2243 Browser.sendString(BrowserActivity.this, url,
2245 R.string.choosertitle_sharevia));
2248 case R.id.copy_link_context_menu_id:
2251 case R.id.save_link_context_menu_id:
2252 case R.id.download_context_menu_id:
2253 onDownloadStartNoStream(url, null, null, null, -1);
2260 loadUrlFromContext(getTopWindow(), (String) msg.obj);
2267 case RELEASE_WAKELOCK:
2268 if (mWakeLock.isHeld()) {
2269 mWakeLock.release();
2270 // if we reach here, Browser should be still in the
2271 // background loading after WAKELOCK_TIMEOUT (5-min).
2272 // To avoid burning the battery, stop loading.
2273 mTabControl.stopAllLoading();
2277 case UPDATE_BOOKMARK_THUMBNAIL:
2278 WebView view = (WebView) msg.obj;
2280 updateScreenshot(view);
2288 * Share a page, providing the title, url, favicon, and a screenshot. Uses
2289 * an {@link Intent} to launch the Activity chooser.
2290 * @param c Context used to launch a new Activity.
2291 * @param title Title of the page. Stored in the Intent with
2292 * {@link Intent#EXTRA_SUBJECT}
2293 * @param url URL of the page. Stored in the Intent with
2294 * {@link Intent#EXTRA_TEXT}
2295 * @param favicon Bitmap of the favicon for the page. Stored in the Intent
2296 * with {@link Browser#EXTRA_SHARE_FAVICON}
2297 * @param screenshot Bitmap of a screenshot of the page. Stored in the
2298 * Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2300 public static final void sharePage(Context c, String title, String url,
2301 Bitmap favicon, Bitmap screenshot) {
2302 Intent send = new Intent(Intent.ACTION_SEND);
2303 send.setType("text/plain");
2304 send.putExtra(Intent.EXTRA_TEXT, url);
2305 send.putExtra(Intent.EXTRA_SUBJECT, title);
2306 send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2307 send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2309 c.startActivity(Intent.createChooser(send, c.getString(
2310 R.string.choosertitle_sharevia)));
2311 } catch(android.content.ActivityNotFoundException ex) {
2312 // if no app handles it, do nothing
2316 private void updateScreenshot(WebView view) {
2317 // If this is a bookmarked site, add a screenshot to the database.
2318 // FIXME: When should we update? Every time?
2319 // FIXME: Would like to make sure there is actually something to
2320 // draw, but the API for that (WebViewCore.pictureReady()) is not
2321 // currently accessible here.
2323 ContentResolver cr = getContentResolver();
2324 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2325 cr, view.getOriginalUrl(), view.getUrl(), true);
2327 boolean succeed = c.moveToFirst();
2328 ContentValues values = null;
2330 if (values == null) {
2331 final ByteArrayOutputStream os
2332 = new ByteArrayOutputStream();
2333 Bitmap bm = createScreenshot(view);
2338 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2339 values = new ContentValues();
2340 values.put(Browser.BookmarkColumns.THUMBNAIL,
2343 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2344 c.getInt(0)), values, null, null);
2345 succeed = c.moveToNext();
2352 * Values for the size of the thumbnail created when taking a screenshot.
2353 * Lazily initialized. Instead of using these directly, use
2354 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2356 private static int THUMBNAIL_WIDTH = 0;
2357 private static int THUMBNAIL_HEIGHT = 0;
2360 * Return the desired width for thumbnail screenshots, which are stored in
2361 * the database, and used on the bookmarks screen.
2362 * @param context Context for finding out the density of the screen.
2363 * @return int desired width for thumbnail screenshot.
2365 /* package */ static int getDesiredThumbnailWidth(Context context) {
2366 if (THUMBNAIL_WIDTH == 0) {
2367 float density = context.getResources().getDisplayMetrics().density;
2368 THUMBNAIL_WIDTH = (int) (90 * density);
2369 THUMBNAIL_HEIGHT = (int) (80 * density);
2371 return THUMBNAIL_WIDTH;
2375 * Return the desired height for thumbnail screenshots, which are stored in
2376 * the database, and used on the bookmarks screen.
2377 * @param context Context for finding out the density of the screen.
2378 * @return int desired height for thumbnail screenshot.
2380 /* package */ static int getDesiredThumbnailHeight(Context context) {
2381 // To ensure that they are both initialized.
2382 getDesiredThumbnailWidth(context);
2383 return THUMBNAIL_HEIGHT;
2386 private Bitmap createScreenshot(WebView view) {
2387 Picture thumbnail = view.capturePicture();
2388 if (thumbnail == null) {
2391 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2392 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2393 Canvas canvas = new Canvas(bm);
2394 // May need to tweak these values to determine what is the
2395 // best scale factor
2396 int thumbnailWidth = thumbnail.getWidth();
2397 int thumbnailHeight = thumbnail.getHeight();
2398 float scaleFactorX = 1.0f;
2399 float scaleFactorY = 1.0f;
2400 if (thumbnailWidth > 0) {
2401 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2402 (float)thumbnailWidth;
2407 if (view.getWidth() > view.getHeight() &&
2408 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2409 // If the device is in landscape and the page is shorter
2410 // than the height of the view, stretch the thumbnail to fill the
2412 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2413 (float)thumbnailHeight;
2415 // In the portrait case, this looks nice.
2416 scaleFactorY = scaleFactorX;
2419 canvas.scale(scaleFactorX, scaleFactorY);
2421 thumbnail.draw(canvas);
2425 // -------------------------------------------------------------------------
2426 // Helper function for WebViewClient.
2427 //-------------------------------------------------------------------------
2429 // Use in overrideUrlLoading
2430 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2431 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2432 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2433 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2435 // Keep this initial progress in sync with initialProgressValue (* 100)
2436 // in ProgressTracker.cpp
2437 private final static int INITIAL_PROGRESS = 10;
2439 void onPageStarted(WebView view, String url, Bitmap favicon) {
2440 // when BrowserActivity just starts, onPageStarted may be called before
2441 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2442 // to start the timer. As we won't switch tabs while an activity is in
2443 // pause state, we can ensure calling resume and pause in pair.
2444 if (mActivityInPause) resumeWebViewTimers();
2447 setUrlTitle(url, null);
2448 setFavicon(favicon);
2449 // Show some progress so that the user knows the page is beginning to
2451 onProgressChanged(view, INITIAL_PROGRESS);
2452 mDidStopLoad = false;
2453 if (!mIsNetworkUp) createAndShowNetworkDialog();
2455 if (mSettings.isTracing()) {
2458 WebAddress uri = new WebAddress(url);
2460 } catch (android.net.ParseException ex) {
2463 host = host.replace('.', '_');
2466 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2469 // Performance probe
2471 mStart = SystemClock.uptimeMillis();
2472 mProcessStart = Process.getElapsedCpuTime();
2473 long[] sysCpu = new long[7];
2474 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2476 mUserStart = sysCpu[0] + sysCpu[1];
2477 mSystemStart = sysCpu[2];
2478 mIdleStart = sysCpu[3];
2479 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2481 mUiStart = SystemClock.currentThreadTimeMillis();
2485 void onPageFinished(WebView view, String url) {
2486 // Reset the title and icon in case we stopped a provisional load.
2487 resetTitleAndIcon(view);
2488 // Update the lock icon image only once we are done loading
2489 updateLockIconToLatest();
2490 // pause the WebView timer and release the wake lock if it is finished
2491 // while BrowserActivity is in pause state.
2492 if (mActivityInPause && pauseWebViewTimers()) {
2493 if (mWakeLock.isHeld()) {
2494 mHandler.removeMessages(RELEASE_WAKELOCK);
2495 mWakeLock.release();
2499 // Performance probe
2501 long[] sysCpu = new long[7];
2502 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2504 String uiInfo = "UI thread used "
2505 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2508 Log.d(LOGTAG, uiInfo);
2510 //The string that gets written to the log
2511 String performanceString = "It took total "
2512 + (SystemClock.uptimeMillis() - mStart)
2513 + " ms clock time to load the page."
2514 + "\nbrowser process used "
2515 + (Process.getElapsedCpuTime() - mProcessStart)
2516 + " ms, user processes used "
2517 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2518 + " ms, kernel used "
2519 + (sysCpu[2] - mSystemStart) * 10
2520 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2521 + " ms and irq took "
2522 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2523 * 10 + " ms, " + uiInfo;
2525 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2528 // strip the url to maintain consistency
2529 String newUrl = new String(url);
2530 if (newUrl.startsWith("http://www.")) {
2531 newUrl = newUrl.substring(11);
2532 } else if (newUrl.startsWith("http://")) {
2533 newUrl = newUrl.substring(7);
2534 } else if (newUrl.startsWith("https://www.")) {
2535 newUrl = newUrl.substring(12);
2536 } else if (newUrl.startsWith("https://")) {
2537 newUrl = newUrl.substring(8);
2540 Log.d(LOGTAG, newUrl + " loaded");
2548 Debug.stopMethodTracing();
2552 boolean shouldOverrideUrlLoading(WebView view, String url) {
2553 if (url.startsWith(SCHEME_WTAI)) {
2554 // wtai://wp/mc;number
2555 // number=string(phone-number)
2556 if (url.startsWith(SCHEME_WTAI_MC)) {
2557 Intent intent = new Intent(Intent.ACTION_VIEW,
2558 Uri.parse(WebView.SCHEME_TEL +
2559 url.substring(SCHEME_WTAI_MC.length())));
2560 startActivity(intent);
2563 // wtai://wp/sd;dtmf
2564 // dtmf=string(dialstring)
2565 if (url.startsWith(SCHEME_WTAI_SD)) {
2566 // TODO: only send when there is active voice connection
2569 // wtai://wp/ap;number;name
2570 // number=string(phone-number)
2572 if (url.startsWith(SCHEME_WTAI_AP)) {
2578 // The "about:" schemes are internal to the browser; don't want these to
2579 // be dispatched to other apps.
2580 if (url.startsWith("about:")) {
2585 // perform generic parsing of the URI to turn it into an Intent.
2587 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2588 } catch (URISyntaxException ex) {
2589 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2593 // check whether the intent can be resolved. If not, we will see
2594 // whether we can download it from the Market.
2595 if (getPackageManager().resolveActivity(intent, 0) == null) {
2596 String packagename = intent.getPackage();
2597 if (packagename != null) {
2598 intent = new Intent(Intent.ACTION_VIEW, Uri
2599 .parse("market://search?q=pname:" + packagename));
2600 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2601 startActivity(intent);
2608 // sanitize the Intent, ensuring web pages can not bypass browser
2609 // security (only access to BROWSABLE activities).
2610 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2611 intent.setComponent(null);
2613 if (startActivityIfNeeded(intent, -1)) {
2616 } catch (ActivityNotFoundException ex) {
2617 // ignore the error. If no application can handle the URL,
2618 // eg about:blank, assume the browser can handle it.
2629 // -------------------------------------------------------------------------
2630 // Helper function for WebChromeClient
2631 // -------------------------------------------------------------------------
2633 void onProgressChanged(WebView view, int newProgress) {
2634 mFakeTitleBar.setProgress(newProgress);
2636 if (newProgress == 100) {
2637 // onProgressChanged() may continue to be called after the main
2638 // frame has finished loading, as any remaining sub frames continue
2639 // to load. We'll only get called once though with newProgress as
2640 // 100 when everything is loaded. (onPageFinished is called once
2641 // when the main frame completes loading regardless of the state of
2642 // any sub frames so calls to onProgressChanges may continue after
2643 // onPageFinished has executed)
2646 updateInLoadMenuItems();
2647 // If the options menu is open, leave the title bar
2648 if (!mOptionsMenuOpen || !mIconView) {
2654 // onPageFinished may have already been called but a subframe is
2655 // still loading and updating the progress. Reset mInLoad and
2656 // update the menu items.
2658 updateInLoadMenuItems();
2660 // When the page first begins to load, the Activity may still be
2661 // paused, in which case showFakeTitleBar will do nothing. Call
2662 // again as the page continues to load so that it will be shown.
2663 // (Calling it will the fake title bar is already showing will also
2665 if (!mOptionsMenuOpen || mIconView) {
2666 // This page has begun to load, so show the title bar
2672 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2673 // if a view already exists then immediately terminate the new one
2674 if (mCustomView != null) {
2675 callback.onCustomViewHidden();
2679 // Add the custom view to its container.
2680 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2682 mCustomViewCallback = callback;
2683 // Save the menu state and set it to empty while the custom
2685 mOldMenuState = mMenuState;
2686 mMenuState = EMPTY_MENU;
2687 // Hide the content view.
2688 mContentView.setVisibility(View.GONE);
2689 // Finally show the custom view container.
2690 setStatusBarVisibility(false);
2691 mCustomViewContainer.setVisibility(View.VISIBLE);
2692 mCustomViewContainer.bringToFront();
2695 void onHideCustomView() {
2696 if (mCustomView == null)
2699 // Hide the custom view.
2700 mCustomView.setVisibility(View.GONE);
2701 // Remove the custom view from its container.
2702 mCustomViewContainer.removeView(mCustomView);
2704 // Reset the old menu state.
2705 mMenuState = mOldMenuState;
2706 mOldMenuState = EMPTY_MENU;
2707 mCustomViewContainer.setVisibility(View.GONE);
2708 mCustomViewCallback.onCustomViewHidden();
2709 // Show the content view.
2710 setStatusBarVisibility(true);
2711 mContentView.setVisibility(View.VISIBLE);
2714 Bitmap getDefaultVideoPoster() {
2715 if (mDefaultVideoPoster == null) {
2716 mDefaultVideoPoster = BitmapFactory.decodeResource(
2717 getResources(), R.drawable.default_video_poster);
2719 return mDefaultVideoPoster;
2722 View getVideoLoadingProgressView() {
2723 if (mVideoProgressView == null) {
2724 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2725 mVideoProgressView = inflater.inflate(
2726 R.layout.video_loading_progress, null);
2728 return mVideoProgressView;
2732 * The Object used to inform the WebView of the file to upload.
2734 private ValueCallback<Uri> mUploadMessage;
2736 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2737 if (mUploadMessage != null) return;
2738 mUploadMessage = uploadMsg;
2739 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2740 i.addCategory(Intent.CATEGORY_OPENABLE);
2742 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2743 getString(R.string.choose_upload)), FILE_SELECTED);
2746 // -------------------------------------------------------------------------
2747 // Implement functions for DownloadListener
2748 // -------------------------------------------------------------------------
2751 * Notify the host application a download should be done, or that
2752 * the data should be streamed if a streaming viewer is available.
2753 * @param url The full url to the content that should be downloaded
2754 * @param contentDisposition Content-disposition http header, if
2756 * @param mimetype The mimetype of the content reported by the server
2757 * @param contentLength The file size reported by the server
2759 public void onDownloadStart(String url, String userAgent,
2760 String contentDisposition, String mimetype, long contentLength) {
2761 // if we're dealing wih A/V content that's not explicitly marked
2762 // for download, check if it's streamable.
2763 if (contentDisposition == null
2764 || !contentDisposition.regionMatches(
2765 true, 0, "attachment", 0, 10)) {
2766 // query the package manager to see if there's a registered handler
2768 Intent intent = new Intent(Intent.ACTION_VIEW);
2769 intent.setDataAndType(Uri.parse(url), mimetype);
2770 ResolveInfo info = getPackageManager().resolveActivity(intent,
2771 PackageManager.MATCH_DEFAULT_ONLY);
2773 ComponentName myName = getComponentName();
2774 // If we resolved to ourselves, we don't want to attempt to
2775 // load the url only to try and download it again.
2776 if (!myName.getPackageName().equals(
2777 info.activityInfo.packageName)
2778 || !myName.getClassName().equals(
2779 info.activityInfo.name)) {
2780 // someone (other than us) knows how to handle this mime
2781 // type with this scheme, don't download.
2783 startActivity(intent);
2785 } catch (ActivityNotFoundException ex) {
2787 Log.d(LOGTAG, "activity not found for " + mimetype
2788 + " over " + Uri.parse(url).getScheme(),
2791 // Best behavior is to fall back to a download in this
2797 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2800 // This is to work around the fact that java.net.URI throws Exceptions
2801 // instead of just encoding URL's properly
2802 // Helper method for onDownloadStartNoStream
2803 private static String encodePath(String path) {
2804 char[] chars = path.toCharArray();
2806 boolean needed = false;
2807 for (char c : chars) {
2808 if (c == '[' || c == ']') {
2813 if (needed == false) {
2817 StringBuilder sb = new StringBuilder("");
2818 for (char c : chars) {
2819 if (c == '[' || c == ']') {
2821 sb.append(Integer.toHexString(c));
2827 return sb.toString();
2831 * Notify the host application a download should be done, even if there
2832 * is a streaming viewer available for thise type.
2833 * @param url The full url to the content that should be downloaded
2834 * @param contentDisposition Content-disposition http header, if
2836 * @param mimetype The mimetype of the content reported by the server
2837 * @param contentLength The file size reported by the server
2839 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2840 String contentDisposition, String mimetype, long contentLength) {
2842 String filename = URLUtil.guessFileName(url,
2843 contentDisposition, mimetype);
2845 // Check to see if we have an SDCard
2846 String status = Environment.getExternalStorageState();
2847 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2851 // Check to see if the SDCard is busy, same as the music app
2852 if (status.equals(Environment.MEDIA_SHARED)) {
2853 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2854 title = R.string.download_sdcard_busy_dlg_title;
2856 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2857 title = R.string.download_no_sdcard_dlg_title;
2860 new AlertDialog.Builder(this)
2862 .setIcon(android.R.drawable.ic_dialog_alert)
2864 .setPositiveButton(R.string.ok, null)
2869 // java.net.URI is a lot stricter than KURL so we have to encode some
2870 // extra characters. Fix for b 2538060 and b 1634719
2871 WebAddress webAddress;
2873 webAddress = new WebAddress(url);
2874 webAddress.mPath = encodePath(webAddress.mPath);
2875 } catch (Exception e) {
2876 // This only happens for very bad urls, we want to chatch the
2878 Log.e(LOGTAG, "Exception trying to parse url:" + url);
2882 // XXX: Have to use the old url since the cookies were stored using the
2883 // old percent-encoded url.
2884 String cookies = CookieManager.getInstance().getCookie(url);
2886 ContentValues values = new ContentValues();
2887 values.put(Downloads.Impl.COLUMN_URI, webAddress.toString());
2888 values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2889 values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2890 values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
2892 values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
2893 BrowserDownloadPage.class.getCanonicalName());
2894 values.put(Downloads.Impl.COLUMN_VISIBILITY,
2895 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2896 values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2897 values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2898 values.put(Downloads.Impl.COLUMN_DESCRIPTION, webAddress.mHost);
2899 if (contentLength > 0) {
2900 values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
2902 if (mimetype == null) {
2903 // We must have long pressed on a link or image to download it. We
2904 // are not sure of the mimetype in this case, so do a head request
2905 new FetchUrlMimeType(this).execute(values);
2907 final Uri contentUri =
2908 getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
2910 Toast.makeText(this, R.string.download_pending, Toast.LENGTH_SHORT)
2914 // -------------------------------------------------------------------------
2917 * Resets the lock icon. This method is called when we start a new load and
2918 * know the url to be loaded.
2920 private void resetLockIcon(String url) {
2921 // Save the lock-icon state (we revert to it if the load gets cancelled)
2922 mTabControl.getCurrentTab().resetLockIcon(url);
2923 updateLockIconImage(LOCK_ICON_UNSECURE);
2927 * Update the lock icon to correspond to our latest state.
2929 private void updateLockIconToLatest() {
2930 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
2934 * Updates the lock-icon image in the title-bar.
2936 private void updateLockIconImage(int lockIconType) {
2938 if (lockIconType == LOCK_ICON_SECURE) {
2940 } else if (lockIconType == LOCK_ICON_MIXED) {
2943 mTitleBar.setLock(d);
2944 mFakeTitleBar.setLock(d);
2948 * Displays a page-info dialog.
2949 * @param tab The tab to show info about
2950 * @param fromShowSSLCertificateOnError The flag that indicates whether
2951 * this dialog was opened from the SSL-certificate-on-error dialog or
2952 * not. This is important, since we need to know whether to return to
2953 * the parent dialog or simply dismiss.
2955 private void showPageInfo(final Tab tab,
2956 final boolean fromShowSSLCertificateOnError) {
2957 final LayoutInflater factory = LayoutInflater
2960 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2962 final WebView view = tab.getWebView();
2965 String title = null;
2969 title = tab.getTitle();
2970 } else if (view == mTabControl.getCurrentWebView()) {
2971 // Use the cached title and url if this is the current WebView
2975 url = view.getUrl();
2976 title = view.getTitle();
2982 if (title == null) {
2986 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2987 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2989 mPageInfoView = tab;
2990 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
2992 AlertDialog.Builder alertDialogBuilder =
2993 new AlertDialog.Builder(this)
2994 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2995 .setView(pageInfoView)
2998 new DialogInterface.OnClickListener() {
2999 public void onClick(DialogInterface dialog,
3001 mPageInfoDialog = null;
3002 mPageInfoView = null;
3004 // if we came here from the SSL error dialog
3005 if (fromShowSSLCertificateOnError) {
3006 // go back to the SSL error dialog
3007 showSSLCertificateOnError(
3008 mSSLCertificateOnErrorView,
3009 mSSLCertificateOnErrorHandler,
3010 mSSLCertificateOnErrorError);
3014 .setOnCancelListener(
3015 new DialogInterface.OnCancelListener() {
3016 public void onCancel(DialogInterface dialog) {
3017 mPageInfoDialog = null;
3018 mPageInfoView = null;
3020 // if we came here from the SSL error dialog
3021 if (fromShowSSLCertificateOnError) {
3022 // go back to the SSL error dialog
3023 showSSLCertificateOnError(
3024 mSSLCertificateOnErrorView,
3025 mSSLCertificateOnErrorHandler,
3026 mSSLCertificateOnErrorError);
3031 // if we have a main top-level page SSL certificate set or a certificate
3033 if (fromShowSSLCertificateOnError ||
3034 (view != null && view.getCertificate() != null)) {
3035 // add a 'View Certificate' button
3036 alertDialogBuilder.setNeutralButton(
3037 R.string.view_certificate,
3038 new DialogInterface.OnClickListener() {
3039 public void onClick(DialogInterface dialog,
3041 mPageInfoDialog = null;
3042 mPageInfoView = null;
3044 // if we came here from the SSL error dialog
3045 if (fromShowSSLCertificateOnError) {
3046 // go back to the SSL error dialog
3047 showSSLCertificateOnError(
3048 mSSLCertificateOnErrorView,
3049 mSSLCertificateOnErrorHandler,
3050 mSSLCertificateOnErrorError);
3052 // otherwise, display the top-most certificate from
3054 if (view.getCertificate() != null) {
3055 showSSLCertificate(tab);
3062 mPageInfoDialog = alertDialogBuilder.show();
3066 * Displays the main top-level page SSL certificate dialog
3067 * (accessible from the Page-Info dialog).
3068 * @param tab The tab to show certificate for.
3070 private void showSSLCertificate(final Tab tab) {
3071 final View certificateView =
3072 inflateCertificateView(tab.getWebView().getCertificate());
3073 if (certificateView == null) {
3077 LayoutInflater factory = LayoutInflater.from(this);
3079 final LinearLayout placeholder =
3080 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3082 LinearLayout ll = (LinearLayout) factory.inflate(
3083 R.layout.ssl_success, placeholder);
3084 ((TextView)ll.findViewById(R.id.success))
3085 .setText(R.string.ssl_certificate_is_valid);
3087 mSSLCertificateView = tab;
3088 mSSLCertificateDialog =
3089 new AlertDialog.Builder(this)
3090 .setTitle(R.string.ssl_certificate).setIcon(
3091 R.drawable.ic_dialog_browser_certificate_secure)
3092 .setView(certificateView)
3093 .setPositiveButton(R.string.ok,
3094 new DialogInterface.OnClickListener() {
3095 public void onClick(DialogInterface dialog,
3097 mSSLCertificateDialog = null;
3098 mSSLCertificateView = null;
3100 showPageInfo(tab, false);
3103 .setOnCancelListener(
3104 new DialogInterface.OnCancelListener() {
3105 public void onCancel(DialogInterface dialog) {
3106 mSSLCertificateDialog = null;
3107 mSSLCertificateView = null;
3109 showPageInfo(tab, false);
3116 * Displays the SSL error certificate dialog.
3117 * @param view The target web-view.
3118 * @param handler The SSL error handler responsible for cancelling the
3119 * connection that resulted in an SSL error or proceeding per user request.
3120 * @param error The SSL error object.
3122 void showSSLCertificateOnError(
3123 final WebView view, final SslErrorHandler handler, final SslError error) {
3125 final View certificateView =
3126 inflateCertificateView(error.getCertificate());
3127 if (certificateView == null) {
3131 LayoutInflater factory = LayoutInflater.from(this);
3133 final LinearLayout placeholder =
3134 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3136 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3137 LinearLayout ll = (LinearLayout)factory
3138 .inflate(R.layout.ssl_warning, placeholder);
3139 ((TextView)ll.findViewById(R.id.warning))
3140 .setText(R.string.ssl_untrusted);
3143 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3144 LinearLayout ll = (LinearLayout)factory
3145 .inflate(R.layout.ssl_warning, placeholder);
3146 ((TextView)ll.findViewById(R.id.warning))
3147 .setText(R.string.ssl_mismatch);
3150 if (error.hasError(SslError.SSL_EXPIRED)) {
3151 LinearLayout ll = (LinearLayout)factory
3152 .inflate(R.layout.ssl_warning, placeholder);
3153 ((TextView)ll.findViewById(R.id.warning))
3154 .setText(R.string.ssl_expired);
3157 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3158 LinearLayout ll = (LinearLayout)factory
3159 .inflate(R.layout.ssl_warning, placeholder);
3160 ((TextView)ll.findViewById(R.id.warning))
3161 .setText(R.string.ssl_not_yet_valid);
3164 mSSLCertificateOnErrorHandler = handler;
3165 mSSLCertificateOnErrorView = view;
3166 mSSLCertificateOnErrorError = error;
3167 mSSLCertificateOnErrorDialog =
3168 new AlertDialog.Builder(this)
3169 .setTitle(R.string.ssl_certificate).setIcon(
3170 R.drawable.ic_dialog_browser_certificate_partially_secure)
3171 .setView(certificateView)
3172 .setPositiveButton(R.string.ok,
3173 new DialogInterface.OnClickListener() {
3174 public void onClick(DialogInterface dialog,
3176 mSSLCertificateOnErrorDialog = null;
3177 mSSLCertificateOnErrorView = null;
3178 mSSLCertificateOnErrorHandler = null;
3179 mSSLCertificateOnErrorError = null;
3181 view.getWebViewClient().onReceivedSslError(
3182 view, handler, error);
3185 .setNeutralButton(R.string.page_info_view,
3186 new DialogInterface.OnClickListener() {
3187 public void onClick(DialogInterface dialog,
3189 mSSLCertificateOnErrorDialog = null;
3191 // do not clear the dialog state: we will
3192 // need to show the dialog again once the
3193 // user is done exploring the page-info details
3195 showPageInfo(mTabControl.getTabFromView(view),
3199 .setOnCancelListener(
3200 new DialogInterface.OnCancelListener() {
3201 public void onCancel(DialogInterface dialog) {
3202 mSSLCertificateOnErrorDialog = null;
3203 mSSLCertificateOnErrorView = null;
3204 mSSLCertificateOnErrorHandler = null;
3205 mSSLCertificateOnErrorError = null;
3207 view.getWebViewClient().onReceivedSslError(
3208 view, handler, error);
3215 * Inflates the SSL certificate view (helper method).
3216 * @param certificate The SSL certificate.
3217 * @return The resultant certificate view with issued-to, issued-by,
3218 * issued-on, expires-on, and possibly other fields set.
3219 * If the input certificate is null, returns null.
3221 private View inflateCertificateView(SslCertificate certificate) {
3222 if (certificate == null) {
3226 LayoutInflater factory = LayoutInflater.from(this);
3228 View certificateView = factory.inflate(
3229 R.layout.ssl_certificate, null);
3232 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3233 if (issuedTo != null) {
3234 ((TextView) certificateView.findViewById(R.id.to_common))
3235 .setText(issuedTo.getCName());
3236 ((TextView) certificateView.findViewById(R.id.to_org))
3237 .setText(issuedTo.getOName());
3238 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3239 .setText(issuedTo.getUName());
3243 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3244 if (issuedBy != null) {
3245 ((TextView) certificateView.findViewById(R.id.by_common))
3246 .setText(issuedBy.getCName());
3247 ((TextView) certificateView.findViewById(R.id.by_org))
3248 .setText(issuedBy.getOName());
3249 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3250 .setText(issuedBy.getUName());
3254 String issuedOn = formatCertificateDate(
3255 certificate.getValidNotBeforeDate());
3256 ((TextView) certificateView.findViewById(R.id.issued_on))
3260 String expiresOn = formatCertificateDate(
3261 certificate.getValidNotAfterDate());
3262 ((TextView) certificateView.findViewById(R.id.expires_on))
3263 .setText(expiresOn);
3265 return certificateView;
3269 * Formats the certificate date to a properly localized date string.
3270 * @return Properly localized version of the certificate date string and
3271 * the "" if it fails to localize.
3273 private String formatCertificateDate(Date certificateDate) {
3274 if (certificateDate == null) {
3277 String formattedDate = DateFormat.getDateFormat(this).format(certificateDate);
3278 if (formattedDate == null) {
3281 return formattedDate;
3285 * Displays an http-authentication dialog.
3287 void showHttpAuthentication(final HttpAuthHandler handler,
3288 final String host, final String realm, final String title,
3289 final String name, final String password, int focusId) {
3290 LayoutInflater factory = LayoutInflater.from(this);
3291 final View v = factory
3292 .inflate(R.layout.http_authentication, null);
3294 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3296 if (password != null) {
3297 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3300 String titleText = title;
3301 if (titleText == null) {
3302 titleText = getText(R.string.sign_in_to).toString().replace(
3303 "%s1", host).replace("%s2", realm);
3306 mHttpAuthHandler = handler;
3307 AlertDialog dialog = new AlertDialog.Builder(this)
3308 .setTitle(titleText)
3309 .setIcon(android.R.drawable.ic_dialog_alert)
3311 .setPositiveButton(R.string.action,
3312 new DialogInterface.OnClickListener() {
3313 public void onClick(DialogInterface dialog,
3315 String nm = ((EditText) v
3316 .findViewById(R.id.username_edit))
3317 .getText().toString();
3318 String pw = ((EditText) v
3319 .findViewById(R.id.password_edit))
3320 .getText().toString();
3321 BrowserActivity.this.setHttpAuthUsernamePassword
3322 (host, realm, nm, pw);
3323 handler.proceed(nm, pw);
3324 mHttpAuthenticationDialog = null;
3325 mHttpAuthHandler = null;
3327 .setNegativeButton(R.string.cancel,
3328 new DialogInterface.OnClickListener() {
3329 public void onClick(DialogInterface dialog,
3332 BrowserActivity.this.resetTitleAndRevertLockIcon();
3333 mHttpAuthenticationDialog = null;
3334 mHttpAuthHandler = null;
3336 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3337 public void onCancel(DialogInterface dialog) {
3339 BrowserActivity.this.resetTitleAndRevertLockIcon();
3340 mHttpAuthenticationDialog = null;
3341 mHttpAuthHandler = null;
3344 // Make the IME appear when the dialog is displayed if applicable.
3345 dialog.getWindow().setSoftInputMode(
3346 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3349 dialog.findViewById(focusId).requestFocus();
3351 v.findViewById(R.id.username_edit).requestFocus();
3353 mHttpAuthenticationDialog = dialog;
3356 public int getProgress() {
3357 WebView w = mTabControl.getCurrentWebView();
3359 return w.getProgress();
3366 * Set HTTP authentication password.
3368 * @param host The host for the password
3369 * @param realm The realm for the password
3370 * @param username The username for the password. If it is null, it means
3371 * password can't be saved.
3372 * @param password The password
3374 public void setHttpAuthUsernamePassword(String host, String realm,
3377 WebView w = getTopWindow();
3379 w.setHttpAuthUsernamePassword(host, realm, username, password);
3384 * connectivity manager says net has come or gone... inform the user
3385 * @param up true if net has come up, false if net has gone down
3387 public void onNetworkToggle(boolean up) {
3388 if (up == mIsNetworkUp) {
3391 mIsNetworkUp = true;
3392 if (mAlertDialog != null) {
3393 mAlertDialog.cancel();
3394 mAlertDialog = null;
3397 mIsNetworkUp = false;
3399 createAndShowNetworkDialog();
3402 WebView w = mTabControl.getCurrentWebView();
3404 w.setNetworkAvailable(up);
3408 boolean isNetworkUp() {
3409 return mIsNetworkUp;
3412 // This method shows the network dialog alerting the user that the net is
3413 // down. It will only show the dialog if mAlertDialog is null.
3414 private void createAndShowNetworkDialog() {
3415 if (mAlertDialog == null) {
3416 mAlertDialog = new AlertDialog.Builder(this)
3417 .setTitle(R.string.loadSuspendedTitle)
3418 .setMessage(R.string.loadSuspended)
3419 .setPositiveButton(R.string.ok, null)
3425 protected void onActivityResult(int requestCode, int resultCode,
3427 if (getTopWindow() == null) return;
3429 switch (requestCode) {
3431 if (resultCode == RESULT_OK && intent != null) {
3432 String data = intent.getAction();
3433 Bundle extras = intent.getExtras();
3434 if (extras != null && extras.getBoolean("new_window", false)) {
3437 final Tab currentTab =
3438 mTabControl.getCurrentTab();
3439 dismissSubWindow(currentTab);
3440 if (data != null && data.length() != 0) {
3441 loadUrl(getTopWindow(), data);
3445 // Deliberately fall through to PREFERENCES_PAGE, since the
3446 // same extra may be attached to the COMBO_PAGE
3447 case PREFERENCES_PAGE:
3448 if (resultCode == RESULT_OK && intent != null) {
3449 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3450 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3451 mTabControl.removeParentChildRelationShips();
3455 // Choose a file from the file picker.
3457 if (null == mUploadMessage) break;
3458 Uri result = intent == null || resultCode != RESULT_OK ? null
3460 mUploadMessage.onReceiveValue(result);
3461 mUploadMessage = null;
3466 getTopWindow().requestFocus();
3470 * This method is called as a result of the user selecting the options
3471 * menu to see the download window. It shows the download window on top of
3472 * the current window.
3474 private void viewDownloads(Uri downloadRecord) {
3475 Intent intent = new Intent(this,
3476 BrowserDownloadPage.class);
3477 intent.setData(downloadRecord);
3478 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3484 * @param startWithHistory If true, open starting on the history tab.
3485 * Otherwise, start with the bookmarks tab.
3487 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3488 WebView current = mTabControl.getCurrentWebView();
3489 if (current == null) {
3492 Intent intent = new Intent(this,
3493 CombinedBookmarkHistoryActivity.class);
3494 String title = current.getTitle();
3495 String url = current.getUrl();
3496 Bitmap thumbnail = createScreenshot(current);
3498 // Just in case the user opens bookmarks before a page finishes loading
3499 // so the current history item, and therefore the page, is null.
3501 url = mLastEnteredUrl;
3504 url = mSettings.getHomePage();
3507 // In case the web page has not yet received its associated title.
3508 if (title == null) {
3511 intent.putExtra("title", title);
3512 intent.putExtra("url", url);
3513 intent.putExtra("thumbnail", thumbnail);
3514 // Disable opening in a new window if we have maxed out the windows
3515 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3516 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3517 if (startWithHistory) {
3518 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3519 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3521 startActivityForResult(intent, COMBO_PAGE);
3524 // Called when loading from context menu or LOAD_URL message
3525 private void loadUrlFromContext(WebView view, String url) {
3526 // In case the user enters nothing.
3527 if (url != null && url.length() != 0 && view != null) {
3528 url = smartUrlFilter(url);
3529 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3536 * Load the URL into the given WebView and update the title bar
3537 * to reflect the new load. Call this instead of WebView.loadUrl
3539 * @param view The WebView used to load url.
3540 * @param url The URL to load.
3542 private void loadUrl(WebView view, String url) {
3543 updateTitleBarForNewLoad(view, url);
3548 * Load UrlData into a Tab and update the title bar to reflect the new
3549 * load. Call this instead of UrlData.loadIn directly.
3550 * @param t The Tab used to load.
3551 * @param data The UrlData being loaded.
3553 private void loadUrlDataIn(Tab t, UrlData data) {
3554 updateTitleBarForNewLoad(t.getWebView(), data.mUrl);
3559 * If the WebView is the top window, update the title bar to reflect
3560 * loading the new URL. i.e. set its text, clear the favicon (which
3561 * will be set once the page begins loading), and set the progress to
3562 * INITIAL_PROGRESS to show that the page has begun to load. Called
3563 * by loadUrl and loadUrlDataIn.
3564 * @param view The WebView that is starting a load.
3565 * @param url The URL that is being loaded.
3567 private void updateTitleBarForNewLoad(WebView view, String url) {
3568 if (view == getTopWindow()) {
3569 setUrlTitle(url, null);
3571 onProgressChanged(view, INITIAL_PROGRESS);
3575 private String smartUrlFilter(Uri inUri) {
3576 if (inUri != null) {
3577 return smartUrlFilter(inUri.toString());
3582 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3583 "(?i)" + // switch on case insensitive matching
3584 "(" + // begin group for schema
3585 "(?:http|https|file):\\/\\/" +
3586 "|(?:inline|data|about|content|javascript):" +
3591 * Attempts to determine whether user input is a URL or search
3592 * terms. Anything with a space is passed to search.
3594 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3595 * "Http://" converts to "http://"
3597 * @return Original or modified URL
3600 String smartUrlFilter(String url) {
3602 String inUrl = url.trim();
3603 boolean hasSpace = inUrl.indexOf(' ') != -1;
3605 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3606 if (matcher.matches()) {
3607 // force scheme to lowercase
3608 String scheme = matcher.group(1);
3609 String lcScheme = scheme.toLowerCase();
3610 if (!lcScheme.equals(scheme)) {
3611 inUrl = lcScheme + matcher.group(2);
3614 inUrl = inUrl.replace(" ", "%20");
3619 // FIXME: Is this the correct place to add to searches?
3620 // what if someone else calls this function?
3621 int shortcut = parseUrlShortcut(inUrl);
3622 if (shortcut != SHORTCUT_INVALID) {
3623 Browser.addSearchUrl(mResolver, inUrl);
3624 String query = inUrl.substring(2);
3626 case SHORTCUT_GOOGLE_SEARCH:
3627 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3628 case SHORTCUT_WIKIPEDIA_SEARCH:
3629 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3630 case SHORTCUT_DICTIONARY_SEARCH:
3631 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3632 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3633 // FIXME: we need location in this case
3634 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3638 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3639 return URLUtil.guessUrl(inUrl);
3643 Browser.addSearchUrl(mResolver, inUrl);
3644 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3647 /* package */ void setShouldShowErrorConsole(boolean flag) {
3648 if (flag == mShouldShowErrorConsole) {
3653 mShouldShowErrorConsole = flag;
3655 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3656 .getErrorConsole(true);
3659 // Setting the show state of the console will cause it's the layout to be inflated.
3660 if (errorConsole.numberOfErrors() > 0) {
3661 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3663 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3666 // Now we can add it to the main view.
3667 mErrorConsoleContainer.addView(errorConsole,
3668 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3669 ViewGroup.LayoutParams.WRAP_CONTENT));
3671 mErrorConsoleContainer.removeView(errorConsole);
3676 boolean shouldShowErrorConsole() {
3677 return mShouldShowErrorConsole;
3680 private void setStatusBarVisibility(boolean visible) {
3681 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3682 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3686 private void sendNetworkType(String type, String subtype) {
3687 WebView w = mTabControl.getCurrentWebView();
3689 w.setNetworkType(type, subtype);
3693 private void packageChanged(String packageName, boolean wasAdded) {
3694 WebView w = mTabControl.getCurrentWebView();
3700 w.addPackageName(packageName);
3702 w.removePackageName(packageName);
3706 private void addPackageNames(Set<String> packageNames) {
3707 WebView w = mTabControl.getCurrentWebView();
3712 w.addPackageNames(packageNames);
3715 private void getInstalledPackages() {
3716 AsyncTask<Void, Void, Set<String> > task =
3717 new AsyncTask<Void, Void, Set<String> >() {
3718 protected Set<String> doInBackground(Void... unused) {
3719 Set<String> installedPackages = new HashSet<String>();
3720 PackageManager pm = BrowserActivity.this.getPackageManager();
3722 List<PackageInfo> packages = pm.getInstalledPackages(0);
3723 for (PackageInfo p : packages) {
3724 if (BrowserActivity.this.sGoogleApps.contains(p.packageName)) {
3725 installedPackages.add(p.packageName);
3730 return installedPackages;
3733 // Executes on the UI thread
3734 protected void onPostExecute(Set<String> installedPackages) {
3735 addPackageNames(installedPackages);
3741 final static int LOCK_ICON_UNSECURE = 0;
3742 final static int LOCK_ICON_SECURE = 1;
3743 final static int LOCK_ICON_MIXED = 2;
3745 private BrowserSettings mSettings;
3746 private TabControl mTabControl;
3747 private ContentResolver mResolver;
3748 private FrameLayout mContentView;
3749 private View mCustomView;
3750 private FrameLayout mCustomViewContainer;
3751 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3753 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3754 // view, we should rewrite this.
3755 private int mCurrentMenuState = 0;
3756 private int mMenuState = R.id.MAIN_MENU;
3757 private int mOldMenuState = EMPTY_MENU;
3758 private static final int EMPTY_MENU = -1;
3761 private FindDialog mFindDialog;
3762 // Used to prevent chording to result in firing two shortcuts immediately
3763 // one after another. Fixes bug 1211714.
3766 private boolean mInLoad;
3767 private boolean mIsNetworkUp;
3768 private boolean mDidStopLoad;
3770 /* package */ boolean mActivityInPause = true;
3772 private boolean mMenuIsDown;
3774 private static boolean mInTrace;
3776 // Performance probe
3777 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3778 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3779 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3780 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3781 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3782 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3783 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3784 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3785 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3788 private long mStart;
3789 private long mProcessStart;
3790 private long mUserStart;
3791 private long mSystemStart;
3792 private long mIdleStart;
3793 private long mIrqStart;
3795 private long mUiStart;
3797 private Drawable mMixLockIcon;
3798 private Drawable mSecLockIcon;
3800 /* hold a ref so we can auto-cancel if necessary */
3801 private AlertDialog mAlertDialog;
3803 // The up-to-date URL and title (these can be different from those stored
3804 // in WebView, since it takes some time for the information in WebView to
3806 private String mUrl;
3807 private String mTitle;
3809 // As PageInfo has different style for landscape / portrait, we have
3810 // to re-open it when configuration changed
3811 private AlertDialog mPageInfoDialog;
3812 private Tab mPageInfoView;
3813 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3814 // dialog, we should not just dismiss it, but should get back to the
3815 // SSL-certificate-on-error dialog. This flag is used to store this state
3816 private boolean mPageInfoFromShowSSLCertificateOnError;
3818 // as SSLCertificateOnError has different style for landscape / portrait,
3819 // we have to re-open it when configuration changed
3820 private AlertDialog mSSLCertificateOnErrorDialog;
3821 private WebView mSSLCertificateOnErrorView;
3822 private SslErrorHandler mSSLCertificateOnErrorHandler;
3823 private SslError mSSLCertificateOnErrorError;
3825 // as SSLCertificate has different style for landscape / portrait, we
3826 // have to re-open it when configuration changed
3827 private AlertDialog mSSLCertificateDialog;
3828 private Tab mSSLCertificateView;
3830 // as HttpAuthentication has different style for landscape / portrait, we
3831 // have to re-open it when configuration changed
3832 private AlertDialog mHttpAuthenticationDialog;
3833 private HttpAuthHandler mHttpAuthHandler;
3835 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3836 new FrameLayout.LayoutParams(
3837 ViewGroup.LayoutParams.MATCH_PARENT,
3838 ViewGroup.LayoutParams.MATCH_PARENT);
3839 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3840 new FrameLayout.LayoutParams(
3841 ViewGroup.LayoutParams.MATCH_PARENT,
3842 ViewGroup.LayoutParams.MATCH_PARENT,
3845 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3847 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3848 // Dictionary search
3849 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3850 // Google Mobile Local search
3851 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3853 final static String QUERY_PLACE_HOLDER = "%s";
3855 // "source" parameter for Google search through search key
3856 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3857 // "source" parameter for Google search through goto menu
3858 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3859 // "source" parameter for Google search through simplily type
3860 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3861 // "source" parameter for Google search suggested by the browser
3862 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3863 // "source" parameter for Google search from unknown source
3864 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3866 private final static String LOGTAG = "browser";
3868 private String mLastEnteredUrl;
3870 private PowerManager.WakeLock mWakeLock;
3871 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3873 private Toast mStopToast;
3875 private TitleBar mTitleBar;
3877 private LinearLayout mErrorConsoleContainer = null;
3878 private boolean mShouldShowErrorConsole = false;
3880 // As the ids are dynamically created, we can't guarantee that they will
3881 // be in sequence, so this static array maps ids to a window number.
3882 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3883 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3884 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3885 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3887 // monitor platform changes
3888 private IntentFilter mNetworkStateChangedFilter;
3889 private BroadcastReceiver mNetworkStateIntentReceiver;
3891 private BroadcastReceiver mPackageInstallationReceiver;
3893 private SystemAllowGeolocationOrigins mSystemAllowGeolocationOrigins;
3895 // activity requestCode
3896 final static int COMBO_PAGE = 1;
3897 final static int DOWNLOAD_PAGE = 2;
3898 final static int PREFERENCES_PAGE = 3;
3899 final static int FILE_SELECTED = 4;
3901 // the default <video> poster
3902 private Bitmap mDefaultVideoPoster;
3903 // the video progress view
3904 private View mVideoProgressView;
3906 // The Google packages we monitor for the navigator.isApplicationInstalled()
3907 // API. Add as needed.
3908 private static Set<String> sGoogleApps;
3910 sGoogleApps = new HashSet<String>();
3911 sGoogleApps.add("com.google.android.youtube");
3915 * A UrlData class to abstract how the content will be set to WebView.
3916 * This base class uses loadUrl to show the content.
3918 /* package */ static class UrlData {
3920 final Map<String, String> mHeaders;
3921 final Intent mVoiceIntent;
3923 UrlData(String url) {
3925 this.mHeaders = null;
3926 this.mVoiceIntent = null;
3929 UrlData(String url, Map<String, String> headers, Intent intent) {
3931 this.mHeaders = headers;
3932 if (RecognizerResultsIntent.ACTION_VOICE_SEARCH_RESULTS
3933 .equals(intent.getAction())) {
3934 this.mVoiceIntent = intent;
3936 this.mVoiceIntent = null;
3941 return mVoiceIntent == null && (mUrl == null || mUrl.length() == 0);
3945 * Load this UrlData into the given Tab. Use loadUrlDataIn to update
3946 * the title bar as well.
3948 public void loadIn(Tab t) {
3949 if (mVoiceIntent != null) {
3950 t.activateVoiceSearchMode(mVoiceIntent);
3952 t.getWebView().loadUrl(mUrl, mHeaders);
3957 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);