OSDN Git Service

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