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