OSDN Git Service

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