OSDN Git Service

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