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