blob: f9c4dc9564f0f8d46d078bee34ee57a24fcff0b7 [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();
1443 startSearch(mSettings.getHomePage().equals(url) ? null : url, false,
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.
1988 private void openTabAndShow(String url, final Message msg,
1989 boolean closeOnExit, String appId) {
1990 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.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002001 private void 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.
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002030 sendAnimateFromOverview(
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002031 mTabControl.createNewTab(closeOnExit, appId, urlData.mUrl), true,
2032 urlData, delay, msg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002033 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002034 } else if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 // We should not have a msg here.
2036 assert msg == null;
2037 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002038 sendAnimateFromOverview(currentTab, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002039 TAB_OVERVIEW_DELAY, null);
2040 } else {
2041 // Get rid of the subwindow if it exists
2042 dismissSubWindow(currentTab);
2043 // Load the given url.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002044 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 }
2046 }
2047 }
2048
2049 private Animation createTabAnimation(final AnimatingView view,
2050 final View cell, boolean scaleDown) {
2051 final AnimationSet set = new AnimationSet(true);
2052 final float scaleX = (float) cell.getWidth() / view.getWidth();
2053 final float scaleY = (float) cell.getHeight() / view.getHeight();
2054 if (scaleDown) {
2055 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2056 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2057 cell.getTop()));
2058 } else {
2059 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2060 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2061 cell.getTop(), 0));
2062 }
2063 set.setDuration(TAB_ANIMATION_DURATION);
2064 set.setInterpolator(new DecelerateInterpolator());
2065 return set;
2066 }
2067
2068 // Animate to the tab overview. currentIndex tells us which position to
2069 // animate to and newIndex is the position that should be selected after
2070 // the animation completes.
2071 // If remove is true, after the animation stops, a confirmation dialog will
2072 // be displayed to the user.
2073 private void animateToTabOverview(final int newIndex, final boolean remove,
2074 final AnimatingView view) {
2075 // Find the view in the ImageGrid allowing for the "New Tab" cell.
2076 int position = mTabControl.getTabIndex(view.mTab);
2077 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2078 position++;
2079 }
2080
2081 // Offset the tab position with the first visible position to get a
2082 // number between 0 and 3.
2083 position -= mTabOverview.getFirstVisiblePosition();
2084
2085 // Grab the view that we are going to animate to.
2086 final View v = mTabOverview.getChildAt(position);
2087
2088 final Animation.AnimationListener l =
2089 new Animation.AnimationListener() {
2090 public void onAnimationStart(Animation a) {
Patrick Scottd068f802009-06-22 11:46:06 -04002091 if (mTabOverview != null) {
2092 mTabOverview.requestFocus();
2093 // Clear the listener so we don't trigger a tab
2094 // selection.
2095 mTabOverview.setListener(null);
2096 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002097 }
2098 public void onAnimationRepeat(Animation a) {}
2099 public void onAnimationEnd(Animation a) {
2100 // We are no longer animating so decrement the count.
2101 mAnimationCount--;
2102 // Make the view GONE so that it will not draw between
2103 // now and when the Runnable is handled.
2104 view.setVisibility(View.GONE);
2105 // Post a runnable since we can't modify the view
2106 // hierarchy during this callback.
2107 mHandler.post(new Runnable() {
2108 public void run() {
2109 // Remove the AnimatingView.
2110 mContentView.removeView(view);
2111 if (mTabOverview != null) {
2112 // Make newIndex visible.
2113 mTabOverview.setCurrentIndex(newIndex);
2114 // Restore the listener.
2115 mTabOverview.setListener(mTabListener);
2116 // Change the menu to TAB_MENU if the
2117 // ImageGrid is interactive.
2118 if (mTabOverview.isLive()) {
2119 mMenuState = R.id.TAB_MENU;
2120 mTabOverview.requestFocus();
2121 }
2122 }
2123 // If a remove was requested, remove the tab.
2124 if (remove) {
2125 // During a remove, the current tab has
2126 // already changed. Remember the current one
2127 // here.
2128 final TabControl.Tab currentTab =
2129 mTabControl.getCurrentTab();
2130 // Remove the tab at newIndex from
2131 // TabControl and the tab overview.
2132 final TabControl.Tab tab =
2133 mTabControl.getTab(newIndex);
2134 mTabControl.removeTab(tab);
2135 // Restore the current tab.
2136 if (currentTab != tab) {
2137 mTabControl.setCurrentTab(currentTab);
2138 }
2139 if (mTabOverview != null) {
2140 mTabOverview.remove(newIndex);
2141 // Make the current tab visible.
2142 mTabOverview.setCurrentIndex(
2143 mTabControl.getCurrentIndex());
2144 }
2145 }
2146 }
2147 });
2148 }
2149 };
2150
2151 // Do an animation if there is a view to animate to.
2152 if (v != null) {
2153 // Create our animation
2154 final Animation anim = createTabAnimation(view, v, true);
2155 anim.setAnimationListener(l);
2156 // Start animating
2157 view.startAnimation(anim);
2158 } else {
2159 // If something goes wrong and we didn't find a view to animate to,
2160 // just do everything here.
2161 l.onAnimationStart(null);
2162 l.onAnimationEnd(null);
2163 }
2164 }
2165
2166 // Animate from the tab picker. The index supplied is the index to animate
2167 // from.
2168 private void animateFromTabOverview(final AnimatingView view,
2169 final boolean newTab, final Message msg) {
2170 // firstVisible is the first visible tab on the screen. This helps
2171 // to know which corner of the screen the selected tab is.
2172 int firstVisible = mTabOverview.getFirstVisiblePosition();
2173 // tabPosition is the 0-based index of of the tab being opened
2174 int tabPosition = mTabControl.getTabIndex(view.mTab);
2175 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2176 // Add one to make room for the "New Tab" cell.
2177 tabPosition++;
2178 }
2179 // If this is a new tab, animate from the "New Tab" cell.
2180 if (newTab) {
2181 tabPosition = 0;
2182 }
2183 // Location corresponds to the four corners of the screen.
2184 // A new tab or 0 is upper left, 0 for an old tab is upper
2185 // right, 1 is lower left, and 2 is lower right
2186 int location = tabPosition - firstVisible;
2187
2188 // Find the view at this location.
2189 final View v = mTabOverview.getChildAt(location);
2190
2191 // Wait until the animation completes to replace the AnimatingView.
2192 final Animation.AnimationListener l =
2193 new Animation.AnimationListener() {
2194 public void onAnimationStart(Animation a) {}
2195 public void onAnimationRepeat(Animation a) {}
2196 public void onAnimationEnd(Animation a) {
2197 mHandler.post(new Runnable() {
2198 public void run() {
2199 mContentView.removeView(view);
2200 // Dismiss the tab overview. If the cell at the
2201 // given location is null, set the fade
2202 // parameter to true.
2203 dismissTabOverview(v == null);
2204 TabControl.Tab t =
2205 mTabControl.getCurrentTab();
2206 mMenuState = R.id.MAIN_MENU;
2207 // Resume regular updates.
2208 t.getWebView().resumeTimers();
2209 // Dispatch the message after the animation
2210 // completes.
2211 if (msg != null) {
2212 msg.sendToTarget();
2213 }
2214 // The animation is done and the tab overview is
2215 // gone so allow key events and other animations
2216 // to begin.
2217 mAnimationCount--;
2218 // Reset all the title bar info.
2219 resetTitle();
2220 }
2221 });
2222 }
2223 };
2224
2225 if (v != null) {
2226 final Animation anim = createTabAnimation(view, v, false);
2227 // Set the listener and start animating
2228 anim.setAnimationListener(l);
2229 view.startAnimation(anim);
2230 // Make the view VISIBLE during the animation.
2231 view.setVisibility(View.VISIBLE);
2232 } else {
2233 // Go ahead and do all the cleanup.
2234 l.onAnimationEnd(null);
2235 }
2236 }
2237
2238 // Dismiss the tab overview applying a fade if needed.
2239 private void dismissTabOverview(final boolean fade) {
2240 if (fade) {
2241 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2242 anim.setDuration(500);
2243 anim.startNow();
2244 mTabOverview.startAnimation(anim);
2245 }
2246 // Just in case there was a problem with animating away from the tab
2247 // overview
2248 WebView current = mTabControl.getCurrentWebView();
2249 if (current != null) {
2250 current.setVisibility(View.VISIBLE);
2251 } else {
2252 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2253 }
2254 // Make the sub window container visible.
2255 if (mTabControl.getCurrentSubWindow() != null) {
2256 mTabControl.getCurrentTab().getSubWebViewContainer()
2257 .setVisibility(View.VISIBLE);
2258 }
2259 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002260 // Clear all the data for tab picker so next time it will be
2261 // recreated.
2262 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002263 mTabOverview.clear();
2264 mTabOverview = null;
2265 mTabListener = null;
2266 }
2267
2268 private void openTab(String url) {
2269 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002270 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002271 if (t != null) {
2272 t.getWebView().loadUrl(url);
2273 }
2274 } else {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002275 openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002276 }
2277 }
2278
2279 private class Copy implements OnMenuItemClickListener {
2280 private CharSequence mText;
2281
2282 public boolean onMenuItemClick(MenuItem item) {
2283 copy(mText);
2284 return true;
2285 }
2286
2287 public Copy(CharSequence toCopy) {
2288 mText = toCopy;
2289 }
2290 }
2291
2292 private class Download implements OnMenuItemClickListener {
2293 private String mText;
2294
2295 public boolean onMenuItemClick(MenuItem item) {
2296 onDownloadStartNoStream(mText, null, null, null, -1);
2297 return true;
2298 }
2299
2300 public Download(String toDownload) {
2301 mText = toDownload;
2302 }
2303 }
2304
2305 private void copy(CharSequence text) {
2306 try {
2307 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2308 if (clip != null) {
2309 clip.setClipboardText(text);
2310 }
2311 } catch (android.os.RemoteException e) {
2312 Log.e(LOGTAG, "Copy failed", e);
2313 }
2314 }
2315
2316 /**
2317 * Resets the browser title-view to whatever it must be (for example, if we
2318 * load a page from history).
2319 */
2320 private void resetTitle() {
2321 resetLockIcon();
2322 resetTitleIconAndProgress();
2323 }
2324
2325 /**
2326 * Resets the browser title-view to whatever it must be
2327 * (for example, if we had a loading error)
2328 * When we have a new page, we call resetTitle, when we
2329 * have to reset the titlebar to whatever it used to be
2330 * (for example, if the user chose to stop loading), we
2331 * call resetTitleAndRevertLockIcon.
2332 */
2333 /* package */ void resetTitleAndRevertLockIcon() {
2334 revertLockIcon();
2335 resetTitleIconAndProgress();
2336 }
2337
2338 /**
2339 * Reset the title, favicon, and progress.
2340 */
2341 private void resetTitleIconAndProgress() {
2342 WebView current = mTabControl.getCurrentWebView();
2343 if (current == null) {
2344 return;
2345 }
2346 resetTitleAndIcon(current);
2347 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002348 mWebChromeClient.onProgressChanged(current, progress);
2349 }
2350
2351 // Reset the title and the icon based on the given item.
2352 private void resetTitleAndIcon(WebView view) {
2353 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2354 if (item != null) {
2355 setUrlTitle(item.getUrl(), item.getTitle());
2356 setFavicon(item.getFavicon());
2357 } else {
2358 setUrlTitle(null, null);
2359 setFavicon(null);
2360 }
2361 }
2362
2363 /**
2364 * Sets a title composed of the URL and the title string.
2365 * @param url The URL of the site being loaded.
2366 * @param title The title of the site being loaded.
2367 */
2368 private void setUrlTitle(String url, String title) {
2369 mUrl = url;
2370 mTitle = title;
2371
2372 // While the tab overview is animating or being shown, block changes
2373 // to the title.
2374 if (mAnimationCount == 0 && mTabOverview == null) {
2375 setTitle(buildUrlTitle(url, title));
2376 }
2377 }
2378
2379 /**
2380 * Builds and returns the page title, which is some
2381 * combination of the page URL and title.
2382 * @param url The URL of the site being loaded.
2383 * @param title The title of the site being loaded.
2384 * @return The page title.
2385 */
2386 private String buildUrlTitle(String url, String title) {
2387 String urlTitle = "";
2388
2389 if (url != null) {
2390 String titleUrl = buildTitleUrl(url);
2391
2392 if (title != null && 0 < title.length()) {
2393 if (titleUrl != null && 0 < titleUrl.length()) {
2394 urlTitle = titleUrl + ": " + title;
2395 } else {
2396 urlTitle = title;
2397 }
2398 } else {
2399 if (titleUrl != null) {
2400 urlTitle = titleUrl;
2401 }
2402 }
2403 }
2404
2405 return urlTitle;
2406 }
2407
2408 /**
2409 * @param url The URL to build a title version of the URL from.
2410 * @return The title version of the URL or null if fails.
2411 * The title version of the URL can be either the URL hostname,
2412 * or the hostname with an "https://" prefix (for secure URLs),
2413 * or an empty string if, for example, the URL in question is a
2414 * file:// URL with no hostname.
2415 */
2416 private static String buildTitleUrl(String url) {
2417 String titleUrl = null;
2418
2419 if (url != null) {
2420 try {
2421 // parse the url string
2422 URL urlObj = new URL(url);
2423 if (urlObj != null) {
2424 titleUrl = "";
2425
2426 String protocol = urlObj.getProtocol();
2427 String host = urlObj.getHost();
2428
2429 if (host != null && 0 < host.length()) {
2430 titleUrl = host;
2431 if (protocol != null) {
2432 // if a secure site, add an "https://" prefix!
2433 if (protocol.equalsIgnoreCase("https")) {
2434 titleUrl = protocol + "://" + host;
2435 }
2436 }
2437 }
2438 }
2439 } catch (MalformedURLException e) {}
2440 }
2441
2442 return titleUrl;
2443 }
2444
2445 // Set the favicon in the title bar.
2446 private void setFavicon(Bitmap icon) {
2447 // While the tab overview is animating or being shown, block changes to
2448 // the favicon.
2449 if (mAnimationCount > 0 || mTabOverview != null) {
2450 return;
2451 }
2452 Drawable[] array = new Drawable[2];
2453 PaintDrawable p = new PaintDrawable(Color.WHITE);
2454 p.setCornerRadius(3f);
2455 array[0] = p;
2456 if (icon == null) {
2457 array[1] = mGenericFavicon;
2458 } else {
2459 array[1] = new BitmapDrawable(icon);
2460 }
2461 LayerDrawable d = new LayerDrawable(array);
2462 d.setLayerInset(1, 2, 2, 2, 2);
2463 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2464 }
2465
2466 /**
2467 * Saves the current lock-icon state before resetting
2468 * the lock icon. If we have an error, we may need to
2469 * roll back to the previous state.
2470 */
2471 private void saveLockIcon() {
2472 mPrevLockType = mLockIconType;
2473 }
2474
2475 /**
2476 * Reverts the lock-icon state to the last saved state,
2477 * for example, if we had an error, and need to cancel
2478 * the load.
2479 */
2480 private void revertLockIcon() {
2481 mLockIconType = mPrevLockType;
2482
Dave Bort31a6d1c2009-04-13 15:56:49 -07002483 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002484 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2485 " revert lock icon to " + mLockIconType);
2486 }
2487
2488 updateLockIconImage(mLockIconType);
2489 }
2490
2491 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2492 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2493 // Animate to the tab picker, remove the current tab, then
2494 // animate away from the tab picker to the parent WebView.
2495 tabPicker(false, indexFrom, remove);
2496 // Change to the parent tab
2497 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2498 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002499 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002500 } else {
2501 // Increment this here so that no other animations can happen in
2502 // between the end of the tab picker transition and the beginning
2503 // of openTabAndShow. This has a matching decrement in the handler
2504 // of OPEN_TAB_AND_SHOW.
2505 mAnimationCount++;
2506 // Send a message to open a new tab.
2507 mHandler.sendMessageDelayed(
2508 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2509 mSettings.getHomePage()), delay);
2510 }
2511 }
2512
2513 private void goBackOnePageOrQuit() {
2514 TabControl.Tab current = mTabControl.getCurrentTab();
2515 if (current == null) {
2516 /*
2517 * Instead of finishing the activity, simply push this to the back
2518 * of the stack and let ActivityManager to choose the foreground
2519 * activity. As BrowserActivity is singleTask, it will be always the
2520 * root of the task. So we can use either true or false for
2521 * moveTaskToBack().
2522 */
2523 moveTaskToBack(true);
2524 }
2525 WebView w = current.getWebView();
2526 if (w.canGoBack()) {
2527 w.goBack();
2528 } else {
2529 // Check to see if we are closing a window that was created by
2530 // another window. If so, we switch back to that window.
2531 TabControl.Tab parent = current.getParentTab();
2532 if (parent != null) {
2533 switchTabs(mTabControl.getCurrentIndex(),
2534 mTabControl.getTabIndex(parent), true);
2535 } else {
2536 if (current.closeOnExit()) {
2537 if (mTabControl.getTabCount() == 1) {
2538 finish();
2539 return;
2540 }
2541 // call pauseWebView() now, we won't be able to call it in
2542 // onPause() as the WebView won't be valid.
2543 pauseWebView();
2544 removeTabFromContentView(current);
2545 mTabControl.removeTab(current);
2546 }
2547 /*
2548 * Instead of finishing the activity, simply push this to the back
2549 * of the stack and let ActivityManager to choose the foreground
2550 * activity. As BrowserActivity is singleTask, it will be always the
2551 * root of the task. So we can use either true or false for
2552 * moveTaskToBack().
2553 */
2554 moveTaskToBack(true);
2555 }
2556 }
2557 }
2558
2559 public KeyTracker.State onKeyTracker(int keyCode,
2560 KeyEvent event,
2561 KeyTracker.Stage stage,
2562 int duration) {
2563 // if onKeyTracker() is called after activity onStop()
2564 // because of accumulated key events,
2565 // we should ignore it as browser is not active any more.
2566 WebView topWindow = getTopWindow();
2567 if (topWindow == null)
2568 return KeyTracker.State.NOT_TRACKING;
2569
2570 if (keyCode == KeyEvent.KEYCODE_BACK) {
2571 // During animations, block the back key so that other animations
2572 // are not triggered and so that we don't end up destroying all the
2573 // WebViews before finishing the animation.
2574 if (mAnimationCount > 0) {
2575 return KeyTracker.State.DONE_TRACKING;
2576 }
2577 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2578 bookmarksOrHistoryPicker(true);
2579 return KeyTracker.State.DONE_TRACKING;
2580 } else if (stage == KeyTracker.Stage.UP) {
2581 // FIXME: Currently, we do not have a notion of the
2582 // history picker for the subwindow, but maybe we
2583 // should?
2584 WebView subwindow = mTabControl.getCurrentSubWindow();
2585 if (subwindow != null) {
2586 if (subwindow.canGoBack()) {
2587 subwindow.goBack();
2588 } else {
2589 dismissSubWindow(mTabControl.getCurrentTab());
2590 }
2591 } else {
2592 goBackOnePageOrQuit();
2593 }
2594 return KeyTracker.State.DONE_TRACKING;
2595 }
2596 return KeyTracker.State.KEEP_TRACKING;
2597 }
2598 return KeyTracker.State.NOT_TRACKING;
2599 }
2600
2601 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2602 if (keyCode == KeyEvent.KEYCODE_MENU) {
2603 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002604 } else if (mMenuIsDown) {
2605 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2606 // still down, we don't want to trigger the search. Pretend to
2607 // consume the key and do nothing.
2608 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002609 }
2610 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2611 if (!handled) {
2612 switch (keyCode) {
2613 case KeyEvent.KEYCODE_SPACE:
2614 if (event.isShiftPressed()) {
2615 getTopWindow().pageUp(false);
2616 } else {
2617 getTopWindow().pageDown(false);
2618 }
2619 handled = true;
2620 break;
2621
2622 default:
2623 break;
2624 }
2625 }
2626 return handled || super.onKeyDown(keyCode, event);
2627 }
2628
2629 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2630 if (keyCode == KeyEvent.KEYCODE_MENU) {
2631 mMenuIsDown = false;
2632 }
2633 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2634 }
2635
2636 private void stopLoading() {
2637 resetTitleAndRevertLockIcon();
2638 WebView w = getTopWindow();
2639 w.stopLoading();
2640 mWebViewClient.onPageFinished(w, w.getUrl());
2641
2642 cancelStopToast();
2643 mStopToast = Toast
2644 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2645 mStopToast.show();
2646 }
2647
2648 private void cancelStopToast() {
2649 if (mStopToast != null) {
2650 mStopToast.cancel();
2651 mStopToast = null;
2652 }
2653 }
2654
2655 // called by a non-UI thread to post the message
2656 public void postMessage(int what, int arg1, int arg2, Object obj) {
2657 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2658 }
2659
2660 // public message ids
2661 public final static int LOAD_URL = 1001;
2662 public final static int STOP_LOAD = 1002;
2663
2664 // Message Ids
2665 private static final int FOCUS_NODE_HREF = 102;
2666 private static final int CANCEL_CREDS_REQUEST = 103;
2667 private static final int ANIMATE_FROM_OVERVIEW = 104;
2668 private static final int ANIMATE_TO_OVERVIEW = 105;
2669 private static final int OPEN_TAB_AND_SHOW = 106;
2670 private static final int CHECK_MEMORY = 107;
2671 private static final int RELEASE_WAKELOCK = 108;
2672
2673 // Private handler for handling javascript and saving passwords
2674 private Handler mHandler = new Handler() {
2675
2676 public void handleMessage(Message msg) {
2677 switch (msg.what) {
2678 case ANIMATE_FROM_OVERVIEW:
2679 final HashMap map = (HashMap) msg.obj;
2680 animateFromTabOverview((AnimatingView) map.get("view"),
2681 msg.arg1 == 1, (Message) map.get("msg"));
2682 break;
2683
2684 case ANIMATE_TO_OVERVIEW:
2685 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2686 (AnimatingView) msg.obj);
2687 break;
2688
2689 case OPEN_TAB_AND_SHOW:
2690 // Decrement mAnimationCount before openTabAndShow because
2691 // the method relies on the value being 0 to start the next
2692 // animation.
2693 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002694 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002695 break;
2696
2697 case FOCUS_NODE_HREF:
2698 String url = (String) msg.getData().get("url");
2699 if (url == null || url.length() == 0) {
2700 break;
2701 }
2702 HashMap focusNodeMap = (HashMap) msg.obj;
2703 WebView view = (WebView) focusNodeMap.get("webview");
2704 // Only apply the action if the top window did not change.
2705 if (getTopWindow() != view) {
2706 break;
2707 }
2708 switch (msg.arg1) {
2709 case R.id.open_context_menu_id:
2710 case R.id.view_image_context_menu_id:
2711 loadURL(getTopWindow(), url);
2712 break;
2713 case R.id.open_newtab_context_menu_id:
2714 openTab(url);
2715 break;
2716 case R.id.bookmark_context_menu_id:
2717 Intent intent = new Intent(BrowserActivity.this,
2718 AddBookmarkPage.class);
2719 intent.putExtra("url", url);
2720 startActivity(intent);
2721 break;
2722 case R.id.share_link_context_menu_id:
2723 Browser.sendString(BrowserActivity.this, url);
2724 break;
2725 case R.id.copy_link_context_menu_id:
2726 copy(url);
2727 break;
2728 case R.id.save_link_context_menu_id:
2729 case R.id.download_context_menu_id:
2730 onDownloadStartNoStream(url, null, null, null, -1);
2731 break;
2732 }
2733 break;
2734
2735 case LOAD_URL:
2736 loadURL(getTopWindow(), (String) msg.obj);
2737 break;
2738
2739 case STOP_LOAD:
2740 stopLoading();
2741 break;
2742
2743 case CANCEL_CREDS_REQUEST:
2744 resumeAfterCredentials();
2745 break;
2746
2747 case CHECK_MEMORY:
2748 // reschedule to check memory condition
2749 mHandler.removeMessages(CHECK_MEMORY);
2750 mHandler.sendMessageDelayed(mHandler.obtainMessage
2751 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2752 checkMemory();
2753 break;
2754
2755 case RELEASE_WAKELOCK:
2756 if (mWakeLock.isHeld()) {
2757 mWakeLock.release();
2758 }
2759 break;
2760 }
2761 }
2762 };
2763
2764 // -------------------------------------------------------------------------
2765 // WebViewClient implementation.
2766 //-------------------------------------------------------------------------
2767
2768 // Use in overrideUrlLoading
2769 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2770 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2771 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2772 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2773
2774 /* package */ WebViewClient getWebViewClient() {
2775 return mWebViewClient;
2776 }
2777
2778 private void updateIcon(String url, Bitmap icon) {
2779 if (icon != null) {
2780 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2781 url, icon);
2782 }
2783 setFavicon(icon);
2784 }
2785
2786 private final WebViewClient mWebViewClient = new WebViewClient() {
2787 @Override
2788 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2789 resetLockIcon(url);
2790 setUrlTitle(url, null);
2791 // Call updateIcon instead of setFavicon so the bookmark
2792 // database can be updated.
2793 updateIcon(url, favicon);
2794
2795 if (mSettings.isTracing() == true) {
2796 // FIXME: we should save the trace file somewhere other than data.
2797 // I can't use "/tmp" as it competes for system memory.
2798 File file = getDir("browserTrace", 0);
2799 String baseDir = file.getPath();
2800 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2801 String host;
2802 try {
2803 WebAddress uri = new WebAddress(url);
2804 host = uri.mHost;
2805 } catch (android.net.ParseException ex) {
2806 host = "unknown_host";
2807 }
2808 host = host.replace('.', '_');
2809 baseDir = baseDir + host;
2810 file = new File(baseDir+".data");
2811 if (file.exists() == true) {
2812 file.delete();
2813 }
2814 file = new File(baseDir+".key");
2815 if (file.exists() == true) {
2816 file.delete();
2817 }
2818 mInTrace = true;
2819 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2820 }
2821
2822 // Performance probe
2823 if (false) {
2824 mStart = SystemClock.uptimeMillis();
2825 mProcessStart = Process.getElapsedCpuTime();
2826 long[] sysCpu = new long[7];
2827 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2828 sysCpu, null)) {
2829 mUserStart = sysCpu[0] + sysCpu[1];
2830 mSystemStart = sysCpu[2];
2831 mIdleStart = sysCpu[3];
2832 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2833 }
2834 mUiStart = SystemClock.currentThreadTimeMillis();
2835 }
2836
2837 if (!mPageStarted) {
2838 mPageStarted = true;
2839 // if onResume() has been called, resumeWebView() does nothing.
2840 resumeWebView();
2841 }
2842
2843 // reset sync timer to avoid sync starts during loading a page
2844 CookieSyncManager.getInstance().resetSync();
2845
2846 mInLoad = true;
2847 updateInLoadMenuItems();
2848 if (!mIsNetworkUp) {
2849 if ( mAlertDialog == null) {
2850 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2851 .setTitle(R.string.loadSuspendedTitle)
2852 .setMessage(R.string.loadSuspended)
2853 .setPositiveButton(R.string.ok, null)
2854 .show();
2855 }
2856 if (view != null) {
2857 view.setNetworkAvailable(false);
2858 }
2859 }
2860
2861 // schedule to check memory condition
2862 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2863 CHECK_MEMORY_INTERVAL);
2864 }
2865
2866 @Override
2867 public void onPageFinished(WebView view, String url) {
2868 // Reset the title and icon in case we stopped a provisional
2869 // load.
2870 resetTitleAndIcon(view);
2871
2872 // Update the lock icon image only once we are done loading
2873 updateLockIconImage(mLockIconType);
2874
2875 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002876 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002877 long[] sysCpu = new long[7];
2878 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2879 sysCpu, null)) {
2880 String uiInfo = "UI thread used "
2881 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2882 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002883 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002884 Log.d(LOGTAG, uiInfo);
2885 }
2886 //The string that gets written to the log
2887 String performanceString = "It took total "
2888 + (SystemClock.uptimeMillis() - mStart)
2889 + " ms clock time to load the page."
2890 + "\nbrowser process used "
2891 + (Process.getElapsedCpuTime() - mProcessStart)
2892 + " ms, user processes used "
2893 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2894 + " ms, kernel used "
2895 + (sysCpu[2] - mSystemStart) * 10
2896 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2897 + " ms and irq took "
2898 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2899 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002900 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002901 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2902 }
2903 if (url != null) {
2904 // strip the url to maintain consistency
2905 String newUrl = new String(url);
2906 if (newUrl.startsWith("http://www.")) {
2907 newUrl = newUrl.substring(11);
2908 } else if (newUrl.startsWith("http://")) {
2909 newUrl = newUrl.substring(7);
2910 } else if (newUrl.startsWith("https://www.")) {
2911 newUrl = newUrl.substring(12);
2912 } else if (newUrl.startsWith("https://")) {
2913 newUrl = newUrl.substring(8);
2914 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07002915 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002916 Log.d(LOGTAG, newUrl + " loaded");
2917 }
2918 /*
2919 if (sWhiteList.contains(newUrl)) {
2920 // The string that gets pushed to the statistcs
2921 // service
2922 performanceString = performanceString
2923 + "\nWebpage: "
2924 + newUrl
2925 + "\nCarrier: "
2926 + android.os.SystemProperties
2927 .get("gsm.sim.operator.alpha");
2928 if (mWebView != null
2929 && mWebView.getContext() != null
2930 && mWebView.getContext().getSystemService(
2931 Context.CONNECTIVITY_SERVICE) != null) {
2932 ConnectivityManager cManager =
2933 (ConnectivityManager) mWebView
2934 .getContext().getSystemService(
2935 Context.CONNECTIVITY_SERVICE);
2936 NetworkInfo nInfo = cManager
2937 .getActiveNetworkInfo();
2938 if (nInfo != null) {
2939 performanceString = performanceString
2940 + "\nNetwork Type: "
2941 + nInfo.getType().toString();
2942 }
2943 }
2944 Checkin.logEvent(mResolver,
2945 Checkin.Events.Tag.WEBPAGE_LOAD,
2946 performanceString);
2947 Log.w(LOGTAG, "pushed to the statistics service");
2948 }
2949 */
2950 }
2951 }
2952 }
2953
2954 if (mInTrace) {
2955 mInTrace = false;
2956 Debug.stopMethodTracing();
2957 }
2958
2959 if (mPageStarted) {
2960 mPageStarted = false;
2961 // pauseWebView() will do nothing and return false if onPause()
2962 // is not called yet.
2963 if (pauseWebView()) {
2964 if (mWakeLock.isHeld()) {
2965 mHandler.removeMessages(RELEASE_WAKELOCK);
2966 mWakeLock.release();
2967 }
2968 }
2969 }
2970
The Android Open Source Project0c908882009-03-03 19:32:16 -08002971 mHandler.removeMessages(CHECK_MEMORY);
2972 checkMemory();
2973 }
2974
2975 // return true if want to hijack the url to let another app to handle it
2976 @Override
2977 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2978 if (url.startsWith(SCHEME_WTAI)) {
2979 // wtai://wp/mc;number
2980 // number=string(phone-number)
2981 if (url.startsWith(SCHEME_WTAI_MC)) {
2982 Intent intent = new Intent(Intent.ACTION_VIEW,
2983 Uri.parse(WebView.SCHEME_TEL +
2984 url.substring(SCHEME_WTAI_MC.length())));
2985 startActivity(intent);
2986 return true;
2987 }
2988 // wtai://wp/sd;dtmf
2989 // dtmf=string(dialstring)
2990 if (url.startsWith(SCHEME_WTAI_SD)) {
2991 // TODO
2992 // only send when there is active voice connection
2993 return false;
2994 }
2995 // wtai://wp/ap;number;name
2996 // number=string(phone-number)
2997 // name=string
2998 if (url.startsWith(SCHEME_WTAI_AP)) {
2999 // TODO
3000 return false;
3001 }
3002 }
3003
Dianne Hackborn99189432009-06-17 18:06:18 -07003004 // The "about:" schemes are internal to the browser; don't
3005 // want these to be dispatched to other apps.
3006 if (url.startsWith("about:")) {
3007 return false;
3008 }
3009
3010 Intent intent;
3011
3012 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003013 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003014 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3015 } catch (URISyntaxException ex) {
3016 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003017 return false;
3018 }
3019
Grace Kloba5b078b52009-06-24 20:23:41 -07003020 // check whether the intent can be resolved. If not, we will see
3021 // whether we can download it from the Market.
3022 if (getPackageManager().resolveActivity(intent, 0) == null) {
3023 String packagename = intent.getPackage();
3024 if (packagename != null) {
3025 intent = new Intent(Intent.ACTION_VIEW, Uri
3026 .parse("market://search?q=pname:" + packagename));
3027 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3028 startActivity(intent);
3029 return true;
3030 } else {
3031 return false;
3032 }
3033 }
3034
Dianne Hackborn99189432009-06-17 18:06:18 -07003035 // sanitize the Intent, ensuring web pages can not bypass browser
3036 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003037 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003038 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003039 try {
3040 if (startActivityIfNeeded(intent, -1)) {
3041 return true;
3042 }
3043 } catch (ActivityNotFoundException ex) {
3044 // ignore the error. If no application can handle the URL,
3045 // eg about:blank, assume the browser can handle it.
3046 }
3047
3048 if (mMenuIsDown) {
3049 openTab(url);
3050 closeOptionsMenu();
3051 return true;
3052 }
3053
3054 return false;
3055 }
3056
3057 /**
3058 * Updates the lock icon. This method is called when we discover another
3059 * resource to be loaded for this page (for example, javascript). While
3060 * we update the icon type, we do not update the lock icon itself until
3061 * we are done loading, it is slightly more secure this way.
3062 */
3063 @Override
3064 public void onLoadResource(WebView view, String url) {
3065 if (url != null && url.length() > 0) {
3066 // It is only if the page claims to be secure
3067 // that we may have to update the lock:
3068 if (mLockIconType == LOCK_ICON_SECURE) {
3069 // If NOT a 'safe' url, change the lock to mixed content!
3070 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3071 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003072 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003073 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3074 " updated lock icon to " + mLockIconType + " due to " + url);
3075 }
3076 }
3077 }
3078 }
3079 }
3080
3081 /**
3082 * Show the dialog, asking the user if they would like to continue after
3083 * an excessive number of HTTP redirects.
3084 */
3085 @Override
3086 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3087 final Message continueMsg) {
3088 new AlertDialog.Builder(BrowserActivity.this)
3089 .setTitle(R.string.browserFrameRedirect)
3090 .setMessage(R.string.browserFrame307Post)
3091 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3092 public void onClick(DialogInterface dialog, int which) {
3093 continueMsg.sendToTarget();
3094 }})
3095 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3096 public void onClick(DialogInterface dialog, int which) {
3097 cancelMsg.sendToTarget();
3098 }})
3099 .setOnCancelListener(new OnCancelListener() {
3100 public void onCancel(DialogInterface dialog) {
3101 cancelMsg.sendToTarget();
3102 }})
3103 .show();
3104 }
3105
Patrick Scotta6555242009-03-24 18:01:26 -07003106 // Container class for the next error dialog that needs to be
3107 // displayed.
3108 class ErrorDialog {
3109 public final int mTitle;
3110 public final String mDescription;
3111 public final int mError;
3112 ErrorDialog(int title, String desc, int error) {
3113 mTitle = title;
3114 mDescription = desc;
3115 mError = error;
3116 }
3117 };
3118
3119 private void processNextError() {
3120 if (mQueuedErrors == null) {
3121 return;
3122 }
3123 // The first one is currently displayed so just remove it.
3124 mQueuedErrors.removeFirst();
3125 if (mQueuedErrors.size() == 0) {
3126 mQueuedErrors = null;
3127 return;
3128 }
3129 showError(mQueuedErrors.getFirst());
3130 }
3131
3132 private DialogInterface.OnDismissListener mDialogListener =
3133 new DialogInterface.OnDismissListener() {
3134 public void onDismiss(DialogInterface d) {
3135 processNextError();
3136 }
3137 };
3138 private LinkedList<ErrorDialog> mQueuedErrors;
3139
3140 private void queueError(int err, String desc) {
3141 if (mQueuedErrors == null) {
3142 mQueuedErrors = new LinkedList<ErrorDialog>();
3143 }
3144 for (ErrorDialog d : mQueuedErrors) {
3145 if (d.mError == err) {
3146 // Already saw a similar error, ignore the new one.
3147 return;
3148 }
3149 }
3150 ErrorDialog errDialog = new ErrorDialog(
3151 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3152 R.string.browserFrameFileErrorLabel :
3153 R.string.browserFrameNetworkErrorLabel,
3154 desc, err);
3155 mQueuedErrors.addLast(errDialog);
3156
3157 // Show the dialog now if the queue was empty.
3158 if (mQueuedErrors.size() == 1) {
3159 showError(errDialog);
3160 }
3161 }
3162
3163 private void showError(ErrorDialog errDialog) {
3164 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3165 .setTitle(errDialog.mTitle)
3166 .setMessage(errDialog.mDescription)
3167 .setPositiveButton(R.string.ok, null)
3168 .create();
3169 d.setOnDismissListener(mDialogListener);
3170 d.show();
3171 }
3172
The Android Open Source Project0c908882009-03-03 19:32:16 -08003173 /**
3174 * Show a dialog informing the user of the network error reported by
3175 * WebCore.
3176 */
3177 @Override
3178 public void onReceivedError(WebView view, int errorCode,
3179 String description, String failingUrl) {
3180 if (errorCode != EventHandler.ERROR_LOOKUP &&
3181 errorCode != EventHandler.ERROR_CONNECT &&
3182 errorCode != EventHandler.ERROR_BAD_URL &&
3183 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3184 errorCode != EventHandler.FILE_ERROR) {
Patrick Scotta6555242009-03-24 18:01:26 -07003185 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003186 }
Patrick Scotta6555242009-03-24 18:01:26 -07003187 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3188 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003189
3190 // We need to reset the title after an error.
3191 resetTitleAndRevertLockIcon();
3192 }
3193
3194 /**
3195 * Check with the user if it is ok to resend POST data as the page they
3196 * are trying to navigate to is the result of a POST.
3197 */
3198 @Override
3199 public void onFormResubmission(WebView view, final Message dontResend,
3200 final Message resend) {
3201 new AlertDialog.Builder(BrowserActivity.this)
3202 .setTitle(R.string.browserFrameFormResubmitLabel)
3203 .setMessage(R.string.browserFrameFormResubmitMessage)
3204 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3205 public void onClick(DialogInterface dialog, int which) {
3206 resend.sendToTarget();
3207 }})
3208 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3209 public void onClick(DialogInterface dialog, int which) {
3210 dontResend.sendToTarget();
3211 }})
3212 .setOnCancelListener(new OnCancelListener() {
3213 public void onCancel(DialogInterface dialog) {
3214 dontResend.sendToTarget();
3215 }})
3216 .show();
3217 }
3218
3219 /**
3220 * Insert the url into the visited history database.
3221 * @param url The url to be inserted.
3222 * @param isReload True if this url is being reloaded.
3223 * FIXME: Not sure what to do when reloading the page.
3224 */
3225 @Override
3226 public void doUpdateVisitedHistory(WebView view, String url,
3227 boolean isReload) {
3228 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3229 return;
3230 }
3231 Browser.updateVisitedHistory(mResolver, url, true);
3232 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3233 }
3234
3235 /**
3236 * Displays SSL error(s) dialog to the user.
3237 */
3238 @Override
3239 public void onReceivedSslError(
3240 final WebView view, final SslErrorHandler handler, final SslError error) {
3241
3242 if (mSettings.showSecurityWarnings()) {
3243 final LayoutInflater factory =
3244 LayoutInflater.from(BrowserActivity.this);
3245 final View warningsView =
3246 factory.inflate(R.layout.ssl_warnings, null);
3247 final LinearLayout placeholder =
3248 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3249
3250 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3251 LinearLayout ll = (LinearLayout)factory
3252 .inflate(R.layout.ssl_warning, null);
3253 ((TextView)ll.findViewById(R.id.warning))
3254 .setText(R.string.ssl_untrusted);
3255 placeholder.addView(ll);
3256 }
3257
3258 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3259 LinearLayout ll = (LinearLayout)factory
3260 .inflate(R.layout.ssl_warning, null);
3261 ((TextView)ll.findViewById(R.id.warning))
3262 .setText(R.string.ssl_mismatch);
3263 placeholder.addView(ll);
3264 }
3265
3266 if (error.hasError(SslError.SSL_EXPIRED)) {
3267 LinearLayout ll = (LinearLayout)factory
3268 .inflate(R.layout.ssl_warning, null);
3269 ((TextView)ll.findViewById(R.id.warning))
3270 .setText(R.string.ssl_expired);
3271 placeholder.addView(ll);
3272 }
3273
3274 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3275 LinearLayout ll = (LinearLayout)factory
3276 .inflate(R.layout.ssl_warning, null);
3277 ((TextView)ll.findViewById(R.id.warning))
3278 .setText(R.string.ssl_not_yet_valid);
3279 placeholder.addView(ll);
3280 }
3281
3282 new AlertDialog.Builder(BrowserActivity.this)
3283 .setTitle(R.string.security_warning)
3284 .setIcon(android.R.drawable.ic_dialog_alert)
3285 .setView(warningsView)
3286 .setPositiveButton(R.string.ssl_continue,
3287 new DialogInterface.OnClickListener() {
3288 public void onClick(DialogInterface dialog, int whichButton) {
3289 handler.proceed();
3290 }
3291 })
3292 .setNeutralButton(R.string.view_certificate,
3293 new DialogInterface.OnClickListener() {
3294 public void onClick(DialogInterface dialog, int whichButton) {
3295 showSSLCertificateOnError(view, handler, error);
3296 }
3297 })
3298 .setNegativeButton(R.string.cancel,
3299 new DialogInterface.OnClickListener() {
3300 public void onClick(DialogInterface dialog, int whichButton) {
3301 handler.cancel();
3302 BrowserActivity.this.resetTitleAndRevertLockIcon();
3303 }
3304 })
3305 .setOnCancelListener(
3306 new DialogInterface.OnCancelListener() {
3307 public void onCancel(DialogInterface dialog) {
3308 handler.cancel();
3309 BrowserActivity.this.resetTitleAndRevertLockIcon();
3310 }
3311 })
3312 .show();
3313 } else {
3314 handler.proceed();
3315 }
3316 }
3317
3318 /**
3319 * Handles an HTTP authentication request.
3320 *
3321 * @param handler The authentication handler
3322 * @param host The host
3323 * @param realm The realm
3324 */
3325 @Override
3326 public void onReceivedHttpAuthRequest(WebView view,
3327 final HttpAuthHandler handler, final String host, final String realm) {
3328 String username = null;
3329 String password = null;
3330
3331 boolean reuseHttpAuthUsernamePassword =
3332 handler.useHttpAuthUsernamePassword();
3333
3334 if (reuseHttpAuthUsernamePassword &&
3335 (mTabControl.getCurrentWebView() != null)) {
3336 String[] credentials =
3337 mTabControl.getCurrentWebView()
3338 .getHttpAuthUsernamePassword(host, realm);
3339 if (credentials != null && credentials.length == 2) {
3340 username = credentials[0];
3341 password = credentials[1];
3342 }
3343 }
3344
3345 if (username != null && password != null) {
3346 handler.proceed(username, password);
3347 } else {
3348 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3349 }
3350 }
3351
3352 @Override
3353 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3354 if (mMenuIsDown) {
3355 // only check shortcut key when MENU is held
3356 return getWindow().isShortcutKey(event.getKeyCode(), event);
3357 } else {
3358 return false;
3359 }
3360 }
3361
3362 @Override
3363 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3364 if (view != mTabControl.getCurrentTopWebView()) {
3365 return;
3366 }
3367 if (event.isDown()) {
3368 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3369 } else {
3370 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3371 }
3372 }
3373 };
3374
3375 //--------------------------------------------------------------------------
3376 // WebChromeClient implementation
3377 //--------------------------------------------------------------------------
3378
3379 /* package */ WebChromeClient getWebChromeClient() {
3380 return mWebChromeClient;
3381 }
3382
3383 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3384 // Helper method to create a new tab or sub window.
3385 private void createWindow(final boolean dialog, final Message msg) {
3386 if (dialog) {
3387 mTabControl.createSubWindow();
3388 final TabControl.Tab t = mTabControl.getCurrentTab();
3389 attachSubWindow(t);
3390 WebView.WebViewTransport transport =
3391 (WebView.WebViewTransport) msg.obj;
3392 transport.setWebView(t.getSubWebView());
3393 msg.sendToTarget();
3394 } else {
3395 final TabControl.Tab parent = mTabControl.getCurrentTab();
3396 // openTabAndShow will dispatch the message after creating the
3397 // new WebView. This will prevent another request from coming
3398 // in during the animation.
Patrick Scott95d601f2009-06-11 10:06:46 -04003399 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003400 parent.addChildTab(mTabControl.getCurrentTab());
3401 WebView.WebViewTransport transport =
3402 (WebView.WebViewTransport) msg.obj;
3403 transport.setWebView(mTabControl.getCurrentWebView());
3404 }
3405 }
3406
3407 @Override
3408 public boolean onCreateWindow(WebView view, final boolean dialog,
3409 final boolean userGesture, final Message resultMsg) {
3410 // Ignore these requests during tab animations or if the tab
3411 // overview is showing.
3412 if (mAnimationCount > 0 || mTabOverview != null) {
3413 return false;
3414 }
3415 // Short-circuit if we can't create any more tabs or sub windows.
3416 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3417 new AlertDialog.Builder(BrowserActivity.this)
3418 .setTitle(R.string.too_many_subwindows_dialog_title)
3419 .setIcon(android.R.drawable.ic_dialog_alert)
3420 .setMessage(R.string.too_many_subwindows_dialog_message)
3421 .setPositiveButton(R.string.ok, null)
3422 .show();
3423 return false;
3424 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3425 new AlertDialog.Builder(BrowserActivity.this)
3426 .setTitle(R.string.too_many_windows_dialog_title)
3427 .setIcon(android.R.drawable.ic_dialog_alert)
3428 .setMessage(R.string.too_many_windows_dialog_message)
3429 .setPositiveButton(R.string.ok, null)
3430 .show();
3431 return false;
3432 }
3433
3434 // Short-circuit if this was a user gesture.
3435 if (userGesture) {
3436 // createWindow will call openTabAndShow for new Windows and
3437 // that will call tabPicker which will increment
3438 // mAnimationCount.
3439 createWindow(dialog, resultMsg);
3440 return true;
3441 }
3442
3443 // Allow the popup and create the appropriate window.
3444 final AlertDialog.OnClickListener allowListener =
3445 new AlertDialog.OnClickListener() {
3446 public void onClick(DialogInterface d,
3447 int which) {
3448 // Same comment as above for setting
3449 // mAnimationCount.
3450 createWindow(dialog, resultMsg);
3451 // Since we incremented mAnimationCount while the
3452 // dialog was up, we have to decrement it here.
3453 mAnimationCount--;
3454 }
3455 };
3456
3457 // Block the popup by returning a null WebView.
3458 final AlertDialog.OnClickListener blockListener =
3459 new AlertDialog.OnClickListener() {
3460 public void onClick(DialogInterface d, int which) {
3461 resultMsg.sendToTarget();
3462 // We are not going to trigger an animation so
3463 // unblock keys and animation requests.
3464 mAnimationCount--;
3465 }
3466 };
3467
3468 // Build a confirmation dialog to display to the user.
3469 final AlertDialog d =
3470 new AlertDialog.Builder(BrowserActivity.this)
3471 .setTitle(R.string.attention)
3472 .setIcon(android.R.drawable.ic_dialog_alert)
3473 .setMessage(R.string.popup_window_attempt)
3474 .setPositiveButton(R.string.allow, allowListener)
3475 .setNegativeButton(R.string.block, blockListener)
3476 .setCancelable(false)
3477 .create();
3478
3479 // Show the confirmation dialog.
3480 d.show();
3481 // We want to increment mAnimationCount here to prevent a
3482 // potential race condition. If the user allows a pop-up from a
3483 // site and that pop-up then triggers another pop-up, it is
3484 // possible to get the BACK key between here and when the dialog
3485 // appears.
3486 mAnimationCount++;
3487 return true;
3488 }
3489
3490 @Override
3491 public void onCloseWindow(WebView window) {
3492 final int currentIndex = mTabControl.getCurrentIndex();
3493 final TabControl.Tab parent =
3494 mTabControl.getCurrentTab().getParentTab();
3495 if (parent != null) {
3496 // JavaScript can only close popup window.
3497 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3498 }
3499 }
3500
3501 @Override
3502 public void onProgressChanged(WebView view, int newProgress) {
3503 // Block progress updates to the title bar while the tab overview
3504 // is animating or being displayed.
3505 if (mAnimationCount == 0 && mTabOverview == null) {
3506 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3507 newProgress * 100);
3508 }
3509
3510 if (newProgress == 100) {
3511 // onProgressChanged() is called for sub-frame too while
3512 // onPageFinished() is only called for the main frame. sync
3513 // cookie and cache promptly here.
3514 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003515 if (mInLoad) {
3516 mInLoad = false;
3517 updateInLoadMenuItems();
3518 }
3519 } else {
3520 // onPageFinished may have already been called but a subframe
3521 // is still loading and updating the progress. Reset mInLoad
3522 // and update the menu items.
3523 if (!mInLoad) {
3524 mInLoad = true;
3525 updateInLoadMenuItems();
3526 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003527 }
3528 }
3529
3530 @Override
3531 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003532 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003533
3534 // here, if url is null, we want to reset the title
3535 setUrlTitle(url, title);
3536
3537 if (url == null ||
3538 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3539 return;
3540 }
3541 if (url.startsWith("http://www.")) {
3542 url = url.substring(11);
3543 } else if (url.startsWith("http://")) {
3544 url = url.substring(4);
3545 }
3546 try {
3547 url = "%" + url;
3548 String [] selArgs = new String[] { url };
3549
3550 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3551 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3552 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3553 Browser.HISTORY_PROJECTION, where, selArgs, null);
3554 if (c.moveToFirst()) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003555 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003556 Log.v(LOGTAG, "updating cursor");
3557 }
3558 // Current implementation of database only has one entry per
3559 // url.
3560 int titleIndex =
3561 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3562 c.updateString(titleIndex, title);
3563 c.commitUpdates();
3564 }
3565 c.close();
3566 } catch (IllegalStateException e) {
3567 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3568 } catch (SQLiteException ex) {
3569 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3570 }
3571 }
3572
3573 @Override
3574 public void onReceivedIcon(WebView view, Bitmap icon) {
3575 updateIcon(view.getUrl(), icon);
3576 }
3577 };
3578
3579 /**
3580 * Notify the host application a download should be done, or that
3581 * the data should be streamed if a streaming viewer is available.
3582 * @param url The full url to the content that should be downloaded
3583 * @param contentDisposition Content-disposition http header, if
3584 * present.
3585 * @param mimetype The mimetype of the content reported by the server
3586 * @param contentLength The file size reported by the server
3587 */
3588 public void onDownloadStart(String url, String userAgent,
3589 String contentDisposition, String mimetype, long contentLength) {
3590 // if we're dealing wih A/V content that's not explicitly marked
3591 // for download, check if it's streamable.
3592 if (contentDisposition == null
3593 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3594 // query the package manager to see if there's a registered handler
3595 // that matches.
3596 Intent intent = new Intent(Intent.ACTION_VIEW);
3597 intent.setDataAndType(Uri.parse(url), mimetype);
3598 if (getPackageManager().resolveActivity(intent,
3599 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3600 // someone knows how to handle this mime type with this scheme, don't download.
3601 try {
3602 startActivity(intent);
3603 return;
3604 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003605 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003606 Log.d(LOGTAG, "activity not found for " + mimetype
3607 + " over " + Uri.parse(url).getScheme(), ex);
3608 }
3609 // Best behavior is to fall back to a download in this case
3610 }
3611 }
3612 }
3613 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3614 }
3615
3616 /**
3617 * Notify the host application a download should be done, even if there
3618 * is a streaming viewer available for thise type.
3619 * @param url The full url to the content that should be downloaded
3620 * @param contentDisposition Content-disposition http header, if
3621 * present.
3622 * @param mimetype The mimetype of the content reported by the server
3623 * @param contentLength The file size reported by the server
3624 */
3625 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3626 String contentDisposition, String mimetype, long contentLength) {
3627
3628 String filename = URLUtil.guessFileName(url,
3629 contentDisposition, mimetype);
3630
3631 // Check to see if we have an SDCard
3632 String status = Environment.getExternalStorageState();
3633 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3634 int title;
3635 String msg;
3636
3637 // Check to see if the SDCard is busy, same as the music app
3638 if (status.equals(Environment.MEDIA_SHARED)) {
3639 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3640 title = R.string.download_sdcard_busy_dlg_title;
3641 } else {
3642 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3643 title = R.string.download_no_sdcard_dlg_title;
3644 }
3645
3646 new AlertDialog.Builder(this)
3647 .setTitle(title)
3648 .setIcon(android.R.drawable.ic_dialog_alert)
3649 .setMessage(msg)
3650 .setPositiveButton(R.string.ok, null)
3651 .show();
3652 return;
3653 }
3654
3655 // java.net.URI is a lot stricter than KURL so we have to undo
3656 // KURL's percent-encoding and redo the encoding using java.net.URI.
3657 URI uri = null;
3658 try {
3659 // Undo the percent-encoding that KURL may have done.
3660 String newUrl = new String(URLUtil.decode(url.getBytes()));
3661 // Parse the url into pieces
3662 WebAddress w = new WebAddress(newUrl);
3663 String frag = null;
3664 String query = null;
3665 String path = w.mPath;
3666 // Break the path into path, query, and fragment
3667 if (path.length() > 0) {
3668 // Strip the fragment
3669 int idx = path.lastIndexOf('#');
3670 if (idx != -1) {
3671 frag = path.substring(idx + 1);
3672 path = path.substring(0, idx);
3673 }
3674 idx = path.lastIndexOf('?');
3675 if (idx != -1) {
3676 query = path.substring(idx + 1);
3677 path = path.substring(0, idx);
3678 }
3679 }
3680 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3681 query, frag);
3682 } catch (Exception e) {
3683 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3684 return;
3685 }
3686
3687 // XXX: Have to use the old url since the cookies were stored using the
3688 // old percent-encoded url.
3689 String cookies = CookieManager.getInstance().getCookie(url);
3690
3691 ContentValues values = new ContentValues();
3692 values.put(Downloads.URI, uri.toString());
3693 values.put(Downloads.COOKIE_DATA, cookies);
3694 values.put(Downloads.USER_AGENT, userAgent);
3695 values.put(Downloads.NOTIFICATION_PACKAGE,
3696 getPackageName());
3697 values.put(Downloads.NOTIFICATION_CLASS,
3698 BrowserDownloadPage.class.getCanonicalName());
3699 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3700 values.put(Downloads.MIMETYPE, mimetype);
3701 values.put(Downloads.FILENAME_HINT, filename);
3702 values.put(Downloads.DESCRIPTION, uri.getHost());
3703 if (contentLength > 0) {
3704 values.put(Downloads.TOTAL_BYTES, contentLength);
3705 }
3706 if (mimetype == null) {
3707 // We must have long pressed on a link or image to download it. We
3708 // are not sure of the mimetype in this case, so do a head request
3709 new FetchUrlMimeType(this).execute(values);
3710 } else {
3711 final Uri contentUri =
3712 getContentResolver().insert(Downloads.CONTENT_URI, values);
3713 viewDownloads(contentUri);
3714 }
3715
3716 }
3717
3718 /**
3719 * Resets the lock icon. This method is called when we start a new load and
3720 * know the url to be loaded.
3721 */
3722 private void resetLockIcon(String url) {
3723 // Save the lock-icon state (we revert to it if the load gets cancelled)
3724 saveLockIcon();
3725
3726 mLockIconType = LOCK_ICON_UNSECURE;
3727 if (URLUtil.isHttpsUrl(url)) {
3728 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003729 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003730 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3731 " reset lock icon to " + mLockIconType);
3732 }
3733 }
3734
3735 updateLockIconImage(LOCK_ICON_UNSECURE);
3736 }
3737
3738 /**
3739 * Resets the lock icon. This method is called when the icon needs to be
3740 * reset but we do not know whether we are loading a secure or not secure
3741 * page.
3742 */
3743 private void resetLockIcon() {
3744 // Save the lock-icon state (we revert to it if the load gets cancelled)
3745 saveLockIcon();
3746
3747 mLockIconType = LOCK_ICON_UNSECURE;
3748
Dave Bort31a6d1c2009-04-13 15:56:49 -07003749 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003750 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3751 " reset lock icon to " + mLockIconType);
3752 }
3753
3754 updateLockIconImage(LOCK_ICON_UNSECURE);
3755 }
3756
3757 /**
3758 * Updates the lock-icon image in the title-bar.
3759 */
3760 private void updateLockIconImage(int lockIconType) {
3761 Drawable d = null;
3762 if (lockIconType == LOCK_ICON_SECURE) {
3763 d = mSecLockIcon;
3764 } else if (lockIconType == LOCK_ICON_MIXED) {
3765 d = mMixLockIcon;
3766 }
3767 // If the tab overview is animating or being shown, do not update the
3768 // lock icon.
3769 if (mAnimationCount == 0 && mTabOverview == null) {
3770 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3771 }
3772 }
3773
3774 /**
3775 * Displays a page-info dialog.
3776 * @param tab The tab to show info about
3777 * @param fromShowSSLCertificateOnError The flag that indicates whether
3778 * this dialog was opened from the SSL-certificate-on-error dialog or
3779 * not. This is important, since we need to know whether to return to
3780 * the parent dialog or simply dismiss.
3781 */
3782 private void showPageInfo(final TabControl.Tab tab,
3783 final boolean fromShowSSLCertificateOnError) {
3784 final LayoutInflater factory = LayoutInflater
3785 .from(this);
3786
3787 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3788
3789 final WebView view = tab.getWebView();
3790
3791 String url = null;
3792 String title = null;
3793
3794 if (view == null) {
3795 url = tab.getUrl();
3796 title = tab.getTitle();
3797 } else if (view == mTabControl.getCurrentWebView()) {
3798 // Use the cached title and url if this is the current WebView
3799 url = mUrl;
3800 title = mTitle;
3801 } else {
3802 url = view.getUrl();
3803 title = view.getTitle();
3804 }
3805
3806 if (url == null) {
3807 url = "";
3808 }
3809 if (title == null) {
3810 title = "";
3811 }
3812
3813 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3814 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3815
3816 mPageInfoView = tab;
3817 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3818
3819 AlertDialog.Builder alertDialogBuilder =
3820 new AlertDialog.Builder(this)
3821 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3822 .setView(pageInfoView)
3823 .setPositiveButton(
3824 R.string.ok,
3825 new DialogInterface.OnClickListener() {
3826 public void onClick(DialogInterface dialog,
3827 int whichButton) {
3828 mPageInfoDialog = null;
3829 mPageInfoView = null;
3830 mPageInfoFromShowSSLCertificateOnError = null;
3831
3832 // if we came here from the SSL error dialog
3833 if (fromShowSSLCertificateOnError) {
3834 // go back to the SSL error dialog
3835 showSSLCertificateOnError(
3836 mSSLCertificateOnErrorView,
3837 mSSLCertificateOnErrorHandler,
3838 mSSLCertificateOnErrorError);
3839 }
3840 }
3841 })
3842 .setOnCancelListener(
3843 new DialogInterface.OnCancelListener() {
3844 public void onCancel(DialogInterface dialog) {
3845 mPageInfoDialog = null;
3846 mPageInfoView = null;
3847 mPageInfoFromShowSSLCertificateOnError = null;
3848
3849 // if we came here from the SSL error dialog
3850 if (fromShowSSLCertificateOnError) {
3851 // go back to the SSL error dialog
3852 showSSLCertificateOnError(
3853 mSSLCertificateOnErrorView,
3854 mSSLCertificateOnErrorHandler,
3855 mSSLCertificateOnErrorError);
3856 }
3857 }
3858 });
3859
3860 // if we have a main top-level page SSL certificate set or a certificate
3861 // error
3862 if (fromShowSSLCertificateOnError ||
3863 (view != null && view.getCertificate() != null)) {
3864 // add a 'View Certificate' button
3865 alertDialogBuilder.setNeutralButton(
3866 R.string.view_certificate,
3867 new DialogInterface.OnClickListener() {
3868 public void onClick(DialogInterface dialog,
3869 int whichButton) {
3870 mPageInfoDialog = null;
3871 mPageInfoView = null;
3872 mPageInfoFromShowSSLCertificateOnError = null;
3873
3874 // if we came here from the SSL error dialog
3875 if (fromShowSSLCertificateOnError) {
3876 // go back to the SSL error dialog
3877 showSSLCertificateOnError(
3878 mSSLCertificateOnErrorView,
3879 mSSLCertificateOnErrorHandler,
3880 mSSLCertificateOnErrorError);
3881 } else {
3882 // otherwise, display the top-most certificate from
3883 // the chain
3884 if (view.getCertificate() != null) {
3885 showSSLCertificate(tab);
3886 }
3887 }
3888 }
3889 });
3890 }
3891
3892 mPageInfoDialog = alertDialogBuilder.show();
3893 }
3894
3895 /**
3896 * Displays the main top-level page SSL certificate dialog
3897 * (accessible from the Page-Info dialog).
3898 * @param tab The tab to show certificate for.
3899 */
3900 private void showSSLCertificate(final TabControl.Tab tab) {
3901 final View certificateView =
3902 inflateCertificateView(tab.getWebView().getCertificate());
3903 if (certificateView == null) {
3904 return;
3905 }
3906
3907 LayoutInflater factory = LayoutInflater.from(this);
3908
3909 final LinearLayout placeholder =
3910 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3911
3912 LinearLayout ll = (LinearLayout) factory.inflate(
3913 R.layout.ssl_success, placeholder);
3914 ((TextView)ll.findViewById(R.id.success))
3915 .setText(R.string.ssl_certificate_is_valid);
3916
3917 mSSLCertificateView = tab;
3918 mSSLCertificateDialog =
3919 new AlertDialog.Builder(this)
3920 .setTitle(R.string.ssl_certificate).setIcon(
3921 R.drawable.ic_dialog_browser_certificate_secure)
3922 .setView(certificateView)
3923 .setPositiveButton(R.string.ok,
3924 new DialogInterface.OnClickListener() {
3925 public void onClick(DialogInterface dialog,
3926 int whichButton) {
3927 mSSLCertificateDialog = null;
3928 mSSLCertificateView = null;
3929
3930 showPageInfo(tab, false);
3931 }
3932 })
3933 .setOnCancelListener(
3934 new DialogInterface.OnCancelListener() {
3935 public void onCancel(DialogInterface dialog) {
3936 mSSLCertificateDialog = null;
3937 mSSLCertificateView = null;
3938
3939 showPageInfo(tab, false);
3940 }
3941 })
3942 .show();
3943 }
3944
3945 /**
3946 * Displays the SSL error certificate dialog.
3947 * @param view The target web-view.
3948 * @param handler The SSL error handler responsible for cancelling the
3949 * connection that resulted in an SSL error or proceeding per user request.
3950 * @param error The SSL error object.
3951 */
3952 private void showSSLCertificateOnError(
3953 final WebView view, final SslErrorHandler handler, final SslError error) {
3954
3955 final View certificateView =
3956 inflateCertificateView(error.getCertificate());
3957 if (certificateView == null) {
3958 return;
3959 }
3960
3961 LayoutInflater factory = LayoutInflater.from(this);
3962
3963 final LinearLayout placeholder =
3964 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3965
3966 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3967 LinearLayout ll = (LinearLayout)factory
3968 .inflate(R.layout.ssl_warning, placeholder);
3969 ((TextView)ll.findViewById(R.id.warning))
3970 .setText(R.string.ssl_untrusted);
3971 }
3972
3973 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3974 LinearLayout ll = (LinearLayout)factory
3975 .inflate(R.layout.ssl_warning, placeholder);
3976 ((TextView)ll.findViewById(R.id.warning))
3977 .setText(R.string.ssl_mismatch);
3978 }
3979
3980 if (error.hasError(SslError.SSL_EXPIRED)) {
3981 LinearLayout ll = (LinearLayout)factory
3982 .inflate(R.layout.ssl_warning, placeholder);
3983 ((TextView)ll.findViewById(R.id.warning))
3984 .setText(R.string.ssl_expired);
3985 }
3986
3987 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3988 LinearLayout ll = (LinearLayout)factory
3989 .inflate(R.layout.ssl_warning, placeholder);
3990 ((TextView)ll.findViewById(R.id.warning))
3991 .setText(R.string.ssl_not_yet_valid);
3992 }
3993
3994 mSSLCertificateOnErrorHandler = handler;
3995 mSSLCertificateOnErrorView = view;
3996 mSSLCertificateOnErrorError = error;
3997 mSSLCertificateOnErrorDialog =
3998 new AlertDialog.Builder(this)
3999 .setTitle(R.string.ssl_certificate).setIcon(
4000 R.drawable.ic_dialog_browser_certificate_partially_secure)
4001 .setView(certificateView)
4002 .setPositiveButton(R.string.ok,
4003 new DialogInterface.OnClickListener() {
4004 public void onClick(DialogInterface dialog,
4005 int whichButton) {
4006 mSSLCertificateOnErrorDialog = null;
4007 mSSLCertificateOnErrorView = null;
4008 mSSLCertificateOnErrorHandler = null;
4009 mSSLCertificateOnErrorError = null;
4010
4011 mWebViewClient.onReceivedSslError(
4012 view, handler, error);
4013 }
4014 })
4015 .setNeutralButton(R.string.page_info_view,
4016 new DialogInterface.OnClickListener() {
4017 public void onClick(DialogInterface dialog,
4018 int whichButton) {
4019 mSSLCertificateOnErrorDialog = null;
4020
4021 // do not clear the dialog state: we will
4022 // need to show the dialog again once the
4023 // user is done exploring the page-info details
4024
4025 showPageInfo(mTabControl.getTabFromView(view),
4026 true);
4027 }
4028 })
4029 .setOnCancelListener(
4030 new DialogInterface.OnCancelListener() {
4031 public void onCancel(DialogInterface dialog) {
4032 mSSLCertificateOnErrorDialog = null;
4033 mSSLCertificateOnErrorView = null;
4034 mSSLCertificateOnErrorHandler = null;
4035 mSSLCertificateOnErrorError = null;
4036
4037 mWebViewClient.onReceivedSslError(
4038 view, handler, error);
4039 }
4040 })
4041 .show();
4042 }
4043
4044 /**
4045 * Inflates the SSL certificate view (helper method).
4046 * @param certificate The SSL certificate.
4047 * @return The resultant certificate view with issued-to, issued-by,
4048 * issued-on, expires-on, and possibly other fields set.
4049 * If the input certificate is null, returns null.
4050 */
4051 private View inflateCertificateView(SslCertificate certificate) {
4052 if (certificate == null) {
4053 return null;
4054 }
4055
4056 LayoutInflater factory = LayoutInflater.from(this);
4057
4058 View certificateView = factory.inflate(
4059 R.layout.ssl_certificate, null);
4060
4061 // issued to:
4062 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4063 if (issuedTo != null) {
4064 ((TextView) certificateView.findViewById(R.id.to_common))
4065 .setText(issuedTo.getCName());
4066 ((TextView) certificateView.findViewById(R.id.to_org))
4067 .setText(issuedTo.getOName());
4068 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4069 .setText(issuedTo.getUName());
4070 }
4071
4072 // issued by:
4073 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4074 if (issuedBy != null) {
4075 ((TextView) certificateView.findViewById(R.id.by_common))
4076 .setText(issuedBy.getCName());
4077 ((TextView) certificateView.findViewById(R.id.by_org))
4078 .setText(issuedBy.getOName());
4079 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4080 .setText(issuedBy.getUName());
4081 }
4082
4083 // issued on:
4084 String issuedOn = reformatCertificateDate(
4085 certificate.getValidNotBefore());
4086 ((TextView) certificateView.findViewById(R.id.issued_on))
4087 .setText(issuedOn);
4088
4089 // expires on:
4090 String expiresOn = reformatCertificateDate(
4091 certificate.getValidNotAfter());
4092 ((TextView) certificateView.findViewById(R.id.expires_on))
4093 .setText(expiresOn);
4094
4095 return certificateView;
4096 }
4097
4098 /**
4099 * Re-formats the certificate date (Date.toString()) string to
4100 * a properly localized date string.
4101 * @return Properly localized version of the certificate date string and
4102 * the original certificate date string if fails to localize.
4103 * If the original string is null, returns an empty string "".
4104 */
4105 private String reformatCertificateDate(String certificateDate) {
4106 String reformattedDate = null;
4107
4108 if (certificateDate != null) {
4109 Date date = null;
4110 try {
4111 date = java.text.DateFormat.getInstance().parse(certificateDate);
4112 } catch (ParseException e) {
4113 date = null;
4114 }
4115
4116 if (date != null) {
4117 reformattedDate =
4118 DateFormat.getDateFormat(this).format(date);
4119 }
4120 }
4121
4122 return reformattedDate != null ? reformattedDate :
4123 (certificateDate != null ? certificateDate : "");
4124 }
4125
4126 /**
4127 * Displays an http-authentication dialog.
4128 */
4129 private void showHttpAuthentication(final HttpAuthHandler handler,
4130 final String host, final String realm, final String title,
4131 final String name, final String password, int focusId) {
4132 LayoutInflater factory = LayoutInflater.from(this);
4133 final View v = factory
4134 .inflate(R.layout.http_authentication, null);
4135 if (name != null) {
4136 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4137 }
4138 if (password != null) {
4139 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4140 }
4141
4142 String titleText = title;
4143 if (titleText == null) {
4144 titleText = getText(R.string.sign_in_to).toString().replace(
4145 "%s1", host).replace("%s2", realm);
4146 }
4147
4148 mHttpAuthHandler = handler;
4149 AlertDialog dialog = new AlertDialog.Builder(this)
4150 .setTitle(titleText)
4151 .setIcon(android.R.drawable.ic_dialog_alert)
4152 .setView(v)
4153 .setPositiveButton(R.string.action,
4154 new DialogInterface.OnClickListener() {
4155 public void onClick(DialogInterface dialog,
4156 int whichButton) {
4157 String nm = ((EditText) v
4158 .findViewById(R.id.username_edit))
4159 .getText().toString();
4160 String pw = ((EditText) v
4161 .findViewById(R.id.password_edit))
4162 .getText().toString();
4163 BrowserActivity.this.setHttpAuthUsernamePassword
4164 (host, realm, nm, pw);
4165 handler.proceed(nm, pw);
4166 mHttpAuthenticationDialog = null;
4167 mHttpAuthHandler = null;
4168 }})
4169 .setNegativeButton(R.string.cancel,
4170 new DialogInterface.OnClickListener() {
4171 public void onClick(DialogInterface dialog,
4172 int whichButton) {
4173 handler.cancel();
4174 BrowserActivity.this.resetTitleAndRevertLockIcon();
4175 mHttpAuthenticationDialog = null;
4176 mHttpAuthHandler = null;
4177 }})
4178 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4179 public void onCancel(DialogInterface dialog) {
4180 handler.cancel();
4181 BrowserActivity.this.resetTitleAndRevertLockIcon();
4182 mHttpAuthenticationDialog = null;
4183 mHttpAuthHandler = null;
4184 }})
4185 .create();
4186 // Make the IME appear when the dialog is displayed if applicable.
4187 dialog.getWindow().setSoftInputMode(
4188 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4189 dialog.show();
4190 if (focusId != 0) {
4191 dialog.findViewById(focusId).requestFocus();
4192 } else {
4193 v.findViewById(R.id.username_edit).requestFocus();
4194 }
4195 mHttpAuthenticationDialog = dialog;
4196 }
4197
4198 public int getProgress() {
4199 WebView w = mTabControl.getCurrentWebView();
4200 if (w != null) {
4201 return w.getProgress();
4202 } else {
4203 return 100;
4204 }
4205 }
4206
4207 /**
4208 * Set HTTP authentication password.
4209 *
4210 * @param host The host for the password
4211 * @param realm The realm for the password
4212 * @param username The username for the password. If it is null, it means
4213 * password can't be saved.
4214 * @param password The password
4215 */
4216 public void setHttpAuthUsernamePassword(String host, String realm,
4217 String username,
4218 String password) {
4219 WebView w = mTabControl.getCurrentWebView();
4220 if (w != null) {
4221 w.setHttpAuthUsernamePassword(host, realm, username, password);
4222 }
4223 }
4224
4225 /**
4226 * connectivity manager says net has come or gone... inform the user
4227 * @param up true if net has come up, false if net has gone down
4228 */
4229 public void onNetworkToggle(boolean up) {
4230 if (up == mIsNetworkUp) {
4231 return;
4232 } else if (up) {
4233 mIsNetworkUp = true;
4234 if (mAlertDialog != null) {
4235 mAlertDialog.cancel();
4236 mAlertDialog = null;
4237 }
4238 } else {
4239 mIsNetworkUp = false;
4240 if (mInLoad && mAlertDialog == null) {
4241 mAlertDialog = new AlertDialog.Builder(this)
4242 .setTitle(R.string.loadSuspendedTitle)
4243 .setMessage(R.string.loadSuspended)
4244 .setPositiveButton(R.string.ok, null)
4245 .show();
4246 }
4247 }
4248 WebView w = mTabControl.getCurrentWebView();
4249 if (w != null) {
4250 w.setNetworkAvailable(up);
4251 }
4252 }
4253
4254 @Override
4255 protected void onActivityResult(int requestCode, int resultCode,
4256 Intent intent) {
4257 switch (requestCode) {
4258 case COMBO_PAGE:
4259 if (resultCode == RESULT_OK && intent != null) {
4260 String data = intent.getAction();
4261 Bundle extras = intent.getExtras();
4262 if (extras != null && extras.getBoolean("new_window", false)) {
4263 openTab(data);
4264 } else {
4265 final TabControl.Tab currentTab =
4266 mTabControl.getCurrentTab();
4267 // If the Window overview is up and we are not in the
4268 // middle of an animation, animate away from it to the
4269 // current tab.
4270 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004271 sendAnimateFromOverview(currentTab, false, new UrlData(data),
The Android Open Source Project0c908882009-03-03 19:32:16 -08004272 TAB_OVERVIEW_DELAY, null);
4273 } else {
4274 dismissSubWindow(currentTab);
4275 if (data != null && data.length() != 0) {
4276 getTopWindow().loadUrl(data);
4277 }
4278 }
4279 }
4280 }
4281 break;
4282 default:
4283 break;
4284 }
4285 getTopWindow().requestFocus();
4286 }
4287
4288 /*
4289 * This method is called as a result of the user selecting the options
4290 * menu to see the download window, or when a download changes state. It
4291 * shows the download window ontop of the current window.
4292 */
4293 /* package */ void viewDownloads(Uri downloadRecord) {
4294 Intent intent = new Intent(this,
4295 BrowserDownloadPage.class);
4296 intent.setData(downloadRecord);
4297 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4298
4299 }
4300
4301 /**
4302 * Handle results from Tab Switcher mTabOverview tool
4303 */
4304 private class TabListener implements ImageGrid.Listener {
4305 public void remove(int position) {
4306 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004307 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004308 throw new AssertionError();
4309 }
4310
4311 // Remember the current tab.
4312 TabControl.Tab current = mTabControl.getCurrentTab();
4313 final TabControl.Tab remove = mTabControl.getTab(position);
4314 mTabControl.removeTab(remove);
4315 // If we removed the current tab, use the tab at position - 1 if
4316 // possible.
4317 if (current == remove) {
4318 // If the user removes the last tab, act like the New Tab item
4319 // was clicked on.
4320 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004321 current = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004322 sendAnimateFromOverview(current, true,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004323 new UrlData(mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004324 } else {
4325 final int index = position > 0 ? (position - 1) : 0;
4326 current = mTabControl.getTab(index);
4327 }
4328 }
4329
4330 // The tab overview could have been dismissed before this method is
4331 // called.
4332 if (mTabOverview != null) {
4333 // Remove the tab and change the index.
4334 mTabOverview.remove(position);
4335 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4336 }
4337
4338 // Only the current tab ensures its WebView is non-null. This
4339 // implies that we are reloading the freed tab.
4340 mTabControl.setCurrentTab(current);
4341 }
4342 public void onClick(int index) {
4343 // Change the tab if necessary.
4344 // Index equals ImageGrid.CANCEL when pressing back from the tab
4345 // overview.
4346 if (index == ImageGrid.CANCEL) {
4347 index = mTabControl.getCurrentIndex();
4348 // The current index is -1 if the current tab was removed.
4349 if (index == -1) {
4350 // Take the last tab as a fallback.
4351 index = mTabControl.getTabCount() - 1;
4352 }
4353 }
4354
The Android Open Source Project0c908882009-03-03 19:32:16 -08004355 // NEW_TAB means that the "New Tab" cell was clicked on.
4356 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004357 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004358 } else {
4359 sendAnimateFromOverview(mTabControl.getTab(index),
Patrick Scott95d601f2009-06-11 10:06:46 -04004360 false, EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004361 }
4362 }
4363 }
4364
4365 // A fake View that draws the WebView's picture with a fast zoom filter.
4366 // The View is used in case the tab is freed during the animation because
4367 // of low memory.
4368 private static class AnimatingView extends View {
4369 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4370 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4371 private static final DrawFilter sZoomFilter =
4372 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4373 private final Picture mPicture;
4374 private final float mScale;
4375 private final int mScrollX;
4376 private final int mScrollY;
4377 final TabControl.Tab mTab;
4378
4379 AnimatingView(Context ctxt, TabControl.Tab t) {
4380 super(ctxt);
4381 mTab = t;
4382 // Use the top window in the animation since the tab overview will
4383 // display the top window in each cell.
4384 final WebView w = t.getTopWindow();
4385 mPicture = w.capturePicture();
4386 mScale = w.getScale() / w.getWidth();
4387 mScrollX = w.getScrollX();
4388 mScrollY = w.getScrollY();
4389 }
4390
4391 @Override
4392 protected void onDraw(Canvas canvas) {
4393 canvas.save();
4394 canvas.drawColor(Color.WHITE);
4395 if (mPicture != null) {
4396 canvas.setDrawFilter(sZoomFilter);
4397 float scale = getWidth() * mScale;
4398 canvas.scale(scale, scale);
4399 canvas.translate(-mScrollX, -mScrollY);
4400 canvas.drawPicture(mPicture);
4401 }
4402 canvas.restore();
4403 }
4404 }
4405
4406 /**
4407 * Open the tab picker. This function will always use the current tab in
4408 * its animation.
4409 * @param stay boolean stating whether the tab picker is to remain open
4410 * (in which case it needs a listener and its menu) or not.
4411 * @param index The index of the tab to show as the selection in the tab
4412 * overview.
4413 * @param remove If true, the tab at index will be removed after the
4414 * animation completes.
4415 */
4416 private void tabPicker(final boolean stay, final int index,
4417 final boolean remove) {
4418 if (mTabOverview != null) {
4419 return;
4420 }
4421
4422 int size = mTabControl.getTabCount();
4423
4424 TabListener l = null;
4425 if (stay) {
4426 l = mTabListener = new TabListener();
4427 }
4428 mTabOverview = new ImageGrid(this, stay, l);
4429
4430 for (int i = 0; i < size; i++) {
4431 final TabControl.Tab t = mTabControl.getTab(i);
4432 mTabControl.populatePickerData(t);
4433 mTabOverview.add(t);
4434 }
4435
4436 // Tell the tab overview to show the current tab, the tab overview will
4437 // handle the "New Tab" case.
4438 int currentIndex = mTabControl.getCurrentIndex();
4439 mTabOverview.setCurrentIndex(currentIndex);
4440
4441 // Attach the tab overview.
4442 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4443
4444 // Create a fake AnimatingView to animate the WebView's picture.
4445 final TabControl.Tab current = mTabControl.getCurrentTab();
4446 final AnimatingView v = new AnimatingView(this, current);
4447 mContentView.addView(v, COVER_SCREEN_PARAMS);
4448 removeTabFromContentView(current);
4449 // Pause timers to get the animation smoother.
4450 current.getWebView().pauseTimers();
4451
4452 // Send a message so the tab picker has a chance to layout and get
4453 // positions for all the cells.
4454 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4455 index, remove ? 1 : 0, v));
4456 // Setting this will indicate that we are animating to the overview. We
4457 // set it here to prevent another request to animate from coming in
4458 // between now and when ANIMATE_TO_OVERVIEW is handled.
4459 mAnimationCount++;
4460 // Always change the title bar to the window overview title while
4461 // animating.
4462 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4463 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4464 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4465 Window.PROGRESS_VISIBILITY_OFF);
4466 setTitle(R.string.tab_picker_title);
4467 // Make the menu empty until the animation completes.
4468 mMenuState = EMPTY_MENU;
4469 }
4470
4471 private void bookmarksOrHistoryPicker(boolean startWithHistory) {
4472 WebView current = mTabControl.getCurrentWebView();
4473 if (current == null) {
4474 return;
4475 }
4476 Intent intent = new Intent(this,
4477 CombinedBookmarkHistoryActivity.class);
4478 String title = current.getTitle();
4479 String url = current.getUrl();
4480 // Just in case the user opens bookmarks before a page finishes loading
4481 // so the current history item, and therefore the page, is null.
4482 if (null == url) {
4483 url = mLastEnteredUrl;
4484 // This can happen.
4485 if (null == url) {
4486 url = mSettings.getHomePage();
4487 }
4488 }
4489 // In case the web page has not yet received its associated title.
4490 if (title == null) {
4491 title = url;
4492 }
4493 intent.putExtra("title", title);
4494 intent.putExtra("url", url);
4495 intent.putExtra("maxTabsOpen",
4496 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4497 if (startWithHistory) {
4498 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4499 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4500 }
4501 startActivityForResult(intent, COMBO_PAGE);
4502 }
4503
4504 // Called when loading from context menu or LOAD_URL message
4505 private void loadURL(WebView view, String url) {
4506 // In case the user enters nothing.
4507 if (url != null && url.length() != 0 && view != null) {
4508 url = smartUrlFilter(url);
4509 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4510 view.loadUrl(url);
4511 }
4512 }
4513 }
4514
4515 private void checkMemory() {
4516 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4517 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4518 .getMemoryInfo(mi);
4519 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4520 // mi.threshold) for now
4521 // if (mi.lowMemory) {
4522 if (mi.availMem < mi.threshold) {
4523 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4524 + (mi.availMem / 1024) + "K threshold="
4525 + (mi.threshold / 1024) + "K");
4526 mTabControl.freeMemory();
4527 }
4528 }
4529
4530 private String smartUrlFilter(Uri inUri) {
4531 if (inUri != null) {
4532 return smartUrlFilter(inUri.toString());
4533 }
4534 return null;
4535 }
4536
4537
4538 // get window count
4539
4540 int getWindowCount(){
4541 if(mTabControl != null){
4542 return mTabControl.getTabCount();
4543 }
4544 return 0;
4545 }
4546
4547 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4548 "(?i)" + // switch on case insensitive matching
4549 "(" + // begin group for schema
4550 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004551 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004552 ")" +
4553 "(.*)" );
4554
4555 /**
4556 * Attempts to determine whether user input is a URL or search
4557 * terms. Anything with a space is passed to search.
4558 *
4559 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4560 * "Http://" converts to "http://"
4561 *
4562 * @return Original or modified URL
4563 *
4564 */
4565 String smartUrlFilter(String url) {
4566
4567 String inUrl = url.trim();
4568 boolean hasSpace = inUrl.indexOf(' ') != -1;
4569
4570 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4571 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004572 // force scheme to lowercase
4573 String scheme = matcher.group(1);
4574 String lcScheme = scheme.toLowerCase();
4575 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004576 inUrl = lcScheme + matcher.group(2);
4577 }
4578 if (hasSpace) {
4579 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004580 }
4581 return inUrl;
4582 }
4583 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004584 // FIXME: Is this the correct place to add to searches?
4585 // what if someone else calls this function?
4586 int shortcut = parseUrlShortcut(inUrl);
4587 if (shortcut != SHORTCUT_INVALID) {
4588 Browser.addSearchUrl(mResolver, inUrl);
4589 String query = inUrl.substring(2);
4590 switch (shortcut) {
4591 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004592 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004593 case SHORTCUT_WIKIPEDIA_SEARCH:
4594 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4595 case SHORTCUT_DICTIONARY_SEARCH:
4596 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4597 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004598 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004599 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004600 }
4601 }
4602 } else {
4603 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4604 return URLUtil.guessUrl(inUrl);
4605 }
4606 }
4607
4608 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004609 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004610 }
4611
4612 private final static int LOCK_ICON_UNSECURE = 0;
4613 private final static int LOCK_ICON_SECURE = 1;
4614 private final static int LOCK_ICON_MIXED = 2;
4615
4616 private int mLockIconType = LOCK_ICON_UNSECURE;
4617 private int mPrevLockType = LOCK_ICON_UNSECURE;
4618
4619 private BrowserSettings mSettings;
4620 private TabControl mTabControl;
4621 private ContentResolver mResolver;
4622 private FrameLayout mContentView;
4623 private ImageGrid mTabOverview;
4624
4625 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4626 // view, we should rewrite this.
4627 private int mCurrentMenuState = 0;
4628 private int mMenuState = R.id.MAIN_MENU;
4629 private static final int EMPTY_MENU = -1;
4630 private Menu mMenu;
4631
4632 private FindDialog mFindDialog;
4633 // Used to prevent chording to result in firing two shortcuts immediately
4634 // one after another. Fixes bug 1211714.
4635 boolean mCanChord;
4636
4637 private boolean mInLoad;
4638 private boolean mIsNetworkUp;
4639
4640 private boolean mPageStarted;
4641 private boolean mActivityInPause = true;
4642
4643 private boolean mMenuIsDown;
4644
4645 private final KeyTracker mKeyTracker = new KeyTracker(this);
4646
4647 // As trackball doesn't send repeat down, we have to track it ourselves
4648 private boolean mTrackTrackball;
4649
4650 private static boolean mInTrace;
4651
4652 // Performance probe
4653 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4654 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4655 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4656 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4657 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4658 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4659 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4660 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4661 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4662 };
4663
4664 private long mStart;
4665 private long mProcessStart;
4666 private long mUserStart;
4667 private long mSystemStart;
4668 private long mIdleStart;
4669 private long mIrqStart;
4670
4671 private long mUiStart;
4672
4673 private Drawable mMixLockIcon;
4674 private Drawable mSecLockIcon;
4675 private Drawable mGenericFavicon;
4676
4677 /* hold a ref so we can auto-cancel if necessary */
4678 private AlertDialog mAlertDialog;
4679
4680 // Wait for credentials before loading google.com
4681 private ProgressDialog mCredsDlg;
4682
4683 // The up-to-date URL and title (these can be different from those stored
4684 // in WebView, since it takes some time for the information in WebView to
4685 // get updated)
4686 private String mUrl;
4687 private String mTitle;
4688
4689 // As PageInfo has different style for landscape / portrait, we have
4690 // to re-open it when configuration changed
4691 private AlertDialog mPageInfoDialog;
4692 private TabControl.Tab mPageInfoView;
4693 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4694 // dialog, we should not just dismiss it, but should get back to the
4695 // SSL-certificate-on-error dialog. This flag is used to store this state
4696 private Boolean mPageInfoFromShowSSLCertificateOnError;
4697
4698 // as SSLCertificateOnError has different style for landscape / portrait,
4699 // we have to re-open it when configuration changed
4700 private AlertDialog mSSLCertificateOnErrorDialog;
4701 private WebView mSSLCertificateOnErrorView;
4702 private SslErrorHandler mSSLCertificateOnErrorHandler;
4703 private SslError mSSLCertificateOnErrorError;
4704
4705 // as SSLCertificate has different style for landscape / portrait, we
4706 // have to re-open it when configuration changed
4707 private AlertDialog mSSLCertificateDialog;
4708 private TabControl.Tab mSSLCertificateView;
4709
4710 // as HttpAuthentication has different style for landscape / portrait, we
4711 // have to re-open it when configuration changed
4712 private AlertDialog mHttpAuthenticationDialog;
4713 private HttpAuthHandler mHttpAuthHandler;
4714
4715 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4716 new FrameLayout.LayoutParams(
4717 ViewGroup.LayoutParams.FILL_PARENT,
4718 ViewGroup.LayoutParams.FILL_PARENT);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004719 // Google search
4720 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004721 // Wikipedia search
4722 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4723 // Dictionary search
4724 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4725 // Google Mobile Local search
4726 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4727
4728 final static String QUERY_PLACE_HOLDER = "%s";
4729
4730 // "source" parameter for Google search through search key
4731 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4732 // "source" parameter for Google search through goto menu
4733 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4734 // "source" parameter for Google search through simplily type
4735 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4736 // "source" parameter for Google search suggested by the browser
4737 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4738 // "source" parameter for Google search from unknown source
4739 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4740
4741 private final static String LOGTAG = "browser";
4742
4743 private TabListener mTabListener;
4744
4745 private String mLastEnteredUrl;
4746
4747 private PowerManager.WakeLock mWakeLock;
4748 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4749
4750 private Toast mStopToast;
4751
4752 // Used during animations to prevent other animations from being triggered.
4753 // A count is used since the animation to and from the Window overview can
4754 // overlap. A count of 0 means no animation where a count of > 0 means
4755 // there are animations in progress.
4756 private int mAnimationCount;
4757
4758 // As the ids are dynamically created, we can't guarantee that they will
4759 // be in sequence, so this static array maps ids to a window number.
4760 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4761 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4762 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4763 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4764
4765 // monitor platform changes
4766 private IntentFilter mNetworkStateChangedFilter;
4767 private BroadcastReceiver mNetworkStateIntentReceiver;
4768
4769 // activity requestCode
4770 final static int COMBO_PAGE = 1;
4771 final static int DOWNLOAD_PAGE = 2;
4772 final static int PREFERENCES_PAGE = 3;
4773
4774 // the frenquency of checking whether system memory is low
4775 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004776
4777 /**
4778 * A UrlData class to abstract how the content will be set to WebView.
4779 * This base class uses loadUrl to show the content.
4780 */
4781 private static class UrlData {
4782 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004783 byte[] mPostData;
4784
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004785 UrlData(String url) {
4786 this.mUrl = url;
4787 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004788
4789 void setPostData(byte[] postData) {
4790 mPostData = postData;
4791 }
4792
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004793 boolean isEmpty() {
4794 return mUrl == null || mUrl.length() == 0;
4795 }
4796
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004797 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004798 if (mPostData != null) {
4799 webView.postUrl(mUrl, mPostData);
4800 } else {
4801 webView.loadUrl(mUrl);
4802 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004803 }
4804 };
4805
4806 /**
4807 * A subclass of UrlData class that can display inlined content using
4808 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4809 */
4810 private static class InlinedUrlData extends UrlData {
4811 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4812 super(failUrl);
4813 mInlined = inlined;
4814 mMimeType = mimeType;
4815 mEncoding = encoding;
4816 }
4817 String mMimeType;
4818 String mInlined;
4819 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004820 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004821 boolean isEmpty() {
4822 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4823 }
4824
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004825 @Override
4826 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004827 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4828 }
4829 }
4830
4831 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004832}