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