OSDN Git Service

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