OSDN Git Service

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