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