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