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