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