OSDN Git Service

am 8fa17c4f: (-s ours) am 79f107bd: Do not merge
[android-x86/packages-apps-Browser.git] / src / com / android / browser / BrowserActivity.java
1 /*
2  * Copyright (C) 2006 The Android Open Source Project
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package com.android.browser;
18
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.database.DatabaseUtils;
40 import android.graphics.Bitmap;
41 import android.graphics.BitmapFactory;
42 import android.graphics.Canvas;
43 import android.graphics.Picture;
44 import android.graphics.PixelFormat;
45 import android.graphics.Rect;
46 import android.graphics.drawable.Drawable;
47 import android.net.ConnectivityManager;
48 import android.net.NetworkInfo;
49 import android.net.Uri;
50 import android.net.WebAddress;
51 import android.net.http.SslCertificate;
52 import android.net.http.SslError;
53 import android.os.AsyncTask;
54 import android.os.Bundle;
55 import android.os.Debug;
56 import android.os.Environment;
57 import android.os.Handler;
58 import android.os.Message;
59 import android.os.PowerManager;
60 import android.os.Process;
61 import android.os.ServiceManager;
62 import android.os.SystemClock;
63 import android.provider.Browser;
64 import android.provider.ContactsContract;
65 import android.provider.ContactsContract.Intents.Insert;
66 import android.provider.Downloads;
67 import android.provider.MediaStore;
68 import android.text.IClipboard;
69 import android.text.TextUtils;
70 import android.text.format.DateFormat;
71 import android.util.AttributeSet;
72 import android.util.Log;
73 import android.view.ContextMenu;
74 import android.view.Gravity;
75 import android.view.KeyEvent;
76 import android.view.LayoutInflater;
77 import android.view.Menu;
78 import android.view.MenuInflater;
79 import android.view.MenuItem;
80 import android.view.View;
81 import android.view.ViewGroup;
82 import android.view.Window;
83 import android.view.WindowManager;
84 import android.view.ContextMenu.ContextMenuInfo;
85 import android.view.MenuItem.OnMenuItemClickListener;
86 import android.webkit.CookieManager;
87 import android.webkit.CookieSyncManager;
88 import android.webkit.DownloadListener;
89 import android.webkit.HttpAuthHandler;
90 import android.webkit.PluginManager;
91 import android.webkit.SslErrorHandler;
92 import android.webkit.URLUtil;
93 import android.webkit.ValueCallback;
94 import android.webkit.WebChromeClient;
95 import android.webkit.WebHistoryItem;
96 import android.webkit.WebIconDatabase;
97 import android.webkit.WebView;
98 import android.widget.EditText;
99 import android.widget.FrameLayout;
100 import android.widget.LinearLayout;
101 import android.widget.TextView;
102 import android.widget.Toast;
103 import android.accounts.Account;
104 import android.accounts.AccountManager;
105 import android.accounts.AccountManagerFuture;
106 import android.accounts.AuthenticatorException;
107 import android.accounts.OperationCanceledException;
108 import android.accounts.AccountManagerCallback;
109
110 import com.android.common.Patterns;
111
112 import com.google.android.gsf.GoogleLoginServiceConstants;
113
114 import java.io.ByteArrayOutputStream;
115 import java.io.File;
116 import java.io.IOException;
117 import java.io.InputStream;
118 import java.net.MalformedURLException;
119 import java.net.URI;
120 import java.net.URISyntaxException;
121 import java.net.URL;
122 import java.net.URLEncoder;
123 import java.text.ParseException;
124 import java.util.Date;
125 import java.util.HashMap;
126 import java.util.regex.Matcher;
127 import java.util.regex.Pattern;
128
129 public class BrowserActivity extends Activity
130     implements View.OnCreateContextMenuListener, DownloadListener,
131         AccountManagerCallback<Account[]> {
132
133     /* Define some aliases to make these debugging flags easier to refer to.
134      * This file imports android.provider.Browser, so we can't just refer to "Browser.DEBUG".
135      */
136     private final static boolean DEBUG = com.android.browser.Browser.DEBUG;
137     private final static boolean LOGV_ENABLED = com.android.browser.Browser.LOGV_ENABLED;
138     private final static boolean LOGD_ENABLED = com.android.browser.Browser.LOGD_ENABLED;
139
140     // These are single-character shortcuts for searching popular sources.
141     private static final int SHORTCUT_INVALID = 0;
142     private static final int SHORTCUT_GOOGLE_SEARCH = 1;
143     private static final int SHORTCUT_WIKIPEDIA_SEARCH = 2;
144     private static final int SHORTCUT_DICTIONARY_SEARCH = 3;
145     private static final int SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH = 4;
146
147     private Account[] mAccountsGoogle;
148     private Account[] mAccountsPreferHosted;
149
150     private void startReadOfGoogleAccounts() {
151         mAccountsGoogle = null;
152         mAccountsPreferHosted = null;
153
154         AccountManager.get(this).getAccountsByTypeAndFeatures(
155                 GoogleLoginServiceConstants.ACCOUNT_TYPE,
156                 new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_HOSTED_OR_GOOGLE},
157                 this, null);
158     }
159
160     /** This implements AccountManagerCallback<Account[]> */
161     public void run(AccountManagerFuture<Account[]> accountManagerFuture) {
162         try {
163             if (mAccountsGoogle == null) {
164                 mAccountsGoogle = accountManagerFuture.getResult();
165
166                 AccountManager.get(this).getAccountsByTypeAndFeatures(
167                         GoogleLoginServiceConstants.ACCOUNT_TYPE,
168                         new String[]{GoogleLoginServiceConstants.FEATURE_LEGACY_GOOGLE},
169                         this, null);
170             } else {
171                 mAccountsPreferHosted = accountManagerFuture.getResult();
172                 setupHomePage();
173             }
174         } catch (OperationCanceledException e) {
175             setupHomePage();
176         } catch (IOException e) {
177             setupHomePage();
178         } catch (AuthenticatorException e) {
179             setupHomePage();
180         }
181     }
182
183     private void setupHomePage() {
184         // get the default home page
185         String homepage = mSettings.getHomePage();
186
187         if (mAccountsPreferHosted != null && mAccountsGoogle != null) {
188             // three cases:
189             //
190             //   hostedUser == googleUser
191             //      The device has only a google account
192             //
193             //   hostedUser != googleUser
194             //      The device has a hosted account and a google account
195             //
196             //   hostedUser != null, googleUser == null
197             //      The device has only a hosted account (so far)
198             String hostedUser = mAccountsPreferHosted.length == 0 
199                     ? null
200                     : mAccountsPreferHosted[0].name;
201             String googleUser = mAccountsGoogle.length == 0 ? null : mAccountsGoogle[0].name;
202
203             // developers might have no accounts at all
204             if (hostedUser == null) return;
205
206             if (googleUser == null || !hostedUser.equals(googleUser)) {
207                 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
208                 homepage = homepage.replace("?", "/a/" + domain + "?");
209             }
210         }
211
212         mSettings.setHomePage(BrowserActivity.this, homepage);
213         resumeAfterCredentials();
214     }
215
216     private static class ClearThumbnails extends AsyncTask<File, Void, Void> {
217         @Override
218         public Void doInBackground(File... files) {
219             if (files != null) {
220                 for (File f : files) {
221                     if (!f.delete()) {
222                       Log.e(LOGTAG, f.getPath() + " was not deleted");
223                     }
224                 }
225             }
226             return null;
227         }
228     }
229
230     /**
231      * This layout holds everything you see below the status bar, including the
232      * error console, the custom view container, and the webviews.
233      */
234     private FrameLayout mBrowserFrameLayout;
235
236     @Override
237     public void onCreate(Bundle icicle) {
238         if (LOGV_ENABLED) {
239             Log.v(LOGTAG, this + " onStart");
240         }
241         super.onCreate(icicle);
242         // test the browser in OpenGL
243         // requestWindowFeature(Window.FEATURE_OPENGL);
244
245         setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
246
247         mResolver = getContentResolver();
248
249         // If this was a web search request, pass it on to the default web
250         // search provider and finish this activity.
251         if (handleWebSearchIntent(getIntent())) {
252             finish();
253             return;
254         }
255
256         mSecLockIcon = Resources.getSystem().getDrawable(
257                 android.R.drawable.ic_secure);
258         mMixLockIcon = Resources.getSystem().getDrawable(
259                 android.R.drawable.ic_partial_secure);
260
261         FrameLayout frameLayout = (FrameLayout) getWindow().getDecorView()
262                 .findViewById(com.android.internal.R.id.content);
263         mBrowserFrameLayout = (FrameLayout) LayoutInflater.from(this)
264                 .inflate(R.layout.custom_screen, null);
265         mContentView = (FrameLayout) mBrowserFrameLayout.findViewById(
266                 R.id.main_content);
267         mErrorConsoleContainer = (LinearLayout) mBrowserFrameLayout
268                 .findViewById(R.id.error_console);
269         mCustomViewContainer = (FrameLayout) mBrowserFrameLayout
270                 .findViewById(R.id.fullscreen_custom_content);
271         frameLayout.addView(mBrowserFrameLayout, COVER_SCREEN_PARAMS);
272         mTitleBar = new TitleBar(this);
273         mFakeTitleBar = new TitleBar(this);
274
275         // Create the tab control and our initial tab
276         mTabControl = new TabControl(this);
277
278         // Open the icon database and retain all the bookmark urls for favicons
279         retainIconsOnStartup();
280
281         // Keep a settings instance handy.
282         mSettings = BrowserSettings.getInstance();
283         mSettings.setTabControl(mTabControl);
284         mSettings.loadFromDb(this);
285
286         PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
287         mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
288
289         /* enables registration for changes in network status from
290            http stack */
291         mNetworkStateChangedFilter = new IntentFilter();
292         mNetworkStateChangedFilter.addAction(
293                 ConnectivityManager.CONNECTIVITY_ACTION);
294         mNetworkStateIntentReceiver = new BroadcastReceiver() {
295                 @Override
296                 public void onReceive(Context context, Intent intent) {
297                     if (intent.getAction().equals(
298                             ConnectivityManager.CONNECTIVITY_ACTION)) {
299                         boolean noConnectivity = intent.getBooleanExtra(
300                                 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
301                         if (!noConnectivity) {
302                             NetworkInfo info = intent.getParcelableExtra(
303                                     ConnectivityManager.EXTRA_NETWORK_INFO);
304                             String typeName = info.getTypeName();
305                             String subtypeName = info.getSubtypeName();
306                             sendNetworkType(typeName.toLowerCase(),
307                                     (subtypeName != null ? subtypeName.toLowerCase() : ""));
308                         }
309                         onNetworkToggle(!noConnectivity);
310                     }
311                 }
312             };
313
314         IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
315         filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
316         filter.addDataScheme("package");
317         mPackageInstallationReceiver = new BroadcastReceiver() {
318             @Override
319             public void onReceive(Context context, Intent intent) {
320                 final String action = intent.getAction();
321                 final String packageName = intent.getData()
322                         .getSchemeSpecificPart();
323                 final boolean replacing = intent.getBooleanExtra(
324                         Intent.EXTRA_REPLACING, false);
325                 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
326                     // if it is replacing, refreshPlugins() when adding
327                     return;
328                 }
329                 PackageManager pm = BrowserActivity.this.getPackageManager();
330                 PackageInfo pkgInfo = null;
331                 try {
332                     pkgInfo = pm.getPackageInfo(packageName,
333                             PackageManager.GET_PERMISSIONS);
334                 } catch (PackageManager.NameNotFoundException e) {
335                     return;
336                 }
337                 if (pkgInfo != null) {
338                     String permissions[] = pkgInfo.requestedPermissions;
339                     if (permissions == null) {
340                         return;
341                     }
342                     boolean permissionOk = false;
343                     for (String permit : permissions) {
344                         if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
345                             permissionOk = true;
346                             break;
347                         }
348                     }
349                     if (permissionOk) {
350                         PluginManager.getInstance(BrowserActivity.this)
351                                 .refreshPlugins(
352                                         Intent.ACTION_PACKAGE_ADDED
353                                                 .equals(action));
354                     }
355                 }
356             }
357         };
358         registerReceiver(mPackageInstallationReceiver, filter);
359
360         if (!mTabControl.restoreState(icicle)) {
361             // clear up the thumbnail directory if we can't restore the state as
362             // none of the files in the directory are referenced any more.
363             new ClearThumbnails().execute(
364                     mTabControl.getThumbnailDir().listFiles());
365             // there is no quit on Android. But if we can't restore the state,
366             // we can treat it as a new Browser, remove the old session cookies.
367             CookieManager.getInstance().removeSessionCookie();
368             final Intent intent = getIntent();
369             final Bundle extra = intent.getExtras();
370             // Create an initial tab.
371             // If the intent is ACTION_VIEW and data is not null, the Browser is
372             // invoked to view the content by another application. In this case,
373             // the tab will be close when exit.
374             UrlData urlData = getUrlDataFromIntent(intent);
375
376             final Tab t = mTabControl.createNewTab(
377                     Intent.ACTION_VIEW.equals(intent.getAction()) &&
378                     intent.getData() != null,
379                     intent.getStringExtra(Browser.EXTRA_APPLICATION_ID), urlData.mUrl);
380             mTabControl.setCurrentTab(t);
381             attachTabToContentView(t);
382             WebView webView = t.getWebView();
383             if (extra != null) {
384                 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
385                 if (scale > 0 && scale <= 1000) {
386                     webView.setInitialScale(scale);
387                 }
388             }
389             // If we are not restoring from an icicle, then there is a high
390             // likely hood this is the first run. So, check to see if the
391             // homepage needs to be configured and copy any plugins from our
392             // asset directory to the data partition.
393             if ((extra == null || !extra.getBoolean("testing"))
394                     && !mSettings.isLoginInitialized()) {
395                 startReadOfGoogleAccounts();
396             }
397
398             if (urlData.isEmpty()) {
399                 if (mSettings.isLoginInitialized()) {
400                     webView.loadUrl(mSettings.getHomePage());
401                 } else {
402                     waitForCredentials();
403                 }
404             } else {
405                 if (extra != null) {
406                     urlData.setPostData(extra
407                             .getByteArray(Browser.EXTRA_POST_DATA));
408                 }
409                 urlData.loadIn(webView);
410             }
411         } else {
412             // TabControl.restoreState() will create a new tab even if
413             // restoring the state fails.
414             attachTabToContentView(mTabControl.getCurrentTab());
415         }
416
417         // Read JavaScript flags if it exists.
418         String jsFlags = mSettings.getJsFlags();
419         if (jsFlags.trim().length() != 0) {
420             mTabControl.getCurrentWebView().setJsFlags(jsFlags);
421         }
422     }
423
424     @Override
425     protected void onNewIntent(Intent intent) {
426         Tab current = mTabControl.getCurrentTab();
427         // When a tab is closed on exit, the current tab index is set to -1.
428         // Reset before proceed as Browser requires the current tab to be set.
429         if (current == null) {
430             // Try to reset the tab in case the index was incorrect.
431             current = mTabControl.getTab(0);
432             if (current == null) {
433                 // No tabs at all so just ignore this intent.
434                 return;
435             }
436             mTabControl.setCurrentTab(current);
437             attachTabToContentView(current);
438             resetTitleAndIcon(current.getWebView());
439         }
440         final String action = intent.getAction();
441         final int flags = intent.getFlags();
442         if (Intent.ACTION_MAIN.equals(action) ||
443                 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
444             // just resume the browser
445             return;
446         }
447         if (Intent.ACTION_VIEW.equals(action)
448                 || Intent.ACTION_SEARCH.equals(action)
449                 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
450                 || Intent.ACTION_WEB_SEARCH.equals(action)) {
451             // If this was a search request (e.g. search query directly typed into the address bar),
452             // pass it on to the default web search provider.
453             if (handleWebSearchIntent(intent)) {
454                 return;
455             }
456
457             UrlData urlData = getUrlDataFromIntent(intent);
458             if (urlData.isEmpty()) {
459                 urlData = new UrlData(mSettings.getHomePage());
460             }
461             urlData.setPostData(intent
462                     .getByteArrayExtra(Browser.EXTRA_POST_DATA));
463
464             final String appId = intent
465                     .getStringExtra(Browser.EXTRA_APPLICATION_ID);
466             if (Intent.ACTION_VIEW.equals(action)
467                     && !getPackageName().equals(appId)
468                     && (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
469                 Tab appTab = mTabControl.getTabFromId(appId);
470                 if (appTab != null) {
471                     Log.i(LOGTAG, "Reusing tab for " + appId);
472                     // Dismiss the subwindow if applicable.
473                     dismissSubWindow(appTab);
474                     // Since we might kill the WebView, remove it from the
475                     // content view first.
476                     removeTabFromContentView(appTab);
477                     // Recreate the main WebView after destroying the old one.
478                     // If the WebView has the same original url and is on that
479                     // page, it can be reused.
480                     boolean needsLoad =
481                             mTabControl.recreateWebView(appTab, urlData.mUrl);
482
483                     if (current != appTab) {
484                         switchToTab(mTabControl.getTabIndex(appTab));
485                         if (needsLoad) {
486                             urlData.loadIn(appTab.getWebView());
487                         }
488                     } else {
489                         // If the tab was the current tab, we have to attach
490                         // it to the view system again.
491                         attachTabToContentView(appTab);
492                         if (needsLoad) {
493                             urlData.loadIn(appTab.getWebView());
494                         }
495                     }
496                     return;
497                 } else {
498                     // No matching application tab, try to find a regular tab
499                     // with a matching url.
500                     appTab = mTabControl.findUnusedTabWithUrl(urlData.mUrl);
501                     if (appTab != null) {
502                         if (current != appTab) {
503                             switchToTab(mTabControl.getTabIndex(appTab));
504                         }
505                         // Otherwise, we are already viewing the correct tab.
506                     } else {
507                         // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url
508                         // will be opened in a new tab unless we have reached
509                         // MAX_TABS. Then the url will be opened in the current
510                         // tab. If a new tab is created, it will have "true" for
511                         // exit on close.
512                         openTabAndShow(urlData, true, appId);
513                     }
514                 }
515             } else {
516                 if (!urlData.isEmpty()
517                         && urlData.mUrl.startsWith("about:debug")) {
518                     if ("about:debug.dom".equals(urlData.mUrl)) {
519                         current.getWebView().dumpDomTree(false);
520                     } else if ("about:debug.dom.file".equals(urlData.mUrl)) {
521                         current.getWebView().dumpDomTree(true);
522                     } else if ("about:debug.render".equals(urlData.mUrl)) {
523                         current.getWebView().dumpRenderTree(false);
524                     } else if ("about:debug.render.file".equals(urlData.mUrl)) {
525                         current.getWebView().dumpRenderTree(true);
526                     } else if ("about:debug.display".equals(urlData.mUrl)) {
527                         current.getWebView().dumpDisplayTree();
528                     } else if (urlData.mUrl.startsWith("about:debug.drag")) {
529                         int index = urlData.mUrl.codePointAt(16) - '0';
530                         if (index <= 0 || index > 9) {
531                             current.getWebView().setDragTracker(null);
532                         } else {
533                             current.getWebView().setDragTracker(new MeshTracker(index));
534                         }
535                     } else {
536                         mSettings.toggleDebugSettings();
537                     }
538                     return;
539                 }
540                 // Get rid of the subwindow if it exists
541                 dismissSubWindow(current);
542                 urlData.loadIn(current.getWebView());
543             }
544         }
545     }
546
547     private int parseUrlShortcut(String url) {
548         if (url == null) return SHORTCUT_INVALID;
549
550         // FIXME: quick search, need to be customized by setting
551         if (url.length() > 2 && url.charAt(1) == ' ') {
552             switch (url.charAt(0)) {
553             case 'g': return SHORTCUT_GOOGLE_SEARCH;
554             case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
555             case 'd': return SHORTCUT_DICTIONARY_SEARCH;
556             case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
557             }
558         }
559         return SHORTCUT_INVALID;
560     }
561
562     /**
563      * Launches the default web search activity with the query parameters if the given intent's data
564      * are identified as plain search terms and not URLs/shortcuts.
565      * @return true if the intent was handled and web search activity was launched, false if not.
566      */
567     private boolean handleWebSearchIntent(Intent intent) {
568         if (intent == null) return false;
569
570         String url = null;
571         final String action = intent.getAction();
572         if (Intent.ACTION_VIEW.equals(action)) {
573             Uri data = intent.getData();
574             if (data != null) url = data.toString();
575         } else if (Intent.ACTION_SEARCH.equals(action)
576                 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
577                 || Intent.ACTION_WEB_SEARCH.equals(action)) {
578             url = intent.getStringExtra(SearchManager.QUERY);
579         }
580         return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA),
581                 intent.getStringExtra(SearchManager.EXTRA_DATA_KEY));
582     }
583
584     /**
585      * Launches the default web search activity with the query parameters if the given url string
586      * was identified as plain search terms and not URL/shortcut.
587      * @return true if the request was handled and web search activity was launched, false if not.
588      */
589     private boolean handleWebSearchRequest(String inUrl, Bundle appData, String extraData) {
590         if (inUrl == null) return false;
591
592         // In general, we shouldn't modify URL from Intent.
593         // But currently, we get the user-typed URL from search box as well.
594         String url = fixUrl(inUrl).trim();
595
596         // URLs and site specific search shortcuts are handled by the regular flow of control, so
597         // return early.
598         if (Patterns.WEB_URL.matcher(url).matches()
599                 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
600                 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
601             return false;
602         }
603
604         Browser.updateVisitedHistory(mResolver, url, false);
605         Browser.addSearchUrl(mResolver, url);
606
607         Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
608         intent.addCategory(Intent.CATEGORY_DEFAULT);
609         intent.putExtra(SearchManager.QUERY, url);
610         if (appData != null) {
611             intent.putExtra(SearchManager.APP_DATA, appData);
612         }
613         if (extraData != null) {
614             intent.putExtra(SearchManager.EXTRA_DATA_KEY, extraData);
615         }
616         intent.putExtra(Browser.EXTRA_APPLICATION_ID, getPackageName());
617         startActivity(intent);
618
619         return true;
620     }
621
622     private UrlData getUrlDataFromIntent(Intent intent) {
623         String url = null;
624         if (intent != null) {
625             final String action = intent.getAction();
626             if (Intent.ACTION_VIEW.equals(action)) {
627                 url = smartUrlFilter(intent.getData());
628                 if (url != null && url.startsWith("content:")) {
629                     /* Append mimetype so webview knows how to display */
630                     String mimeType = intent.resolveType(getContentResolver());
631                     if (mimeType != null) {
632                         url += "?" + mimeType;
633                     }
634                 }
635                 if ("inline:".equals(url)) {
636                     return new InlinedUrlData(
637                             intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
638                             intent.getType(),
639                             intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
640                             intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
641                 }
642             } else if (Intent.ACTION_SEARCH.equals(action)
643                     || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
644                     || Intent.ACTION_WEB_SEARCH.equals(action)) {
645                 url = intent.getStringExtra(SearchManager.QUERY);
646                 if (url != null) {
647                     mLastEnteredUrl = url;
648                     Browser.updateVisitedHistory(mResolver, url, false);
649                     // In general, we shouldn't modify URL from Intent.
650                     // But currently, we get the user-typed URL from search box as well.
651                     url = fixUrl(url);
652                     url = smartUrlFilter(url);
653                     String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
654                     if (url.contains(searchSource)) {
655                         String source = null;
656                         final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
657                         if (appData != null) {
658                             source = appData.getString(SearchManager.SOURCE);
659                         }
660                         if (TextUtils.isEmpty(source)) {
661                             source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
662                         }
663                         url = url.replace(searchSource, "&source=android-"+source+"&");
664                     }
665                 }
666             }
667         }
668         return new UrlData(url);
669     }
670
671     /* package */ static String fixUrl(String inUrl) {
672         // FIXME: Converting the url to lower case
673         // duplicates functionality in smartUrlFilter().
674         // However, changing all current callers of fixUrl to
675         // call smartUrlFilter in addition may have unwanted
676         // consequences, and is deferred for now.
677         int colon = inUrl.indexOf(':');
678         boolean allLower = true;
679         for (int index = 0; index < colon; index++) {
680             char ch = inUrl.charAt(index);
681             if (!Character.isLetter(ch)) {
682                 break;
683             }
684             allLower &= Character.isLowerCase(ch);
685             if (index == colon - 1 && !allLower) {
686                 inUrl = inUrl.substring(0, colon).toLowerCase()
687                         + inUrl.substring(colon);
688             }
689         }
690         if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
691             return inUrl;
692         if (inUrl.startsWith("http:") ||
693                 inUrl.startsWith("https:")) {
694             if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
695                 inUrl = inUrl.replaceFirst("/", "//");
696             } else inUrl = inUrl.replaceFirst(":", "://");
697         }
698         return inUrl;
699     }
700
701     @Override
702     protected void onResume() {
703         super.onResume();
704         if (LOGV_ENABLED) {
705             Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
706         }
707
708         if (!mActivityInPause) {
709             Log.e(LOGTAG, "BrowserActivity is already resumed.");
710             return;
711         }
712
713         mTabControl.resumeCurrentTab();
714         mActivityInPause = false;
715         resumeWebViewTimers();
716
717         if (mWakeLock.isHeld()) {
718             mHandler.removeMessages(RELEASE_WAKELOCK);
719             mWakeLock.release();
720         }
721
722         if (mCredsDlg != null) {
723             if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
724              // In case credential request never comes back
725                 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
726             }
727         }
728
729         registerReceiver(mNetworkStateIntentReceiver,
730                          mNetworkStateChangedFilter);
731         WebView.enablePlatformNotifications();
732     }
733
734     /**
735      * Since the actual title bar is embedded in the WebView, and removing it
736      * would change its appearance, use a different TitleBar to show overlayed
737      * at the top of the screen, when the menu is open or the page is loading.
738      */
739     private TitleBar mFakeTitleBar;
740
741     /**
742      * Holder for the fake title bar.  It will have a foreground shadow, as well
743      * as a white background, so the fake title bar looks like the real one.
744      */
745     private ViewGroup mFakeTitleBarHolder;
746
747     /**
748      * Layout parameters for the fake title bar within mFakeTitleBarHolder
749      */
750     private FrameLayout.LayoutParams mFakeTitleBarParams
751             = new FrameLayout.LayoutParams(
752             ViewGroup.LayoutParams.MATCH_PARENT,
753             ViewGroup.LayoutParams.WRAP_CONTENT);
754     /**
755      * Keeps track of whether the options menu is open.  This is important in
756      * determining whether to show or hide the title bar overlay.
757      */
758     private boolean mOptionsMenuOpen;
759
760     /**
761      * Only meaningful when mOptionsMenuOpen is true.  This variable keeps track
762      * of whether the configuration has changed.  The first onMenuOpened call
763      * after a configuration change is simply a reopening of the same menu
764      * (i.e. mIconView did not change).
765      */
766     private boolean mConfigChanged;
767
768     /**
769      * Whether or not the options menu is in its smaller, icon menu form.  When
770      * true, we want the title bar overlay to be up.  When false, we do not.
771      * Only meaningful if mOptionsMenuOpen is true.
772      */
773     private boolean mIconView;
774
775     @Override
776     public boolean onMenuOpened(int featureId, Menu menu) {
777         if (Window.FEATURE_OPTIONS_PANEL == featureId) {
778             if (mOptionsMenuOpen) {
779                 if (mConfigChanged) {
780                     // We do not need to make any changes to the state of the
781                     // title bar, since the only thing that happened was a
782                     // change in orientation
783                     mConfigChanged = false;
784                 } else {
785                     if (mIconView) {
786                         // Switching the menu to expanded view, so hide the
787                         // title bar.
788                         hideFakeTitleBar();
789                         mIconView = false;
790                     } else {
791                         // Switching the menu back to icon view, so show the
792                         // title bar once again.
793                         showFakeTitleBar();
794                         mIconView = true;
795                     }
796                 }
797             } else {
798                 // The options menu is closed, so open it, and show the title
799                 showFakeTitleBar();
800                 mOptionsMenuOpen = true;
801                 mConfigChanged = false;
802                 mIconView = true;
803             }
804         }
805         return true;
806     }
807
808     /**
809      * Special class used exclusively for the shadow drawn underneath the fake
810      * title bar.  The shadow does not need to be drawn if the WebView
811      * underneath is scrolled to the top, because it will draw directly on top
812      * of the embedded shadow.
813      */
814     private static class Shadow extends View {
815         private WebView mWebView;
816
817         public Shadow(Context context, AttributeSet attrs) {
818             super(context, attrs);
819         }
820
821         public void setWebView(WebView view) {
822             mWebView = view;
823         }
824
825         @Override
826         public void draw(Canvas canvas) {
827             // In general onDraw is the method to override, but we care about
828             // whether or not the background gets drawn, which happens in draw()
829             if (mWebView == null || mWebView.getScrollY() > getHeight()) {
830                 super.draw(canvas);
831             }
832             // Need to invalidate so that if the scroll position changes, we
833             // still draw as appropriate.
834             invalidate();
835         }
836     }
837
838     private void showFakeTitleBar() {
839         final View decor = getWindow().peekDecorView();
840         if (mFakeTitleBar.getParent() == null && mActiveTabsPage == null
841                 && !mActivityInPause && decor != null
842                 && decor.getWindowToken() != null) {
843             Rect visRect = new Rect();
844             if (!mBrowserFrameLayout.getGlobalVisibleRect(visRect)) {
845                 if (LOGD_ENABLED) {
846                     Log.d(LOGTAG, "showFakeTitleBar visRect failed");
847                 }
848                 return;
849             }
850
851             WindowManager manager
852                     = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
853
854             // Add the title bar to the window manager so it can receive touches
855             // while the menu is up
856             WindowManager.LayoutParams params
857                     = new WindowManager.LayoutParams(
858                     ViewGroup.LayoutParams.MATCH_PARENT,
859                     ViewGroup.LayoutParams.WRAP_CONTENT,
860                     WindowManager.LayoutParams.TYPE_APPLICATION_SUB_PANEL,
861                     WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
862                     PixelFormat.TRANSLUCENT);
863             params.gravity = Gravity.TOP;
864             WebView mainView = mTabControl.getCurrentWebView();
865             boolean atTop = mainView != null && mainView.getScrollY() == 0;
866             params.windowAnimations = atTop ? 0 : R.style.TitleBar;
867             // XXX : Without providing an offset, the fake title bar will be
868             // placed underneath the status bar.  Use the global visible rect
869             // of mBrowserFrameLayout to determine the bottom of the status bar
870             params.y = visRect.top;
871             // Add a holder for the title bar.  It also holds a shadow to show
872             // below the title bar.
873             if (mFakeTitleBarHolder == null) {
874                 mFakeTitleBarHolder = (ViewGroup) LayoutInflater.from(this)
875                     .inflate(R.layout.title_bar_bg, null);
876             }
877             Shadow shadow = (Shadow) mFakeTitleBarHolder.findViewById(
878                     R.id.shadow);
879             shadow.setWebView(mainView);
880             mFakeTitleBarHolder.addView(mFakeTitleBar, 0, mFakeTitleBarParams);
881             manager.addView(mFakeTitleBarHolder, params);
882         }
883     }
884
885     @Override
886     public void onOptionsMenuClosed(Menu menu) {
887         mOptionsMenuOpen = false;
888         if (!mInLoad) {
889             hideFakeTitleBar();
890         } else if (!mIconView) {
891             // The page is currently loading, and we are in expanded mode, so
892             // we were not showing the menu.  Show it once again.  It will be
893             // removed when the page finishes.
894             showFakeTitleBar();
895         }
896     }
897
898     private void hideFakeTitleBar() {
899         if (mFakeTitleBar.getParent() == null) return;
900         WindowManager.LayoutParams params = (WindowManager.LayoutParams)
901                 mFakeTitleBarHolder.getLayoutParams();
902         WebView mainView = mTabControl.getCurrentWebView();
903         // Although we decided whether or not to animate based on the current
904         // scroll position, the scroll position may have changed since the
905         // fake title bar was displayed.  Make sure it has the appropriate
906         // animation/lack thereof before removing.
907         params.windowAnimations = mainView != null && mainView.getScrollY() == 0
908                 ? 0 : R.style.TitleBar;
909         WindowManager manager
910                     = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
911         manager.updateViewLayout(mFakeTitleBarHolder, params);
912         mFakeTitleBarHolder.removeView(mFakeTitleBar);
913         manager.removeView(mFakeTitleBarHolder);
914     }
915
916     /**
917      * Special method for the fake title bar to call when displaying its context
918      * menu, since it is in its own Window, and its parent does not show a
919      * context menu.
920      */
921     /* package */ void showTitleBarContextMenu() {
922         if (null == mTitleBar.getParent()) {
923             return;
924         }
925         openContextMenu(mTitleBar);
926     }
927
928     @Override
929     public void onContextMenuClosed(Menu menu) {
930         super.onContextMenuClosed(menu);
931         if (mInLoad) {
932             showFakeTitleBar();
933         }
934     }
935
936     /**
937      *  onSaveInstanceState(Bundle map)
938      *  onSaveInstanceState is called right before onStop(). The map contains
939      *  the saved state.
940      */
941     @Override
942     protected void onSaveInstanceState(Bundle outState) {
943         if (LOGV_ENABLED) {
944             Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
945         }
946         // the default implementation requires each view to have an id. As the
947         // browser handles the state itself and it doesn't use id for the views,
948         // don't call the default implementation. Otherwise it will trigger the
949         // warning like this, "couldn't save which view has focus because the
950         // focused view XXX has no id".
951
952         // Save all the tabs
953         mTabControl.saveState(outState);
954     }
955
956     @Override
957     protected void onPause() {
958         super.onPause();
959
960         if (mActivityInPause) {
961             Log.e(LOGTAG, "BrowserActivity is already paused.");
962             return;
963         }
964
965         mTabControl.pauseCurrentTab();
966         mActivityInPause = true;
967         if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
968             mWakeLock.acquire();
969             mHandler.sendMessageDelayed(mHandler
970                     .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
971         }
972
973         // Clear the credentials toast if it is up
974         if (mCredsDlg != null && mCredsDlg.isShowing()) {
975             mCredsDlg.dismiss();
976         }
977         mCredsDlg = null;
978
979         // FIXME: This removes the active tabs page and resets the menu to
980         // MAIN_MENU.  A better solution might be to do this work in onNewIntent
981         // but then we would need to save it in onSaveInstanceState and restore
982         // it in onCreate/onRestoreInstanceState
983         if (mActiveTabsPage != null) {
984             removeActiveTabPage(true);
985         }
986
987         cancelStopToast();
988
989         // unregister network state listener
990         unregisterReceiver(mNetworkStateIntentReceiver);
991         WebView.disablePlatformNotifications();
992     }
993
994     @Override
995     protected void onDestroy() {
996         if (LOGV_ENABLED) {
997             Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
998         }
999         super.onDestroy();
1000
1001         if (mUploadMessage != null) {
1002             mUploadMessage.onReceiveValue(null);
1003             mUploadMessage = null;
1004         }
1005
1006         if (mTabControl == null) return;
1007
1008         // Remove the fake title bar if it is there
1009         hideFakeTitleBar();
1010
1011         // Remove the current tab and sub window
1012         Tab t = mTabControl.getCurrentTab();
1013         if (t != null) {
1014             dismissSubWindow(t);
1015             removeTabFromContentView(t);
1016         }
1017         // Destroy all the tabs
1018         mTabControl.destroy();
1019         WebIconDatabase.getInstance().close();
1020
1021         unregisterReceiver(mPackageInstallationReceiver);
1022     }
1023
1024     @Override
1025     public void onConfigurationChanged(Configuration newConfig) {
1026         mConfigChanged = true;
1027         super.onConfigurationChanged(newConfig);
1028
1029         if (mPageInfoDialog != null) {
1030             mPageInfoDialog.dismiss();
1031             showPageInfo(
1032                 mPageInfoView,
1033                 mPageInfoFromShowSSLCertificateOnError);
1034         }
1035         if (mSSLCertificateDialog != null) {
1036             mSSLCertificateDialog.dismiss();
1037             showSSLCertificate(
1038                 mSSLCertificateView);
1039         }
1040         if (mSSLCertificateOnErrorDialog != null) {
1041             mSSLCertificateOnErrorDialog.dismiss();
1042             showSSLCertificateOnError(
1043                 mSSLCertificateOnErrorView,
1044                 mSSLCertificateOnErrorHandler,
1045                 mSSLCertificateOnErrorError);
1046         }
1047         if (mHttpAuthenticationDialog != null) {
1048             String title = ((TextView) mHttpAuthenticationDialog
1049                     .findViewById(com.android.internal.R.id.alertTitle)).getText()
1050                     .toString();
1051             String name = ((TextView) mHttpAuthenticationDialog
1052                     .findViewById(R.id.username_edit)).getText().toString();
1053             String password = ((TextView) mHttpAuthenticationDialog
1054                     .findViewById(R.id.password_edit)).getText().toString();
1055             int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1056                     .getId();
1057             mHttpAuthenticationDialog.dismiss();
1058             showHttpAuthentication(mHttpAuthHandler, null, null, title,
1059                     name, password, focusId);
1060         }
1061     }
1062
1063     @Override
1064     public void onLowMemory() {
1065         super.onLowMemory();
1066         mTabControl.freeMemory();
1067     }
1068
1069     private boolean resumeWebViewTimers() {
1070         Tab tab = mTabControl.getCurrentTab();
1071         boolean inLoad = tab.inLoad();
1072         if ((!mActivityInPause && !inLoad) || (mActivityInPause && inLoad)) {
1073             CookieSyncManager.getInstance().startSync();
1074             WebView w = tab.getWebView();
1075             if (w != null) {
1076                 w.resumeTimers();
1077             }
1078             return true;
1079         } else {
1080             return false;
1081         }
1082     }
1083
1084     private boolean pauseWebViewTimers() {
1085         Tab tab = mTabControl.getCurrentTab();
1086         boolean inLoad = tab.inLoad();
1087         if (mActivityInPause && !inLoad) {
1088             CookieSyncManager.getInstance().stopSync();
1089             WebView w = mTabControl.getCurrentWebView();
1090             if (w != null) {
1091                 w.pauseTimers();
1092             }
1093             return true;
1094         } else {
1095             return false;
1096         }
1097     }
1098
1099     // FIXME: Do we want to call this when loading google for the first time?
1100     /*
1101      * This function is called when we are launching for the first time. We
1102      * are waiting for the login credentials before loading Google home
1103      * pages. This way the user will be logged in straight away.
1104      */
1105     private void waitForCredentials() {
1106         // Show a toast
1107         mCredsDlg = new ProgressDialog(this);
1108         mCredsDlg.setIndeterminate(true);
1109         mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1110         // If the user cancels the operation, then cancel the Google
1111         // Credentials request.
1112         mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1113         mCredsDlg.show();
1114
1115         // We set a timeout for the retrieval of credentials in onResume()
1116         // as that is when we have freed up some CPU time to get
1117         // the login credentials.
1118     }
1119
1120     /*
1121      * If we have received the credentials or we have timed out and we are
1122      * showing the credentials dialog, then it is time to move on.
1123      */
1124     private void resumeAfterCredentials() {
1125         if (mCredsDlg == null) {
1126             return;
1127         }
1128
1129         // Clear the toast
1130         if (mCredsDlg.isShowing()) {
1131             mCredsDlg.dismiss();
1132         }
1133         mCredsDlg = null;
1134
1135         // Clear any pending timeout
1136         mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1137
1138         // Load the page
1139         WebView w = mTabControl.getCurrentWebView();
1140         if (w != null) {
1141             w.loadUrl(mSettings.getHomePage());
1142         }
1143
1144         // Update the settings, need to do this last as it can take a moment
1145         // to persist the settings. In the mean time we could be loading
1146         // content.
1147         mSettings.setLoginInitialized(this);
1148     }
1149
1150     // Open the icon database and retain all the icons for visited sites.
1151     private void retainIconsOnStartup() {
1152         final WebIconDatabase db = WebIconDatabase.getInstance();
1153         db.open(getDir("icons", 0).getPath());
1154         try {
1155             Cursor c = Browser.getAllBookmarks(mResolver);
1156             if (!c.moveToFirst()) {
1157                 c.deactivate();
1158                 return;
1159             }
1160             int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1161             do {
1162                 String url = c.getString(urlIndex);
1163                 db.retainIconForPageUrl(url);
1164             } while (c.moveToNext());
1165             c.deactivate();
1166         } catch (IllegalStateException e) {
1167             Log.e(LOGTAG, "retainIconsOnStartup", e);
1168         }
1169     }
1170
1171     // Helper method for getting the top window.
1172     WebView getTopWindow() {
1173         return mTabControl.getCurrentTopWebView();
1174     }
1175
1176     TabControl getTabControl() {
1177         return mTabControl;
1178     }
1179
1180     @Override
1181     public boolean onCreateOptionsMenu(Menu menu) {
1182         super.onCreateOptionsMenu(menu);
1183
1184         MenuInflater inflater = getMenuInflater();
1185         inflater.inflate(R.menu.browser, menu);
1186         mMenu = menu;
1187         updateInLoadMenuItems();
1188         return true;
1189     }
1190
1191     /**
1192      * As the menu can be open when loading state changes
1193      * we must manually update the state of the stop/reload menu
1194      * item
1195      */
1196     private void updateInLoadMenuItems() {
1197         if (mMenu == null) {
1198             return;
1199         }
1200         MenuItem src = mInLoad ?
1201                 mMenu.findItem(R.id.stop_menu_id):
1202                     mMenu.findItem(R.id.reload_menu_id);
1203         MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1204         dest.setIcon(src.getIcon());
1205         dest.setTitle(src.getTitle());
1206     }
1207
1208     @Override
1209     public boolean onContextItemSelected(MenuItem item) {
1210         // chording is not an issue with context menus, but we use the same
1211         // options selector, so set mCanChord to true so we can access them.
1212         mCanChord = true;
1213         int id = item.getItemId();
1214         boolean result = true;
1215         switch (id) {
1216             // For the context menu from the title bar
1217             case R.id.title_bar_copy_page_url:
1218                 Tab currentTab = mTabControl.getCurrentTab();
1219                 if (null == currentTab) {
1220                     result = false;
1221                     break;
1222                 }
1223                 WebView mainView = currentTab.getWebView();
1224                 if (null == mainView) {
1225                     result = false;
1226                     break;
1227                 }
1228                 copy(mainView.getUrl());
1229                 break;
1230             // -- Browser context menu
1231             case R.id.open_context_menu_id:
1232             case R.id.open_newtab_context_menu_id:
1233             case R.id.bookmark_context_menu_id:
1234             case R.id.save_link_context_menu_id:
1235             case R.id.share_link_context_menu_id:
1236             case R.id.copy_link_context_menu_id:
1237                 final WebView webView = getTopWindow();
1238                 if (null == webView) {
1239                     result = false;
1240                     break;
1241                 }
1242                 final HashMap hrefMap = new HashMap();
1243                 hrefMap.put("webview", webView);
1244                 final Message msg = mHandler.obtainMessage(
1245                         FOCUS_NODE_HREF, id, 0, hrefMap);
1246                 webView.requestFocusNodeHref(msg);
1247                 break;
1248
1249             default:
1250                 // For other context menus
1251                 result = onOptionsItemSelected(item);
1252         }
1253         mCanChord = false;
1254         return result;
1255     }
1256
1257     private Bundle createGoogleSearchSourceBundle(String source) {
1258         Bundle bundle = new Bundle();
1259         bundle.putString(SearchManager.SOURCE, source);
1260         return bundle;
1261     }
1262
1263     /**
1264      * Overriding this to insert a local information bundle
1265      */
1266     @Override
1267     public boolean onSearchRequested() {
1268         if (mOptionsMenuOpen) closeOptionsMenu();
1269         String url = (getTopWindow() == null) ? null : getTopWindow().getUrl();
1270         startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1271                 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1272         return true;
1273     }
1274
1275     @Override
1276     public void startSearch(String initialQuery, boolean selectInitialQuery,
1277             Bundle appSearchData, boolean globalSearch) {
1278         if (appSearchData == null) {
1279             appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1280         }
1281         super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1282     }
1283
1284     /**
1285      * Switch tabs.  Called by the TitleBarSet when sliding the title bar
1286      * results in changing tabs.
1287      * @param index Index of the tab to change to, as defined by
1288      *              mTabControl.getTabIndex(Tab t).
1289      * @return boolean True if we successfully switched to a different tab.  If
1290      *                 the indexth tab is null, or if that tab is the same as
1291      *                 the current one, return false.
1292      */
1293     /* package */ boolean switchToTab(int index) {
1294         Tab tab = mTabControl.getTab(index);
1295         Tab currentTab = mTabControl.getCurrentTab();
1296         if (tab == null || tab == currentTab) {
1297             return false;
1298         }
1299         if (currentTab != null) {
1300             // currentTab may be null if it was just removed.  In that case,
1301             // we do not need to remove it
1302             removeTabFromContentView(currentTab);
1303         }
1304         mTabControl.setCurrentTab(tab);
1305         attachTabToContentView(tab);
1306         resetTitleIconAndProgress();
1307         updateLockIconToLatest();
1308         return true;
1309     }
1310
1311     /* package */ Tab openTabToHomePage() {
1312         return openTabAndShow(mSettings.getHomePage(), false, null);
1313     }
1314
1315     /* package */ void closeCurrentWindow() {
1316         final Tab current = mTabControl.getCurrentTab();
1317         if (mTabControl.getTabCount() == 1) {
1318             // This is the last tab.  Open a new one, with the home
1319             // page and close the current one.
1320             openTabToHomePage();
1321             closeTab(current);
1322             return;
1323         }
1324         final Tab parent = current.getParentTab();
1325         int indexToShow = -1;
1326         if (parent != null) {
1327             indexToShow = mTabControl.getTabIndex(parent);
1328         } else {
1329             final int currentIndex = mTabControl.getCurrentIndex();
1330             // Try to move to the tab to the right
1331             indexToShow = currentIndex + 1;
1332             if (indexToShow > mTabControl.getTabCount() - 1) {
1333                 // Try to move to the tab to the left
1334                 indexToShow = currentIndex - 1;
1335             }
1336         }
1337         if (switchToTab(indexToShow)) {
1338             // Close window
1339             closeTab(current);
1340         }
1341     }
1342
1343     private ActiveTabsPage mActiveTabsPage;
1344
1345     /**
1346      * Remove the active tabs page.
1347      * @param needToAttach If true, the active tabs page did not attach a tab
1348      *                     to the content view, so we need to do that here.
1349      */
1350     /* package */ void removeActiveTabPage(boolean needToAttach) {
1351         mContentView.removeView(mActiveTabsPage);
1352         mActiveTabsPage = null;
1353         mMenuState = R.id.MAIN_MENU;
1354         if (needToAttach) {
1355             attachTabToContentView(mTabControl.getCurrentTab());
1356         }
1357         getTopWindow().requestFocus();
1358     }
1359
1360     @Override
1361     public boolean onOptionsItemSelected(MenuItem item) {
1362         if (!mCanChord) {
1363             // The user has already fired a shortcut with this hold down of the
1364             // menu key.
1365             return false;
1366         }
1367         if (null == getTopWindow()) {
1368             return false;
1369         }
1370         if (mMenuIsDown) {
1371             // The shortcut action consumes the MENU. Even if it is still down,
1372             // it won't trigger the next shortcut action. In the case of the
1373             // shortcut action triggering a new activity, like Bookmarks, we
1374             // won't get onKeyUp for MENU. So it is important to reset it here.
1375             mMenuIsDown = false;
1376         }
1377         switch (item.getItemId()) {
1378             // -- Main menu
1379             case R.id.new_tab_menu_id:
1380                 openTabToHomePage();
1381                 break;
1382
1383             case R.id.goto_menu_id:
1384                 onSearchRequested();
1385                 break;
1386
1387             case R.id.bookmarks_menu_id:
1388                 bookmarksOrHistoryPicker(false);
1389                 break;
1390
1391             case R.id.active_tabs_menu_id:
1392                 mActiveTabsPage = new ActiveTabsPage(this, mTabControl);
1393                 removeTabFromContentView(mTabControl.getCurrentTab());
1394                 hideFakeTitleBar();
1395                 mContentView.addView(mActiveTabsPage, COVER_SCREEN_PARAMS);
1396                 mActiveTabsPage.requestFocus();
1397                 mMenuState = EMPTY_MENU;
1398                 break;
1399
1400             case R.id.add_bookmark_menu_id:
1401                 Intent i = new Intent(BrowserActivity.this,
1402                         AddBookmarkPage.class);
1403                 WebView w = getTopWindow();
1404                 i.putExtra("url", w.getUrl());
1405                 i.putExtra("title", w.getTitle());
1406                 i.putExtra("touch_icon_url", w.getTouchIconUrl());
1407                 i.putExtra("thumbnail", createScreenshot(w));
1408                 startActivity(i);
1409                 break;
1410
1411             case R.id.stop_reload_menu_id:
1412                 if (mInLoad) {
1413                     stopLoading();
1414                 } else {
1415                     getTopWindow().reload();
1416                 }
1417                 break;
1418
1419             case R.id.back_menu_id:
1420                 getTopWindow().goBack();
1421                 break;
1422
1423             case R.id.forward_menu_id:
1424                 getTopWindow().goForward();
1425                 break;
1426
1427             case R.id.close_menu_id:
1428                 // Close the subwindow if it exists.
1429                 if (mTabControl.getCurrentSubWindow() != null) {
1430                     dismissSubWindow(mTabControl.getCurrentTab());
1431                     break;
1432                 }
1433                 closeCurrentWindow();
1434                 break;
1435
1436             case R.id.homepage_menu_id:
1437                 Tab current = mTabControl.getCurrentTab();
1438                 if (current != null) {
1439                     dismissSubWindow(current);
1440                     current.getWebView().loadUrl(mSettings.getHomePage());
1441                 }
1442                 break;
1443
1444             case R.id.preferences_menu_id:
1445                 Intent intent = new Intent(this,
1446                         BrowserPreferencesPage.class);
1447                 intent.putExtra(BrowserPreferencesPage.CURRENT_PAGE,
1448                         getTopWindow().getUrl());
1449                 startActivityForResult(intent, PREFERENCES_PAGE);
1450                 break;
1451
1452             case R.id.find_menu_id:
1453                 if (null == mFindDialog) {
1454                     mFindDialog = new FindDialog(this);
1455                 }
1456                 mFindDialog.setWebView(getTopWindow());
1457                 mFindDialog.show();
1458                 mMenuState = EMPTY_MENU;
1459                 break;
1460
1461             case R.id.select_text_id:
1462                 getTopWindow().emulateShiftHeld();
1463                 break;
1464             case R.id.page_info_menu_id:
1465                 showPageInfo(mTabControl.getCurrentTab(), false);
1466                 break;
1467
1468             case R.id.classic_history_menu_id:
1469                 bookmarksOrHistoryPicker(true);
1470                 break;
1471
1472             case R.id.title_bar_share_page_url:
1473             case R.id.share_page_menu_id:
1474                 Tab currentTab = mTabControl.getCurrentTab();
1475                 if (null == currentTab) {
1476                     mCanChord = false;
1477                     return false;
1478                 }
1479                 currentTab.populatePickerData();
1480                 sharePage(this, currentTab.getTitle(),
1481                         currentTab.getUrl(), currentTab.getFavicon(),
1482                         createScreenshot(currentTab.getWebView()));
1483                 break;
1484
1485             case R.id.dump_nav_menu_id:
1486                 getTopWindow().debugDump();
1487                 break;
1488
1489             case R.id.zoom_in_menu_id:
1490                 getTopWindow().zoomIn();
1491                 break;
1492
1493             case R.id.zoom_out_menu_id:
1494                 getTopWindow().zoomOut();
1495                 break;
1496
1497             case R.id.view_downloads_menu_id:
1498                 viewDownloads(null);
1499                 break;
1500
1501             case R.id.window_one_menu_id:
1502             case R.id.window_two_menu_id:
1503             case R.id.window_three_menu_id:
1504             case R.id.window_four_menu_id:
1505             case R.id.window_five_menu_id:
1506             case R.id.window_six_menu_id:
1507             case R.id.window_seven_menu_id:
1508             case R.id.window_eight_menu_id:
1509                 {
1510                     int menuid = item.getItemId();
1511                     for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1512                         if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1513                             Tab desiredTab = mTabControl.getTab(id);
1514                             if (desiredTab != null &&
1515                                     desiredTab != mTabControl.getCurrentTab()) {
1516                                 switchToTab(id);
1517                             }
1518                             break;
1519                         }
1520                     }
1521                 }
1522                 break;
1523
1524             default:
1525                 if (!super.onOptionsItemSelected(item)) {
1526                     return false;
1527                 }
1528                 // Otherwise fall through.
1529         }
1530         mCanChord = false;
1531         return true;
1532     }
1533
1534     public void closeFind() {
1535         mMenuState = R.id.MAIN_MENU;
1536     }
1537
1538     @Override
1539     public boolean onPrepareOptionsMenu(Menu menu) {
1540         // This happens when the user begins to hold down the menu key, so
1541         // allow them to chord to get a shortcut.
1542         mCanChord = true;
1543         // Note: setVisible will decide whether an item is visible; while
1544         // setEnabled() will decide whether an item is enabled, which also means
1545         // whether the matching shortcut key will function.
1546         super.onPrepareOptionsMenu(menu);
1547         switch (mMenuState) {
1548             case EMPTY_MENU:
1549                 if (mCurrentMenuState != mMenuState) {
1550                     menu.setGroupVisible(R.id.MAIN_MENU, false);
1551                     menu.setGroupEnabled(R.id.MAIN_MENU, false);
1552                     menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1553                 }
1554                 break;
1555             default:
1556                 if (mCurrentMenuState != mMenuState) {
1557                     menu.setGroupVisible(R.id.MAIN_MENU, true);
1558                     menu.setGroupEnabled(R.id.MAIN_MENU, true);
1559                     menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1560                 }
1561                 final WebView w = getTopWindow();
1562                 boolean canGoBack = false;
1563                 boolean canGoForward = false;
1564                 boolean isHome = false;
1565                 if (w != null) {
1566                     canGoBack = w.canGoBack();
1567                     canGoForward = w.canGoForward();
1568                     isHome = mSettings.getHomePage().equals(w.getUrl());
1569                 }
1570                 final MenuItem back = menu.findItem(R.id.back_menu_id);
1571                 back.setEnabled(canGoBack);
1572
1573                 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1574                 home.setEnabled(!isHome);
1575
1576                 menu.findItem(R.id.forward_menu_id)
1577                         .setEnabled(canGoForward);
1578
1579                 menu.findItem(R.id.new_tab_menu_id).setEnabled(
1580                         mTabControl.canCreateNewTab());
1581
1582                 // decide whether to show the share link option
1583                 PackageManager pm = getPackageManager();
1584                 Intent send = new Intent(Intent.ACTION_SEND);
1585                 send.setType("text/plain");
1586                 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1587                 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1588
1589                 boolean isNavDump = mSettings.isNavDump();
1590                 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1591                 nav.setVisible(isNavDump);
1592                 nav.setEnabled(isNavDump);
1593                 break;
1594         }
1595         mCurrentMenuState = mMenuState;
1596         return true;
1597     }
1598
1599     @Override
1600     public void onCreateContextMenu(ContextMenu menu, View v,
1601             ContextMenuInfo menuInfo) {
1602         WebView webview = (WebView) v;
1603         WebView.HitTestResult result = webview.getHitTestResult();
1604         if (result == null) {
1605             return;
1606         }
1607
1608         int type = result.getType();
1609         if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1610             Log.w(LOGTAG,
1611                     "We should not show context menu when nothing is touched");
1612             return;
1613         }
1614         if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1615             // let TextView handles context menu
1616             return;
1617         }
1618
1619         // Note, http://b/issue?id=1106666 is requesting that
1620         // an inflated menu can be used again. This is not available
1621         // yet, so inflate each time (yuk!)
1622         MenuInflater inflater = getMenuInflater();
1623         inflater.inflate(R.menu.browsercontext, menu);
1624
1625         // Show the correct menu group
1626         String extra = result.getExtra();
1627         menu.setGroupVisible(R.id.PHONE_MENU,
1628                 type == WebView.HitTestResult.PHONE_TYPE);
1629         menu.setGroupVisible(R.id.EMAIL_MENU,
1630                 type == WebView.HitTestResult.EMAIL_TYPE);
1631         menu.setGroupVisible(R.id.GEO_MENU,
1632                 type == WebView.HitTestResult.GEO_TYPE);
1633         menu.setGroupVisible(R.id.IMAGE_MENU,
1634                 type == WebView.HitTestResult.IMAGE_TYPE
1635                 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1636         menu.setGroupVisible(R.id.ANCHOR_MENU,
1637                 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1638                 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1639
1640         // Setup custom handling depending on the type
1641         switch (type) {
1642             case WebView.HitTestResult.PHONE_TYPE:
1643                 menu.setHeaderTitle(Uri.decode(extra));
1644                 menu.findItem(R.id.dial_context_menu_id).setIntent(
1645                         new Intent(Intent.ACTION_VIEW, Uri
1646                                 .parse(WebView.SCHEME_TEL + extra)));
1647                 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1648                 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1649                 addIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
1650                 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1651                         addIntent);
1652                 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1653                         new Copy(extra));
1654                 break;
1655
1656             case WebView.HitTestResult.EMAIL_TYPE:
1657                 menu.setHeaderTitle(extra);
1658                 menu.findItem(R.id.email_context_menu_id).setIntent(
1659                         new Intent(Intent.ACTION_VIEW, Uri
1660                                 .parse(WebView.SCHEME_MAILTO + extra)));
1661                 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1662                         new Copy(extra));
1663                 break;
1664
1665             case WebView.HitTestResult.GEO_TYPE:
1666                 menu.setHeaderTitle(extra);
1667                 menu.findItem(R.id.map_context_menu_id).setIntent(
1668                         new Intent(Intent.ACTION_VIEW, Uri
1669                                 .parse(WebView.SCHEME_GEO
1670                                         + URLEncoder.encode(extra))));
1671                 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1672                         new Copy(extra));
1673                 break;
1674
1675             case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1676             case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1677                 TextView titleView = (TextView) LayoutInflater.from(this)
1678                         .inflate(android.R.layout.browser_link_context_header,
1679                         null);
1680                 titleView.setText(extra);
1681                 menu.setHeaderView(titleView);
1682                 // decide whether to show the open link in new tab option
1683                 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1684                         mTabControl.canCreateNewTab());
1685                 menu.findItem(R.id.bookmark_context_menu_id).setVisible(
1686                         Bookmarks.urlHasAcceptableScheme(extra));
1687                 PackageManager pm = getPackageManager();
1688                 Intent send = new Intent(Intent.ACTION_SEND);
1689                 send.setType("text/plain");
1690                 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1691                 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1692                 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1693                     break;
1694                 }
1695                 // otherwise fall through to handle image part
1696             case WebView.HitTestResult.IMAGE_TYPE:
1697                 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1698                     menu.setHeaderTitle(extra);
1699                 }
1700                 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1701                         new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1702                 menu.findItem(R.id.download_context_menu_id).
1703                         setOnMenuItemClickListener(new Download(extra));
1704                 menu.findItem(R.id.set_wallpaper_context_menu_id).
1705                         setOnMenuItemClickListener(new SetAsWallpaper(extra));
1706                 break;
1707
1708             default:
1709                 Log.w(LOGTAG, "We should not get here.");
1710                 break;
1711         }
1712         hideFakeTitleBar();
1713     }
1714
1715     // Attach the given tab to the content view.
1716     // this should only be called for the current tab.
1717     private void attachTabToContentView(Tab t) {
1718         // Attach the container that contains the main WebView and any other UI
1719         // associated with the tab.
1720         t.attachTabToContentView(mContentView);
1721
1722         if (mShouldShowErrorConsole) {
1723             ErrorConsoleView errorConsole = t.getErrorConsole(true);
1724             if (errorConsole.numberOfErrors() == 0) {
1725                 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1726             } else {
1727                 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1728             }
1729
1730             mErrorConsoleContainer.addView(errorConsole,
1731                     new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
1732                                                   ViewGroup.LayoutParams.WRAP_CONTENT));
1733         }
1734
1735         WebView view = t.getWebView();
1736         view.setEmbeddedTitleBar(mTitleBar);
1737         // Request focus on the top window.
1738         t.getTopWindow().requestFocus();
1739     }
1740
1741     // Attach a sub window to the main WebView of the given tab.
1742     void attachSubWindow(Tab t) {
1743         t.attachSubWindow(mContentView);
1744         getTopWindow().requestFocus();
1745     }
1746
1747     // Remove the given tab from the content view.
1748     private void removeTabFromContentView(Tab t) {
1749         // Remove the container that contains the main WebView.
1750         t.removeTabFromContentView(mContentView);
1751
1752         ErrorConsoleView errorConsole = t.getErrorConsole(false);
1753         if (errorConsole != null) {
1754             mErrorConsoleContainer.removeView(errorConsole);
1755         }
1756
1757         WebView view = t.getWebView();
1758         if (view != null) {
1759             view.setEmbeddedTitleBar(null);
1760         }
1761     }
1762
1763     // Remove the sub window if it exists. Also called by TabControl when the
1764     // user clicks the 'X' to dismiss a sub window.
1765     /* package */ void dismissSubWindow(Tab t) {
1766         t.removeSubWindow(mContentView);
1767         // dismiss the subwindow. This will destroy the WebView.
1768         t.dismissSubWindow();
1769         getTopWindow().requestFocus();
1770     }
1771
1772     // A wrapper function of {@link #openTabAndShow(UrlData, boolean, String)}
1773     // that accepts url as string.
1774     private Tab openTabAndShow(String url, boolean closeOnExit, String appId) {
1775         return openTabAndShow(new UrlData(url), closeOnExit, appId);
1776     }
1777
1778     // This method does a ton of stuff. It will attempt to create a new tab
1779     // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1780     // url isn't null, it will load the given url.
1781     /* package */Tab openTabAndShow(UrlData urlData, boolean closeOnExit,
1782             String appId) {
1783         final Tab currentTab = mTabControl.getCurrentTab();
1784         if (mTabControl.canCreateNewTab()) {
1785             final Tab tab = mTabControl.createNewTab(closeOnExit, appId,
1786                     urlData.mUrl);
1787             WebView webview = tab.getWebView();
1788             // If the last tab was removed from the active tabs page, currentTab
1789             // will be null.
1790             if (currentTab != null) {
1791                 removeTabFromContentView(currentTab);
1792             }
1793             // We must set the new tab as the current tab to reflect the old
1794             // animation behavior.
1795             mTabControl.setCurrentTab(tab);
1796             attachTabToContentView(tab);
1797             if (!urlData.isEmpty()) {
1798                 urlData.loadIn(webview);
1799             }
1800             return tab;
1801         } else {
1802             // Get rid of the subwindow if it exists
1803             dismissSubWindow(currentTab);
1804             if (!urlData.isEmpty()) {
1805                 // Load the given url.
1806                 urlData.loadIn(currentTab.getWebView());
1807             }
1808         }
1809         return currentTab;
1810     }
1811
1812     private Tab openTab(String url) {
1813         if (mSettings.openInBackground()) {
1814             Tab t = mTabControl.createNewTab();
1815             if (t != null) {
1816                 WebView view = t.getWebView();
1817                 view.loadUrl(url);
1818             }
1819             return t;
1820         } else {
1821             return openTabAndShow(url, false, null);
1822         }
1823     }
1824
1825     private class Copy implements OnMenuItemClickListener {
1826         private CharSequence mText;
1827
1828         public boolean onMenuItemClick(MenuItem item) {
1829             copy(mText);
1830             return true;
1831         }
1832
1833         public Copy(CharSequence toCopy) {
1834             mText = toCopy;
1835         }
1836     }
1837
1838     private class Download implements OnMenuItemClickListener {
1839         private String mText;
1840
1841         public boolean onMenuItemClick(MenuItem item) {
1842             onDownloadStartNoStream(mText, null, null, null, -1);
1843             return true;
1844         }
1845
1846         public Download(String toDownload) {
1847             mText = toDownload;
1848         }
1849     }
1850
1851     private class SetAsWallpaper extends Thread implements
1852             OnMenuItemClickListener, DialogInterface.OnCancelListener {
1853         private URL mUrl;
1854         private ProgressDialog mWallpaperProgress;
1855         private boolean mCanceled = false;
1856
1857         public SetAsWallpaper(String url) {
1858             try {
1859                 mUrl = new URL(url);
1860             } catch (MalformedURLException e) {
1861                 mUrl = null;
1862             }
1863         }
1864
1865         public void onCancel(DialogInterface dialog) {
1866             mCanceled = true;
1867         }
1868
1869         public boolean onMenuItemClick(MenuItem item) {
1870             if (mUrl != null) {
1871                 // The user may have tried to set a image with a large file size as their
1872                 // background so it may take a few moments to perform the operation. Display
1873                 // a progress spinner while it is working.
1874                 mWallpaperProgress = new ProgressDialog(BrowserActivity.this);
1875                 mWallpaperProgress.setIndeterminate(true);
1876                 mWallpaperProgress.setMessage(getText(R.string.progress_dialog_setting_wallpaper));
1877                 mWallpaperProgress.setCancelable(true);
1878                 mWallpaperProgress.setOnCancelListener(this);
1879                 mWallpaperProgress.show();
1880                 start();
1881             }
1882             return true;
1883         }
1884
1885         public void run() {
1886             Drawable oldWallpaper = BrowserActivity.this.getWallpaper();
1887             try {
1888                 // TODO: This will cause the resource to be downloaded again, when we
1889                 // should in most cases be able to grab it from the cache. To fix this
1890                 // we should query WebCore to see if we can access a cached version and
1891                 // instead open an input stream on that. This pattern could also be used
1892                 // in the download manager where the same problem exists.
1893                 InputStream inputstream = mUrl.openStream();
1894                 if (inputstream != null) {
1895                     setWallpaper(inputstream);
1896                 }
1897             } catch (IOException e) {
1898                 Log.e(LOGTAG, "Unable to set new wallpaper");
1899                 // Act as though the user canceled the operation so we try to
1900                 // restore the old wallpaper.
1901                 mCanceled = true;
1902             }
1903
1904             if (mCanceled) {
1905                 // Restore the old wallpaper if the user cancelled whilst we were setting
1906                 // the new wallpaper.
1907                 int width = oldWallpaper.getIntrinsicWidth();
1908                 int height = oldWallpaper.getIntrinsicHeight();
1909                 Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
1910                 Canvas canvas = new Canvas(bm);
1911                 oldWallpaper.setBounds(0, 0, width, height);
1912                 oldWallpaper.draw(canvas);
1913                 try {
1914                     setWallpaper(bm);
1915                 } catch (IOException e) {
1916                     Log.e(LOGTAG, "Unable to restore old wallpaper.");
1917                 }
1918                 mCanceled = false;
1919             }
1920
1921             if (mWallpaperProgress.isShowing()) {
1922                 mWallpaperProgress.dismiss();
1923             }
1924         }
1925     }
1926
1927     private void copy(CharSequence text) {
1928         try {
1929             IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
1930             if (clip != null) {
1931                 clip.setClipboardText(text);
1932             }
1933         } catch (android.os.RemoteException e) {
1934             Log.e(LOGTAG, "Copy failed", e);
1935         }
1936     }
1937
1938     /**
1939      * Resets the browser title-view to whatever it must be
1940      * (for example, if we had a loading error)
1941      * When we have a new page, we call resetTitle, when we
1942      * have to reset the titlebar to whatever it used to be
1943      * (for example, if the user chose to stop loading), we
1944      * call resetTitleAndRevertLockIcon.
1945      */
1946     /* package */ void resetTitleAndRevertLockIcon() {
1947         mTabControl.getCurrentTab().revertLockIcon();
1948         updateLockIconToLatest();
1949         resetTitleIconAndProgress();
1950     }
1951
1952     /**
1953      * Reset the title, favicon, and progress.
1954      */
1955     private void resetTitleIconAndProgress() {
1956         WebView current = mTabControl.getCurrentWebView();
1957         if (current == null) {
1958             return;
1959         }
1960         resetTitleAndIcon(current);
1961         int progress = current.getProgress();
1962         current.getWebChromeClient().onProgressChanged(current, progress);
1963     }
1964
1965     // Reset the title and the icon based on the given item.
1966     private void resetTitleAndIcon(WebView view) {
1967         WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
1968         if (item != null) {
1969             setUrlTitle(item.getUrl(), item.getTitle());
1970             setFavicon(item.getFavicon());
1971         } else {
1972             setUrlTitle(null, null);
1973             setFavicon(null);
1974         }
1975     }
1976
1977     /**
1978      * Sets a title composed of the URL and the title string.
1979      * @param url The URL of the site being loaded.
1980      * @param title The title of the site being loaded.
1981      */
1982     void setUrlTitle(String url, String title) {
1983         mUrl = url;
1984         mTitle = title;
1985
1986         mTitleBar.setTitleAndUrl(title, url);
1987         mFakeTitleBar.setTitleAndUrl(title, url);
1988     }
1989
1990     /**
1991      * @param url The URL to build a title version of the URL from.
1992      * @return The title version of the URL or null if fails.
1993      * The title version of the URL can be either the URL hostname,
1994      * or the hostname with an "https://" prefix (for secure URLs),
1995      * or an empty string if, for example, the URL in question is a
1996      * file:// URL with no hostname.
1997      */
1998     /* package */ static String buildTitleUrl(String url) {
1999         String titleUrl = null;
2000
2001         if (url != null) {
2002             try {
2003                 // parse the url string
2004                 URL urlObj = new URL(url);
2005                 if (urlObj != null) {
2006                     titleUrl = "";
2007
2008                     String protocol = urlObj.getProtocol();
2009                     String host = urlObj.getHost();
2010
2011                     if (host != null && 0 < host.length()) {
2012                         titleUrl = host;
2013                         if (protocol != null) {
2014                             // if a secure site, add an "https://" prefix!
2015                             if (protocol.equalsIgnoreCase("https")) {
2016                                 titleUrl = protocol + "://" + host;
2017                             }
2018                         }
2019                     }
2020                 }
2021             } catch (MalformedURLException e) {}
2022         }
2023
2024         return titleUrl;
2025     }
2026
2027     // Set the favicon in the title bar.
2028     void setFavicon(Bitmap icon) {
2029         mTitleBar.setFavicon(icon);
2030         mFakeTitleBar.setFavicon(icon);
2031     }
2032
2033     /**
2034      * Close the tab, remove its associated title bar, and adjust mTabControl's
2035      * current tab to a valid value.
2036      */
2037     /* package */ void closeTab(Tab t) {
2038         int currentIndex = mTabControl.getCurrentIndex();
2039         int removeIndex = mTabControl.getTabIndex(t);
2040         mTabControl.removeTab(t);
2041         if (currentIndex >= removeIndex && currentIndex != 0) {
2042             currentIndex--;
2043         }
2044         mTabControl.setCurrentTab(mTabControl.getTab(currentIndex));
2045         resetTitleIconAndProgress();
2046     }
2047
2048     private void goBackOnePageOrQuit() {
2049         Tab current = mTabControl.getCurrentTab();
2050         if (current == null) {
2051             /*
2052              * Instead of finishing the activity, simply push this to the back
2053              * of the stack and let ActivityManager to choose the foreground
2054              * activity. As BrowserActivity is singleTask, it will be always the
2055              * root of the task. So we can use either true or false for
2056              * moveTaskToBack().
2057              */
2058             moveTaskToBack(true);
2059             return;
2060         }
2061         WebView w = current.getWebView();
2062         if (w.canGoBack()) {
2063             w.goBack();
2064         } else {
2065             // Check to see if we are closing a window that was created by
2066             // another window. If so, we switch back to that window.
2067             Tab parent = current.getParentTab();
2068             if (parent != null) {
2069                 switchToTab(mTabControl.getTabIndex(parent));
2070                 // Now we close the other tab
2071                 closeTab(current);
2072             } else {
2073                 if (current.closeOnExit()) {
2074                     // force the tab's inLoad() to be false as we are going to
2075                     // either finish the activity or remove the tab. This will
2076                     // ensure pauseWebViewTimers() taking action.
2077                     mTabControl.getCurrentTab().clearInLoad();
2078                     if (mTabControl.getTabCount() == 1) {
2079                         finish();
2080                         return;
2081                     }
2082                     // call pauseWebViewTimers() now, we won't be able to call
2083                     // it in onPause() as the WebView won't be valid.
2084                     // Temporarily change mActivityInPause to be true as
2085                     // pauseWebViewTimers() will do nothing if mActivityInPause
2086                     // is false.
2087                     boolean savedState = mActivityInPause;
2088                     if (savedState) {
2089                         Log.e(LOGTAG, "BrowserActivity is already paused "
2090                                 + "while handing goBackOnePageOrQuit.");
2091                     }
2092                     mActivityInPause = true;
2093                     pauseWebViewTimers();
2094                     mActivityInPause = savedState;
2095                     removeTabFromContentView(current);
2096                     mTabControl.removeTab(current);
2097                 }
2098                 /*
2099                  * Instead of finishing the activity, simply push this to the back
2100                  * of the stack and let ActivityManager to choose the foreground
2101                  * activity. As BrowserActivity is singleTask, it will be always the
2102                  * root of the task. So we can use either true or false for
2103                  * moveTaskToBack().
2104                  */
2105                 moveTaskToBack(true);
2106             }
2107         }
2108     }
2109
2110     boolean isMenuDown() {
2111         return mMenuIsDown;
2112     }
2113
2114     @Override
2115     public boolean onKeyDown(int keyCode, KeyEvent event) {
2116         // Even if MENU is already held down, we need to call to super to open
2117         // the IME on long press.
2118         if (KeyEvent.KEYCODE_MENU == keyCode) {
2119             mMenuIsDown = true;
2120             return super.onKeyDown(keyCode, event);
2121         }
2122         // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2123         // still down, we don't want to trigger the search. Pretend to consume
2124         // the key and do nothing.
2125         if (mMenuIsDown) return true;
2126
2127         switch(keyCode) {
2128             case KeyEvent.KEYCODE_SPACE:
2129                 // WebView/WebTextView handle the keys in the KeyDown. As
2130                 // the Activity's shortcut keys are only handled when WebView
2131                 // doesn't, have to do it in onKeyDown instead of onKeyUp.
2132                 if (event.isShiftPressed()) {
2133                     getTopWindow().pageUp(false);
2134                 } else {
2135                     getTopWindow().pageDown(false);
2136                 }
2137                 return true;
2138             case KeyEvent.KEYCODE_BACK:
2139                 if (event.getRepeatCount() == 0) {
2140                     event.startTracking();
2141                     return true;
2142                 } else if (mCustomView == null && mActiveTabsPage == null
2143                         && event.isLongPress()) {
2144                     bookmarksOrHistoryPicker(true);
2145                     return true;
2146                 }
2147                 break;
2148         }
2149         return super.onKeyDown(keyCode, event);
2150     }
2151
2152     @Override
2153     public boolean onKeyUp(int keyCode, KeyEvent event) {
2154         switch(keyCode) {
2155             case KeyEvent.KEYCODE_MENU:
2156                 mMenuIsDown = false;
2157                 break;
2158             case KeyEvent.KEYCODE_BACK:
2159                 if (event.isTracking() && !event.isCanceled()) {
2160                     if (mCustomView != null) {
2161                         // if a custom view is showing, hide it
2162                         mTabControl.getCurrentWebView().getWebChromeClient()
2163                                 .onHideCustomView();
2164                     } else if (mActiveTabsPage != null) {
2165                         // if tab page is showing, hide it
2166                         removeActiveTabPage(true);
2167                     } else {
2168                         WebView subwindow = mTabControl.getCurrentSubWindow();
2169                         if (subwindow != null) {
2170                             if (subwindow.canGoBack()) {
2171                                 subwindow.goBack();
2172                             } else {
2173                                 dismissSubWindow(mTabControl.getCurrentTab());
2174                             }
2175                         } else {
2176                             goBackOnePageOrQuit();
2177                         }
2178                     }
2179                     return true;
2180                 }
2181                 break;
2182         }
2183         return super.onKeyUp(keyCode, event);
2184     }
2185
2186     /* package */ void stopLoading() {
2187         mDidStopLoad = true;
2188         resetTitleAndRevertLockIcon();
2189         WebView w = getTopWindow();
2190         w.stopLoading();
2191         // FIXME: before refactor, it is using mWebViewClient. So I keep the
2192         // same logic here. But for subwindow case, should we call into the main
2193         // WebView's onPageFinished as we never call its onPageStarted and if
2194         // the page finishes itself, we don't call onPageFinished.
2195         mTabControl.getCurrentWebView().getWebViewClient().onPageFinished(w,
2196                 w.getUrl());
2197
2198         cancelStopToast();
2199         mStopToast = Toast
2200                 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2201         mStopToast.show();
2202     }
2203
2204     boolean didUserStopLoading() {
2205         return mDidStopLoad;
2206     }
2207
2208     private void cancelStopToast() {
2209         if (mStopToast != null) {
2210             mStopToast.cancel();
2211             mStopToast = null;
2212         }
2213     }
2214
2215     // called by a UI or non-UI thread to post the message
2216     public void postMessage(int what, int arg1, int arg2, Object obj,
2217             long delayMillis) {
2218         mHandler.sendMessageDelayed(mHandler.obtainMessage(what, arg1, arg2,
2219                 obj), delayMillis);
2220     }
2221
2222     // called by a UI or non-UI thread to remove the message
2223     void removeMessages(int what, Object object) {
2224         mHandler.removeMessages(what, object);
2225     }
2226
2227     // public message ids
2228     public final static int LOAD_URL                = 1001;
2229     public final static int STOP_LOAD               = 1002;
2230
2231     // Message Ids
2232     private static final int FOCUS_NODE_HREF         = 102;
2233     private static final int CANCEL_CREDS_REQUEST    = 103;
2234     private static final int RELEASE_WAKELOCK        = 107;
2235
2236     static final int UPDATE_BOOKMARK_THUMBNAIL       = 108;
2237
2238     // Private handler for handling javascript and saving passwords
2239     private Handler mHandler = new Handler() {
2240
2241         public void handleMessage(Message msg) {
2242             switch (msg.what) {
2243                 case FOCUS_NODE_HREF:
2244                 {
2245                     String url = (String) msg.getData().get("url");
2246                     String title = (String) msg.getData().get("title");
2247                     if (url == null || url.length() == 0) {
2248                         break;
2249                     }
2250                     HashMap focusNodeMap = (HashMap) msg.obj;
2251                     WebView view = (WebView) focusNodeMap.get("webview");
2252                     // Only apply the action if the top window did not change.
2253                     if (getTopWindow() != view) {
2254                         break;
2255                     }
2256                     switch (msg.arg1) {
2257                         case R.id.open_context_menu_id:
2258                         case R.id.view_image_context_menu_id:
2259                             loadURL(getTopWindow(), url);
2260                             break;
2261                         case R.id.open_newtab_context_menu_id:
2262                             final Tab parent = mTabControl.getCurrentTab();
2263                             final Tab newTab = openTab(url);
2264                             if (newTab != parent) {
2265                                 parent.addChildTab(newTab);
2266                             }
2267                             break;
2268                         case R.id.bookmark_context_menu_id:
2269                             Intent intent = new Intent(BrowserActivity.this,
2270                                     AddBookmarkPage.class);
2271                             intent.putExtra("url", url);
2272                             intent.putExtra("title", title);
2273                             startActivity(intent);
2274                             break;
2275                         case R.id.share_link_context_menu_id:
2276                             // See if this site has been visited before
2277                             StringBuilder sb = new StringBuilder(
2278                                     Browser.BookmarkColumns.URL + " = ");
2279                             DatabaseUtils.appendEscapedSQLString(sb, url);
2280                             Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
2281                                     Browser.HISTORY_PROJECTION,
2282                                     sb.toString(),
2283                                     null,
2284                                     null);
2285                             if (c.moveToFirst()) {
2286                                 // The site has been visited before, so grab the
2287                                 // info from the database.
2288                                 Bitmap favicon = null;
2289                                 Bitmap thumbnail = null;
2290                                 String linkTitle = c.getString(Browser.
2291                                         HISTORY_PROJECTION_TITLE_INDEX);
2292                                 byte[] data = c.getBlob(Browser.
2293                                         HISTORY_PROJECTION_FAVICON_INDEX);
2294                                 if (data != null) {
2295                                     favicon = BitmapFactory.decodeByteArray(
2296                                             data, 0, data.length);
2297                                 }
2298                                 data = c.getBlob(Browser.
2299                                         HISTORY_PROJECTION_THUMBNAIL_INDEX);
2300                                 if (data != null) {
2301                                     thumbnail = BitmapFactory.decodeByteArray(
2302                                             data, 0, data.length);
2303                                 }
2304                                 sharePage(BrowserActivity.this,
2305                                         linkTitle, url, favicon, thumbnail);
2306                             } else {
2307                                 Browser.sendString(BrowserActivity.this, url,
2308                                         getString(
2309                                         R.string.choosertitle_sharevia));
2310                             }
2311                             break;
2312                         case R.id.copy_link_context_menu_id:
2313                             copy(url);
2314                             break;
2315                         case R.id.save_link_context_menu_id:
2316                         case R.id.download_context_menu_id:
2317                             onDownloadStartNoStream(url, null, null, null, -1);
2318                             break;
2319                     }
2320                     break;
2321                 }
2322
2323                 case LOAD_URL:
2324                     loadURL(getTopWindow(), (String) msg.obj);
2325                     break;
2326
2327                 case STOP_LOAD:
2328                     stopLoading();
2329                     break;
2330
2331                 case CANCEL_CREDS_REQUEST:
2332                     resumeAfterCredentials();
2333                     break;
2334
2335                 case RELEASE_WAKELOCK:
2336                     if (mWakeLock.isHeld()) {
2337                         mWakeLock.release();
2338                         // if we reach here, Browser should be still in the
2339                         // background loading after WAKELOCK_TIMEOUT (5-min).
2340                         // To avoid burning the battery, stop loading.
2341                         mTabControl.stopAllLoading();
2342                     }
2343                     break;
2344
2345                 case UPDATE_BOOKMARK_THUMBNAIL:
2346                     WebView view = (WebView) msg.obj;
2347                     if (view != null) {
2348                         updateScreenshot(view);
2349                     }
2350                     break;
2351             }
2352         }
2353     };
2354
2355     /**
2356      * Share a page, providing the title, url, favicon, and a screenshot.  Uses
2357      * an {@link Intent} to launch the Activity chooser.
2358      * @param c Context used to launch a new Activity.
2359      * @param title Title of the page.  Stored in the Intent with
2360      *          {@link Browser#EXTRA_SHARE_TITLE}
2361      * @param url URL of the page.  Stored in the Intent with
2362      *          {@link Intent#EXTRA_TEXT}
2363      * @param favicon Bitmap of the favicon for the page.  Stored in the Intent
2364      *          with {@link Browser#EXTRA_SHARE_FAVICON}
2365      * @param screenshot Bitmap of a screenshot of the page.  Stored in the
2366      *          Intent with {@link Browser#EXTRA_SHARE_SCREENSHOT}
2367      */
2368     public static final void sharePage(Context c, String title, String url,
2369             Bitmap favicon, Bitmap screenshot) {
2370         Intent send = new Intent(Intent.ACTION_SEND);
2371         send.setType("text/plain");
2372         send.putExtra(Intent.EXTRA_TEXT, url);
2373         send.putExtra(Browser.EXTRA_SHARE_TITLE, title);
2374         send.putExtra(Browser.EXTRA_SHARE_FAVICON, favicon);
2375         send.putExtra(Browser.EXTRA_SHARE_SCREENSHOT, screenshot);
2376         try {
2377             c.startActivity(Intent.createChooser(send, c.getString(
2378                     R.string.choosertitle_sharevia)));
2379         } catch(android.content.ActivityNotFoundException ex) {
2380             // if no app handles it, do nothing
2381         }
2382     }
2383
2384     private void updateScreenshot(WebView view) {
2385         // If this is a bookmarked site, add a screenshot to the database.
2386         // FIXME: When should we update?  Every time?
2387         // FIXME: Would like to make sure there is actually something to
2388         // draw, but the API for that (WebViewCore.pictureReady()) is not
2389         // currently accessible here.
2390
2391         ContentResolver cr = getContentResolver();
2392         final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
2393                 cr, view.getOriginalUrl(), view.getUrl(), true);
2394         if (c != null) {
2395             boolean succeed = c.moveToFirst();
2396             ContentValues values = null;
2397             while (succeed) {
2398                 if (values == null) {
2399                     final ByteArrayOutputStream os
2400                             = new ByteArrayOutputStream();
2401                     Bitmap bm = createScreenshot(view);
2402                     if (bm == null) {
2403                         c.close();
2404                         return;
2405                     }
2406                     bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2407                     values = new ContentValues();
2408                     values.put(Browser.BookmarkColumns.THUMBNAIL,
2409                             os.toByteArray());
2410                 }
2411                 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2412                         c.getInt(0)), values, null, null);
2413                 succeed = c.moveToNext();
2414             }
2415             c.close();
2416         }
2417     }
2418
2419     /**
2420      * Values for the size of the thumbnail created when taking a screenshot.
2421      * Lazily initialized.  Instead of using these directly, use
2422      * getDesiredThumbnailWidth() or getDesiredThumbnailHeight().
2423      */
2424     private static int THUMBNAIL_WIDTH = 0;
2425     private static int THUMBNAIL_HEIGHT = 0;
2426
2427     /**
2428      * Return the desired width for thumbnail screenshots, which are stored in
2429      * the database, and used on the bookmarks screen.
2430      * @param context Context for finding out the density of the screen.
2431      * @return int desired width for thumbnail screenshot.
2432      */
2433     /* package */ static int getDesiredThumbnailWidth(Context context) {
2434         if (THUMBNAIL_WIDTH == 0) {
2435             float density = context.getResources().getDisplayMetrics().density;
2436             THUMBNAIL_WIDTH = (int) (90 * density);
2437             THUMBNAIL_HEIGHT = (int) (80 * density);
2438         }
2439         return THUMBNAIL_WIDTH;
2440     }
2441
2442     /**
2443      * Return the desired height for thumbnail screenshots, which are stored in
2444      * the database, and used on the bookmarks screen.
2445      * @param context Context for finding out the density of the screen.
2446      * @return int desired height for thumbnail screenshot.
2447      */
2448     /* package */ static int getDesiredThumbnailHeight(Context context) {
2449         // To ensure that they are both initialized.
2450         getDesiredThumbnailWidth(context);
2451         return THUMBNAIL_HEIGHT;
2452     }
2453
2454     private Bitmap createScreenshot(WebView view) {
2455         Picture thumbnail = view.capturePicture();
2456         if (thumbnail == null) {
2457             return null;
2458         }
2459         Bitmap bm = Bitmap.createBitmap(getDesiredThumbnailWidth(this),
2460                 getDesiredThumbnailHeight(this), Bitmap.Config.ARGB_4444);
2461         Canvas canvas = new Canvas(bm);
2462         // May need to tweak these values to determine what is the
2463         // best scale factor
2464         int thumbnailWidth = thumbnail.getWidth();
2465         int thumbnailHeight = thumbnail.getHeight();
2466         float scaleFactorX = 1.0f;
2467         float scaleFactorY = 1.0f;
2468         if (thumbnailWidth > 0) {
2469             scaleFactorX = (float) getDesiredThumbnailWidth(this) /
2470                     (float)thumbnailWidth;
2471         } else {
2472             return null;
2473         }
2474
2475         if (view.getWidth() > view.getHeight() &&
2476                 thumbnailHeight < view.getHeight() && thumbnailHeight > 0) {
2477             // If the device is in landscape and the page is shorter
2478             // than the height of the view, stretch the thumbnail to fill the
2479             // space.
2480             scaleFactorY = (float) getDesiredThumbnailHeight(this) /
2481                     (float)thumbnailHeight;
2482         } else {
2483             // In the portrait case, this looks nice.
2484             scaleFactorY = scaleFactorX;
2485         }
2486
2487         canvas.scale(scaleFactorX, scaleFactorY);
2488
2489         thumbnail.draw(canvas);
2490         return bm;
2491     }
2492
2493     // -------------------------------------------------------------------------
2494     // Helper function for WebViewClient.
2495     //-------------------------------------------------------------------------
2496
2497     // Use in overrideUrlLoading
2498     /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2499     /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2500     /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2501     /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2502
2503     void onPageStarted(WebView view, String url, Bitmap favicon) {
2504         // when BrowserActivity just starts, onPageStarted may be called before
2505         // onResume as it is triggered from onCreate. Call resumeWebViewTimers
2506         // to start the timer. As we won't switch tabs while an activity is in
2507         // pause state, we can ensure calling resume and pause in pair.
2508         if (mActivityInPause) resumeWebViewTimers();
2509
2510         resetLockIcon(url);
2511         setUrlTitle(url, null);
2512         setFavicon(favicon);
2513         // Keep this initial progress in sync with initialProgressValue (* 100)
2514         // in ProgressTracker.cpp
2515         // Show some progress so that the user knows the page is beginning to
2516         // load
2517         onProgressChanged(view, 10);
2518         mDidStopLoad = false;
2519         if (!mIsNetworkUp) createAndShowNetworkDialog();
2520
2521         if (mSettings.isTracing()) {
2522             String host;
2523             try {
2524                 WebAddress uri = new WebAddress(url);
2525                 host = uri.mHost;
2526             } catch (android.net.ParseException ex) {
2527                 host = "browser";
2528             }
2529             host = host.replace('.', '_');
2530             host += ".trace";
2531             mInTrace = true;
2532             Debug.startMethodTracing(host, 20 * 1024 * 1024);
2533         }
2534
2535         // Performance probe
2536         if (false) {
2537             mStart = SystemClock.uptimeMillis();
2538             mProcessStart = Process.getElapsedCpuTime();
2539             long[] sysCpu = new long[7];
2540             if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2541                     sysCpu, null)) {
2542                 mUserStart = sysCpu[0] + sysCpu[1];
2543                 mSystemStart = sysCpu[2];
2544                 mIdleStart = sysCpu[3];
2545                 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2546             }
2547             mUiStart = SystemClock.currentThreadTimeMillis();
2548         }
2549     }
2550
2551     void onPageFinished(WebView view, String url) {
2552         // Reset the title and icon in case we stopped a provisional load.
2553         resetTitleAndIcon(view);
2554         // Update the lock icon image only once we are done loading
2555         updateLockIconToLatest();
2556         // pause the WebView timer and release the wake lock if it is finished
2557         // while BrowserActivity is in pause state.
2558         if (mActivityInPause && pauseWebViewTimers()) {
2559             if (mWakeLock.isHeld()) {
2560                 mHandler.removeMessages(RELEASE_WAKELOCK);
2561                 mWakeLock.release();
2562             }
2563         }
2564
2565         // Performance probe
2566         if (false) {
2567             long[] sysCpu = new long[7];
2568             if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2569                     sysCpu, null)) {
2570                 String uiInfo = "UI thread used "
2571                         + (SystemClock.currentThreadTimeMillis() - mUiStart)
2572                         + " ms";
2573                 if (LOGD_ENABLED) {
2574                     Log.d(LOGTAG, uiInfo);
2575                 }
2576                 //The string that gets written to the log
2577                 String performanceString = "It took total "
2578                         + (SystemClock.uptimeMillis() - mStart)
2579                         + " ms clock time to load the page."
2580                         + "\nbrowser process used "
2581                         + (Process.getElapsedCpuTime() - mProcessStart)
2582                         + " ms, user processes used "
2583                         + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2584                         + " ms, kernel used "
2585                         + (sysCpu[2] - mSystemStart) * 10
2586                         + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2587                         + " ms and irq took "
2588                         + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2589                         * 10 + " ms, " + uiInfo;
2590                 if (LOGD_ENABLED) {
2591                     Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2592                 }
2593                 if (url != null) {
2594                     // strip the url to maintain consistency
2595                     String newUrl = new String(url);
2596                     if (newUrl.startsWith("http://www.")) {
2597                         newUrl = newUrl.substring(11);
2598                     } else if (newUrl.startsWith("http://")) {
2599                         newUrl = newUrl.substring(7);
2600                     } else if (newUrl.startsWith("https://www.")) {
2601                         newUrl = newUrl.substring(12);
2602                     } else if (newUrl.startsWith("https://")) {
2603                         newUrl = newUrl.substring(8);
2604                     }
2605                     if (LOGD_ENABLED) {
2606                         Log.d(LOGTAG, newUrl + " loaded");
2607                     }
2608                 }
2609             }
2610          }
2611
2612         if (mInTrace) {
2613             mInTrace = false;
2614             Debug.stopMethodTracing();
2615         }
2616     }
2617
2618     boolean shouldOverrideUrlLoading(WebView view, String url) {
2619         if (url.startsWith(SCHEME_WTAI)) {
2620             // wtai://wp/mc;number
2621             // number=string(phone-number)
2622             if (url.startsWith(SCHEME_WTAI_MC)) {
2623                 Intent intent = new Intent(Intent.ACTION_VIEW,
2624                         Uri.parse(WebView.SCHEME_TEL +
2625                         url.substring(SCHEME_WTAI_MC.length())));
2626                 startActivity(intent);
2627                 return true;
2628             }
2629             // wtai://wp/sd;dtmf
2630             // dtmf=string(dialstring)
2631             if (url.startsWith(SCHEME_WTAI_SD)) {
2632                 // TODO: only send when there is active voice connection
2633                 return false;
2634             }
2635             // wtai://wp/ap;number;name
2636             // number=string(phone-number)
2637             // name=string
2638             if (url.startsWith(SCHEME_WTAI_AP)) {
2639                 // TODO
2640                 return false;
2641             }
2642         }
2643
2644         // The "about:" schemes are internal to the browser; don't want these to
2645         // be dispatched to other apps.
2646         if (url.startsWith("about:")) {
2647             return false;
2648         }
2649
2650         Intent intent;
2651         // perform generic parsing of the URI to turn it into an Intent.
2652         try {
2653             intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
2654         } catch (URISyntaxException ex) {
2655             Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
2656             return false;
2657         }
2658
2659         // check whether the intent can be resolved. If not, we will see
2660         // whether we can download it from the Market.
2661         if (getPackageManager().resolveActivity(intent, 0) == null) {
2662             String packagename = intent.getPackage();
2663             if (packagename != null) {
2664                 intent = new Intent(Intent.ACTION_VIEW, Uri
2665                         .parse("market://search?q=pname:" + packagename));
2666                 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2667                 startActivity(intent);
2668                 return true;
2669             } else {
2670                 return false;
2671             }
2672         }
2673
2674         // sanitize the Intent, ensuring web pages can not bypass browser
2675         // security (only access to BROWSABLE activities).
2676         intent.addCategory(Intent.CATEGORY_BROWSABLE);
2677         intent.setComponent(null);
2678         try {
2679             if (startActivityIfNeeded(intent, -1)) {
2680                 return true;
2681             }
2682         } catch (ActivityNotFoundException ex) {
2683             // ignore the error. If no application can handle the URL,
2684             // eg about:blank, assume the browser can handle it.
2685         }
2686
2687         if (mMenuIsDown) {
2688             openTab(url);
2689             closeOptionsMenu();
2690             return true;
2691         }
2692         return false;
2693     }
2694
2695     // -------------------------------------------------------------------------
2696     // Helper function for WebChromeClient
2697     // -------------------------------------------------------------------------
2698
2699     void onProgressChanged(WebView view, int newProgress) {
2700         mTitleBar.setProgress(newProgress);
2701         mFakeTitleBar.setProgress(newProgress);
2702
2703         if (newProgress == 100) {
2704             // onProgressChanged() may continue to be called after the main
2705             // frame has finished loading, as any remaining sub frames continue
2706             // to load. We'll only get called once though with newProgress as
2707             // 100 when everything is loaded. (onPageFinished is called once
2708             // when the main frame completes loading regardless of the state of
2709             // any sub frames so calls to onProgressChanges may continue after
2710             // onPageFinished has executed)
2711             if (mInLoad) {
2712                 mInLoad = false;
2713                 updateInLoadMenuItems();
2714                 // If the options menu is open, leave the title bar
2715                 if (!mOptionsMenuOpen || !mIconView) {
2716                     hideFakeTitleBar();
2717                 }
2718             }
2719         } else if (!mInLoad) {
2720             // onPageFinished may have already been called but a subframe is
2721             // still loading and updating the progress. Reset mInLoad and update
2722             // the menu items.
2723             mInLoad = true;
2724             updateInLoadMenuItems();
2725             if (!mOptionsMenuOpen || mIconView) {
2726                 // This page has begun to load, so show the title bar
2727                 showFakeTitleBar();
2728             }
2729         }
2730     }
2731
2732     void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
2733         // if a view already exists then immediately terminate the new one
2734         if (mCustomView != null) {
2735             callback.onCustomViewHidden();
2736             return;
2737         }
2738
2739         // Add the custom view to its container.
2740         mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
2741         mCustomView = view;
2742         mCustomViewCallback = callback;
2743         // Save the menu state and set it to empty while the custom
2744         // view is showing.
2745         mOldMenuState = mMenuState;
2746         mMenuState = EMPTY_MENU;
2747         // Hide the content view.
2748         mContentView.setVisibility(View.GONE);
2749         // Finally show the custom view container.
2750         setStatusBarVisibility(false);
2751         mCustomViewContainer.setVisibility(View.VISIBLE);
2752         mCustomViewContainer.bringToFront();
2753     }
2754
2755     void onHideCustomView() {
2756         if (mCustomView == null)
2757             return;
2758
2759         // Hide the custom view.
2760         mCustomView.setVisibility(View.GONE);
2761         // Remove the custom view from its container.
2762         mCustomViewContainer.removeView(mCustomView);
2763         mCustomView = null;
2764         // Reset the old menu state.
2765         mMenuState = mOldMenuState;
2766         mOldMenuState = EMPTY_MENU;
2767         mCustomViewContainer.setVisibility(View.GONE);
2768         mCustomViewCallback.onCustomViewHidden();
2769         // Show the content view.
2770         setStatusBarVisibility(true);
2771         mContentView.setVisibility(View.VISIBLE);
2772     }
2773
2774     Bitmap getDefaultVideoPoster() {
2775         if (mDefaultVideoPoster == null) {
2776             mDefaultVideoPoster = BitmapFactory.decodeResource(
2777                     getResources(), R.drawable.default_video_poster);
2778         }
2779         return mDefaultVideoPoster;
2780     }
2781
2782     View getVideoLoadingProgressView() {
2783         if (mVideoProgressView == null) {
2784             LayoutInflater inflater = LayoutInflater.from(BrowserActivity.this);
2785             mVideoProgressView = inflater.inflate(
2786                     R.layout.video_loading_progress, null);
2787         }
2788         return mVideoProgressView;
2789     }
2790
2791     /*
2792      * The Object used to inform the WebView of the file to upload.
2793      */
2794     private ValueCallback<Uri> mUploadMessage;
2795
2796     void openFileChooser(ValueCallback<Uri> uploadMsg) {
2797         if (mUploadMessage != null) return;
2798         mUploadMessage = uploadMsg;
2799         Intent i = new Intent(Intent.ACTION_GET_CONTENT);
2800         i.addCategory(Intent.CATEGORY_OPENABLE);
2801         i.setType("*/*");
2802         BrowserActivity.this.startActivityForResult(Intent.createChooser(i,
2803                 getString(R.string.choose_upload)), FILE_SELECTED);
2804     }
2805
2806     // -------------------------------------------------------------------------
2807     // Implement functions for DownloadListener
2808     // -------------------------------------------------------------------------
2809
2810     /**
2811      * Notify the host application a download should be done, or that
2812      * the data should be streamed if a streaming viewer is available.
2813      * @param url The full url to the content that should be downloaded
2814      * @param contentDisposition Content-disposition http header, if
2815      *                           present.
2816      * @param mimetype The mimetype of the content reported by the server
2817      * @param contentLength The file size reported by the server
2818      */
2819     public void onDownloadStart(String url, String userAgent,
2820             String contentDisposition, String mimetype, long contentLength) {
2821         // if we're dealing wih A/V content that's not explicitly marked
2822         //     for download, check if it's streamable.
2823         if (contentDisposition == null
2824                 || !contentDisposition.regionMatches(
2825                         true, 0, "attachment", 0, 10)) {
2826             // query the package manager to see if there's a registered handler
2827             //     that matches.
2828             Intent intent = new Intent(Intent.ACTION_VIEW);
2829             intent.setDataAndType(Uri.parse(url), mimetype);
2830             ResolveInfo info = getPackageManager().resolveActivity(intent,
2831                     PackageManager.MATCH_DEFAULT_ONLY);
2832             if (info != null) {
2833                 ComponentName myName = getComponentName();
2834                 // If we resolved to ourselves, we don't want to attempt to
2835                 // load the url only to try and download it again.
2836                 if (!myName.getPackageName().equals(
2837                         info.activityInfo.packageName)
2838                         || !myName.getClassName().equals(
2839                                 info.activityInfo.name)) {
2840                     // someone (other than us) knows how to handle this mime
2841                     // type with this scheme, don't download.
2842                     try {
2843                         startActivity(intent);
2844                         return;
2845                     } catch (ActivityNotFoundException ex) {
2846                         if (LOGD_ENABLED) {
2847                             Log.d(LOGTAG, "activity not found for " + mimetype
2848                                     + " over " + Uri.parse(url).getScheme(),
2849                                     ex);
2850                         }
2851                         // Best behavior is to fall back to a download in this
2852                         // case
2853                     }
2854                 }
2855             }
2856         }
2857         onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
2858     }
2859
2860     /**
2861      * Notify the host application a download should be done, even if there
2862      * is a streaming viewer available for thise type.
2863      * @param url The full url to the content that should be downloaded
2864      * @param contentDisposition Content-disposition http header, if
2865      *                           present.
2866      * @param mimetype The mimetype of the content reported by the server
2867      * @param contentLength The file size reported by the server
2868      */
2869     /*package */ void onDownloadStartNoStream(String url, String userAgent,
2870             String contentDisposition, String mimetype, long contentLength) {
2871
2872         String filename = URLUtil.guessFileName(url,
2873                 contentDisposition, mimetype);
2874
2875         // Check to see if we have an SDCard
2876         String status = Environment.getExternalStorageState();
2877         if (!status.equals(Environment.MEDIA_MOUNTED)) {
2878             int title;
2879             String msg;
2880
2881             // Check to see if the SDCard is busy, same as the music app
2882             if (status.equals(Environment.MEDIA_SHARED)) {
2883                 msg = getString(R.string.download_sdcard_busy_dlg_msg);
2884                 title = R.string.download_sdcard_busy_dlg_title;
2885             } else {
2886                 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
2887                 title = R.string.download_no_sdcard_dlg_title;
2888             }
2889
2890             new AlertDialog.Builder(this)
2891                 .setTitle(title)
2892                 .setIcon(android.R.drawable.ic_dialog_alert)
2893                 .setMessage(msg)
2894                 .setPositiveButton(R.string.ok, null)
2895                 .show();
2896             return;
2897         }
2898
2899         // java.net.URI is a lot stricter than KURL so we have to undo
2900         // KURL's percent-encoding and redo the encoding using java.net.URI.
2901         URI uri = null;
2902         try {
2903             // Undo the percent-encoding that KURL may have done.
2904             String newUrl = new String(URLUtil.decode(url.getBytes()));
2905             // Parse the url into pieces
2906             WebAddress w = new WebAddress(newUrl);
2907             String frag = null;
2908             String query = null;
2909             String path = w.mPath;
2910             // Break the path into path, query, and fragment
2911             if (path.length() > 0) {
2912                 // Strip the fragment
2913                 int idx = path.lastIndexOf('#');
2914                 if (idx != -1) {
2915                     frag = path.substring(idx + 1);
2916                     path = path.substring(0, idx);
2917                 }
2918                 idx = path.lastIndexOf('?');
2919                 if (idx != -1) {
2920                     query = path.substring(idx + 1);
2921                     path = path.substring(0, idx);
2922                 }
2923             }
2924             uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
2925                     query, frag);
2926         } catch (Exception e) {
2927             Log.e(LOGTAG, "Could not parse url for download: " + url, e);
2928             return;
2929         }
2930
2931         // XXX: Have to use the old url since the cookies were stored using the
2932         // old percent-encoded url.
2933         String cookies = CookieManager.getInstance().getCookie(url);
2934
2935         ContentValues values = new ContentValues();
2936         values.put(Downloads.Impl.COLUMN_URI, uri.toString());
2937         values.put(Downloads.Impl.COLUMN_COOKIE_DATA, cookies);
2938         values.put(Downloads.Impl.COLUMN_USER_AGENT, userAgent);
2939         values.put(Downloads.Impl.COLUMN_NOTIFICATION_PACKAGE,
2940                 getPackageName());
2941         values.put(Downloads.Impl.COLUMN_NOTIFICATION_CLASS,
2942                 BrowserDownloadPage.class.getCanonicalName());
2943         values.put(Downloads.Impl.COLUMN_VISIBILITY,
2944                 Downloads.Impl.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
2945         values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimetype);
2946         values.put(Downloads.Impl.COLUMN_FILE_NAME_HINT, filename);
2947         values.put(Downloads.Impl.COLUMN_DESCRIPTION, uri.getHost());
2948         if (contentLength > 0) {
2949             values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, contentLength);
2950         }
2951         if (mimetype == null) {
2952             // We must have long pressed on a link or image to download it. We
2953             // are not sure of the mimetype in this case, so do a head request
2954             new FetchUrlMimeType(this).execute(values);
2955         } else {
2956             final Uri contentUri =
2957                     getContentResolver().insert(Downloads.Impl.CONTENT_URI, values);
2958         }
2959
2960     }
2961
2962     // -------------------------------------------------------------------------
2963
2964     /**
2965      * Resets the lock icon. This method is called when we start a new load and
2966      * know the url to be loaded.
2967      */
2968     private void resetLockIcon(String url) {
2969         // Save the lock-icon state (we revert to it if the load gets cancelled)
2970         mTabControl.getCurrentTab().resetLockIcon(url);
2971         updateLockIconImage(LOCK_ICON_UNSECURE);
2972     }
2973
2974     /**
2975      * Update the lock icon to correspond to our latest state.
2976      */
2977     private void updateLockIconToLatest() {
2978         updateLockIconImage(mTabControl.getCurrentTab().getLockIconType());
2979     }
2980
2981     /**
2982      * Updates the lock-icon image in the title-bar.
2983      */
2984     private void updateLockIconImage(int lockIconType) {
2985         Drawable d = null;
2986         if (lockIconType == LOCK_ICON_SECURE) {
2987             d = mSecLockIcon;
2988         } else if (lockIconType == LOCK_ICON_MIXED) {
2989             d = mMixLockIcon;
2990         }
2991         mTitleBar.setLock(d);
2992         mFakeTitleBar.setLock(d);
2993     }
2994
2995     /**
2996      * Displays a page-info dialog.
2997      * @param tab The tab to show info about
2998      * @param fromShowSSLCertificateOnError The flag that indicates whether
2999      * this dialog was opened from the SSL-certificate-on-error dialog or
3000      * not. This is important, since we need to know whether to return to
3001      * the parent dialog or simply dismiss.
3002      */
3003     private void showPageInfo(final Tab tab,
3004                               final boolean fromShowSSLCertificateOnError) {
3005         final LayoutInflater factory = LayoutInflater
3006                 .from(this);
3007
3008         final View pageInfoView = factory.inflate(R.layout.page_info, null);
3009
3010         final WebView view = tab.getWebView();
3011
3012         String url = null;
3013         String title = null;
3014
3015         if (view == null) {
3016             url = tab.getUrl();
3017             title = tab.getTitle();
3018         } else if (view == mTabControl.getCurrentWebView()) {
3019              // Use the cached title and url if this is the current WebView
3020             url = mUrl;
3021             title = mTitle;
3022         } else {
3023             url = view.getUrl();
3024             title = view.getTitle();
3025         }
3026
3027         if (url == null) {
3028             url = "";
3029         }
3030         if (title == null) {
3031             title = "";
3032         }
3033
3034         ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3035         ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3036
3037         mPageInfoView = tab;
3038         mPageInfoFromShowSSLCertificateOnError = fromShowSSLCertificateOnError;
3039
3040         AlertDialog.Builder alertDialogBuilder =
3041             new AlertDialog.Builder(this)
3042             .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3043             .setView(pageInfoView)
3044             .setPositiveButton(
3045                 R.string.ok,
3046                 new DialogInterface.OnClickListener() {
3047                     public void onClick(DialogInterface dialog,
3048                                         int whichButton) {
3049                         mPageInfoDialog = null;
3050                         mPageInfoView = null;
3051
3052                         // if we came here from the SSL error dialog
3053                         if (fromShowSSLCertificateOnError) {
3054                             // go back to the SSL error dialog
3055                             showSSLCertificateOnError(
3056                                 mSSLCertificateOnErrorView,
3057                                 mSSLCertificateOnErrorHandler,
3058                                 mSSLCertificateOnErrorError);
3059                         }
3060                     }
3061                 })
3062             .setOnCancelListener(
3063                 new DialogInterface.OnCancelListener() {
3064                     public void onCancel(DialogInterface dialog) {
3065                         mPageInfoDialog = null;
3066                         mPageInfoView = null;
3067
3068                         // if we came here from the SSL error dialog
3069                         if (fromShowSSLCertificateOnError) {
3070                             // go back to the SSL error dialog
3071                             showSSLCertificateOnError(
3072                                 mSSLCertificateOnErrorView,
3073                                 mSSLCertificateOnErrorHandler,
3074                                 mSSLCertificateOnErrorError);
3075                         }
3076                     }
3077                 });
3078
3079         // if we have a main top-level page SSL certificate set or a certificate
3080         // error
3081         if (fromShowSSLCertificateOnError ||
3082                 (view != null && view.getCertificate() != null)) {
3083             // add a 'View Certificate' button
3084             alertDialogBuilder.setNeutralButton(
3085                 R.string.view_certificate,
3086                 new DialogInterface.OnClickListener() {
3087                     public void onClick(DialogInterface dialog,
3088                                         int whichButton) {
3089                         mPageInfoDialog = null;
3090                         mPageInfoView = null;
3091
3092                         // if we came here from the SSL error dialog
3093                         if (fromShowSSLCertificateOnError) {
3094                             // go back to the SSL error dialog
3095                             showSSLCertificateOnError(
3096                                 mSSLCertificateOnErrorView,
3097                                 mSSLCertificateOnErrorHandler,
3098                                 mSSLCertificateOnErrorError);
3099                         } else {
3100                             // otherwise, display the top-most certificate from
3101                             // the chain
3102                             if (view.getCertificate() != null) {
3103                                 showSSLCertificate(tab);
3104                             }
3105                         }
3106                     }
3107                 });
3108         }
3109
3110         mPageInfoDialog = alertDialogBuilder.show();
3111     }
3112
3113        /**
3114      * Displays the main top-level page SSL certificate dialog
3115      * (accessible from the Page-Info dialog).
3116      * @param tab The tab to show certificate for.
3117      */
3118     private void showSSLCertificate(final Tab tab) {
3119         final View certificateView =
3120                 inflateCertificateView(tab.getWebView().getCertificate());
3121         if (certificateView == null) {
3122             return;
3123         }
3124
3125         LayoutInflater factory = LayoutInflater.from(this);
3126
3127         final LinearLayout placeholder =
3128                 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3129
3130         LinearLayout ll = (LinearLayout) factory.inflate(
3131             R.layout.ssl_success, placeholder);
3132         ((TextView)ll.findViewById(R.id.success))
3133             .setText(R.string.ssl_certificate_is_valid);
3134
3135         mSSLCertificateView = tab;
3136         mSSLCertificateDialog =
3137             new AlertDialog.Builder(this)
3138                 .setTitle(R.string.ssl_certificate).setIcon(
3139                     R.drawable.ic_dialog_browser_certificate_secure)
3140                 .setView(certificateView)
3141                 .setPositiveButton(R.string.ok,
3142                         new DialogInterface.OnClickListener() {
3143                             public void onClick(DialogInterface dialog,
3144                                     int whichButton) {
3145                                 mSSLCertificateDialog = null;
3146                                 mSSLCertificateView = null;
3147
3148                                 showPageInfo(tab, false);
3149                             }
3150                         })
3151                 .setOnCancelListener(
3152                         new DialogInterface.OnCancelListener() {
3153                             public void onCancel(DialogInterface dialog) {
3154                                 mSSLCertificateDialog = null;
3155                                 mSSLCertificateView = null;
3156
3157                                 showPageInfo(tab, false);
3158                             }
3159                         })
3160                 .show();
3161     }
3162
3163     /**
3164      * Displays the SSL error certificate dialog.
3165      * @param view The target web-view.
3166      * @param handler The SSL error handler responsible for cancelling the
3167      * connection that resulted in an SSL error or proceeding per user request.
3168      * @param error The SSL error object.
3169      */
3170     void showSSLCertificateOnError(
3171         final WebView view, final SslErrorHandler handler, final SslError error) {
3172
3173         final View certificateView =
3174             inflateCertificateView(error.getCertificate());
3175         if (certificateView == null) {
3176             return;
3177         }
3178
3179         LayoutInflater factory = LayoutInflater.from(this);
3180
3181         final LinearLayout placeholder =
3182                 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3183
3184         if (error.hasError(SslError.SSL_UNTRUSTED)) {
3185             LinearLayout ll = (LinearLayout)factory
3186                 .inflate(R.layout.ssl_warning, placeholder);
3187             ((TextView)ll.findViewById(R.id.warning))
3188                 .setText(R.string.ssl_untrusted);
3189         }
3190
3191         if (error.hasError(SslError.SSL_IDMISMATCH)) {
3192             LinearLayout ll = (LinearLayout)factory
3193                 .inflate(R.layout.ssl_warning, placeholder);
3194             ((TextView)ll.findViewById(R.id.warning))
3195                 .setText(R.string.ssl_mismatch);
3196         }
3197
3198         if (error.hasError(SslError.SSL_EXPIRED)) {
3199             LinearLayout ll = (LinearLayout)factory
3200                 .inflate(R.layout.ssl_warning, placeholder);
3201             ((TextView)ll.findViewById(R.id.warning))
3202                 .setText(R.string.ssl_expired);
3203         }
3204
3205         if (error.hasError(SslError.SSL_NOTYETVALID)) {
3206             LinearLayout ll = (LinearLayout)factory
3207                 .inflate(R.layout.ssl_warning, placeholder);
3208             ((TextView)ll.findViewById(R.id.warning))
3209                 .setText(R.string.ssl_not_yet_valid);
3210         }
3211
3212         mSSLCertificateOnErrorHandler = handler;
3213         mSSLCertificateOnErrorView = view;
3214         mSSLCertificateOnErrorError = error;
3215         mSSLCertificateOnErrorDialog =
3216             new AlertDialog.Builder(this)
3217                 .setTitle(R.string.ssl_certificate).setIcon(
3218                     R.drawable.ic_dialog_browser_certificate_partially_secure)
3219                 .setView(certificateView)
3220                 .setPositiveButton(R.string.ok,
3221                         new DialogInterface.OnClickListener() {
3222                             public void onClick(DialogInterface dialog,
3223                                     int whichButton) {
3224                                 mSSLCertificateOnErrorDialog = null;
3225                                 mSSLCertificateOnErrorView = null;
3226                                 mSSLCertificateOnErrorHandler = null;
3227                                 mSSLCertificateOnErrorError = null;
3228
3229                                 view.getWebViewClient().onReceivedSslError(
3230                                                 view, handler, error);
3231                             }
3232                         })
3233                  .setNeutralButton(R.string.page_info_view,
3234                         new DialogInterface.OnClickListener() {
3235                             public void onClick(DialogInterface dialog,
3236                                     int whichButton) {
3237                                 mSSLCertificateOnErrorDialog = null;
3238
3239                                 // do not clear the dialog state: we will
3240                                 // need to show the dialog again once the
3241                                 // user is done exploring the page-info details
3242
3243                                 showPageInfo(mTabControl.getTabFromView(view),
3244                                         true);
3245                             }
3246                         })
3247                 .setOnCancelListener(
3248                         new DialogInterface.OnCancelListener() {
3249                             public void onCancel(DialogInterface dialog) {
3250                                 mSSLCertificateOnErrorDialog = null;
3251                                 mSSLCertificateOnErrorView = null;
3252                                 mSSLCertificateOnErrorHandler = null;
3253                                 mSSLCertificateOnErrorError = null;
3254
3255                                 view.getWebViewClient().onReceivedSslError(
3256                                                 view, handler, error);
3257                             }
3258                         })
3259                 .show();
3260     }
3261
3262     /**
3263      * Inflates the SSL certificate view (helper method).
3264      * @param certificate The SSL certificate.
3265      * @return The resultant certificate view with issued-to, issued-by,
3266      * issued-on, expires-on, and possibly other fields set.
3267      * If the input certificate is null, returns null.
3268      */
3269     private View inflateCertificateView(SslCertificate certificate) {
3270         if (certificate == null) {
3271             return null;
3272         }
3273
3274         LayoutInflater factory = LayoutInflater.from(this);
3275
3276         View certificateView = factory.inflate(
3277             R.layout.ssl_certificate, null);
3278
3279         // issued to:
3280         SslCertificate.DName issuedTo = certificate.getIssuedTo();
3281         if (issuedTo != null) {
3282             ((TextView) certificateView.findViewById(R.id.to_common))
3283                 .setText(issuedTo.getCName());
3284             ((TextView) certificateView.findViewById(R.id.to_org))
3285                 .setText(issuedTo.getOName());
3286             ((TextView) certificateView.findViewById(R.id.to_org_unit))
3287                 .setText(issuedTo.getUName());
3288         }
3289
3290         // issued by:
3291         SslCertificate.DName issuedBy = certificate.getIssuedBy();
3292         if (issuedBy != null) {
3293             ((TextView) certificateView.findViewById(R.id.by_common))
3294                 .setText(issuedBy.getCName());
3295             ((TextView) certificateView.findViewById(R.id.by_org))
3296                 .setText(issuedBy.getOName());
3297             ((TextView) certificateView.findViewById(R.id.by_org_unit))
3298                 .setText(issuedBy.getUName());
3299         }
3300
3301         // issued on:
3302         String issuedOn = reformatCertificateDate(
3303             certificate.getValidNotBefore());
3304         ((TextView) certificateView.findViewById(R.id.issued_on))
3305             .setText(issuedOn);
3306
3307         // expires on:
3308         String expiresOn = reformatCertificateDate(
3309             certificate.getValidNotAfter());
3310         ((TextView) certificateView.findViewById(R.id.expires_on))
3311             .setText(expiresOn);
3312
3313         return certificateView;
3314     }
3315
3316     /**
3317      * Re-formats the certificate date (Date.toString()) string to
3318      * a properly localized date string.
3319      * @return Properly localized version of the certificate date string and
3320      * the original certificate date string if fails to localize.
3321      * If the original string is null, returns an empty string "".
3322      */
3323     private String reformatCertificateDate(String certificateDate) {
3324       String reformattedDate = null;
3325
3326       if (certificateDate != null) {
3327           Date date = null;
3328           try {
3329               date = java.text.DateFormat.getInstance().parse(certificateDate);
3330           } catch (ParseException e) {
3331               date = null;
3332           }
3333
3334           if (date != null) {
3335               reformattedDate =
3336                   DateFormat.getDateFormat(this).format(date);
3337           }
3338       }
3339
3340       return reformattedDate != null ? reformattedDate :
3341           (certificateDate != null ? certificateDate : "");
3342     }
3343
3344     /**
3345      * Displays an http-authentication dialog.
3346      */
3347     void showHttpAuthentication(final HttpAuthHandler handler,
3348             final String host, final String realm, final String title,
3349             final String name, final String password, int focusId) {
3350         LayoutInflater factory = LayoutInflater.from(this);
3351         final View v = factory
3352                 .inflate(R.layout.http_authentication, null);
3353         if (name != null) {
3354             ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3355         }
3356         if (password != null) {
3357             ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3358         }
3359
3360         String titleText = title;
3361         if (titleText == null) {
3362             titleText = getText(R.string.sign_in_to).toString().replace(
3363                     "%s1", host).replace("%s2", realm);
3364         }
3365
3366         mHttpAuthHandler = handler;
3367         AlertDialog dialog = new AlertDialog.Builder(this)
3368                 .setTitle(titleText)
3369                 .setIcon(android.R.drawable.ic_dialog_alert)
3370                 .setView(v)
3371                 .setPositiveButton(R.string.action,
3372                         new DialogInterface.OnClickListener() {
3373                              public void onClick(DialogInterface dialog,
3374                                      int whichButton) {
3375                                 String nm = ((EditText) v
3376                                         .findViewById(R.id.username_edit))
3377                                         .getText().toString();
3378                                 String pw = ((EditText) v
3379                                         .findViewById(R.id.password_edit))
3380                                         .getText().toString();
3381                                 BrowserActivity.this.setHttpAuthUsernamePassword
3382                                         (host, realm, nm, pw);
3383                                 handler.proceed(nm, pw);
3384                                 mHttpAuthenticationDialog = null;
3385                                 mHttpAuthHandler = null;
3386                             }})
3387                 .setNegativeButton(R.string.cancel,
3388                         new DialogInterface.OnClickListener() {
3389                             public void onClick(DialogInterface dialog,
3390                                     int whichButton) {
3391                                 handler.cancel();
3392                                 BrowserActivity.this.resetTitleAndRevertLockIcon();
3393                                 mHttpAuthenticationDialog = null;
3394                                 mHttpAuthHandler = null;
3395                             }})
3396                 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3397                         public void onCancel(DialogInterface dialog) {
3398                             handler.cancel();
3399                             BrowserActivity.this.resetTitleAndRevertLockIcon();
3400                             mHttpAuthenticationDialog = null;
3401                             mHttpAuthHandler = null;
3402                         }})
3403                 .create();
3404         // Make the IME appear when the dialog is displayed if applicable.
3405         dialog.getWindow().setSoftInputMode(
3406                 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3407         dialog.show();
3408         if (focusId != 0) {
3409             dialog.findViewById(focusId).requestFocus();
3410         } else {
3411             v.findViewById(R.id.username_edit).requestFocus();
3412         }
3413         mHttpAuthenticationDialog = dialog;
3414     }
3415
3416     public int getProgress() {
3417         WebView w = mTabControl.getCurrentWebView();
3418         if (w != null) {
3419             return w.getProgress();
3420         } else {
3421             return 100;
3422         }
3423     }
3424
3425     /**
3426      * Set HTTP authentication password.
3427      *
3428      * @param host The host for the password
3429      * @param realm The realm for the password
3430      * @param username The username for the password. If it is null, it means
3431      *            password can't be saved.
3432      * @param password The password
3433      */
3434     public void setHttpAuthUsernamePassword(String host, String realm,
3435                                             String username,
3436                                             String password) {
3437         WebView w = mTabControl.getCurrentWebView();
3438         if (w != null) {
3439             w.setHttpAuthUsernamePassword(host, realm, username, password);
3440         }
3441     }
3442
3443     /**
3444      * connectivity manager says net has come or gone... inform the user
3445      * @param up true if net has come up, false if net has gone down
3446      */
3447     public void onNetworkToggle(boolean up) {
3448         if (up == mIsNetworkUp) {
3449             return;
3450         } else if (up) {
3451             mIsNetworkUp = true;
3452             if (mAlertDialog != null) {
3453                 mAlertDialog.cancel();
3454                 mAlertDialog = null;
3455             }
3456         } else {
3457             mIsNetworkUp = false;
3458             if (mInLoad) {
3459                 createAndShowNetworkDialog();
3460            }
3461         }
3462         WebView w = mTabControl.getCurrentWebView();
3463         if (w != null) {
3464             w.setNetworkAvailable(up);
3465         }
3466     }
3467
3468     boolean isNetworkUp() {
3469         return mIsNetworkUp;
3470     }
3471
3472     // This method shows the network dialog alerting the user that the net is
3473     // down. It will only show the dialog if mAlertDialog is null.
3474     private void createAndShowNetworkDialog() {
3475         if (mAlertDialog == null) {
3476             mAlertDialog = new AlertDialog.Builder(this)
3477                     .setTitle(R.string.loadSuspendedTitle)
3478                     .setMessage(R.string.loadSuspended)
3479                     .setPositiveButton(R.string.ok, null)
3480                     .show();
3481         }
3482     }
3483
3484     @Override
3485     protected void onActivityResult(int requestCode, int resultCode,
3486                                     Intent intent) {
3487         if (getTopWindow() == null) return;
3488
3489         switch (requestCode) {
3490             case COMBO_PAGE:
3491                 if (resultCode == RESULT_OK && intent != null) {
3492                     String data = intent.getAction();
3493                     Bundle extras = intent.getExtras();
3494                     if (extras != null && extras.getBoolean("new_window", false)) {
3495                         openTab(data);
3496                     } else {
3497                         final Tab currentTab =
3498                                 mTabControl.getCurrentTab();
3499                         dismissSubWindow(currentTab);
3500                         if (data != null && data.length() != 0) {
3501                             getTopWindow().loadUrl(data);
3502                         }
3503                     }
3504                 }
3505                 // Deliberately fall through to PREFERENCES_PAGE, since the
3506                 // same extra may be attached to the COMBO_PAGE
3507             case PREFERENCES_PAGE:
3508                 if (resultCode == RESULT_OK && intent != null) {
3509                     String action = intent.getStringExtra(Intent.EXTRA_TEXT);
3510                     if (BrowserSettings.PREF_CLEAR_HISTORY.equals(action)) {
3511                         mTabControl.removeParentChildRelationShips();
3512                     }
3513                 }
3514                 break;
3515             // Choose a file from the file picker.
3516             case FILE_SELECTED:
3517                 if (null == mUploadMessage) break;
3518                 Uri result = intent == null || resultCode != RESULT_OK ? null
3519                         : intent.getData();
3520                 mUploadMessage.onReceiveValue(result);
3521                 mUploadMessage = null;
3522                 break;
3523             default:
3524                 break;
3525         }
3526         getTopWindow().requestFocus();
3527     }
3528
3529     /*
3530      * This method is called as a result of the user selecting the options
3531      * menu to see the download window. It shows the download window on top of
3532      * the current window.
3533      */
3534     private void viewDownloads(Uri downloadRecord) {
3535         Intent intent = new Intent(this,
3536                 BrowserDownloadPage.class);
3537         intent.setData(downloadRecord);
3538         startActivityForResult(intent, BrowserActivity.DOWNLOAD_PAGE);
3539
3540     }
3541
3542     /**
3543      * Open the Go page.
3544      * @param startWithHistory If true, open starting on the history tab.
3545      *                         Otherwise, start with the bookmarks tab.
3546      */
3547     /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
3548         WebView current = mTabControl.getCurrentWebView();
3549         if (current == null) {
3550             return;
3551         }
3552         Intent intent = new Intent(this,
3553                 CombinedBookmarkHistoryActivity.class);
3554         String title = current.getTitle();
3555         String url = current.getUrl();
3556         Bitmap thumbnail = createScreenshot(current);
3557
3558         // Just in case the user opens bookmarks before a page finishes loading
3559         // so the current history item, and therefore the page, is null.
3560         if (null == url) {
3561             url = mLastEnteredUrl;
3562             // This can happen.
3563             if (null == url) {
3564                 url = mSettings.getHomePage();
3565             }
3566         }
3567         // In case the web page has not yet received its associated title.
3568         if (title == null) {
3569             title = url;
3570         }
3571         intent.putExtra("title", title);
3572         intent.putExtra("url", url);
3573         intent.putExtra("thumbnail", thumbnail);
3574         // Disable opening in a new window if we have maxed out the windows
3575         intent.putExtra("disable_new_window", !mTabControl.canCreateNewTab());
3576         intent.putExtra("touch_icon_url", current.getTouchIconUrl());
3577         if (startWithHistory) {
3578             intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
3579                     CombinedBookmarkHistoryActivity.HISTORY_TAB);
3580         }
3581         startActivityForResult(intent, COMBO_PAGE);
3582     }
3583
3584     // Called when loading from context menu or LOAD_URL message
3585     private void loadURL(WebView view, String url) {
3586         // In case the user enters nothing.
3587         if (url != null && url.length() != 0 && view != null) {
3588             url = smartUrlFilter(url);
3589             if (!view.getWebViewClient().shouldOverrideUrlLoading(view, url)) {
3590                 view.loadUrl(url);
3591             }
3592         }
3593     }
3594
3595     private String smartUrlFilter(Uri inUri) {
3596         if (inUri != null) {
3597             return smartUrlFilter(inUri.toString());
3598         }
3599         return null;
3600     }
3601
3602     protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
3603             "(?i)" + // switch on case insensitive matching
3604             "(" +    // begin group for schema
3605             "(?:http|https|file):\\/\\/" +
3606             "|(?:inline|data|about|content|javascript):" +
3607             ")" +
3608             "(.*)" );
3609
3610     /**
3611      * Attempts to determine whether user input is a URL or search
3612      * terms.  Anything with a space is passed to search.
3613      *
3614      * Converts to lowercase any mistakenly uppercased schema (i.e.,
3615      * "Http://" converts to "http://"
3616      *
3617      * @return Original or modified URL
3618      *
3619      */
3620     String smartUrlFilter(String url) {
3621
3622         String inUrl = url.trim();
3623         boolean hasSpace = inUrl.indexOf(' ') != -1;
3624
3625         Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
3626         if (matcher.matches()) {
3627             // force scheme to lowercase
3628             String scheme = matcher.group(1);
3629             String lcScheme = scheme.toLowerCase();
3630             if (!lcScheme.equals(scheme)) {
3631                 inUrl = lcScheme + matcher.group(2);
3632             }
3633             if (hasSpace) {
3634                 inUrl = inUrl.replace(" ", "%20");
3635             }
3636             return inUrl;
3637         }
3638         if (hasSpace) {
3639             // FIXME: Is this the correct place to add to searches?
3640             // what if someone else calls this function?
3641             int shortcut = parseUrlShortcut(inUrl);
3642             if (shortcut != SHORTCUT_INVALID) {
3643                 Browser.addSearchUrl(mResolver, inUrl);
3644                 String query = inUrl.substring(2);
3645                 switch (shortcut) {
3646                 case SHORTCUT_GOOGLE_SEARCH:
3647                     return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
3648                 case SHORTCUT_WIKIPEDIA_SEARCH:
3649                     return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
3650                 case SHORTCUT_DICTIONARY_SEARCH:
3651                     return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
3652                 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
3653                     // FIXME: we need location in this case
3654                     return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
3655                 }
3656             }
3657         } else {
3658             if (Patterns.WEB_URL.matcher(inUrl).matches()) {
3659                 return URLUtil.guessUrl(inUrl);
3660             }
3661         }
3662
3663         Browser.addSearchUrl(mResolver, inUrl);
3664         return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
3665     }
3666
3667     /* package */ void setShouldShowErrorConsole(boolean flag) {
3668         if (flag == mShouldShowErrorConsole) {
3669             // Nothing to do.
3670             return;
3671         }
3672
3673         mShouldShowErrorConsole = flag;
3674
3675         ErrorConsoleView errorConsole = mTabControl.getCurrentTab()
3676                 .getErrorConsole(true);
3677
3678         if (flag) {
3679             // Setting the show state of the console will cause it's the layout to be inflated.
3680             if (errorConsole.numberOfErrors() > 0) {
3681                 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3682             } else {
3683                 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
3684             }
3685
3686             // Now we can add it to the main view.
3687             mErrorConsoleContainer.addView(errorConsole,
3688                     new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
3689                                                   ViewGroup.LayoutParams.WRAP_CONTENT));
3690         } else {
3691             mErrorConsoleContainer.removeView(errorConsole);
3692         }
3693
3694     }
3695
3696     boolean shouldShowErrorConsole() {
3697         return mShouldShowErrorConsole;
3698     }
3699
3700     private void setStatusBarVisibility(boolean visible) {
3701         int flag = visible ? 0 : WindowManager.LayoutParams.FLAG_FULLSCREEN;
3702         getWindow().setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN);
3703     }
3704
3705
3706     private void sendNetworkType(String type, String subtype) {
3707         WebView w = mTabControl.getCurrentWebView();
3708         if (w != null) {
3709             w.setNetworkType(type, subtype);
3710         }
3711     }
3712
3713     final static int LOCK_ICON_UNSECURE = 0;
3714     final static int LOCK_ICON_SECURE   = 1;
3715     final static int LOCK_ICON_MIXED    = 2;
3716
3717     private BrowserSettings mSettings;
3718     private TabControl      mTabControl;
3719     private ContentResolver mResolver;
3720     private FrameLayout     mContentView;
3721     private View            mCustomView;
3722     private FrameLayout     mCustomViewContainer;
3723     private WebChromeClient.CustomViewCallback mCustomViewCallback;
3724
3725     // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
3726     // view, we should rewrite this.
3727     private int mCurrentMenuState = 0;
3728     private int mMenuState = R.id.MAIN_MENU;
3729     private int mOldMenuState = EMPTY_MENU;
3730     private static final int EMPTY_MENU = -1;
3731     private Menu mMenu;
3732
3733     private FindDialog mFindDialog;
3734     // Used to prevent chording to result in firing two shortcuts immediately
3735     // one after another.  Fixes bug 1211714.
3736     boolean mCanChord;
3737
3738     private boolean mInLoad;
3739     private boolean mIsNetworkUp;
3740     private boolean mDidStopLoad;
3741
3742     private boolean mActivityInPause = true;
3743
3744     private boolean mMenuIsDown;
3745
3746     private static boolean mInTrace;
3747
3748     // Performance probe
3749     private static final int[] SYSTEM_CPU_FORMAT = new int[] {
3750             Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
3751             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
3752             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
3753             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
3754             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
3755             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
3756             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
3757             Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG  // 7: softirq time
3758     };
3759
3760     private long mStart;
3761     private long mProcessStart;
3762     private long mUserStart;
3763     private long mSystemStart;
3764     private long mIdleStart;
3765     private long mIrqStart;
3766
3767     private long mUiStart;
3768
3769     private Drawable    mMixLockIcon;
3770     private Drawable    mSecLockIcon;
3771
3772     /* hold a ref so we can auto-cancel if necessary */
3773     private AlertDialog mAlertDialog;
3774
3775     // Wait for credentials before loading google.com
3776     private ProgressDialog mCredsDlg;
3777
3778     // The up-to-date URL and title (these can be different from those stored
3779     // in WebView, since it takes some time for the information in WebView to
3780     // get updated)
3781     private String mUrl;
3782     private String mTitle;
3783
3784     // As PageInfo has different style for landscape / portrait, we have
3785     // to re-open it when configuration changed
3786     private AlertDialog mPageInfoDialog;
3787     private Tab mPageInfoView;
3788     // If the Page-Info dialog is launched from the SSL-certificate-on-error
3789     // dialog, we should not just dismiss it, but should get back to the
3790     // SSL-certificate-on-error dialog. This flag is used to store this state
3791     private boolean mPageInfoFromShowSSLCertificateOnError;
3792
3793     // as SSLCertificateOnError has different style for landscape / portrait,
3794     // we have to re-open it when configuration changed
3795     private AlertDialog mSSLCertificateOnErrorDialog;
3796     private WebView mSSLCertificateOnErrorView;
3797     private SslErrorHandler mSSLCertificateOnErrorHandler;
3798     private SslError mSSLCertificateOnErrorError;
3799
3800     // as SSLCertificate has different style for landscape / portrait, we
3801     // have to re-open it when configuration changed
3802     private AlertDialog mSSLCertificateDialog;
3803     private Tab mSSLCertificateView;
3804
3805     // as HttpAuthentication has different style for landscape / portrait, we
3806     // have to re-open it when configuration changed
3807     private AlertDialog mHttpAuthenticationDialog;
3808     private HttpAuthHandler mHttpAuthHandler;
3809
3810     /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
3811                                             new FrameLayout.LayoutParams(
3812                                             ViewGroup.LayoutParams.MATCH_PARENT,
3813                                             ViewGroup.LayoutParams.MATCH_PARENT);
3814     /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
3815                                             new FrameLayout.LayoutParams(
3816                                             ViewGroup.LayoutParams.MATCH_PARENT,
3817                                             ViewGroup.LayoutParams.MATCH_PARENT,
3818                                             Gravity.CENTER);
3819     // Google search
3820     final static String QuickSearch_G = "http://www.google.com/m?q=%s";
3821     // Wikipedia search
3822     final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
3823     // Dictionary search
3824     final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
3825     // Google Mobile Local search
3826     final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
3827
3828     final static String QUERY_PLACE_HOLDER = "%s";
3829
3830     // "source" parameter for Google search through search key
3831     final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
3832     // "source" parameter for Google search through goto menu
3833     final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
3834     // "source" parameter for Google search through simplily type
3835     final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
3836     // "source" parameter for Google search suggested by the browser
3837     final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
3838     // "source" parameter for Google search from unknown source
3839     final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
3840
3841     private final static String LOGTAG = "browser";
3842
3843     private String mLastEnteredUrl;
3844
3845     private PowerManager.WakeLock mWakeLock;
3846     private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
3847
3848     private Toast mStopToast;
3849
3850     private TitleBar mTitleBar;
3851
3852     private LinearLayout mErrorConsoleContainer = null;
3853     private boolean mShouldShowErrorConsole = false;
3854
3855     // As the ids are dynamically created, we can't guarantee that they will
3856     // be in sequence, so this static array maps ids to a window number.
3857     final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
3858     { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
3859       R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
3860       R.id.window_seven_menu_id, R.id.window_eight_menu_id };
3861
3862     // monitor platform changes
3863     private IntentFilter mNetworkStateChangedFilter;
3864     private BroadcastReceiver mNetworkStateIntentReceiver;
3865
3866     private BroadcastReceiver mPackageInstallationReceiver;
3867
3868     // activity requestCode
3869     final static int COMBO_PAGE                 = 1;
3870     final static int DOWNLOAD_PAGE              = 2;
3871     final static int PREFERENCES_PAGE           = 3;
3872     final static int FILE_SELECTED              = 4;
3873
3874     // the default <video> poster
3875     private Bitmap mDefaultVideoPoster;
3876     // the video progress view
3877     private View mVideoProgressView;
3878
3879     /**
3880      * A UrlData class to abstract how the content will be set to WebView.
3881      * This base class uses loadUrl to show the content.
3882      */
3883     private static class UrlData {
3884         String mUrl;
3885         byte[] mPostData;
3886
3887         UrlData(String url) {
3888             this.mUrl = url;
3889         }
3890
3891         void setPostData(byte[] postData) {
3892             mPostData = postData;
3893         }
3894
3895         boolean isEmpty() {
3896             return mUrl == null || mUrl.length() == 0;
3897         }
3898
3899         public void loadIn(WebView webView) {
3900             if (mPostData != null) {
3901                 webView.postUrl(mUrl, mPostData);
3902             } else {
3903                 webView.loadUrl(mUrl);
3904             }
3905         }
3906     };
3907
3908     /**
3909      * A subclass of UrlData class that can display inlined content using
3910      * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
3911      */
3912     private static class InlinedUrlData extends UrlData {
3913         InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
3914             super(failUrl);
3915             mInlined = inlined;
3916             mMimeType = mimeType;
3917             mEncoding = encoding;
3918         }
3919         String mMimeType;
3920         String mInlined;
3921         String mEncoding;
3922         @Override
3923         boolean isEmpty() {
3924             return mInlined == null || mInlined.length() == 0 || super.isEmpty();
3925         }
3926
3927         @Override
3928         public void loadIn(WebView webView) {
3929             webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
3930         }
3931     }
3932
3933     /* package */ static final UrlData EMPTY_URL_DATA = new UrlData(null);
3934 }