OSDN Git Service

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