blob: 53640e5e6e2678c5a40ce53734bbd787c6a3d94a [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 /**
1292 * Overriding this forces the search key to launch global search. The difference
1293 * is the final "true" which requests global search.
1294 */
1295 @Override
1296 public boolean onSearchRequested() {
1297 startSearch(null, false,
1298 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), true);
1299 return true;
1300 }
1301
1302 @Override
1303 public void startSearch(String initialQuery, boolean selectInitialQuery,
1304 Bundle appSearchData, boolean globalSearch) {
1305 if (appSearchData == null) {
1306 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1307 }
1308 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1309 }
1310
1311 @Override
1312 public boolean onOptionsItemSelected(MenuItem item) {
1313 if (!mCanChord) {
1314 // The user has already fired a shortcut with this hold down of the
1315 // menu key.
1316 return false;
1317 }
1318 switch (item.getItemId()) {
1319 // -- Main menu
1320 case R.id.goto_menu_id: {
1321 String url = getTopWindow().getUrl();
1322 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1323 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
1324 }
1325 break;
1326
1327 case R.id.bookmarks_menu_id:
1328 bookmarksOrHistoryPicker(false);
1329 break;
1330
1331 case R.id.windows_menu_id:
1332 if (mTabControl.getTabCount() == 1) {
1333 openTabAndShow(mSettings.getHomePage(), null, false);
1334 } else {
1335 tabPicker(true, mTabControl.getCurrentIndex(), false);
1336 }
1337 break;
1338
1339 case R.id.stop_reload_menu_id:
1340 if (mInLoad) {
1341 stopLoading();
1342 } else {
1343 getTopWindow().reload();
1344 }
1345 break;
1346
1347 case R.id.back_menu_id:
1348 getTopWindow().goBack();
1349 break;
1350
1351 case R.id.forward_menu_id:
1352 getTopWindow().goForward();
1353 break;
1354
1355 case R.id.close_menu_id:
1356 // Close the subwindow if it exists.
1357 if (mTabControl.getCurrentSubWindow() != null) {
1358 dismissSubWindow(mTabControl.getCurrentTab());
1359 break;
1360 }
1361 final int currentIndex = mTabControl.getCurrentIndex();
1362 final TabControl.Tab parent =
1363 mTabControl.getCurrentTab().getParentTab();
1364 int indexToShow = -1;
1365 if (parent != null) {
1366 indexToShow = mTabControl.getTabIndex(parent);
1367 } else {
1368 // Get the last tab in the list. If it is the current tab,
1369 // subtract 1 more.
1370 indexToShow = mTabControl.getTabCount() - 1;
1371 if (currentIndex == indexToShow) {
1372 indexToShow--;
1373 }
1374 }
1375 switchTabs(currentIndex, indexToShow, true);
1376 break;
1377
1378 case R.id.homepage_menu_id:
1379 TabControl.Tab current = mTabControl.getCurrentTab();
1380 if (current != null) {
1381 dismissSubWindow(current);
1382 current.getWebView().loadUrl(mSettings.getHomePage());
1383 }
1384 break;
1385
1386 case R.id.preferences_menu_id:
1387 Intent intent = new Intent(this,
1388 BrowserPreferencesPage.class);
1389 startActivityForResult(intent, PREFERENCES_PAGE);
1390 break;
1391
1392 case R.id.find_menu_id:
1393 if (null == mFindDialog) {
1394 mFindDialog = new FindDialog(this);
1395 }
1396 mFindDialog.setWebView(getTopWindow());
1397 mFindDialog.show();
1398 mMenuState = EMPTY_MENU;
1399 break;
1400
1401 case R.id.select_text_id:
1402 getTopWindow().emulateShiftHeld();
1403 break;
1404 case R.id.page_info_menu_id:
1405 showPageInfo(mTabControl.getCurrentTab(), false);
1406 break;
1407
1408 case R.id.classic_history_menu_id:
1409 bookmarksOrHistoryPicker(true);
1410 break;
1411
1412 case R.id.share_page_menu_id:
1413 Browser.sendString(this, getTopWindow().getUrl());
1414 break;
1415
1416 case R.id.dump_nav_menu_id:
1417 getTopWindow().debugDump();
1418 break;
1419
1420 case R.id.zoom_in_menu_id:
1421 getTopWindow().zoomIn();
1422 break;
1423
1424 case R.id.zoom_out_menu_id:
1425 getTopWindow().zoomOut();
1426 break;
1427
1428 case R.id.view_downloads_menu_id:
1429 viewDownloads(null);
1430 break;
1431
1432 // -- Tab menu
1433 case R.id.view_tab_menu_id:
1434 if (mTabListener != null && mTabOverview != null) {
1435 int pos = mTabOverview.getContextMenuPosition(item);
1436 mTabOverview.setCurrentIndex(pos);
1437 mTabListener.onClick(pos);
1438 }
1439 break;
1440
1441 case R.id.remove_tab_menu_id:
1442 if (mTabListener != null && mTabOverview != null) {
1443 int pos = mTabOverview.getContextMenuPosition(item);
1444 mTabListener.remove(pos);
1445 }
1446 break;
1447
1448 case R.id.new_tab_menu_id:
1449 // No need to check for mTabOverview here since we are not
1450 // dependent on it for a position.
1451 if (mTabListener != null) {
1452 // If the overview happens to be non-null, make the "New
1453 // Tab" cell visible.
1454 if (mTabOverview != null) {
1455 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1456 }
1457 mTabListener.onClick(ImageGrid.NEW_TAB);
1458 }
1459 break;
1460
1461 case R.id.bookmark_tab_menu_id:
1462 if (mTabListener != null && mTabOverview != null) {
1463 int pos = mTabOverview.getContextMenuPosition(item);
1464 TabControl.Tab t = mTabControl.getTab(pos);
1465 // Since we called populatePickerData for all of the
1466 // tabs, getTitle and getUrl will return appropriate
1467 // values.
1468 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1469 t.getUrl());
1470 }
1471 break;
1472
1473 case R.id.history_tab_menu_id:
1474 bookmarksOrHistoryPicker(true);
1475 break;
1476
1477 case R.id.bookmarks_tab_menu_id:
1478 bookmarksOrHistoryPicker(false);
1479 break;
1480
1481 case R.id.properties_tab_menu_id:
1482 if (mTabListener != null && mTabOverview != null) {
1483 int pos = mTabOverview.getContextMenuPosition(item);
1484 showPageInfo(mTabControl.getTab(pos), false);
1485 }
1486 break;
1487
1488 case R.id.window_one_menu_id:
1489 case R.id.window_two_menu_id:
1490 case R.id.window_three_menu_id:
1491 case R.id.window_four_menu_id:
1492 case R.id.window_five_menu_id:
1493 case R.id.window_six_menu_id:
1494 case R.id.window_seven_menu_id:
1495 case R.id.window_eight_menu_id:
1496 {
1497 int menuid = item.getItemId();
1498 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1499 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1500 TabControl.Tab desiredTab = mTabControl.getTab(id);
1501 if (desiredTab != null &&
1502 desiredTab != mTabControl.getCurrentTab()) {
1503 switchTabs(mTabControl.getCurrentIndex(), id, false);
1504 }
1505 break;
1506 }
1507 }
1508 }
1509 break;
1510
1511 default:
1512 if (!super.onOptionsItemSelected(item)) {
1513 return false;
1514 }
1515 // Otherwise fall through.
1516 }
1517 mCanChord = false;
1518 return true;
1519 }
1520
1521 public void closeFind() {
1522 mMenuState = R.id.MAIN_MENU;
1523 }
1524
1525 @Override public boolean onPrepareOptionsMenu(Menu menu)
1526 {
1527 // This happens when the user begins to hold down the menu key, so
1528 // allow them to chord to get a shortcut.
1529 mCanChord = true;
1530 // Note: setVisible will decide whether an item is visible; while
1531 // setEnabled() will decide whether an item is enabled, which also means
1532 // whether the matching shortcut key will function.
1533 super.onPrepareOptionsMenu(menu);
1534 switch (mMenuState) {
1535 case R.id.TAB_MENU:
1536 if (mCurrentMenuState != mMenuState) {
1537 menu.setGroupVisible(R.id.MAIN_MENU, false);
1538 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1539 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1540 menu.setGroupVisible(R.id.TAB_MENU, true);
1541 menu.setGroupEnabled(R.id.TAB_MENU, true);
1542 }
1543 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1544 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1545 tab.setVisible(newT);
1546 tab.setEnabled(newT);
1547 break;
1548 case EMPTY_MENU:
1549 if (mCurrentMenuState != mMenuState) {
1550 menu.setGroupVisible(R.id.MAIN_MENU, false);
1551 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1552 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1553 menu.setGroupVisible(R.id.TAB_MENU, false);
1554 menu.setGroupEnabled(R.id.TAB_MENU, false);
1555 }
1556 break;
1557 default:
1558 if (mCurrentMenuState != mMenuState) {
1559 menu.setGroupVisible(R.id.MAIN_MENU, true);
1560 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1561 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1562 menu.setGroupVisible(R.id.TAB_MENU, false);
1563 menu.setGroupEnabled(R.id.TAB_MENU, false);
1564 }
1565 final WebView w = getTopWindow();
1566 boolean canGoBack = false;
1567 boolean canGoForward = false;
1568 boolean isHome = false;
1569 if (w != null) {
1570 canGoBack = w.canGoBack();
1571 canGoForward = w.canGoForward();
1572 isHome = mSettings.getHomePage().equals(w.getUrl());
1573 }
1574 final MenuItem back = menu.findItem(R.id.back_menu_id);
1575 back.setEnabled(canGoBack);
1576
1577 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1578 home.setEnabled(!isHome);
1579
1580 menu.findItem(R.id.forward_menu_id)
1581 .setEnabled(canGoForward);
1582
1583 // decide whether to show the share link option
1584 PackageManager pm = getPackageManager();
1585 Intent send = new Intent(Intent.ACTION_SEND);
1586 send.setType("text/plain");
1587 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1588 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1589
1590 // If there is only 1 window, the text will be "New window"
1591 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1592 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1593 getString(R.string.view_tabs_condensed) :
1594 getString(R.string.tab_picker_new_tab));
1595
1596 boolean isNavDump = mSettings.isNavDump();
1597 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1598 nav.setVisible(isNavDump);
1599 nav.setEnabled(isNavDump);
1600 break;
1601 }
1602 mCurrentMenuState = mMenuState;
1603 return true;
1604 }
1605
1606 @Override
1607 public void onCreateContextMenu(ContextMenu menu, View v,
1608 ContextMenuInfo menuInfo) {
1609 WebView webview = (WebView) v;
1610 WebView.HitTestResult result = webview.getHitTestResult();
1611 if (result == null) {
1612 return;
1613 }
1614
1615 int type = result.getType();
1616 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1617 Log.w(LOGTAG,
1618 "We should not show context menu when nothing is touched");
1619 return;
1620 }
1621 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1622 // let TextView handles context menu
1623 return;
1624 }
1625
1626 // Note, http://b/issue?id=1106666 is requesting that
1627 // an inflated menu can be used again. This is not available
1628 // yet, so inflate each time (yuk!)
1629 MenuInflater inflater = getMenuInflater();
1630 inflater.inflate(R.menu.browsercontext, menu);
1631
1632 // Show the correct menu group
1633 String extra = result.getExtra();
1634 menu.setGroupVisible(R.id.PHONE_MENU,
1635 type == WebView.HitTestResult.PHONE_TYPE);
1636 menu.setGroupVisible(R.id.EMAIL_MENU,
1637 type == WebView.HitTestResult.EMAIL_TYPE);
1638 menu.setGroupVisible(R.id.GEO_MENU,
1639 type == WebView.HitTestResult.GEO_TYPE);
1640 menu.setGroupVisible(R.id.IMAGE_MENU,
1641 type == WebView.HitTestResult.IMAGE_TYPE
1642 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1643 menu.setGroupVisible(R.id.ANCHOR_MENU,
1644 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1645 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1646
1647 // Setup custom handling depending on the type
1648 switch (type) {
1649 case WebView.HitTestResult.PHONE_TYPE:
1650 menu.setHeaderTitle(Uri.decode(extra));
1651 menu.findItem(R.id.dial_context_menu_id).setIntent(
1652 new Intent(Intent.ACTION_VIEW, Uri
1653 .parse(WebView.SCHEME_TEL + extra)));
1654 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1655 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1656 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1657 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1658 addIntent);
1659 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1660 new Copy(extra));
1661 break;
1662
1663 case WebView.HitTestResult.EMAIL_TYPE:
1664 menu.setHeaderTitle(extra);
1665 menu.findItem(R.id.email_context_menu_id).setIntent(
1666 new Intent(Intent.ACTION_VIEW, Uri
1667 .parse(WebView.SCHEME_MAILTO + extra)));
1668 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1669 new Copy(extra));
1670 break;
1671
1672 case WebView.HitTestResult.GEO_TYPE:
1673 menu.setHeaderTitle(extra);
1674 menu.findItem(R.id.map_context_menu_id).setIntent(
1675 new Intent(Intent.ACTION_VIEW, Uri
1676 .parse(WebView.SCHEME_GEO
1677 + URLEncoder.encode(extra))));
1678 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1679 new Copy(extra));
1680 break;
1681
1682 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1683 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1684 TextView titleView = (TextView) LayoutInflater.from(this)
1685 .inflate(android.R.layout.browser_link_context_header,
1686 null);
1687 titleView.setText(extra);
1688 menu.setHeaderView(titleView);
1689 // decide whether to show the open link in new tab option
1690 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1691 mTabControl.getTabCount() < TabControl.MAX_TABS);
1692 PackageManager pm = getPackageManager();
1693 Intent send = new Intent(Intent.ACTION_SEND);
1694 send.setType("text/plain");
1695 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1696 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1697 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1698 break;
1699 }
1700 // otherwise fall through to handle image part
1701 case WebView.HitTestResult.IMAGE_TYPE:
1702 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1703 menu.setHeaderTitle(extra);
1704 }
1705 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1706 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1707 menu.findItem(R.id.download_context_menu_id).
1708 setOnMenuItemClickListener(new Download(extra));
1709 break;
1710
1711 default:
1712 Log.w(LOGTAG, "We should not get here.");
1713 break;
1714 }
1715 }
1716
1717 // Used by attachTabToContentView for the WebView's ZoomControl widget.
1718 private static final FrameLayout.LayoutParams ZOOM_PARAMS =
1719 new FrameLayout.LayoutParams(
1720 ViewGroup.LayoutParams.FILL_PARENT,
1721 ViewGroup.LayoutParams.WRAP_CONTENT,
1722 Gravity.BOTTOM);
1723
1724 // Attach the given tab to the content view.
1725 private void attachTabToContentView(TabControl.Tab t) {
1726 final WebView main = t.getWebView();
1727 // Attach the main WebView.
1728 mContentView.addView(main, COVER_SCREEN_PARAMS);
1729 // Attach the Zoom control widget and hide it.
1730 final View zoom = main.getZoomControls();
1731 mContentView.addView(zoom, ZOOM_PARAMS);
1732 zoom.setVisibility(View.GONE);
1733 // Attach the sub window if necessary
1734 attachSubWindow(t);
1735 // Request focus on the top window.
1736 t.getTopWindow().requestFocus();
1737 }
1738
1739 // Attach a sub window to the main WebView of the given tab.
1740 private void attachSubWindow(TabControl.Tab t) {
1741 // If a sub window exists, attach it to the content view.
1742 final WebView subView = t.getSubWebView();
1743 if (subView != null) {
1744 final View container = t.getSubWebViewContainer();
1745 mContentView.addView(container, COVER_SCREEN_PARAMS);
1746 subView.requestFocus();
1747 }
1748 }
1749
1750 // Remove the given tab from the content view.
1751 private void removeTabFromContentView(TabControl.Tab t) {
1752 // Remove the Zoom widget and the main WebView.
1753 mContentView.removeView(t.getWebView().getZoomControls());
1754 mContentView.removeView(t.getWebView());
1755 // Remove the sub window if it exists.
1756 if (t.getSubWebView() != null) {
1757 mContentView.removeView(t.getSubWebViewContainer());
1758 }
1759 }
1760
1761 // Remove the sub window if it exists. Also called by TabControl when the
1762 // user clicks the 'X' to dismiss a sub window.
1763 /* package */ void dismissSubWindow(TabControl.Tab t) {
1764 final WebView mainView = t.getWebView();
1765 if (t.getSubWebView() != null) {
1766 // Remove the container view and request focus on the main WebView.
1767 mContentView.removeView(t.getSubWebViewContainer());
1768 mainView.requestFocus();
1769 // Tell the TabControl to dismiss the subwindow. This will destroy
1770 // the WebView.
1771 mTabControl.dismissSubWindow(t);
1772 }
1773 }
1774
1775 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
1776 private void sendAnimateFromOverview(final TabControl.Tab tab,
1777 final boolean newTab, final String url, final int delay,
1778 final Message msg) {
1779 // Set the current tab.
1780 mTabControl.setCurrentTab(tab);
1781 // Attach the WebView so it will layout.
1782 attachTabToContentView(tab);
1783 // Set the view to invisibile for now.
1784 tab.getWebView().setVisibility(View.INVISIBLE);
1785 // If there is a sub window, make it invisible too.
1786 if (tab.getSubWebView() != null) {
1787 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
1788 }
1789 // Create our fake animating view.
1790 final AnimatingView view = new AnimatingView(this, tab);
1791 // Attach it to the view system and make in invisible so it will
1792 // layout but not flash white on the screen.
1793 mContentView.addView(view, COVER_SCREEN_PARAMS);
1794 view.setVisibility(View.INVISIBLE);
1795 // Send the animate message.
1796 final HashMap map = new HashMap();
1797 map.put("view", view);
1798 // Load the url after the AnimatingView has captured the picture. This
1799 // prevents any bad layout or bad scale from being used during
1800 // animation.
1801 if (url != null) {
1802 dismissSubWindow(tab);
1803 tab.getWebView().loadUrl(url);
1804 }
1805 map.put("msg", msg);
1806 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1807 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
1808 // Increment the count to indicate that we are in an animation.
1809 mAnimationCount++;
1810 // Remove the listener so we don't get any more tab changes.
1811 mTabOverview.setListener(null);
1812 mTabListener = null;
1813 // Make the menu empty until the animation completes.
1814 mMenuState = EMPTY_MENU;
1815
1816 }
1817
1818 // 500ms animation with 800ms delay
1819 private static final int TAB_ANIMATION_DURATION = 500;
1820 private static final int TAB_OVERVIEW_DELAY = 800;
1821
1822 // Called by TabControl when a tab is requesting focus
1823 /* package */ void showTab(TabControl.Tab t) {
1824 // Disallow focus change during a tab animation.
1825 if (mAnimationCount > 0) {
1826 return;
1827 }
1828 int delay = 0;
1829 if (mTabOverview == null) {
1830 // Add a delay so the tab overview can be shown before the second
1831 // animation begins.
1832 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1833 tabPicker(false, mTabControl.getTabIndex(t), false);
1834 }
1835 sendAnimateFromOverview(t, false, null, delay, null);
1836 }
1837
1838 // This method does a ton of stuff. It will attempt to create a new tab
1839 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1840 // url isn't null, it will load the given url. If the tab overview is not
1841 // showing, it will animate to the tab overview, create a new tab and
1842 // animate away from it. After the animation completes, it will dispatch
1843 // the given Message. If the tab overview is already showing (i.e. this
1844 // method is called from TabListener.onClick(), the method will animate
1845 // away from the tab overview.
1846 private void openTabAndShow(String url, final Message msg,
1847 boolean closeOnExit) {
1848 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1849 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1850 if (newTab) {
1851 int delay = 0;
1852 // If the tab overview is up and there are animations, just load
1853 // the url.
1854 if (mTabOverview != null && mAnimationCount > 0) {
1855 if (url != null) {
1856 // We should not have a msg here since onCreateWindow
1857 // checks the animation count and every other caller passes
1858 // null.
1859 assert msg == null;
1860 // just dismiss the subwindow and load the given url.
1861 dismissSubWindow(currentTab);
1862 currentTab.getWebView().loadUrl(url);
1863 }
1864 } else {
1865 // show mTabOverview if it is not there.
1866 if (mTabOverview == null) {
1867 // We have to delay the animation from the tab picker by the
1868 // length of the tab animation. Add a delay so the tab
1869 // overview can be shown before the second animation begins.
1870 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1871 tabPicker(false, ImageGrid.NEW_TAB, false);
1872 }
1873 // Animate from the Tab overview after any animations have
1874 // finished.
1875 sendAnimateFromOverview(mTabControl.createNewTab(closeOnExit),
1876 true, url, delay, msg);
1877 }
1878 } else if (url != null) {
1879 // We should not have a msg here.
1880 assert msg == null;
1881 if (mTabOverview != null && mAnimationCount == 0) {
1882 sendAnimateFromOverview(currentTab, false, url,
1883 TAB_OVERVIEW_DELAY, null);
1884 } else {
1885 // Get rid of the subwindow if it exists
1886 dismissSubWindow(currentTab);
1887 // Load the given url.
1888 currentTab.getWebView().loadUrl(url);
1889 }
1890 }
1891 }
1892
1893 private Animation createTabAnimation(final AnimatingView view,
1894 final View cell, boolean scaleDown) {
1895 final AnimationSet set = new AnimationSet(true);
1896 final float scaleX = (float) cell.getWidth() / view.getWidth();
1897 final float scaleY = (float) cell.getHeight() / view.getHeight();
1898 if (scaleDown) {
1899 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
1900 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
1901 cell.getTop()));
1902 } else {
1903 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
1904 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
1905 cell.getTop(), 0));
1906 }
1907 set.setDuration(TAB_ANIMATION_DURATION);
1908 set.setInterpolator(new DecelerateInterpolator());
1909 return set;
1910 }
1911
1912 // Animate to the tab overview. currentIndex tells us which position to
1913 // animate to and newIndex is the position that should be selected after
1914 // the animation completes.
1915 // If remove is true, after the animation stops, a confirmation dialog will
1916 // be displayed to the user.
1917 private void animateToTabOverview(final int newIndex, final boolean remove,
1918 final AnimatingView view) {
1919 // Find the view in the ImageGrid allowing for the "New Tab" cell.
1920 int position = mTabControl.getTabIndex(view.mTab);
1921 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
1922 position++;
1923 }
1924
1925 // Offset the tab position with the first visible position to get a
1926 // number between 0 and 3.
1927 position -= mTabOverview.getFirstVisiblePosition();
1928
1929 // Grab the view that we are going to animate to.
1930 final View v = mTabOverview.getChildAt(position);
1931
1932 final Animation.AnimationListener l =
1933 new Animation.AnimationListener() {
1934 public void onAnimationStart(Animation a) {
1935 mTabOverview.requestFocus();
1936 // Clear the listener so we don't trigger a tab
1937 // selection.
1938 mTabOverview.setListener(null);
1939 }
1940 public void onAnimationRepeat(Animation a) {}
1941 public void onAnimationEnd(Animation a) {
1942 // We are no longer animating so decrement the count.
1943 mAnimationCount--;
1944 // Make the view GONE so that it will not draw between
1945 // now and when the Runnable is handled.
1946 view.setVisibility(View.GONE);
1947 // Post a runnable since we can't modify the view
1948 // hierarchy during this callback.
1949 mHandler.post(new Runnable() {
1950 public void run() {
1951 // Remove the AnimatingView.
1952 mContentView.removeView(view);
1953 if (mTabOverview != null) {
1954 // Make newIndex visible.
1955 mTabOverview.setCurrentIndex(newIndex);
1956 // Restore the listener.
1957 mTabOverview.setListener(mTabListener);
1958 // Change the menu to TAB_MENU if the
1959 // ImageGrid is interactive.
1960 if (mTabOverview.isLive()) {
1961 mMenuState = R.id.TAB_MENU;
1962 mTabOverview.requestFocus();
1963 }
1964 }
1965 // If a remove was requested, remove the tab.
1966 if (remove) {
1967 // During a remove, the current tab has
1968 // already changed. Remember the current one
1969 // here.
1970 final TabControl.Tab currentTab =
1971 mTabControl.getCurrentTab();
1972 // Remove the tab at newIndex from
1973 // TabControl and the tab overview.
1974 final TabControl.Tab tab =
1975 mTabControl.getTab(newIndex);
1976 mTabControl.removeTab(tab);
1977 // Restore the current tab.
1978 if (currentTab != tab) {
1979 mTabControl.setCurrentTab(currentTab);
1980 }
1981 if (mTabOverview != null) {
1982 mTabOverview.remove(newIndex);
1983 // Make the current tab visible.
1984 mTabOverview.setCurrentIndex(
1985 mTabControl.getCurrentIndex());
1986 }
1987 }
1988 }
1989 });
1990 }
1991 };
1992
1993 // Do an animation if there is a view to animate to.
1994 if (v != null) {
1995 // Create our animation
1996 final Animation anim = createTabAnimation(view, v, true);
1997 anim.setAnimationListener(l);
1998 // Start animating
1999 view.startAnimation(anim);
2000 } else {
2001 // If something goes wrong and we didn't find a view to animate to,
2002 // just do everything here.
2003 l.onAnimationStart(null);
2004 l.onAnimationEnd(null);
2005 }
2006 }
2007
2008 // Animate from the tab picker. The index supplied is the index to animate
2009 // from.
2010 private void animateFromTabOverview(final AnimatingView view,
2011 final boolean newTab, final Message msg) {
2012 // firstVisible is the first visible tab on the screen. This helps
2013 // to know which corner of the screen the selected tab is.
2014 int firstVisible = mTabOverview.getFirstVisiblePosition();
2015 // tabPosition is the 0-based index of of the tab being opened
2016 int tabPosition = mTabControl.getTabIndex(view.mTab);
2017 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2018 // Add one to make room for the "New Tab" cell.
2019 tabPosition++;
2020 }
2021 // If this is a new tab, animate from the "New Tab" cell.
2022 if (newTab) {
2023 tabPosition = 0;
2024 }
2025 // Location corresponds to the four corners of the screen.
2026 // A new tab or 0 is upper left, 0 for an old tab is upper
2027 // right, 1 is lower left, and 2 is lower right
2028 int location = tabPosition - firstVisible;
2029
2030 // Find the view at this location.
2031 final View v = mTabOverview.getChildAt(location);
2032
2033 // Wait until the animation completes to replace the AnimatingView.
2034 final Animation.AnimationListener l =
2035 new Animation.AnimationListener() {
2036 public void onAnimationStart(Animation a) {}
2037 public void onAnimationRepeat(Animation a) {}
2038 public void onAnimationEnd(Animation a) {
2039 mHandler.post(new Runnable() {
2040 public void run() {
2041 mContentView.removeView(view);
2042 // Dismiss the tab overview. If the cell at the
2043 // given location is null, set the fade
2044 // parameter to true.
2045 dismissTabOverview(v == null);
2046 TabControl.Tab t =
2047 mTabControl.getCurrentTab();
2048 mMenuState = R.id.MAIN_MENU;
2049 // Resume regular updates.
2050 t.getWebView().resumeTimers();
2051 // Dispatch the message after the animation
2052 // completes.
2053 if (msg != null) {
2054 msg.sendToTarget();
2055 }
2056 // The animation is done and the tab overview is
2057 // gone so allow key events and other animations
2058 // to begin.
2059 mAnimationCount--;
2060 // Reset all the title bar info.
2061 resetTitle();
2062 }
2063 });
2064 }
2065 };
2066
2067 if (v != null) {
2068 final Animation anim = createTabAnimation(view, v, false);
2069 // Set the listener and start animating
2070 anim.setAnimationListener(l);
2071 view.startAnimation(anim);
2072 // Make the view VISIBLE during the animation.
2073 view.setVisibility(View.VISIBLE);
2074 } else {
2075 // Go ahead and do all the cleanup.
2076 l.onAnimationEnd(null);
2077 }
2078 }
2079
2080 // Dismiss the tab overview applying a fade if needed.
2081 private void dismissTabOverview(final boolean fade) {
2082 if (fade) {
2083 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2084 anim.setDuration(500);
2085 anim.startNow();
2086 mTabOverview.startAnimation(anim);
2087 }
2088 // Just in case there was a problem with animating away from the tab
2089 // overview
2090 WebView current = mTabControl.getCurrentWebView();
2091 if (current != null) {
2092 current.setVisibility(View.VISIBLE);
2093 } else {
2094 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2095 }
2096 // Make the sub window container visible.
2097 if (mTabControl.getCurrentSubWindow() != null) {
2098 mTabControl.getCurrentTab().getSubWebViewContainer()
2099 .setVisibility(View.VISIBLE);
2100 }
2101 mContentView.removeView(mTabOverview);
2102 mTabOverview.clear();
2103 mTabOverview = null;
2104 mTabListener = null;
2105 }
2106
2107 private void openTab(String url) {
2108 if (mSettings.openInBackground()) {
2109 TabControl.Tab t = mTabControl.createNewTab(false);
2110 if (t != null) {
2111 t.getWebView().loadUrl(url);
2112 }
2113 } else {
2114 openTabAndShow(url, null, false);
2115 }
2116 }
2117
2118 private class Copy implements OnMenuItemClickListener {
2119 private CharSequence mText;
2120
2121 public boolean onMenuItemClick(MenuItem item) {
2122 copy(mText);
2123 return true;
2124 }
2125
2126 public Copy(CharSequence toCopy) {
2127 mText = toCopy;
2128 }
2129 }
2130
2131 private class Download implements OnMenuItemClickListener {
2132 private String mText;
2133
2134 public boolean onMenuItemClick(MenuItem item) {
2135 onDownloadStartNoStream(mText, null, null, null, -1);
2136 return true;
2137 }
2138
2139 public Download(String toDownload) {
2140 mText = toDownload;
2141 }
2142 }
2143
2144 private void copy(CharSequence text) {
2145 try {
2146 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2147 if (clip != null) {
2148 clip.setClipboardText(text);
2149 }
2150 } catch (android.os.RemoteException e) {
2151 Log.e(LOGTAG, "Copy failed", e);
2152 }
2153 }
2154
2155 /**
2156 * Resets the browser title-view to whatever it must be (for example, if we
2157 * load a page from history).
2158 */
2159 private void resetTitle() {
2160 resetLockIcon();
2161 resetTitleIconAndProgress();
2162 }
2163
2164 /**
2165 * Resets the browser title-view to whatever it must be
2166 * (for example, if we had a loading error)
2167 * When we have a new page, we call resetTitle, when we
2168 * have to reset the titlebar to whatever it used to be
2169 * (for example, if the user chose to stop loading), we
2170 * call resetTitleAndRevertLockIcon.
2171 */
2172 /* package */ void resetTitleAndRevertLockIcon() {
2173 revertLockIcon();
2174 resetTitleIconAndProgress();
2175 }
2176
2177 /**
2178 * Reset the title, favicon, and progress.
2179 */
2180 private void resetTitleIconAndProgress() {
2181 WebView current = mTabControl.getCurrentWebView();
2182 if (current == null) {
2183 return;
2184 }
2185 resetTitleAndIcon(current);
2186 int progress = current.getProgress();
2187 mInLoad = (progress != 100);
2188 updateInLoadMenuItems();
2189 mWebChromeClient.onProgressChanged(current, progress);
2190 }
2191
2192 // Reset the title and the icon based on the given item.
2193 private void resetTitleAndIcon(WebView view) {
2194 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2195 if (item != null) {
2196 setUrlTitle(item.getUrl(), item.getTitle());
2197 setFavicon(item.getFavicon());
2198 } else {
2199 setUrlTitle(null, null);
2200 setFavicon(null);
2201 }
2202 }
2203
2204 /**
2205 * Sets a title composed of the URL and the title string.
2206 * @param url The URL of the site being loaded.
2207 * @param title The title of the site being loaded.
2208 */
2209 private void setUrlTitle(String url, String title) {
2210 mUrl = url;
2211 mTitle = title;
2212
2213 // While the tab overview is animating or being shown, block changes
2214 // to the title.
2215 if (mAnimationCount == 0 && mTabOverview == null) {
2216 setTitle(buildUrlTitle(url, title));
2217 }
2218 }
2219
2220 /**
2221 * Builds and returns the page title, which is some
2222 * combination of the page URL and title.
2223 * @param url The URL of the site being loaded.
2224 * @param title The title of the site being loaded.
2225 * @return The page title.
2226 */
2227 private String buildUrlTitle(String url, String title) {
2228 String urlTitle = "";
2229
2230 if (url != null) {
2231 String titleUrl = buildTitleUrl(url);
2232
2233 if (title != null && 0 < title.length()) {
2234 if (titleUrl != null && 0 < titleUrl.length()) {
2235 urlTitle = titleUrl + ": " + title;
2236 } else {
2237 urlTitle = title;
2238 }
2239 } else {
2240 if (titleUrl != null) {
2241 urlTitle = titleUrl;
2242 }
2243 }
2244 }
2245
2246 return urlTitle;
2247 }
2248
2249 /**
2250 * @param url The URL to build a title version of the URL from.
2251 * @return The title version of the URL or null if fails.
2252 * The title version of the URL can be either the URL hostname,
2253 * or the hostname with an "https://" prefix (for secure URLs),
2254 * or an empty string if, for example, the URL in question is a
2255 * file:// URL with no hostname.
2256 */
2257 private static String buildTitleUrl(String url) {
2258 String titleUrl = null;
2259
2260 if (url != null) {
2261 try {
2262 // parse the url string
2263 URL urlObj = new URL(url);
2264 if (urlObj != null) {
2265 titleUrl = "";
2266
2267 String protocol = urlObj.getProtocol();
2268 String host = urlObj.getHost();
2269
2270 if (host != null && 0 < host.length()) {
2271 titleUrl = host;
2272 if (protocol != null) {
2273 // if a secure site, add an "https://" prefix!
2274 if (protocol.equalsIgnoreCase("https")) {
2275 titleUrl = protocol + "://" + host;
2276 }
2277 }
2278 }
2279 }
2280 } catch (MalformedURLException e) {}
2281 }
2282
2283 return titleUrl;
2284 }
2285
2286 // Set the favicon in the title bar.
2287 private void setFavicon(Bitmap icon) {
2288 // While the tab overview is animating or being shown, block changes to
2289 // the favicon.
2290 if (mAnimationCount > 0 || mTabOverview != null) {
2291 return;
2292 }
2293 Drawable[] array = new Drawable[2];
2294 PaintDrawable p = new PaintDrawable(Color.WHITE);
2295 p.setCornerRadius(3f);
2296 array[0] = p;
2297 if (icon == null) {
2298 array[1] = mGenericFavicon;
2299 } else {
2300 array[1] = new BitmapDrawable(icon);
2301 }
2302 LayerDrawable d = new LayerDrawable(array);
2303 d.setLayerInset(1, 2, 2, 2, 2);
2304 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2305 }
2306
2307 /**
2308 * Saves the current lock-icon state before resetting
2309 * the lock icon. If we have an error, we may need to
2310 * roll back to the previous state.
2311 */
2312 private void saveLockIcon() {
2313 mPrevLockType = mLockIconType;
2314 }
2315
2316 /**
2317 * Reverts the lock-icon state to the last saved state,
2318 * for example, if we had an error, and need to cancel
2319 * the load.
2320 */
2321 private void revertLockIcon() {
2322 mLockIconType = mPrevLockType;
2323
2324 if (Config.LOGV) {
2325 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2326 " revert lock icon to " + mLockIconType);
2327 }
2328
2329 updateLockIconImage(mLockIconType);
2330 }
2331
2332 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2333 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2334 // Animate to the tab picker, remove the current tab, then
2335 // animate away from the tab picker to the parent WebView.
2336 tabPicker(false, indexFrom, remove);
2337 // Change to the parent tab
2338 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2339 if (tab != null) {
2340 sendAnimateFromOverview(tab, false, null, delay, null);
2341 } else {
2342 // Increment this here so that no other animations can happen in
2343 // between the end of the tab picker transition and the beginning
2344 // of openTabAndShow. This has a matching decrement in the handler
2345 // of OPEN_TAB_AND_SHOW.
2346 mAnimationCount++;
2347 // Send a message to open a new tab.
2348 mHandler.sendMessageDelayed(
2349 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2350 mSettings.getHomePage()), delay);
2351 }
2352 }
2353
2354 private void goBackOnePageOrQuit() {
2355 TabControl.Tab current = mTabControl.getCurrentTab();
2356 if (current == null) {
2357 /*
2358 * Instead of finishing the activity, simply push this to the back
2359 * of the stack and let ActivityManager to choose the foreground
2360 * activity. As BrowserActivity is singleTask, it will be always the
2361 * root of the task. So we can use either true or false for
2362 * moveTaskToBack().
2363 */
2364 moveTaskToBack(true);
2365 }
2366 WebView w = current.getWebView();
2367 if (w.canGoBack()) {
2368 w.goBack();
2369 } else {
2370 // Check to see if we are closing a window that was created by
2371 // another window. If so, we switch back to that window.
2372 TabControl.Tab parent = current.getParentTab();
2373 if (parent != null) {
2374 switchTabs(mTabControl.getCurrentIndex(),
2375 mTabControl.getTabIndex(parent), true);
2376 } else {
2377 if (current.closeOnExit()) {
2378 if (mTabControl.getTabCount() == 1) {
2379 finish();
2380 return;
2381 }
2382 // call pauseWebView() now, we won't be able to call it in
2383 // onPause() as the WebView won't be valid.
2384 pauseWebView();
2385 removeTabFromContentView(current);
2386 mTabControl.removeTab(current);
2387 }
2388 /*
2389 * Instead of finishing the activity, simply push this to the back
2390 * of the stack and let ActivityManager to choose the foreground
2391 * activity. As BrowserActivity is singleTask, it will be always the
2392 * root of the task. So we can use either true or false for
2393 * moveTaskToBack().
2394 */
2395 moveTaskToBack(true);
2396 }
2397 }
2398 }
2399
2400 public KeyTracker.State onKeyTracker(int keyCode,
2401 KeyEvent event,
2402 KeyTracker.Stage stage,
2403 int duration) {
2404 // if onKeyTracker() is called after activity onStop()
2405 // because of accumulated key events,
2406 // we should ignore it as browser is not active any more.
2407 WebView topWindow = getTopWindow();
2408 if (topWindow == null)
2409 return KeyTracker.State.NOT_TRACKING;
2410
2411 if (keyCode == KeyEvent.KEYCODE_BACK) {
2412 // During animations, block the back key so that other animations
2413 // are not triggered and so that we don't end up destroying all the
2414 // WebViews before finishing the animation.
2415 if (mAnimationCount > 0) {
2416 return KeyTracker.State.DONE_TRACKING;
2417 }
2418 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2419 bookmarksOrHistoryPicker(true);
2420 return KeyTracker.State.DONE_TRACKING;
2421 } else if (stage == KeyTracker.Stage.UP) {
2422 // FIXME: Currently, we do not have a notion of the
2423 // history picker for the subwindow, but maybe we
2424 // should?
2425 WebView subwindow = mTabControl.getCurrentSubWindow();
2426 if (subwindow != null) {
2427 if (subwindow.canGoBack()) {
2428 subwindow.goBack();
2429 } else {
2430 dismissSubWindow(mTabControl.getCurrentTab());
2431 }
2432 } else {
2433 goBackOnePageOrQuit();
2434 }
2435 return KeyTracker.State.DONE_TRACKING;
2436 }
2437 return KeyTracker.State.KEEP_TRACKING;
2438 }
2439 return KeyTracker.State.NOT_TRACKING;
2440 }
2441
2442 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2443 if (keyCode == KeyEvent.KEYCODE_MENU) {
2444 mMenuIsDown = true;
2445 }
2446 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2447 if (!handled) {
2448 switch (keyCode) {
2449 case KeyEvent.KEYCODE_SPACE:
2450 if (event.isShiftPressed()) {
2451 getTopWindow().pageUp(false);
2452 } else {
2453 getTopWindow().pageDown(false);
2454 }
2455 handled = true;
2456 break;
2457
2458 default:
2459 break;
2460 }
2461 }
2462 return handled || super.onKeyDown(keyCode, event);
2463 }
2464
2465 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2466 if (keyCode == KeyEvent.KEYCODE_MENU) {
2467 mMenuIsDown = false;
2468 }
2469 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2470 }
2471
2472 private void stopLoading() {
2473 resetTitleAndRevertLockIcon();
2474 WebView w = getTopWindow();
2475 w.stopLoading();
2476 mWebViewClient.onPageFinished(w, w.getUrl());
2477
2478 cancelStopToast();
2479 mStopToast = Toast
2480 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2481 mStopToast.show();
2482 }
2483
2484 private void cancelStopToast() {
2485 if (mStopToast != null) {
2486 mStopToast.cancel();
2487 mStopToast = null;
2488 }
2489 }
2490
2491 // called by a non-UI thread to post the message
2492 public void postMessage(int what, int arg1, int arg2, Object obj) {
2493 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2494 }
2495
2496 // public message ids
2497 public final static int LOAD_URL = 1001;
2498 public final static int STOP_LOAD = 1002;
2499
2500 // Message Ids
2501 private static final int FOCUS_NODE_HREF = 102;
2502 private static final int CANCEL_CREDS_REQUEST = 103;
2503 private static final int ANIMATE_FROM_OVERVIEW = 104;
2504 private static final int ANIMATE_TO_OVERVIEW = 105;
2505 private static final int OPEN_TAB_AND_SHOW = 106;
2506 private static final int CHECK_MEMORY = 107;
2507 private static final int RELEASE_WAKELOCK = 108;
2508
2509 // Private handler for handling javascript and saving passwords
2510 private Handler mHandler = new Handler() {
2511
2512 public void handleMessage(Message msg) {
2513 switch (msg.what) {
2514 case ANIMATE_FROM_OVERVIEW:
2515 final HashMap map = (HashMap) msg.obj;
2516 animateFromTabOverview((AnimatingView) map.get("view"),
2517 msg.arg1 == 1, (Message) map.get("msg"));
2518 break;
2519
2520 case ANIMATE_TO_OVERVIEW:
2521 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2522 (AnimatingView) msg.obj);
2523 break;
2524
2525 case OPEN_TAB_AND_SHOW:
2526 // Decrement mAnimationCount before openTabAndShow because
2527 // the method relies on the value being 0 to start the next
2528 // animation.
2529 mAnimationCount--;
2530 openTabAndShow((String) msg.obj, null, false);
2531 break;
2532
2533 case FOCUS_NODE_HREF:
2534 String url = (String) msg.getData().get("url");
2535 if (url == null || url.length() == 0) {
2536 break;
2537 }
2538 HashMap focusNodeMap = (HashMap) msg.obj;
2539 WebView view = (WebView) focusNodeMap.get("webview");
2540 // Only apply the action if the top window did not change.
2541 if (getTopWindow() != view) {
2542 break;
2543 }
2544 switch (msg.arg1) {
2545 case R.id.open_context_menu_id:
2546 case R.id.view_image_context_menu_id:
2547 loadURL(getTopWindow(), url);
2548 break;
2549 case R.id.open_newtab_context_menu_id:
2550 openTab(url);
2551 break;
2552 case R.id.bookmark_context_menu_id:
2553 Intent intent = new Intent(BrowserActivity.this,
2554 AddBookmarkPage.class);
2555 intent.putExtra("url", url);
2556 startActivity(intent);
2557 break;
2558 case R.id.share_link_context_menu_id:
2559 Browser.sendString(BrowserActivity.this, url);
2560 break;
2561 case R.id.copy_link_context_menu_id:
2562 copy(url);
2563 break;
2564 case R.id.save_link_context_menu_id:
2565 case R.id.download_context_menu_id:
2566 onDownloadStartNoStream(url, null, null, null, -1);
2567 break;
2568 }
2569 break;
2570
2571 case LOAD_URL:
2572 loadURL(getTopWindow(), (String) msg.obj);
2573 break;
2574
2575 case STOP_LOAD:
2576 stopLoading();
2577 break;
2578
2579 case CANCEL_CREDS_REQUEST:
2580 resumeAfterCredentials();
2581 break;
2582
2583 case CHECK_MEMORY:
2584 // reschedule to check memory condition
2585 mHandler.removeMessages(CHECK_MEMORY);
2586 mHandler.sendMessageDelayed(mHandler.obtainMessage
2587 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2588 checkMemory();
2589 break;
2590
2591 case RELEASE_WAKELOCK:
2592 if (mWakeLock.isHeld()) {
2593 mWakeLock.release();
2594 }
2595 break;
2596 }
2597 }
2598 };
2599
2600 // -------------------------------------------------------------------------
2601 // WebViewClient implementation.
2602 //-------------------------------------------------------------------------
2603
2604 // Use in overrideUrlLoading
2605 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2606 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2607 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2608 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2609
2610 /* package */ WebViewClient getWebViewClient() {
2611 return mWebViewClient;
2612 }
2613
2614 private void updateIcon(String url, Bitmap icon) {
2615 if (icon != null) {
2616 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2617 url, icon);
2618 }
2619 setFavicon(icon);
2620 }
2621
2622 private final WebViewClient mWebViewClient = new WebViewClient() {
2623 @Override
2624 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2625 resetLockIcon(url);
2626 setUrlTitle(url, null);
2627 // Call updateIcon instead of setFavicon so the bookmark
2628 // database can be updated.
2629 updateIcon(url, favicon);
2630
2631 if (mSettings.isTracing() == true) {
2632 // FIXME: we should save the trace file somewhere other than data.
2633 // I can't use "/tmp" as it competes for system memory.
2634 File file = getDir("browserTrace", 0);
2635 String baseDir = file.getPath();
2636 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2637 String host;
2638 try {
2639 WebAddress uri = new WebAddress(url);
2640 host = uri.mHost;
2641 } catch (android.net.ParseException ex) {
2642 host = "unknown_host";
2643 }
2644 host = host.replace('.', '_');
2645 baseDir = baseDir + host;
2646 file = new File(baseDir+".data");
2647 if (file.exists() == true) {
2648 file.delete();
2649 }
2650 file = new File(baseDir+".key");
2651 if (file.exists() == true) {
2652 file.delete();
2653 }
2654 mInTrace = true;
2655 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2656 }
2657
2658 // Performance probe
2659 if (false) {
2660 mStart = SystemClock.uptimeMillis();
2661 mProcessStart = Process.getElapsedCpuTime();
2662 long[] sysCpu = new long[7];
2663 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2664 sysCpu, null)) {
2665 mUserStart = sysCpu[0] + sysCpu[1];
2666 mSystemStart = sysCpu[2];
2667 mIdleStart = sysCpu[3];
2668 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2669 }
2670 mUiStart = SystemClock.currentThreadTimeMillis();
2671 }
2672
2673 if (!mPageStarted) {
2674 mPageStarted = true;
2675 // if onResume() has been called, resumeWebView() does nothing.
2676 resumeWebView();
2677 }
2678
2679 // reset sync timer to avoid sync starts during loading a page
2680 CookieSyncManager.getInstance().resetSync();
2681
2682 mInLoad = true;
2683 updateInLoadMenuItems();
2684 if (!mIsNetworkUp) {
2685 if ( mAlertDialog == null) {
2686 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2687 .setTitle(R.string.loadSuspendedTitle)
2688 .setMessage(R.string.loadSuspended)
2689 .setPositiveButton(R.string.ok, null)
2690 .show();
2691 }
2692 if (view != null) {
2693 view.setNetworkAvailable(false);
2694 }
2695 }
2696
2697 // schedule to check memory condition
2698 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2699 CHECK_MEMORY_INTERVAL);
2700 }
2701
2702 @Override
2703 public void onPageFinished(WebView view, String url) {
2704 // Reset the title and icon in case we stopped a provisional
2705 // load.
2706 resetTitleAndIcon(view);
2707
2708 // Update the lock icon image only once we are done loading
2709 updateLockIconImage(mLockIconType);
2710
2711 // Performance probe
2712 if (false) {
2713 long[] sysCpu = new long[7];
2714 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2715 sysCpu, null)) {
2716 String uiInfo = "UI thread used "
2717 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2718 + " ms";
2719 if (Config.LOGD) {
2720 Log.d(LOGTAG, uiInfo);
2721 }
2722 //The string that gets written to the log
2723 String performanceString = "It took total "
2724 + (SystemClock.uptimeMillis() - mStart)
2725 + " ms clock time to load the page."
2726 + "\nbrowser process used "
2727 + (Process.getElapsedCpuTime() - mProcessStart)
2728 + " ms, user processes used "
2729 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2730 + " ms, kernel used "
2731 + (sysCpu[2] - mSystemStart) * 10
2732 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2733 + " ms and irq took "
2734 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2735 * 10 + " ms, " + uiInfo;
2736 if (Config.LOGD) {
2737 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2738 }
2739 if (url != null) {
2740 // strip the url to maintain consistency
2741 String newUrl = new String(url);
2742 if (newUrl.startsWith("http://www.")) {
2743 newUrl = newUrl.substring(11);
2744 } else if (newUrl.startsWith("http://")) {
2745 newUrl = newUrl.substring(7);
2746 } else if (newUrl.startsWith("https://www.")) {
2747 newUrl = newUrl.substring(12);
2748 } else if (newUrl.startsWith("https://")) {
2749 newUrl = newUrl.substring(8);
2750 }
2751 if (Config.LOGD) {
2752 Log.d(LOGTAG, newUrl + " loaded");
2753 }
2754 /*
2755 if (sWhiteList.contains(newUrl)) {
2756 // The string that gets pushed to the statistcs
2757 // service
2758 performanceString = performanceString
2759 + "\nWebpage: "
2760 + newUrl
2761 + "\nCarrier: "
2762 + android.os.SystemProperties
2763 .get("gsm.sim.operator.alpha");
2764 if (mWebView != null
2765 && mWebView.getContext() != null
2766 && mWebView.getContext().getSystemService(
2767 Context.CONNECTIVITY_SERVICE) != null) {
2768 ConnectivityManager cManager =
2769 (ConnectivityManager) mWebView
2770 .getContext().getSystemService(
2771 Context.CONNECTIVITY_SERVICE);
2772 NetworkInfo nInfo = cManager
2773 .getActiveNetworkInfo();
2774 if (nInfo != null) {
2775 performanceString = performanceString
2776 + "\nNetwork Type: "
2777 + nInfo.getType().toString();
2778 }
2779 }
2780 Checkin.logEvent(mResolver,
2781 Checkin.Events.Tag.WEBPAGE_LOAD,
2782 performanceString);
2783 Log.w(LOGTAG, "pushed to the statistics service");
2784 }
2785 */
2786 }
2787 }
2788 }
2789
2790 if (mInTrace) {
2791 mInTrace = false;
2792 Debug.stopMethodTracing();
2793 }
2794
2795 if (mPageStarted) {
2796 mPageStarted = false;
2797 // pauseWebView() will do nothing and return false if onPause()
2798 // is not called yet.
2799 if (pauseWebView()) {
2800 if (mWakeLock.isHeld()) {
2801 mHandler.removeMessages(RELEASE_WAKELOCK);
2802 mWakeLock.release();
2803 }
2804 }
2805 }
2806
2807 if (mInLoad) {
2808 mInLoad = false;
2809 updateInLoadMenuItems();
2810 }
2811
2812 mHandler.removeMessages(CHECK_MEMORY);
2813 checkMemory();
2814 }
2815
2816 // return true if want to hijack the url to let another app to handle it
2817 @Override
2818 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2819 if (url.startsWith(SCHEME_WTAI)) {
2820 // wtai://wp/mc;number
2821 // number=string(phone-number)
2822 if (url.startsWith(SCHEME_WTAI_MC)) {
2823 Intent intent = new Intent(Intent.ACTION_VIEW,
2824 Uri.parse(WebView.SCHEME_TEL +
2825 url.substring(SCHEME_WTAI_MC.length())));
2826 startActivity(intent);
2827 return true;
2828 }
2829 // wtai://wp/sd;dtmf
2830 // dtmf=string(dialstring)
2831 if (url.startsWith(SCHEME_WTAI_SD)) {
2832 // TODO
2833 // only send when there is active voice connection
2834 return false;
2835 }
2836 // wtai://wp/ap;number;name
2837 // number=string(phone-number)
2838 // name=string
2839 if (url.startsWith(SCHEME_WTAI_AP)) {
2840 // TODO
2841 return false;
2842 }
2843 }
2844
2845 Uri uri;
2846 try {
2847 uri = Uri.parse(url);
2848 } catch (IllegalArgumentException ex) {
2849 return false;
2850 }
2851
2852 // check whether other activities want to handle this url
2853 Intent intent = new Intent(Intent.ACTION_VIEW, uri);
2854 intent.addCategory(Intent.CATEGORY_BROWSABLE);
2855 try {
2856 if (startActivityIfNeeded(intent, -1)) {
2857 return true;
2858 }
2859 } catch (ActivityNotFoundException ex) {
2860 // ignore the error. If no application can handle the URL,
2861 // eg about:blank, assume the browser can handle it.
2862 }
2863
2864 if (mMenuIsDown) {
2865 openTab(url);
2866 closeOptionsMenu();
2867 return true;
2868 }
2869
2870 return false;
2871 }
2872
2873 /**
2874 * Updates the lock icon. This method is called when we discover another
2875 * resource to be loaded for this page (for example, javascript). While
2876 * we update the icon type, we do not update the lock icon itself until
2877 * we are done loading, it is slightly more secure this way.
2878 */
2879 @Override
2880 public void onLoadResource(WebView view, String url) {
2881 if (url != null && url.length() > 0) {
2882 // It is only if the page claims to be secure
2883 // that we may have to update the lock:
2884 if (mLockIconType == LOCK_ICON_SECURE) {
2885 // If NOT a 'safe' url, change the lock to mixed content!
2886 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
2887 mLockIconType = LOCK_ICON_MIXED;
2888 if (Config.LOGV) {
2889 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
2890 " updated lock icon to " + mLockIconType + " due to " + url);
2891 }
2892 }
2893 }
2894 }
2895 }
2896
2897 /**
2898 * Show the dialog, asking the user if they would like to continue after
2899 * an excessive number of HTTP redirects.
2900 */
2901 @Override
2902 public void onTooManyRedirects(WebView view, final Message cancelMsg,
2903 final Message continueMsg) {
2904 new AlertDialog.Builder(BrowserActivity.this)
2905 .setTitle(R.string.browserFrameRedirect)
2906 .setMessage(R.string.browserFrame307Post)
2907 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2908 public void onClick(DialogInterface dialog, int which) {
2909 continueMsg.sendToTarget();
2910 }})
2911 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2912 public void onClick(DialogInterface dialog, int which) {
2913 cancelMsg.sendToTarget();
2914 }})
2915 .setOnCancelListener(new OnCancelListener() {
2916 public void onCancel(DialogInterface dialog) {
2917 cancelMsg.sendToTarget();
2918 }})
2919 .show();
2920 }
2921
2922 /**
2923 * Show a dialog informing the user of the network error reported by
2924 * WebCore.
2925 */
2926 @Override
2927 public void onReceivedError(WebView view, int errorCode,
2928 String description, String failingUrl) {
2929 if (errorCode != EventHandler.ERROR_LOOKUP &&
2930 errorCode != EventHandler.ERROR_CONNECT &&
2931 errorCode != EventHandler.ERROR_BAD_URL &&
2932 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
2933 errorCode != EventHandler.FILE_ERROR) {
2934 new AlertDialog.Builder(BrowserActivity.this)
2935 .setTitle((errorCode == EventHandler.FILE_NOT_FOUND_ERROR) ?
2936 R.string.browserFrameFileErrorLabel :
2937 R.string.browserFrameNetworkErrorLabel)
2938 .setMessage(description)
2939 .setPositiveButton(R.string.ok, null)
2940 .show();
2941 }
2942 Log.e(LOGTAG, "onReceivedError code:"+errorCode+" "+description);
2943
2944 // We need to reset the title after an error.
2945 resetTitleAndRevertLockIcon();
2946 }
2947
2948 /**
2949 * Check with the user if it is ok to resend POST data as the page they
2950 * are trying to navigate to is the result of a POST.
2951 */
2952 @Override
2953 public void onFormResubmission(WebView view, final Message dontResend,
2954 final Message resend) {
2955 new AlertDialog.Builder(BrowserActivity.this)
2956 .setTitle(R.string.browserFrameFormResubmitLabel)
2957 .setMessage(R.string.browserFrameFormResubmitMessage)
2958 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
2959 public void onClick(DialogInterface dialog, int which) {
2960 resend.sendToTarget();
2961 }})
2962 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
2963 public void onClick(DialogInterface dialog, int which) {
2964 dontResend.sendToTarget();
2965 }})
2966 .setOnCancelListener(new OnCancelListener() {
2967 public void onCancel(DialogInterface dialog) {
2968 dontResend.sendToTarget();
2969 }})
2970 .show();
2971 }
2972
2973 /**
2974 * Insert the url into the visited history database.
2975 * @param url The url to be inserted.
2976 * @param isReload True if this url is being reloaded.
2977 * FIXME: Not sure what to do when reloading the page.
2978 */
2979 @Override
2980 public void doUpdateVisitedHistory(WebView view, String url,
2981 boolean isReload) {
2982 if (url.regionMatches(true, 0, "about:", 0, 6)) {
2983 return;
2984 }
2985 Browser.updateVisitedHistory(mResolver, url, true);
2986 WebIconDatabase.getInstance().retainIconForPageUrl(url);
2987 }
2988
2989 /**
2990 * Displays SSL error(s) dialog to the user.
2991 */
2992 @Override
2993 public void onReceivedSslError(
2994 final WebView view, final SslErrorHandler handler, final SslError error) {
2995
2996 if (mSettings.showSecurityWarnings()) {
2997 final LayoutInflater factory =
2998 LayoutInflater.from(BrowserActivity.this);
2999 final View warningsView =
3000 factory.inflate(R.layout.ssl_warnings, null);
3001 final LinearLayout placeholder =
3002 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3003
3004 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3005 LinearLayout ll = (LinearLayout)factory
3006 .inflate(R.layout.ssl_warning, null);
3007 ((TextView)ll.findViewById(R.id.warning))
3008 .setText(R.string.ssl_untrusted);
3009 placeholder.addView(ll);
3010 }
3011
3012 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3013 LinearLayout ll = (LinearLayout)factory
3014 .inflate(R.layout.ssl_warning, null);
3015 ((TextView)ll.findViewById(R.id.warning))
3016 .setText(R.string.ssl_mismatch);
3017 placeholder.addView(ll);
3018 }
3019
3020 if (error.hasError(SslError.SSL_EXPIRED)) {
3021 LinearLayout ll = (LinearLayout)factory
3022 .inflate(R.layout.ssl_warning, null);
3023 ((TextView)ll.findViewById(R.id.warning))
3024 .setText(R.string.ssl_expired);
3025 placeholder.addView(ll);
3026 }
3027
3028 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3029 LinearLayout ll = (LinearLayout)factory
3030 .inflate(R.layout.ssl_warning, null);
3031 ((TextView)ll.findViewById(R.id.warning))
3032 .setText(R.string.ssl_not_yet_valid);
3033 placeholder.addView(ll);
3034 }
3035
3036 new AlertDialog.Builder(BrowserActivity.this)
3037 .setTitle(R.string.security_warning)
3038 .setIcon(android.R.drawable.ic_dialog_alert)
3039 .setView(warningsView)
3040 .setPositiveButton(R.string.ssl_continue,
3041 new DialogInterface.OnClickListener() {
3042 public void onClick(DialogInterface dialog, int whichButton) {
3043 handler.proceed();
3044 }
3045 })
3046 .setNeutralButton(R.string.view_certificate,
3047 new DialogInterface.OnClickListener() {
3048 public void onClick(DialogInterface dialog, int whichButton) {
3049 showSSLCertificateOnError(view, handler, error);
3050 }
3051 })
3052 .setNegativeButton(R.string.cancel,
3053 new DialogInterface.OnClickListener() {
3054 public void onClick(DialogInterface dialog, int whichButton) {
3055 handler.cancel();
3056 BrowserActivity.this.resetTitleAndRevertLockIcon();
3057 }
3058 })
3059 .setOnCancelListener(
3060 new DialogInterface.OnCancelListener() {
3061 public void onCancel(DialogInterface dialog) {
3062 handler.cancel();
3063 BrowserActivity.this.resetTitleAndRevertLockIcon();
3064 }
3065 })
3066 .show();
3067 } else {
3068 handler.proceed();
3069 }
3070 }
3071
3072 /**
3073 * Handles an HTTP authentication request.
3074 *
3075 * @param handler The authentication handler
3076 * @param host The host
3077 * @param realm The realm
3078 */
3079 @Override
3080 public void onReceivedHttpAuthRequest(WebView view,
3081 final HttpAuthHandler handler, final String host, final String realm) {
3082 String username = null;
3083 String password = null;
3084
3085 boolean reuseHttpAuthUsernamePassword =
3086 handler.useHttpAuthUsernamePassword();
3087
3088 if (reuseHttpAuthUsernamePassword &&
3089 (mTabControl.getCurrentWebView() != null)) {
3090 String[] credentials =
3091 mTabControl.getCurrentWebView()
3092 .getHttpAuthUsernamePassword(host, realm);
3093 if (credentials != null && credentials.length == 2) {
3094 username = credentials[0];
3095 password = credentials[1];
3096 }
3097 }
3098
3099 if (username != null && password != null) {
3100 handler.proceed(username, password);
3101 } else {
3102 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3103 }
3104 }
3105
3106 @Override
3107 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3108 if (mMenuIsDown) {
3109 // only check shortcut key when MENU is held
3110 return getWindow().isShortcutKey(event.getKeyCode(), event);
3111 } else {
3112 return false;
3113 }
3114 }
3115
3116 @Override
3117 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3118 if (view != mTabControl.getCurrentTopWebView()) {
3119 return;
3120 }
3121 if (event.isDown()) {
3122 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3123 } else {
3124 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3125 }
3126 }
3127 };
3128
3129 //--------------------------------------------------------------------------
3130 // WebChromeClient implementation
3131 //--------------------------------------------------------------------------
3132
3133 /* package */ WebChromeClient getWebChromeClient() {
3134 return mWebChromeClient;
3135 }
3136
3137 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3138 // Helper method to create a new tab or sub window.
3139 private void createWindow(final boolean dialog, final Message msg) {
3140 if (dialog) {
3141 mTabControl.createSubWindow();
3142 final TabControl.Tab t = mTabControl.getCurrentTab();
3143 attachSubWindow(t);
3144 WebView.WebViewTransport transport =
3145 (WebView.WebViewTransport) msg.obj;
3146 transport.setWebView(t.getSubWebView());
3147 msg.sendToTarget();
3148 } else {
3149 final TabControl.Tab parent = mTabControl.getCurrentTab();
3150 // openTabAndShow will dispatch the message after creating the
3151 // new WebView. This will prevent another request from coming
3152 // in during the animation.
3153 openTabAndShow(null, msg, false);
3154 parent.addChildTab(mTabControl.getCurrentTab());
3155 WebView.WebViewTransport transport =
3156 (WebView.WebViewTransport) msg.obj;
3157 transport.setWebView(mTabControl.getCurrentWebView());
3158 }
3159 }
3160
3161 @Override
3162 public boolean onCreateWindow(WebView view, final boolean dialog,
3163 final boolean userGesture, final Message resultMsg) {
3164 // Ignore these requests during tab animations or if the tab
3165 // overview is showing.
3166 if (mAnimationCount > 0 || mTabOverview != null) {
3167 return false;
3168 }
3169 // Short-circuit if we can't create any more tabs or sub windows.
3170 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3171 new AlertDialog.Builder(BrowserActivity.this)
3172 .setTitle(R.string.too_many_subwindows_dialog_title)
3173 .setIcon(android.R.drawable.ic_dialog_alert)
3174 .setMessage(R.string.too_many_subwindows_dialog_message)
3175 .setPositiveButton(R.string.ok, null)
3176 .show();
3177 return false;
3178 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3179 new AlertDialog.Builder(BrowserActivity.this)
3180 .setTitle(R.string.too_many_windows_dialog_title)
3181 .setIcon(android.R.drawable.ic_dialog_alert)
3182 .setMessage(R.string.too_many_windows_dialog_message)
3183 .setPositiveButton(R.string.ok, null)
3184 .show();
3185 return false;
3186 }
3187
3188 // Short-circuit if this was a user gesture.
3189 if (userGesture) {
3190 // createWindow will call openTabAndShow for new Windows and
3191 // that will call tabPicker which will increment
3192 // mAnimationCount.
3193 createWindow(dialog, resultMsg);
3194 return true;
3195 }
3196
3197 // Allow the popup and create the appropriate window.
3198 final AlertDialog.OnClickListener allowListener =
3199 new AlertDialog.OnClickListener() {
3200 public void onClick(DialogInterface d,
3201 int which) {
3202 // Same comment as above for setting
3203 // mAnimationCount.
3204 createWindow(dialog, resultMsg);
3205 // Since we incremented mAnimationCount while the
3206 // dialog was up, we have to decrement it here.
3207 mAnimationCount--;
3208 }
3209 };
3210
3211 // Block the popup by returning a null WebView.
3212 final AlertDialog.OnClickListener blockListener =
3213 new AlertDialog.OnClickListener() {
3214 public void onClick(DialogInterface d, int which) {
3215 resultMsg.sendToTarget();
3216 // We are not going to trigger an animation so
3217 // unblock keys and animation requests.
3218 mAnimationCount--;
3219 }
3220 };
3221
3222 // Build a confirmation dialog to display to the user.
3223 final AlertDialog d =
3224 new AlertDialog.Builder(BrowserActivity.this)
3225 .setTitle(R.string.attention)
3226 .setIcon(android.R.drawable.ic_dialog_alert)
3227 .setMessage(R.string.popup_window_attempt)
3228 .setPositiveButton(R.string.allow, allowListener)
3229 .setNegativeButton(R.string.block, blockListener)
3230 .setCancelable(false)
3231 .create();
3232
3233 // Show the confirmation dialog.
3234 d.show();
3235 // We want to increment mAnimationCount here to prevent a
3236 // potential race condition. If the user allows a pop-up from a
3237 // site and that pop-up then triggers another pop-up, it is
3238 // possible to get the BACK key between here and when the dialog
3239 // appears.
3240 mAnimationCount++;
3241 return true;
3242 }
3243
3244 @Override
3245 public void onCloseWindow(WebView window) {
3246 final int currentIndex = mTabControl.getCurrentIndex();
3247 final TabControl.Tab parent =
3248 mTabControl.getCurrentTab().getParentTab();
3249 if (parent != null) {
3250 // JavaScript can only close popup window.
3251 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3252 }
3253 }
3254
3255 @Override
3256 public void onProgressChanged(WebView view, int newProgress) {
3257 // Block progress updates to the title bar while the tab overview
3258 // is animating or being displayed.
3259 if (mAnimationCount == 0 && mTabOverview == null) {
3260 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3261 newProgress * 100);
3262 }
3263
3264 if (newProgress == 100) {
3265 // onProgressChanged() is called for sub-frame too while
3266 // onPageFinished() is only called for the main frame. sync
3267 // cookie and cache promptly here.
3268 CookieSyncManager.getInstance().sync();
3269 }
3270 }
3271
3272 @Override
3273 public void onReceivedTitle(WebView view, String title) {
3274 String url = view.getOriginalUrl();
3275
3276 // here, if url is null, we want to reset the title
3277 setUrlTitle(url, title);
3278
3279 if (url == null ||
3280 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3281 return;
3282 }
3283 if (url.startsWith("http://www.")) {
3284 url = url.substring(11);
3285 } else if (url.startsWith("http://")) {
3286 url = url.substring(4);
3287 }
3288 try {
3289 url = "%" + url;
3290 String [] selArgs = new String[] { url };
3291
3292 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3293 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3294 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3295 Browser.HISTORY_PROJECTION, where, selArgs, null);
3296 if (c.moveToFirst()) {
3297 if (Config.LOGV) {
3298 Log.v(LOGTAG, "updating cursor");
3299 }
3300 // Current implementation of database only has one entry per
3301 // url.
3302 int titleIndex =
3303 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3304 c.updateString(titleIndex, title);
3305 c.commitUpdates();
3306 }
3307 c.close();
3308 } catch (IllegalStateException e) {
3309 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3310 } catch (SQLiteException ex) {
3311 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3312 }
3313 }
3314
3315 @Override
3316 public void onReceivedIcon(WebView view, Bitmap icon) {
3317 updateIcon(view.getUrl(), icon);
3318 }
3319 };
3320
3321 /**
3322 * Notify the host application a download should be done, or that
3323 * the data should be streamed if a streaming viewer is available.
3324 * @param url The full url to the content that should be downloaded
3325 * @param contentDisposition Content-disposition http header, if
3326 * present.
3327 * @param mimetype The mimetype of the content reported by the server
3328 * @param contentLength The file size reported by the server
3329 */
3330 public void onDownloadStart(String url, String userAgent,
3331 String contentDisposition, String mimetype, long contentLength) {
3332 // if we're dealing wih A/V content that's not explicitly marked
3333 // for download, check if it's streamable.
3334 if (contentDisposition == null
3335 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3336 // query the package manager to see if there's a registered handler
3337 // that matches.
3338 Intent intent = new Intent(Intent.ACTION_VIEW);
3339 intent.setDataAndType(Uri.parse(url), mimetype);
3340 if (getPackageManager().resolveActivity(intent,
3341 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3342 // someone knows how to handle this mime type with this scheme, don't download.
3343 try {
3344 startActivity(intent);
3345 return;
3346 } catch (ActivityNotFoundException ex) {
3347 if (Config.LOGD) {
3348 Log.d(LOGTAG, "activity not found for " + mimetype
3349 + " over " + Uri.parse(url).getScheme(), ex);
3350 }
3351 // Best behavior is to fall back to a download in this case
3352 }
3353 }
3354 }
3355 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3356 }
3357
3358 /**
3359 * Notify the host application a download should be done, even if there
3360 * is a streaming viewer available for thise type.
3361 * @param url The full url to the content that should be downloaded
3362 * @param contentDisposition Content-disposition http header, if
3363 * present.
3364 * @param mimetype The mimetype of the content reported by the server
3365 * @param contentLength The file size reported by the server
3366 */
3367 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3368 String contentDisposition, String mimetype, long contentLength) {
3369
3370 String filename = URLUtil.guessFileName(url,
3371 contentDisposition, mimetype);
3372
3373 // Check to see if we have an SDCard
3374 String status = Environment.getExternalStorageState();
3375 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3376 int title;
3377 String msg;
3378
3379 // Check to see if the SDCard is busy, same as the music app
3380 if (status.equals(Environment.MEDIA_SHARED)) {
3381 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3382 title = R.string.download_sdcard_busy_dlg_title;
3383 } else {
3384 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3385 title = R.string.download_no_sdcard_dlg_title;
3386 }
3387
3388 new AlertDialog.Builder(this)
3389 .setTitle(title)
3390 .setIcon(android.R.drawable.ic_dialog_alert)
3391 .setMessage(msg)
3392 .setPositiveButton(R.string.ok, null)
3393 .show();
3394 return;
3395 }
3396
3397 // java.net.URI is a lot stricter than KURL so we have to undo
3398 // KURL's percent-encoding and redo the encoding using java.net.URI.
3399 URI uri = null;
3400 try {
3401 // Undo the percent-encoding that KURL may have done.
3402 String newUrl = new String(URLUtil.decode(url.getBytes()));
3403 // Parse the url into pieces
3404 WebAddress w = new WebAddress(newUrl);
3405 String frag = null;
3406 String query = null;
3407 String path = w.mPath;
3408 // Break the path into path, query, and fragment
3409 if (path.length() > 0) {
3410 // Strip the fragment
3411 int idx = path.lastIndexOf('#');
3412 if (idx != -1) {
3413 frag = path.substring(idx + 1);
3414 path = path.substring(0, idx);
3415 }
3416 idx = path.lastIndexOf('?');
3417 if (idx != -1) {
3418 query = path.substring(idx + 1);
3419 path = path.substring(0, idx);
3420 }
3421 }
3422 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3423 query, frag);
3424 } catch (Exception e) {
3425 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3426 return;
3427 }
3428
3429 // XXX: Have to use the old url since the cookies were stored using the
3430 // old percent-encoded url.
3431 String cookies = CookieManager.getInstance().getCookie(url);
3432
3433 ContentValues values = new ContentValues();
3434 values.put(Downloads.URI, uri.toString());
3435 values.put(Downloads.COOKIE_DATA, cookies);
3436 values.put(Downloads.USER_AGENT, userAgent);
3437 values.put(Downloads.NOTIFICATION_PACKAGE,
3438 getPackageName());
3439 values.put(Downloads.NOTIFICATION_CLASS,
3440 BrowserDownloadPage.class.getCanonicalName());
3441 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3442 values.put(Downloads.MIMETYPE, mimetype);
3443 values.put(Downloads.FILENAME_HINT, filename);
3444 values.put(Downloads.DESCRIPTION, uri.getHost());
3445 if (contentLength > 0) {
3446 values.put(Downloads.TOTAL_BYTES, contentLength);
3447 }
3448 if (mimetype == null) {
3449 // We must have long pressed on a link or image to download it. We
3450 // are not sure of the mimetype in this case, so do a head request
3451 new FetchUrlMimeType(this).execute(values);
3452 } else {
3453 final Uri contentUri =
3454 getContentResolver().insert(Downloads.CONTENT_URI, values);
3455 viewDownloads(contentUri);
3456 }
3457
3458 }
3459
3460 /**
3461 * Resets the lock icon. This method is called when we start a new load and
3462 * know the url to be loaded.
3463 */
3464 private void resetLockIcon(String url) {
3465 // Save the lock-icon state (we revert to it if the load gets cancelled)
3466 saveLockIcon();
3467
3468 mLockIconType = LOCK_ICON_UNSECURE;
3469 if (URLUtil.isHttpsUrl(url)) {
3470 mLockIconType = LOCK_ICON_SECURE;
3471 if (Config.LOGV) {
3472 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3473 " reset lock icon to " + mLockIconType);
3474 }
3475 }
3476
3477 updateLockIconImage(LOCK_ICON_UNSECURE);
3478 }
3479
3480 /**
3481 * Resets the lock icon. This method is called when the icon needs to be
3482 * reset but we do not know whether we are loading a secure or not secure
3483 * page.
3484 */
3485 private void resetLockIcon() {
3486 // Save the lock-icon state (we revert to it if the load gets cancelled)
3487 saveLockIcon();
3488
3489 mLockIconType = LOCK_ICON_UNSECURE;
3490
3491 if (Config.LOGV) {
3492 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3493 " reset lock icon to " + mLockIconType);
3494 }
3495
3496 updateLockIconImage(LOCK_ICON_UNSECURE);
3497 }
3498
3499 /**
3500 * Updates the lock-icon image in the title-bar.
3501 */
3502 private void updateLockIconImage(int lockIconType) {
3503 Drawable d = null;
3504 if (lockIconType == LOCK_ICON_SECURE) {
3505 d = mSecLockIcon;
3506 } else if (lockIconType == LOCK_ICON_MIXED) {
3507 d = mMixLockIcon;
3508 }
3509 // If the tab overview is animating or being shown, do not update the
3510 // lock icon.
3511 if (mAnimationCount == 0 && mTabOverview == null) {
3512 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3513 }
3514 }
3515
3516 /**
3517 * Displays a page-info dialog.
3518 * @param tab The tab to show info about
3519 * @param fromShowSSLCertificateOnError The flag that indicates whether
3520 * this dialog was opened from the SSL-certificate-on-error dialog or
3521 * not. This is important, since we need to know whether to return to
3522 * the parent dialog or simply dismiss.
3523 */
3524 private void showPageInfo(final TabControl.Tab tab,
3525 final boolean fromShowSSLCertificateOnError) {
3526 final LayoutInflater factory = LayoutInflater
3527 .from(this);
3528
3529 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3530
3531 final WebView view = tab.getWebView();
3532
3533 String url = null;
3534 String title = null;
3535
3536 if (view == null) {
3537 url = tab.getUrl();
3538 title = tab.getTitle();
3539 } else if (view == mTabControl.getCurrentWebView()) {
3540 // Use the cached title and url if this is the current WebView
3541 url = mUrl;
3542 title = mTitle;
3543 } else {
3544 url = view.getUrl();
3545 title = view.getTitle();
3546 }
3547
3548 if (url == null) {
3549 url = "";
3550 }
3551 if (title == null) {
3552 title = "";
3553 }
3554
3555 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3556 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3557
3558 mPageInfoView = tab;
3559 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3560
3561 AlertDialog.Builder alertDialogBuilder =
3562 new AlertDialog.Builder(this)
3563 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3564 .setView(pageInfoView)
3565 .setPositiveButton(
3566 R.string.ok,
3567 new DialogInterface.OnClickListener() {
3568 public void onClick(DialogInterface dialog,
3569 int whichButton) {
3570 mPageInfoDialog = null;
3571 mPageInfoView = null;
3572 mPageInfoFromShowSSLCertificateOnError = null;
3573
3574 // if we came here from the SSL error dialog
3575 if (fromShowSSLCertificateOnError) {
3576 // go back to the SSL error dialog
3577 showSSLCertificateOnError(
3578 mSSLCertificateOnErrorView,
3579 mSSLCertificateOnErrorHandler,
3580 mSSLCertificateOnErrorError);
3581 }
3582 }
3583 })
3584 .setOnCancelListener(
3585 new DialogInterface.OnCancelListener() {
3586 public void onCancel(DialogInterface dialog) {
3587 mPageInfoDialog = null;
3588 mPageInfoView = null;
3589 mPageInfoFromShowSSLCertificateOnError = null;
3590
3591 // if we came here from the SSL error dialog
3592 if (fromShowSSLCertificateOnError) {
3593 // go back to the SSL error dialog
3594 showSSLCertificateOnError(
3595 mSSLCertificateOnErrorView,
3596 mSSLCertificateOnErrorHandler,
3597 mSSLCertificateOnErrorError);
3598 }
3599 }
3600 });
3601
3602 // if we have a main top-level page SSL certificate set or a certificate
3603 // error
3604 if (fromShowSSLCertificateOnError ||
3605 (view != null && view.getCertificate() != null)) {
3606 // add a 'View Certificate' button
3607 alertDialogBuilder.setNeutralButton(
3608 R.string.view_certificate,
3609 new DialogInterface.OnClickListener() {
3610 public void onClick(DialogInterface dialog,
3611 int whichButton) {
3612 mPageInfoDialog = null;
3613 mPageInfoView = null;
3614 mPageInfoFromShowSSLCertificateOnError = null;
3615
3616 // if we came here from the SSL error dialog
3617 if (fromShowSSLCertificateOnError) {
3618 // go back to the SSL error dialog
3619 showSSLCertificateOnError(
3620 mSSLCertificateOnErrorView,
3621 mSSLCertificateOnErrorHandler,
3622 mSSLCertificateOnErrorError);
3623 } else {
3624 // otherwise, display the top-most certificate from
3625 // the chain
3626 if (view.getCertificate() != null) {
3627 showSSLCertificate(tab);
3628 }
3629 }
3630 }
3631 });
3632 }
3633
3634 mPageInfoDialog = alertDialogBuilder.show();
3635 }
3636
3637 /**
3638 * Displays the main top-level page SSL certificate dialog
3639 * (accessible from the Page-Info dialog).
3640 * @param tab The tab to show certificate for.
3641 */
3642 private void showSSLCertificate(final TabControl.Tab tab) {
3643 final View certificateView =
3644 inflateCertificateView(tab.getWebView().getCertificate());
3645 if (certificateView == null) {
3646 return;
3647 }
3648
3649 LayoutInflater factory = LayoutInflater.from(this);
3650
3651 final LinearLayout placeholder =
3652 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3653
3654 LinearLayout ll = (LinearLayout) factory.inflate(
3655 R.layout.ssl_success, placeholder);
3656 ((TextView)ll.findViewById(R.id.success))
3657 .setText(R.string.ssl_certificate_is_valid);
3658
3659 mSSLCertificateView = tab;
3660 mSSLCertificateDialog =
3661 new AlertDialog.Builder(this)
3662 .setTitle(R.string.ssl_certificate).setIcon(
3663 R.drawable.ic_dialog_browser_certificate_secure)
3664 .setView(certificateView)
3665 .setPositiveButton(R.string.ok,
3666 new DialogInterface.OnClickListener() {
3667 public void onClick(DialogInterface dialog,
3668 int whichButton) {
3669 mSSLCertificateDialog = null;
3670 mSSLCertificateView = null;
3671
3672 showPageInfo(tab, false);
3673 }
3674 })
3675 .setOnCancelListener(
3676 new DialogInterface.OnCancelListener() {
3677 public void onCancel(DialogInterface dialog) {
3678 mSSLCertificateDialog = null;
3679 mSSLCertificateView = null;
3680
3681 showPageInfo(tab, false);
3682 }
3683 })
3684 .show();
3685 }
3686
3687 /**
3688 * Displays the SSL error certificate dialog.
3689 * @param view The target web-view.
3690 * @param handler The SSL error handler responsible for cancelling the
3691 * connection that resulted in an SSL error or proceeding per user request.
3692 * @param error The SSL error object.
3693 */
3694 private void showSSLCertificateOnError(
3695 final WebView view, final SslErrorHandler handler, final SslError error) {
3696
3697 final View certificateView =
3698 inflateCertificateView(error.getCertificate());
3699 if (certificateView == null) {
3700 return;
3701 }
3702
3703 LayoutInflater factory = LayoutInflater.from(this);
3704
3705 final LinearLayout placeholder =
3706 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3707
3708 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3709 LinearLayout ll = (LinearLayout)factory
3710 .inflate(R.layout.ssl_warning, placeholder);
3711 ((TextView)ll.findViewById(R.id.warning))
3712 .setText(R.string.ssl_untrusted);
3713 }
3714
3715 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3716 LinearLayout ll = (LinearLayout)factory
3717 .inflate(R.layout.ssl_warning, placeholder);
3718 ((TextView)ll.findViewById(R.id.warning))
3719 .setText(R.string.ssl_mismatch);
3720 }
3721
3722 if (error.hasError(SslError.SSL_EXPIRED)) {
3723 LinearLayout ll = (LinearLayout)factory
3724 .inflate(R.layout.ssl_warning, placeholder);
3725 ((TextView)ll.findViewById(R.id.warning))
3726 .setText(R.string.ssl_expired);
3727 }
3728
3729 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3730 LinearLayout ll = (LinearLayout)factory
3731 .inflate(R.layout.ssl_warning, placeholder);
3732 ((TextView)ll.findViewById(R.id.warning))
3733 .setText(R.string.ssl_not_yet_valid);
3734 }
3735
3736 mSSLCertificateOnErrorHandler = handler;
3737 mSSLCertificateOnErrorView = view;
3738 mSSLCertificateOnErrorError = error;
3739 mSSLCertificateOnErrorDialog =
3740 new AlertDialog.Builder(this)
3741 .setTitle(R.string.ssl_certificate).setIcon(
3742 R.drawable.ic_dialog_browser_certificate_partially_secure)
3743 .setView(certificateView)
3744 .setPositiveButton(R.string.ok,
3745 new DialogInterface.OnClickListener() {
3746 public void onClick(DialogInterface dialog,
3747 int whichButton) {
3748 mSSLCertificateOnErrorDialog = null;
3749 mSSLCertificateOnErrorView = null;
3750 mSSLCertificateOnErrorHandler = null;
3751 mSSLCertificateOnErrorError = null;
3752
3753 mWebViewClient.onReceivedSslError(
3754 view, handler, error);
3755 }
3756 })
3757 .setNeutralButton(R.string.page_info_view,
3758 new DialogInterface.OnClickListener() {
3759 public void onClick(DialogInterface dialog,
3760 int whichButton) {
3761 mSSLCertificateOnErrorDialog = null;
3762
3763 // do not clear the dialog state: we will
3764 // need to show the dialog again once the
3765 // user is done exploring the page-info details
3766
3767 showPageInfo(mTabControl.getTabFromView(view),
3768 true);
3769 }
3770 })
3771 .setOnCancelListener(
3772 new DialogInterface.OnCancelListener() {
3773 public void onCancel(DialogInterface dialog) {
3774 mSSLCertificateOnErrorDialog = null;
3775 mSSLCertificateOnErrorView = null;
3776 mSSLCertificateOnErrorHandler = null;
3777 mSSLCertificateOnErrorError = null;
3778
3779 mWebViewClient.onReceivedSslError(
3780 view, handler, error);
3781 }
3782 })
3783 .show();
3784 }
3785
3786 /**
3787 * Inflates the SSL certificate view (helper method).
3788 * @param certificate The SSL certificate.
3789 * @return The resultant certificate view with issued-to, issued-by,
3790 * issued-on, expires-on, and possibly other fields set.
3791 * If the input certificate is null, returns null.
3792 */
3793 private View inflateCertificateView(SslCertificate certificate) {
3794 if (certificate == null) {
3795 return null;
3796 }
3797
3798 LayoutInflater factory = LayoutInflater.from(this);
3799
3800 View certificateView = factory.inflate(
3801 R.layout.ssl_certificate, null);
3802
3803 // issued to:
3804 SslCertificate.DName issuedTo = certificate.getIssuedTo();
3805 if (issuedTo != null) {
3806 ((TextView) certificateView.findViewById(R.id.to_common))
3807 .setText(issuedTo.getCName());
3808 ((TextView) certificateView.findViewById(R.id.to_org))
3809 .setText(issuedTo.getOName());
3810 ((TextView) certificateView.findViewById(R.id.to_org_unit))
3811 .setText(issuedTo.getUName());
3812 }
3813
3814 // issued by:
3815 SslCertificate.DName issuedBy = certificate.getIssuedBy();
3816 if (issuedBy != null) {
3817 ((TextView) certificateView.findViewById(R.id.by_common))
3818 .setText(issuedBy.getCName());
3819 ((TextView) certificateView.findViewById(R.id.by_org))
3820 .setText(issuedBy.getOName());
3821 ((TextView) certificateView.findViewById(R.id.by_org_unit))
3822 .setText(issuedBy.getUName());
3823 }
3824
3825 // issued on:
3826 String issuedOn = reformatCertificateDate(
3827 certificate.getValidNotBefore());
3828 ((TextView) certificateView.findViewById(R.id.issued_on))
3829 .setText(issuedOn);
3830
3831 // expires on:
3832 String expiresOn = reformatCertificateDate(
3833 certificate.getValidNotAfter());
3834 ((TextView) certificateView.findViewById(R.id.expires_on))
3835 .setText(expiresOn);
3836
3837 return certificateView;
3838 }
3839
3840 /**
3841 * Re-formats the certificate date (Date.toString()) string to
3842 * a properly localized date string.
3843 * @return Properly localized version of the certificate date string and
3844 * the original certificate date string if fails to localize.
3845 * If the original string is null, returns an empty string "".
3846 */
3847 private String reformatCertificateDate(String certificateDate) {
3848 String reformattedDate = null;
3849
3850 if (certificateDate != null) {
3851 Date date = null;
3852 try {
3853 date = java.text.DateFormat.getInstance().parse(certificateDate);
3854 } catch (ParseException e) {
3855 date = null;
3856 }
3857
3858 if (date != null) {
3859 reformattedDate =
3860 DateFormat.getDateFormat(this).format(date);
3861 }
3862 }
3863
3864 return reformattedDate != null ? reformattedDate :
3865 (certificateDate != null ? certificateDate : "");
3866 }
3867
3868 /**
3869 * Displays an http-authentication dialog.
3870 */
3871 private void showHttpAuthentication(final HttpAuthHandler handler,
3872 final String host, final String realm, final String title,
3873 final String name, final String password, int focusId) {
3874 LayoutInflater factory = LayoutInflater.from(this);
3875 final View v = factory
3876 .inflate(R.layout.http_authentication, null);
3877 if (name != null) {
3878 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
3879 }
3880 if (password != null) {
3881 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
3882 }
3883
3884 String titleText = title;
3885 if (titleText == null) {
3886 titleText = getText(R.string.sign_in_to).toString().replace(
3887 "%s1", host).replace("%s2", realm);
3888 }
3889
3890 mHttpAuthHandler = handler;
3891 AlertDialog dialog = new AlertDialog.Builder(this)
3892 .setTitle(titleText)
3893 .setIcon(android.R.drawable.ic_dialog_alert)
3894 .setView(v)
3895 .setPositiveButton(R.string.action,
3896 new DialogInterface.OnClickListener() {
3897 public void onClick(DialogInterface dialog,
3898 int whichButton) {
3899 String nm = ((EditText) v
3900 .findViewById(R.id.username_edit))
3901 .getText().toString();
3902 String pw = ((EditText) v
3903 .findViewById(R.id.password_edit))
3904 .getText().toString();
3905 BrowserActivity.this.setHttpAuthUsernamePassword
3906 (host, realm, nm, pw);
3907 handler.proceed(nm, pw);
3908 mHttpAuthenticationDialog = null;
3909 mHttpAuthHandler = null;
3910 }})
3911 .setNegativeButton(R.string.cancel,
3912 new DialogInterface.OnClickListener() {
3913 public void onClick(DialogInterface dialog,
3914 int whichButton) {
3915 handler.cancel();
3916 BrowserActivity.this.resetTitleAndRevertLockIcon();
3917 mHttpAuthenticationDialog = null;
3918 mHttpAuthHandler = null;
3919 }})
3920 .setOnCancelListener(new DialogInterface.OnCancelListener() {
3921 public void onCancel(DialogInterface dialog) {
3922 handler.cancel();
3923 BrowserActivity.this.resetTitleAndRevertLockIcon();
3924 mHttpAuthenticationDialog = null;
3925 mHttpAuthHandler = null;
3926 }})
3927 .create();
3928 // Make the IME appear when the dialog is displayed if applicable.
3929 dialog.getWindow().setSoftInputMode(
3930 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
3931 dialog.show();
3932 if (focusId != 0) {
3933 dialog.findViewById(focusId).requestFocus();
3934 } else {
3935 v.findViewById(R.id.username_edit).requestFocus();
3936 }
3937 mHttpAuthenticationDialog = dialog;
3938 }
3939
3940 public int getProgress() {
3941 WebView w = mTabControl.getCurrentWebView();
3942 if (w != null) {
3943 return w.getProgress();
3944 } else {
3945 return 100;
3946 }
3947 }
3948
3949 /**
3950 * Set HTTP authentication password.
3951 *
3952 * @param host The host for the password
3953 * @param realm The realm for the password
3954 * @param username The username for the password. If it is null, it means
3955 * password can't be saved.
3956 * @param password The password
3957 */
3958 public void setHttpAuthUsernamePassword(String host, String realm,
3959 String username,
3960 String password) {
3961 WebView w = mTabControl.getCurrentWebView();
3962 if (w != null) {
3963 w.setHttpAuthUsernamePassword(host, realm, username, password);
3964 }
3965 }
3966
3967 /**
3968 * connectivity manager says net has come or gone... inform the user
3969 * @param up true if net has come up, false if net has gone down
3970 */
3971 public void onNetworkToggle(boolean up) {
3972 if (up == mIsNetworkUp) {
3973 return;
3974 } else if (up) {
3975 mIsNetworkUp = true;
3976 if (mAlertDialog != null) {
3977 mAlertDialog.cancel();
3978 mAlertDialog = null;
3979 }
3980 } else {
3981 mIsNetworkUp = false;
3982 if (mInLoad && mAlertDialog == null) {
3983 mAlertDialog = new AlertDialog.Builder(this)
3984 .setTitle(R.string.loadSuspendedTitle)
3985 .setMessage(R.string.loadSuspended)
3986 .setPositiveButton(R.string.ok, null)
3987 .show();
3988 }
3989 }
3990 WebView w = mTabControl.getCurrentWebView();
3991 if (w != null) {
3992 w.setNetworkAvailable(up);
3993 }
3994 }
3995
3996 @Override
3997 protected void onActivityResult(int requestCode, int resultCode,
3998 Intent intent) {
3999 switch (requestCode) {
4000 case COMBO_PAGE:
4001 if (resultCode == RESULT_OK && intent != null) {
4002 String data = intent.getAction();
4003 Bundle extras = intent.getExtras();
4004 if (extras != null && extras.getBoolean("new_window", false)) {
4005 openTab(data);
4006 } else {
4007 final TabControl.Tab currentTab =
4008 mTabControl.getCurrentTab();
4009 // If the Window overview is up and we are not in the
4010 // middle of an animation, animate away from it to the
4011 // current tab.
4012 if (mTabOverview != null && mAnimationCount == 0) {
4013 sendAnimateFromOverview(currentTab, false, data,
4014 TAB_OVERVIEW_DELAY, null);
4015 } else {
4016 dismissSubWindow(currentTab);
4017 if (data != null && data.length() != 0) {
4018 getTopWindow().loadUrl(data);
4019 }
4020 }
4021 }
4022 }
4023 break;
4024 default:
4025 break;
4026 }
4027 getTopWindow().requestFocus();
4028 }
4029
4030 /*
4031 * This method is called as a result of the user selecting the options
4032 * menu to see the download window, or when a download changes state. It
4033 * shows the download window ontop of the current window.
4034 */
4035 /* package */ void viewDownloads(Uri downloadRecord) {
4036 Intent intent = new Intent(this,
4037 BrowserDownloadPage.class);
4038 intent.setData(downloadRecord);
4039 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4040
4041 }
4042
4043 /**
4044 * Handle results from Tab Switcher mTabOverview tool
4045 */
4046 private class TabListener implements ImageGrid.Listener {
4047 public void remove(int position) {
4048 // Note: Remove is not enabled if we have only one tab.
4049 if (Config.DEBUG && mTabControl.getTabCount() == 1) {
4050 throw new AssertionError();
4051 }
4052
4053 // Remember the current tab.
4054 TabControl.Tab current = mTabControl.getCurrentTab();
4055 final TabControl.Tab remove = mTabControl.getTab(position);
4056 mTabControl.removeTab(remove);
4057 // If we removed the current tab, use the tab at position - 1 if
4058 // possible.
4059 if (current == remove) {
4060 // If the user removes the last tab, act like the New Tab item
4061 // was clicked on.
4062 if (mTabControl.getTabCount() == 0) {
4063 current = mTabControl.createNewTab(false);
4064 sendAnimateFromOverview(current, true,
4065 mSettings.getHomePage(), TAB_OVERVIEW_DELAY, null);
4066 } else {
4067 final int index = position > 0 ? (position - 1) : 0;
4068 current = mTabControl.getTab(index);
4069 }
4070 }
4071
4072 // The tab overview could have been dismissed before this method is
4073 // called.
4074 if (mTabOverview != null) {
4075 // Remove the tab and change the index.
4076 mTabOverview.remove(position);
4077 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4078 }
4079
4080 // Only the current tab ensures its WebView is non-null. This
4081 // implies that we are reloading the freed tab.
4082 mTabControl.setCurrentTab(current);
4083 }
4084 public void onClick(int index) {
4085 // Change the tab if necessary.
4086 // Index equals ImageGrid.CANCEL when pressing back from the tab
4087 // overview.
4088 if (index == ImageGrid.CANCEL) {
4089 index = mTabControl.getCurrentIndex();
4090 // The current index is -1 if the current tab was removed.
4091 if (index == -1) {
4092 // Take the last tab as a fallback.
4093 index = mTabControl.getTabCount() - 1;
4094 }
4095 }
4096
4097 // Clear all the data for tab picker so next time it will be
4098 // recreated.
4099 mTabControl.wipeAllPickerData();
4100
4101 // NEW_TAB means that the "New Tab" cell was clicked on.
4102 if (index == ImageGrid.NEW_TAB) {
4103 openTabAndShow(mSettings.getHomePage(), null, false);
4104 } else {
4105 sendAnimateFromOverview(mTabControl.getTab(index),
4106 false, null, 0, null);
4107 }
4108 }
4109 }
4110
4111 // A fake View that draws the WebView's picture with a fast zoom filter.
4112 // The View is used in case the tab is freed during the animation because
4113 // of low memory.
4114 private static class AnimatingView extends View {
4115 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4116 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4117 private static final DrawFilter sZoomFilter =
4118 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4119 private final Picture mPicture;
4120 private final float mScale;
4121 private final int mScrollX;
4122 private final int mScrollY;
4123 final TabControl.Tab mTab;
4124
4125 AnimatingView(Context ctxt, TabControl.Tab t) {
4126 super(ctxt);
4127 mTab = t;
4128 // Use the top window in the animation since the tab overview will
4129 // display the top window in each cell.
4130 final WebView w = t.getTopWindow();
4131 mPicture = w.capturePicture();
4132 mScale = w.getScale() / w.getWidth();
4133 mScrollX = w.getScrollX();
4134 mScrollY = w.getScrollY();
4135 }
4136
4137 @Override
4138 protected void onDraw(Canvas canvas) {
4139 canvas.save();
4140 canvas.drawColor(Color.WHITE);
4141 if (mPicture != null) {
4142 canvas.setDrawFilter(sZoomFilter);
4143 float scale = getWidth() * mScale;
4144 canvas.scale(scale, scale);
4145 canvas.translate(-mScrollX, -mScrollY);
4146 canvas.drawPicture(mPicture);
4147 }
4148 canvas.restore();
4149 }
4150 }
4151
4152 /**
4153 * Open the tab picker. This function will always use the current tab in
4154 * its animation.
4155 * @param stay boolean stating whether the tab picker is to remain open
4156 * (in which case it needs a listener and its menu) or not.
4157 * @param index The index of the tab to show as the selection in the tab
4158 * overview.
4159 * @param remove If true, the tab at index will be removed after the
4160 * animation completes.
4161 */
4162 private void tabPicker(final boolean stay, final int index,
4163 final boolean remove) {
4164 if (mTabOverview != null) {
4165 return;
4166 }
4167
4168 int size = mTabControl.getTabCount();
4169
4170 TabListener l = null;
4171 if (stay) {
4172 l = mTabListener = new TabListener();
4173 }
4174 mTabOverview = new ImageGrid(this, stay, l);
4175
4176 for (int i = 0; i < size; i++) {
4177 final TabControl.Tab t = mTabControl.getTab(i);
4178 mTabControl.populatePickerData(t);
4179 mTabOverview.add(t);
4180 }
4181
4182 // Tell the tab overview to show the current tab, the tab overview will
4183 // handle the "New Tab" case.
4184 int currentIndex = mTabControl.getCurrentIndex();
4185 mTabOverview.setCurrentIndex(currentIndex);
4186
4187 // Attach the tab overview.
4188 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4189
4190 // Create a fake AnimatingView to animate the WebView's picture.
4191 final TabControl.Tab current = mTabControl.getCurrentTab();
4192 final AnimatingView v = new AnimatingView(this, current);
4193 mContentView.addView(v, COVER_SCREEN_PARAMS);
4194 removeTabFromContentView(current);
4195 // Pause timers to get the animation smoother.
4196 current.getWebView().pauseTimers();
4197
4198 // Send a message so the tab picker has a chance to layout and get
4199 // positions for all the cells.
4200 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4201 index, remove ? 1 : 0, v));
4202 // Setting this will indicate that we are animating to the overview. We
4203 // set it here to prevent another request to animate from coming in
4204 // between now and when ANIMATE_TO_OVERVIEW is handled.
4205 mAnimationCount++;
4206 // Always change the title bar to the window overview title while
4207 // animating.
4208 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4209 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4210 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4211 Window.PROGRESS_VISIBILITY_OFF);
4212 setTitle(R.string.tab_picker_title);
4213 // Make the menu empty until the animation completes.
4214 mMenuState = EMPTY_MENU;
4215 }
4216
4217 private void bookmarksOrHistoryPicker(boolean startWithHistory) {
4218 WebView current = mTabControl.getCurrentWebView();
4219 if (current == null) {
4220 return;
4221 }
4222 Intent intent = new Intent(this,
4223 CombinedBookmarkHistoryActivity.class);
4224 String title = current.getTitle();
4225 String url = current.getUrl();
4226 // Just in case the user opens bookmarks before a page finishes loading
4227 // so the current history item, and therefore the page, is null.
4228 if (null == url) {
4229 url = mLastEnteredUrl;
4230 // This can happen.
4231 if (null == url) {
4232 url = mSettings.getHomePage();
4233 }
4234 }
4235 // In case the web page has not yet received its associated title.
4236 if (title == null) {
4237 title = url;
4238 }
4239 intent.putExtra("title", title);
4240 intent.putExtra("url", url);
4241 intent.putExtra("maxTabsOpen",
4242 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4243 if (startWithHistory) {
4244 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4245 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4246 }
4247 startActivityForResult(intent, COMBO_PAGE);
4248 }
4249
4250 // Called when loading from context menu or LOAD_URL message
4251 private void loadURL(WebView view, String url) {
4252 // In case the user enters nothing.
4253 if (url != null && url.length() != 0 && view != null) {
4254 url = smartUrlFilter(url);
4255 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4256 view.loadUrl(url);
4257 }
4258 }
4259 }
4260
4261 private void checkMemory() {
4262 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4263 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4264 .getMemoryInfo(mi);
4265 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4266 // mi.threshold) for now
4267 // if (mi.lowMemory) {
4268 if (mi.availMem < mi.threshold) {
4269 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4270 + (mi.availMem / 1024) + "K threshold="
4271 + (mi.threshold / 1024) + "K");
4272 mTabControl.freeMemory();
4273 }
4274 }
4275
4276 private String smartUrlFilter(Uri inUri) {
4277 if (inUri != null) {
4278 return smartUrlFilter(inUri.toString());
4279 }
4280 return null;
4281 }
4282
4283
4284 // get window count
4285
4286 int getWindowCount(){
4287 if(mTabControl != null){
4288 return mTabControl.getTabCount();
4289 }
4290 return 0;
4291 }
4292
4293 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4294 "(?i)" + // switch on case insensitive matching
4295 "(" + // begin group for schema
4296 "(?:http|https|file):\\/\\/" +
4297 "|(?:data|about|content|javascript):" +
4298 ")" +
4299 "(.*)" );
4300
4301 /**
4302 * Attempts to determine whether user input is a URL or search
4303 * terms. Anything with a space is passed to search.
4304 *
4305 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4306 * "Http://" converts to "http://"
4307 *
4308 * @return Original or modified URL
4309 *
4310 */
4311 String smartUrlFilter(String url) {
4312
4313 String inUrl = url.trim();
4314 boolean hasSpace = inUrl.indexOf(' ') != -1;
4315
4316 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4317 if (matcher.matches()) {
4318 if (hasSpace) {
4319 inUrl = inUrl.replace(" ", "%20");
4320 }
4321 // force scheme to lowercase
4322 String scheme = matcher.group(1);
4323 String lcScheme = scheme.toLowerCase();
4324 if (!lcScheme.equals(scheme)) {
4325 return lcScheme + matcher.group(2);
4326 }
4327 return inUrl;
4328 }
4329 if (hasSpace) {
4330 // FIXME: quick search, need to be customized by setting
4331 if (inUrl.length() > 2 && inUrl.charAt(1) == ' ') {
4332 // FIXME: Is this the correct place to add to searches?
4333 // what if someone else calls this function?
4334 char char0 = inUrl.charAt(0);
4335
4336 if (char0 == 'g') {
4337 Browser.addSearchUrl(mResolver, inUrl);
4338 return composeSearchUrl(inUrl.substring(2));
4339
4340 } else if (char0 == 'w') {
4341 Browser.addSearchUrl(mResolver, inUrl);
4342 return URLUtil.composeSearchUrl(inUrl.substring(2),
4343 QuickSearch_W,
4344 QUERY_PLACE_HOLDER);
4345
4346 } else if (char0 == 'd') {
4347 Browser.addSearchUrl(mResolver, inUrl);
4348 return URLUtil.composeSearchUrl(inUrl.substring(2),
4349 QuickSearch_D,
4350 QUERY_PLACE_HOLDER);
4351
4352 } else if (char0 == 'l') {
4353 Browser.addSearchUrl(mResolver, inUrl);
4354 // FIXME: we need location in this case
4355 return URLUtil.composeSearchUrl(inUrl.substring(2),
4356 QuickSearch_L,
4357 QUERY_PLACE_HOLDER);
4358 }
4359 }
4360 } else {
4361 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4362 return URLUtil.guessUrl(inUrl);
4363 }
4364 }
4365
4366 Browser.addSearchUrl(mResolver, inUrl);
4367 return composeSearchUrl(inUrl);
4368 }
4369
4370 /* package */ String composeSearchUrl(String search) {
4371 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4372 QUERY_PLACE_HOLDER);
4373 }
4374
4375 /* package */void setBaseSearchUrl(String url) {
4376 if (url == null || url.length() == 0) {
4377 /*
4378 * get the google search url based on the SIM. Default is US. NOTE:
4379 * This code uses resources to optionally select the search Uri,
4380 * based on the MCC value from the SIM. The default string will most
4381 * likely be fine. It is parameterized to accept info from the
4382 * Locale, the language code is the first parameter (%1$s) and the
4383 * country code is the second (%2$s). This code must function in the
4384 * same way as a similar lookup in
4385 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4386 * change either of these functions, change them both. (The same is
4387 * true for the underlying resource strings, which are stored in
4388 * mcc-specific xml files.)
4389 */
4390 Locale l = Locale.getDefault();
4391 QuickSearch_G = getResources().getString(
4392 R.string.google_search_base, l.getLanguage(),
4393 l.getCountry().toLowerCase())
4394 + "client=ms-"
4395 + SystemProperties.get("persist.sys.com.google.clientid", "unknown")
4396 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4397 } else {
4398 QuickSearch_G = url;
4399 }
4400 }
4401
4402 private final static int LOCK_ICON_UNSECURE = 0;
4403 private final static int LOCK_ICON_SECURE = 1;
4404 private final static int LOCK_ICON_MIXED = 2;
4405
4406 private int mLockIconType = LOCK_ICON_UNSECURE;
4407 private int mPrevLockType = LOCK_ICON_UNSECURE;
4408
4409 private BrowserSettings mSettings;
4410 private TabControl mTabControl;
4411 private ContentResolver mResolver;
4412 private FrameLayout mContentView;
4413 private ImageGrid mTabOverview;
4414
4415 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4416 // view, we should rewrite this.
4417 private int mCurrentMenuState = 0;
4418 private int mMenuState = R.id.MAIN_MENU;
4419 private static final int EMPTY_MENU = -1;
4420 private Menu mMenu;
4421
4422 private FindDialog mFindDialog;
4423 // Used to prevent chording to result in firing two shortcuts immediately
4424 // one after another. Fixes bug 1211714.
4425 boolean mCanChord;
4426
4427 private boolean mInLoad;
4428 private boolean mIsNetworkUp;
4429
4430 private boolean mPageStarted;
4431 private boolean mActivityInPause = true;
4432
4433 private boolean mMenuIsDown;
4434
4435 private final KeyTracker mKeyTracker = new KeyTracker(this);
4436
4437 // As trackball doesn't send repeat down, we have to track it ourselves
4438 private boolean mTrackTrackball;
4439
4440 private static boolean mInTrace;
4441
4442 // Performance probe
4443 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4444 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4445 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4446 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4447 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4448 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4449 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4450 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4451 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4452 };
4453
4454 private long mStart;
4455 private long mProcessStart;
4456 private long mUserStart;
4457 private long mSystemStart;
4458 private long mIdleStart;
4459 private long mIrqStart;
4460
4461 private long mUiStart;
4462
4463 private Drawable mMixLockIcon;
4464 private Drawable mSecLockIcon;
4465 private Drawable mGenericFavicon;
4466
4467 /* hold a ref so we can auto-cancel if necessary */
4468 private AlertDialog mAlertDialog;
4469
4470 // Wait for credentials before loading google.com
4471 private ProgressDialog mCredsDlg;
4472
4473 // The up-to-date URL and title (these can be different from those stored
4474 // in WebView, since it takes some time for the information in WebView to
4475 // get updated)
4476 private String mUrl;
4477 private String mTitle;
4478
4479 // As PageInfo has different style for landscape / portrait, we have
4480 // to re-open it when configuration changed
4481 private AlertDialog mPageInfoDialog;
4482 private TabControl.Tab mPageInfoView;
4483 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4484 // dialog, we should not just dismiss it, but should get back to the
4485 // SSL-certificate-on-error dialog. This flag is used to store this state
4486 private Boolean mPageInfoFromShowSSLCertificateOnError;
4487
4488 // as SSLCertificateOnError has different style for landscape / portrait,
4489 // we have to re-open it when configuration changed
4490 private AlertDialog mSSLCertificateOnErrorDialog;
4491 private WebView mSSLCertificateOnErrorView;
4492 private SslErrorHandler mSSLCertificateOnErrorHandler;
4493 private SslError mSSLCertificateOnErrorError;
4494
4495 // as SSLCertificate has different style for landscape / portrait, we
4496 // have to re-open it when configuration changed
4497 private AlertDialog mSSLCertificateDialog;
4498 private TabControl.Tab mSSLCertificateView;
4499
4500 // as HttpAuthentication has different style for landscape / portrait, we
4501 // have to re-open it when configuration changed
4502 private AlertDialog mHttpAuthenticationDialog;
4503 private HttpAuthHandler mHttpAuthHandler;
4504
4505 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4506 new FrameLayout.LayoutParams(
4507 ViewGroup.LayoutParams.FILL_PARENT,
4508 ViewGroup.LayoutParams.FILL_PARENT);
4509 // We may provide UI to customize these
4510 // Google search from the browser
4511 static String QuickSearch_G;
4512 // Wikipedia search
4513 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4514 // Dictionary search
4515 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4516 // Google Mobile Local search
4517 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4518
4519 final static String QUERY_PLACE_HOLDER = "%s";
4520
4521 // "source" parameter for Google search through search key
4522 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4523 // "source" parameter for Google search through goto menu
4524 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4525 // "source" parameter for Google search through simplily type
4526 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4527 // "source" parameter for Google search suggested by the browser
4528 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4529 // "source" parameter for Google search from unknown source
4530 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4531
4532 private final static String LOGTAG = "browser";
4533
4534 private TabListener mTabListener;
4535
4536 private String mLastEnteredUrl;
4537
4538 private PowerManager.WakeLock mWakeLock;
4539 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4540
4541 private Toast mStopToast;
4542
4543 // Used during animations to prevent other animations from being triggered.
4544 // A count is used since the animation to and from the Window overview can
4545 // overlap. A count of 0 means no animation where a count of > 0 means
4546 // there are animations in progress.
4547 private int mAnimationCount;
4548
4549 // As the ids are dynamically created, we can't guarantee that they will
4550 // be in sequence, so this static array maps ids to a window number.
4551 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4552 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4553 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4554 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4555
4556 // monitor platform changes
4557 private IntentFilter mNetworkStateChangedFilter;
4558 private BroadcastReceiver mNetworkStateIntentReceiver;
4559
4560 // activity requestCode
4561 final static int COMBO_PAGE = 1;
4562 final static int DOWNLOAD_PAGE = 2;
4563 final static int PREFERENCES_PAGE = 3;
4564
4565 // the frenquency of checking whether system memory is low
4566 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
4567}