OSDN Git Service

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