2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.browser;
19 import com.google.android.googleapps.IGoogleLoginService;
20 import com.google.android.googlelogin.GoogleLoginServiceConstants;
21 import com.google.android.providers.GoogleSettings.Partner;
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;
132 import java.io.BufferedOutputStream;
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;
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;
154 public class BrowserActivity extends Activity
155 implements KeyTracker.OnKeyTracker,
156 View.OnCreateContextMenuListener,
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".
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;
166 private IGoogleLoginService mGls = null;
167 private ServiceConnection mGlsConnection = null;
169 private SensorManager mSensorManager = null;
171 private WebStorage.QuotaUpdater mWebStorageQuotaUpdater = null;
173 /* Whitelisted webpages
174 private static HashSet<String> sWhiteList;
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");
190 private void setupHomePage() {
191 final Runnable getAccount = new Runnable() {
194 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
195 // get the default home page
196 String homepage = mSettings.getHomePage();
199 if (mGls == null) return;
201 if (!homepage.startsWith("http://www.google.")) return;
202 if (homepage.indexOf('?') == -1) return;
204 String hostedUser = mGls.getAccount(GoogleLoginServiceConstants.PREFER_HOSTED);
205 String googleUser = mGls.getAccount(GoogleLoginServiceConstants.REQUIRE_GOOGLE);
209 // hostedUser == googleUser
210 // The device has only a google account
212 // hostedUser != googleUser
213 // The device has a hosted account and a google account
215 // hostedUser != null, googleUser == null
216 // The device has only a hosted account (so far)
218 // developers might have no accounts at all
219 if (hostedUser == null) return;
221 if (googleUser == null || !hostedUser.equals(googleUser)) {
222 String domain = hostedUser.substring(hostedUser.lastIndexOf('@')+1);
223 homepage = homepage.replace("?", "/a/" + domain + "?");
225 } catch (RemoteException ignore) {
226 // Login service died; carry on
227 } catch (RuntimeException ignore) {
228 // Login service died; carry on
234 private void finish(final String homepage) {
235 mHandler.post(new Runnable() {
237 mSettings.setHomePage(BrowserActivity.this, homepage);
238 resumeAfterCredentials();
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;
251 final boolean[] done = { false };
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) {
261 Thread account = new Thread(getAccount);
262 account.setName("GLSAccount");
266 public void onServiceDisconnected(ComponentName className) {
271 bindService(GoogleLoginServiceConstants.SERVICE_INTENT,
272 mGlsConnection, Context.BIND_AUTO_CREATE);
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.
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/"
291 final int BUFSIZE = 4096;
292 boolean mDoOverwrite = false;
296 AssetManager manager;
298 public CopyPlugins (boolean overwrite, Context context) {
299 mDoOverwrite = overwrite;
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
309 * @param zip the zip file used.
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)) {
324 * Utility method to copy the content from an inputstream
325 * to a file output stream.
327 public void copyStreams(InputStream is, FileOutputStream fos) {
328 BufferedOutputStream os = null;
330 byte data[] = new byte[BUFSIZE];
332 os = new BufferedOutputStream(fos, BUFSIZE);
333 while ((count = is.read(data, 0, BUFSIZE)) != -1) {
334 os.write(data, 0, count);
337 } catch (IOException e) {
338 Log.e(TAG, "Exception while copying: " + e);
344 } catch (IOException e2) {
345 Log.e(TAG, "Exception while closing the stream: " + e2);
351 * Returns a string containing the contents of a file
353 * @param file the target file
355 private String contentsOfFile(File file) {
357 FileInputStream is = null;
359 byte[] buffer = new byte[BUFSIZE];
361 is = new FileInputStream(file);
362 StringBuffer out = new StringBuffer();
364 while ((count = is.read(buffer, 0, BUFSIZE)) != -1) {
365 out.append(new String(buffer, 0, count));
367 ret = out.toString();
368 } catch (IOException e) {
369 Log.e(TAG, "Exception getting contents of file " + e);
374 } catch (IOException e2) {
375 Log.e(TAG, "Exception while closing the file: " + e2);
383 * Utility method to initialize the user data plugins path.
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();
393 Log.v(TAG, "Plugin path: " + pluginsPath);
398 * Utility method to delete a file or a directory
400 * @param file the File to delete
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]);
409 if (!file.delete()) {
410 Log.e(TAG, file.getPath() + " could not get deleted");
415 * Clean the content of the plugins directory.
416 * We delete the directory, then recreate it.
418 public void cleanPluginsDirectory() {
420 Log.v(TAG, "delete plugins directory: " + pluginsPath);
422 File pluginsDirectory = new File(pluginsPath);
423 deleteFile(pluginsDirectory);
424 pluginsDirectory.mkdir();
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.
433 public void copyBuildInfos() {
436 Log.v(TAG, "Copy build infos to the plugins directory");
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);
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.
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.
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
462 public boolean newSystemImage() {
464 File buildInfoFile = new File(SYSTEM_BUILD_INFOS_FILE);
465 File buildInfoPlugins = new File(pluginsPath, BUILD_INFOS_FILE);
466 if (!buildInfoPlugins.exists()) {
468 Log.v(TAG, "build.prop in plugins directory " + pluginsPath
469 + " does not exist, therefore it's a new system image");
473 String buildInfo = contentsOfFile(buildInfoFile);
474 String buildInfoPlugin = contentsOfFile(buildInfoPlugins);
475 if (buildInfo == null || buildInfoPlugin == null
476 || buildInfo.compareTo(buildInfoPlugin) != 0) {
478 Log.v(TAG, "build.prop are different, "
479 + " therefore it's a new system image");
484 } catch (Exception e) {
485 Log.e(TAG, "Exc in newSystemImage(): " + e);
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.
498 private boolean checkIsDifferentVersions() {
500 ZipFile zip = new ZipFile(APK_PATH);
501 Vector<ZipEntry> files = pluginsFilesFromZip(zip);
502 int zipFilterLength = ZIP_FILTER.length();
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()) {
511 Log.v(TAG, "checkIsDifferentVersions(): extracted file "
512 + path + " does not exist, we have a different version");
517 } catch (IOException e) {
518 Log.e(TAG, "Exception in checkDifferentVersions(): " + e);
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.
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)
534 // Lower the priority
535 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
537 if (pluginsPath == null) {
538 Log.e(TAG, "No plugins path found!");
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();
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();
554 if (outputFile.exists() && !mDoOverwrite) {
556 Log.v(TAG, path + " already extracted.");
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);
566 FileOutputStream fos = new FileOutputStream(outputFile);
568 Log.v(TAG, "copy " + entry + " to "
569 + pluginsPath + "/" + path);
571 copyStreams(zip.getInputStream(entry), fos);
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);
583 Log.v(TAG, "rename " + sourceFile.getPath()
584 + " to " + renamedFile.getPath());
586 sourceFile.renameTo(renamedFile);
590 } catch (IOException e) {
591 Log.e(TAG, "IO Exception: " + e);
597 * Copy the content of assets/plugins/ to the app_plugins directory
598 * in the data partition.
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.
608 * @param overwrite if true overwrite the files even if they are
609 * already present (to let the user "reset" the plugins if needed).
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");
624 private class ClearThumbnails extends AsyncTask<File, Void, Void> {
626 public Void doInBackground(File... files) {
628 for (File f : files) {
636 @Override public void onCreate(Bundle icicle) {
638 Log.v(LOGTAG, this + " onStart");
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);
646 // test the browser in OpenGL
647 // requestWindowFeature(Window.FEATURE_OPENGL);
649 setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
651 mResolver = getContentResolver();
653 setBaseSearchUrl(PreferenceManager.getDefaultSharedPreferences(this)
654 .getString("search_url", ""));
657 // start MASF proxy service
659 //Intent proxyServiceIntent = new Intent();
660 //proxyServiceIntent.setComponent
661 // (new ComponentName(
662 // "com.android.masfproxyservice",
663 // "com.android.masfproxyservice.MasfProxyService"));
664 //startService(proxyServiceIntent, null);
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);
673 mContentView = (FrameLayout) getWindow().getDecorView().findViewById(
674 com.android.internal.R.id.content);
676 // Create the tab control and our initial tab
677 mTabControl = new TabControl(this);
679 // Open the icon database and retain all the bookmark urls for favicons
680 retainIconsOnStartup();
682 // Keep a settings instance handy.
683 mSettings = BrowserSettings.getInstance();
684 mSettings.setTabControl(mTabControl);
685 mSettings.loadFromDb(this);
687 PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
688 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Browser");
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();
712 int scale = extra.getInt(Browser.INITIAL_ZOOM_LEVEL, 0);
713 if (scale > 0 && scale <= 1000) {
714 webView.setInitialScale(scale);
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()) {
727 if (url == null || url.length() == 0) {
728 if (mSettings.isLoginInitialized()) {
729 webView.loadUrl(mSettings.getHomePage());
731 waitForCredentials();
734 byte[] postData = getLocationData(intent);
735 if (postData != null) {
736 webView.postUrl(url, postData);
738 webView.loadUrl(url);
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());
748 /* enables registration for changes in network status from
750 mNetworkStateChangedFilter = new IntentFilter();
751 mNetworkStateChangedFilter.addAction(
752 ConnectivityManager.CONNECTIVITY_ACTION);
753 mNetworkStateIntentReceiver = new BroadcastReceiver() {
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);
765 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
766 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
767 filter.addDataScheme("package");
768 mPackageInstallationReceiver = new BroadcastReceiver() {
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
780 PackageManager pm = BrowserActivity.this.getPackageManager();
781 PackageInfo pkgInfo = null;
783 pkgInfo = pm.getPackageInfo(packageName,
784 PackageManager.GET_PERMISSIONS);
785 } catch (PackageManager.NameNotFoundException e) {
788 if (pkgInfo != null) {
789 String permissions[] = pkgInfo.requestedPermissions;
790 if (permissions == null) {
793 boolean permissionOk = false;
794 for (String permit : permissions) {
795 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
801 PluginManager.getInstance(BrowserActivity.this)
803 Intent.ACTION_PACKAGE_ADDED
809 registerReceiver(mPackageInstallationReceiver, filter);
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.
824 mTabControl.setCurrentTab(current);
825 attachTabToContentView(current);
826 resetTitleAndIcon(current.getWebView());
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
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();
843 if (Intent.ACTION_VIEW.equals(action) &&
844 (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
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.
859 mTabControl.recreateWebView(appTab, url);
860 if (current != appTab) {
861 showTab(appTab, needsLoad ? url : null);
863 if (mTabOverview != null && mAnimationCount == 0) {
864 sendAnimateFromOverview(appTab, false,
865 needsLoad ? url : null, null,
866 TAB_OVERVIEW_DELAY, null);
868 // If the tab was the current tab, we have to attach
869 // it to the view system again.
870 attachTabToContentView(appTab);
872 appTab.getWebView().loadUrl(url);
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);
884 if ("about:debug".equals(url)) {
885 mSettings.toggleDebugSettings();
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);
895 // Get rid of the subwindow if it exists
896 dismissSubWindow(current);
897 if (postData != null) {
898 current.getWebView().postUrl(url, postData);
900 current.getWebView().loadUrl(url);
907 private String getUrlFromIntent(Intent intent) {
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;
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);
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);
931 // In general, we shouldn't modify URL from Intent.
932 // But currently, we get the user-typed URL from search box as well.
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);
942 if (TextUtils.isEmpty(source)) {
943 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
945 url = url.replace(searchSource, "&source=android-"+source+"&");
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();
978 /* package */ static String fixUrl(String inUrl) {
979 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
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(":", "://");
991 * Looking for the pattern like this
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];
1007 public void onSensorChanged(int sensor, float[] values) {
1008 boolean show = false;
1009 float[] diff = new float[3];
1011 for (int i = 0; i < 3; i++) {
1012 diff[i] = values[i] - mPrev[i];
1013 if (Math.abs(diff[i]) > 1) {
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];
1021 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
1022 // reset when it is flat
1023 mDiff[i] = mRevertDiff[i] = 0;
1025 mDiff[i] += diff[i];
1026 mPrevDiff[i] = diff[i];
1027 mPrev[i] = values[i];
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]
1037 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
1038 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
1039 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
1040 + mRevertDiff[2] + ")");
1043 long now = android.os.SystemClock.uptimeMillis();
1044 if (now - mLastGestureTime > 1000) {
1045 mLastGestureTime = 0;
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;
1058 if ((gestY || gestZ) && !(gestY && gestZ)) {
1059 WebView view = mTabControl.getCurrentWebView();
1069 view.flingScroll(0, Math.round(y * 100));
1072 mLastGestureTime = now;
1077 public void onAccuracyChanged(int sensor, int accuracy) {
1078 // TODO Auto-generated method stub
1083 @Override protected void onResume() {
1086 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
1089 if (!mActivityInPause) {
1090 Log.e(LOGTAG, "BrowserActivity is already resumed.");
1094 mTabControl.resumeCurrentTab();
1095 mActivityInPause = false;
1096 resumeWebViewTimers();
1098 if (mWakeLock.isHeld()) {
1099 mHandler.removeMessages(RELEASE_WAKELOCK);
1100 mWakeLock.release();
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);
1110 registerReceiver(mNetworkStateIntentReceiver,
1111 mNetworkStateChangedFilter);
1112 WebView.enablePlatformNotifications();
1114 if (mSettings.doFlick()) {
1115 if (mSensorManager == null) {
1116 mSensorManager = (SensorManager) getSystemService(
1117 Context.SENSOR_SERVICE);
1119 mSensorManager.registerListener(mSensorListener,
1120 SensorManager.SENSOR_ACCELEROMETER,
1121 SensorManager.SENSOR_DELAY_FASTEST);
1123 mSensorManager = null;
1128 * onSaveInstanceState(Bundle map)
1129 * onSaveInstanceState is called right before onStop(). The map contains
1132 @Override protected void onSaveInstanceState(Bundle outState) {
1134 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
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".
1142 // Save all the tabs
1143 mTabControl.saveState(outState);
1146 @Override protected void onPause() {
1149 if (mActivityInPause) {
1150 Log.e(LOGTAG, "BrowserActivity is already paused.");
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);
1162 // Clear the credentials toast if it is up
1163 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1164 mCredsDlg.dismiss();
1170 // unregister network state listener
1171 unregisterReceiver(mNetworkStateIntentReceiver);
1172 WebView.disablePlatformNotifications();
1174 if (mSensorManager != null) {
1175 mSensorManager.unregisterListener(mSensorListener);
1179 @Override protected void onDestroy() {
1181 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1184 // Remove the current tab and sub window
1185 TabControl.Tab t = mTabControl.getCurrentTab();
1187 dismissSubWindow(t);
1188 removeTabFromContentView(t);
1190 // Destroy all the tabs
1191 mTabControl.destroy();
1192 WebIconDatabase.getInstance().close();
1193 if (mGlsConnection != null) {
1194 unbindService(mGlsConnection);
1195 mGlsConnection = null;
1199 // stop MASF proxy service
1201 //Intent proxyServiceIntent = new Intent();
1202 //proxyServiceIntent.setComponent
1203 // (new ComponentName(
1204 // "com.android.masfproxyservice",
1205 // "com.android.masfproxyservice.MasfProxyService"));
1206 //stopService(proxyServiceIntent);
1208 unregisterReceiver(mPackageInstallationReceiver);
1212 public void onConfigurationChanged(Configuration newConfig) {
1213 super.onConfigurationChanged(newConfig);
1215 if (mPageInfoDialog != null) {
1216 mPageInfoDialog.dismiss();
1219 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1221 if (mSSLCertificateDialog != null) {
1222 mSSLCertificateDialog.dismiss();
1224 mSSLCertificateView);
1226 if (mSSLCertificateOnErrorDialog != null) {
1227 mSSLCertificateOnErrorDialog.dismiss();
1228 showSSLCertificateOnError(
1229 mSSLCertificateOnErrorView,
1230 mSSLCertificateOnErrorHandler,
1231 mSSLCertificateOnErrorError);
1233 if (mHttpAuthenticationDialog != null) {
1234 String title = ((TextView) mHttpAuthenticationDialog
1235 .findViewById(com.android.internal.R.id.alertTitle)).getText()
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()
1243 mHttpAuthenticationDialog.dismiss();
1244 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1245 name, password, focusId);
1247 if (mFindDialog != null && mFindDialog.isShowing()) {
1248 mFindDialog.onConfigurationChanged(newConfig);
1252 @Override public void onLowMemory() {
1253 super.onLowMemory();
1254 mTabControl.freeMemory();
1257 private boolean resumeWebViewTimers() {
1258 if ((!mActivityInPause && !mPageStarted) ||
1259 (mActivityInPause && mPageStarted)) {
1260 CookieSyncManager.getInstance().startSync();
1261 WebView w = mTabControl.getCurrentWebView();
1271 private boolean pauseWebViewTimers() {
1272 if (mActivityInPause && !mPageStarted) {
1273 CookieSyncManager.getInstance().stopSync();
1274 WebView w = mTabControl.getCurrentWebView();
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.
1289 private void waitForCredentials() {
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));
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.
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.
1308 private void resumeAfterCredentials() {
1309 if (mCredsDlg == null) {
1314 if (mCredsDlg.isShowing()) {
1315 mCredsDlg.dismiss();
1319 // Clear any pending timeout
1320 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1323 WebView w = mTabControl.getCurrentWebView();
1325 w.loadUrl(mSettings.getHomePage());
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
1331 mSettings.setLoginInitialized(this);
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());
1339 Cursor c = Browser.getAllBookmarks(mResolver);
1340 if (!c.moveToFirst()) {
1344 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1346 String url = c.getString(urlIndex);
1347 db.retainIconForPageUrl(url);
1348 } while (c.moveToNext());
1350 } catch (IllegalStateException e) {
1351 Log.e(LOGTAG, "retainIconsOnStartup", e);
1355 // Helper method for getting the top window.
1356 WebView getTopWindow() {
1357 return mTabControl.getCurrentTopWebView();
1361 public boolean onCreateOptionsMenu(Menu menu) {
1362 super.onCreateOptionsMenu(menu);
1364 MenuInflater inflater = getMenuInflater();
1365 inflater.inflate(R.menu.browser, menu);
1367 updateInLoadMenuItems();
1372 * As the menu can be open when loading state changes
1373 * we must manually update the state of the stop/reload menu
1376 private void updateInLoadMenuItems() {
1377 if (mMenu == null) {
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());
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.
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);
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);
1411 // For other context menus
1412 return onOptionsItemSelected(item);
1418 private Bundle createGoogleSearchSourceBundle(String source) {
1419 Bundle bundle = new Bundle();
1420 bundle.putString(SearchManager.SOURCE, source);
1425 * Overriding this to insert a local information bundle
1428 public boolean onSearchRequested() {
1429 startSearch(null, false,
1430 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
1435 public void startSearch(String initialQuery, boolean selectInitialQuery,
1436 Bundle appSearchData, boolean globalSearch) {
1437 if (appSearchData == null) {
1438 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1440 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1444 public boolean onOptionsItemSelected(MenuItem item) {
1446 // The user has already fired a shortcut with this hold down of the
1450 switch (item.getItemId()) {
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);
1459 case R.id.bookmarks_menu_id:
1460 bookmarksOrHistoryPicker(false);
1463 case R.id.windows_menu_id:
1464 if (mTabControl.getTabCount() == 1) {
1465 openTabAndShow(mSettings.getHomePage(), null, false, null);
1467 tabPicker(true, mTabControl.getCurrentIndex(), false);
1471 case R.id.stop_reload_menu_id:
1475 getTopWindow().reload();
1479 case R.id.back_menu_id:
1480 getTopWindow().goBack();
1483 case R.id.forward_menu_id:
1484 getTopWindow().goForward();
1487 case R.id.close_menu_id:
1488 // Close the subwindow if it exists.
1489 if (mTabControl.getCurrentSubWindow() != null) {
1490 dismissSubWindow(mTabControl.getCurrentTab());
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);
1500 // Get the last tab in the list. If it is the current tab,
1502 indexToShow = mTabControl.getTabCount() - 1;
1503 if (currentIndex == indexToShow) {
1507 switchTabs(currentIndex, indexToShow, true);
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());
1518 case R.id.preferences_menu_id:
1519 Intent intent = new Intent(this,
1520 BrowserPreferencesPage.class);
1521 startActivityForResult(intent, PREFERENCES_PAGE);
1524 case R.id.find_menu_id:
1525 if (null == mFindDialog) {
1526 mFindDialog = new FindDialog(this);
1528 mFindDialog.setWebView(getTopWindow());
1530 mMenuState = EMPTY_MENU;
1533 case R.id.select_text_id:
1534 getTopWindow().emulateShiftHeld();
1536 case R.id.page_info_menu_id:
1537 showPageInfo(mTabControl.getCurrentTab(), false);
1540 case R.id.classic_history_menu_id:
1541 bookmarksOrHistoryPicker(true);
1544 case R.id.share_page_menu_id:
1545 Browser.sendString(this, getTopWindow().getUrl());
1548 case R.id.dump_nav_menu_id:
1549 getTopWindow().debugDump();
1552 case R.id.zoom_in_menu_id:
1553 getTopWindow().zoomIn();
1556 case R.id.zoom_out_menu_id:
1557 getTopWindow().zoomOut();
1560 case R.id.view_downloads_menu_id:
1561 viewDownloads(null);
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);
1573 case R.id.remove_tab_menu_id:
1574 if (mTabListener != null && mTabOverview != null) {
1575 int pos = mTabOverview.getContextMenuPosition(item);
1576 mTabListener.remove(pos);
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);
1589 mTabListener.onClick(ImageGrid.NEW_TAB);
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
1600 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1605 case R.id.history_tab_menu_id:
1606 bookmarksOrHistoryPicker(true);
1609 case R.id.bookmarks_tab_menu_id:
1610 bookmarksOrHistoryPicker(false);
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);
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:
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);
1644 if (!super.onOptionsItemSelected(item)) {
1647 // Otherwise fall through.
1653 public void closeFind() {
1654 mMenuState = R.id.MAIN_MENU;
1657 @Override public boolean onPrepareOptionsMenu(Menu menu)
1659 // This happens when the user begins to hold down the menu key, so
1660 // allow them to chord to get a shortcut.
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) {
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);
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);
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);
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);
1697 final WebView w = getTopWindow();
1698 boolean canGoBack = false;
1699 boolean canGoForward = false;
1700 boolean isHome = false;
1702 canGoBack = w.canGoBack();
1703 canGoForward = w.canGoForward();
1704 isHome = mSettings.getHomePage().equals(w.getUrl());
1706 final MenuItem back = menu.findItem(R.id.back_menu_id);
1707 back.setEnabled(canGoBack);
1709 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1710 home.setEnabled(!isHome);
1712 menu.findItem(R.id.forward_menu_id)
1713 .setEnabled(canGoForward);
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);
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));
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);
1734 mCurrentMenuState = mMenuState;
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) {
1747 int type = result.getType();
1748 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1750 "We should not show context menu when nothing is touched");
1753 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1754 // let TextView handles context menu
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);
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);
1779 // Setup custom handling depending on the 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(
1791 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
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(
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(
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,
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) {
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);
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));
1844 Log.w(LOGTAG, "We should not get here.");
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
1856 // Request focus on the top window.
1857 t.getTopWindow().requestFocus();
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();
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());
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
1891 mTabControl.dismissSubWindow(t);
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);
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
1922 dismissSubWindow(tab);
1923 if (postData != null) {
1924 tab.getWebView().postUrl(url, postData);
1926 tab.getWebView().loadUrl(url);
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.
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;
1942 // 500ms animation with 800ms delay
1943 private static final int TAB_ANIMATION_DURATION = 500;
1944 private static final int TAB_OVERVIEW_DELAY = 800;
1946 // Called by TabControl when a tab is requesting focus
1947 /* package */ void showTab(TabControl.Tab t) {
1951 private void showTab(TabControl.Tab t, String url) {
1952 // Disallow focus change during a tab animation.
1953 if (mAnimationCount > 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);
1963 sendAnimateFromOverview(t, false, url, null, delay, null);
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();
1980 // If the tab overview is up and there are animations, just load
1982 if (mTabOverview != null && mAnimationCount > 0) {
1984 // We should not have a msg here since onCreateWindow
1985 // checks the animation count and every other caller passes
1988 // just dismiss the subwindow and load the given url.
1989 dismissSubWindow(currentTab);
1990 currentTab.getWebView().loadUrl(url);
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);
2001 // Animate from the Tab overview after any animations have
2003 final TabControl.Tab tab = mTabControl.createNewTab(
2004 closeOnExit, appId, url);
2005 sendAnimateFromOverview(tab, true, url, null, delay, msg);
2008 } else if (url != null) {
2009 // We should not have a msg here.
2011 if (mTabOverview != null && mAnimationCount == 0) {
2012 sendAnimateFromOverview(currentTab, false, url, null,
2013 TAB_OVERVIEW_DELAY, null);
2015 // Get rid of the subwindow if it exists
2016 dismissSubWindow(currentTab);
2017 // Load the given url.
2018 currentTab.getWebView().loadUrl(url);
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();
2030 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2031 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2034 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2035 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2038 set.setDuration(TAB_ANIMATION_DURATION);
2039 set.setInterpolator(new DecelerateInterpolator());
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()) {
2056 // Offset the tab position with the first visible position to get a
2057 // number between 0 and 3.
2058 position -= mTabOverview.getFirstVisiblePosition();
2060 // Grab the view that we are going to animate to.
2061 final View v = mTabOverview.getChildAt(position);
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
2069 mTabOverview.setListener(null);
2071 public void onAnimationRepeat(Animation a) {}
2072 public void onAnimationEnd(Animation a) {
2073 // We are no longer animating so decrement the count.
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() {
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();
2096 // If a remove was requested, remove the tab.
2098 // During a remove, the current tab has
2099 // already changed. Remember the current one
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);
2112 if (mTabOverview != null) {
2113 mTabOverview.remove(newIndex);
2114 // Make the current tab visible.
2115 mTabOverview.setCurrentIndex(
2116 mTabControl.getCurrentIndex());
2124 // Do an animation if there is a view to animate to.
2126 // Create our animation
2127 final Animation anim = createTabAnimation(view, v, true);
2128 anim.setAnimationListener(l);
2130 view.startAnimation(anim);
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);
2139 // Animate from the tab picker. The index supplied is the index to animate
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.
2152 // If this is a new tab, animate from the "New Tab" cell.
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;
2161 // Find the view at this location.
2162 final View v = mTabOverview.getChildAt(location);
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() {
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);
2178 mTabControl.getCurrentTab();
2179 mMenuState = R.id.MAIN_MENU;
2180 // Resume regular updates.
2181 t.getWebView().resumeTimers();
2182 // Dispatch the message after the animation
2187 // The animation is done and the tab overview is
2188 // gone so allow key events and other animations
2191 // Reset all the title bar info.
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);
2206 // Go ahead and do all the cleanup.
2207 l.onAnimationEnd(null);
2211 // Dismiss the tab overview applying a fade if needed.
2212 private void dismissTabOverview(final boolean fade) {
2214 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2215 anim.setDuration(500);
2217 mTabOverview.startAnimation(anim);
2219 // Just in case there was a problem with animating away from the tab
2221 WebView current = mTabControl.getCurrentWebView();
2222 if (current != null) {
2223 current.setVisibility(View.VISIBLE);
2225 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2227 // Make the sub window container visible.
2228 if (mTabControl.getCurrentSubWindow() != null) {
2229 mTabControl.getCurrentTab().getSubWebViewContainer()
2230 .setVisibility(View.VISIBLE);
2232 mContentView.removeView(mTabOverview);
2233 // Clear all the data for tab picker so next time it will be
2235 mTabControl.wipeAllPickerData();
2236 mTabOverview.clear();
2237 mTabOverview = null;
2238 mTabListener = null;
2241 private TabControl.Tab openTab(String url) {
2242 if (mSettings.openInBackground()) {
2243 TabControl.Tab t = mTabControl.createNewTab();
2245 t.getWebView().loadUrl(url);
2249 return openTabAndShow(url, null, false, null);
2253 private class Copy implements OnMenuItemClickListener {
2254 private CharSequence mText;
2256 public boolean onMenuItemClick(MenuItem item) {
2261 public Copy(CharSequence toCopy) {
2266 private class Download implements OnMenuItemClickListener {
2267 private String mText;
2269 public boolean onMenuItemClick(MenuItem item) {
2270 onDownloadStartNoStream(mText, null, null, null, -1);
2274 public Download(String toDownload) {
2279 private void copy(CharSequence text) {
2281 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2283 clip.setClipboardText(text);
2285 } catch (android.os.RemoteException e) {
2286 Log.e(LOGTAG, "Copy failed", e);
2291 * Resets the browser title-view to whatever it must be (for example, if we
2292 * load a page from history).
2294 private void resetTitle() {
2296 resetTitleIconAndProgress();
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.
2307 /* package */ void resetTitleAndRevertLockIcon() {
2309 resetTitleIconAndProgress();
2313 * Reset the title, favicon, and progress.
2315 private void resetTitleIconAndProgress() {
2316 WebView current = mTabControl.getCurrentWebView();
2317 if (current == null) {
2320 resetTitleAndIcon(current);
2321 int progress = current.getProgress();
2322 mWebChromeClient.onProgressChanged(current, progress);
2325 // Reset the title and the icon based on the given item.
2326 private void resetTitleAndIcon(WebView view) {
2327 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2329 setUrlTitle(item.getUrl(), item.getTitle());
2330 setFavicon(item.getFavicon());
2332 setUrlTitle(null, null);
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.
2342 private void setUrlTitle(String url, String title) {
2346 // While the tab overview is animating or being shown, block changes
2348 if (mAnimationCount == 0 && mTabOverview == null) {
2349 setTitle(buildUrlTitle(url, title));
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.
2360 private String buildUrlTitle(String url, String title) {
2361 String urlTitle = "";
2364 String titleUrl = buildTitleUrl(url);
2366 if (title != null && 0 < title.length()) {
2367 if (titleUrl != null && 0 < titleUrl.length()) {
2368 urlTitle = titleUrl + ": " + title;
2373 if (titleUrl != null) {
2374 urlTitle = titleUrl;
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.
2390 private static String buildTitleUrl(String url) {
2391 String titleUrl = null;
2395 // parse the url string
2396 URL urlObj = new URL(url);
2397 if (urlObj != null) {
2400 String protocol = urlObj.getProtocol();
2401 String host = urlObj.getHost();
2403 if (host != null && 0 < host.length()) {
2405 if (protocol != null) {
2406 // if a secure site, add an "https://" prefix!
2407 if (protocol.equalsIgnoreCase("https")) {
2408 titleUrl = protocol + "://" + host;
2413 } catch (MalformedURLException e) {}
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
2423 if (mAnimationCount > 0 || mTabOverview != null) {
2426 Drawable[] array = new Drawable[2];
2427 PaintDrawable p = new PaintDrawable(Color.WHITE);
2428 p.setCornerRadius(3f);
2431 array[1] = mGenericFavicon;
2433 array[1] = new BitmapDrawable(icon);
2435 LayerDrawable d = new LayerDrawable(array);
2436 d.setLayerInset(1, 2, 2, 2, 2);
2437 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
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.
2445 private void saveLockIcon() {
2446 mPrevLockType = mLockIconType;
2450 * Reverts the lock-icon state to the last saved state,
2451 * for example, if we had an error, and need to cancel
2454 private void revertLockIcon() {
2455 mLockIconType = mPrevLockType;
2458 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2459 " revert lock icon to " + mLockIconType);
2462 updateLockIconImage(mLockIconType);
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);
2473 sendAnimateFromOverview(tab, false, null, null, delay, null);
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.
2480 // Send a message to open a new tab.
2481 mHandler.sendMessageDelayed(
2482 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2483 mSettings.getHomePage()), delay);
2487 private void goBackOnePageOrQuit() {
2488 TabControl.Tab current = mTabControl.getCurrentTab();
2489 if (current == null) {
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
2497 moveTaskToBack(true);
2499 WebView w = current.getWebView();
2500 if (w.canGoBack()) {
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);
2510 if (current.closeOnExit()) {
2511 if (mTabControl.getTabCount() == 1) {
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);
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
2528 moveTaskToBack(true);
2533 public KeyTracker.State onKeyTracker(int keyCode,
2535 KeyTracker.Stage stage,
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;
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;
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
2558 WebView subwindow = mTabControl.getCurrentSubWindow();
2559 if (subwindow != null) {
2560 if (subwindow.canGoBack()) {
2563 dismissSubWindow(mTabControl.getCurrentTab());
2566 goBackOnePageOrQuit();
2568 return KeyTracker.State.DONE_TRACKING;
2570 return KeyTracker.State.KEEP_TRACKING;
2572 return KeyTracker.State.NOT_TRACKING;
2575 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2576 if (keyCode == KeyEvent.KEYCODE_MENU) {
2579 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2582 case KeyEvent.KEYCODE_SPACE:
2583 if (event.isShiftPressed()) {
2584 getTopWindow().pageUp(false);
2586 getTopWindow().pageDown(false);
2595 return handled || super.onKeyDown(keyCode, event);
2598 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2599 if (keyCode == KeyEvent.KEYCODE_MENU) {
2600 mMenuIsDown = false;
2602 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2605 private void stopLoading() {
2606 resetTitleAndRevertLockIcon();
2607 WebView w = getTopWindow();
2609 mWebViewClient.onPageFinished(w, w.getUrl());
2613 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2617 private void cancelStopToast() {
2618 if (mStopToast != null) {
2619 mStopToast.cancel();
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));
2629 // public message ids
2630 public final static int LOAD_URL = 1001;
2631 public final static int STOP_LOAD = 1002;
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;
2642 // Private handler for handling javascript and saving passwords
2643 private Handler mHandler = new Handler() {
2645 public void handleMessage(Message msg) {
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"));
2653 case ANIMATE_TO_OVERVIEW:
2654 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2655 (AnimatingView) msg.obj);
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
2663 openTabAndShow((String) msg.obj, null, false, null);
2666 case FOCUS_NODE_HREF:
2667 String url = (String) msg.getData().get("url");
2668 if (url == null || url.length() == 0) {
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) {
2678 case R.id.open_context_menu_id:
2679 case R.id.view_image_context_menu_id:
2680 loadURL(getTopWindow(), url);
2682 case R.id.open_newtab_context_menu_id:
2683 final TabControl.Tab parent = mTabControl
2685 final TabControl.Tab newTab = openTab(url);
2686 if (newTab != parent) {
2687 parent.addChildTab(newTab);
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);
2696 case R.id.share_link_context_menu_id:
2697 Browser.sendString(BrowserActivity.this, url);
2699 case R.id.copy_link_context_menu_id:
2702 case R.id.save_link_context_menu_id:
2703 case R.id.download_context_menu_id:
2704 onDownloadStartNoStream(url, null, null, null, -1);
2710 loadURL(getTopWindow(), (String) msg.obj);
2717 case CANCEL_CREDS_REQUEST:
2718 resumeAfterCredentials();
2722 // reschedule to check memory condition
2723 mHandler.removeMessages(CHECK_MEMORY);
2724 mHandler.sendMessageDelayed(mHandler.obtainMessage
2725 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2729 case RELEASE_WAKELOCK:
2730 if (mWakeLock.isHeld()) {
2731 mWakeLock.release();
2738 // -------------------------------------------------------------------------
2739 // WebViewClient implementation.
2740 //-------------------------------------------------------------------------
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;";
2748 /* package */ WebViewClient getWebViewClient() {
2749 return mWebViewClient;
2752 private void updateIcon(String url, Bitmap icon) {
2754 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2760 private final WebViewClient mWebViewClient = new WebViewClient() {
2762 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2764 setUrlTitle(url, null);
2765 // Call updateIcon instead of setFavicon so the bookmark
2766 // database can be updated.
2767 updateIcon(url, favicon);
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;
2777 WebAddress uri = new WebAddress(url);
2779 } catch (android.net.ParseException ex) {
2780 host = "unknown_host";
2782 host = host.replace('.', '_');
2783 baseDir = baseDir + host;
2784 file = new File(baseDir+".data");
2785 if (file.exists() == true) {
2788 file = new File(baseDir+".key");
2789 if (file.exists() == true) {
2793 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2796 // Performance probe
2798 mStart = SystemClock.uptimeMillis();
2799 mProcessStart = Process.getElapsedCpuTime();
2800 long[] sysCpu = new long[7];
2801 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2803 mUserStart = sysCpu[0] + sysCpu[1];
2804 mSystemStart = sysCpu[2];
2805 mIdleStart = sysCpu[3];
2806 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2808 mUiStart = SystemClock.currentThreadTimeMillis();
2811 if (!mPageStarted) {
2812 mPageStarted = true;
2813 // if onResume() has been called, resumeWebViewTimers() does
2815 resumeWebViewTimers();
2818 // reset sync timer to avoid sync starts during loading a page
2819 CookieSyncManager.getInstance().resetSync();
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)
2832 view.setNetworkAvailable(false);
2836 // schedule to check memory condition
2837 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2838 CHECK_MEMORY_INTERVAL);
2842 public void onPageFinished(WebView view, String url) {
2843 // Reset the title and icon in case we stopped a provisional
2845 resetTitleAndIcon(view);
2847 // Update the lock icon image only once we are done loading
2848 updateLockIconImage(mLockIconType);
2850 // Performance probe
2852 long[] sysCpu = new long[7];
2853 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2855 String uiInfo = "UI thread used "
2856 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2859 Log.d(LOGTAG, uiInfo);
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;
2876 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
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);
2891 Log.d(LOGTAG, newUrl + " loaded");
2894 if (sWhiteList.contains(newUrl)) {
2895 // The string that gets pushed to the statistcs
2897 performanceString = performanceString
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();
2919 Checkin.logEvent(mResolver,
2920 Checkin.Events.Tag.WEBPAGE_LOAD,
2922 Log.w(LOGTAG, "pushed to the statistics service");
2931 Debug.stopMethodTracing();
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();
2946 mHandler.removeMessages(CHECK_MEMORY);
2950 // return true if want to hijack the url to let another app to handle it
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);
2963 // wtai://wp/sd;dtmf
2964 // dtmf=string(dialstring)
2965 if (url.startsWith(SCHEME_WTAI_SD)) {
2967 // only send when there is active voice connection
2970 // wtai://wp/ap;number;name
2971 // number=string(phone-number)
2973 if (url.startsWith(SCHEME_WTAI_AP)) {
2981 uri = Uri.parse(url);
2982 } catch (IllegalArgumentException ex) {
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);
2990 if (startActivityIfNeeded(intent, -1)) {
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.
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.
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;
3023 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3024 " updated lock icon to " + mLockIconType + " due to " + url);
3032 * Show the dialog, asking the user if they would like to continue after
3033 * an excessive number of HTTP redirects.
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();
3045 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3046 public void onClick(DialogInterface dialog, int which) {
3047 cancelMsg.sendToTarget();
3049 .setOnCancelListener(new OnCancelListener() {
3050 public void onCancel(DialogInterface dialog) {
3051 cancelMsg.sendToTarget();
3056 // Container class for the next error dialog that needs to be
3059 public final int mTitle;
3060 public final String mDescription;
3061 public final int mError;
3062 ErrorDialog(int title, String desc, int error) {
3064 mDescription = desc;
3069 private void processNextError() {
3070 if (mQueuedErrors == null) {
3073 // The first one is currently displayed so just remove it.
3074 mQueuedErrors.removeFirst();
3075 if (mQueuedErrors.size() == 0) {
3076 mQueuedErrors = null;
3079 showError(mQueuedErrors.getFirst());
3082 private DialogInterface.OnDismissListener mDialogListener =
3083 new DialogInterface.OnDismissListener() {
3084 public void onDismiss(DialogInterface d) {
3088 private LinkedList<ErrorDialog> mQueuedErrors;
3090 private void queueError(int err, String desc) {
3091 if (mQueuedErrors == null) {
3092 mQueuedErrors = new LinkedList<ErrorDialog>();
3094 for (ErrorDialog d : mQueuedErrors) {
3095 if (d.mError == err) {
3096 // Already saw a similar error, ignore the new one.
3100 ErrorDialog errDialog = new ErrorDialog(
3101 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3102 R.string.browserFrameFileErrorLabel :
3103 R.string.browserFrameNetworkErrorLabel,
3105 mQueuedErrors.addLast(errDialog);
3107 // Show the dialog now if the queue was empty.
3108 if (mQueuedErrors.size() == 1) {
3109 showError(errDialog);
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)
3119 d.setOnDismissListener(mDialogListener);
3124 * Show a dialog informing the user of the network error reported by
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);
3137 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3138 + " " + description);
3140 // We need to reset the title after an error.
3141 resetTitleAndRevertLockIcon();
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.
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();
3158 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3159 public void onClick(DialogInterface dialog, int which) {
3160 dontResend.sendToTarget();
3162 .setOnCancelListener(new OnCancelListener() {
3163 public void onCancel(DialogInterface dialog) {
3164 dontResend.sendToTarget();
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.
3176 public void doUpdateVisitedHistory(WebView view, String url,
3178 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3181 Browser.updateVisitedHistory(mResolver, url, true);
3182 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3186 * Displays SSL error(s) dialog to the user.
3189 public void onReceivedSslError(
3190 final WebView view, final SslErrorHandler handler, final SslError error) {
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);
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);
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);
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);
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);
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) {
3242 .setNeutralButton(R.string.view_certificate,
3243 new DialogInterface.OnClickListener() {
3244 public void onClick(DialogInterface dialog, int whichButton) {
3245 showSSLCertificateOnError(view, handler, error);
3248 .setNegativeButton(R.string.cancel,
3249 new DialogInterface.OnClickListener() {
3250 public void onClick(DialogInterface dialog, int whichButton) {
3252 BrowserActivity.this.resetTitleAndRevertLockIcon();
3255 .setOnCancelListener(
3256 new DialogInterface.OnCancelListener() {
3257 public void onCancel(DialogInterface dialog) {
3259 BrowserActivity.this.resetTitleAndRevertLockIcon();
3269 * Handles an HTTP authentication request.
3271 * @param handler The authentication handler
3272 * @param host The host
3273 * @param realm The realm
3276 public void onReceivedHttpAuthRequest(WebView view,
3277 final HttpAuthHandler handler, final String host, final String realm) {
3278 String username = null;
3279 String password = null;
3281 boolean reuseHttpAuthUsernamePassword =
3282 handler.useHttpAuthUsernamePassword();
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];
3295 if (username != null && password != null) {
3296 handler.proceed(username, password);
3298 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3303 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3305 // only check shortcut key when MENU is held
3306 return getWindow().isShortcutKey(event.getKeyCode(), event);
3313 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3314 if (view != mTabControl.getCurrentTopWebView()) {
3317 if (event.isDown()) {
3318 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3320 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3325 //--------------------------------------------------------------------------
3326 // WebChromeClient implementation
3327 //--------------------------------------------------------------------------
3329 /* package */ WebChromeClient getWebChromeClient() {
3330 return mWebChromeClient;
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) {
3337 mTabControl.createSubWindow();
3338 final TabControl.Tab t = mTabControl.getCurrentTab();
3340 WebView.WebViewTransport transport =
3341 (WebView.WebViewTransport) msg.obj;
3342 transport.setWebView(t.getSubWebView());
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,
3351 if (newTab != parent) {
3352 parent.addChildTab(newTab);
3354 WebView.WebViewTransport transport =
3355 (WebView.WebViewTransport) msg.obj;
3356 transport.setWebView(mTabControl.getCurrentWebView());
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) {
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)
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)
3387 // Short-circuit if this was a user gesture.
3389 // createWindow will call openTabAndShow for new Windows and
3390 // that will call tabPicker which will increment
3392 createWindow(dialog, resultMsg);
3396 // Allow the popup and create the appropriate window.
3397 final AlertDialog.OnClickListener allowListener =
3398 new AlertDialog.OnClickListener() {
3399 public void onClick(DialogInterface d,
3401 // Same comment as above for setting
3403 createWindow(dialog, resultMsg);
3404 // Since we incremented mAnimationCount while the
3405 // dialog was up, we have to decrement it here.
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.
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)
3432 // Show the confirmation dialog.
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
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);
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,
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();
3470 updateInLoadMenuItems();
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.
3478 updateInLoadMenuItems();
3484 public void onReceivedTitle(WebView view, String title) {
3485 String url = view.getOriginalUrl();
3487 // here, if url is null, we want to reset the title
3488 setUrlTitle(url, title);
3491 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
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);
3503 String [] selArgs = new String[] { url };
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
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);
3518 } catch (IllegalStateException e) {
3519 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3520 } catch (SQLiteException ex) {
3521 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3526 public void onReceivedIcon(WebView view, Bitmap icon) {
3527 updateIcon(view.getUrl(), icon);
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!
3540 public void onExceededDatabaseQuota(String url,
3541 String databaseIdentifier, long currentQuota,
3542 WebStorage.QuotaUpdater quotaUpdater) {
3545 "BrowserActivity received onExceededDatabaseQuota for "
3548 + databaseIdentifier +
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);
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
3570 * @param mimetype The mimetype of the content reported by the server
3571 * @param contentLength The file size reported by the server
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
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.
3587 startActivity(intent);
3589 } catch (ActivityNotFoundException ex) {
3591 Log.d(LOGTAG, "activity not found for " + mimetype
3592 + " over " + Uri.parse(url).getScheme(), ex);
3594 // Best behavior is to fall back to a download in this case
3598 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
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
3607 * @param mimetype The mimetype of the content reported by the server
3608 * @param contentLength The file size reported by the server
3610 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3611 String contentDisposition, String mimetype, long contentLength) {
3613 String filename = URLUtil.guessFileName(url,
3614 contentDisposition, mimetype);
3616 // Check to see if we have an SDCard
3617 String status = Environment.getExternalStorageState();
3618 if (!status.equals(Environment.MEDIA_MOUNTED)) {
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;
3627 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3628 title = R.string.download_no_sdcard_dlg_title;
3631 new AlertDialog.Builder(this)
3633 .setIcon(android.R.drawable.ic_dialog_alert)
3635 .setPositiveButton(R.string.ok, null)
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.
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);
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('#');
3656 frag = path.substring(idx + 1);
3657 path = path.substring(0, idx);
3659 idx = path.lastIndexOf('?');
3661 query = path.substring(idx + 1);
3662 path = path.substring(0, idx);
3665 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3667 } catch (Exception e) {
3668 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
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);
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,
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);
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);
3696 final Uri contentUri =
3697 getContentResolver().insert(Downloads.CONTENT_URI, values);
3698 viewDownloads(contentUri);
3704 * Resets the lock icon. This method is called when we start a new load and
3705 * know the url to be loaded.
3707 private void resetLockIcon(String url) {
3708 // Save the lock-icon state (we revert to it if the load gets cancelled)
3711 mLockIconType = LOCK_ICON_UNSECURE;
3712 if (URLUtil.isHttpsUrl(url)) {
3713 mLockIconType = LOCK_ICON_SECURE;
3715 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3716 " reset lock icon to " + mLockIconType);
3720 updateLockIconImage(LOCK_ICON_UNSECURE);
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
3728 private void resetLockIcon() {
3729 // Save the lock-icon state (we revert to it if the load gets cancelled)
3732 mLockIconType = LOCK_ICON_UNSECURE;
3735 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3736 " reset lock icon to " + mLockIconType);
3739 updateLockIconImage(LOCK_ICON_UNSECURE);
3743 * Updates the lock-icon image in the title-bar.
3745 private void updateLockIconImage(int lockIconType) {
3747 if (lockIconType == LOCK_ICON_SECURE) {
3749 } else if (lockIconType == LOCK_ICON_MIXED) {
3752 // If the tab overview is animating or being shown, do not update the
3754 if (mAnimationCount == 0 && mTabOverview == null) {
3755 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
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.
3767 private void showPageInfo(final TabControl.Tab tab,
3768 final boolean fromShowSSLCertificateOnError) {
3769 final LayoutInflater factory = LayoutInflater
3772 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3774 final WebView view = tab.getWebView();
3777 String title = null;
3781 title = tab.getTitle();
3782 } else if (view == mTabControl.getCurrentWebView()) {
3783 // Use the cached title and url if this is the current WebView
3787 url = view.getUrl();
3788 title = view.getTitle();
3794 if (title == null) {
3798 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3799 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3801 mPageInfoView = tab;
3802 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
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)
3810 new DialogInterface.OnClickListener() {
3811 public void onClick(DialogInterface dialog,
3813 mPageInfoDialog = null;
3814 mPageInfoView = null;
3815 mPageInfoFromShowSSLCertificateOnError = null;
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);
3827 .setOnCancelListener(
3828 new DialogInterface.OnCancelListener() {
3829 public void onCancel(DialogInterface dialog) {
3830 mPageInfoDialog = null;
3831 mPageInfoView = null;
3832 mPageInfoFromShowSSLCertificateOnError = null;
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);
3845 // if we have a main top-level page SSL certificate set or a certificate
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,
3855 mPageInfoDialog = null;
3856 mPageInfoView = null;
3857 mPageInfoFromShowSSLCertificateOnError = null;
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);
3867 // otherwise, display the top-most certificate from
3869 if (view.getCertificate() != null) {
3870 showSSLCertificate(tab);
3877 mPageInfoDialog = alertDialogBuilder.show();
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.
3885 private void showSSLCertificate(final TabControl.Tab tab) {
3886 final View certificateView =
3887 inflateCertificateView(tab.getWebView().getCertificate());
3888 if (certificateView == null) {
3892 LayoutInflater factory = LayoutInflater.from(this);
3894 final LinearLayout placeholder =
3895 (LinearLayout)certificateView.findViewById(R.id.placeholder);
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);
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,
3912 mSSLCertificateDialog = null;
3913 mSSLCertificateView = null;
3915 showPageInfo(tab, false);
3918 .setOnCancelListener(
3919 new DialogInterface.OnCancelListener() {
3920 public void onCancel(DialogInterface dialog) {
3921 mSSLCertificateDialog = null;
3922 mSSLCertificateView = null;
3924 showPageInfo(tab, false);
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.
3937 private void showSSLCertificateOnError(
3938 final WebView view, final SslErrorHandler handler, final SslError error) {
3940 final View certificateView =
3941 inflateCertificateView(error.getCertificate());
3942 if (certificateView == null) {
3946 LayoutInflater factory = LayoutInflater.from(this);
3948 final LinearLayout placeholder =
3949 (LinearLayout)certificateView.findViewById(R.id.placeholder);
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);
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);
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);
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);
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,
3991 mSSLCertificateOnErrorDialog = null;
3992 mSSLCertificateOnErrorView = null;
3993 mSSLCertificateOnErrorHandler = null;
3994 mSSLCertificateOnErrorError = null;
3996 mWebViewClient.onReceivedSslError(
3997 view, handler, error);
4000 .setNeutralButton(R.string.page_info_view,
4001 new DialogInterface.OnClickListener() {
4002 public void onClick(DialogInterface dialog,
4004 mSSLCertificateOnErrorDialog = null;
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
4010 showPageInfo(mTabControl.getTabFromView(view),
4014 .setOnCancelListener(
4015 new DialogInterface.OnCancelListener() {
4016 public void onCancel(DialogInterface dialog) {
4017 mSSLCertificateOnErrorDialog = null;
4018 mSSLCertificateOnErrorView = null;
4019 mSSLCertificateOnErrorHandler = null;
4020 mSSLCertificateOnErrorError = null;
4022 mWebViewClient.onReceivedSslError(
4023 view, handler, error);
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.
4036 private View inflateCertificateView(SslCertificate certificate) {
4037 if (certificate == null) {
4041 LayoutInflater factory = LayoutInflater.from(this);
4043 View certificateView = factory.inflate(
4044 R.layout.ssl_certificate, null);
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());
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());
4069 String issuedOn = reformatCertificateDate(
4070 certificate.getValidNotBefore());
4071 ((TextView) certificateView.findViewById(R.id.issued_on))
4075 String expiresOn = reformatCertificateDate(
4076 certificate.getValidNotAfter());
4077 ((TextView) certificateView.findViewById(R.id.expires_on))
4078 .setText(expiresOn);
4080 return certificateView;
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 "".
4090 private String reformatCertificateDate(String certificateDate) {
4091 String reformattedDate = null;
4093 if (certificateDate != null) {
4096 date = java.text.DateFormat.getInstance().parse(certificateDate);
4097 } catch (ParseException e) {
4103 DateFormat.getDateFormat(this).format(date);
4107 return reformattedDate != null ? reformattedDate :
4108 (certificateDate != null ? certificateDate : "");
4112 * Displays an http-authentication dialog.
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);
4121 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4123 if (password != null) {
4124 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4127 String titleText = title;
4128 if (titleText == null) {
4129 titleText = getText(R.string.sign_in_to).toString().replace(
4130 "%s1", host).replace("%s2", realm);
4133 mHttpAuthHandler = handler;
4134 AlertDialog dialog = new AlertDialog.Builder(this)
4135 .setTitle(titleText)
4136 .setIcon(android.R.drawable.ic_dialog_alert)
4138 .setPositiveButton(R.string.action,
4139 new DialogInterface.OnClickListener() {
4140 public void onClick(DialogInterface dialog,
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;
4154 .setNegativeButton(R.string.cancel,
4155 new DialogInterface.OnClickListener() {
4156 public void onClick(DialogInterface dialog,
4159 BrowserActivity.this.resetTitleAndRevertLockIcon();
4160 mHttpAuthenticationDialog = null;
4161 mHttpAuthHandler = null;
4163 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4164 public void onCancel(DialogInterface dialog) {
4166 BrowserActivity.this.resetTitleAndRevertLockIcon();
4167 mHttpAuthenticationDialog = null;
4168 mHttpAuthHandler = null;
4171 // Make the IME appear when the dialog is displayed if applicable.
4172 dialog.getWindow().setSoftInputMode(
4173 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4176 dialog.findViewById(focusId).requestFocus();
4178 v.findViewById(R.id.username_edit).requestFocus();
4180 mHttpAuthenticationDialog = dialog;
4183 public int getProgress() {
4184 WebView w = mTabControl.getCurrentWebView();
4186 return w.getProgress();
4193 * Set HTTP authentication password.
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
4201 public void setHttpAuthUsernamePassword(String host, String realm,
4204 WebView w = mTabControl.getCurrentWebView();
4206 w.setHttpAuthUsernamePassword(host, realm, username, password);
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
4214 public void onNetworkToggle(boolean up) {
4215 if (up == mIsNetworkUp) {
4218 mIsNetworkUp = true;
4219 if (mAlertDialog != null) {
4220 mAlertDialog.cancel();
4221 mAlertDialog = null;
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)
4233 WebView w = mTabControl.getCurrentWebView();
4235 w.setNetworkAvailable(up);
4240 protected void onActivityResult(int requestCode, int resultCode,
4242 switch (requestCode) {
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)) {
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
4255 if (mTabOverview != null && mAnimationCount == 0) {
4256 sendAnimateFromOverview(currentTab, false, data,
4257 null, TAB_OVERVIEW_DELAY, null);
4259 dismissSubWindow(currentTab);
4260 if (data != null && data.length() != 0) {
4261 getTopWindow().loadUrl(data);
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);
4273 mWebStorageQuotaUpdater.updateQuota(currentQuota);
4278 getTopWindow().requestFocus();
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.
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);
4295 * Handle results from Tab Switcher mTabOverview tool
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();
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
4310 if (current == remove) {
4311 // If the user removes the last tab, act like the New Tab item
4313 if (mTabControl.getTabCount() == 0) {
4314 current = mTabControl.createNewTab();
4315 sendAnimateFromOverview(current, true,
4316 mSettings.getHomePage(), null, TAB_OVERVIEW_DELAY,
4319 final int index = position > 0 ? (position - 1) : 0;
4320 current = mTabControl.getTab(index);
4324 // The tab overview could have been dismissed before this method is
4326 if (mTabOverview != null) {
4327 // Remove the tab and change the index.
4328 mTabOverview.remove(position);
4329 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
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);
4336 public void onClick(int index) {
4337 // Change the tab if necessary.
4338 // Index equals ImageGrid.CANCEL when pressing back from the tab
4340 if (index == ImageGrid.CANCEL) {
4341 index = mTabControl.getCurrentIndex();
4342 // The current index is -1 if the current tab was removed.
4344 // Take the last tab as a fallback.
4345 index = mTabControl.getTabCount() - 1;
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);
4353 sendAnimateFromOverview(mTabControl.getTab(index),
4354 false, null, null, 0, null);
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
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;
4373 AnimatingView(Context ctxt, TabControl.Tab 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();
4387 mScrollX = mScrollY = 0;
4392 protected void onDraw(Canvas canvas) {
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);
4407 * Open the tab picker. This function will always use the current tab in
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
4413 * @param remove If true, the tab at index will be removed after the
4414 * animation completes.
4416 private void tabPicker(final boolean stay, final int index,
4417 final boolean remove) {
4418 if (mTabOverview != null) {
4422 int size = mTabControl.getTabCount();
4424 TabListener l = null;
4426 l = mTabListener = new TabListener();
4428 mTabOverview = new ImageGrid(this, stay, l);
4430 for (int i = 0; i < size; i++) {
4431 final TabControl.Tab t = mTabControl.getTab(i);
4432 mTabControl.populatePickerData(t);
4433 mTabOverview.add(t);
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);
4441 // Attach the tab overview.
4442 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
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();
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.
4460 // Always change the title bar to the window overview title while
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;
4471 private void bookmarksOrHistoryPicker(boolean startWithHistory) {
4472 WebView current = mTabControl.getCurrentWebView();
4473 if (current == null) {
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.
4483 url = mLastEnteredUrl;
4486 url = mSettings.getHomePage();
4489 // In case the web page has not yet received its associated title.
4490 if (title == null) {
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);
4501 startActivityForResult(intent, COMBO_PAGE);
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)) {
4515 private void checkMemory() {
4516 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4517 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
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();
4530 private String smartUrlFilter(Uri inUri) {
4531 if (inUri != null) {
4532 return smartUrlFilter(inUri.toString());
4540 int getWindowCount(){
4541 if(mTabControl != null){
4542 return mTabControl.getTabCount();
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):" +
4556 * Attempts to determine whether user input is a URL or search
4557 * terms. Anything with a space is passed to search.
4559 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4560 * "Http://" converts to "http://"
4562 * @return Original or modified URL
4565 String smartUrlFilter(String url) {
4567 String inUrl = url.trim();
4568 boolean hasSpace = inUrl.indexOf(' ') != -1;
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);
4579 inUrl = inUrl.replace(" ", "%20");
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);
4591 Browser.addSearchUrl(mResolver, inUrl);
4592 return composeSearchUrl(inUrl.substring(2));
4594 } else if (char0 == 'w') {
4595 Browser.addSearchUrl(mResolver, inUrl);
4596 return URLUtil.composeSearchUrl(inUrl.substring(2),
4598 QUERY_PLACE_HOLDER);
4600 } else if (char0 == 'd') {
4601 Browser.addSearchUrl(mResolver, inUrl);
4602 return URLUtil.composeSearchUrl(inUrl.substring(2),
4604 QUERY_PLACE_HOLDER);
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),
4611 QUERY_PLACE_HOLDER);
4615 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4616 return URLUtil.guessUrl(inUrl);
4620 Browser.addSearchUrl(mResolver, inUrl);
4621 return composeSearchUrl(inUrl);
4624 /* package */ String composeSearchUrl(String search) {
4625 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4626 QUERY_PLACE_HOLDER);
4629 /* package */void setBaseSearchUrl(String url) {
4630 if (url == null || url.length() == 0) {
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.)
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)) {
4651 } else if ("tw".equals(country)) {
4654 } else if ("pt".equals(language)) {
4655 if ("br".equals(country)) {
4657 } else if ("pt".equals(country)) {
4661 QuickSearch_G = getResources().getString(
4662 R.string.google_search_base,
4666 + Partner.getString(this.getContentResolver(), Partner.CLIENT_ID)
4667 // FIXME, remove this when GEOLOCATION team make their move
4669 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4671 QuickSearch_G = url;
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;
4679 private int mLockIconType = LOCK_ICON_UNSECURE;
4680 private int mPrevLockType = LOCK_ICON_UNSECURE;
4682 private BrowserSettings mSettings;
4683 private TabControl mTabControl;
4684 private ContentResolver mResolver;
4685 private FrameLayout mContentView;
4686 private ImageGrid mTabOverview;
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;
4695 private FindDialog mFindDialog;
4696 // Used to prevent chording to result in firing two shortcuts immediately
4697 // one after another. Fixes bug 1211714.
4700 private boolean mInLoad;
4701 private boolean mIsNetworkUp;
4703 private boolean mPageStarted;
4704 private boolean mActivityInPause = true;
4706 private boolean mMenuIsDown;
4708 private final KeyTracker mKeyTracker = new KeyTracker(this);
4710 // As trackball doesn't send repeat down, we have to track it ourselves
4711 private boolean mTrackTrackball;
4713 private static boolean mInTrace;
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
4727 private long mStart;
4728 private long mProcessStart;
4729 private long mUserStart;
4730 private long mSystemStart;
4731 private long mIdleStart;
4732 private long mIrqStart;
4734 private long mUiStart;
4736 private Drawable mMixLockIcon;
4737 private Drawable mSecLockIcon;
4738 private Drawable mGenericFavicon;
4740 /* hold a ref so we can auto-cancel if necessary */
4741 private AlertDialog mAlertDialog;
4743 // Wait for credentials before loading google.com
4744 private ProgressDialog mCredsDlg;
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
4749 private String mUrl;
4750 private String mTitle;
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;
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;
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;
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;
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;
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";
4792 final static String QUERY_PLACE_HOLDER = "%s";
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";
4805 private final static String LOGTAG = "browser";
4807 private TabListener mTabListener;
4809 private String mLastEnteredUrl;
4811 private PowerManager.WakeLock mWakeLock;
4812 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4814 private Toast mStopToast;
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;
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 };
4829 // monitor platform changes
4830 private IntentFilter mNetworkStateChangedFilter;
4831 private BroadcastReceiver mNetworkStateIntentReceiver;
4833 private BroadcastReceiver mPackageInstallationReceiver;
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;
4841 // the frenquency of checking whether system memory is low
4842 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds