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