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