OSDN Git Service

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