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