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