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