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.ContentResolver;
27 import android.content.ContentUris;
28 import android.content.ContentValues;
29 import android.content.Context;
30 import android.content.DialogInterface;
31 import android.content.Intent;
32 import android.content.IntentFilter;
33 import android.content.pm.PackageInfo;
34 import android.content.pm.PackageManager;
35 import android.content.pm.ResolveInfo;
36 import android.content.res.Configuration;
37 import android.content.res.Resources;
38 import android.database.Cursor;
39 import android.graphics.Bitmap;
40 import android.graphics.BitmapFactory;
41 import android.graphics.Canvas;
42 import android.graphics.Picture;
43 import android.graphics.PixelFormat;
44 import android.graphics.Rect;
45 import android.graphics.drawable.Drawable;
46 import android.net.ConnectivityManager;
47 import android.net.Uri;
48 import android.net.WebAddress;
49 import android.net.http.SslCertificate;
50 import android.net.http.SslError;
51 import android.os.AsyncTask;
52 import android.os.Bundle;
53 import android.os.Debug;
54 import android.os.Environment;
55 import android.os.Handler;
56 import android.os.Message;
57 import android.os.PowerManager;
58 import android.os.Process;
59 import android.os.ServiceManager;
60 import android.os.SystemClock;
61 import android.provider.Browser;
62 import android.provider.ContactsContract;
63 import android.provider.ContactsContract.Intents.Insert;
64 import android.provider.Downloads;
65 import android.provider.MediaStore;
66 import android.text.IClipboard;
67 import android.text.TextUtils;
68 import android.text.format.DateFormat;
69 import android.util.AttributeSet;
70 import android.util.Log;
71 import android.view.ContextMenu;
72 import android.view.Gravity;
73 import android.view.KeyEvent;
74 import android.view.LayoutInflater;
75 import android.view.Menu;
76 import android.view.MenuInflater;
77 import android.view.MenuItem;
78 import android.view.View;
79 import android.view.ViewGroup;
80 import android.view.Window;
81 import android.view.WindowManager;
82 import android.view.ContextMenu.ContextMenuInfo;
83 import android.view.MenuItem.OnMenuItemClickListener;
84 import android.webkit.CookieManager;
85 import android.webkit.CookieSyncManager;
86 import android.webkit.DownloadListener;
87 import android.webkit.HttpAuthHandler;
88 import android.webkit.PluginManager;
89 import android.webkit.SslErrorHandler;
90 import android.webkit.URLUtil;
91 import android.webkit.ValueCallback;
92 import android.webkit.WebChromeClient;
93 import android.webkit.WebHistoryItem;
94 import android.webkit.WebIconDatabase;
95 import android.webkit.WebView;
96 import android.widget.EditText;
97 import android.widget.FrameLayout;
98 import android.widget.LinearLayout;
99 import android.widget.TextView;
100 import android.widget.Toast;
101 import android.accounts.Account;
102 import android.accounts.AccountManager;
103 import android.accounts.AccountManagerFuture;
104 import android.accounts.AuthenticatorException;
105 import android.accounts.OperationCanceledException;
106 import android.accounts.AccountManagerCallback;
108 import com.android.common.Patterns;
110 import com.google.android.googlelogin.GoogleLoginServiceConstants;
112 import java.io.ByteArrayOutputStream;
114 import java.io.IOException;
115 import java.io.InputStream;
116 import java.net.MalformedURLException;
118 import java.net.URISyntaxException;
120 import java.net.URLEncoder;
121 import java.text.ParseException;
122 import java.util.Date;
123 import java.util.HashMap;
124 import java.util.regex.Matcher;
125 import java.util.regex.Pattern;
127 public class BrowserActivity extends Activity
128 implements View.OnCreateContextMenuListener, DownloadListener,
129 AccountManagerCallback<Account[]> {
131 /* Define some aliases to make these debugging flags easier to refer to.
132 * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
134 private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
135 private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
136 private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
138 // These are single-character shortcuts for searching popular sources.
139 private static final int SHORTCUT_INVALID = 0;
140 private static final int SHORTCUT_GOOGLE_SEARCH = 1;
141 private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
142 private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
143 private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
145 private Account[] mAccountsGoogle;
146 private Account[] mAccountsPreferHosted;
148 private void startReadOfGoogleAccounts() {
149 mAccountsGoogle = null;
150 mAccountsPreferHosted = null;
152 AccountManager.get(this).getAccountsByTypeAndFeatures(
153 GoogleLoginServiceConstants.ACCOUNT_TYPE,
154 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
158 /** This implements AccountManagerCallback<Account[]> */
159 public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
161 if (mAccountsGoogle == null) {
162 mAccountsGoogle = accountManagerFuture.getResult();
164 AccountManager.get(this).getAccountsByTypeAndFeatures(
165 GoogleLoginServiceConstants.ACCOUNT_TYPE,
166 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
169 mAccountsPreferHosted = accountManagerFuture.getResult();
172 } catch (OperationCanceledException e) {
174 } catch (IOException e) {
176 } catch (AuthenticatorException e) {
181 private void setupHomePage() {
182 // get the default home page
183 String homepage = mSettings.getHomePage();
185 if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
188 // hostedUser == googleUser
189 // The device has only a google account
191 // hostedUser != googleUser
192 // The device has a hosted account and a google account
194 // hostedUser != null, googleUser == null
195 // The device has only a hosted account (so far)
196 String hostedUser = mAccountsPreferHosted.length == 0
198 : mAccountsPreferHosted[0].name;
199 String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
201 // developers might have no accounts at all
202 if (hostedUser == null) return;
204 if (googleUser == null || !hostedUser.equals(googleUser)) {
205 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
206 homepage = homepage.replace("?", "/a/" + domain + "?");
210 mSettings.setHomePage(BrowserActivity.this, homepage);
211 resumeAfterCredentials();
214 private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
216 public Void doInBackground(File... files) {
218 for (File f : files) {
220 Log.e(LOGTAG, f.getPath() + " was not deleted");
229 * This layout holds everything you see below the status bar, including the
230 * error console, the custom view container, and the webviews.
232 private FrameLayout mBrowserFrameLayout;
235 public void onCreate(Bundle icicle) {
237 Log.v(LOGTAG, this + " onStart");
239 super.onCreate(icicle);
240 // test the browser in OpenGL
241 // requestWindowFeature(Window.FEATURE_OPENGL);
243 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
245 mResolver = getContentResolver();
247 // If this was a web search request, pass it on to the default web
248 // search provider and finish this activity.
249 if (handleWebSearchIntent(getIntent())) {
254 mSecLockIcon = Resources.getSystem().getDrawable(
255 android.R.drawable.ic_secure);
256 mMixLockIcon = Resources.getSystem().getDrawable(
257 android.R.drawable.ic_partial_secure);
259 FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
260 .findViewById(com.android.internal.R.id.content);
261 mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
262 .inflate(R.layout.custom_screen, null);
263 mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
265 mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
266 .findViewById(R.id.error_console);
267 mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
268 .findViewById(R.id.fullscreen_custom_content);
269 frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
270 mTitleBar = new TitleBar(this);
271 mFakeTitleBar = new TitleBar(this);
273 // Create the tab control and our initial tab
274 mTabControl = new TabControl(this);
276 // Open the icon database and retain all the bookmark urls for favicons
277 retainIconsOnStartup();
279 // Keep a settings instance handy.
280 mSettings = BrowserSettings.getInstance();
281 mSettings.setTabControl(mTabControl);
282 mSettings.loadFromDb(this);
284 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
285 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
287 /* enables registration for changes in network status from
289 mNetworkStateChangedFilter = new IntentFilter();
290 mNetworkStateChangedFilter.addAction(
291 ConnectivityManager.CONNECTIVITY_ACTION);
292 mNetworkStateIntentReceiver = new BroadcastReceiver() {
294 public void onReceive(Context context, Intent intent) {
295 if (intent.getAction().equals(
296 ConnectivityManager.CONNECTIVITY_ACTION)) {
297 boolean noConnectivity = intent.getBooleanExtra(
298 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
299 onNetworkToggle(!noConnectivity);
304 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
305 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
306 filter.addDataScheme("package");
307 mPackageInstallationReceiver = new BroadcastReceiver() {
309 public void onReceive(Context context, Intent intent) {
310 final String action = intent.getAction();
311 final String packageName = intent.getData()
312 .getSchemeSpecificPart();
313 final boolean replacing = intent.getBooleanExtra(
314 Intent.EXTRA_REPLACING, false);
315 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
316 // if it is replacing, refreshPlugins() when adding
319 PackageManager pm = BrowserActivity.this.getPackageManager();
320 PackageInfo pkgInfo = null;
322 pkgInfo = pm.getPackageInfo(packageName,
323 PackageManager.GET_PERMISSIONS);
324 } catch (PackageManager.NameNotFoundException e) {
327 if (pkgInfo != null) {
328 String permissions[] = pkgInfo.requestedPermissions;
329 if (permissions == null) {
332 boolean permissionOk = false;
333 for (String permit : permissions) {
334 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
340 PluginManager.getInstance(BrowserActivity.this)
342 Intent.ACTION_PACKAGE_ADDED
348 registerReceiver(mPackageInstallationReceiver, filter);
350 if (!mTabControl.restoreState(icicle)) {
351 // clear up the thumbnail directory if we can't restore the state as
352 // none of the files in the directory are referenced any more.
353 new ClearThumbnails().execute(
354 mTabControl.getThumbnailDir().listFiles());
355 // there is no quit on Android. But if we can't restore the state,
356 // we can treat it as a new Browser, remove the old session cookies.
357 CookieManager.getInstance().removeSessionCookie();
358 final Intent intent = getIntent();
359 final Bundle extra = intent.getExtras();
360 // Create an initial tab.
361 // If the intent is ACTION_VIEW and data is not null, the Browser is
362 // invoked to view the content by another application. In this case,
363 // the tab will be close when exit.
364 UrlData urlData = getUrlDataFromIntent(intent);
366 final Tab t = mTabControl.createNewTab(
367 Intent.ACTION_VIEW.equals(intent.getAction()) &&
368 intent.getData() != null,
369 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
370 mTabControl.setCurrentTab(t);
371 attachTabToContentView(t);
372 WebView webView = t.getWebView();
374 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
375 if (scale > 0 && scale <= 1000) {
376 webView.setInitialScale(scale);
379 // If we are not restoring from an icicle, then there is a high
380 // likely hood this is the first run. So, check to see if the
381 // homepage needs to be configured and copy any plugins from our
382 // asset directory to the data partition.
383 if ((extra == null || !extra.getBoolean("testing"))
384 && !mSettings.isLoginInitialized()) {
385 startReadOfGoogleAccounts();
388 if (urlData.isEmpty()) {
389 if (mSettings.isLoginInitialized()) {
390 webView.loadUrl(mSettings.getHomePage());
392 waitForCredentials();
396 urlData.setPostData(extra
397 .getByteArray(Browser.EXTRA_POST_DATA));
399 urlData.loadIn(webView);
402 // TabControl.restoreState() will create a new tab even if
403 // restoring the state fails.
404 attachTabToContentView(mTabControl.getCurrentTab());
407 // Read JavaScript flags if it exists.
408 String jsFlags = mSettings.getJsFlags();
409 if (jsFlags.trim().length() != 0) {
410 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
415 protected void onNewIntent(Intent intent) {
416 Tab current = mTabControl.getCurrentTab();
417 // When a tab is closed on exit, the current tab index is set to -1.
418 // Reset before proceed as Browser requires the current tab to be set.
419 if (current == null) {
420 // Try to reset the tab in case the index was incorrect.
421 current = mTabControl.getTab(0);
422 if (current == null) {
423 // No tabs at all so just ignore this intent.
426 mTabControl.setCurrentTab(current);
427 attachTabToContentView(current);
428 resetTitleAndIcon(current.getWebView());
430 final String action = intent.getAction();
431 final int flags = intent.getFlags();
432 if (Intent.ACTION_MAIN.equals(action) ||
433 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
434 // just resume the browser
437 if (Intent.ACTION_VIEW.equals(action)
438 || Intent.ACTION_SEARCH.equals(action)
439 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
440 || Intent.ACTION_WEB_SEARCH.equals(action)) {
441 // If this was a search request (e.g. search query directly typed into the address bar),
442 // pass it on to the default web search provider.
443 if (handleWebSearchIntent(intent)) {
447 UrlData urlData = getUrlDataFromIntent(intent);
448 if (urlData.isEmpty()) {
449 urlData = new UrlData(mSettings.getHomePage());
451 urlData.setPostData(intent
452 .getByteArrayExtra(Browser.EXTRA_POST_DATA));
454 final String appId = intent
455 .getStringExtra(Browser.EXTRA_APPLICATION_ID);
456 if (Intent.ACTION_VIEW.equals(action)
457 && !getPackageName().equals(appId)
458 && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
459 Tab appTab = mTabControl.getTabFromId(appId);
460 if (appTab != null) {
461 Log.i(LOGTAG, "Reusing tab for " + appId);
462 // Dismiss the subwindow if applicable.
463 dismissSubWindow(appTab);
464 // Since we might kill the WebView, remove it from the
465 // content view first.
466 removeTabFromContentView(appTab);
467 // Recreate the main WebView after destroying the old one.
468 // If the WebView has the same original url and is on that
469 // page, it can be reused.
471 mTabControl.recreateWebView(appTab, urlData.mUrl);
473 if (current != appTab) {
474 switchToTab(mTabControl.getTabIndex(appTab));
476 urlData.loadIn(appTab.getWebView());
479 // If the tab was the current tab, we have to attach
480 // it to the view system again.
481 attachTabToContentView(appTab);
483 urlData.loadIn(appTab.getWebView());
488 // No matching application tab, try to find a regular tab
489 // with a matching url.
490 appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
491 if (appTab != null) {
492 if (current != appTab) {
493 switchToTab(mTabControl.getTabIndex(appTab));
495 // Otherwise, we are already viewing the correct tab.
497 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
498 // will be opened in a new tab unless we have reached
499 // MAX_TABS. Then the url will be opened in the current
500 // tab. If a new tab is created, it will have "true" for
502 openTabAndShow(urlData, true, appId);
506 if (!urlData.isEmpty()
507 && urlData.mUrl.startsWith("about:debug")) {
508 if ("about:debug.dom".equals(urlData.mUrl)) {
509 current.getWebView().dumpDomTree(false);
510 } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
511 current.getWebView().dumpDomTree(true);
512 } else if ("about:debug.render".equals(urlData.mUrl)) {
513 current.getWebView().dumpRenderTree(false);
514 } else if ("about:debug.render.file".equals(urlData.mUrl)) {
515 current.getWebView().dumpRenderTree(true);
516 } else if ("about:debug.display".equals(urlData.mUrl)) {
517 current.getWebView().dumpDisplayTree();
518 } else if (urlData.mUrl.startsWith("about:debug.drag")) {
519 int index = urlData.mUrl.codePointAt(16) - '0';
520 if (index <= 0 || index > 9) {
521 current.getWebView().setDragTracker(null);
523 current.getWebView().setDragTracker(new MeshTracker(index));
526 mSettings.toggleDebugSettings();
530 // Get rid of the subwindow if it exists
531 dismissSubWindow(current);
532 urlData.loadIn(current.getWebView());
537 private int parseUrlShortcut(String url) {
538 if (url == null) return SHORTCUT_INVALID;
540 // FIXME: quick search, need to be customized by setting
541 if (url.length() > 2 && url.charAt(1) == ' ') {
542 switch (url.charAt(0)) {
543 case 'g': return SHORTCUT_GOOGLE_SEARCH;
544 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
545 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
546 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
549 return SHORTCUT_INVALID;
553 * Launches the default web search activity with the query parameters if the given intent's data
554 * are identified as plain search terms and not URLs/shortcuts.
555 * @return true if the intent was handled and web search activity was launched, false if not.
557 private boolean handleWebSearchIntent(Intent intent) {
558 if (intent == null) return false;
561 final String action = intent.getAction();
562 if (Intent.ACTION_VIEW.equals(action)) {
563 Uri data = intent.getData();
564 if (data != null) url = data.toString();
565 } else if (Intent.ACTION_SEARCH.equals(action)
566 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
567 || Intent.ACTION_WEB_SEARCH.equals(action)) {
568 url = intent.getStringExtra(SearchManager.QUERY);
570 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
571 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
575 * Launches the default web search activity with the query parameters if the given url string
576 * was identified as plain search terms and not URL/shortcut.
577 * @return true if the request was handled and web search activity was launched, false if not.
579 private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
580 if (inUrl == null) return false;
582 // In general, we shouldn't modify URL from Intent.
583 // But currently, we get the user-typed URL from search box as well.
584 String url = fixUrl(inUrl).trim();
586 // URLs and site specific search shortcuts are handled by the regular flow of control, so
588 if (Patterns.WEB_URL.matcher(url).matches()
589 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
590 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
594 Browser.updateVisitedHistory(mResolver, url, false);
595 Browser.addSearchUrl(mResolver, url);
597 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
598 intent.addCategory(Intent.CATEGORY_DEFAULT);
599 intent.putExtra(SearchManager.QUERY, url);
600 if (appData != null) {
601 intent.putExtra(SearchManager.APP_DATA, appData);
603 if (extraData != null) {
604 intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
606 intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
607 startActivity(intent);
612 private UrlData getUrlDataFromIntent(Intent intent) {
614 if (intent != null) {
615 final String action = intent.getAction();
616 if (Intent.ACTION_VIEW.equals(action)) {
617 url = smartUrlFilter(intent.getData());
618 if (url != null && url.startsWith("content:")) {
619 /* Append mimetype so webview knows how to display */
620 String mimeType = intent.resolveType(getContentResolver());
621 if (mimeType != null) {
622 url += "?" + mimeType;
625 if ("inline:".equals(url)) {
626 return new InlinedUrlData(
627 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
629 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
630 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
632 } else if (Intent.ACTION_SEARCH.equals(action)
633 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
634 || Intent.ACTION_WEB_SEARCH.equals(action)) {
635 url = intent.getStringExtra(SearchManager.QUERY);
637 mLastEnteredUrl = url;
638 Browser.updateVisitedHistory(mResolver, url, false);
639 // In general, we shouldn't modify URL from Intent.
640 // But currently, we get the user-typed URL from search box as well.
642 url = smartUrlFilter(url);
643 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
644 if (url.contains(searchSource)) {
645 String source = null;
646 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
647 if (appData != null) {
648 source = appData.getString(SearchManager.SOURCE);
650 if (TextUtils.isEmpty(source)) {
651 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
653 url = url.replace(searchSource, "&source=android-"+source+"&");
658 return new UrlData(url);
661 /* package */ static String fixUrl(String inUrl) {
662 // FIXME: Converting the url to lower case
663 // duplicates functionality in smartUrlFilter().
664 // However, changing all current callers of fixUrl to
665 // call smartUrlFilter in addition may have unwanted
666 // consequences, and is deferred for now.
667 int colon = inUrl.indexOf(':');
668 boolean allLower = true;
669 for (int index = 0; index < colon; index++) {
670 char ch = inUrl.charAt(index);
671 if (!Character.isLetter(ch)) {
674 allLower &= Character.isLowerCase(ch);
675 if (index == colon - 1 && !allLower) {
676 inUrl = inUrl.substring(0, colon).toLowerCase()
677 + inUrl.substring(colon);
680 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
682 if (inUrl.startsWith("http:") ||
683 inUrl.startsWith("https:")) {
684 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
685 inUrl = inUrl.replaceFirst("/", "//");
686 } else inUrl = inUrl.replaceFirst(":", "://");
692 protected void onResume() {
695 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
698 if (!mActivityInPause) {
699 Log.e(LOGTAG, "BrowserActivity is already resumed.");
703 mTabControl.resumeCurrentTab();
704 mActivityInPause = false;
705 resumeWebViewTimers();
707 if (mWakeLock.isHeld()) {
708 mHandler.removeMessages(RELEASE_WAKELOCK);
712 if (mCredsDlg != null) {
713 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
714 // In case credential request never comes back
715 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
719 registerReceiver(mNetworkStateIntentReceiver,
720 mNetworkStateChangedFilter);
721 WebView.enablePlatformNotifications();
725 * Since the actual title bar is embedded in the WebView, and removing it
726 * would change its appearance, use a different TitleBar to show overlayed
727 * at the top of the screen, when the menu is open or the page is loading.
729 private TitleBar mFakeTitleBar;
732 * Holder for the fake title bar. It will have a foreground shadow, as well
733 * as a white background, so the fake title bar looks like the real one.
735 private ViewGroup mFakeTitleBarHolder;
738 * Layout parameters for the fake title bar within mFakeTitleBarHolder
740 private FrameLayout.LayoutParams mFakeTitleBarParams
741 = new FrameLayout.LayoutParams(
742 ViewGroup.LayoutParams.MATCH_PARENT,
743 ViewGroup.LayoutParams.WRAP_CONTENT);
745 * Keeps track of whether the options menu is open. This is important in
746 * determining whether to show or hide the title bar overlay.
748 private boolean mOptionsMenuOpen;
751 * Only meaningful when mOptionsMenuOpen is true. This variable keeps track
752 * of whether the configuration has changed. The first onMenuOpened call
753 * after a configuration change is simply a reopening of the same menu
754 * (i.e. mIconView did not change).
756 private boolean mConfigChanged;
759 * Whether or not the options menu is in its smaller, icon menu form. When
760 * true, we want the title bar overlay to be up. When false, we do not.
761 * Only meaningful if mOptionsMenuOpen is true.
763 private boolean mIconView;
766 public boolean onMenuOpened(int featureId, Menu menu) {
767 if (Window.FEATURE_OPTIONS_PANEL == featureId) {
768 if (mOptionsMenuOpen) {
769 if (mConfigChanged) {
770 // We do not need to make any changes to the state of the
771 // title bar, since the only thing that happened was a
772 // change in orientation
773 mConfigChanged = false;
776 // Switching the menu to expanded view, so hide the
781 // Switching the menu back to icon view, so show the
782 // title bar once again.
788 // The options menu is closed, so open it, and show the title
790 mOptionsMenuOpen = true;
791 mConfigChanged = false;
799 * Special class used exclusively for the shadow drawn underneath the fake
800 * title bar. The shadow does not need to be drawn if the WebView
801 * underneath is scrolled to the top, because it will draw directly on top
802 * of the embedded shadow.
804 private static class Shadow extends View {
805 private WebView mWebView;
807 public Shadow(Context context, AttributeSet attrs) {
808 super(context, attrs);
811 public void setWebView(WebView view) {
816 public void draw(Canvas canvas) {
817 // In general onDraw is the method to override, but we care about
818 // whether or not the background gets drawn, which happens in draw()
819 if (mWebView == null || mWebView.getScrollY() > getHeight()) {
822 // Need to invalidate so that if the scroll position changes, we
823 // still draw as appropriate.
828 private void showFakeTitleBar() {
829 final View decor = getWindow().peekDecorView();
830 if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
831 && !mActivityInPause && decor != null
832 && decor.getWindowToken() != null) {
833 Rect visRect = new Rect();
834 if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
836 Log.d(LOGTAG, "showFakeTitleBar visRect failed");
841 WindowManager manager
842 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
844 // Add the title bar to the window manager so it can receive touches
845 // while the menu is up
846 WindowManager.LayoutParams params
847 = new WindowManager.LayoutParams(
848 ViewGroup.LayoutParams.MATCH_PARENT,
849 ViewGroup.LayoutParams.WRAP_CONTENT,
850 WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
851 WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
852 PixelFormat.TRANSLUCENT);
853 params.gravity = Gravity.TOP;
854 WebView mainView = mTabControl.getCurrentWebView();
855 boolean atTop = mainView != null && mainView.getScrollY() == 0;
856 params.windowAnimations = atTop ? 0 : R.style.TitleBar;
857 // XXX : Without providing an offset, the fake title bar will be
858 // placed underneath the status bar. Use the global visible rect
859 // of mBrowserFrameLayout to determine the bottom of the status bar
860 params.y = visRect.top;
861 // Add a holder for the title bar. It also holds a shadow to show
862 // below the title bar.
863 if (mFakeTitleBarHolder == null) {
864 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
865 .inflate(R.layout.title_bar_bg, null);
867 Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
869 shadow.setWebView(mainView);
870 mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
871 manager.addView(mFakeTitleBarHolder, params);
876 public void onOptionsMenuClosed(Menu menu) {
877 mOptionsMenuOpen = false;
880 } else if (!mIconView) {
881 // The page is currently loading, and we are in expanded mode, so
882 // we were not showing the menu. Show it once again. It will be
883 // removed when the page finishes.
888 private void hideFakeTitleBar() {
889 if (mFakeTitleBar.getParent() == null) return;
890 WindowManager.LayoutParams params = (WindowManager.LayoutParams)
891 mFakeTitleBarHolder.getLayoutParams();
892 WebView mainView = mTabControl.getCurrentWebView();
893 // Although we decided whether or not to animate based on the current
894 // scroll position, the scroll position may have changed since the
895 // fake title bar was displayed. Make sure it has the appropriate
896 // animation/lack thereof before removing.
897 params.windowAnimations = mainView != null && mainView.getScrollY() == 0
898 ? 0 : R.style.TitleBar;
899 WindowManager manager
900 = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
901 manager.updateViewLayout(mFakeTitleBarHolder, params);
902 mFakeTitleBarHolder.removeView(mFakeTitleBar);
903 manager.removeView(mFakeTitleBarHolder);
907 * Special method for the fake title bar to call when displaying its context
908 * menu, since it is in its own Window, and its parent does not show a
911 /* package */ void showTitleBarContextMenu() {
912 if (null == mTitleBar.getParent()) {
915 openContextMenu(mTitleBar);
919 public void onContextMenuClosed(Menu menu) {
920 super.onContextMenuClosed(menu);
927 * onSaveInstanceState(Bundle map)
928 * onSaveInstanceState is called right before onStop(). The map contains
932 protected void onSaveInstanceState(Bundle outState) {
934 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
936 // the default implementation requires each view to have an id. As the
937 // browser handles the state itself and it doesn't use id for the views,
938 // don't call the default implementation. Otherwise it will trigger the
939 // warning like this, "couldn't save which view has focus because the
940 // focused view XXX has no id".
943 mTabControl.saveState(outState);
947 protected void onPause() {
950 if (mActivityInPause) {
951 Log.e(LOGTAG, "BrowserActivity is already paused.");
955 mTabControl.pauseCurrentTab();
956 mActivityInPause = true;
957 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
959 mHandler.sendMessageDelayed(mHandler
960 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
963 // Clear the credentials toast if it is up
964 if (mCredsDlg != null && mCredsDlg.isShowing()) {
969 // FIXME: This removes the active tabs page and resets the menu to
970 // MAIN_MENU. A better solution might be to do this work in onNewIntent
971 // but then we would need to save it in onSaveInstanceState and restore
972 // it in onCreate/onRestoreInstanceState
973 if (mActiveTabsPage != null) {
974 removeActiveTabPage(true);
979 // unregister network state listener
980 unregisterReceiver(mNetworkStateIntentReceiver);
981 WebView.disablePlatformNotifications();
985 protected void onDestroy() {
987 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
991 if (mUploadMessage != null) {
992 mUploadMessage.onReceiveValue(null);
993 mUploadMessage = null;
996 if (mTabControl == null) return;
998 // Remove the fake title bar if it is there
1001 // Remove the current tab and sub window
1002 Tab t = mTabControl.getCurrentTab();
1004 dismissSubWindow(t);
1005 removeTabFromContentView(t);
1007 // Destroy all the tabs
1008 mTabControl.destroy();
1009 WebIconDatabase.getInstance().close();
1011 unregisterReceiver(mPackageInstallationReceiver);
1015 public void onConfigurationChanged(Configuration newConfig) {
1016 mConfigChanged = true;
1017 super.onConfigurationChanged(newConfig);
1019 if (mPageInfoDialog != null) {
1020 mPageInfoDialog.dismiss();
1023 mPageInfoFromShowSSLCertificateOnError);
1025 if (mSSLCertificateDialog != null) {
1026 mSSLCertificateDialog.dismiss();
1028 mSSLCertificateView);
1030 if (mSSLCertificateOnErrorDialog != null) {
1031 mSSLCertificateOnErrorDialog.dismiss();
1032 showSSLCertificateOnError(
1033 mSSLCertificateOnErrorView,
1034 mSSLCertificateOnErrorHandler,
1035 mSSLCertificateOnErrorError);
1037 if (mHttpAuthenticationDialog != null) {
1038 String title = ((TextView) mHttpAuthenticationDialog
1039 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1041 String name = ((TextView) mHttpAuthenticationDialog
1042 .findViewById(R.id.username_edit)).getText().toString();
1043 String password = ((TextView) mHttpAuthenticationDialog
1044 .findViewById(R.id.password_edit)).getText().toString();
1045 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1047 mHttpAuthenticationDialog.dismiss();
1048 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1049 name, password, focusId);
1054 public void onLowMemory() {
1055 super.onLowMemory();
1056 mTabControl.freeMemory();
1059 private boolean resumeWebViewTimers() {
1060 Tab tab = mTabControl.getCurrentTab();
1061 boolean inLoad = tab.inLoad();
1062 if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1063 CookieSyncManager.getInstance().startSync();
1064 WebView w = tab.getWebView();
1074 private boolean pauseWebViewTimers() {
1075 Tab tab = mTabControl.getCurrentTab();
1076 boolean inLoad = tab.inLoad();
1077 if (mActivityInPause && !inLoad) {
1078 CookieSyncManager.getInstance().stopSync();
1079 WebView w = mTabControl.getCurrentWebView();
1089 // FIXME: Do we want to call this when loading google for the first time?
1091 * This function is called when we are launching for the first time. We
1092 * are waiting for the login credentials before loading Google home
1093 * pages. This way the user will be logged in straight away.
1095 private void waitForCredentials() {
1097 mCredsDlg = new ProgressDialog(this);
1098 mCredsDlg.setIndeterminate(true);
1099 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1100 // If the user cancels the operation, then cancel the Google
1101 // Credentials request.
1102 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1105 // We set a timeout for the retrieval of credentials in onResume()
1106 // as that is when we have freed up some CPU time to get
1107 // the login credentials.
1111 * If we have received the credentials or we have timed out and we are
1112 * showing the credentials dialog, then it is time to move on.
1114 private void resumeAfterCredentials() {
1115 if (mCredsDlg == null) {
1120 if (mCredsDlg.isShowing()) {
1121 mCredsDlg.dismiss();
1125 // Clear any pending timeout
1126 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1129 WebView w = mTabControl.getCurrentWebView();
1131 w.loadUrl(mSettings.getHomePage());
1134 // Update the settings, need to do this last as it can take a moment
1135 // to persist the settings. In the mean time we could be loading
1137 mSettings.setLoginInitialized(this);
1140 // Open the icon database and retain all the icons for visited sites.
1141 private void retainIconsOnStartup() {
1142 final WebIconDatabase db = WebIconDatabase.getInstance();
1143 db.open(getDir("icons", 0).getPath());
1145 Cursor c = Browser.getAllBookmarks(mResolver);
1146 if (!c.moveToFirst()) {
1150 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1152 String url = c.getString(urlIndex);
1153 db.retainIconForPageUrl(url);
1154 } while (c.moveToNext());
1156 } catch (IllegalStateException e) {
1157 Log.e(LOGTAG, "retainIconsOnStartup", e);
1161 // Helper method for getting the top window.
1162 WebView getTopWindow() {
1163 return mTabControl.getCurrentTopWebView();
1166 TabControl getTabControl() {
1171 public boolean onCreateOptionsMenu(Menu menu) {
1172 super.onCreateOptionsMenu(menu);
1174 MenuInflater inflater = getMenuInflater();
1175 inflater.inflate(R.menu.browser, menu);
1177 updateInLoadMenuItems();
1182 * As the menu can be open when loading state changes
1183 * we must manually update the state of the stop/reload menu
1186 private void updateInLoadMenuItems() {
1187 if (mMenu == null) {
1190 MenuItem src = mInLoad ?
1191 mMenu.findItem(R.id.stop_menu_id):
1192 mMenu.findItem(R.id.reload_menu_id);
1193 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1194 dest.setIcon(src.getIcon());
1195 dest.setTitle(src.getTitle());
1199 public boolean onContextItemSelected(MenuItem item) {
1200 // chording is not an issue with context menus, but we use the same
1201 // options selector, so set mCanChord to true so we can access them.
1203 int id = item.getItemId();
1205 // For the context menu from the title bar
1206 case R.id.title_bar_share_page_url:
1207 case R.id.title_bar_copy_page_url:
1208 WebView mainView = mTabControl.getCurrentWebView();
1209 if (null == mainView) {
1212 if (id == R.id.title_bar_share_page_url) {
1213 Browser.sendString(this, mainView.getUrl());
1215 copy(mainView.getUrl());
1218 // -- Browser context menu
1219 case R.id.open_context_menu_id:
1220 case R.id.open_newtab_context_menu_id:
1221 case R.id.bookmark_context_menu_id:
1222 case R.id.save_link_context_menu_id:
1223 case R.id.share_link_context_menu_id:
1224 case R.id.copy_link_context_menu_id:
1225 final WebView webView = getTopWindow();
1226 if (null == webView) {
1229 final HashMap hrefMap = new HashMap();
1230 hrefMap.put("webview", webView);
1231 final Message msg = mHandler.obtainMessage(
1232 FOCUS_NODE_HREF, id, 0, hrefMap);
1233 webView.requestFocusNodeHref(msg);
1237 // For other context menus
1238 return onOptionsItemSelected(item);
1244 private Bundle createGoogleSearchSourceBundle(String source) {
1245 Bundle bundle = new Bundle();
1246 bundle.putString(SearchManager.SOURCE, source);
1251 * Overriding this to insert a local information bundle
1254 public boolean onSearchRequested() {
1255 if (mOptionsMenuOpen) closeOptionsMenu();
1256 String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1257 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1258 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1263 public void startSearch(String initialQuery, boolean selectInitialQuery,
1264 Bundle appSearchData, boolean globalSearch) {
1265 if (appSearchData == null) {
1266 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1268 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1272 * Switch tabs. Called by the TitleBarSet when sliding the title bar
1273 * results in changing tabs.
1274 * @param index Index of the tab to change to, as defined by
1275 * mTabControl.getTabIndex(Tab t).
1276 * @return boolean True if we successfully switched to a different tab. If
1277 * the indexth tab is null, or if that tab is the same as
1278 * the current one, return false.
1280 /* package */ boolean switchToTab(int index) {
1281 Tab tab = mTabControl.getTab(index);
1282 Tab currentTab = mTabControl.getCurrentTab();
1283 if (tab == null || tab == currentTab) {
1286 if (currentTab != null) {
1287 // currentTab may be null if it was just removed. In that case,
1288 // we do not need to remove it
1289 removeTabFromContentView(currentTab);
1291 mTabControl.setCurrentTab(tab);
1292 attachTabToContentView(tab);
1293 resetTitleIconAndProgress();
1294 updateLockIconToLatest();
1298 /* package */ Tab openTabToHomePage() {
1299 return openTabAndShow(mSettings.getHomePage(), false, null);
1302 /* package */ void closeCurrentWindow() {
1303 final Tab current = mTabControl.getCurrentTab();
1304 if (mTabControl.getTabCount() == 1) {
1305 // This is the last tab. Open a new one, with the home
1306 // page and close the current one.
1307 openTabToHomePage();
1311 final Tab parent = current.getParentTab();
1312 int indexToShow = -1;
1313 if (parent != null) {
1314 indexToShow = mTabControl.getTabIndex(parent);
1316 final int currentIndex = mTabControl.getCurrentIndex();
1317 // Try to move to the tab to the right
1318 indexToShow = currentIndex + 1;
1319 if (indexToShow > mTabControl.getTabCount() - 1) {
1320 // Try to move to the tab to the left
1321 indexToShow = currentIndex - 1;
1324 if (switchToTab(indexToShow)) {
1330 private ActiveTabsPage mActiveTabsPage;
1333 * Remove the active tabs page.
1334 * @param needToAttach If true, the active tabs page did not attach a tab
1335 * to the content view, so we need to do that here.
1337 /* package */ void removeActiveTabPage(boolean needToAttach) {
1338 mContentView.removeView(mActiveTabsPage);
1339 mActiveTabsPage = null;
1340 mMenuState = R.id.MAIN_MENU;
1342 attachTabToContentView(mTabControl.getCurrentTab());
1344 getTopWindow().requestFocus();
1348 public boolean onOptionsItemSelected(MenuItem item) {
1350 // The user has already fired a shortcut with this hold down of the
1354 if (null == getTopWindow()) {
1358 // The shortcut action consumes the MENU. Even if it is still down,
1359 // it won't trigger the next shortcut action. In the case of the
1360 // shortcut action triggering a new activity, like Bookmarks, we
1361 // won't get onKeyUp for MENU. So it is important to reset it here.
1362 mMenuIsDown = false;
1364 switch (item.getItemId()) {
1366 case R.id.new_tab_menu_id:
1367 openTabToHomePage();
1370 case R.id.goto_menu_id:
1371 onSearchRequested();
1374 case R.id.bookmarks_menu_id:
1375 bookmarksOrHistoryPicker(false);
1378 case R.id.active_tabs_menu_id:
1379 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1380 removeTabFromContentView(mTabControl.getCurrentTab());
1382 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1383 mActiveTabsPage.requestFocus();
1384 mMenuState = EMPTY_MENU;
1387 case R.id.add_bookmark_menu_id:
1388 Intent i = new Intent(BrowserActivity.this,
1389 AddBookmarkPage.class);
1390 WebView w = getTopWindow();
1391 i.putExtra("url", w.getUrl());
1392 i.putExtra("title", w.getTitle());
1393 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1394 i.putExtra("thumbnail", createScreenshot(w));
1398 case R.id.stop_reload_menu_id:
1402 getTopWindow().reload();
1406 case R.id.back_menu_id:
1407 getTopWindow().goBack();
1410 case R.id.forward_menu_id:
1411 getTopWindow().goForward();
1414 case R.id.close_menu_id:
1415 // Close the subwindow if it exists.
1416 if (mTabControl.getCurrentSubWindow() != null) {
1417 dismissSubWindow(mTabControl.getCurrentTab());
1420 closeCurrentWindow();
1423 case R.id.homepage_menu_id:
1424 Tab current = mTabControl.getCurrentTab();
1425 if (current != null) {
1426 dismissSubWindow(current);
1427 current.getWebView().loadUrl(mSettings.getHomePage());
1431 case R.id.preferences_menu_id:
1432 Intent intent = new Intent(this,
1433 BrowserPreferencesPage.class);
1434 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1435 getTopWindow().getUrl());
1436 startActivityForResult(intent, PREFERENCES_PAGE);
1439 case R.id.find_menu_id:
1440 if (null == mFindDialog) {
1441 mFindDialog = new FindDialog(this);
1443 mFindDialog.setWebView(getTopWindow());
1445 mMenuState = EMPTY_MENU;
1448 case R.id.select_text_id:
1449 getTopWindow().emulateShiftHeld();
1451 case R.id.page_info_menu_id:
1452 showPageInfo(mTabControl.getCurrentTab(), false);
1455 case R.id.classic_history_menu_id:
1456 bookmarksOrHistoryPicker(true);
1459 case R.id.share_page_menu_id:
1460 Browser.sendString(this, getTopWindow().getUrl(),
1461 getText(R.string.choosertitle_sharevia).toString());
1464 case R.id.dump_nav_menu_id:
1465 getTopWindow().debugDump();
1468 case R.id.zoom_in_menu_id:
1469 getTopWindow().zoomIn();
1472 case R.id.zoom_out_menu_id:
1473 getTopWindow().zoomOut();
1476 case R.id.view_downloads_menu_id:
1477 viewDownloads(null);
1480 case R.id.window_one_menu_id:
1481 case R.id.window_two_menu_id:
1482 case R.id.window_three_menu_id:
1483 case R.id.window_four_menu_id:
1484 case R.id.window_five_menu_id:
1485 case R.id.window_six_menu_id:
1486 case R.id.window_seven_menu_id:
1487 case R.id.window_eight_menu_id:
1489 int menuid = item.getItemId();
1490 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1491 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1492 Tab desiredTab = mTabControl.getTab(id);
1493 if (desiredTab != null &&
1494 desiredTab != mTabControl.getCurrentTab()) {
1504 if (!super.onOptionsItemSelected(item)) {
1507 // Otherwise fall through.
1513 public void closeFind() {
1514 mMenuState = R.id.MAIN_MENU;
1518 public boolean onPrepareOptionsMenu(Menu menu) {
1519 // This happens when the user begins to hold down the menu key, so
1520 // allow them to chord to get a shortcut.
1522 // Note: setVisible will decide whether an item is visible; while
1523 // setEnabled() will decide whether an item is enabled, which also means
1524 // whether the matching shortcut key will function.
1525 super.onPrepareOptionsMenu(menu);
1526 switch (mMenuState) {
1528 if (mCurrentMenuState != mMenuState) {
1529 menu.setGroupVisible(R.id.MAIN_MENU, false);
1530 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1531 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1535 if (mCurrentMenuState != mMenuState) {
1536 menu.setGroupVisible(R.id.MAIN_MENU, true);
1537 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1538 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1540 final WebView w = getTopWindow();
1541 boolean canGoBack = false;
1542 boolean canGoForward = false;
1543 boolean isHome = false;
1545 canGoBack = w.canGoBack();
1546 canGoForward = w.canGoForward();
1547 isHome = mSettings.getHomePage().equals(w.getUrl());
1549 final MenuItem back = menu.findItem(R.id.back_menu_id);
1550 back.setEnabled(canGoBack);
1552 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1553 home.setEnabled(!isHome);
1555 menu.findItem(R.id.forward_menu_id)
1556 .setEnabled(canGoForward);
1558 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1559 mTabControl.canCreateNewTab());
1561 // decide whether to show the share link option
1562 PackageManager pm = getPackageManager();
1563 Intent send = new Intent(Intent.ACTION_SEND);
1564 send.setType("text/plain");
1565 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1566 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1568 boolean isNavDump = mSettings.isNavDump();
1569 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1570 nav.setVisible(isNavDump);
1571 nav.setEnabled(isNavDump);
1574 mCurrentMenuState = mMenuState;
1579 public void onCreateContextMenu(ContextMenu menu, View v,
1580 ContextMenuInfo menuInfo) {
1581 WebView webview = (WebView) v;
1582 WebView.HitTestResult result = webview.getHitTestResult();
1583 if (result == null) {
1587 int type = result.getType();
1588 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1590 "We should not show context menu when nothing is touched");
1593 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1594 // let TextView handles context menu
1598 // Note, http://b/issue?id=1106666 is requesting that
1599 // an inflated menu can be used again. This is not available
1600 // yet, so inflate each time (yuk!)
1601 MenuInflater inflater = getMenuInflater();
1602 inflater.inflate(R.menu.browsercontext, menu);
1604 // Show the correct menu group
1605 String extra = result.getExtra();
1606 menu.setGroupVisible(R.id.PHONE_MENU,
1607 type == WebView.HitTestResult.PHONE_TYPE);
1608 menu.setGroupVisible(R.id.EMAIL_MENU,
1609 type == WebView.HitTestResult.EMAIL_TYPE);
1610 menu.setGroupVisible(R.id.GEO_MENU,
1611 type == WebView.HitTestResult.GEO_TYPE);
1612 menu.setGroupVisible(R.id.IMAGE_MENU,
1613 type == WebView.HitTestResult.IMAGE_TYPE
1614 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1615 menu.setGroupVisible(R.id.ANCHOR_MENU,
1616 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1617 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1619 // Setup custom handling depending on the type
1621 case WebView.HitTestResult.PHONE_TYPE:
1622 menu.setHeaderTitle(Uri.decode(extra));
1623 menu.findItem(R.id.dial_context_menu_id).setIntent(
1624 new Intent(Intent.ACTION_VIEW, Uri
1625 .parse(WebView.SCHEME_TEL + extra)));
1626 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1627 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1628 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1629 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1631 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1635 case WebView.HitTestResult.EMAIL_TYPE:
1636 menu.setHeaderTitle(extra);
1637 menu.findItem(R.id.email_context_menu_id).setIntent(
1638 new Intent(Intent.ACTION_VIEW, Uri
1639 .parse(WebView.SCHEME_MAILTO + extra)));
1640 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1644 case WebView.HitTestResult.GEO_TYPE:
1645 menu.setHeaderTitle(extra);
1646 menu.findItem(R.id.map_context_menu_id).setIntent(
1647 new Intent(Intent.ACTION_VIEW, Uri
1648 .parse(WebView.SCHEME_GEO
1649 + URLEncoder.encode(extra))));
1650 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1654 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1655 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1656 TextView titleView = (TextView) LayoutInflater.from(this)
1657 .inflate(android.R.layout.browser_link_context_header,
1659 titleView.setText(extra);
1660 menu.setHeaderView(titleView);
1661 // decide whether to show the open link in new tab option
1662 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1663 mTabControl.canCreateNewTab());
1664 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1665 Bookmarks.urlHasAcceptableScheme(extra));
1666 PackageManager pm = getPackageManager();
1667 Intent send = new Intent(Intent.ACTION_SEND);
1668 send.setType("text/plain");
1669 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1670 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1671 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1674 // otherwise fall through to handle image part
1675 case WebView.HitTestResult.IMAGE_TYPE:
1676 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1677 menu.setHeaderTitle(extra);
1679 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1680 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1681 menu.findItem(R.id.download_context_menu_id).
1682 setOnMenuItemClickListener(new Download(extra));
1683 menu.findItem(R.id.set_wallpaper_context_menu_id).
1684 setOnMenuItemClickListener(new SetAsWallpaper(extra));
1688 Log.w(LOGTAG, "We should not get here.");
1694 // Attach the given tab to the content view.
1695 // this should only be called for the current tab.
1696 private void attachTabToContentView(Tab t) {
1697 // Attach the container that contains the main WebView and any other UI
1698 // associated with the tab.
1699 t.attachTabToContentView(mContentView);
1701 if (mShouldShowErrorConsole) {
1702 ErrorConsoleView errorConsole = t.getErrorConsole(true);
1703 if (errorConsole.numberOfErrors() == 0) {
1704 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1706 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1709 mErrorConsoleContainer.addView(errorConsole,
1710 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1711 ViewGroup.LayoutParams.WRAP_CONTENT));
1714 WebView view = t.getWebView();
1715 view.setEmbeddedTitleBar(mTitleBar);
1716 // Request focus on the top window.
1717 t.getTopWindow().requestFocus();
1720 // Attach a sub window to the main WebView of the given tab.
1721 void attachSubWindow(Tab t) {
1722 t.attachSubWindow(mContentView);
1723 getTopWindow().requestFocus();
1726 // Remove the given tab from the content view.
1727 private void removeTabFromContentView(Tab t) {
1728 // Remove the container that contains the main WebView.
1729 t.removeTabFromContentView(mContentView);
1731 ErrorConsoleView errorConsole = t.getErrorConsole(false);
1732 if (errorConsole != null) {
1733 mErrorConsoleContainer.removeView(errorConsole);
1736 WebView view = t.getWebView();
1738 view.setEmbeddedTitleBar(null);
1742 // Remove the sub window if it exists. Also called by TabControl when the
1743 // user clicks the 'X' to dismiss a sub window.
1744 /* package */ void dismissSubWindow(Tab t) {
1745 t.removeSubWindow(mContentView);
1746 // dismiss the subwindow. This will destroy the WebView.
1747 t.dismissSubWindow();
1748 getTopWindow().requestFocus();
1751 // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1752 // that accepts url as string.
1753 private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1754 return openTabAndShow(new UrlData(url), closeOnExit, appId);
1757 // This method does a ton of stuff. It will attempt to create a new tab
1758 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1759 // url isn't null, it will load the given url.
1760 /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1762 final Tab currentTab = mTabControl.getCurrentTab();
1763 if (mTabControl.canCreateNewTab()) {
1764 final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1766 WebView webview = tab.getWebView();
1767 // If the last tab was removed from the active tabs page, currentTab
1769 if (currentTab != null) {
1770 removeTabFromContentView(currentTab);
1772 // We must set the new tab as the current tab to reflect the old
1773 // animation behavior.
1774 mTabControl.setCurrentTab(tab);
1775 attachTabToContentView(tab);
1776 if (!urlData.isEmpty()) {
1777 urlData.loadIn(webview);
1781 // Get rid of the subwindow if it exists
1782 dismissSubWindow(currentTab);
1783 if (!urlData.isEmpty()) {
1784 // Load the given url.
1785 urlData.loadIn(currentTab.getWebView());
1791 private Tab openTab(String url) {
1792 if (mSettings.openInBackground()) {
1793 Tab t = mTabControl.createNewTab();
1795 WebView view = t.getWebView();
1800 return openTabAndShow(url, false, null);
1804 private class Copy implements OnMenuItemClickListener {
1805 private CharSequence mText;
1807 public boolean onMenuItemClick(MenuItem item) {
1812 public Copy(CharSequence toCopy) {
1817 private class Download implements OnMenuItemClickListener {
1818 private String mText;
1820 public boolean onMenuItemClick(MenuItem item) {
1821 onDownloadStartNoStream(mText, null, null, null, -1);
1825 public Download(String toDownload) {
1830 private class SetAsWallpaper extends Thread implements
1831 OnMenuItemClickListener, DialogInterface.OnCancelListener {
1833 private ProgressDialog mWallpaperProgress;
1834 private boolean mCanceled = false;
1836 public SetAsWallpaper(String url) {
1838 mUrl = new URL(url);
1839 } catch (MalformedURLException e) {
1844 public void onCancel(DialogInterface dialog) {
1848 public boolean onMenuItemClick(MenuItem item) {
1850 // The user may have tried to set a image with a large file size as their
1851 // background so it may take a few moments to perform the operation. Display
1852 // a progress spinner while it is working.
1853 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1854 mWallpaperProgress.setIndeterminate(true);
1855 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1856 mWallpaperProgress.setCancelable(true);
1857 mWallpaperProgress.setOnCancelListener(this);
1858 mWallpaperProgress.show();
1865 Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1867 // TODO: This will cause the resource to be downloaded again, when we
1868 // should in most cases be able to grab it from the cache. To fix this
1869 // we should query WebCore to see if we can access a cached version and
1870 // instead open an input stream on that. This pattern could also be used
1871 // in the download manager where the same problem exists.
1872 InputStream inputstream = mUrl.openStream();
1873 if (inputstream != null) {
1874 setWallpaper(inputstream);
1876 } catch (IOException e) {
1877 Log.e(LOGTAG, "Unable to set new wallpaper");
1878 // Act as though the user canceled the operation so we try to
1879 // restore the old wallpaper.
1884 // Restore the old wallpaper if the user cancelled whilst we were setting
1885 // the new wallpaper.
1886 int width = oldWallpaper.getIntrinsicWidth();
1887 int height = oldWallpaper.getIntrinsicHeight();
1888 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1889 Canvas canvas = new Canvas(bm);
1890 oldWallpaper.setBounds(0, 0, width, height);
1891 oldWallpaper.draw(canvas);
1894 } catch (IOException e) {
1895 Log.e(LOGTAG, "Unable to restore old wallpaper.");
1900 if (mWallpaperProgress.isShowing()) {
1901 mWallpaperProgress.dismiss();
1906 private void copy(CharSequence text) {
1908 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1910 clip.setClipboardText(text);
1912 } catch (android.os.RemoteException e) {
1913 Log.e(LOGTAG, "Copy failed", e);
1918 * Resets the browser title-view to whatever it must be
1919 * (for example, if we had a loading error)
1920 * When we have a new page, we call resetTitle, when we
1921 * have to reset the titlebar to whatever it used to be
1922 * (for example, if the user chose to stop loading), we
1923 * call resetTitleAndRevertLockIcon.
1925 /* package */ void resetTitleAndRevertLockIcon() {
1926 mTabControl.getCurrentTab().revertLockIcon();
1927 updateLockIconToLatest();
1928 resetTitleIconAndProgress();
1932 * Reset the title, favicon, and progress.
1934 private void resetTitleIconAndProgress() {
1935 WebView current = mTabControl.getCurrentWebView();
1936 if (current == null) {
1939 resetTitleAndIcon(current);
1940 int progress = current.getProgress();
1941 current.getWebChromeClient().onProgressChanged(current, progress);
1944 // Reset the title and the icon based on the given item.
1945 private void resetTitleAndIcon(WebView view) {
1946 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1948 setUrlTitle(item.getUrl(), item.getTitle());
1949 setFavicon(item.getFavicon());
1951 setUrlTitle(null, null);
1957 * Sets a title composed of the URL and the title string.
1958 * @param url The URL of the site being loaded.
1959 * @param title The title of the site being loaded.
1961 void setUrlTitle(String url, String title) {
1965 mTitleBar.setTitleAndUrl(title, url);
1966 mFakeTitleBar.setTitleAndUrl(title, url);
1970 * @param url The URL to build a title version of the URL from.
1971 * @return The title version of the URL or null if fails.
1972 * The title version of the URL can be either the URL hostname,
1973 * or the hostname with an "https://" prefix (for secure URLs),
1974 * or an empty string if, for example, the URL in question is a
1975 * file:// URL with no hostname.
1977 /* package */ static String buildTitleUrl(String url) {
1978 String titleUrl = null;
1982 // parse the url string
1983 URL urlObj = new URL(url);
1984 if (urlObj != null) {
1987 String protocol = urlObj.getProtocol();
1988 String host = urlObj.getHost();
1990 if (host != null && 0 < host.length()) {
1992 if (protocol != null) {
1993 // if a secure site, add an "https://" prefix!
1994 if (protocol.equalsIgnoreCase("https")) {
1995 titleUrl = protocol + "://" + host;
2000 } catch (MalformedURLException e) {}
2006 // Set the favicon in the title bar.
2007 void setFavicon(Bitmap icon) {
2008 mTitleBar.setFavicon(icon);
2009 mFakeTitleBar.setFavicon(icon);
2013 * Close the tab, remove its associated title bar, and adjust mTabControl's
2014 * current tab to a valid value.
2016 /* package */ void closeTab(Tab t) {
2017 int currentIndex = mTabControl.getCurrentIndex();
2018 int removeIndex = mTabControl.getTabIndex(t);
2019 mTabControl.removeTab(t);
2020 if (currentIndex >= removeIndex && currentIndex != 0) {
2023 mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2024 resetTitleIconAndProgress();
2027 private void goBackOnePageOrQuit() {
2028 Tab current = mTabControl.getCurrentTab();
2029 if (current == null) {
2031 * Instead of finishing the activity, simply push this to the back
2032 * of the stack and let ActivityManager to choose the foreground
2033 * activity. As BrowserActivity is singleTask, it will be always the
2034 * root of the task. So we can use either true or false for
2037 moveTaskToBack(true);
2040 WebView w = current.getWebView();
2041 if (w.canGoBack()) {
2044 // Check to see if we are closing a window that was created by
2045 // another window. If so, we switch back to that window.
2046 Tab parent = current.getParentTab();
2047 if (parent != null) {
2048 switchToTab(mTabControl.getTabIndex(parent));
2049 // Now we close the other tab
2052 if (current.closeOnExit()) {
2053 // force the tab's inLoad() to be false as we are going to
2054 // either finish the activity or remove the tab. This will
2055 // ensure pauseWebViewTimers() taking action.
2056 mTabControl.getCurrentTab().clearInLoad();
2057 if (mTabControl.getTabCount() == 1) {
2061 // call pauseWebViewTimers() now, we won't be able to call
2062 // it in onPause() as the WebView won't be valid.
2063 // Temporarily change mActivityInPause to be true as
2064 // pauseWebViewTimers() will do nothing if mActivityInPause
2066 boolean savedState = mActivityInPause;
2068 Log.e(LOGTAG, "BrowserActivity is already paused "
2069 + "while handing goBackOnePageOrQuit.");
2071 mActivityInPause = true;
2072 pauseWebViewTimers();
2073 mActivityInPause = savedState;
2074 removeTabFromContentView(current);
2075 mTabControl.removeTab(current);
2078 * Instead of finishing the activity, simply push this to the back
2079 * of the stack and let ActivityManager to choose the foreground
2080 * activity. As BrowserActivity is singleTask, it will be always the
2081 * root of the task. So we can use either true or false for
2084 moveTaskToBack(true);
2089 boolean isMenuDown() {
2094 public boolean onKeyDown(int keyCode, KeyEvent event) {
2095 // Even if MENU is already held down, we need to call to super to open
2096 // the IME on long press.
2097 if (KeyEvent.KEYCODE_MENU == keyCode) {
2099 return super.onKeyDown(keyCode, event);
2101 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2102 // still down, we don't want to trigger the search. Pretend to consume
2103 // the key and do nothing.
2104 if (mMenuIsDown) return true;
2107 case KeyEvent.KEYCODE_SPACE:
2108 // WebView/WebTextView handle the keys in the KeyDown. As
2109 // the Activity's shortcut keys are only handled when WebView
2110 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2111 if (event.isShiftPressed()) {
2112 getTopWindow().pageUp(false);
2114 getTopWindow().pageDown(false);
2117 case KeyEvent.KEYCODE_BACK:
2118 if (event.getRepeatCount() == 0) {
2119 event.startTracking();
2121 } else if (mCustomView == null && mActiveTabsPage == null
2122 && event.isLongPress()) {
2123 bookmarksOrHistoryPicker(true);
2128 return super.onKeyDown(keyCode, event);
2132 public boolean onKeyUp(int keyCode, KeyEvent event) {
2134 case KeyEvent.KEYCODE_MENU:
2135 mMenuIsDown = false;
2137 case KeyEvent.KEYCODE_BACK:
2138 if (event.isTracking() && !event.isCanceled()) {
2139 if (mCustomView != null) {
2140 // if a custom view is showing, hide it
2141 mTabControl.getCurrentWebView().getWebChromeClient()
2142 .onHideCustomView();
2143 } else if (mActiveTabsPage != null) {
2144 // if tab page is showing, hide it
2145 removeActiveTabPage(true);
2147 WebView subwindow = mTabControl.getCurrentSubWindow();
2148 if (subwindow != null) {
2149 if (subwindow.canGoBack()) {
2152 dismissSubWindow(mTabControl.getCurrentTab());
2155 goBackOnePageOrQuit();
2162 return super.onKeyUp(keyCode, event);
2165 /* package */ void stopLoading() {
2166 mDidStopLoad = true;
2167 resetTitleAndRevertLockIcon();
2168 WebView w = getTopWindow();
2170 // FIXME: before refactor, it is using mWebViewClient. So I keep the
2171 // same logic here. But for subwindow case, should we call into the main
2172 // WebView's onPageFinished as we never call its onPageStarted and if
2173 // the page finishes itself, we don't call onPageFinished.
2174 mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2179 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2183 boolean didUserStopLoading() {
2184 return mDidStopLoad;
2187 private void cancelStopToast() {
2188 if (mStopToast != null) {
2189 mStopToast.cancel();
2194 // called by a UI or non-UI thread to post the message
2195 public void postMessage(int what, int arg1, int arg2, Object obj,
2197 mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2201 // called by a UI or non-UI thread to remove the message
2202 void removeMessages(int what, Object object) {
2203 mHandler.removeMessages(what, object);
2206 // public message ids
2207 public final static int LOAD_URL = 1001;
2208 public final static int STOP_LOAD = 1002;
2211 private static final int FOCUS_NODE_HREF = 102;
2212 private static final int CANCEL_CREDS_REQUEST = 103;
2213 private static final int RELEASE_WAKELOCK = 107;
2215 static final int UPDATE_BOOKMARK_THUMBNAIL = 108;
2217 // Private handler for handling javascript and saving passwords
2218 private Handler mHandler = new Handler() {
2220 public void handleMessage(Message msg) {
2222 case FOCUS_NODE_HREF:
2224 String url = (String) msg.getData().get("url");
2225 String title = (String) msg.getData().get("title");
2226 if (url == null || url.length() == 0) {
2229 HashMap focusNodeMap = (HashMap) msg.obj;
2230 WebView view = (WebView) focusNodeMap.get("webview");
2231 // Only apply the action if the top window did not change.
2232 if (getTopWindow() != view) {
2236 case R.id.open_context_menu_id:
2237 case R.id.view_image_context_menu_id:
2238 loadURL(getTopWindow(), url);
2240 case R.id.open_newtab_context_menu_id:
2241 final Tab parent = mTabControl.getCurrentTab();
2242 final Tab newTab = openTab(url);
2243 if (newTab != parent) {
2244 parent.addChildTab(newTab);
2247 case R.id.bookmark_context_menu_id:
2248 Intent intent = new Intent(BrowserActivity.this,
2249 AddBookmarkPage.class);
2250 intent.putExtra("url", url);
2251 intent.putExtra("title", title);
2252 startActivity(intent);
2254 case R.id.share_link_context_menu_id:
2255 Browser.sendString(BrowserActivity.this, url,
2256 getText(R.string.choosertitle_sharevia).toString());
2258 case R.id.copy_link_context_menu_id:
2261 case R.id.save_link_context_menu_id:
2262 case R.id.download_context_menu_id:
2263 onDownloadStartNoStream(url, null, null, null, -1);
2270 loadURL(getTopWindow(), (String) msg.obj);
2277 case CANCEL_CREDS_REQUEST:
2278 resumeAfterCredentials();
2281 case RELEASE_WAKELOCK:
2282 if (mWakeLock.isHeld()) {
2283 mWakeLock.release();
2284 // if we reach here, Browser should be still in the
2285 // background loading after WAKELOCK_TIMEOUT (5-min).
2286 // To avoid burning the battery, stop loading.
2287 mTabControl.stopAllLoading();
2291 case UPDATE_BOOKMARK_THUMBNAIL:
2292 WebView view = (WebView) msg.obj;
2294 updateScreenshot(view);
2301 private void updateScreenshot(WebView view) {
2302 // If this is a bookmarked site, add a screenshot to the database.
2303 // FIXME: When should we update? Every time?
2304 // FIXME: Would like to make sure there is actually something to
2305 // draw, but the API for that (WebViewCore.pictureReady()) is not
2306 // currently accessible here.
2308 ContentResolver cr = getContentResolver();
2309 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2310 cr, view.getOriginalUrl(), view.getUrl(), true);
2312 boolean succeed = c.moveToFirst();
2313 ContentValues values = null;
2315 if (values == null) {
2316 final ByteArrayOutputStream os
2317 = new ByteArrayOutputStream();
2318 Bitmap bm = createScreenshot(view);
2323 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2324 values = new ContentValues();
2325 values.put(Browser.BookmarkColumns.THUMBNAIL,
2328 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2329 c.getInt(0)), values, null, null);
2330 succeed = c.moveToNext();
2337 * Values for the size of the thumbnail created when taking a screenshot.
2338 * Lazily initialized. Instead of using these directly, use
2339 * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2341 private static int THUMBNAIL_WIDTH = 0;
2342 private static int THUMBNAIL_HEIGHT = 0;
2345 * Return the desired width for thumbnail screenshots, which are stored in
2346 * the database, and used on the bookmarks screen.
2347 * @param context Context for finding out the density of the screen.
2348 * @return int desired width for thumbnail screenshot.
2350 /* package */ static int getDesiredThumbnailWidth(Context context) {
2351 if (THUMBNAIL_WIDTH == 0) {
2352 float density = context.getResources().getDisplayMetrics().density;
2353 THUMBNAIL_WIDTH = (int) (90 * density);
2354 THUMBNAIL_HEIGHT = (int) (80 * density);
2356 return THUMBNAIL_WIDTH;
2360 * Return the desired height 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 height for thumbnail screenshot.
2365 /* package */ static int getDesiredThumbnailHeight(Context context) {
2366 // To ensure that they are both initialized.
2367 getDesiredThumbnailWidth(context);
2368 return THUMBNAIL_HEIGHT;
2371 private Bitmap createScreenshot(WebView view) {
2372 Picture thumbnail = view.capturePicture();
2373 if (thumbnail == null) {
2376 Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2377 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2378 Canvas canvas = new Canvas(bm);
2379 // May need to tweak these values to determine what is the
2380 // best scale factor
2381 int thumbnailWidth = thumbnail.getWidth();
2382 int thumbnailHeight = thumbnail.getHeight();
2383 float scaleFactorX = 1.0f;
2384 float scaleFactorY = 1.0f;
2385 if (thumbnailWidth > 0) {
2386 scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2387 (float)thumbnailWidth;
2392 if (view.getWidth() > view.getHeight() &&
2393 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2394 // If the device is in landscape and the page is shorter
2395 // than the height of the view, stretch the thumbnail to fill the
2397 scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2398 (float)thumbnailHeight;
2400 // In the portrait case, this looks nice.
2401 scaleFactorY = scaleFactorX;
2404 canvas.scale(scaleFactorX, scaleFactorY);
2406 thumbnail.draw(canvas);
2410 // -------------------------------------------------------------------------
2411 // Helper function for WebViewClient.
2412 //-------------------------------------------------------------------------
2414 // Use in overrideUrlLoading
2415 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2416 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2417 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2418 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2420 void onPageStarted(WebView view, String url, Bitmap favicon) {
2421 // when BrowserActivity just starts, onPageStarted may be called before
2422 // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2423 // to start the timer. As we won't switch tabs while an activity is in
2424 // pause state, we can ensure calling resume and pause in pair.
2425 if (mActivityInPause) resumeWebViewTimers();
2428 setUrlTitle(url, null);
2429 setFavicon(favicon);
2430 // Keep this initial progress in sync with initialProgressValue (* 100)
2431 // in ProgressTracker.cpp
2432 // Show some progress so that the user knows the page is beginning to
2434 onProgressChanged(view, 10);
2435 mDidStopLoad = false;
2436 if (!mIsNetworkUp) createAndShowNetworkDialog();
2438 if (mSettings.isTracing()) {
2441 WebAddress uri = new WebAddress(url);
2443 } catch (android.net.ParseException ex) {
2446 host = host.replace('.', '_');
2449 Debug.startMethodTracing(host, 20 * 1024 * 1024);
2452 // Performance probe
2454 mStart = SystemClock.uptimeMillis();
2455 mProcessStart = Process.getElapsedCpuTime();
2456 long[] sysCpu = new long[7];
2457 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2459 mUserStart = sysCpu[0] + sysCpu[1];
2460 mSystemStart = sysCpu[2];
2461 mIdleStart = sysCpu[3];
2462 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2464 mUiStart = SystemClock.currentThreadTimeMillis();
2468 void onPageFinished(WebView view, String url) {
2469 // Reset the title and icon in case we stopped a provisional load.
2470 resetTitleAndIcon(view);
2471 // Update the lock icon image only once we are done loading
2472 updateLockIconToLatest();
2473 // pause the WebView timer and release the wake lock if it is finished
2474 // while BrowserActivity is in pause state.
2475 if (mActivityInPause && pauseWebViewTimers()) {
2476 if (mWakeLock.isHeld()) {
2477 mHandler.removeMessages(RELEASE_WAKELOCK);
2478 mWakeLock.release();
2482 // Performance probe
2484 long[] sysCpu = new long[7];
2485 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2487 String uiInfo = "UI thread used "
2488 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2491 Log.d(LOGTAG, uiInfo);
2493 //The string that gets written to the log
2494 String performanceString = "It took total "
2495 + (SystemClock.uptimeMillis() - mStart)
2496 + " ms clock time to load the page."
2497 + "\nbrowser process used "
2498 + (Process.getElapsedCpuTime() - mProcessStart)
2499 + " ms, user processes used "
2500 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2501 + " ms, kernel used "
2502 + (sysCpu[2] - mSystemStart) * 10
2503 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2504 + " ms and irq took "
2505 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2506 * 10 + " ms, " + uiInfo;
2508 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2511 // strip the url to maintain consistency
2512 String newUrl = new String(url);
2513 if (newUrl.startsWith("http://www.")) {
2514 newUrl = newUrl.substring(11);
2515 } else if (newUrl.startsWith("http://")) {
2516 newUrl = newUrl.substring(7);
2517 } else if (newUrl.startsWith("https://www.")) {
2518 newUrl = newUrl.substring(12);
2519 } else if (newUrl.startsWith("https://")) {
2520 newUrl = newUrl.substring(8);
2523 Log.d(LOGTAG, newUrl + " loaded");
2531 Debug.stopMethodTracing();
2535 boolean shouldOverrideUrlLoading(WebView view, String url) {
2536 if (url.startsWith(SCHEME_WTAI)) {
2537 // wtai://wp/mc;number
2538 // number=string(phone-number)
2539 if (url.startsWith(SCHEME_WTAI_MC)) {
2540 Intent intent = new Intent(Intent.ACTION_VIEW,
2541 Uri.parse(WebView.SCHEME_TEL +
2542 url.substring(SCHEME_WTAI_MC.length())));
2543 startActivity(intent);
2546 // wtai://wp/sd;dtmf
2547 // dtmf=string(dialstring)
2548 if (url.startsWith(SCHEME_WTAI_SD)) {
2549 // TODO: only send when there is active voice connection
2552 // wtai://wp/ap;number;name
2553 // number=string(phone-number)
2555 if (url.startsWith(SCHEME_WTAI_AP)) {
2561 // The "about:" schemes are internal to the browser; don't want these to
2562 // be dispatched to other apps.
2563 if (url.startsWith("about:")) {
2568 // perform generic parsing of the URI to turn it into an Intent.
2570 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2571 } catch (URISyntaxException ex) {
2572 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2576 // check whether the intent can be resolved. If not, we will see
2577 // whether we can download it from the Market.
2578 if (getPackageManager().resolveActivity(intent, 0) == null) {
2579 String packagename = intent.getPackage();
2580 if (packagename != null) {
2581 intent = new Intent(Intent.ACTION_VIEW, Uri
2582 .parse("market://search?q=pname:" + packagename));
2583 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2584 startActivity(intent);
2591 // sanitize the Intent, ensuring web pages can not bypass browser
2592 // security (only access to BROWSABLE activities).
2593 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2594 intent.setComponent(null);
2596 if (startActivityIfNeeded(intent, -1)) {
2599 } catch (ActivityNotFoundException ex) {
2600 // ignore the error. If no application can handle the URL,
2601 // eg about:blank, assume the browser can handle it.
2612 // -------------------------------------------------------------------------
2613 // Helper function for WebChromeClient
2614 // -------------------------------------------------------------------------
2616 void onProgressChanged(WebView view, int newProgress) {
2617 mTitleBar.setProgress(newProgress);
2618 mFakeTitleBar.setProgress(newProgress);
2620 if (newProgress == 100) {
2621 // onProgressChanged() may continue to be called after the main
2622 // frame has finished loading, as any remaining sub frames continue
2623 // to load. We'll only get called once though with newProgress as
2624 // 100 when everything is loaded. (onPageFinished is called once
2625 // when the main frame completes loading regardless of the state of
2626 // any sub frames so calls to onProgressChanges may continue after
2627 // onPageFinished has executed)
2630 updateInLoadMenuItems();
2631 // If the options menu is open, leave the title bar
2632 if (!mOptionsMenuOpen || !mIconView) {
2636 } else if (!mInLoad) {
2637 // onPageFinished may have already been called but a subframe is
2638 // still loading and updating the progress. Reset mInLoad and update
2641 updateInLoadMenuItems();
2642 if (!mOptionsMenuOpen || mIconView) {
2643 // This page has begun to load, so show the title bar
2649 void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2650 // if a view already exists then immediately terminate the new one
2651 if (mCustomView != null) {
2652 callback.onCustomViewHidden();
2656 // Add the custom view to its container.
2657 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2659 mCustomViewCallback = callback;
2660 // Save the menu state and set it to empty while the custom
2662 mOldMenuState = mMenuState;
2663 mMenuState = EMPTY_MENU;
2664 // Hide the content view.
2665 mContentView.setVisibility(View.GONE);
2666 // Finally show the custom view container.
2667 setStatusBarVisibility(false);
2668 mCustomViewContainer.setVisibility(View.VISIBLE);
2669 mCustomViewContainer.bringToFront();
2672 void onHideCustomView() {
2673 if (mCustomView == null)
2676 // Hide the custom view.
2677 mCustomView.setVisibility(View.GONE);
2678 // Remove the custom view from its container.
2679 mCustomViewContainer.removeView(mCustomView);
2681 // Reset the old menu state.
2682 mMenuState = mOldMenuState;
2683 mOldMenuState = EMPTY_MENU;
2684 mCustomViewContainer.setVisibility(View.GONE);
2685 mCustomViewCallback.onCustomViewHidden();
2686 // Show the content view.
2687 setStatusBarVisibility(true);
2688 mContentView.setVisibility(View.VISIBLE);
2691 Bitmap getDefaultVideoPoster() {
2692 if (mDefaultVideoPoster == null) {
2693 mDefaultVideoPoster = BitmapFactory.decodeResource(
2694 getResources(), R.drawable.default_video_poster);
2696 return mDefaultVideoPoster;
2699 View getVideoLoadingProgressView() {
2700 if (mVideoProgressView == null) {
2701 LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2702 mVideoProgressView = inflater.inflate(
2703 R.layout.video_loading_progress, null);
2705 return mVideoProgressView;
2709 * The Object used to inform the WebView of the file to upload.
2711 private ValueCallback<Uri> mUploadMessage;
2713 void openFileChooser(ValueCallback<Uri> uploadMsg) {
2714 if (mUploadMessage != null) return;
2715 mUploadMessage = uploadMsg;
2716 Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2717 i.addCategory(Intent.CATEGORY_OPENABLE);
2719 BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2720 getString(R.string.choose_upload)), FILE_SELECTED);
2723 // -------------------------------------------------------------------------
2724 // Implement functions for DownloadListener
2725 // -------------------------------------------------------------------------
2728 * Notify the host application a download should be done, or that
2729 * the data should be streamed if a streaming viewer is available.
2730 * @param url The full url to the content that should be downloaded
2731 * @param contentDisposition Content-disposition http header, if
2733 * @param mimetype The mimetype of the content reported by the server
2734 * @param contentLength The file size reported by the server
2736 public void onDownloadStart(String url, String userAgent,
2737 String contentDisposition, String mimetype, long contentLength) {
2738 // if we're dealing wih A/V content that's not explicitly marked
2739 // for download, check if it's streamable.
2740 if (contentDisposition == null
2741 || !contentDisposition.regionMatches(
2742 true, 0, "attachment", 0, 10)) {
2743 // query the package manager to see if there's a registered handler
2745 Intent intent = new Intent(Intent.ACTION_VIEW);
2746 intent.setDataAndType(Uri.parse(url), mimetype);
2747 ResolveInfo info = getPackageManager().resolveActivity(intent,
2748 PackageManager.MATCH_DEFAULT_ONLY);
2750 ComponentName myName = getComponentName();
2751 // If we resolved to ourselves, we don't want to attempt to
2752 // load the url only to try and download it again.
2753 if (!myName.getPackageName().equals(
2754 info.activityInfo.packageName)
2755 || !myName.getClassName().equals(
2756 info.activityInfo.name)) {
2757 // someone (other than us) knows how to handle this mime
2758 // type with this scheme, don't download.
2760 startActivity(intent);
2762 } catch (ActivityNotFoundException ex) {
2764 Log.d(LOGTAG, "activity not found for " + mimetype
2765 + " over " + Uri.parse(url).getScheme(),
2768 // Best behavior is to fall back to a download in this
2774 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2778 * Notify the host application a download should be done, even if there
2779 * is a streaming viewer available for thise type.
2780 * @param url The full url to the content that should be downloaded
2781 * @param contentDisposition Content-disposition http header, if
2783 * @param mimetype The mimetype of the content reported by the server
2784 * @param contentLength The file size reported by the server
2786 /*package */ void onDownloadStartNoStream(String url, String userAgent,
2787 String contentDisposition, String mimetype, long contentLength) {
2789 String filename = URLUtil.guessFileName(url,
2790 contentDisposition, mimetype);
2792 // Check to see if we have an SDCard
2793 String status = Environment.getExternalStorageState();
2794 if (!status.equals(Environment.MEDIA_MOUNTED)) {
2798 // Check to see if the SDCard is busy, same as the music app
2799 if (status.equals(Environment.MEDIA_SHARED)) {
2800 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2801 title = R.string.download_sdcard_busy_dlg_title;
2803 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2804 title = R.string.download_no_sdcard_dlg_title;
2807 new AlertDialog.Builder(this)
2809 .setIcon(android.R.drawable.ic_dialog_alert)
2811 .setPositiveButton(R.string.ok, null)
2816 // java.net.URI is a lot stricter than KURL so we have to undo
2817 // KURL's percent-encoding and redo the encoding using java.net.URI.
2820 // Undo the percent-encoding that KURL may have done.
2821 String newUrl = new String(URLUtil.decode(url.getBytes()));
2822 // Parse the url into pieces
2823 WebAddress w = new WebAddress(newUrl);
2825 String query = null;
2826 String path = w.mPath;
2827 // Break the path into path, query, and fragment
2828 if (path.length() > 0) {
2829 // Strip the fragment
2830 int idx = path.lastIndexOf('#');
2832 frag = path.substring(idx + 1);
2833 path = path.substring(0, idx);
2835 idx = path.lastIndexOf('?');
2837 query = path.substring(idx + 1);
2838 path = path.substring(0, idx);
2841 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2843 } catch (Exception e) {
2844 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2848 // XXX: Have to use the old url since the cookies were stored using the
2849 // old percent-encoded url.
2850 String cookies = CookieManager.getInstance().getCookie(url);
2852 ContentValues values = new ContentValues();
2853 values.put(Downloads.COLUMN_URI, uri.toString());
2854 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
2855 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
2856 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
2858 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
2859 BrowserDownloadPage.class.getCanonicalName());
2860 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2861 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
2862 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
2863 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
2864 if (contentLength > 0) {
2865 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
2867 if (mimetype == null) {
2868 // We must have long pressed on a link or image to download it. We
2869 // are not sure of the mimetype in this case, so do a head request
2870 new FetchUrlMimeType(this).execute(values);
2872 final Uri contentUri =
2873 getContentResolver().insert(Downloads.CONTENT_URI, values);
2874 viewDownloads(contentUri);
2879 // -------------------------------------------------------------------------
2882 * Resets the lock icon. This method is called when we start a new load and
2883 * know the url to be loaded.
2885 private void resetLockIcon(String url) {
2886 // Save the lock-icon state (we revert to it if the load gets cancelled)
2887 mTabControl.getCurrentTab().resetLockIcon(url);
2888 updateLockIconImage(LOCK_ICON_UNSECURE);
2892 * Update the lock icon to correspond to our latest state.
2894 private void updateLockIconToLatest() {
2895 updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
2899 * Updates the lock-icon image in the title-bar.
2901 private void updateLockIconImage(int lockIconType) {
2903 if (lockIconType == LOCK_ICON_SECURE) {
2905 } else if (lockIconType == LOCK_ICON_MIXED) {
2908 mTitleBar.setLock(d);
2909 mFakeTitleBar.setLock(d);
2913 * Displays a page-info dialog.
2914 * @param tab The tab to show info about
2915 * @param fromShowSSLCertificateOnError The flag that indicates whether
2916 * this dialog was opened from the SSL-certificate-on-error dialog or
2917 * not. This is important, since we need to know whether to return to
2918 * the parent dialog or simply dismiss.
2920 private void showPageInfo(final Tab tab,
2921 final boolean fromShowSSLCertificateOnError) {
2922 final LayoutInflater factory = LayoutInflater
2925 final View pageInfoView = factory.inflate(R.layout.page_info, null);
2927 final WebView view = tab.getWebView();
2930 String title = null;
2934 title = tab.getTitle();
2935 } else if (view == mTabControl.getCurrentWebView()) {
2936 // Use the cached title and url if this is the current WebView
2940 url = view.getUrl();
2941 title = view.getTitle();
2947 if (title == null) {
2951 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
2952 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
2954 mPageInfoView = tab;
2955 mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
2957 AlertDialog.Builder alertDialogBuilder =
2958 new AlertDialog.Builder(this)
2959 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
2960 .setView(pageInfoView)
2963 new DialogInterface.OnClickListener() {
2964 public void onClick(DialogInterface dialog,
2966 mPageInfoDialog = null;
2967 mPageInfoView = null;
2969 // if we came here from the SSL error dialog
2970 if (fromShowSSLCertificateOnError) {
2971 // go back to the SSL error dialog
2972 showSSLCertificateOnError(
2973 mSSLCertificateOnErrorView,
2974 mSSLCertificateOnErrorHandler,
2975 mSSLCertificateOnErrorError);
2979 .setOnCancelListener(
2980 new DialogInterface.OnCancelListener() {
2981 public void onCancel(DialogInterface dialog) {
2982 mPageInfoDialog = null;
2983 mPageInfoView = null;
2985 // if we came here from the SSL error dialog
2986 if (fromShowSSLCertificateOnError) {
2987 // go back to the SSL error dialog
2988 showSSLCertificateOnError(
2989 mSSLCertificateOnErrorView,
2990 mSSLCertificateOnErrorHandler,
2991 mSSLCertificateOnErrorError);
2996 // if we have a main top-level page SSL certificate set or a certificate
2998 if (fromShowSSLCertificateOnError ||
2999 (view != null && view.getCertificate() != null)) {
3000 // add a 'View Certificate' button
3001 alertDialogBuilder.setNeutralButton(
3002 R.string.view_certificate,
3003 new DialogInterface.OnClickListener() {
3004 public void onClick(DialogInterface dialog,
3006 mPageInfoDialog = null;
3007 mPageInfoView = null;
3009 // if we came here from the SSL error dialog
3010 if (fromShowSSLCertificateOnError) {
3011 // go back to the SSL error dialog
3012 showSSLCertificateOnError(
3013 mSSLCertificateOnErrorView,
3014 mSSLCertificateOnErrorHandler,
3015 mSSLCertificateOnErrorError);
3017 // otherwise, display the top-most certificate from
3019 if (view.getCertificate() != null) {
3020 showSSLCertificate(tab);
3027 mPageInfoDialog = alertDialogBuilder.show();
3031 * Displays the main top-level page SSL certificate dialog
3032 * (accessible from the Page-Info dialog).
3033 * @param tab The tab to show certificate for.
3035 private void showSSLCertificate(final Tab tab) {
3036 final View certificateView =
3037 inflateCertificateView(tab.getWebView().getCertificate());
3038 if (certificateView == null) {
3042 LayoutInflater factory = LayoutInflater.from(this);
3044 final LinearLayout placeholder =
3045 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3047 LinearLayout ll = (LinearLayout) factory.inflate(
3048 R.layout.ssl_success, placeholder);
3049 ((TextView)ll.findViewById(R.id.success))
3050 .setText(R.string.ssl_certificate_is_valid);
3052 mSSLCertificateView = tab;
3053 mSSLCertificateDialog =
3054 new AlertDialog.Builder(this)
3055 .setTitle(R.string.ssl_certificate).setIcon(
3056 R.drawable.ic_dialog_browser_certificate_secure)
3057 .setView(certificateView)
3058 .setPositiveButton(R.string.ok,
3059 new DialogInterface.OnClickListener() {
3060 public void onClick(DialogInterface dialog,
3062 mSSLCertificateDialog = null;
3063 mSSLCertificateView = null;
3065 showPageInfo(tab, false);
3068 .setOnCancelListener(
3069 new DialogInterface.OnCancelListener() {
3070 public void onCancel(DialogInterface dialog) {
3071 mSSLCertificateDialog = null;
3072 mSSLCertificateView = null;
3074 showPageInfo(tab, false);
3081 * Displays the SSL error certificate dialog.
3082 * @param view The target web-view.
3083 * @param handler The SSL error handler responsible for cancelling the
3084 * connection that resulted in an SSL error or proceeding per user request.
3085 * @param error The SSL error object.
3087 void showSSLCertificateOnError(
3088 final WebView view, final SslErrorHandler handler, final SslError error) {
3090 final View certificateView =
3091 inflateCertificateView(error.getCertificate());
3092 if (certificateView == null) {
3096 LayoutInflater factory = LayoutInflater.from(this);
3098 final LinearLayout placeholder =
3099 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3101 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3102 LinearLayout ll = (LinearLayout)factory
3103 .inflate(R.layout.ssl_warning, placeholder);
3104 ((TextView)ll.findViewById(R.id.warning))
3105 .setText(R.string.ssl_untrusted);
3108 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3109 LinearLayout ll = (LinearLayout)factory
3110 .inflate(R.layout.ssl_warning, placeholder);
3111 ((TextView)ll.findViewById(R.id.warning))
3112 .setText(R.string.ssl_mismatch);
3115 if (error.hasError(SslError.SSL_EXPIRED)) {
3116 LinearLayout ll = (LinearLayout)factory
3117 .inflate(R.layout.ssl_warning, placeholder);
3118 ((TextView)ll.findViewById(R.id.warning))
3119 .setText(R.string.ssl_expired);
3122 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3123 LinearLayout ll = (LinearLayout)factory
3124 .inflate(R.layout.ssl_warning, placeholder);
3125 ((TextView)ll.findViewById(R.id.warning))
3126 .setText(R.string.ssl_not_yet_valid);
3129 mSSLCertificateOnErrorHandler = handler;
3130 mSSLCertificateOnErrorView = view;
3131 mSSLCertificateOnErrorError = error;
3132 mSSLCertificateOnErrorDialog =
3133 new AlertDialog.Builder(this)
3134 .setTitle(R.string.ssl_certificate).setIcon(
3135 R.drawable.ic_dialog_browser_certificate_partially_secure)
3136 .setView(certificateView)
3137 .setPositiveButton(R.string.ok,
3138 new DialogInterface.OnClickListener() {
3139 public void onClick(DialogInterface dialog,
3141 mSSLCertificateOnErrorDialog = null;
3142 mSSLCertificateOnErrorView = null;
3143 mSSLCertificateOnErrorHandler = null;
3144 mSSLCertificateOnErrorError = null;
3146 view.getWebViewClient().onReceivedSslError(
3147 view, handler, error);
3150 .setNeutralButton(R.string.page_info_view,
3151 new DialogInterface.OnClickListener() {
3152 public void onClick(DialogInterface dialog,
3154 mSSLCertificateOnErrorDialog = null;
3156 // do not clear the dialog state: we will
3157 // need to show the dialog again once the
3158 // user is done exploring the page-info details
3160 showPageInfo(mTabControl.getTabFromView(view),
3164 .setOnCancelListener(
3165 new DialogInterface.OnCancelListener() {
3166 public void onCancel(DialogInterface dialog) {
3167 mSSLCertificateOnErrorDialog = null;
3168 mSSLCertificateOnErrorView = null;
3169 mSSLCertificateOnErrorHandler = null;
3170 mSSLCertificateOnErrorError = null;
3172 view.getWebViewClient().onReceivedSslError(
3173 view, handler, error);
3180 * Inflates the SSL certificate view (helper method).
3181 * @param certificate The SSL certificate.
3182 * @return The resultant certificate view with issued-to, issued-by,
3183 * issued-on, expires-on, and possibly other fields set.
3184 * If the input certificate is null, returns null.
3186 private View inflateCertificateView(SslCertificate certificate) {
3187 if (certificate == null) {
3191 LayoutInflater factory = LayoutInflater.from(this);
3193 View certificateView = factory.inflate(
3194 R.layout.ssl_certificate, null);
3197 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3198 if (issuedTo != null) {
3199 ((TextView) certificateView.findViewById(R.id.to_common))
3200 .setText(issuedTo.getCName());
3201 ((TextView) certificateView.findViewById(R.id.to_org))
3202 .setText(issuedTo.getOName());
3203 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3204 .setText(issuedTo.getUName());
3208 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3209 if (issuedBy != null) {
3210 ((TextView) certificateView.findViewById(R.id.by_common))
3211 .setText(issuedBy.getCName());
3212 ((TextView) certificateView.findViewById(R.id.by_org))
3213 .setText(issuedBy.getOName());
3214 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3215 .setText(issuedBy.getUName());
3219 String issuedOn = reformatCertificateDate(
3220 certificate.getValidNotBefore());
3221 ((TextView) certificateView.findViewById(R.id.issued_on))
3225 String expiresOn = reformatCertificateDate(
3226 certificate.getValidNotAfter());
3227 ((TextView) certificateView.findViewById(R.id.expires_on))
3228 .setText(expiresOn);
3230 return certificateView;
3234 * Re-formats the certificate date (Date.toString()) string to
3235 * a properly localized date string.
3236 * @return Properly localized version of the certificate date string and
3237 * the original certificate date string if fails to localize.
3238 * If the original string is null, returns an empty string "".
3240 private String reformatCertificateDate(String certificateDate) {
3241 String reformattedDate = null;
3243 if (certificateDate != null) {
3246 date = java.text.DateFormat.getInstance().parse(certificateDate);
3247 } catch (ParseException e) {
3253 DateFormat.getDateFormat(this).format(date);
3257 return reformattedDate != null ? reformattedDate :
3258 (certificateDate != null ? certificateDate : "");
3262 * Displays an http-authentication dialog.
3264 void showHttpAuthentication(final HttpAuthHandler handler,
3265 final String host, final String realm, final String title,
3266 final String name, final String password, int focusId) {
3267 LayoutInflater factory = LayoutInflater.from(this);
3268 final View v = factory
3269 .inflate(R.layout.http_authentication, null);
3271 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3273 if (password != null) {
3274 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3277 String titleText = title;
3278 if (titleText == null) {
3279 titleText = getText(R.string.sign_in_to).toString().replace(
3280 "%s1", host).replace("%s2", realm);
3283 mHttpAuthHandler = handler;
3284 AlertDialog dialog = new AlertDialog.Builder(this)
3285 .setTitle(titleText)
3286 .setIcon(android.R.drawable.ic_dialog_alert)
3288 .setPositiveButton(R.string.action,
3289 new DialogInterface.OnClickListener() {
3290 public void onClick(DialogInterface dialog,
3292 String nm = ((EditText) v
3293 .findViewById(R.id.username_edit))
3294 .getText().toString();
3295 String pw = ((EditText) v
3296 .findViewById(R.id.password_edit))
3297 .getText().toString();
3298 BrowserActivity.this.setHttpAuthUsernamePassword
3299 (host, realm, nm, pw);
3300 handler.proceed(nm, pw);
3301 mHttpAuthenticationDialog = null;
3302 mHttpAuthHandler = null;
3304 .setNegativeButton(R.string.cancel,
3305 new DialogInterface.OnClickListener() {
3306 public void onClick(DialogInterface dialog,
3309 BrowserActivity.this.resetTitleAndRevertLockIcon();
3310 mHttpAuthenticationDialog = null;
3311 mHttpAuthHandler = null;
3313 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3314 public void onCancel(DialogInterface dialog) {
3316 BrowserActivity.this.resetTitleAndRevertLockIcon();
3317 mHttpAuthenticationDialog = null;
3318 mHttpAuthHandler = null;
3321 // Make the IME appear when the dialog is displayed if applicable.
3322 dialog.getWindow().setSoftInputMode(
3323 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3326 dialog.findViewById(focusId).requestFocus();
3328 v.findViewById(R.id.username_edit).requestFocus();
3330 mHttpAuthenticationDialog = dialog;
3333 public int getProgress() {
3334 WebView w = mTabControl.getCurrentWebView();
3336 return w.getProgress();
3343 * Set HTTP authentication password.
3345 * @param host The host for the password
3346 * @param realm The realm for the password
3347 * @param username The username for the password. If it is null, it means
3348 * password can't be saved.
3349 * @param password The password
3351 public void setHttpAuthUsernamePassword(String host, String realm,
3354 WebView w = mTabControl.getCurrentWebView();
3356 w.setHttpAuthUsernamePassword(host, realm, username, password);
3361 * connectivity manager says net has come or gone... inform the user
3362 * @param up true if net has come up, false if net has gone down
3364 public void onNetworkToggle(boolean up) {
3365 if (up == mIsNetworkUp) {
3368 mIsNetworkUp = true;
3369 if (mAlertDialog != null) {
3370 mAlertDialog.cancel();
3371 mAlertDialog = null;
3374 mIsNetworkUp = false;
3376 createAndShowNetworkDialog();
3379 WebView w = mTabControl.getCurrentWebView();
3381 w.setNetworkAvailable(up);
3385 boolean isNetworkUp() {
3386 return mIsNetworkUp;
3389 // This method shows the network dialog alerting the user that the net is
3390 // down. It will only show the dialog if mAlertDialog is null.
3391 private void createAndShowNetworkDialog() {
3392 if (mAlertDialog == null) {
3393 mAlertDialog = new AlertDialog.Builder(this)
3394 .setTitle(R.string.loadSuspendedTitle)
3395 .setMessage(R.string.loadSuspended)
3396 .setPositiveButton(R.string.ok, null)
3402 protected void onActivityResult(int requestCode, int resultCode,
3404 if (getTopWindow() == null) return;
3406 switch (requestCode) {
3408 if (resultCode == RESULT_OK && intent != null) {
3409 String data = intent.getAction();
3410 Bundle extras = intent.getExtras();
3411 if (extras != null && extras.getBoolean("new_window", false)) {
3414 final Tab currentTab =
3415 mTabControl.getCurrentTab();
3416 dismissSubWindow(currentTab);
3417 if (data != null && data.length() != 0) {
3418 getTopWindow().loadUrl(data);
3422 // Deliberately fall through to PREFERENCES_PAGE, since the
3423 // same extra may be attached to the COMBO_PAGE
3424 case PREFERENCES_PAGE:
3425 if (resultCode == RESULT_OK && intent != null) {
3426 String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3427 if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3428 mTabControl.removeParentChildRelationShips();
3432 // Choose a file from the file picker.
3434 if (null == mUploadMessage) break;
3435 Uri result = intent == null || resultCode != RESULT_OK ? null
3437 mUploadMessage.onReceiveValue(result);
3438 mUploadMessage = null;
3443 getTopWindow().requestFocus();
3447 * This method is called as a result of the user selecting the options
3448 * menu to see the download window, or when a download changes state. It
3449 * shows the download window ontop of the current window.
3451 /* package */ void viewDownloads(Uri downloadRecord) {
3452 Intent intent = new Intent(this,
3453 BrowserDownloadPage.class);
3454 intent.setData(downloadRecord);
3455 startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3461 * @param startWithHistory If true, open starting on the history tab.
3462 * Otherwise, start with the bookmarks tab.
3464 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3465 WebView current = mTabControl.getCurrentWebView();
3466 if (current == null) {
3469 Intent intent = new Intent(this,
3470 CombinedBookmarkHistoryActivity.class);
3471 String title = current.getTitle();
3472 String url = current.getUrl();
3473 Bitmap thumbnail = createScreenshot(current);
3475 // Just in case the user opens bookmarks before a page finishes loading
3476 // so the current history item, and therefore the page, is null.
3478 url = mLastEnteredUrl;
3481 url = mSettings.getHomePage();
3484 // In case the web page has not yet received its associated title.
3485 if (title == null) {
3488 intent.putExtra("title", title);
3489 intent.putExtra("url", url);
3490 intent.putExtra("thumbnail", thumbnail);
3491 // Disable opening in a new window if we have maxed out the windows
3492 intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3493 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3494 if (startWithHistory) {
3495 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3496 CombinedBookmarkHistoryActivity.HISTORY_TAB);
3498 startActivityForResult(intent, COMBO_PAGE);
3501 // Called when loading from context menu or LOAD_URL message
3502 private void loadURL(WebView view, String url) {
3503 // In case the user enters nothing.
3504 if (url != null && url.length() != 0 && view != null) {
3505 url = smartUrlFilter(url);
3506 if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3512 private String smartUrlFilter(Uri inUri) {
3513 if (inUri != null) {
3514 return smartUrlFilter(inUri.toString());
3519 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3520 "(?i)" + // switch on case insensitive matching
3521 "(" + // begin group for schema
3522 "(?:http|https|file):\\/\\/" +
3523 "|(?:inline|data|about|content|javascript):" +
3528 * Attempts to determine whether user input is a URL or search
3529 * terms. Anything with a space is passed to search.
3531 * Converts to lowercase any mistakenly uppercased schema (i.e.,
3532 * "Http://" converts to "http://"
3534 * @return Original or modified URL
3537 String smartUrlFilter(String url) {
3539 String inUrl = url.trim();
3540 boolean hasSpace = inUrl.indexOf(' ') != -1;
3542 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3543 if (matcher.matches()) {
3544 // force scheme to lowercase
3545 String scheme = matcher.group(1);
3546 String lcScheme = scheme.toLowerCase();
3547 if (!lcScheme.equals(scheme)) {
3548 inUrl = lcScheme + matcher.group(2);
3551 inUrl = inUrl.replace(" ", "%20");
3556 // FIXME: Is this the correct place to add to searches?
3557 // what if someone else calls this function?
3558 int shortcut = parseUrlShortcut(inUrl);
3559 if (shortcut != SHORTCUT_INVALID) {
3560 Browser.addSearchUrl(mResolver, inUrl);
3561 String query = inUrl.substring(2);
3563 case SHORTCUT_GOOGLE_SEARCH:
3564 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3565 case SHORTCUT_WIKIPEDIA_SEARCH:
3566 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3567 case SHORTCUT_DICTIONARY_SEARCH:
3568 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3569 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3570 // FIXME: we need location in this case
3571 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3575 if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3576 return URLUtil.guessUrl(inUrl);
3580 Browser.addSearchUrl(mResolver, inUrl);
3581 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3584 /* package */ void setShouldShowErrorConsole(boolean flag) {
3585 if (flag == mShouldShowErrorConsole) {
3590 mShouldShowErrorConsole = flag;
3592 ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3593 .getErrorConsole(true);
3596 // Setting the show state of the console will cause it's the layout to be inflated.
3597 if (errorConsole.numberOfErrors() > 0) {
3598 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3600 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3603 // Now we can add it to the main view.
3604 mErrorConsoleContainer.addView(errorConsole,
3605 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3606 ViewGroup.LayoutParams.WRAP_CONTENT));
3608 mErrorConsoleContainer.removeView(errorConsole);
3613 boolean shouldShowErrorConsole() {
3614 return mShouldShowErrorConsole;
3617 private void setStatusBarVisibility(boolean visible) {
3618 int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3619 getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3622 final static int LOCK_ICON_UNSECURE = 0;
3623 final static int LOCK_ICON_SECURE = 1;
3624 final static int LOCK_ICON_MIXED = 2;
3626 private BrowserSettings mSettings;
3627 private TabControl mTabControl;
3628 private ContentResolver mResolver;
3629 private FrameLayout mContentView;
3630 private View mCustomView;
3631 private FrameLayout mCustomViewContainer;
3632 private WebChromeClient.CustomViewCallback mCustomViewCallback;
3634 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3635 // view, we should rewrite this.
3636 private int mCurrentMenuState = 0;
3637 private int mMenuState = R.id.MAIN_MENU;
3638 private int mOldMenuState = EMPTY_MENU;
3639 private static final int EMPTY_MENU = -1;
3642 private FindDialog mFindDialog;
3643 // Used to prevent chording to result in firing two shortcuts immediately
3644 // one after another. Fixes bug 1211714.
3647 private boolean mInLoad;
3648 private boolean mIsNetworkUp;
3649 private boolean mDidStopLoad;
3651 private boolean mActivityInPause = true;
3653 private boolean mMenuIsDown;
3655 private static boolean mInTrace;
3657 // Performance probe
3658 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3659 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3660 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3661 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3662 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3663 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3664 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3665 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3666 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
3669 private long mStart;
3670 private long mProcessStart;
3671 private long mUserStart;
3672 private long mSystemStart;
3673 private long mIdleStart;
3674 private long mIrqStart;
3676 private long mUiStart;
3678 private Drawable mMixLockIcon;
3679 private Drawable mSecLockIcon;
3681 /* hold a ref so we can auto-cancel if necessary */
3682 private AlertDialog mAlertDialog;
3684 // Wait for credentials before loading google.com
3685 private ProgressDialog mCredsDlg;
3687 // The up-to-date URL and title (these can be different from those stored
3688 // in WebView, since it takes some time for the information in WebView to
3690 private String mUrl;
3691 private String mTitle;
3693 // As PageInfo has different style for landscape / portrait, we have
3694 // to re-open it when configuration changed
3695 private AlertDialog mPageInfoDialog;
3696 private Tab mPageInfoView;
3697 // If the Page-Info dialog is launched from the SSL-certificate-on-error
3698 // dialog, we should not just dismiss it, but should get back to the
3699 // SSL-certificate-on-error dialog. This flag is used to store this state
3700 private boolean mPageInfoFromShowSSLCertificateOnError;
3702 // as SSLCertificateOnError has different style for landscape / portrait,
3703 // we have to re-open it when configuration changed
3704 private AlertDialog mSSLCertificateOnErrorDialog;
3705 private WebView mSSLCertificateOnErrorView;
3706 private SslErrorHandler mSSLCertificateOnErrorHandler;
3707 private SslError mSSLCertificateOnErrorError;
3709 // as SSLCertificate has different style for landscape / portrait, we
3710 // have to re-open it when configuration changed
3711 private AlertDialog mSSLCertificateDialog;
3712 private Tab mSSLCertificateView;
3714 // as HttpAuthentication has different style for landscape / portrait, we
3715 // have to re-open it when configuration changed
3716 private AlertDialog mHttpAuthenticationDialog;
3717 private HttpAuthHandler mHttpAuthHandler;
3719 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3720 new FrameLayout.LayoutParams(
3721 ViewGroup.LayoutParams.MATCH_PARENT,
3722 ViewGroup.LayoutParams.MATCH_PARENT);
3723 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3724 new FrameLayout.LayoutParams(
3725 ViewGroup.LayoutParams.MATCH_PARENT,
3726 ViewGroup.LayoutParams.MATCH_PARENT,
3729 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3731 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3732 // Dictionary search
3733 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3734 // Google Mobile Local search
3735 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3737 final static String QUERY_PLACE_HOLDER = "%s";
3739 // "source" parameter for Google search through search key
3740 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3741 // "source" parameter for Google search through goto menu
3742 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3743 // "source" parameter for Google search through simplily type
3744 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3745 // "source" parameter for Google search suggested by the browser
3746 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3747 // "source" parameter for Google search from unknown source
3748 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3750 private final static String LOGTAG = "browser";
3752 private String mLastEnteredUrl;
3754 private PowerManager.WakeLock mWakeLock;
3755 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3757 private Toast mStopToast;
3759 private TitleBar mTitleBar;
3761 private LinearLayout mErrorConsoleContainer = null;
3762 private boolean mShouldShowErrorConsole = false;
3764 // As the ids are dynamically created, we can't guarantee that they will
3765 // be in sequence, so this static array maps ids to a window number.
3766 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3767 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3768 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3769 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3771 // monitor platform changes
3772 private IntentFilter mNetworkStateChangedFilter;
3773 private BroadcastReceiver mNetworkStateIntentReceiver;
3775 private BroadcastReceiver mPackageInstallationReceiver;
3777 // activity requestCode
3778 final static int COMBO_PAGE = 1;
3779 final static int DOWNLOAD_PAGE = 2;
3780 final static int PREFERENCES_PAGE = 3;
3781 final static int FILE_SELECTED = 4;
3783 // the default <video> poster
3784 private Bitmap mDefaultVideoPoster;
3785 // the video progress view
3786 private View mVideoProgressView;
3789 * A UrlData class to abstract how the content will be set to WebView.
3790 * This base class uses loadUrl to show the content.
3792 private static class UrlData {
3796 UrlData(String url) {
3800 void setPostData(byte[] postData) {
3801 mPostData = postData;
3805 return mUrl == null || mUrl.length() == 0;
3808 public void loadIn(WebView webView) {
3809 if (mPostData != null) {
3810 webView.postUrl(mUrl, mPostData);
3812 webView.loadUrl(mUrl);
3818 * A subclass of UrlData class that can display inlined content using
3819 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3821 private static class InlinedUrlData extends UrlData {
3822 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3825 mMimeType = mimeType;
3826 mEncoding = encoding;
3833 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
3837 public void loadIn(WebView webView) {
3838 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3842 /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);