BrowserActivity.java revision c9181841c7ed6b9f7dfc953eab8dc7ba1047022c
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        if (t != null) {
1093            dismissSubWindow(t);
1094            removeTabFromContentView(t);
1095        }
1096        // Destroy all the tabs
1097        mTabControl.destroy();
1098        WebIconDatabase.getInstance().close();
1099        if (mGlsConnection != null) {
1100            unbindService(mGlsConnection);
1101            mGlsConnection = null;
1102        }
1103
1104        //
1105        // stop MASF proxy service
1106        //
1107        //Intent proxyServiceIntent = new Intent();
1108        //proxyServiceIntent.setComponent
1109        //   (new ComponentName(
1110        //        "com.android.masfproxyservice",
1111        //        "com.android.masfproxyservice.MasfProxyService"));
1112        //stopService(proxyServiceIntent);
1113    }
1114
1115    @Override
1116    public void onConfigurationChanged(Configuration newConfig) {
1117        super.onConfigurationChanged(newConfig);
1118
1119        if (mPageInfoDialog != null) {
1120            mPageInfoDialog.dismiss();
1121            showPageInfo(
1122                mPageInfoView,
1123                mPageInfoFromShowSSLCertificateOnError.booleanValue());
1124        }
1125        if (mSSLCertificateDialog != null) {
1126            mSSLCertificateDialog.dismiss();
1127            showSSLCertificate(
1128                mSSLCertificateView);
1129        }
1130        if (mSSLCertificateOnErrorDialog != null) {
1131            mSSLCertificateOnErrorDialog.dismiss();
1132            showSSLCertificateOnError(
1133                mSSLCertificateOnErrorView,
1134                mSSLCertificateOnErrorHandler,
1135                mSSLCertificateOnErrorError);
1136        }
1137        if (mHttpAuthenticationDialog != null) {
1138            String title = ((TextView) mHttpAuthenticationDialog
1139                    .findViewById(com.android.internal.R.id.alertTitle)).getText()
1140                    .toString();
1141            String name = ((TextView) mHttpAuthenticationDialog
1142                    .findViewById(R.id.username_edit)).getText().toString();
1143            String password = ((TextView) mHttpAuthenticationDialog
1144                    .findViewById(R.id.password_edit)).getText().toString();
1145            int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1146                    .getId();
1147            mHttpAuthenticationDialog.dismiss();
1148            showHttpAuthentication(mHttpAuthHandler, null, null, title,
1149                    name, password, focusId);
1150        }
1151        if (mFindDialog != null && mFindDialog.isShowing()) {
1152            mFindDialog.onConfigurationChanged(newConfig);
1153        }
1154    }
1155
1156    @Override public void onLowMemory() {
1157        super.onLowMemory();
1158        mTabControl.freeMemory();
1159    }
1160
1161    private boolean resumeWebView() {
1162        if ((!mActivityInPause && !mPageStarted) ||
1163                (mActivityInPause && mPageStarted)) {
1164            CookieSyncManager.getInstance().startSync();
1165            WebView w = mTabControl.getCurrentWebView();
1166            if (w != null) {
1167                w.resumeTimers();
1168            }
1169            return true;
1170        } else {
1171            return false;
1172        }
1173    }
1174
1175    private boolean pauseWebView() {
1176        if (mActivityInPause && !mPageStarted) {
1177            CookieSyncManager.getInstance().stopSync();
1178            WebView w = mTabControl.getCurrentWebView();
1179            if (w != null) {
1180                w.pauseTimers();
1181            }
1182            return true;
1183        } else {
1184            return false;
1185        }
1186    }
1187
1188    /*
1189     * This function is called when we are launching for the first time. We
1190     * are waiting for the login credentials before loading Google home
1191     * pages. This way the user will be logged in straight away.
1192     */
1193    private void waitForCredentials() {
1194        // Show a toast
1195        mCredsDlg = new ProgressDialog(this);
1196        mCredsDlg.setIndeterminate(true);
1197        mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1198        // If the user cancels the operation, then cancel the Google
1199        // Credentials request.
1200        mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1201        mCredsDlg.show();
1202
1203        // We set a timeout for the retrieval of credentials in onResume()
1204        // as that is when we have freed up some CPU time to get
1205        // the login credentials.
1206    }
1207
1208    /*
1209     * If we have received the credentials or we have timed out and we are
1210     * showing the credentials dialog, then it is time to move on.
1211     */
1212    private void resumeAfterCredentials() {
1213        if (mCredsDlg == null) {
1214            return;
1215        }
1216
1217        // Clear the toast
1218        if (mCredsDlg.isShowing()) {
1219            mCredsDlg.dismiss();
1220        }
1221        mCredsDlg = null;
1222
1223        // Clear any pending timeout
1224        mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1225
1226        // Load the page
1227        WebView w = mTabControl.getCurrentWebView();
1228        if (w != null) {
1229            w.loadUrl(mSettings.getHomePage());
1230        }
1231
1232        // Update the settings, need to do this last as it can take a moment
1233        // to persist the settings. In the mean time we could be loading
1234        // content.
1235        mSettings.setLoginInitialized(this);
1236    }
1237
1238    // Open the icon database and retain all the icons for visited sites.
1239    private void retainIconsOnStartup() {
1240        final WebIconDatabase db = WebIconDatabase.getInstance();
1241        db.open(getDir("icons", 0).getPath());
1242        try {
1243            Cursor c = Browser.getAllBookmarks(mResolver);
1244            if (!c.moveToFirst()) {
1245                c.deactivate();
1246                return;
1247            }
1248            int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1249            do {
1250                String url = c.getString(urlIndex);
1251                db.retainIconForPageUrl(url);
1252            } while (c.moveToNext());
1253            c.deactivate();
1254        } catch (IllegalStateException e) {
1255            Log.e(LOGTAG, "retainIconsOnStartup", e);
1256        }
1257    }
1258
1259    // Helper method for getting the top window.
1260    WebView getTopWindow() {
1261        return mTabControl.getCurrentTopWebView();
1262    }
1263
1264    @Override
1265    public boolean onCreateOptionsMenu(Menu menu) {
1266        super.onCreateOptionsMenu(menu);
1267
1268        MenuInflater inflater = getMenuInflater();
1269        inflater.inflate(R.menu.browser, menu);
1270        mMenu = menu;
1271        updateInLoadMenuItems();
1272        return true;
1273    }
1274
1275    /**
1276     * As the menu can be open when loading state changes
1277     * we must manually update the state of the stop/reload menu
1278     * item
1279     */
1280    private void updateInLoadMenuItems() {
1281        if (mMenu == null) {
1282            return;
1283        }
1284        MenuItem src = mInLoad ?
1285                mMenu.findItem(R.id.stop_menu_id):
1286                    mMenu.findItem(R.id.reload_menu_id);
1287        MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1288        dest.setIcon(src.getIcon());
1289        dest.setTitle(src.getTitle());
1290    }
1291
1292    @Override
1293    public boolean onContextItemSelected(MenuItem item) {
1294        // chording is not an issue with context menus, but we use the same
1295        // options selector, so set mCanChord to true so we can access them.
1296        mCanChord = true;
1297        int id = item.getItemId();
1298        final WebView webView = getTopWindow();
1299        final HashMap hrefMap = new HashMap();
1300        hrefMap.put("webview", webView);
1301        final Message msg = mHandler.obtainMessage(
1302                FOCUS_NODE_HREF, id, 0, hrefMap);
1303        switch (id) {
1304            // -- Browser context menu
1305            case R.id.open_context_menu_id:
1306            case R.id.open_newtab_context_menu_id:
1307            case R.id.bookmark_context_menu_id:
1308            case R.id.save_link_context_menu_id:
1309            case R.id.share_link_context_menu_id:
1310            case R.id.copy_link_context_menu_id:
1311                webView.requestFocusNodeHref(msg);
1312                break;
1313
1314            default:
1315                // For other context menus
1316                return onOptionsItemSelected(item);
1317        }
1318        mCanChord = false;
1319        return true;
1320    }
1321
1322    private Bundle createGoogleSearchSourceBundle(String source) {
1323        Bundle bundle = new Bundle();
1324        bundle.putString(SearchManager.SOURCE, source);
1325        return bundle;
1326    }
1327
1328    /**
1329     * Overriding this to insert a local information bundle
1330     */
1331    @Override
1332    public boolean onSearchRequested() {
1333        startSearch(null, false,
1334                createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1335        return true;
1336    }
1337
1338    @Override
1339    public void startSearch(String initialQuery, boolean selectInitialQuery,
1340            Bundle appSearchData, boolean globalSearch) {
1341        if (appSearchData == null) {
1342            appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1343        }
1344        super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1345    }
1346
1347    @Override
1348    public boolean onOptionsItemSelected(MenuItem item) {
1349        if (!mCanChord) {
1350            // The user has already fired a shortcut with this hold down of the
1351            // menu key.
1352            return false;
1353        }
1354        switch (item.getItemId()) {
1355            // -- Main menu
1356            case R.id.goto_menu_id: {
1357                String url = getTopWindow().getUrl();
1358                startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1359                        createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
1360                }
1361                break;
1362
1363            case R.id.bookmarks_menu_id:
1364                bookmarksOrHistoryPicker(false);
1365                break;
1366
1367            case R.id.windows_menu_id:
1368                if (mTabControl.getTabCount() == 1) {
1369                    openTabAndShow(mSettings.getHomePage(), null, false, null);
1370                } else {
1371                    tabPicker(true, mTabControl.getCurrentIndex(), false);
1372                }
1373                break;
1374
1375            case R.id.stop_reload_menu_id:
1376                if (mInLoad) {
1377                    stopLoading();
1378                } else {
1379                    getTopWindow().reload();
1380                }
1381                break;
1382
1383            case R.id.back_menu_id:
1384                getTopWindow().goBack();
1385                break;
1386
1387            case R.id.forward_menu_id:
1388                getTopWindow().goForward();
1389                break;
1390
1391            case R.id.close_menu_id:
1392                // Close the subwindow if it exists.
1393                if (mTabControl.getCurrentSubWindow() != null) {
1394                    dismissSubWindow(mTabControl.getCurrentTab());
1395                    break;
1396                }
1397                final int currentIndex = mTabControl.getCurrentIndex();
1398                final TabControl.Tab parent =
1399                        mTabControl.getCurrentTab().getParentTab();
1400                int indexToShow = -1;
1401                if (parent != null) {
1402                    indexToShow = mTabControl.getTabIndex(parent);
1403                } else {
1404                    // Get the last tab in the list. If it is the current tab,
1405                    // subtract 1 more.
1406                    indexToShow = mTabControl.getTabCount() - 1;
1407                    if (currentIndex == indexToShow) {
1408                        indexToShow--;
1409                    }
1410                }
1411                switchTabs(currentIndex, indexToShow, true);
1412                break;
1413
1414            case R.id.homepage_menu_id:
1415                TabControl.Tab current = mTabControl.getCurrentTab();
1416                if (current != null) {
1417                    dismissSubWindow(current);
1418                    current.getWebView().loadUrl(mSettings.getHomePage());
1419                }
1420                break;
1421
1422            case R.id.preferences_menu_id:
1423                Intent intent = new Intent(this,
1424                        BrowserPreferencesPage.class);
1425                startActivityForResult(intent, PREFERENCES_PAGE);
1426                break;
1427
1428            case R.id.find_menu_id:
1429                if (null == mFindDialog) {
1430                    mFindDialog = new FindDialog(this);
1431                }
1432                mFindDialog.setWebView(getTopWindow());
1433                mFindDialog.show();
1434                mMenuState = EMPTY_MENU;
1435                break;
1436
1437            case R.id.select_text_id:
1438                getTopWindow().emulateShiftHeld();
1439                break;
1440            case R.id.page_info_menu_id:
1441                showPageInfo(mTabControl.getCurrentTab(), false);
1442                break;
1443
1444            case R.id.classic_history_menu_id:
1445                bookmarksOrHistoryPicker(true);
1446                break;
1447
1448            case R.id.share_page_menu_id:
1449                Browser.sendString(this, getTopWindow().getUrl());
1450                break;
1451
1452            case R.id.dump_nav_menu_id:
1453                getTopWindow().debugDump();
1454                break;
1455
1456            case R.id.zoom_in_menu_id:
1457                getTopWindow().zoomIn();
1458                break;
1459
1460            case R.id.zoom_out_menu_id:
1461                getTopWindow().zoomOut();
1462                break;
1463
1464            case R.id.view_downloads_menu_id:
1465                viewDownloads(null);
1466                break;
1467
1468            // -- Tab menu
1469            case R.id.view_tab_menu_id:
1470                if (mTabListener != null && mTabOverview != null) {
1471                    int pos = mTabOverview.getContextMenuPosition(item);
1472                    mTabOverview.setCurrentIndex(pos);
1473                    mTabListener.onClick(pos);
1474                }
1475                break;
1476
1477            case R.id.remove_tab_menu_id:
1478                if (mTabListener != null && mTabOverview != null) {
1479                    int pos = mTabOverview.getContextMenuPosition(item);
1480                    mTabListener.remove(pos);
1481                }
1482                break;
1483
1484            case R.id.new_tab_menu_id:
1485                // No need to check for mTabOverview here since we are not
1486                // dependent on it for a position.
1487                if (mTabListener != null) {
1488                    // If the overview happens to be non-null, make the "New
1489                    // Tab" cell visible.
1490                    if (mTabOverview != null) {
1491                        mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1492                    }
1493                    mTabListener.onClick(ImageGrid.NEW_TAB);
1494                }
1495                break;
1496
1497            case R.id.bookmark_tab_menu_id:
1498                if (mTabListener != null && mTabOverview != null) {
1499                    int pos = mTabOverview.getContextMenuPosition(item);
1500                    TabControl.Tab t = mTabControl.getTab(pos);
1501                    // Since we called populatePickerData for all of the
1502                    // tabs, getTitle and getUrl will return appropriate
1503                    // values.
1504                    Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1505                            t.getUrl());
1506                }
1507                break;
1508
1509            case R.id.history_tab_menu_id:
1510                bookmarksOrHistoryPicker(true);
1511                break;
1512
1513            case R.id.bookmarks_tab_menu_id:
1514                bookmarksOrHistoryPicker(false);
1515                break;
1516
1517            case R.id.properties_tab_menu_id:
1518                if (mTabListener != null && mTabOverview != null) {
1519                    int pos = mTabOverview.getContextMenuPosition(item);
1520                    showPageInfo(mTabControl.getTab(pos), false);
1521                }
1522                break;
1523
1524            case R.id.window_one_menu_id:
1525            case R.id.window_two_menu_id:
1526            case R.id.window_three_menu_id:
1527            case R.id.window_four_menu_id:
1528            case R.id.window_five_menu_id:
1529            case R.id.window_six_menu_id:
1530            case R.id.window_seven_menu_id:
1531            case R.id.window_eight_menu_id:
1532                {
1533                    int menuid = item.getItemId();
1534                    for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1535                        if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1536                            TabControl.Tab desiredTab = mTabControl.getTab(id);
1537                            if (desiredTab != null &&
1538                                    desiredTab != mTabControl.getCurrentTab()) {
1539                                switchTabs(mTabControl.getCurrentIndex(), id, false);
1540                            }
1541                            break;
1542                        }
1543                    }
1544                }
1545                break;
1546
1547            default:
1548                if (!super.onOptionsItemSelected(item)) {
1549                    return false;
1550                }
1551                // Otherwise fall through.
1552        }
1553        mCanChord = false;
1554        return true;
1555    }
1556
1557    public void closeFind() {
1558        mMenuState = R.id.MAIN_MENU;
1559    }
1560
1561    @Override public boolean onPrepareOptionsMenu(Menu menu)
1562    {
1563        // This happens when the user begins to hold down the menu key, so
1564        // allow them to chord to get a shortcut.
1565        mCanChord = true;
1566        // Note: setVisible will decide whether an item is visible; while
1567        // setEnabled() will decide whether an item is enabled, which also means
1568        // whether the matching shortcut key will function.
1569        super.onPrepareOptionsMenu(menu);
1570        switch (mMenuState) {
1571            case R.id.TAB_MENU:
1572                if (mCurrentMenuState != mMenuState) {
1573                    menu.setGroupVisible(R.id.MAIN_MENU, false);
1574                    menu.setGroupEnabled(R.id.MAIN_MENU, false);
1575                    menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1576                    menu.setGroupVisible(R.id.TAB_MENU, true);
1577                    menu.setGroupEnabled(R.id.TAB_MENU, true);
1578                }
1579                boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1580                final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1581                tab.setVisible(newT);
1582                tab.setEnabled(newT);
1583                break;
1584            case EMPTY_MENU:
1585                if (mCurrentMenuState != mMenuState) {
1586                    menu.setGroupVisible(R.id.MAIN_MENU, false);
1587                    menu.setGroupEnabled(R.id.MAIN_MENU, false);
1588                    menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1589                    menu.setGroupVisible(R.id.TAB_MENU, false);
1590                    menu.setGroupEnabled(R.id.TAB_MENU, false);
1591                }
1592                break;
1593            default:
1594                if (mCurrentMenuState != mMenuState) {
1595                    menu.setGroupVisible(R.id.MAIN_MENU, true);
1596                    menu.setGroupEnabled(R.id.MAIN_MENU, true);
1597                    menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1598                    menu.setGroupVisible(R.id.TAB_MENU, false);
1599                    menu.setGroupEnabled(R.id.TAB_MENU, false);
1600                }
1601                final WebView w = getTopWindow();
1602                boolean canGoBack = false;
1603                boolean canGoForward = false;
1604                boolean isHome = false;
1605                if (w != null) {
1606                    canGoBack = w.canGoBack();
1607                    canGoForward = w.canGoForward();
1608                    isHome = mSettings.getHomePage().equals(w.getUrl());
1609                }
1610                final MenuItem back = menu.findItem(R.id.back_menu_id);
1611                back.setEnabled(canGoBack);
1612
1613                final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1614                home.setEnabled(!isHome);
1615
1616                menu.findItem(R.id.forward_menu_id)
1617                        .setEnabled(canGoForward);
1618
1619                // decide whether to show the share link option
1620                PackageManager pm = getPackageManager();
1621                Intent send = new Intent(Intent.ACTION_SEND);
1622                send.setType("text/plain");
1623                ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1624                menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1625
1626                // If there is only 1 window, the text will be "New window"
1627                final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1628                windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1629                        getString(R.string.view_tabs_condensed) :
1630                        getString(R.string.tab_picker_new_tab));
1631
1632                boolean isNavDump = mSettings.isNavDump();
1633                final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1634                nav.setVisible(isNavDump);
1635                nav.setEnabled(isNavDump);
1636                break;
1637        }
1638        mCurrentMenuState = mMenuState;
1639        return true;
1640    }
1641
1642    @Override
1643    public void onCreateContextMenu(ContextMenu menu, View v,
1644            ContextMenuInfo menuInfo) {
1645        WebView webview = (WebView) v;
1646        WebView.HitTestResult result = webview.getHitTestResult();
1647        if (result == null) {
1648            return;
1649        }
1650
1651        int type = result.getType();
1652        if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1653            Log.w(LOGTAG,
1654                    "We should not show context menu when nothing is touched");
1655            return;
1656        }
1657        if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1658            // let TextView handles context menu
1659            return;
1660        }
1661
1662        // Note, http://b/issue?id=1106666 is requesting that
1663        // an inflated menu can be used again. This is not available
1664        // yet, so inflate each time (yuk!)
1665        MenuInflater inflater = getMenuInflater();
1666        inflater.inflate(R.menu.browsercontext, menu);
1667
1668        // Show the correct menu group
1669        String extra = result.getExtra();
1670        menu.setGroupVisible(R.id.PHONE_MENU,
1671                type == WebView.HitTestResult.PHONE_TYPE);
1672        menu.setGroupVisible(R.id.EMAIL_MENU,
1673                type == WebView.HitTestResult.EMAIL_TYPE);
1674        menu.setGroupVisible(R.id.GEO_MENU,
1675                type == WebView.HitTestResult.GEO_TYPE);
1676        menu.setGroupVisible(R.id.IMAGE_MENU,
1677                type == WebView.HitTestResult.IMAGE_TYPE
1678                || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1679        menu.setGroupVisible(R.id.ANCHOR_MENU,
1680                type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1681                || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1682
1683        // Setup custom handling depending on the type
1684        switch (type) {
1685            case WebView.HitTestResult.PHONE_TYPE:
1686                menu.setHeaderTitle(Uri.decode(extra));
1687                menu.findItem(R.id.dial_context_menu_id).setIntent(
1688                        new Intent(Intent.ACTION_VIEW, Uri
1689                                .parse(WebView.SCHEME_TEL + extra)));
1690                Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1691                addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1692                addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1693                menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1694                        addIntent);
1695                menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1696                        new Copy(extra));
1697                break;
1698
1699            case WebView.HitTestResult.EMAIL_TYPE:
1700                menu.setHeaderTitle(extra);
1701                menu.findItem(R.id.email_context_menu_id).setIntent(
1702                        new Intent(Intent.ACTION_VIEW, Uri
1703                                .parse(WebView.SCHEME_MAILTO + extra)));
1704                menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1705                        new Copy(extra));
1706                break;
1707
1708            case WebView.HitTestResult.GEO_TYPE:
1709                menu.setHeaderTitle(extra);
1710                menu.findItem(R.id.map_context_menu_id).setIntent(
1711                        new Intent(Intent.ACTION_VIEW, Uri
1712                                .parse(WebView.SCHEME_GEO
1713                                        + URLEncoder.encode(extra))));
1714                menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1715                        new Copy(extra));
1716                break;
1717
1718            case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1719            case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1720                TextView titleView = (TextView) LayoutInflater.from(this)
1721                        .inflate(android.R.layout.browser_link_context_header,
1722                        null);
1723                titleView.setText(extra);
1724                menu.setHeaderView(titleView);
1725                // decide whether to show the open link in new tab option
1726                menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1727                        mTabControl.getTabCount() < TabControl.MAX_TABS);
1728                PackageManager pm = getPackageManager();
1729                Intent send = new Intent(Intent.ACTION_SEND);
1730                send.setType("text/plain");
1731                ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1732                menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1733                if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1734                    break;
1735                }
1736                // otherwise fall through to handle image part
1737            case WebView.HitTestResult.IMAGE_TYPE:
1738                if (type == WebView.HitTestResult.IMAGE_TYPE) {
1739                    menu.setHeaderTitle(extra);
1740                }
1741                menu.findItem(R.id.view_image_context_menu_id).setIntent(
1742                        new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1743                menu.findItem(R.id.download_context_menu_id).
1744                        setOnMenuItemClickListener(new Download(extra));
1745                break;
1746
1747            default:
1748                Log.w(LOGTAG, "We should not get here.");
1749                break;
1750        }
1751    }
1752
1753    // Attach the given tab to the content view.
1754    private void attachTabToContentView(TabControl.Tab t) {
1755        final WebView main = t.getWebView();
1756        // Attach the main WebView.
1757        mContentView.addView(main, COVER_SCREEN_PARAMS);
1758        // Attach the sub window if necessary
1759        attachSubWindow(t);
1760        // Request focus on the top window.
1761        t.getTopWindow().requestFocus();
1762    }
1763
1764    // Attach a sub window to the main WebView of the given tab.
1765    private void attachSubWindow(TabControl.Tab t) {
1766        // If a sub window exists, attach it to the content view.
1767        final WebView subView = t.getSubWebView();
1768        if (subView != null) {
1769            final View container = t.getSubWebViewContainer();
1770            mContentView.addView(container, COVER_SCREEN_PARAMS);
1771            subView.requestFocus();
1772        }
1773    }
1774
1775    // Remove the given tab from the content view.
1776    private void removeTabFromContentView(TabControl.Tab t) {
1777        // Remove the main WebView.
1778        mContentView.removeView(t.getWebView());
1779        // Remove the sub window if it exists.
1780        if (t.getSubWebView() != null) {
1781            mContentView.removeView(t.getSubWebViewContainer());
1782        }
1783    }
1784
1785    // Remove the sub window if it exists. Also called by TabControl when the
1786    // user clicks the 'X' to dismiss a sub window.
1787    /* package */ void dismissSubWindow(TabControl.Tab t) {
1788        final WebView mainView = t.getWebView();
1789        if (t.getSubWebView() != null) {
1790            // Remove the container view and request focus on the main WebView.
1791            mContentView.removeView(t.getSubWebViewContainer());
1792            mainView.requestFocus();
1793            // Tell the TabControl to dismiss the subwindow. This will destroy
1794            // the WebView.
1795            mTabControl.dismissSubWindow(t);
1796        }
1797    }
1798
1799    // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
1800    private void sendAnimateFromOverview(final TabControl.Tab tab,
1801            final boolean newTab, final String url, final int delay,
1802            final Message msg) {
1803        // Set the current tab.
1804        mTabControl.setCurrentTab(tab);
1805        // Attach the WebView so it will layout.
1806        attachTabToContentView(tab);
1807        // Set the view to invisibile for now.
1808        tab.getWebView().setVisibility(View.INVISIBLE);
1809        // If there is a sub window, make it invisible too.
1810        if (tab.getSubWebView() != null) {
1811            tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
1812        }
1813        // Create our fake animating view.
1814        final AnimatingView view = new AnimatingView(this, tab);
1815        // Attach it to the view system and make in invisible so it will
1816        // layout but not flash white on the screen.
1817        mContentView.addView(view, COVER_SCREEN_PARAMS);
1818        view.setVisibility(View.INVISIBLE);
1819        // Send the animate message.
1820        final HashMap map = new HashMap();
1821        map.put("view", view);
1822        // Load the url after the AnimatingView has captured the picture. This
1823        // prevents any bad layout or bad scale from being used during
1824        // animation.
1825        if (url != null) {
1826            dismissSubWindow(tab);
1827            tab.getWebView().loadUrl(url);
1828        }
1829        map.put("msg", msg);
1830        mHandler.sendMessageDelayed(mHandler.obtainMessage(
1831                ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
1832        // Increment the count to indicate that we are in an animation.
1833        mAnimationCount++;
1834        // Remove the listener so we don't get any more tab changes.
1835        mTabOverview.setListener(null);
1836        mTabListener = null;
1837        // Make the menu empty until the animation completes.
1838        mMenuState = EMPTY_MENU;
1839
1840    }
1841
1842    // 500ms animation with 800ms delay
1843    private static final int TAB_ANIMATION_DURATION = 500;
1844    private static final int TAB_OVERVIEW_DELAY     = 800;
1845
1846    // Called by TabControl when a tab is requesting focus
1847    /* package */ void showTab(TabControl.Tab t) {
1848        showTab(t, null);
1849    }
1850
1851    private void showTab(TabControl.Tab t, String url) {
1852        // Disallow focus change during a tab animation.
1853        if (mAnimationCount > 0) {
1854            return;
1855        }
1856        int delay = 0;
1857        if (mTabOverview == null) {
1858            // Add a delay so the tab overview can be shown before the second
1859            // animation begins.
1860            delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1861            tabPicker(false, mTabControl.getTabIndex(t), false);
1862        }
1863        sendAnimateFromOverview(t, false, url, delay, null);
1864    }
1865
1866    // This method does a ton of stuff. It will attempt to create a new tab
1867    // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1868    // url isn't null, it will load the given url. If the tab overview is not
1869    // showing, it will animate to the tab overview, create a new tab and
1870    // animate away from it. After the animation completes, it will dispatch
1871    // the given Message. If the tab overview is already showing (i.e. this
1872    // method is called from TabListener.onClick(), the method will animate
1873    // away from the tab overview.
1874    private TabControl.Tab openTabAndShow(String url, final Message msg,
1875            boolean closeOnExit, String appId) {
1876        final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1877        final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1878        if (newTab) {
1879            int delay = 0;
1880            // If the tab overview is up and there are animations, just load
1881            // the url.
1882            if (mTabOverview != null && mAnimationCount > 0) {
1883                if (url != null) {
1884                    // We should not have a msg here since onCreateWindow
1885                    // checks the animation count and every other caller passes
1886                    // null.
1887                    assert msg == null;
1888                    // just dismiss the subwindow and load the given url.
1889                    dismissSubWindow(currentTab);
1890                    currentTab.getWebView().loadUrl(url);
1891                }
1892            } else {
1893                // show mTabOverview if it is not there.
1894                if (mTabOverview == null) {
1895                    // We have to delay the animation from the tab picker by the
1896                    // length of the tab animation. Add a delay so the tab
1897                    // overview can be shown before the second animation begins.
1898                    delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1899                    tabPicker(false, ImageGrid.NEW_TAB, false);
1900                }
1901                // Animate from the Tab overview after any animations have
1902                // finished.
1903                final TabControl.Tab tab = mTabControl.createNewTab(
1904                        closeOnExit, appId, url);
1905                sendAnimateFromOverview(tab, true, url, delay, msg);
1906                return tab;
1907            }
1908        } else if (url != null) {
1909            // We should not have a msg here.
1910            assert msg == null;
1911            if (mTabOverview != null && mAnimationCount == 0) {
1912                sendAnimateFromOverview(currentTab, false, url,
1913                        TAB_OVERVIEW_DELAY, null);
1914            } else {
1915                // Get rid of the subwindow if it exists
1916                dismissSubWindow(currentTab);
1917                // Load the given url.
1918                currentTab.getWebView().loadUrl(url);
1919            }
1920        }
1921        return currentTab;
1922    }
1923
1924    private Animation createTabAnimation(final AnimatingView view,
1925            final View cell, boolean scaleDown) {
1926        final AnimationSet set = new AnimationSet(true);
1927        final float scaleX = (float) cell.getWidth() / view.getWidth();
1928        final float scaleY = (float) cell.getHeight() / view.getHeight();
1929        if (scaleDown) {
1930            set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
1931            set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
1932                    cell.getTop()));
1933        } else {
1934            set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
1935            set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
1936                    cell.getTop(), 0));
1937        }
1938        set.setDuration(TAB_ANIMATION_DURATION);
1939        set.setInterpolator(new DecelerateInterpolator());
1940        return set;
1941    }
1942
1943    // Animate to the tab overview. currentIndex tells us which position to
1944    // animate to and newIndex is the position that should be selected after
1945    // the animation completes.
1946    // If remove is true, after the animation stops, a confirmation dialog will
1947    // be displayed to the user.
1948    private void animateToTabOverview(final int newIndex, final boolean remove,
1949            final AnimatingView view) {
1950        // Find the view in the ImageGrid allowing for the "New Tab" cell.
1951        int position = mTabControl.getTabIndex(view.mTab);
1952        if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
1953            position++;
1954        }
1955
1956        // Offset the tab position with the first visible position to get a
1957        // number between 0 and 3.
1958        position -= mTabOverview.getFirstVisiblePosition();
1959
1960        // Grab the view that we are going to animate to.
1961        final View v = mTabOverview.getChildAt(position);
1962
1963        final Animation.AnimationListener l =
1964                new Animation.AnimationListener() {
1965                    public void onAnimationStart(Animation a) {
1966                        mTabOverview.requestFocus();
1967                        // Clear the listener so we don't trigger a tab
1968                        // selection.
1969                        mTabOverview.setListener(null);
1970                    }
1971                    public void onAnimationRepeat(Animation a) {}
1972                    public void onAnimationEnd(Animation a) {
1973                        // We are no longer animating so decrement the count.
1974                        mAnimationCount--;
1975                        // Make the view GONE so that it will not draw between
1976                        // now and when the Runnable is handled.
1977                        view.setVisibility(View.GONE);
1978                        // Post a runnable since we can't modify the view
1979                        // hierarchy during this callback.
1980                        mHandler.post(new Runnable() {
1981                            public void run() {
1982                                // Remove the AnimatingView.
1983                                mContentView.removeView(view);
1984                                if (mTabOverview != null) {
1985                                    // Make newIndex visible.
1986                                    mTabOverview.setCurrentIndex(newIndex);
1987                                    // Restore the listener.
1988                                    mTabOverview.setListener(mTabListener);
1989                                    // Change the menu to TAB_MENU if the
1990                                    // ImageGrid is interactive.
1991                                    if (mTabOverview.isLive()) {
1992                                        mMenuState = R.id.TAB_MENU;
1993                                        mTabOverview.requestFocus();
1994                                    }
1995                                }
1996                                // If a remove was requested, remove the tab.
1997                                if (remove) {
1998                                    // During a remove, the current tab has
1999                                    // already changed. Remember the current one
2000                                    // here.
2001                                    final TabControl.Tab currentTab =
2002                                            mTabControl.getCurrentTab();
2003                                    // Remove the tab at newIndex from
2004                                    // TabControl and the tab overview.
2005                                    final TabControl.Tab tab =
2006                                            mTabControl.getTab(newIndex);
2007                                    mTabControl.removeTab(tab);
2008                                    // Restore the current tab.
2009                                    if (currentTab != tab) {
2010                                        mTabControl.setCurrentTab(currentTab);
2011                                    }
2012                                    if (mTabOverview != null) {
2013                                        mTabOverview.remove(newIndex);
2014                                        // Make the current tab visible.
2015                                        mTabOverview.setCurrentIndex(
2016                                                mTabControl.getCurrentIndex());
2017                                    }
2018                                }
2019                            }
2020                        });
2021                    }
2022                };
2023
2024        // Do an animation if there is a view to animate to.
2025        if (v != null) {
2026            // Create our animation
2027            final Animation anim = createTabAnimation(view, v, true);
2028            anim.setAnimationListener(l);
2029            // Start animating
2030            view.startAnimation(anim);
2031        } else {
2032            // If something goes wrong and we didn't find a view to animate to,
2033            // just do everything here.
2034            l.onAnimationStart(null);
2035            l.onAnimationEnd(null);
2036        }
2037    }
2038
2039    // Animate from the tab picker. The index supplied is the index to animate
2040    // from.
2041    private void animateFromTabOverview(final AnimatingView view,
2042            final boolean newTab, final Message msg) {
2043        // firstVisible is the first visible tab on the screen.  This helps
2044        // to know which corner of the screen the selected tab is.
2045        int firstVisible = mTabOverview.getFirstVisiblePosition();
2046        // tabPosition is the 0-based index of of the tab being opened
2047        int tabPosition = mTabControl.getTabIndex(view.mTab);
2048        if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2049            // Add one to make room for the "New Tab" cell.
2050            tabPosition++;
2051        }
2052        // If this is a new tab, animate from the "New Tab" cell.
2053        if (newTab) {
2054            tabPosition = 0;
2055        }
2056        // Location corresponds to the four corners of the screen.
2057        // A new tab or 0 is upper left, 0 for an old tab is upper
2058        // right, 1 is lower left, and 2 is lower right
2059        int location = tabPosition - firstVisible;
2060
2061        // Find the view at this location.
2062        final View v = mTabOverview.getChildAt(location);
2063
2064        // Wait until the animation completes to replace the AnimatingView.
2065        final Animation.AnimationListener l =
2066                new Animation.AnimationListener() {
2067                    public void onAnimationStart(Animation a) {}
2068                    public void onAnimationRepeat(Animation a) {}
2069                    public void onAnimationEnd(Animation a) {
2070                        mHandler.post(new Runnable() {
2071                            public void run() {
2072                                mContentView.removeView(view);
2073                                // Dismiss the tab overview. If the cell at the
2074                                // given location is null, set the fade
2075                                // parameter to true.
2076                                dismissTabOverview(v == null);
2077                                TabControl.Tab t =
2078                                        mTabControl.getCurrentTab();
2079                                mMenuState = R.id.MAIN_MENU;
2080                                // Resume regular updates.
2081                                t.getWebView().resumeTimers();
2082                                // Dispatch the message after the animation
2083                                // completes.
2084                                if (msg != null) {
2085                                    msg.sendToTarget();
2086                                }
2087                                // The animation is done and the tab overview is
2088                                // gone so allow key events and other animations
2089                                // to begin.
2090                                mAnimationCount--;
2091                                // Reset all the title bar info.
2092                                resetTitle();
2093                            }
2094                        });
2095                    }
2096                };
2097
2098        if (v != null) {
2099            final Animation anim = createTabAnimation(view, v, false);
2100            // Set the listener and start animating
2101            anim.setAnimationListener(l);
2102            view.startAnimation(anim);
2103            // Make the view VISIBLE during the animation.
2104            view.setVisibility(View.VISIBLE);
2105        } else {
2106            // Go ahead and do all the cleanup.
2107            l.onAnimationEnd(null);
2108        }
2109    }
2110
2111    // Dismiss the tab overview applying a fade if needed.
2112    private void dismissTabOverview(final boolean fade) {
2113        if (fade) {
2114            AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2115            anim.setDuration(500);
2116            anim.startNow();
2117            mTabOverview.startAnimation(anim);
2118        }
2119        // Just in case there was a problem with animating away from the tab
2120        // overview
2121        WebView current = mTabControl.getCurrentWebView();
2122        if (current != null) {
2123            current.setVisibility(View.VISIBLE);
2124        } else {
2125            Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2126        }
2127        // Make the sub window container visible.
2128        if (mTabControl.getCurrentSubWindow() != null) {
2129            mTabControl.getCurrentTab().getSubWebViewContainer()
2130                    .setVisibility(View.VISIBLE);
2131        }
2132        mContentView.removeView(mTabOverview);
2133        mTabOverview.clear();
2134        mTabOverview = null;
2135        mTabListener = null;
2136    }
2137
2138    private TabControl.Tab openTab(String url) {
2139        if (mSettings.openInBackground()) {
2140            TabControl.Tab t = mTabControl.createNewTab();
2141            if (t != null) {
2142                t.getWebView().loadUrl(url);
2143            }
2144            return t;
2145        } else {
2146            return openTabAndShow(url, null, false, null);
2147        }
2148    }
2149
2150    private class Copy implements OnMenuItemClickListener {
2151        private CharSequence mText;
2152
2153        public boolean onMenuItemClick(MenuItem item) {
2154            copy(mText);
2155            return true;
2156        }
2157
2158        public Copy(CharSequence toCopy) {
2159            mText = toCopy;
2160        }
2161    }
2162
2163    private class Download implements OnMenuItemClickListener {
2164        private String mText;
2165
2166        public boolean onMenuItemClick(MenuItem item) {
2167            onDownloadStartNoStream(mText, null, null, null, -1);
2168            return true;
2169        }
2170
2171        public Download(String toDownload) {
2172            mText = toDownload;
2173        }
2174    }
2175
2176    private void copy(CharSequence text) {
2177        try {
2178            IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2179            if (clip != null) {
2180                clip.setClipboardText(text);
2181            }
2182        } catch (android.os.RemoteException e) {
2183            Log.e(LOGTAG, "Copy failed", e);
2184        }
2185    }
2186
2187    /**
2188     * Resets the browser title-view to whatever it must be (for example, if we
2189     * load a page from history).
2190     */
2191    private void resetTitle() {
2192        resetLockIcon();
2193        resetTitleIconAndProgress();
2194    }
2195
2196    /**
2197     * Resets the browser title-view to whatever it must be
2198     * (for example, if we had a loading error)
2199     * When we have a new page, we call resetTitle, when we
2200     * have to reset the titlebar to whatever it used to be
2201     * (for example, if the user chose to stop loading), we
2202     * call resetTitleAndRevertLockIcon.
2203     */
2204    /* package */ void resetTitleAndRevertLockIcon() {
2205        revertLockIcon();
2206        resetTitleIconAndProgress();
2207    }
2208
2209    /**
2210     * Reset the title, favicon, and progress.
2211     */
2212    private void resetTitleIconAndProgress() {
2213        WebView current = mTabControl.getCurrentWebView();
2214        if (current == null) {
2215            return;
2216        }
2217        resetTitleAndIcon(current);
2218        int progress = current.getProgress();
2219        mWebChromeClient.onProgressChanged(current, progress);
2220    }
2221
2222    // Reset the title and the icon based on the given item.
2223    private void resetTitleAndIcon(WebView view) {
2224        WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2225        if (item != null) {
2226            setUrlTitle(item.getUrl(), item.getTitle());
2227            setFavicon(item.getFavicon());
2228        } else {
2229            setUrlTitle(null, null);
2230            setFavicon(null);
2231        }
2232    }
2233
2234    /**
2235     * Sets a title composed of the URL and the title string.
2236     * @param url The URL of the site being loaded.
2237     * @param title The title of the site being loaded.
2238     */
2239    private void setUrlTitle(String url, String title) {
2240        mUrl = url;
2241        mTitle = title;
2242
2243        // While the tab overview is animating or being shown, block changes
2244        // to the title.
2245        if (mAnimationCount == 0 && mTabOverview == null) {
2246            setTitle(buildUrlTitle(url, title));
2247        }
2248    }
2249
2250    /**
2251     * Builds and returns the page title, which is some
2252     * combination of the page URL and title.
2253     * @param url The URL of the site being loaded.
2254     * @param title The title of the site being loaded.
2255     * @return The page title.
2256     */
2257    private String buildUrlTitle(String url, String title) {
2258        String urlTitle = "";
2259
2260        if (url != null) {
2261            String titleUrl = buildTitleUrl(url);
2262
2263            if (title != null && 0 < title.length()) {
2264                if (titleUrl != null && 0 < titleUrl.length()) {
2265                    urlTitle = titleUrl + ": " + title;
2266                } else {
2267                    urlTitle = title;
2268                }
2269            } else {
2270                if (titleUrl != null) {
2271                    urlTitle = titleUrl;
2272                }
2273            }
2274        }
2275
2276        return urlTitle;
2277    }
2278
2279    /**
2280     * @param url The URL to build a title version of the URL from.
2281     * @return The title version of the URL or null if fails.
2282     * The title version of the URL can be either the URL hostname,
2283     * or the hostname with an "https://" prefix (for secure URLs),
2284     * or an empty string if, for example, the URL in question is a
2285     * file:// URL with no hostname.
2286     */
2287    private static String buildTitleUrl(String url) {
2288        String titleUrl = null;
2289
2290        if (url != null) {
2291            try {
2292                // parse the url string
2293                URL urlObj = new URL(url);
2294                if (urlObj != null) {
2295                    titleUrl = "";
2296
2297                    String protocol = urlObj.getProtocol();
2298                    String host = urlObj.getHost();
2299
2300                    if (host != null && 0 < host.length()) {
2301                        titleUrl = host;
2302                        if (protocol != null) {
2303                            // if a secure site, add an "https://" prefix!
2304                            if (protocol.equalsIgnoreCase("https")) {
2305                                titleUrl = protocol + "://" + host;
2306                            }
2307                        }
2308                    }
2309                }
2310            } catch (MalformedURLException e) {}
2311        }
2312
2313        return titleUrl;
2314    }
2315
2316    // Set the favicon in the title bar.
2317    private void setFavicon(Bitmap icon) {
2318        // While the tab overview is animating or being shown, block changes to
2319        // the favicon.
2320        if (mAnimationCount > 0 || mTabOverview != null) {
2321            return;
2322        }
2323        Drawable[] array = new Drawable[2];
2324        PaintDrawable p = new PaintDrawable(Color.WHITE);
2325        p.setCornerRadius(3f);
2326        array[0] = p;
2327        if (icon == null) {
2328            array[1] = mGenericFavicon;
2329        } else {
2330            array[1] = new BitmapDrawable(icon);
2331        }
2332        LayerDrawable d = new LayerDrawable(array);
2333        d.setLayerInset(1, 2, 2, 2, 2);
2334        getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2335    }
2336
2337    /**
2338     * Saves the current lock-icon state before resetting
2339     * the lock icon. If we have an error, we may need to
2340     * roll back to the previous state.
2341     */
2342    private void saveLockIcon() {
2343        mPrevLockType = mLockIconType;
2344    }
2345
2346    /**
2347     * Reverts the lock-icon state to the last saved state,
2348     * for example, if we had an error, and need to cancel
2349     * the load.
2350     */
2351    private void revertLockIcon() {
2352        mLockIconType = mPrevLockType;
2353
2354        if (Config.LOGV) {
2355            Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2356                  " revert lock icon to " + mLockIconType);
2357        }
2358
2359        updateLockIconImage(mLockIconType);
2360    }
2361
2362    private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2363        int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2364        // Animate to the tab picker, remove the current tab, then
2365        // animate away from the tab picker to the parent WebView.
2366        tabPicker(false, indexFrom, remove);
2367        // Change to the parent tab
2368        final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2369        if (tab != null) {
2370            sendAnimateFromOverview(tab, false, null, delay, null);
2371        } else {
2372            // Increment this here so that no other animations can happen in
2373            // between the end of the tab picker transition and the beginning
2374            // of openTabAndShow. This has a matching decrement in the handler
2375            // of OPEN_TAB_AND_SHOW.
2376            mAnimationCount++;
2377            // Send a message to open a new tab.
2378            mHandler.sendMessageDelayed(
2379                    mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2380                        mSettings.getHomePage()), delay);
2381        }
2382    }
2383
2384    private void goBackOnePageOrQuit() {
2385        TabControl.Tab current = mTabControl.getCurrentTab();
2386        if (current == null) {
2387            /*
2388             * Instead of finishing the activity, simply push this to the back
2389             * of the stack and let ActivityManager to choose the foreground
2390             * activity. As BrowserActivity is singleTask, it will be always the
2391             * root of the task. So we can use either true or false for
2392             * moveTaskToBack().
2393             */
2394            moveTaskToBack(true);
2395        }
2396        WebView w = current.getWebView();
2397        if (w.canGoBack()) {
2398            w.goBack();
2399        } else {
2400            // Check to see if we are closing a window that was created by
2401            // another window. If so, we switch back to that window.
2402            TabControl.Tab parent = current.getParentTab();
2403            if (parent != null) {
2404                switchTabs(mTabControl.getCurrentIndex(),
2405                        mTabControl.getTabIndex(parent), true);
2406            } else {
2407                if (current.closeOnExit()) {
2408                    if (mTabControl.getTabCount() == 1) {
2409                        finish();
2410                        return;
2411                    }
2412                    // call pauseWebView() now, we won't be able to call it in
2413                    // onPause() as the WebView won't be valid.
2414                    pauseWebView();
2415                    removeTabFromContentView(current);
2416                    mTabControl.removeTab(current);
2417                }
2418                /*
2419                 * Instead of finishing the activity, simply push this to the back
2420                 * of the stack and let ActivityManager to choose the foreground
2421                 * activity. As BrowserActivity is singleTask, it will be always the
2422                 * root of the task. So we can use either true or false for
2423                 * moveTaskToBack().
2424                 */
2425                moveTaskToBack(true);
2426            }
2427        }
2428    }
2429
2430    public KeyTracker.State onKeyTracker(int keyCode,
2431                                         KeyEvent event,
2432                                         KeyTracker.Stage stage,
2433                                         int duration) {
2434        // if onKeyTracker() is called after activity onStop()
2435        // because of accumulated key events,
2436        // we should ignore it as browser is not active any more.
2437        WebView topWindow = getTopWindow();
2438        if (topWindow == null)
2439            return KeyTracker.State.NOT_TRACKING;
2440
2441        if (keyCode == KeyEvent.KEYCODE_BACK) {
2442            // During animations, block the back key so that other animations
2443            // are not triggered and so that we don't end up destroying all the
2444            // WebViews before finishing the animation.
2445            if (mAnimationCount > 0) {
2446                return KeyTracker.State.DONE_TRACKING;
2447            }
2448            if (stage == KeyTracker.Stage.LONG_REPEAT) {
2449                bookmarksOrHistoryPicker(true);
2450                return KeyTracker.State.DONE_TRACKING;
2451            } else if (stage == KeyTracker.Stage.UP) {
2452                // FIXME: Currently, we do not have a notion of the
2453                // history picker for the subwindow, but maybe we
2454                // should?
2455                WebView subwindow = mTabControl.getCurrentSubWindow();
2456                if (subwindow != null) {
2457                    if (subwindow.canGoBack()) {
2458                        subwindow.goBack();
2459                    } else {
2460                        dismissSubWindow(mTabControl.getCurrentTab());
2461                    }
2462                } else {
2463                    goBackOnePageOrQuit();
2464                }
2465                return KeyTracker.State.DONE_TRACKING;
2466            }
2467            return KeyTracker.State.KEEP_TRACKING;
2468        }
2469        return KeyTracker.State.NOT_TRACKING;
2470    }
2471
2472    @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2473        if (keyCode == KeyEvent.KEYCODE_MENU) {
2474            mMenuIsDown = true;
2475        }
2476        boolean handled =  mKeyTracker.doKeyDown(keyCode, event);
2477        if (!handled) {
2478            switch (keyCode) {
2479                case KeyEvent.KEYCODE_SPACE:
2480                    if (event.isShiftPressed()) {
2481                        getTopWindow().pageUp(false);
2482                    } else {
2483                        getTopWindow().pageDown(false);
2484                    }
2485                    handled = true;
2486                    break;
2487
2488                default:
2489                    break;
2490            }
2491        }
2492        return handled || super.onKeyDown(keyCode, event);
2493    }
2494
2495    @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2496        if (keyCode == KeyEvent.KEYCODE_MENU) {
2497            mMenuIsDown = false;
2498        }
2499        return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2500    }
2501
2502    private void stopLoading() {
2503        resetTitleAndRevertLockIcon();
2504        WebView w = getTopWindow();
2505        w.stopLoading();
2506        mWebViewClient.onPageFinished(w, w.getUrl());
2507
2508        cancelStopToast();
2509        mStopToast = Toast
2510                .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2511        mStopToast.show();
2512    }
2513
2514    private void cancelStopToast() {
2515        if (mStopToast != null) {
2516            mStopToast.cancel();
2517            mStopToast = null;
2518        }
2519    }
2520
2521    // called by a non-UI thread to post the message
2522    public void postMessage(int what, int arg1, int arg2, Object obj) {
2523        mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2524    }
2525
2526    // public message ids
2527    public final static int LOAD_URL                = 1001;
2528    public final static int STOP_LOAD               = 1002;
2529
2530    // Message Ids
2531    private static final int FOCUS_NODE_HREF         = 102;
2532    private static final int CANCEL_CREDS_REQUEST    = 103;
2533    private static final int ANIMATE_FROM_OVERVIEW   = 104;
2534    private static final int ANIMATE_TO_OVERVIEW     = 105;
2535    private static final int OPEN_TAB_AND_SHOW       = 106;
2536    private static final int CHECK_MEMORY            = 107;
2537    private static final int RELEASE_WAKELOCK        = 108;
2538
2539    // Private handler for handling javascript and saving passwords
2540    private Handler mHandler = new Handler() {
2541
2542        public void handleMessage(Message msg) {
2543            switch (msg.what) {
2544                case ANIMATE_FROM_OVERVIEW:
2545                    final HashMap map = (HashMap) msg.obj;
2546                    animateFromTabOverview((AnimatingView) map.get("view"),
2547                            msg.arg1 == 1, (Message) map.get("msg"));
2548                    break;
2549
2550                case ANIMATE_TO_OVERVIEW:
2551                    animateToTabOverview(msg.arg1, msg.arg2 == 1,
2552                            (AnimatingView) msg.obj);
2553                    break;
2554
2555                case OPEN_TAB_AND_SHOW:
2556                    // Decrement mAnimationCount before openTabAndShow because
2557                    // the method relies on the value being 0 to start the next
2558                    // animation.
2559                    mAnimationCount--;
2560                    openTabAndShow((String) msg.obj, null, false, null);
2561                    break;
2562
2563                case FOCUS_NODE_HREF:
2564                    String url = (String) msg.getData().get("url");
2565                    if (url == null || url.length() == 0) {
2566                        break;
2567                    }
2568                    HashMap focusNodeMap = (HashMap) msg.obj;
2569                    WebView view = (WebView) focusNodeMap.get("webview");
2570                    // Only apply the action if the top window did not change.
2571                    if (getTopWindow() != view) {
2572                        break;
2573                    }
2574                    switch (msg.arg1) {
2575                        case R.id.open_context_menu_id:
2576                        case R.id.view_image_context_menu_id:
2577                            loadURL(getTopWindow(), url);
2578                            break;
2579                        case R.id.open_newtab_context_menu_id:
2580                            final TabControl.Tab parent = mTabControl
2581                                    .getCurrentTab();
2582                            final TabControl.Tab newTab = openTab(url);
2583                            if (newTab != parent) {
2584                                parent.addChildTab(newTab);
2585                            }
2586                            break;
2587                        case R.id.bookmark_context_menu_id:
2588                            Intent intent = new Intent(BrowserActivity.this,
2589                                    AddBookmarkPage.class);
2590                            intent.putExtra("url", url);
2591                            startActivity(intent);
2592                            break;
2593                        case R.id.share_link_context_menu_id:
2594                            Browser.sendString(BrowserActivity.this, url);
2595                            break;
2596                        case R.id.copy_link_context_menu_id:
2597                            copy(url);
2598                            break;
2599                        case R.id.save_link_context_menu_id:
2600                        case R.id.download_context_menu_id:
2601                            onDownloadStartNoStream(url, null, null, null, -1);
2602                            break;
2603                    }
2604                    break;
2605
2606                case LOAD_URL:
2607                    loadURL(getTopWindow(), (String) msg.obj);
2608                    break;
2609
2610                case STOP_LOAD:
2611                    stopLoading();
2612                    break;
2613
2614                case CANCEL_CREDS_REQUEST:
2615                    resumeAfterCredentials();
2616                    break;
2617
2618                case CHECK_MEMORY:
2619                    // reschedule to check memory condition
2620                    mHandler.removeMessages(CHECK_MEMORY);
2621                    mHandler.sendMessageDelayed(mHandler.obtainMessage
2622                            (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2623                    checkMemory();
2624                    break;
2625
2626                case RELEASE_WAKELOCK:
2627                    if (mWakeLock.isHeld()) {
2628                        mWakeLock.release();
2629                    }
2630                    break;
2631            }
2632        }
2633    };
2634
2635    // -------------------------------------------------------------------------
2636    // WebViewClient implementation.
2637    //-------------------------------------------------------------------------
2638
2639    // Use in overrideUrlLoading
2640    /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2641    /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2642    /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2643    /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2644
2645    /* package */ WebViewClient getWebViewClient() {
2646        return mWebViewClient;
2647    }
2648
2649    private void updateIcon(String url, Bitmap icon) {
2650        if (icon != null) {
2651            BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2652                    url, icon);
2653        }
2654        setFavicon(icon);
2655    }
2656
2657    private final WebViewClient mWebViewClient = new WebViewClient() {
2658        @Override
2659        public void onPageStarted(WebView view, String url, Bitmap favicon) {
2660            resetLockIcon(url);
2661            setUrlTitle(url, null);
2662            // Call updateIcon instead of setFavicon so the bookmark
2663            // database can be updated.
2664            updateIcon(url, favicon);
2665
2666            if (mSettings.isTracing() == true) {
2667                // FIXME: we should save the trace file somewhere other than data.
2668                // I can't use "/tmp" as it competes for system memory.
2669                File file = getDir("browserTrace", 0);
2670                String baseDir = file.getPath();
2671                if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2672                String host;
2673                try {
2674                    WebAddress uri = new WebAddress(url);
2675                    host = uri.mHost;
2676                } catch (android.net.ParseException ex) {
2677                    host = "unknown_host";
2678                }
2679                host = host.replace('.', '_');
2680                baseDir = baseDir + host;
2681                file = new File(baseDir+".data");
2682                if (file.exists() == true) {
2683                    file.delete();
2684                }
2685                file = new File(baseDir+".key");
2686                if (file.exists() == true) {
2687                    file.delete();
2688                }
2689                mInTrace = true;
2690                Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2691            }
2692
2693            // Performance probe
2694            if (false) {
2695                mStart = SystemClock.uptimeMillis();
2696                mProcessStart = Process.getElapsedCpuTime();
2697                long[] sysCpu = new long[7];
2698                if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2699                        sysCpu, null)) {
2700                    mUserStart = sysCpu[0] + sysCpu[1];
2701                    mSystemStart = sysCpu[2];
2702                    mIdleStart = sysCpu[3];
2703                    mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2704                }
2705                mUiStart = SystemClock.currentThreadTimeMillis();
2706            }
2707
2708            if (!mPageStarted) {
2709                mPageStarted = true;
2710                // if onResume() has been called, resumeWebView() does nothing.
2711                resumeWebView();
2712            }
2713
2714            // reset sync timer to avoid sync starts during loading a page
2715            CookieSyncManager.getInstance().resetSync();
2716
2717            mInLoad = true;
2718            updateInLoadMenuItems();
2719            if (!mIsNetworkUp) {
2720                if ( mAlertDialog == null) {
2721                    mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2722                        .setTitle(R.string.loadSuspendedTitle)
2723                        .setMessage(R.string.loadSuspended)
2724                        .setPositiveButton(R.string.ok, null)
2725                        .show();
2726                }
2727                if (view != null) {
2728                    view.setNetworkAvailable(false);
2729                }
2730            }
2731
2732            // schedule to check memory condition
2733            mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2734                    CHECK_MEMORY_INTERVAL);
2735        }
2736
2737        @Override
2738        public void onPageFinished(WebView view, String url) {
2739            // Reset the title and icon in case we stopped a provisional
2740            // load.
2741            resetTitleAndIcon(view);
2742
2743            // Update the lock icon image only once we are done loading
2744            updateLockIconImage(mLockIconType);
2745
2746            // Performance probe
2747            if (false) {
2748                long[] sysCpu = new long[7];
2749                if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2750                        sysCpu, null)) {
2751                    String uiInfo = "UI thread used "
2752                            + (SystemClock.currentThreadTimeMillis() - mUiStart)
2753                            + " ms";
2754                    if (Config.LOGD) {
2755                        Log.d(LOGTAG, uiInfo);
2756                    }
2757                    //The string that gets written to the log
2758                    String performanceString = "It took total "
2759                            + (SystemClock.uptimeMillis() - mStart)
2760                            + " ms clock time to load the page."
2761                            + "\nbrowser process used "
2762                            + (Process.getElapsedCpuTime() - mProcessStart)
2763                            + " ms, user processes used "
2764                            + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2765                            + " ms, kernel used "
2766                            + (sysCpu[2] - mSystemStart) * 10
2767                            + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2768                            + " ms and irq took "
2769                            + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2770                            * 10 + " ms, " + uiInfo;
2771                    if (Config.LOGD) {
2772                        Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2773                    }
2774                    if (url != null) {
2775                        // strip the url to maintain consistency
2776                        String newUrl = new String(url);
2777                        if (newUrl.startsWith("http://www.")) {
2778                            newUrl = newUrl.substring(11);
2779                        } else if (newUrl.startsWith("http://")) {
2780                            newUrl = newUrl.substring(7);
2781                        } else if (newUrl.startsWith("https://www.")) {
2782                            newUrl = newUrl.substring(12);
2783                        } else if (newUrl.startsWith("https://")) {
2784                            newUrl = newUrl.substring(8);
2785                        }
2786                        if (Config.LOGD) {
2787                            Log.d(LOGTAG, newUrl + " loaded");
2788                        }
2789                        /*
2790                        if (sWhiteList.contains(newUrl)) {
2791                            // The string that gets pushed to the statistcs
2792                            // service
2793                            performanceString = performanceString
2794                                    + "\nWebpage: "
2795                                    + newUrl
2796                                    + "\nCarrier: "
2797                                    + android.os.SystemProperties
2798                                            .get("gsm.sim.operator.alpha");
2799                            if (mWebView != null
2800                                    && mWebView.getContext() != null
2801                                    && mWebView.getContext().getSystemService(
2802                                    Context.CONNECTIVITY_SERVICE) != null) {
2803                                ConnectivityManager cManager =
2804                                        (ConnectivityManager) mWebView
2805                                        .getContext().getSystemService(
2806                                        Context.CONNECTIVITY_SERVICE);
2807                                NetworkInfo nInfo = cManager
2808                                        .getActiveNetworkInfo();
2809                                if (nInfo != null) {
2810                                    performanceString = performanceString
2811                                            + "\nNetwork Type: "
2812                                            + nInfo.getType().toString();
2813                                }
2814                            }
2815                            Checkin.logEvent(mResolver,
2816                                    Checkin.Events.Tag.WEBPAGE_LOAD,
2817                                    performanceString);
2818                            Log.w(LOGTAG, "pushed to the statistics service");
2819                        }
2820                        */
2821                    }
2822                }
2823             }
2824
2825            if (mInTrace) {
2826                mInTrace = false;
2827                Debug.stopMethodTracing();
2828            }
2829
2830            if (mPageStarted) {
2831                mPageStarted = false;
2832                // pauseWebView() will do nothing and return false if onPause()
2833                // is not called yet.
2834                if (pauseWebView()) {
2835                    if (mWakeLock.isHeld()) {
2836                        mHandler.removeMessages(RELEASE_WAKELOCK);
2837                        mWakeLock.release();
2838                    }
2839                }
2840            }
2841
2842            mHandler.removeMessages(CHECK_MEMORY);
2843            checkMemory();
2844        }
2845
2846        // return true if want to hijack the url to let another app to handle it
2847        @Override
2848        public boolean shouldOverrideUrlLoading(WebView view, String url) {
2849            if (url.startsWith(SCHEME_WTAI)) {
2850                // wtai://wp/mc;number
2851                // number=string(phone-number)
2852                if (url.startsWith(SCHEME_WTAI_MC)) {
2853                    Intent intent = new Intent(Intent.ACTION_VIEW,
2854                            Uri.parse(WebView.SCHEME_TEL +
2855                            url.substring(SCHEME_WTAI_MC.length())));
2856                    startActivity(intent);
2857                    return true;
2858                }
2859                // wtai://wp/sd;dtmf
2860                // dtmf=string(dialstring)
2861                if (url.startsWith(SCHEME_WTAI_SD)) {
2862                    // TODO
2863                    // only send when there is active voice connection
2864                    return false;
2865                }
2866                // wtai://wp/ap;number;name
2867                // number=string(phone-number)
2868                // name=string
2869                if (url.startsWith(SCHEME_WTAI_AP)) {
2870                    // TODO
2871                    return false;
2872                }
2873            }
2874
2875            Uri uri;
2876            try {
2877                uri = Uri.parse(url);
2878            } catch (IllegalArgumentException ex) {
2879                return false;
2880            }
2881
2882            // check whether other activities want to handle this url
2883            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
2884            intent.addCategory(Intent.CATEGORY_BROWSABLE);
2885            try {
2886                if (startActivityIfNeeded(intent, -1)) {
2887                    return true;
2888                }
2889            } catch (ActivityNotFoundException ex) {
2890                // ignore the error. If no application can handle the URL,
2891                // eg about:blank, assume the browser can handle it.
2892            }
2893
2894            if (mMenuIsDown) {
2895                openTab(url);
2896                closeOptionsMenu();
2897                return true;
2898            }
2899
2900            return false;
2901        }
2902
2903        /**
2904         * Updates the lock icon. This method is called when we discover another
2905         * resource to be loaded for this page (for example, javascript). While
2906         * we update the icon type, we do not update the lock icon itself until
2907         * we are done loading, it is slightly more secure this way.
2908         */
2909        @Override
2910        public void onLoadResource(WebView view, String url) {
2911            if (url != null && url.length() > 0) {
2912                // It is only if the page claims to be secure
2913                // that we may have to update the lock:
2914                if (mLockIconType == LOCK_ICON_SECURE) {
2915                    // If NOT a 'safe' url, change the lock to mixed content!
2916                    if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2917                        mLockIconType = LOCK_ICON_MIXED;
2918                        if (Config.LOGV) {
2919                            Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2920                                  " updated lock icon to " + mLockIconType + " due to " + url);
2921                        }
2922                    }
2923                }
2924            }
2925        }
2926
2927        /**
2928         * Show the dialog, asking the user if they would like to continue after
2929         * an excessive number of HTTP redirects.
2930         */
2931        @Override
2932        public void onTooManyRedirects(WebView view, final Message cancelMsg,
2933                final Message continueMsg) {
2934            new AlertDialog.Builder(BrowserActivity.this)
2935                .setTitle(R.string.browserFrameRedirect)
2936                .setMessage(R.string.browserFrame307Post)
2937                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2938                    public void onClick(DialogInterface dialog, int which) {
2939                        continueMsg.sendToTarget();
2940                    }})
2941                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2942                    public void onClick(DialogInterface dialog, int which) {
2943                        cancelMsg.sendToTarget();
2944                    }})
2945                .setOnCancelListener(new OnCancelListener() {
2946                    public void onCancel(DialogInterface dialog) {
2947                        cancelMsg.sendToTarget();
2948                    }})
2949                .show();
2950        }
2951
2952        // Container class for the next error dialog that needs to be
2953        // displayed.
2954        class ErrorDialog {
2955            public final int mTitle;
2956            public final String mDescription;
2957            public final int mError;
2958            ErrorDialog(int title, String desc, int error) {
2959                mTitle = title;
2960                mDescription = desc;
2961                mError = error;
2962            }
2963        };
2964
2965        private void processNextError() {
2966            if (mQueuedErrors == null) {
2967                return;
2968            }
2969            // The first one is currently displayed so just remove it.
2970            mQueuedErrors.removeFirst();
2971            if (mQueuedErrors.size() == 0) {
2972                mQueuedErrors = null;
2973                return;
2974            }
2975            showError(mQueuedErrors.getFirst());
2976        }
2977
2978        private DialogInterface.OnDismissListener mDialogListener =
2979                new DialogInterface.OnDismissListener() {
2980                    public void onDismiss(DialogInterface d) {
2981                        processNextError();
2982                    }
2983                };
2984        private LinkedList<ErrorDialog> mQueuedErrors;
2985
2986        private void queueError(int err, String desc) {
2987            if (mQueuedErrors == null) {
2988                mQueuedErrors = new LinkedList<ErrorDialog>();
2989            }
2990            for (ErrorDialog d : mQueuedErrors) {
2991                if (d.mError == err) {
2992                    // Already saw a similar error, ignore the new one.
2993                    return;
2994                }
2995            }
2996            ErrorDialog errDialog = new ErrorDialog(
2997                    err == EventHandler.FILE_NOT_FOUND_ERROR ?
2998                    R.string.browserFrameFileErrorLabel :
2999                    R.string.browserFrameNetworkErrorLabel,
3000                    desc, err);
3001            mQueuedErrors.addLast(errDialog);
3002
3003            // Show the dialog now if the queue was empty.
3004            if (mQueuedErrors.size() == 1) {
3005                showError(errDialog);
3006            }
3007        }
3008
3009        private void showError(ErrorDialog errDialog) {
3010            AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3011                    .setTitle(errDialog.mTitle)
3012                    .setMessage(errDialog.mDescription)
3013                    .setPositiveButton(R.string.ok, null)
3014                    .create();
3015            d.setOnDismissListener(mDialogListener);
3016            d.show();
3017        }
3018
3019        /**
3020         * Show a dialog informing the user of the network error reported by
3021         * WebCore.
3022         */
3023        @Override
3024        public void onReceivedError(WebView view, int errorCode,
3025                String description, String failingUrl) {
3026            if (errorCode != EventHandler.ERROR_LOOKUP &&
3027                    errorCode != EventHandler.ERROR_CONNECT &&
3028                    errorCode != EventHandler.ERROR_BAD_URL &&
3029                    errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3030                    errorCode != EventHandler.FILE_ERROR) {
3031                queueError(errorCode, description);
3032            }
3033            Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3034                    + " " + description);
3035
3036            // We need to reset the title after an error.
3037            resetTitleAndRevertLockIcon();
3038        }
3039
3040        /**
3041         * Check with the user if it is ok to resend POST data as the page they
3042         * are trying to navigate to is the result of a POST.
3043         */
3044        @Override
3045        public void onFormResubmission(WebView view, final Message dontResend,
3046                                       final Message resend) {
3047            new AlertDialog.Builder(BrowserActivity.this)
3048                .setTitle(R.string.browserFrameFormResubmitLabel)
3049                .setMessage(R.string.browserFrameFormResubmitMessage)
3050                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3051                    public void onClick(DialogInterface dialog, int which) {
3052                        resend.sendToTarget();
3053                    }})
3054                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3055                    public void onClick(DialogInterface dialog, int which) {
3056                        dontResend.sendToTarget();
3057                    }})
3058                .setOnCancelListener(new OnCancelListener() {
3059                    public void onCancel(DialogInterface dialog) {
3060                        dontResend.sendToTarget();
3061                    }})
3062                .show();
3063        }
3064
3065        /**
3066         * Insert the url into the visited history database.
3067         * @param url The url to be inserted.
3068         * @param isReload True if this url is being reloaded.
3069         * FIXME: Not sure what to do when reloading the page.
3070         */
3071        @Override
3072        public void doUpdateVisitedHistory(WebView view, String url,
3073                boolean isReload) {
3074            if (url.regionMatches(true, 0, "about:", 0, 6)) {
3075                return;
3076            }
3077            Browser.updateVisitedHistory(mResolver, url, true);
3078            WebIconDatabase.getInstance().retainIconForPageUrl(url);
3079        }
3080
3081        /**
3082         * Displays SSL error(s) dialog to the user.
3083         */
3084        @Override
3085        public void onReceivedSslError(
3086            final WebView view, final SslErrorHandler handler, final SslError error) {
3087
3088            if (mSettings.showSecurityWarnings()) {
3089                final LayoutInflater factory =
3090                    LayoutInflater.from(BrowserActivity.this);
3091                final View warningsView =
3092                    factory.inflate(R.layout.ssl_warnings, null);
3093                final LinearLayout placeholder =
3094                    (LinearLayout)warningsView.findViewById(R.id.placeholder);
3095
3096                if (error.hasError(SslError.SSL_UNTRUSTED)) {
3097                    LinearLayout ll = (LinearLayout)factory
3098                        .inflate(R.layout.ssl_warning, null);
3099                    ((TextView)ll.findViewById(R.id.warning))
3100                        .setText(R.string.ssl_untrusted);
3101                    placeholder.addView(ll);
3102                }
3103
3104                if (error.hasError(SslError.SSL_IDMISMATCH)) {
3105                    LinearLayout ll = (LinearLayout)factory
3106                        .inflate(R.layout.ssl_warning, null);
3107                    ((TextView)ll.findViewById(R.id.warning))
3108                        .setText(R.string.ssl_mismatch);
3109                    placeholder.addView(ll);
3110                }
3111
3112                if (error.hasError(SslError.SSL_EXPIRED)) {
3113                    LinearLayout ll = (LinearLayout)factory
3114                        .inflate(R.layout.ssl_warning, null);
3115                    ((TextView)ll.findViewById(R.id.warning))
3116                        .setText(R.string.ssl_expired);
3117                    placeholder.addView(ll);
3118                }
3119
3120                if (error.hasError(SslError.SSL_NOTYETVALID)) {
3121                    LinearLayout ll = (LinearLayout)factory
3122                        .inflate(R.layout.ssl_warning, null);
3123                    ((TextView)ll.findViewById(R.id.warning))
3124                        .setText(R.string.ssl_not_yet_valid);
3125                    placeholder.addView(ll);
3126                }
3127
3128                new AlertDialog.Builder(BrowserActivity.this)
3129                    .setTitle(R.string.security_warning)
3130                    .setIcon(android.R.drawable.ic_dialog_alert)
3131                    .setView(warningsView)
3132                    .setPositiveButton(R.string.ssl_continue,
3133                            new DialogInterface.OnClickListener() {
3134                                public void onClick(DialogInterface dialog, int whichButton) {
3135                                    handler.proceed();
3136                                }
3137                            })
3138                    .setNeutralButton(R.string.view_certificate,
3139                            new DialogInterface.OnClickListener() {
3140                                public void onClick(DialogInterface dialog, int whichButton) {
3141                                    showSSLCertificateOnError(view, handler, error);
3142                                }
3143                            })
3144                    .setNegativeButton(R.string.cancel,
3145                            new DialogInterface.OnClickListener() {
3146                                public void onClick(DialogInterface dialog, int whichButton) {
3147                                    handler.cancel();
3148                                    BrowserActivity.this.resetTitleAndRevertLockIcon();
3149                                }
3150                            })
3151                    .setOnCancelListener(
3152                            new DialogInterface.OnCancelListener() {
3153                                public void onCancel(DialogInterface dialog) {
3154                                    handler.cancel();
3155                                    BrowserActivity.this.resetTitleAndRevertLockIcon();
3156                                }
3157                            })
3158                    .show();
3159            } else {
3160                handler.proceed();
3161            }
3162        }
3163
3164        /**
3165         * Handles an HTTP authentication request.
3166         *
3167         * @param handler The authentication handler
3168         * @param host The host
3169         * @param realm The realm
3170         */
3171        @Override
3172        public void onReceivedHttpAuthRequest(WebView view,
3173                final HttpAuthHandler handler, final String host, final String realm) {
3174            String username = null;
3175            String password = null;
3176
3177            boolean reuseHttpAuthUsernamePassword =
3178                handler.useHttpAuthUsernamePassword();
3179
3180            if (reuseHttpAuthUsernamePassword &&
3181                    (mTabControl.getCurrentWebView() != null)) {
3182                String[] credentials =
3183                        mTabControl.getCurrentWebView()
3184                                .getHttpAuthUsernamePassword(host, realm);
3185                if (credentials != null && credentials.length == 2) {
3186                    username = credentials[0];
3187                    password = credentials[1];
3188                }
3189            }
3190
3191            if (username != null && password != null) {
3192                handler.proceed(username, password);
3193            } else {
3194                showHttpAuthentication(handler, host, realm, null, null, null, 0);
3195            }
3196        }
3197
3198        @Override
3199        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3200            if (mMenuIsDown) {
3201                // only check shortcut key when MENU is held
3202                return getWindow().isShortcutKey(event.getKeyCode(), event);
3203            } else {
3204                return false;
3205            }
3206        }
3207
3208        @Override
3209        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3210            if (view != mTabControl.getCurrentTopWebView()) {
3211                return;
3212            }
3213            if (event.isDown()) {
3214                BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3215            } else {
3216                BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3217            }
3218        }
3219    };
3220
3221    //--------------------------------------------------------------------------
3222    // WebChromeClient implementation
3223    //--------------------------------------------------------------------------
3224
3225    /* package */ WebChromeClient getWebChromeClient() {
3226        return mWebChromeClient;
3227    }
3228
3229    private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3230        // Helper method to create a new tab or sub window.
3231        private void createWindow(final boolean dialog, final Message msg) {
3232            if (dialog) {
3233                mTabControl.createSubWindow();
3234                final TabControl.Tab t = mTabControl.getCurrentTab();
3235                attachSubWindow(t);
3236                WebView.WebViewTransport transport =
3237                        (WebView.WebViewTransport) msg.obj;
3238                transport.setWebView(t.getSubWebView());
3239                msg.sendToTarget();
3240            } else {
3241                final TabControl.Tab parent = mTabControl.getCurrentTab();
3242                // openTabAndShow will dispatch the message after creating the
3243                // new WebView. This will prevent another request from coming
3244                // in during the animation.
3245                final TabControl.Tab newTab = openTabAndShow(null, msg, false,
3246                        null);
3247                if (newTab != parent) {
3248                    parent.addChildTab(newTab);
3249                }
3250                WebView.WebViewTransport transport =
3251                        (WebView.WebViewTransport) msg.obj;
3252                transport.setWebView(mTabControl.getCurrentWebView());
3253            }
3254        }
3255
3256        @Override
3257        public boolean onCreateWindow(WebView view, final boolean dialog,
3258                final boolean userGesture, final Message resultMsg) {
3259            // Ignore these requests during tab animations or if the tab
3260            // overview is showing.
3261            if (mAnimationCount > 0 || mTabOverview != null) {
3262                return false;
3263            }
3264            // Short-circuit if we can't create any more tabs or sub windows.
3265            if (dialog && mTabControl.getCurrentSubWindow() != null) {
3266                new AlertDialog.Builder(BrowserActivity.this)
3267                        .setTitle(R.string.too_many_subwindows_dialog_title)
3268                        .setIcon(android.R.drawable.ic_dialog_alert)
3269                        .setMessage(R.string.too_many_subwindows_dialog_message)
3270                        .setPositiveButton(R.string.ok, null)
3271                        .show();
3272                return false;
3273            } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3274                new AlertDialog.Builder(BrowserActivity.this)
3275                        .setTitle(R.string.too_many_windows_dialog_title)
3276                        .setIcon(android.R.drawable.ic_dialog_alert)
3277                        .setMessage(R.string.too_many_windows_dialog_message)
3278                        .setPositiveButton(R.string.ok, null)
3279                        .show();
3280                return false;
3281            }
3282
3283            // Short-circuit if this was a user gesture.
3284            if (userGesture) {
3285                // createWindow will call openTabAndShow for new Windows and
3286                // that will call tabPicker which will increment
3287                // mAnimationCount.
3288                createWindow(dialog, resultMsg);
3289                return true;
3290            }
3291
3292            // Allow the popup and create the appropriate window.
3293            final AlertDialog.OnClickListener allowListener =
3294                    new AlertDialog.OnClickListener() {
3295                        public void onClick(DialogInterface d,
3296                                int which) {
3297                            // Same comment as above for setting
3298                            // mAnimationCount.
3299                            createWindow(dialog, resultMsg);
3300                            // Since we incremented mAnimationCount while the
3301                            // dialog was up, we have to decrement it here.
3302                            mAnimationCount--;
3303                        }
3304                    };
3305
3306            // Block the popup by returning a null WebView.
3307            final AlertDialog.OnClickListener blockListener =
3308                    new AlertDialog.OnClickListener() {
3309                        public void onClick(DialogInterface d, int which) {
3310                            resultMsg.sendToTarget();
3311                            // We are not going to trigger an animation so
3312                            // unblock keys and animation requests.
3313                            mAnimationCount--;
3314                        }
3315                    };
3316
3317            // Build a confirmation dialog to display to the user.
3318            final AlertDialog d =
3319                    new AlertDialog.Builder(BrowserActivity.this)
3320                    .setTitle(R.string.attention)
3321                    .setIcon(android.R.drawable.ic_dialog_alert)
3322                    .setMessage(R.string.popup_window_attempt)
3323                    .setPositiveButton(R.string.allow, allowListener)
3324                    .setNegativeButton(R.string.block, blockListener)
3325                    .setCancelable(false)
3326                    .create();
3327
3328            // Show the confirmation dialog.
3329            d.show();
3330            // We want to increment mAnimationCount here to prevent a
3331            // potential race condition. If the user allows a pop-up from a
3332            // site and that pop-up then triggers another pop-up, it is
3333            // possible to get the BACK key between here and when the dialog
3334            // appears.
3335            mAnimationCount++;
3336            return true;
3337        }
3338
3339        @Override
3340        public void onCloseWindow(WebView window) {
3341            final int currentIndex = mTabControl.getCurrentIndex();
3342            final TabControl.Tab parent =
3343                    mTabControl.getCurrentTab().getParentTab();
3344            if (parent != null) {
3345                // JavaScript can only close popup window.
3346                switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3347            }
3348        }
3349
3350        @Override
3351        public void onProgressChanged(WebView view, int newProgress) {
3352            // Block progress updates to the title bar while the tab overview
3353            // is animating or being displayed.
3354            if (mAnimationCount == 0 && mTabOverview == null) {
3355                getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3356                        newProgress * 100);
3357            }
3358
3359            if (newProgress == 100) {
3360                // onProgressChanged() is called for sub-frame too while
3361                // onPageFinished() is only called for the main frame. sync
3362                // cookie and cache promptly here.
3363                CookieSyncManager.getInstance().sync();
3364                if (mInLoad) {
3365                    mInLoad = false;
3366                    updateInLoadMenuItems();
3367                }
3368            } else {
3369                // onPageFinished may have already been called but a subframe
3370                // is still loading and updating the progress. Reset mInLoad
3371                // and update the menu items.
3372                if (!mInLoad) {
3373                    mInLoad = true;
3374                    updateInLoadMenuItems();
3375                }
3376            }
3377        }
3378
3379        @Override
3380        public void onReceivedTitle(WebView view, String title) {
3381            String url = view.getOriginalUrl();
3382
3383            // here, if url is null, we want to reset the title
3384            setUrlTitle(url, title);
3385
3386            if (url == null ||
3387                url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3388                return;
3389            }
3390            if (url.startsWith("http://www.")) {
3391                url = url.substring(11);
3392            } else if (url.startsWith("http://")) {
3393                url = url.substring(4);
3394            }
3395            try {
3396                url = "%" + url;
3397                String [] selArgs = new String[] { url };
3398
3399                String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3400                        + Browser.BookmarkColumns.BOOKMARK + " = 0";
3401                Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3402                    Browser.HISTORY_PROJECTION, where, selArgs, null);
3403                if (c.moveToFirst()) {
3404                    if (Config.LOGV) {
3405                        Log.v(LOGTAG, "updating cursor");
3406                    }
3407                    // Current implementation of database only has one entry per
3408                    // url.
3409                    int titleIndex =
3410                            c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3411                    c.updateString(titleIndex, title);
3412                    c.commitUpdates();
3413                }
3414                c.close();
3415            } catch (IllegalStateException e) {
3416                Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3417            } catch (SQLiteException ex) {
3418                Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3419            }
3420        }
3421
3422        @Override
3423        public void onReceivedIcon(WebView view, Bitmap icon) {
3424            updateIcon(view.getUrl(), icon);
3425        }
3426    };
3427
3428    /**
3429     * Notify the host application a download should be done, or that
3430     * the data should be streamed if a streaming viewer is available.
3431     * @param url The full url to the content that should be downloaded
3432     * @param contentDisposition Content-disposition http header, if
3433     *                           present.
3434     * @param mimetype The mimetype of the content reported by the server
3435     * @param contentLength The file size reported by the server
3436     */
3437    public void onDownloadStart(String url, String userAgent,
3438            String contentDisposition, String mimetype, long contentLength) {
3439        // if we're dealing wih A/V content that's not explicitly marked
3440        //     for download, check if it's streamable.
3441        if (contentDisposition == null
3442                        || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3443            // query the package manager to see if there's a registered handler
3444            //     that matches.
3445            Intent intent = new Intent(Intent.ACTION_VIEW);
3446            intent.setDataAndType(Uri.parse(url), mimetype);
3447            if (getPackageManager().resolveActivity(intent,
3448                        PackageManager.MATCH_DEFAULT_ONLY) != null) {
3449                // someone knows how to handle this mime type with this scheme, don't download.
3450                try {
3451                    startActivity(intent);
3452                    return;
3453                } catch (ActivityNotFoundException ex) {
3454                    if (Config.LOGD) {
3455                        Log.d(LOGTAG, "activity not found for " + mimetype
3456                                + " over " + Uri.parse(url).getScheme(), ex);
3457                    }
3458                    // Best behavior is to fall back to a download in this case
3459                }
3460            }
3461        }
3462        onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3463    }
3464
3465    /**
3466     * Notify the host application a download should be done, even if there
3467     * is a streaming viewer available for thise type.
3468     * @param url The full url to the content that should be downloaded
3469     * @param contentDisposition Content-disposition http header, if
3470     *                           present.
3471     * @param mimetype The mimetype of the content reported by the server
3472     * @param contentLength The file size reported by the server
3473     */
3474    /*package */ void onDownloadStartNoStream(String url, String userAgent,
3475            String contentDisposition, String mimetype, long contentLength) {
3476
3477        String filename = URLUtil.guessFileName(url,
3478                contentDisposition, mimetype);
3479
3480        // Check to see if we have an SDCard
3481        String status = Environment.getExternalStorageState();
3482        if (!status.equals(Environment.MEDIA_MOUNTED)) {
3483            int title;
3484            String msg;
3485
3486            // Check to see if the SDCard is busy, same as the music app
3487            if (status.equals(Environment.MEDIA_SHARED)) {
3488                msg = getString(R.string.download_sdcard_busy_dlg_msg);
3489                title = R.string.download_sdcard_busy_dlg_title;
3490            } else {
3491                msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3492                title = R.string.download_no_sdcard_dlg_title;
3493            }
3494
3495            new AlertDialog.Builder(this)
3496                .setTitle(title)
3497                .setIcon(android.R.drawable.ic_dialog_alert)
3498                .setMessage(msg)
3499                .setPositiveButton(R.string.ok, null)
3500                .show();
3501            return;
3502        }
3503
3504        // java.net.URI is a lot stricter than KURL so we have to undo
3505        // KURL's percent-encoding and redo the encoding using java.net.URI.
3506        URI uri = null;
3507        try {
3508            // Undo the percent-encoding that KURL may have done.
3509            String newUrl = new String(URLUtil.decode(url.getBytes()));
3510            // Parse the url into pieces
3511            WebAddress w = new WebAddress(newUrl);
3512            String frag = null;
3513            String query = null;
3514            String path = w.mPath;
3515            // Break the path into path, query, and fragment
3516            if (path.length() > 0) {
3517                // Strip the fragment
3518                int idx = path.lastIndexOf('#');
3519                if (idx != -1) {
3520                    frag = path.substring(idx + 1);
3521                    path = path.substring(0, idx);
3522                }
3523                idx = path.lastIndexOf('?');
3524                if (idx != -1) {
3525                    query = path.substring(idx + 1);
3526                    path = path.substring(0, idx);
3527                }
3528            }
3529            uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3530                    query, frag);
3531        } catch (Exception e) {
3532            Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3533            return;
3534        }
3535
3536        // XXX: Have to use the old url since the cookies were stored using the
3537        // old percent-encoded url.
3538        String cookies = CookieManager.getInstance().getCookie(url);
3539
3540        ContentValues values = new ContentValues();
3541        values.put(Downloads.URI, uri.toString());
3542        values.put(Downloads.COOKIE_DATA, cookies);
3543        values.put(Downloads.USER_AGENT, userAgent);
3544        values.put(Downloads.NOTIFICATION_PACKAGE,
3545                getPackageName());
3546        values.put(Downloads.NOTIFICATION_CLASS,
3547                BrowserDownloadPage.class.getCanonicalName());
3548        values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3549        values.put(Downloads.MIMETYPE, mimetype);
3550        values.put(Downloads.FILENAME_HINT, filename);
3551        values.put(Downloads.DESCRIPTION, uri.getHost());
3552        if (contentLength > 0) {
3553            values.put(Downloads.TOTAL_BYTES, contentLength);
3554        }
3555        if (mimetype == null) {
3556            // We must have long pressed on a link or image to download it. We
3557            // are not sure of the mimetype in this case, so do a head request
3558            new FetchUrlMimeType(this).execute(values);
3559        } else {
3560            final Uri contentUri =
3561                    getContentResolver().insert(Downloads.CONTENT_URI, values);
3562            viewDownloads(contentUri);
3563        }
3564
3565    }
3566
3567    /**
3568     * Resets the lock icon. This method is called when we start a new load and
3569     * know the url to be loaded.
3570     */
3571    private void resetLockIcon(String url) {
3572        // Save the lock-icon state (we revert to it if the load gets cancelled)
3573        saveLockIcon();
3574
3575        mLockIconType = LOCK_ICON_UNSECURE;
3576        if (URLUtil.isHttpsUrl(url)) {
3577            mLockIconType = LOCK_ICON_SECURE;
3578            if (Config.LOGV) {
3579                Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3580                      " reset lock icon to " + mLockIconType);
3581            }
3582        }
3583
3584        updateLockIconImage(LOCK_ICON_UNSECURE);
3585    }
3586
3587    /**
3588     * Resets the lock icon.  This method is called when the icon needs to be
3589     * reset but we do not know whether we are loading a secure or not secure
3590     * page.
3591     */
3592    private void resetLockIcon() {
3593        // Save the lock-icon state (we revert to it if the load gets cancelled)
3594        saveLockIcon();
3595
3596        mLockIconType = LOCK_ICON_UNSECURE;
3597
3598        if (Config.LOGV) {
3599          Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3600                " reset lock icon to " + mLockIconType);
3601        }
3602
3603        updateLockIconImage(LOCK_ICON_UNSECURE);
3604    }
3605
3606    /**
3607     * Updates the lock-icon image in the title-bar.
3608     */
3609    private void updateLockIconImage(int lockIconType) {
3610        Drawable d = null;
3611        if (lockIconType == LOCK_ICON_SECURE) {
3612            d = mSecLockIcon;
3613        } else if (lockIconType == LOCK_ICON_MIXED) {
3614            d = mMixLockIcon;
3615        }
3616        // If the tab overview is animating or being shown, do not update the
3617        // lock icon.
3618        if (mAnimationCount == 0 && mTabOverview == null) {
3619            getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3620        }
3621    }
3622
3623    /**
3624     * Displays a page-info dialog.
3625     * @param tab The tab to show info about
3626     * @param fromShowSSLCertificateOnError The flag that indicates whether
3627     * this dialog was opened from the SSL-certificate-on-error dialog or
3628     * not. This is important, since we need to know whether to return to
3629     * the parent dialog or simply dismiss.
3630     */
3631    private void showPageInfo(final TabControl.Tab tab,
3632                              final boolean fromShowSSLCertificateOnError) {
3633        final LayoutInflater factory = LayoutInflater
3634                .from(this);
3635
3636        final View pageInfoView = factory.inflate(R.layout.page_info, null);
3637
3638        final WebView view = tab.getWebView();
3639
3640        String url = null;
3641        String title = null;
3642
3643        if (view == null) {
3644            url = tab.getUrl();
3645            title = tab.getTitle();
3646        } else if (view == mTabControl.getCurrentWebView()) {
3647             // Use the cached title and url if this is the current WebView
3648            url = mUrl;
3649            title = mTitle;
3650        } else {
3651            url = view.getUrl();
3652            title = view.getTitle();
3653        }
3654
3655        if (url == null) {
3656            url = "";
3657        }
3658        if (title == null) {
3659            title = "";
3660        }
3661
3662        ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3663        ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3664
3665        mPageInfoView = tab;
3666        mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3667
3668        AlertDialog.Builder alertDialogBuilder =
3669            new AlertDialog.Builder(this)
3670            .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3671            .setView(pageInfoView)
3672            .setPositiveButton(
3673                R.string.ok,
3674                new DialogInterface.OnClickListener() {
3675                    public void onClick(DialogInterface dialog,
3676                                        int whichButton) {
3677                        mPageInfoDialog = null;
3678                        mPageInfoView = null;
3679                        mPageInfoFromShowSSLCertificateOnError = null;
3680
3681                        // if we came here from the SSL error dialog
3682                        if (fromShowSSLCertificateOnError) {
3683                            // go back to the SSL error dialog
3684                            showSSLCertificateOnError(
3685                                mSSLCertificateOnErrorView,
3686                                mSSLCertificateOnErrorHandler,
3687                                mSSLCertificateOnErrorError);
3688                        }
3689                    }
3690                })
3691            .setOnCancelListener(
3692                new DialogInterface.OnCancelListener() {
3693                    public void onCancel(DialogInterface dialog) {
3694                        mPageInfoDialog = null;
3695                        mPageInfoView = null;
3696                        mPageInfoFromShowSSLCertificateOnError = null;
3697
3698                        // if we came here from the SSL error dialog
3699                        if (fromShowSSLCertificateOnError) {
3700                            // go back to the SSL error dialog
3701                            showSSLCertificateOnError(
3702                                mSSLCertificateOnErrorView,
3703                                mSSLCertificateOnErrorHandler,
3704                                mSSLCertificateOnErrorError);
3705                        }
3706                    }
3707                });
3708
3709        // if we have a main top-level page SSL certificate set or a certificate
3710        // error
3711        if (fromShowSSLCertificateOnError ||
3712                (view != null && view.getCertificate() != null)) {
3713            // add a 'View Certificate' button
3714            alertDialogBuilder.setNeutralButton(
3715                R.string.view_certificate,
3716                new DialogInterface.OnClickListener() {
3717                    public void onClick(DialogInterface dialog,
3718                                        int whichButton) {
3719                        mPageInfoDialog = null;
3720                        mPageInfoView = null;
3721                        mPageInfoFromShowSSLCertificateOnError = null;
3722
3723                        // if we came here from the SSL error dialog
3724                        if (fromShowSSLCertificateOnError) {
3725                            // go back to the SSL error dialog
3726                            showSSLCertificateOnError(
3727                                mSSLCertificateOnErrorView,
3728                                mSSLCertificateOnErrorHandler,
3729                                mSSLCertificateOnErrorError);
3730                        } else {
3731                            // otherwise, display the top-most certificate from
3732                            // the chain
3733                            if (view.getCertificate() != null) {
3734                                showSSLCertificate(tab);
3735                            }
3736                        }
3737                    }
3738                });
3739        }
3740
3741        mPageInfoDialog = alertDialogBuilder.show();
3742    }
3743
3744       /**
3745     * Displays the main top-level page SSL certificate dialog
3746     * (accessible from the Page-Info dialog).
3747     * @param tab The tab to show certificate for.
3748     */
3749    private void showSSLCertificate(final TabControl.Tab tab) {
3750        final View certificateView =
3751                inflateCertificateView(tab.getWebView().getCertificate());
3752        if (certificateView == null) {
3753            return;
3754        }
3755
3756        LayoutInflater factory = LayoutInflater.from(this);
3757
3758        final LinearLayout placeholder =
3759                (LinearLayout)certificateView.findViewById(R.id.placeholder);
3760
3761        LinearLayout ll = (LinearLayout) factory.inflate(
3762            R.layout.ssl_success, placeholder);
3763        ((TextView)ll.findViewById(R.id.success))
3764            .setText(R.string.ssl_certificate_is_valid);
3765
3766        mSSLCertificateView = tab;
3767        mSSLCertificateDialog =
3768            new AlertDialog.Builder(this)
3769                .setTitle(R.string.ssl_certificate).setIcon(
3770                    R.drawable.ic_dialog_browser_certificate_secure)
3771                .setView(certificateView)
3772                .setPositiveButton(R.string.ok,
3773                        new DialogInterface.OnClickListener() {
3774                            public void onClick(DialogInterface dialog,
3775                                    int whichButton) {
3776                                mSSLCertificateDialog = null;
3777                                mSSLCertificateView = null;
3778
3779                                showPageInfo(tab, false);
3780                            }
3781                        })
3782                .setOnCancelListener(
3783                        new DialogInterface.OnCancelListener() {
3784                            public void onCancel(DialogInterface dialog) {
3785                                mSSLCertificateDialog = null;
3786                                mSSLCertificateView = null;
3787
3788                                showPageInfo(tab, false);
3789                            }
3790                        })
3791                .show();
3792    }
3793
3794    /**
3795     * Displays the SSL error certificate dialog.
3796     * @param view The target web-view.
3797     * @param handler The SSL error handler responsible for cancelling the
3798     * connection that resulted in an SSL error or proceeding per user request.
3799     * @param error The SSL error object.
3800     */
3801    private void showSSLCertificateOnError(
3802        final WebView view, final SslErrorHandler handler, final SslError error) {
3803
3804        final View certificateView =
3805            inflateCertificateView(error.getCertificate());
3806        if (certificateView == null) {
3807            return;
3808        }
3809
3810        LayoutInflater factory = LayoutInflater.from(this);
3811
3812        final LinearLayout placeholder =
3813                (LinearLayout)certificateView.findViewById(R.id.placeholder);
3814
3815        if (error.hasError(SslError.SSL_UNTRUSTED)) {
3816            LinearLayout ll = (LinearLayout)factory
3817                .inflate(R.layout.ssl_warning, placeholder);
3818            ((TextView)ll.findViewById(R.id.warning))
3819                .setText(R.string.ssl_untrusted);
3820        }
3821
3822        if (error.hasError(SslError.SSL_IDMISMATCH)) {
3823            LinearLayout ll = (LinearLayout)factory
3824                .inflate(R.layout.ssl_warning, placeholder);
3825            ((TextView)ll.findViewById(R.id.warning))
3826                .setText(R.string.ssl_mismatch);
3827        }
3828
3829        if (error.hasError(SslError.SSL_EXPIRED)) {
3830            LinearLayout ll = (LinearLayout)factory
3831                .inflate(R.layout.ssl_warning, placeholder);
3832            ((TextView)ll.findViewById(R.id.warning))
3833                .setText(R.string.ssl_expired);
3834        }
3835
3836        if (error.hasError(SslError.SSL_NOTYETVALID)) {
3837            LinearLayout ll = (LinearLayout)factory
3838                .inflate(R.layout.ssl_warning, placeholder);
3839            ((TextView)ll.findViewById(R.id.warning))
3840                .setText(R.string.ssl_not_yet_valid);
3841        }
3842
3843        mSSLCertificateOnErrorHandler = handler;
3844        mSSLCertificateOnErrorView = view;
3845        mSSLCertificateOnErrorError = error;
3846        mSSLCertificateOnErrorDialog =
3847            new AlertDialog.Builder(this)
3848                .setTitle(R.string.ssl_certificate).setIcon(
3849                    R.drawable.ic_dialog_browser_certificate_partially_secure)
3850                .setView(certificateView)
3851                .setPositiveButton(R.string.ok,
3852                        new DialogInterface.OnClickListener() {
3853                            public void onClick(DialogInterface dialog,
3854                                    int whichButton) {
3855                                mSSLCertificateOnErrorDialog = null;
3856                                mSSLCertificateOnErrorView = null;
3857                                mSSLCertificateOnErrorHandler = null;
3858                                mSSLCertificateOnErrorError = null;
3859
3860                                mWebViewClient.onReceivedSslError(
3861                                    view, handler, error);
3862                            }
3863                        })
3864                 .setNeutralButton(R.string.page_info_view,
3865                        new DialogInterface.OnClickListener() {
3866                            public void onClick(DialogInterface dialog,
3867                                    int whichButton) {
3868                                mSSLCertificateOnErrorDialog = null;
3869
3870                                // do not clear the dialog state: we will
3871                                // need to show the dialog again once the
3872                                // user is done exploring the page-info details
3873
3874                                showPageInfo(mTabControl.getTabFromView(view),
3875                                        true);
3876                            }
3877                        })
3878                .setOnCancelListener(
3879                        new DialogInterface.OnCancelListener() {
3880                            public void onCancel(DialogInterface dialog) {
3881                                mSSLCertificateOnErrorDialog = null;
3882                                mSSLCertificateOnErrorView = null;
3883                                mSSLCertificateOnErrorHandler = null;
3884                                mSSLCertificateOnErrorError = null;
3885
3886                                mWebViewClient.onReceivedSslError(
3887                                    view, handler, error);
3888                            }
3889                        })
3890                .show();
3891    }
3892
3893    /**
3894     * Inflates the SSL certificate view (helper method).
3895     * @param certificate The SSL certificate.
3896     * @return The resultant certificate view with issued-to, issued-by,
3897     * issued-on, expires-on, and possibly other fields set.
3898     * If the input certificate is null, returns null.
3899     */
3900    private View inflateCertificateView(SslCertificate certificate) {
3901        if (certificate == null) {
3902            return null;
3903        }
3904
3905        LayoutInflater factory = LayoutInflater.from(this);
3906
3907        View certificateView = factory.inflate(
3908            R.layout.ssl_certificate, null);
3909
3910        // issued to:
3911        SslCertificate.DName issuedTo = certificate.getIssuedTo();
3912        if (issuedTo != null) {
3913            ((TextView) certificateView.findViewById(R.id.to_common))
3914                .setText(issuedTo.getCName());
3915            ((TextView) certificateView.findViewById(R.id.to_org))
3916                .setText(issuedTo.getOName());
3917            ((TextView) certificateView.findViewById(R.id.to_org_unit))
3918                .setText(issuedTo.getUName());
3919        }
3920
3921        // issued by:
3922        SslCertificate.DName issuedBy = certificate.getIssuedBy();
3923        if (issuedBy != null) {
3924            ((TextView) certificateView.findViewById(R.id.by_common))
3925                .setText(issuedBy.getCName());
3926            ((TextView) certificateView.findViewById(R.id.by_org))
3927                .setText(issuedBy.getOName());
3928            ((TextView) certificateView.findViewById(R.id.by_org_unit))
3929                .setText(issuedBy.getUName());
3930        }
3931
3932        // issued on:
3933        String issuedOn = reformatCertificateDate(
3934            certificate.getValidNotBefore());
3935        ((TextView) certificateView.findViewById(R.id.issued_on))
3936            .setText(issuedOn);
3937
3938        // expires on:
3939        String expiresOn = reformatCertificateDate(
3940            certificate.getValidNotAfter());
3941        ((TextView) certificateView.findViewById(R.id.expires_on))
3942            .setText(expiresOn);
3943
3944        return certificateView;
3945    }
3946
3947    /**
3948     * Re-formats the certificate date (Date.toString()) string to
3949     * a properly localized date string.
3950     * @return Properly localized version of the certificate date string and
3951     * the original certificate date string if fails to localize.
3952     * If the original string is null, returns an empty string "".
3953     */
3954    private String reformatCertificateDate(String certificateDate) {
3955      String reformattedDate = null;
3956
3957      if (certificateDate != null) {
3958          Date date = null;
3959          try {
3960              date = java.text.DateFormat.getInstance().parse(certificateDate);
3961          } catch (ParseException e) {
3962              date = null;
3963          }
3964
3965          if (date != null) {
3966              reformattedDate =
3967                  DateFormat.getDateFormat(this).format(date);
3968          }
3969      }
3970
3971      return reformattedDate != null ? reformattedDate :
3972          (certificateDate != null ? certificateDate : "");
3973    }
3974
3975    /**
3976     * Displays an http-authentication dialog.
3977     */
3978    private void showHttpAuthentication(final HttpAuthHandler handler,
3979            final String host, final String realm, final String title,
3980            final String name, final String password, int focusId) {
3981        LayoutInflater factory = LayoutInflater.from(this);
3982        final View v = factory
3983                .inflate(R.layout.http_authentication, null);
3984        if (name != null) {
3985            ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3986        }
3987        if (password != null) {
3988            ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3989        }
3990
3991        String titleText = title;
3992        if (titleText == null) {
3993            titleText = getText(R.string.sign_in_to).toString().replace(
3994                    "%s1", host).replace("%s2", realm);
3995        }
3996
3997        mHttpAuthHandler = handler;
3998        AlertDialog dialog = new AlertDialog.Builder(this)
3999                .setTitle(titleText)
4000                .setIcon(android.R.drawable.ic_dialog_alert)
4001                .setView(v)
4002                .setPositiveButton(R.string.action,
4003                        new DialogInterface.OnClickListener() {
4004                             public void onClick(DialogInterface dialog,
4005                                     int whichButton) {
4006                                String nm = ((EditText) v
4007                                        .findViewById(R.id.username_edit))
4008                                        .getText().toString();
4009                                String pw = ((EditText) v
4010                                        .findViewById(R.id.password_edit))
4011                                        .getText().toString();
4012                                BrowserActivity.this.setHttpAuthUsernamePassword
4013                                        (host, realm, nm, pw);
4014                                handler.proceed(nm, pw);
4015                                mHttpAuthenticationDialog = null;
4016                                mHttpAuthHandler = null;
4017                            }})
4018                .setNegativeButton(R.string.cancel,
4019                        new DialogInterface.OnClickListener() {
4020                            public void onClick(DialogInterface dialog,
4021                                    int whichButton) {
4022                                handler.cancel();
4023                                BrowserActivity.this.resetTitleAndRevertLockIcon();
4024                                mHttpAuthenticationDialog = null;
4025                                mHttpAuthHandler = null;
4026                            }})
4027                .setOnCancelListener(new DialogInterface.OnCancelListener() {
4028                        public void onCancel(DialogInterface dialog) {
4029                            handler.cancel();
4030                            BrowserActivity.this.resetTitleAndRevertLockIcon();
4031                            mHttpAuthenticationDialog = null;
4032                            mHttpAuthHandler = null;
4033                        }})
4034                .create();
4035        // Make the IME appear when the dialog is displayed if applicable.
4036        dialog.getWindow().setSoftInputMode(
4037                WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4038        dialog.show();
4039        if (focusId != 0) {
4040            dialog.findViewById(focusId).requestFocus();
4041        } else {
4042            v.findViewById(R.id.username_edit).requestFocus();
4043        }
4044        mHttpAuthenticationDialog = dialog;
4045    }
4046
4047    public int getProgress() {
4048        WebView w = mTabControl.getCurrentWebView();
4049        if (w != null) {
4050            return w.getProgress();
4051        } else {
4052            return 100;
4053        }
4054    }
4055
4056    /**
4057     * Set HTTP authentication password.
4058     *
4059     * @param host The host for the password
4060     * @param realm The realm for the password
4061     * @param username The username for the password. If it is null, it means
4062     *            password can't be saved.
4063     * @param password The password
4064     */
4065    public void setHttpAuthUsernamePassword(String host, String realm,
4066                                            String username,
4067                                            String password) {
4068        WebView w = mTabControl.getCurrentWebView();
4069        if (w != null) {
4070            w.setHttpAuthUsernamePassword(host, realm, username, password);
4071        }
4072    }
4073
4074    /**
4075     * connectivity manager says net has come or gone... inform the user
4076     * @param up true if net has come up, false if net has gone down
4077     */
4078    public void onNetworkToggle(boolean up) {
4079        if (up == mIsNetworkUp) {
4080            return;
4081        } else if (up) {
4082            mIsNetworkUp = true;
4083            if (mAlertDialog != null) {
4084                mAlertDialog.cancel();
4085                mAlertDialog = null;
4086            }
4087        } else {
4088            mIsNetworkUp = false;
4089            if (mInLoad && mAlertDialog == null) {
4090                mAlertDialog = new AlertDialog.Builder(this)
4091                        .setTitle(R.string.loadSuspendedTitle)
4092                        .setMessage(R.string.loadSuspended)
4093                        .setPositiveButton(R.string.ok, null)
4094                        .show();
4095            }
4096        }
4097        WebView w = mTabControl.getCurrentWebView();
4098        if (w != null) {
4099            w.setNetworkAvailable(up);
4100        }
4101    }
4102
4103    @Override
4104    protected void onActivityResult(int requestCode, int resultCode,
4105                                    Intent intent) {
4106        switch (requestCode) {
4107            case COMBO_PAGE:
4108                if (resultCode == RESULT_OK && intent != null) {
4109                    String data = intent.getAction();
4110                    Bundle extras = intent.getExtras();
4111                    if (extras != null && extras.getBoolean("new_window", false)) {
4112                        openTab(data);
4113                    } else {
4114                        final TabControl.Tab currentTab =
4115                                mTabControl.getCurrentTab();
4116                        // If the Window overview is up and we are not in the
4117                        // middle of an animation, animate away from it to the
4118                        // current tab.
4119                        if (mTabOverview != null && mAnimationCount == 0) {
4120                            sendAnimateFromOverview(currentTab, false, data,
4121                                    TAB_OVERVIEW_DELAY, null);
4122                        } else {
4123                            dismissSubWindow(currentTab);
4124                            if (data != null && data.length() != 0) {
4125                                getTopWindow().loadUrl(data);
4126                            }
4127                        }
4128                    }
4129                }
4130                break;
4131            default:
4132                break;
4133        }
4134        getTopWindow().requestFocus();
4135    }
4136
4137    /*
4138     * This method is called as a result of the user selecting the options
4139     * menu to see the download window, or when a download changes state. It
4140     * shows the download window ontop of the current window.
4141     */
4142    /* package */ void viewDownloads(Uri downloadRecord) {
4143        Intent intent = new Intent(this,
4144                BrowserDownloadPage.class);
4145        intent.setData(downloadRecord);
4146        startActivityForResult(intent, this.DOWNLOAD_PAGE);
4147
4148    }
4149
4150    /**
4151     * Handle results from Tab Switcher mTabOverview tool
4152     */
4153    private class TabListener implements ImageGrid.Listener {
4154        public void remove(int position) {
4155            // Note: Remove is not enabled if we have only one tab.
4156            if (Config.DEBUG && mTabControl.getTabCount() == 1) {
4157                throw new AssertionError();
4158            }
4159
4160            // Remember the current tab.
4161            TabControl.Tab current = mTabControl.getCurrentTab();
4162            final TabControl.Tab remove = mTabControl.getTab(position);
4163            mTabControl.removeTab(remove);
4164            // If we removed the current tab, use the tab at position - 1 if
4165            // possible.
4166            if (current == remove) {
4167                // If the user removes the last tab, act like the New Tab item
4168                // was clicked on.
4169                if (mTabControl.getTabCount() == 0) {
4170                    current = mTabControl.createNewTab();
4171                    sendAnimateFromOverview(current, true,
4172                            mSettings.getHomePage(), TAB_OVERVIEW_DELAY, null);
4173                } else {
4174                    final int index = position > 0 ? (position - 1) : 0;
4175                    current = mTabControl.getTab(index);
4176                }
4177            }
4178
4179            // The tab overview could have been dismissed before this method is
4180            // called.
4181            if (mTabOverview != null) {
4182                // Remove the tab and change the index.
4183                mTabOverview.remove(position);
4184                mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4185            }
4186
4187            // Only the current tab ensures its WebView is non-null. This
4188            // implies that we are reloading the freed tab.
4189            mTabControl.setCurrentTab(current);
4190        }
4191        public void onClick(int index) {
4192            // Change the tab if necessary.
4193            // Index equals ImageGrid.CANCEL when pressing back from the tab
4194            // overview.
4195            if (index == ImageGrid.CANCEL) {
4196                index = mTabControl.getCurrentIndex();
4197                // The current index is -1 if the current tab was removed.
4198                if (index == -1) {
4199                    // Take the last tab as a fallback.
4200                    index = mTabControl.getTabCount() - 1;
4201                }
4202            }
4203
4204            // Clear all the data for tab picker so next time it will be
4205            // recreated.
4206            mTabControl.wipeAllPickerData();
4207
4208            // NEW_TAB means that the "New Tab" cell was clicked on.
4209            if (index == ImageGrid.NEW_TAB) {
4210                openTabAndShow(mSettings.getHomePage(), null, false, null);
4211            } else {
4212                sendAnimateFromOverview(mTabControl.getTab(index),
4213                        false, null, 0, null);
4214            }
4215        }
4216    }
4217
4218    // A fake View that draws the WebView's picture with a fast zoom filter.
4219    // The View is used in case the tab is freed during the animation because
4220    // of low memory.
4221    private static class AnimatingView extends View {
4222        private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4223                Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4224        private static final DrawFilter sZoomFilter =
4225                new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4226        private final Picture mPicture;
4227        private final float   mScale;
4228        private final int     mScrollX;
4229        private final int     mScrollY;
4230        final TabControl.Tab  mTab;
4231
4232        AnimatingView(Context ctxt, TabControl.Tab t) {
4233            super(ctxt);
4234            mTab = t;
4235            // Use the top window in the animation since the tab overview will
4236            // display the top window in each cell.
4237            final WebView w = t.getTopWindow();
4238            mPicture = w.capturePicture();
4239            mScale = w.getScale() / w.getWidth();
4240            mScrollX = w.getScrollX();
4241            mScrollY = w.getScrollY();
4242        }
4243
4244        @Override
4245        protected void onDraw(Canvas canvas) {
4246            canvas.save();
4247            canvas.drawColor(Color.WHITE);
4248            if (mPicture != null) {
4249                canvas.setDrawFilter(sZoomFilter);
4250                float scale = getWidth() * mScale;
4251                canvas.scale(scale, scale);
4252                canvas.translate(-mScrollX, -mScrollY);
4253                canvas.drawPicture(mPicture);
4254            }
4255            canvas.restore();
4256        }
4257    }
4258
4259    /**
4260     *  Open the tab picker. This function will always use the current tab in
4261     *  its animation.
4262     *  @param stay boolean stating whether the tab picker is to remain open
4263     *          (in which case it needs a listener and its menu) or not.
4264     *  @param index The index of the tab to show as the selection in the tab
4265     *               overview.
4266     *  @param remove If true, the tab at index will be removed after the
4267     *                animation completes.
4268     */
4269    private void tabPicker(final boolean stay, final int index,
4270            final boolean remove) {
4271        if (mTabOverview != null) {
4272            return;
4273        }
4274
4275        int size = mTabControl.getTabCount();
4276
4277        TabListener l = null;
4278        if (stay) {
4279            l = mTabListener = new TabListener();
4280        }
4281        mTabOverview = new ImageGrid(this, stay, l);
4282
4283        for (int i = 0; i < size; i++) {
4284            final TabControl.Tab t = mTabControl.getTab(i);
4285            mTabControl.populatePickerData(t);
4286            mTabOverview.add(t);
4287        }
4288
4289        // Tell the tab overview to show the current tab, the tab overview will
4290        // handle the "New Tab" case.
4291        int currentIndex = mTabControl.getCurrentIndex();
4292        mTabOverview.setCurrentIndex(currentIndex);
4293
4294        // Attach the tab overview.
4295        mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4296
4297        // Create a fake AnimatingView to animate the WebView's picture.
4298        final TabControl.Tab current = mTabControl.getCurrentTab();
4299        final AnimatingView v = new AnimatingView(this, current);
4300        mContentView.addView(v, COVER_SCREEN_PARAMS);
4301        removeTabFromContentView(current);
4302        // Pause timers to get the animation smoother.
4303        current.getWebView().pauseTimers();
4304
4305        // Send a message so the tab picker has a chance to layout and get
4306        // positions for all the cells.
4307        mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4308                index, remove ? 1 : 0, v));
4309        // Setting this will indicate that we are animating to the overview. We
4310        // set it here to prevent another request to animate from coming in
4311        // between now and when ANIMATE_TO_OVERVIEW is handled.
4312        mAnimationCount++;
4313        // Always change the title bar to the window overview title while
4314        // animating.
4315        getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4316        getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4317        getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4318                Window.PROGRESS_VISIBILITY_OFF);
4319        setTitle(R.string.tab_picker_title);
4320        // Make the menu empty until the animation completes.
4321        mMenuState = EMPTY_MENU;
4322    }
4323
4324    private void bookmarksOrHistoryPicker(boolean startWithHistory) {
4325        WebView current = mTabControl.getCurrentWebView();
4326        if (current == null) {
4327            return;
4328        }
4329        Intent intent = new Intent(this,
4330                CombinedBookmarkHistoryActivity.class);
4331        String title = current.getTitle();
4332        String url = current.getUrl();
4333        // Just in case the user opens bookmarks before a page finishes loading
4334        // so the current history item, and therefore the page, is null.
4335        if (null == url) {
4336            url = mLastEnteredUrl;
4337            // This can happen.
4338            if (null == url) {
4339                url = mSettings.getHomePage();
4340            }
4341        }
4342        // In case the web page has not yet received its associated title.
4343        if (title == null) {
4344            title = url;
4345        }
4346        intent.putExtra("title", title);
4347        intent.putExtra("url", url);
4348        intent.putExtra("maxTabsOpen",
4349                mTabControl.getTabCount() >= TabControl.MAX_TABS);
4350        if (startWithHistory) {
4351            intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4352                    CombinedBookmarkHistoryActivity.HISTORY_TAB);
4353        }
4354        startActivityForResult(intent, COMBO_PAGE);
4355    }
4356
4357    // Called when loading from context menu or LOAD_URL message
4358    private void loadURL(WebView view, String url) {
4359        // In case the user enters nothing.
4360        if (url != null && url.length() != 0 && view != null) {
4361            url = smartUrlFilter(url);
4362            if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4363                view.loadUrl(url);
4364            }
4365        }
4366    }
4367
4368    private void checkMemory() {
4369        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4370        ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4371                .getMemoryInfo(mi);
4372        // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4373        // mi.threshold) for now
4374        //        if (mi.lowMemory) {
4375        if (mi.availMem < mi.threshold) {
4376            Log.w(LOGTAG, "Browser is freeing memory now because: available="
4377                            + (mi.availMem / 1024) + "K threshold="
4378                            + (mi.threshold / 1024) + "K");
4379            mTabControl.freeMemory();
4380        }
4381    }
4382
4383    private String smartUrlFilter(Uri inUri) {
4384        if (inUri != null) {
4385            return smartUrlFilter(inUri.toString());
4386        }
4387        return null;
4388    }
4389
4390
4391    // get window count
4392
4393    int getWindowCount(){
4394      if(mTabControl != null){
4395        return mTabControl.getTabCount();
4396      }
4397      return 0;
4398    }
4399
4400    protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4401            "(?i)" + // switch on case insensitive matching
4402            "(" +    // begin group for schema
4403            "(?:http|https|file):\\/\\/" +
4404            "|(?:data|about|content|javascript):" +
4405            ")" +
4406            "(.*)" );
4407
4408    /**
4409     * Attempts to determine whether user input is a URL or search
4410     * terms.  Anything with a space is passed to search.
4411     *
4412     * Converts to lowercase any mistakenly uppercased schema (i.e.,
4413     * "Http://" converts to "http://"
4414     *
4415     * @return Original or modified URL
4416     *
4417     */
4418    String smartUrlFilter(String url) {
4419
4420        String inUrl = url.trim();
4421        boolean hasSpace = inUrl.indexOf(' ') != -1;
4422
4423        Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4424        if (matcher.matches()) {
4425            if (hasSpace) {
4426                inUrl = inUrl.replace(" ", "%20");
4427            }
4428            // force scheme to lowercase
4429            String scheme = matcher.group(1);
4430            String lcScheme = scheme.toLowerCase();
4431            if (!lcScheme.equals(scheme)) {
4432                return lcScheme + matcher.group(2);
4433            }
4434            return inUrl;
4435        }
4436        if (hasSpace) {
4437            // FIXME: quick search, need to be customized by setting
4438            if (inUrl.length() > 2 && inUrl.charAt(1) == ' ') {
4439                // FIXME: Is this the correct place to add to searches?
4440                // what if someone else calls this function?
4441                char char0 = inUrl.charAt(0);
4442
4443                if (char0 == 'g') {
4444                    Browser.addSearchUrl(mResolver, inUrl);
4445                    return composeSearchUrl(inUrl.substring(2));
4446
4447                } else if (char0 == 'w') {
4448                    Browser.addSearchUrl(mResolver, inUrl);
4449                    return URLUtil.composeSearchUrl(inUrl.substring(2),
4450                            QuickSearch_W,
4451                            QUERY_PLACE_HOLDER);
4452
4453                } else if (char0 == 'd') {
4454                    Browser.addSearchUrl(mResolver, inUrl);
4455                    return URLUtil.composeSearchUrl(inUrl.substring(2),
4456                            QuickSearch_D,
4457                            QUERY_PLACE_HOLDER);
4458
4459                } else if (char0 == 'l') {
4460                    Browser.addSearchUrl(mResolver, inUrl);
4461                    // FIXME: we need location in this case
4462                    return URLUtil.composeSearchUrl(inUrl.substring(2),
4463                            QuickSearch_L,
4464                            QUERY_PLACE_HOLDER);
4465                }
4466            }
4467        } else {
4468            if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4469                return URLUtil.guessUrl(inUrl);
4470            }
4471        }
4472
4473        Browser.addSearchUrl(mResolver, inUrl);
4474        return composeSearchUrl(inUrl);
4475    }
4476
4477    /* package */ String composeSearchUrl(String search) {
4478        return URLUtil.composeSearchUrl(search, QuickSearch_G,
4479                QUERY_PLACE_HOLDER);
4480    }
4481
4482    /* package */void setBaseSearchUrl(String url) {
4483        if (url == null || url.length() == 0) {
4484            /*
4485             * get the google search url based on the SIM. Default is US. NOTE:
4486             * This code uses resources to optionally select the search Uri,
4487             * based on the MCC value from the SIM. The default string will most
4488             * likely be fine. It is parameterized to accept info from the
4489             * Locale, the language code is the first parameter (%1$s) and the
4490             * country code is the second (%2$s). This code must function in the
4491             * same way as a similar lookup in
4492             * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4493             * change either of these functions, change them both. (The same is
4494             * true for the underlying resource strings, which are stored in
4495             * mcc-specific xml files.)
4496             */
4497            Locale l = Locale.getDefault();
4498            QuickSearch_G = getResources().getString(
4499                    R.string.google_search_base, l.getLanguage(),
4500                    l.getCountry().toLowerCase())
4501                    + "client=ms-"
4502                    + Partner.getString(this.getContentResolver(), Partner.CLIENT_ID)
4503                    + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4504        } else {
4505            QuickSearch_G = url;
4506        }
4507    }
4508
4509    private final static int LOCK_ICON_UNSECURE = 0;
4510    private final static int LOCK_ICON_SECURE   = 1;
4511    private final static int LOCK_ICON_MIXED    = 2;
4512
4513    private int mLockIconType = LOCK_ICON_UNSECURE;
4514    private int mPrevLockType = LOCK_ICON_UNSECURE;
4515
4516    private BrowserSettings mSettings;
4517    private TabControl      mTabControl;
4518    private ContentResolver mResolver;
4519    private FrameLayout     mContentView;
4520    private ImageGrid       mTabOverview;
4521
4522    // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4523    // view, we should rewrite this.
4524    private int mCurrentMenuState = 0;
4525    private int mMenuState = R.id.MAIN_MENU;
4526    private static final int EMPTY_MENU = -1;
4527    private Menu mMenu;
4528
4529    private FindDialog mFindDialog;
4530    // Used to prevent chording to result in firing two shortcuts immediately
4531    // one after another.  Fixes bug 1211714.
4532    boolean mCanChord;
4533
4534    private boolean mInLoad;
4535    private boolean mIsNetworkUp;
4536
4537    private boolean mPageStarted;
4538    private boolean mActivityInPause = true;
4539
4540    private boolean mMenuIsDown;
4541
4542    private final KeyTracker mKeyTracker = new KeyTracker(this);
4543
4544    // As trackball doesn't send repeat down, we have to track it ourselves
4545    private boolean mTrackTrackball;
4546
4547    private static boolean mInTrace;
4548
4549    // Performance probe
4550    private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4551            Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4552            Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4553            Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4554            Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4555            Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4556            Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4557            Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4558            Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG  // 7: softirq time
4559    };
4560
4561    private long mStart;
4562    private long mProcessStart;
4563    private long mUserStart;
4564    private long mSystemStart;
4565    private long mIdleStart;
4566    private long mIrqStart;
4567
4568    private long mUiStart;
4569
4570    private Drawable    mMixLockIcon;
4571    private Drawable    mSecLockIcon;
4572    private Drawable    mGenericFavicon;
4573
4574    /* hold a ref so we can auto-cancel if necessary */
4575    private AlertDialog mAlertDialog;
4576
4577    // Wait for credentials before loading google.com
4578    private ProgressDialog mCredsDlg;
4579
4580    // The up-to-date URL and title (these can be different from those stored
4581    // in WebView, since it takes some time for the information in WebView to
4582    // get updated)
4583    private String mUrl;
4584    private String mTitle;
4585
4586    // As PageInfo has different style for landscape / portrait, we have
4587    // to re-open it when configuration changed
4588    private AlertDialog mPageInfoDialog;
4589    private TabControl.Tab mPageInfoView;
4590    // If the Page-Info dialog is launched from the SSL-certificate-on-error
4591    // dialog, we should not just dismiss it, but should get back to the
4592    // SSL-certificate-on-error dialog. This flag is used to store this state
4593    private Boolean mPageInfoFromShowSSLCertificateOnError;
4594
4595    // as SSLCertificateOnError has different style for landscape / portrait,
4596    // we have to re-open it when configuration changed
4597    private AlertDialog mSSLCertificateOnErrorDialog;
4598    private WebView mSSLCertificateOnErrorView;
4599    private SslErrorHandler mSSLCertificateOnErrorHandler;
4600    private SslError mSSLCertificateOnErrorError;
4601
4602    // as SSLCertificate has different style for landscape / portrait, we
4603    // have to re-open it when configuration changed
4604    private AlertDialog mSSLCertificateDialog;
4605    private TabControl.Tab mSSLCertificateView;
4606
4607    // as HttpAuthentication has different style for landscape / portrait, we
4608    // have to re-open it when configuration changed
4609    private AlertDialog mHttpAuthenticationDialog;
4610    private HttpAuthHandler mHttpAuthHandler;
4611
4612    /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4613                                            new FrameLayout.LayoutParams(
4614                                            ViewGroup.LayoutParams.FILL_PARENT,
4615                                            ViewGroup.LayoutParams.FILL_PARENT);
4616    // We may provide UI to customize these
4617    // Google search from the browser
4618    static String QuickSearch_G;
4619    // Wikipedia search
4620    final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4621    // Dictionary search
4622    final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4623    // Google Mobile Local search
4624    final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4625
4626    final static String QUERY_PLACE_HOLDER = "%s";
4627
4628    // "source" parameter for Google search through search key
4629    final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4630    // "source" parameter for Google search through goto menu
4631    final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4632    // "source" parameter for Google search through simplily type
4633    final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4634    // "source" parameter for Google search suggested by the browser
4635    final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4636    // "source" parameter for Google search from unknown source
4637    final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4638
4639    private final static String LOGTAG = "browser";
4640
4641    private TabListener mTabListener;
4642
4643    private String mLastEnteredUrl;
4644
4645    private PowerManager.WakeLock mWakeLock;
4646    private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4647
4648    private Toast mStopToast;
4649
4650    // Used during animations to prevent other animations from being triggered.
4651    // A count is used since the animation to and from the Window overview can
4652    // overlap. A count of 0 means no animation where a count of > 0 means
4653    // there are animations in progress.
4654    private int mAnimationCount;
4655
4656    // As the ids are dynamically created, we can't guarantee that they will
4657    // be in sequence, so this static array maps ids to a window number.
4658    final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4659    { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4660      R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4661      R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4662
4663    // monitor platform changes
4664    private IntentFilter mNetworkStateChangedFilter;
4665    private BroadcastReceiver mNetworkStateIntentReceiver;
4666
4667    // activity requestCode
4668    final static int COMBO_PAGE             = 1;
4669    final static int DOWNLOAD_PAGE          = 2;
4670    final static int PREFERENCES_PAGE       = 3;
4671
4672    // the frenquency of checking whether system memory is low
4673    final static int CHECK_MEMORY_INTERVAL = 30000;     // 30 seconds
4674}
4675