OSDN Git Service

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