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