OSDN Git Service

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