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