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