blob: d0fa0bd321c5f73293132093abbb8863f96410bb [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();
1198 dismissSubWindow(t);
1199 removeTabFromContentView(t);
1200 // Destroy all the tabs
1201 mTabControl.destroy();
1202 WebIconDatabase.getInstance().close();
1203 if (mGlsConnection != null) {
1204 unbindService(mGlsConnection);
1205 mGlsConnection = null;
1206 }
1207
1208 //
1209 // stop MASF proxy service
1210 //
1211 //Intent proxyServiceIntent = new Intent();
1212 //proxyServiceIntent.setComponent
1213 // (new ComponentName(
1214 // "com.android.masfproxyservice",
1215 // "com.android.masfproxyservice.MasfProxyService"));
1216 //stopService(proxyServiceIntent);
1217 }
1218
1219 @Override
1220 public void onConfigurationChanged(Configuration newConfig) {
1221 super.onConfigurationChanged(newConfig);
1222
1223 if (mPageInfoDialog != null) {
1224 mPageInfoDialog.dismiss();
1225 showPageInfo(
1226 mPageInfoView,
1227 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1228 }
1229 if (mSSLCertificateDialog != null) {
1230 mSSLCertificateDialog.dismiss();
1231 showSSLCertificate(
1232 mSSLCertificateView);
1233 }
1234 if (mSSLCertificateOnErrorDialog != null) {
1235 mSSLCertificateOnErrorDialog.dismiss();
1236 showSSLCertificateOnError(
1237 mSSLCertificateOnErrorView,
1238 mSSLCertificateOnErrorHandler,
1239 mSSLCertificateOnErrorError);
1240 }
1241 if (mHttpAuthenticationDialog != null) {
1242 String title = ((TextView) mHttpAuthenticationDialog
1243 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1244 .toString();
1245 String name = ((TextView) mHttpAuthenticationDialog
1246 .findViewById(R.id.username_edit)).getText().toString();
1247 String password = ((TextView) mHttpAuthenticationDialog
1248 .findViewById(R.id.password_edit)).getText().toString();
1249 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1250 .getId();
1251 mHttpAuthenticationDialog.dismiss();
1252 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1253 name, password, focusId);
1254 }
1255 if (mFindDialog != null && mFindDialog.isShowing()) {
1256 mFindDialog.onConfigurationChanged(newConfig);
1257 }
1258 }
1259
1260 @Override public void onLowMemory() {
1261 super.onLowMemory();
1262 mTabControl.freeMemory();
1263 }
1264
1265 private boolean resumeWebView() {
1266 if ((!mActivityInPause && !mPageStarted) ||
1267 (mActivityInPause && mPageStarted)) {
1268 CookieSyncManager.getInstance().startSync();
1269 WebView w = mTabControl.getCurrentWebView();
1270 if (w != null) {
1271 w.resumeTimers();
1272 }
1273 return true;
1274 } else {
1275 return false;
1276 }
1277 }
1278
1279 private boolean pauseWebView() {
1280 if (mActivityInPause && !mPageStarted) {
1281 CookieSyncManager.getInstance().stopSync();
1282 WebView w = mTabControl.getCurrentWebView();
1283 if (w != null) {
1284 w.pauseTimers();
1285 }
1286 return true;
1287 } else {
1288 return false;
1289 }
1290 }
1291
1292 /*
1293 * This function is called when we are launching for the first time. We
1294 * are waiting for the login credentials before loading Google home
1295 * pages. This way the user will be logged in straight away.
1296 */
1297 private void waitForCredentials() {
1298 // Show a toast
1299 mCredsDlg = new ProgressDialog(this);
1300 mCredsDlg.setIndeterminate(true);
1301 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1302 // If the user cancels the operation, then cancel the Google
1303 // Credentials request.
1304 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1305 mCredsDlg.show();
1306
1307 // We set a timeout for the retrieval of credentials in onResume()
1308 // as that is when we have freed up some CPU time to get
1309 // the login credentials.
1310 }
1311
1312 /*
1313 * If we have received the credentials or we have timed out and we are
1314 * showing the credentials dialog, then it is time to move on.
1315 */
1316 private void resumeAfterCredentials() {
1317 if (mCredsDlg == null) {
1318 return;
1319 }
1320
1321 // Clear the toast
1322 if (mCredsDlg.isShowing()) {
1323 mCredsDlg.dismiss();
1324 }
1325 mCredsDlg = null;
1326
1327 // Clear any pending timeout
1328 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1329
1330 // Load the page
1331 WebView w = mTabControl.getCurrentWebView();
1332 if (w != null) {
1333 w.loadUrl(mSettings.getHomePage());
1334 }
1335
1336 // Update the settings, need to do this last as it can take a moment
1337 // to persist the settings. In the mean time we could be loading
1338 // content.
1339 mSettings.setLoginInitialized(this);
1340 }
1341
1342 // Open the icon database and retain all the icons for visited sites.
1343 private void retainIconsOnStartup() {
1344 final WebIconDatabase db = WebIconDatabase.getInstance();
1345 db.open(getDir("icons", 0).getPath());
1346 try {
1347 Cursor c = Browser.getAllBookmarks(mResolver);
1348 if (!c.moveToFirst()) {
1349 c.deactivate();
1350 return;
1351 }
1352 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1353 do {
1354 String url = c.getString(urlIndex);
1355 db.retainIconForPageUrl(url);
1356 } while (c.moveToNext());
1357 c.deactivate();
1358 } catch (IllegalStateException e) {
1359 Log.e(LOGTAG, "retainIconsOnStartup", e);
1360 }
1361 }
1362
1363 // Helper method for getting the top window.
1364 WebView getTopWindow() {
1365 return mTabControl.getCurrentTopWebView();
1366 }
1367
1368 @Override
1369 public boolean onCreateOptionsMenu(Menu menu) {
1370 super.onCreateOptionsMenu(menu);
1371
1372 MenuInflater inflater = getMenuInflater();
1373 inflater.inflate(R.menu.browser, menu);
1374 mMenu = menu;
1375 updateInLoadMenuItems();
1376 return true;
1377 }
1378
1379 /**
1380 * As the menu can be open when loading state changes
1381 * we must manually update the state of the stop/reload menu
1382 * item
1383 */
1384 private void updateInLoadMenuItems() {
1385 if (mMenu == null) {
1386 return;
1387 }
1388 MenuItem src = mInLoad ?
1389 mMenu.findItem(R.id.stop_menu_id):
1390 mMenu.findItem(R.id.reload_menu_id);
1391 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1392 dest.setIcon(src.getIcon());
1393 dest.setTitle(src.getTitle());
1394 }
1395
1396 @Override
1397 public boolean onContextItemSelected(MenuItem item) {
1398 // chording is not an issue with context menus, but we use the same
1399 // options selector, so set mCanChord to true so we can access them.
1400 mCanChord = true;
1401 int id = item.getItemId();
1402 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001403 if (null == webView) {
1404 return false;
1405 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001406 final HashMap hrefMap = new HashMap();
1407 hrefMap.put("webview", webView);
1408 final Message msg = mHandler.obtainMessage(
1409 FOCUS_NODE_HREF, id, 0, hrefMap);
1410 switch (id) {
1411 // -- Browser context menu
1412 case R.id.open_context_menu_id:
1413 case R.id.open_newtab_context_menu_id:
1414 case R.id.bookmark_context_menu_id:
1415 case R.id.save_link_context_menu_id:
1416 case R.id.share_link_context_menu_id:
1417 case R.id.copy_link_context_menu_id:
1418 webView.requestFocusNodeHref(msg);
1419 break;
1420
1421 default:
1422 // For other context menus
1423 return onOptionsItemSelected(item);
1424 }
1425 mCanChord = false;
1426 return true;
1427 }
1428
1429 private Bundle createGoogleSearchSourceBundle(String source) {
1430 Bundle bundle = new Bundle();
1431 bundle.putString(SearchManager.SOURCE, source);
1432 return bundle;
1433 }
1434
1435 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001436 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001437 */
1438 @Override
1439 public boolean onSearchRequested() {
1440 startSearch(null, false,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001441 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001442 return true;
1443 }
1444
1445 @Override
1446 public void startSearch(String initialQuery, boolean selectInitialQuery,
1447 Bundle appSearchData, boolean globalSearch) {
1448 if (appSearchData == null) {
1449 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1450 }
1451 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1452 }
1453
1454 @Override
1455 public boolean onOptionsItemSelected(MenuItem item) {
1456 if (!mCanChord) {
1457 // The user has already fired a shortcut with this hold down of the
1458 // menu key.
1459 return false;
1460 }
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001461 if (null == mTabOverview && null == getTopWindow()) {
1462 return false;
1463 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001464 switch (item.getItemId()) {
1465 // -- Main menu
1466 case R.id.goto_menu_id: {
1467 String url = getTopWindow().getUrl();
1468 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1469 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
1470 }
1471 break;
1472
1473 case R.id.bookmarks_menu_id:
1474 bookmarksOrHistoryPicker(false);
1475 break;
1476
1477 case R.id.windows_menu_id:
1478 if (mTabControl.getTabCount() == 1) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001479 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001480 } else {
1481 tabPicker(true, mTabControl.getCurrentIndex(), false);
1482 }
1483 break;
1484
1485 case R.id.stop_reload_menu_id:
1486 if (mInLoad) {
1487 stopLoading();
1488 } else {
1489 getTopWindow().reload();
1490 }
1491 break;
1492
1493 case R.id.back_menu_id:
1494 getTopWindow().goBack();
1495 break;
1496
1497 case R.id.forward_menu_id:
1498 getTopWindow().goForward();
1499 break;
1500
1501 case R.id.close_menu_id:
1502 // Close the subwindow if it exists.
1503 if (mTabControl.getCurrentSubWindow() != null) {
1504 dismissSubWindow(mTabControl.getCurrentTab());
1505 break;
1506 }
1507 final int currentIndex = mTabControl.getCurrentIndex();
1508 final TabControl.Tab parent =
1509 mTabControl.getCurrentTab().getParentTab();
1510 int indexToShow = -1;
1511 if (parent != null) {
1512 indexToShow = mTabControl.getTabIndex(parent);
1513 } else {
1514 // Get the last tab in the list. If it is the current tab,
1515 // subtract 1 more.
1516 indexToShow = mTabControl.getTabCount() - 1;
1517 if (currentIndex == indexToShow) {
1518 indexToShow--;
1519 }
1520 }
1521 switchTabs(currentIndex, indexToShow, true);
1522 break;
1523
1524 case R.id.homepage_menu_id:
1525 TabControl.Tab current = mTabControl.getCurrentTab();
1526 if (current != null) {
1527 dismissSubWindow(current);
1528 current.getWebView().loadUrl(mSettings.getHomePage());
1529 }
1530 break;
1531
1532 case R.id.preferences_menu_id:
1533 Intent intent = new Intent(this,
1534 BrowserPreferencesPage.class);
1535 startActivityForResult(intent, PREFERENCES_PAGE);
1536 break;
1537
1538 case R.id.find_menu_id:
1539 if (null == mFindDialog) {
1540 mFindDialog = new FindDialog(this);
1541 }
1542 mFindDialog.setWebView(getTopWindow());
1543 mFindDialog.show();
1544 mMenuState = EMPTY_MENU;
1545 break;
1546
1547 case R.id.select_text_id:
1548 getTopWindow().emulateShiftHeld();
1549 break;
1550 case R.id.page_info_menu_id:
1551 showPageInfo(mTabControl.getCurrentTab(), false);
1552 break;
1553
1554 case R.id.classic_history_menu_id:
1555 bookmarksOrHistoryPicker(true);
1556 break;
1557
1558 case R.id.share_page_menu_id:
1559 Browser.sendString(this, getTopWindow().getUrl());
1560 break;
1561
1562 case R.id.dump_nav_menu_id:
1563 getTopWindow().debugDump();
1564 break;
1565
1566 case R.id.zoom_in_menu_id:
1567 getTopWindow().zoomIn();
1568 break;
1569
1570 case R.id.zoom_out_menu_id:
1571 getTopWindow().zoomOut();
1572 break;
1573
1574 case R.id.view_downloads_menu_id:
1575 viewDownloads(null);
1576 break;
1577
1578 // -- Tab menu
1579 case R.id.view_tab_menu_id:
1580 if (mTabListener != null && mTabOverview != null) {
1581 int pos = mTabOverview.getContextMenuPosition(item);
1582 mTabOverview.setCurrentIndex(pos);
1583 mTabListener.onClick(pos);
1584 }
1585 break;
1586
1587 case R.id.remove_tab_menu_id:
1588 if (mTabListener != null && mTabOverview != null) {
1589 int pos = mTabOverview.getContextMenuPosition(item);
1590 mTabListener.remove(pos);
1591 }
1592 break;
1593
1594 case R.id.new_tab_menu_id:
1595 // No need to check for mTabOverview here since we are not
1596 // dependent on it for a position.
1597 if (mTabListener != null) {
1598 // If the overview happens to be non-null, make the "New
1599 // Tab" cell visible.
1600 if (mTabOverview != null) {
1601 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1602 }
1603 mTabListener.onClick(ImageGrid.NEW_TAB);
1604 }
1605 break;
1606
1607 case R.id.bookmark_tab_menu_id:
1608 if (mTabListener != null && mTabOverview != null) {
1609 int pos = mTabOverview.getContextMenuPosition(item);
1610 TabControl.Tab t = mTabControl.getTab(pos);
1611 // Since we called populatePickerData for all of the
1612 // tabs, getTitle and getUrl will return appropriate
1613 // values.
1614 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1615 t.getUrl());
1616 }
1617 break;
1618
1619 case R.id.history_tab_menu_id:
1620 bookmarksOrHistoryPicker(true);
1621 break;
1622
1623 case R.id.bookmarks_tab_menu_id:
1624 bookmarksOrHistoryPicker(false);
1625 break;
1626
1627 case R.id.properties_tab_menu_id:
1628 if (mTabListener != null && mTabOverview != null) {
1629 int pos = mTabOverview.getContextMenuPosition(item);
1630 showPageInfo(mTabControl.getTab(pos), false);
1631 }
1632 break;
1633
1634 case R.id.window_one_menu_id:
1635 case R.id.window_two_menu_id:
1636 case R.id.window_three_menu_id:
1637 case R.id.window_four_menu_id:
1638 case R.id.window_five_menu_id:
1639 case R.id.window_six_menu_id:
1640 case R.id.window_seven_menu_id:
1641 case R.id.window_eight_menu_id:
1642 {
1643 int menuid = item.getItemId();
1644 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1645 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1646 TabControl.Tab desiredTab = mTabControl.getTab(id);
1647 if (desiredTab != null &&
1648 desiredTab != mTabControl.getCurrentTab()) {
1649 switchTabs(mTabControl.getCurrentIndex(), id, false);
1650 }
1651 break;
1652 }
1653 }
1654 }
1655 break;
1656
1657 default:
1658 if (!super.onOptionsItemSelected(item)) {
1659 return false;
1660 }
1661 // Otherwise fall through.
1662 }
1663 mCanChord = false;
1664 return true;
1665 }
1666
1667 public void closeFind() {
1668 mMenuState = R.id.MAIN_MENU;
1669 }
1670
1671 @Override public boolean onPrepareOptionsMenu(Menu menu)
1672 {
1673 // This happens when the user begins to hold down the menu key, so
1674 // allow them to chord to get a shortcut.
1675 mCanChord = true;
1676 // Note: setVisible will decide whether an item is visible; while
1677 // setEnabled() will decide whether an item is enabled, which also means
1678 // whether the matching shortcut key will function.
1679 super.onPrepareOptionsMenu(menu);
1680 switch (mMenuState) {
1681 case R.id.TAB_MENU:
1682 if (mCurrentMenuState != mMenuState) {
1683 menu.setGroupVisible(R.id.MAIN_MENU, false);
1684 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1685 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1686 menu.setGroupVisible(R.id.TAB_MENU, true);
1687 menu.setGroupEnabled(R.id.TAB_MENU, true);
1688 }
1689 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1690 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1691 tab.setVisible(newT);
1692 tab.setEnabled(newT);
1693 break;
1694 case EMPTY_MENU:
1695 if (mCurrentMenuState != mMenuState) {
1696 menu.setGroupVisible(R.id.MAIN_MENU, false);
1697 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1698 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1699 menu.setGroupVisible(R.id.TAB_MENU, false);
1700 menu.setGroupEnabled(R.id.TAB_MENU, false);
1701 }
1702 break;
1703 default:
1704 if (mCurrentMenuState != mMenuState) {
1705 menu.setGroupVisible(R.id.MAIN_MENU, true);
1706 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1707 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1708 menu.setGroupVisible(R.id.TAB_MENU, false);
1709 menu.setGroupEnabled(R.id.TAB_MENU, false);
1710 }
1711 final WebView w = getTopWindow();
1712 boolean canGoBack = false;
1713 boolean canGoForward = false;
1714 boolean isHome = false;
1715 if (w != null) {
1716 canGoBack = w.canGoBack();
1717 canGoForward = w.canGoForward();
1718 isHome = mSettings.getHomePage().equals(w.getUrl());
1719 }
1720 final MenuItem back = menu.findItem(R.id.back_menu_id);
1721 back.setEnabled(canGoBack);
1722
1723 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1724 home.setEnabled(!isHome);
1725
1726 menu.findItem(R.id.forward_menu_id)
1727 .setEnabled(canGoForward);
1728
1729 // decide whether to show the share link option
1730 PackageManager pm = getPackageManager();
1731 Intent send = new Intent(Intent.ACTION_SEND);
1732 send.setType("text/plain");
1733 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1734 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1735
1736 // If there is only 1 window, the text will be "New window"
1737 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1738 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1739 getString(R.string.view_tabs_condensed) :
1740 getString(R.string.tab_picker_new_tab));
1741
1742 boolean isNavDump = mSettings.isNavDump();
1743 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1744 nav.setVisible(isNavDump);
1745 nav.setEnabled(isNavDump);
1746 break;
1747 }
1748 mCurrentMenuState = mMenuState;
1749 return true;
1750 }
1751
1752 @Override
1753 public void onCreateContextMenu(ContextMenu menu, View v,
1754 ContextMenuInfo menuInfo) {
1755 WebView webview = (WebView) v;
1756 WebView.HitTestResult result = webview.getHitTestResult();
1757 if (result == null) {
1758 return;
1759 }
1760
1761 int type = result.getType();
1762 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1763 Log.w(LOGTAG,
1764 "We should not show context menu when nothing is touched");
1765 return;
1766 }
1767 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1768 // let TextView handles context menu
1769 return;
1770 }
1771
1772 // Note, http://b/issue?id=1106666 is requesting that
1773 // an inflated menu can be used again. This is not available
1774 // yet, so inflate each time (yuk!)
1775 MenuInflater inflater = getMenuInflater();
1776 inflater.inflate(R.menu.browsercontext, menu);
1777
1778 // Show the correct menu group
1779 String extra = result.getExtra();
1780 menu.setGroupVisible(R.id.PHONE_MENU,
1781 type == WebView.HitTestResult.PHONE_TYPE);
1782 menu.setGroupVisible(R.id.EMAIL_MENU,
1783 type == WebView.HitTestResult.EMAIL_TYPE);
1784 menu.setGroupVisible(R.id.GEO_MENU,
1785 type == WebView.HitTestResult.GEO_TYPE);
1786 menu.setGroupVisible(R.id.IMAGE_MENU,
1787 type == WebView.HitTestResult.IMAGE_TYPE
1788 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1789 menu.setGroupVisible(R.id.ANCHOR_MENU,
1790 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1791 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1792
1793 // Setup custom handling depending on the type
1794 switch (type) {
1795 case WebView.HitTestResult.PHONE_TYPE:
1796 menu.setHeaderTitle(Uri.decode(extra));
1797 menu.findItem(R.id.dial_context_menu_id).setIntent(
1798 new Intent(Intent.ACTION_VIEW, Uri
1799 .parse(WebView.SCHEME_TEL + extra)));
1800 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1801 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1802 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1803 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1804 addIntent);
1805 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1806 new Copy(extra));
1807 break;
1808
1809 case WebView.HitTestResult.EMAIL_TYPE:
1810 menu.setHeaderTitle(extra);
1811 menu.findItem(R.id.email_context_menu_id).setIntent(
1812 new Intent(Intent.ACTION_VIEW, Uri
1813 .parse(WebView.SCHEME_MAILTO + extra)));
1814 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1815 new Copy(extra));
1816 break;
1817
1818 case WebView.HitTestResult.GEO_TYPE:
1819 menu.setHeaderTitle(extra);
1820 menu.findItem(R.id.map_context_menu_id).setIntent(
1821 new Intent(Intent.ACTION_VIEW, Uri
1822 .parse(WebView.SCHEME_GEO
1823 + URLEncoder.encode(extra))));
1824 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1825 new Copy(extra));
1826 break;
1827
1828 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1829 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1830 TextView titleView = (TextView) LayoutInflater.from(this)
1831 .inflate(android.R.layout.browser_link_context_header,
1832 null);
1833 titleView.setText(extra);
1834 menu.setHeaderView(titleView);
1835 // decide whether to show the open link in new tab option
1836 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1837 mTabControl.getTabCount() < TabControl.MAX_TABS);
1838 PackageManager pm = getPackageManager();
1839 Intent send = new Intent(Intent.ACTION_SEND);
1840 send.setType("text/plain");
1841 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1842 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1843 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1844 break;
1845 }
1846 // otherwise fall through to handle image part
1847 case WebView.HitTestResult.IMAGE_TYPE:
1848 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1849 menu.setHeaderTitle(extra);
1850 }
1851 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1852 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1853 menu.findItem(R.id.download_context_menu_id).
1854 setOnMenuItemClickListener(new Download(extra));
1855 break;
1856
1857 default:
1858 Log.w(LOGTAG, "We should not get here.");
1859 break;
1860 }
1861 }
1862
The Android Open Source Project0c908882009-03-03 19:32:16 -08001863 // Attach the given tab to the content view.
1864 private void attachTabToContentView(TabControl.Tab t) {
1865 final WebView main = t.getWebView();
1866 // Attach the main WebView.
1867 mContentView.addView(main, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001868 // Attach the sub window if necessary
1869 attachSubWindow(t);
1870 // Request focus on the top window.
1871 t.getTopWindow().requestFocus();
1872 }
1873
1874 // Attach a sub window to the main WebView of the given tab.
1875 private void attachSubWindow(TabControl.Tab t) {
1876 // If a sub window exists, attach it to the content view.
1877 final WebView subView = t.getSubWebView();
1878 if (subView != null) {
1879 final View container = t.getSubWebViewContainer();
1880 mContentView.addView(container, COVER_SCREEN_PARAMS);
1881 subView.requestFocus();
1882 }
1883 }
1884
1885 // Remove the given tab from the content view.
1886 private void removeTabFromContentView(TabControl.Tab t) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07001887 // Remove the main WebView.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001888 mContentView.removeView(t.getWebView());
1889 // Remove the sub window if it exists.
1890 if (t.getSubWebView() != null) {
1891 mContentView.removeView(t.getSubWebViewContainer());
1892 }
1893 }
1894
1895 // Remove the sub window if it exists. Also called by TabControl when the
1896 // user clicks the 'X' to dismiss a sub window.
1897 /* package */ void dismissSubWindow(TabControl.Tab t) {
1898 final WebView mainView = t.getWebView();
1899 if (t.getSubWebView() != null) {
1900 // Remove the container view and request focus on the main WebView.
1901 mContentView.removeView(t.getSubWebViewContainer());
1902 mainView.requestFocus();
1903 // Tell the TabControl to dismiss the subwindow. This will destroy
1904 // the WebView.
1905 mTabControl.dismissSubWindow(t);
1906 }
1907 }
1908
1909 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
1910 private void sendAnimateFromOverview(final TabControl.Tab tab,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001911 final boolean newTab, final UrlData urlData, final int delay,
The Android Open Source Project0c908882009-03-03 19:32:16 -08001912 final Message msg) {
1913 // Set the current tab.
1914 mTabControl.setCurrentTab(tab);
1915 // Attach the WebView so it will layout.
1916 attachTabToContentView(tab);
1917 // Set the view to invisibile for now.
1918 tab.getWebView().setVisibility(View.INVISIBLE);
1919 // If there is a sub window, make it invisible too.
1920 if (tab.getSubWebView() != null) {
1921 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
1922 }
1923 // Create our fake animating view.
1924 final AnimatingView view = new AnimatingView(this, tab);
1925 // Attach it to the view system and make in invisible so it will
1926 // layout but not flash white on the screen.
1927 mContentView.addView(view, COVER_SCREEN_PARAMS);
1928 view.setVisibility(View.INVISIBLE);
1929 // Send the animate message.
1930 final HashMap map = new HashMap();
1931 map.put("view", view);
1932 // Load the url after the AnimatingView has captured the picture. This
1933 // prevents any bad layout or bad scale from being used during
1934 // animation.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001935 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001936 dismissSubWindow(tab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001937 urlData.loadIn(tab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08001938 }
1939 map.put("msg", msg);
1940 mHandler.sendMessageDelayed(mHandler.obtainMessage(
1941 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
1942 // Increment the count to indicate that we are in an animation.
1943 mAnimationCount++;
1944 // Remove the listener so we don't get any more tab changes.
1945 mTabOverview.setListener(null);
1946 mTabListener = null;
1947 // Make the menu empty until the animation completes.
1948 mMenuState = EMPTY_MENU;
1949
1950 }
1951
1952 // 500ms animation with 800ms delay
Patrick Scott95d601f2009-06-11 10:06:46 -04001953 private static final int TAB_ANIMATION_DURATION = 200;
1954 private static final int TAB_OVERVIEW_DELAY = 500;
The Android Open Source Project0c908882009-03-03 19:32:16 -08001955
1956 // Called by TabControl when a tab is requesting focus
1957 /* package */ void showTab(TabControl.Tab t) {
Patrick Scott95d601f2009-06-11 10:06:46 -04001958 showTab(t, EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001959 }
1960
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001961 private void showTab(TabControl.Tab t, UrlData urlData) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001962 // Disallow focus change during a tab animation.
1963 if (mAnimationCount > 0) {
1964 return;
1965 }
1966 int delay = 0;
1967 if (mTabOverview == null) {
1968 // Add a delay so the tab overview can be shown before the second
1969 // animation begins.
1970 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
1971 tabPicker(false, mTabControl.getTabIndex(t), false);
1972 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001973 sendAnimateFromOverview(t, false, urlData, delay, null);
1974 }
1975
1976 // A wrapper function of {@link #openTabAndShow(UrlData, Message, boolean, String)}
1977 // that accepts url as string.
1978 private void openTabAndShow(String url, final Message msg,
1979 boolean closeOnExit, String appId) {
1980 openTabAndShow(new UrlData(url), msg, closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001981 }
1982
1983 // This method does a ton of stuff. It will attempt to create a new tab
1984 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
1985 // url isn't null, it will load the given url. If the tab overview is not
1986 // showing, it will animate to the tab overview, create a new tab and
1987 // animate away from it. After the animation completes, it will dispatch
1988 // the given Message. If the tab overview is already showing (i.e. this
1989 // method is called from TabListener.onClick(), the method will animate
1990 // away from the tab overview.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001991 private void openTabAndShow(UrlData urlData, final Message msg,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001992 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001993 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
1994 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
1995 if (newTab) {
1996 int delay = 0;
1997 // If the tab overview is up and there are animations, just load
1998 // the url.
1999 if (mTabOverview != null && mAnimationCount > 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002000 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002001 // We should not have a msg here since onCreateWindow
2002 // checks the animation count and every other caller passes
2003 // null.
2004 assert msg == null;
2005 // just dismiss the subwindow and load the given url.
2006 dismissSubWindow(currentTab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002007 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002008 }
2009 } else {
2010 // show mTabOverview if it is not there.
2011 if (mTabOverview == null) {
2012 // We have to delay the animation from the tab picker by the
2013 // length of the tab animation. Add a delay so the tab
2014 // overview can be shown before the second animation begins.
2015 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2016 tabPicker(false, ImageGrid.NEW_TAB, false);
2017 }
2018 // Animate from the Tab overview after any animations have
2019 // finished.
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002020 sendAnimateFromOverview(
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002021 mTabControl.createNewTab(closeOnExit, appId, urlData.mUrl), true,
2022 urlData, delay, msg);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002023 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002024 } else if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002025 // We should not have a msg here.
2026 assert msg == null;
2027 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002028 sendAnimateFromOverview(currentTab, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002029 TAB_OVERVIEW_DELAY, null);
2030 } else {
2031 // Get rid of the subwindow if it exists
2032 dismissSubWindow(currentTab);
2033 // Load the given url.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002034 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002035 }
2036 }
2037 }
2038
2039 private Animation createTabAnimation(final AnimatingView view,
2040 final View cell, boolean scaleDown) {
2041 final AnimationSet set = new AnimationSet(true);
2042 final float scaleX = (float) cell.getWidth() / view.getWidth();
2043 final float scaleY = (float) cell.getHeight() / view.getHeight();
2044 if (scaleDown) {
2045 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2046 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2047 cell.getTop()));
2048 } else {
2049 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2050 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2051 cell.getTop(), 0));
2052 }
2053 set.setDuration(TAB_ANIMATION_DURATION);
2054 set.setInterpolator(new DecelerateInterpolator());
2055 return set;
2056 }
2057
2058 // Animate to the tab overview. currentIndex tells us which position to
2059 // animate to and newIndex is the position that should be selected after
2060 // the animation completes.
2061 // If remove is true, after the animation stops, a confirmation dialog will
2062 // be displayed to the user.
2063 private void animateToTabOverview(final int newIndex, final boolean remove,
2064 final AnimatingView view) {
2065 // Find the view in the ImageGrid allowing for the "New Tab" cell.
2066 int position = mTabControl.getTabIndex(view.mTab);
2067 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2068 position++;
2069 }
2070
2071 // Offset the tab position with the first visible position to get a
2072 // number between 0 and 3.
2073 position -= mTabOverview.getFirstVisiblePosition();
2074
2075 // Grab the view that we are going to animate to.
2076 final View v = mTabOverview.getChildAt(position);
2077
2078 final Animation.AnimationListener l =
2079 new Animation.AnimationListener() {
2080 public void onAnimationStart(Animation a) {
Patrick Scottd068f802009-06-22 11:46:06 -04002081 if (mTabOverview != null) {
2082 mTabOverview.requestFocus();
2083 // Clear the listener so we don't trigger a tab
2084 // selection.
2085 mTabOverview.setListener(null);
2086 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002087 }
2088 public void onAnimationRepeat(Animation a) {}
2089 public void onAnimationEnd(Animation a) {
2090 // We are no longer animating so decrement the count.
2091 mAnimationCount--;
2092 // Make the view GONE so that it will not draw between
2093 // now and when the Runnable is handled.
2094 view.setVisibility(View.GONE);
2095 // Post a runnable since we can't modify the view
2096 // hierarchy during this callback.
2097 mHandler.post(new Runnable() {
2098 public void run() {
2099 // Remove the AnimatingView.
2100 mContentView.removeView(view);
2101 if (mTabOverview != null) {
2102 // Make newIndex visible.
2103 mTabOverview.setCurrentIndex(newIndex);
2104 // Restore the listener.
2105 mTabOverview.setListener(mTabListener);
2106 // Change the menu to TAB_MENU if the
2107 // ImageGrid is interactive.
2108 if (mTabOverview.isLive()) {
2109 mMenuState = R.id.TAB_MENU;
2110 mTabOverview.requestFocus();
2111 }
2112 }
2113 // If a remove was requested, remove the tab.
2114 if (remove) {
2115 // During a remove, the current tab has
2116 // already changed. Remember the current one
2117 // here.
2118 final TabControl.Tab currentTab =
2119 mTabControl.getCurrentTab();
2120 // Remove the tab at newIndex from
2121 // TabControl and the tab overview.
2122 final TabControl.Tab tab =
2123 mTabControl.getTab(newIndex);
2124 mTabControl.removeTab(tab);
2125 // Restore the current tab.
2126 if (currentTab != tab) {
2127 mTabControl.setCurrentTab(currentTab);
2128 }
2129 if (mTabOverview != null) {
2130 mTabOverview.remove(newIndex);
2131 // Make the current tab visible.
2132 mTabOverview.setCurrentIndex(
2133 mTabControl.getCurrentIndex());
2134 }
2135 }
2136 }
2137 });
2138 }
2139 };
2140
2141 // Do an animation if there is a view to animate to.
2142 if (v != null) {
2143 // Create our animation
2144 final Animation anim = createTabAnimation(view, v, true);
2145 anim.setAnimationListener(l);
2146 // Start animating
2147 view.startAnimation(anim);
2148 } else {
2149 // If something goes wrong and we didn't find a view to animate to,
2150 // just do everything here.
2151 l.onAnimationStart(null);
2152 l.onAnimationEnd(null);
2153 }
2154 }
2155
2156 // Animate from the tab picker. The index supplied is the index to animate
2157 // from.
2158 private void animateFromTabOverview(final AnimatingView view,
2159 final boolean newTab, final Message msg) {
2160 // firstVisible is the first visible tab on the screen. This helps
2161 // to know which corner of the screen the selected tab is.
2162 int firstVisible = mTabOverview.getFirstVisiblePosition();
2163 // tabPosition is the 0-based index of of the tab being opened
2164 int tabPosition = mTabControl.getTabIndex(view.mTab);
2165 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2166 // Add one to make room for the "New Tab" cell.
2167 tabPosition++;
2168 }
2169 // If this is a new tab, animate from the "New Tab" cell.
2170 if (newTab) {
2171 tabPosition = 0;
2172 }
2173 // Location corresponds to the four corners of the screen.
2174 // A new tab or 0 is upper left, 0 for an old tab is upper
2175 // right, 1 is lower left, and 2 is lower right
2176 int location = tabPosition - firstVisible;
2177
2178 // Find the view at this location.
2179 final View v = mTabOverview.getChildAt(location);
2180
2181 // Wait until the animation completes to replace the AnimatingView.
2182 final Animation.AnimationListener l =
2183 new Animation.AnimationListener() {
2184 public void onAnimationStart(Animation a) {}
2185 public void onAnimationRepeat(Animation a) {}
2186 public void onAnimationEnd(Animation a) {
2187 mHandler.post(new Runnable() {
2188 public void run() {
2189 mContentView.removeView(view);
2190 // Dismiss the tab overview. If the cell at the
2191 // given location is null, set the fade
2192 // parameter to true.
2193 dismissTabOverview(v == null);
2194 TabControl.Tab t =
2195 mTabControl.getCurrentTab();
2196 mMenuState = R.id.MAIN_MENU;
2197 // Resume regular updates.
2198 t.getWebView().resumeTimers();
2199 // Dispatch the message after the animation
2200 // completes.
2201 if (msg != null) {
2202 msg.sendToTarget();
2203 }
2204 // The animation is done and the tab overview is
2205 // gone so allow key events and other animations
2206 // to begin.
2207 mAnimationCount--;
2208 // Reset all the title bar info.
2209 resetTitle();
2210 }
2211 });
2212 }
2213 };
2214
2215 if (v != null) {
2216 final Animation anim = createTabAnimation(view, v, false);
2217 // Set the listener and start animating
2218 anim.setAnimationListener(l);
2219 view.startAnimation(anim);
2220 // Make the view VISIBLE during the animation.
2221 view.setVisibility(View.VISIBLE);
2222 } else {
2223 // Go ahead and do all the cleanup.
2224 l.onAnimationEnd(null);
2225 }
2226 }
2227
2228 // Dismiss the tab overview applying a fade if needed.
2229 private void dismissTabOverview(final boolean fade) {
2230 if (fade) {
2231 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2232 anim.setDuration(500);
2233 anim.startNow();
2234 mTabOverview.startAnimation(anim);
2235 }
2236 // Just in case there was a problem with animating away from the tab
2237 // overview
2238 WebView current = mTabControl.getCurrentWebView();
2239 if (current != null) {
2240 current.setVisibility(View.VISIBLE);
2241 } else {
2242 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2243 }
2244 // Make the sub window container visible.
2245 if (mTabControl.getCurrentSubWindow() != null) {
2246 mTabControl.getCurrentTab().getSubWebViewContainer()
2247 .setVisibility(View.VISIBLE);
2248 }
2249 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002250 // Clear all the data for tab picker so next time it will be
2251 // recreated.
2252 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002253 mTabOverview.clear();
2254 mTabOverview = null;
2255 mTabListener = null;
2256 }
2257
2258 private void openTab(String url) {
2259 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002260 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002261 if (t != null) {
2262 t.getWebView().loadUrl(url);
2263 }
2264 } else {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002265 openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002266 }
2267 }
2268
2269 private class Copy implements OnMenuItemClickListener {
2270 private CharSequence mText;
2271
2272 public boolean onMenuItemClick(MenuItem item) {
2273 copy(mText);
2274 return true;
2275 }
2276
2277 public Copy(CharSequence toCopy) {
2278 mText = toCopy;
2279 }
2280 }
2281
2282 private class Download implements OnMenuItemClickListener {
2283 private String mText;
2284
2285 public boolean onMenuItemClick(MenuItem item) {
2286 onDownloadStartNoStream(mText, null, null, null, -1);
2287 return true;
2288 }
2289
2290 public Download(String toDownload) {
2291 mText = toDownload;
2292 }
2293 }
2294
2295 private void copy(CharSequence text) {
2296 try {
2297 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2298 if (clip != null) {
2299 clip.setClipboardText(text);
2300 }
2301 } catch (android.os.RemoteException e) {
2302 Log.e(LOGTAG, "Copy failed", e);
2303 }
2304 }
2305
2306 /**
2307 * Resets the browser title-view to whatever it must be (for example, if we
2308 * load a page from history).
2309 */
2310 private void resetTitle() {
2311 resetLockIcon();
2312 resetTitleIconAndProgress();
2313 }
2314
2315 /**
2316 * Resets the browser title-view to whatever it must be
2317 * (for example, if we had a loading error)
2318 * When we have a new page, we call resetTitle, when we
2319 * have to reset the titlebar to whatever it used to be
2320 * (for example, if the user chose to stop loading), we
2321 * call resetTitleAndRevertLockIcon.
2322 */
2323 /* package */ void resetTitleAndRevertLockIcon() {
2324 revertLockIcon();
2325 resetTitleIconAndProgress();
2326 }
2327
2328 /**
2329 * Reset the title, favicon, and progress.
2330 */
2331 private void resetTitleIconAndProgress() {
2332 WebView current = mTabControl.getCurrentWebView();
2333 if (current == null) {
2334 return;
2335 }
2336 resetTitleAndIcon(current);
2337 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002338 mWebChromeClient.onProgressChanged(current, progress);
2339 }
2340
2341 // Reset the title and the icon based on the given item.
2342 private void resetTitleAndIcon(WebView view) {
2343 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2344 if (item != null) {
2345 setUrlTitle(item.getUrl(), item.getTitle());
2346 setFavicon(item.getFavicon());
2347 } else {
2348 setUrlTitle(null, null);
2349 setFavicon(null);
2350 }
2351 }
2352
2353 /**
2354 * Sets a title composed of the URL and the title string.
2355 * @param url The URL of the site being loaded.
2356 * @param title The title of the site being loaded.
2357 */
2358 private void setUrlTitle(String url, String title) {
2359 mUrl = url;
2360 mTitle = title;
2361
2362 // While the tab overview is animating or being shown, block changes
2363 // to the title.
2364 if (mAnimationCount == 0 && mTabOverview == null) {
2365 setTitle(buildUrlTitle(url, title));
2366 }
2367 }
2368
2369 /**
2370 * Builds and returns the page title, which is some
2371 * combination of the page URL and title.
2372 * @param url The URL of the site being loaded.
2373 * @param title The title of the site being loaded.
2374 * @return The page title.
2375 */
2376 private String buildUrlTitle(String url, String title) {
2377 String urlTitle = "";
2378
2379 if (url != null) {
2380 String titleUrl = buildTitleUrl(url);
2381
2382 if (title != null && 0 < title.length()) {
2383 if (titleUrl != null && 0 < titleUrl.length()) {
2384 urlTitle = titleUrl + ": " + title;
2385 } else {
2386 urlTitle = title;
2387 }
2388 } else {
2389 if (titleUrl != null) {
2390 urlTitle = titleUrl;
2391 }
2392 }
2393 }
2394
2395 return urlTitle;
2396 }
2397
2398 /**
2399 * @param url The URL to build a title version of the URL from.
2400 * @return The title version of the URL or null if fails.
2401 * The title version of the URL can be either the URL hostname,
2402 * or the hostname with an "https://" prefix (for secure URLs),
2403 * or an empty string if, for example, the URL in question is a
2404 * file:// URL with no hostname.
2405 */
2406 private static String buildTitleUrl(String url) {
2407 String titleUrl = null;
2408
2409 if (url != null) {
2410 try {
2411 // parse the url string
2412 URL urlObj = new URL(url);
2413 if (urlObj != null) {
2414 titleUrl = "";
2415
2416 String protocol = urlObj.getProtocol();
2417 String host = urlObj.getHost();
2418
2419 if (host != null && 0 < host.length()) {
2420 titleUrl = host;
2421 if (protocol != null) {
2422 // if a secure site, add an "https://" prefix!
2423 if (protocol.equalsIgnoreCase("https")) {
2424 titleUrl = protocol + "://" + host;
2425 }
2426 }
2427 }
2428 }
2429 } catch (MalformedURLException e) {}
2430 }
2431
2432 return titleUrl;
2433 }
2434
2435 // Set the favicon in the title bar.
2436 private void setFavicon(Bitmap icon) {
2437 // While the tab overview is animating or being shown, block changes to
2438 // the favicon.
2439 if (mAnimationCount > 0 || mTabOverview != null) {
2440 return;
2441 }
2442 Drawable[] array = new Drawable[2];
2443 PaintDrawable p = new PaintDrawable(Color.WHITE);
2444 p.setCornerRadius(3f);
2445 array[0] = p;
2446 if (icon == null) {
2447 array[1] = mGenericFavicon;
2448 } else {
2449 array[1] = new BitmapDrawable(icon);
2450 }
2451 LayerDrawable d = new LayerDrawable(array);
2452 d.setLayerInset(1, 2, 2, 2, 2);
2453 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
2454 }
2455
2456 /**
2457 * Saves the current lock-icon state before resetting
2458 * the lock icon. If we have an error, we may need to
2459 * roll back to the previous state.
2460 */
2461 private void saveLockIcon() {
2462 mPrevLockType = mLockIconType;
2463 }
2464
2465 /**
2466 * Reverts the lock-icon state to the last saved state,
2467 * for example, if we had an error, and need to cancel
2468 * the load.
2469 */
2470 private void revertLockIcon() {
2471 mLockIconType = mPrevLockType;
2472
Dave Bort31a6d1c2009-04-13 15:56:49 -07002473 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002474 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2475 " revert lock icon to " + mLockIconType);
2476 }
2477
2478 updateLockIconImage(mLockIconType);
2479 }
2480
2481 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2482 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2483 // Animate to the tab picker, remove the current tab, then
2484 // animate away from the tab picker to the parent WebView.
2485 tabPicker(false, indexFrom, remove);
2486 // Change to the parent tab
2487 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2488 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002489 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002490 } else {
2491 // Increment this here so that no other animations can happen in
2492 // between the end of the tab picker transition and the beginning
2493 // of openTabAndShow. This has a matching decrement in the handler
2494 // of OPEN_TAB_AND_SHOW.
2495 mAnimationCount++;
2496 // Send a message to open a new tab.
2497 mHandler.sendMessageDelayed(
2498 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2499 mSettings.getHomePage()), delay);
2500 }
2501 }
2502
2503 private void goBackOnePageOrQuit() {
2504 TabControl.Tab current = mTabControl.getCurrentTab();
2505 if (current == null) {
2506 /*
2507 * Instead of finishing the activity, simply push this to the back
2508 * of the stack and let ActivityManager to choose the foreground
2509 * activity. As BrowserActivity is singleTask, it will be always the
2510 * root of the task. So we can use either true or false for
2511 * moveTaskToBack().
2512 */
2513 moveTaskToBack(true);
2514 }
2515 WebView w = current.getWebView();
2516 if (w.canGoBack()) {
2517 w.goBack();
2518 } else {
2519 // Check to see if we are closing a window that was created by
2520 // another window. If so, we switch back to that window.
2521 TabControl.Tab parent = current.getParentTab();
2522 if (parent != null) {
2523 switchTabs(mTabControl.getCurrentIndex(),
2524 mTabControl.getTabIndex(parent), true);
2525 } else {
2526 if (current.closeOnExit()) {
2527 if (mTabControl.getTabCount() == 1) {
2528 finish();
2529 return;
2530 }
2531 // call pauseWebView() now, we won't be able to call it in
2532 // onPause() as the WebView won't be valid.
2533 pauseWebView();
2534 removeTabFromContentView(current);
2535 mTabControl.removeTab(current);
2536 }
2537 /*
2538 * Instead of finishing the activity, simply push this to the back
2539 * of the stack and let ActivityManager to choose the foreground
2540 * activity. As BrowserActivity is singleTask, it will be always the
2541 * root of the task. So we can use either true or false for
2542 * moveTaskToBack().
2543 */
2544 moveTaskToBack(true);
2545 }
2546 }
2547 }
2548
2549 public KeyTracker.State onKeyTracker(int keyCode,
2550 KeyEvent event,
2551 KeyTracker.Stage stage,
2552 int duration) {
2553 // if onKeyTracker() is called after activity onStop()
2554 // because of accumulated key events,
2555 // we should ignore it as browser is not active any more.
2556 WebView topWindow = getTopWindow();
2557 if (topWindow == null)
2558 return KeyTracker.State.NOT_TRACKING;
2559
2560 if (keyCode == KeyEvent.KEYCODE_BACK) {
2561 // During animations, block the back key so that other animations
2562 // are not triggered and so that we don't end up destroying all the
2563 // WebViews before finishing the animation.
2564 if (mAnimationCount > 0) {
2565 return KeyTracker.State.DONE_TRACKING;
2566 }
2567 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2568 bookmarksOrHistoryPicker(true);
2569 return KeyTracker.State.DONE_TRACKING;
2570 } else if (stage == KeyTracker.Stage.UP) {
2571 // FIXME: Currently, we do not have a notion of the
2572 // history picker for the subwindow, but maybe we
2573 // should?
2574 WebView subwindow = mTabControl.getCurrentSubWindow();
2575 if (subwindow != null) {
2576 if (subwindow.canGoBack()) {
2577 subwindow.goBack();
2578 } else {
2579 dismissSubWindow(mTabControl.getCurrentTab());
2580 }
2581 } else {
2582 goBackOnePageOrQuit();
2583 }
2584 return KeyTracker.State.DONE_TRACKING;
2585 }
2586 return KeyTracker.State.KEEP_TRACKING;
2587 }
2588 return KeyTracker.State.NOT_TRACKING;
2589 }
2590
2591 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2592 if (keyCode == KeyEvent.KEYCODE_MENU) {
2593 mMenuIsDown = true;
2594 }
2595 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2596 if (!handled) {
2597 switch (keyCode) {
2598 case KeyEvent.KEYCODE_SPACE:
2599 if (event.isShiftPressed()) {
2600 getTopWindow().pageUp(false);
2601 } else {
2602 getTopWindow().pageDown(false);
2603 }
2604 handled = true;
2605 break;
2606
2607 default:
2608 break;
2609 }
2610 }
2611 return handled || super.onKeyDown(keyCode, event);
2612 }
2613
2614 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2615 if (keyCode == KeyEvent.KEYCODE_MENU) {
2616 mMenuIsDown = false;
2617 }
2618 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2619 }
2620
2621 private void stopLoading() {
2622 resetTitleAndRevertLockIcon();
2623 WebView w = getTopWindow();
2624 w.stopLoading();
2625 mWebViewClient.onPageFinished(w, w.getUrl());
2626
2627 cancelStopToast();
2628 mStopToast = Toast
2629 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2630 mStopToast.show();
2631 }
2632
2633 private void cancelStopToast() {
2634 if (mStopToast != null) {
2635 mStopToast.cancel();
2636 mStopToast = null;
2637 }
2638 }
2639
2640 // called by a non-UI thread to post the message
2641 public void postMessage(int what, int arg1, int arg2, Object obj) {
2642 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2643 }
2644
2645 // public message ids
2646 public final static int LOAD_URL = 1001;
2647 public final static int STOP_LOAD = 1002;
2648
2649 // Message Ids
2650 private static final int FOCUS_NODE_HREF = 102;
2651 private static final int CANCEL_CREDS_REQUEST = 103;
2652 private static final int ANIMATE_FROM_OVERVIEW = 104;
2653 private static final int ANIMATE_TO_OVERVIEW = 105;
2654 private static final int OPEN_TAB_AND_SHOW = 106;
2655 private static final int CHECK_MEMORY = 107;
2656 private static final int RELEASE_WAKELOCK = 108;
2657
2658 // Private handler for handling javascript and saving passwords
2659 private Handler mHandler = new Handler() {
2660
2661 public void handleMessage(Message msg) {
2662 switch (msg.what) {
2663 case ANIMATE_FROM_OVERVIEW:
2664 final HashMap map = (HashMap) msg.obj;
2665 animateFromTabOverview((AnimatingView) map.get("view"),
2666 msg.arg1 == 1, (Message) map.get("msg"));
2667 break;
2668
2669 case ANIMATE_TO_OVERVIEW:
2670 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2671 (AnimatingView) msg.obj);
2672 break;
2673
2674 case OPEN_TAB_AND_SHOW:
2675 // Decrement mAnimationCount before openTabAndShow because
2676 // the method relies on the value being 0 to start the next
2677 // animation.
2678 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002679 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002680 break;
2681
2682 case FOCUS_NODE_HREF:
2683 String url = (String) msg.getData().get("url");
2684 if (url == null || url.length() == 0) {
2685 break;
2686 }
2687 HashMap focusNodeMap = (HashMap) msg.obj;
2688 WebView view = (WebView) focusNodeMap.get("webview");
2689 // Only apply the action if the top window did not change.
2690 if (getTopWindow() != view) {
2691 break;
2692 }
2693 switch (msg.arg1) {
2694 case R.id.open_context_menu_id:
2695 case R.id.view_image_context_menu_id:
2696 loadURL(getTopWindow(), url);
2697 break;
2698 case R.id.open_newtab_context_menu_id:
2699 openTab(url);
2700 break;
2701 case R.id.bookmark_context_menu_id:
2702 Intent intent = new Intent(BrowserActivity.this,
2703 AddBookmarkPage.class);
2704 intent.putExtra("url", url);
2705 startActivity(intent);
2706 break;
2707 case R.id.share_link_context_menu_id:
2708 Browser.sendString(BrowserActivity.this, url);
2709 break;
2710 case R.id.copy_link_context_menu_id:
2711 copy(url);
2712 break;
2713 case R.id.save_link_context_menu_id:
2714 case R.id.download_context_menu_id:
2715 onDownloadStartNoStream(url, null, null, null, -1);
2716 break;
2717 }
2718 break;
2719
2720 case LOAD_URL:
2721 loadURL(getTopWindow(), (String) msg.obj);
2722 break;
2723
2724 case STOP_LOAD:
2725 stopLoading();
2726 break;
2727
2728 case CANCEL_CREDS_REQUEST:
2729 resumeAfterCredentials();
2730 break;
2731
2732 case CHECK_MEMORY:
2733 // reschedule to check memory condition
2734 mHandler.removeMessages(CHECK_MEMORY);
2735 mHandler.sendMessageDelayed(mHandler.obtainMessage
2736 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2737 checkMemory();
2738 break;
2739
2740 case RELEASE_WAKELOCK:
2741 if (mWakeLock.isHeld()) {
2742 mWakeLock.release();
2743 }
2744 break;
2745 }
2746 }
2747 };
2748
2749 // -------------------------------------------------------------------------
2750 // WebViewClient implementation.
2751 //-------------------------------------------------------------------------
2752
2753 // Use in overrideUrlLoading
2754 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2755 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2756 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2757 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2758
2759 /* package */ WebViewClient getWebViewClient() {
2760 return mWebViewClient;
2761 }
2762
2763 private void updateIcon(String url, Bitmap icon) {
2764 if (icon != null) {
2765 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2766 url, icon);
2767 }
2768 setFavicon(icon);
2769 }
2770
2771 private final WebViewClient mWebViewClient = new WebViewClient() {
2772 @Override
2773 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2774 resetLockIcon(url);
2775 setUrlTitle(url, null);
2776 // Call updateIcon instead of setFavicon so the bookmark
2777 // database can be updated.
2778 updateIcon(url, favicon);
2779
2780 if (mSettings.isTracing() == true) {
2781 // FIXME: we should save the trace file somewhere other than data.
2782 // I can't use "/tmp" as it competes for system memory.
2783 File file = getDir("browserTrace", 0);
2784 String baseDir = file.getPath();
2785 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2786 String host;
2787 try {
2788 WebAddress uri = new WebAddress(url);
2789 host = uri.mHost;
2790 } catch (android.net.ParseException ex) {
2791 host = "unknown_host";
2792 }
2793 host = host.replace('.', '_');
2794 baseDir = baseDir + host;
2795 file = new File(baseDir+".data");
2796 if (file.exists() == true) {
2797 file.delete();
2798 }
2799 file = new File(baseDir+".key");
2800 if (file.exists() == true) {
2801 file.delete();
2802 }
2803 mInTrace = true;
2804 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2805 }
2806
2807 // Performance probe
2808 if (false) {
2809 mStart = SystemClock.uptimeMillis();
2810 mProcessStart = Process.getElapsedCpuTime();
2811 long[] sysCpu = new long[7];
2812 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2813 sysCpu, null)) {
2814 mUserStart = sysCpu[0] + sysCpu[1];
2815 mSystemStart = sysCpu[2];
2816 mIdleStart = sysCpu[3];
2817 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2818 }
2819 mUiStart = SystemClock.currentThreadTimeMillis();
2820 }
2821
2822 if (!mPageStarted) {
2823 mPageStarted = true;
2824 // if onResume() has been called, resumeWebView() does nothing.
2825 resumeWebView();
2826 }
2827
2828 // reset sync timer to avoid sync starts during loading a page
2829 CookieSyncManager.getInstance().resetSync();
2830
2831 mInLoad = true;
2832 updateInLoadMenuItems();
2833 if (!mIsNetworkUp) {
2834 if ( mAlertDialog == null) {
2835 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2836 .setTitle(R.string.loadSuspendedTitle)
2837 .setMessage(R.string.loadSuspended)
2838 .setPositiveButton(R.string.ok, null)
2839 .show();
2840 }
2841 if (view != null) {
2842 view.setNetworkAvailable(false);
2843 }
2844 }
2845
2846 // schedule to check memory condition
2847 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2848 CHECK_MEMORY_INTERVAL);
2849 }
2850
2851 @Override
2852 public void onPageFinished(WebView view, String url) {
2853 // Reset the title and icon in case we stopped a provisional
2854 // load.
2855 resetTitleAndIcon(view);
2856
2857 // Update the lock icon image only once we are done loading
2858 updateLockIconImage(mLockIconType);
2859
2860 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002861 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002862 long[] sysCpu = new long[7];
2863 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2864 sysCpu, null)) {
2865 String uiInfo = "UI thread used "
2866 + (SystemClock.currentThreadTimeMillis() - mUiStart)
2867 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07002868 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002869 Log.d(LOGTAG, uiInfo);
2870 }
2871 //The string that gets written to the log
2872 String performanceString = "It took total "
2873 + (SystemClock.uptimeMillis() - mStart)
2874 + " ms clock time to load the page."
2875 + "\nbrowser process used "
2876 + (Process.getElapsedCpuTime() - mProcessStart)
2877 + " ms, user processes used "
2878 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
2879 + " ms, kernel used "
2880 + (sysCpu[2] - mSystemStart) * 10
2881 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
2882 + " ms and irq took "
2883 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
2884 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07002885 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002886 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
2887 }
2888 if (url != null) {
2889 // strip the url to maintain consistency
2890 String newUrl = new String(url);
2891 if (newUrl.startsWith("http://www.")) {
2892 newUrl = newUrl.substring(11);
2893 } else if (newUrl.startsWith("http://")) {
2894 newUrl = newUrl.substring(7);
2895 } else if (newUrl.startsWith("https://www.")) {
2896 newUrl = newUrl.substring(12);
2897 } else if (newUrl.startsWith("https://")) {
2898 newUrl = newUrl.substring(8);
2899 }
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, newUrl + " loaded");
2902 }
2903 /*
2904 if (sWhiteList.contains(newUrl)) {
2905 // The string that gets pushed to the statistcs
2906 // service
2907 performanceString = performanceString
2908 + "\nWebpage: "
2909 + newUrl
2910 + "\nCarrier: "
2911 + android.os.SystemProperties
2912 .get("gsm.sim.operator.alpha");
2913 if (mWebView != null
2914 && mWebView.getContext() != null
2915 && mWebView.getContext().getSystemService(
2916 Context.CONNECTIVITY_SERVICE) != null) {
2917 ConnectivityManager cManager =
2918 (ConnectivityManager) mWebView
2919 .getContext().getSystemService(
2920 Context.CONNECTIVITY_SERVICE);
2921 NetworkInfo nInfo = cManager
2922 .getActiveNetworkInfo();
2923 if (nInfo != null) {
2924 performanceString = performanceString
2925 + "\nNetwork Type: "
2926 + nInfo.getType().toString();
2927 }
2928 }
2929 Checkin.logEvent(mResolver,
2930 Checkin.Events.Tag.WEBPAGE_LOAD,
2931 performanceString);
2932 Log.w(LOGTAG, "pushed to the statistics service");
2933 }
2934 */
2935 }
2936 }
2937 }
2938
2939 if (mInTrace) {
2940 mInTrace = false;
2941 Debug.stopMethodTracing();
2942 }
2943
2944 if (mPageStarted) {
2945 mPageStarted = false;
2946 // pauseWebView() will do nothing and return false if onPause()
2947 // is not called yet.
2948 if (pauseWebView()) {
2949 if (mWakeLock.isHeld()) {
2950 mHandler.removeMessages(RELEASE_WAKELOCK);
2951 mWakeLock.release();
2952 }
2953 }
2954 }
2955
The Android Open Source Project0c908882009-03-03 19:32:16 -08002956 mHandler.removeMessages(CHECK_MEMORY);
2957 checkMemory();
2958 }
2959
2960 // return true if want to hijack the url to let another app to handle it
2961 @Override
2962 public boolean shouldOverrideUrlLoading(WebView view, String url) {
2963 if (url.startsWith(SCHEME_WTAI)) {
2964 // wtai://wp/mc;number
2965 // number=string(phone-number)
2966 if (url.startsWith(SCHEME_WTAI_MC)) {
2967 Intent intent = new Intent(Intent.ACTION_VIEW,
2968 Uri.parse(WebView.SCHEME_TEL +
2969 url.substring(SCHEME_WTAI_MC.length())));
2970 startActivity(intent);
2971 return true;
2972 }
2973 // wtai://wp/sd;dtmf
2974 // dtmf=string(dialstring)
2975 if (url.startsWith(SCHEME_WTAI_SD)) {
2976 // TODO
2977 // only send when there is active voice connection
2978 return false;
2979 }
2980 // wtai://wp/ap;number;name
2981 // number=string(phone-number)
2982 // name=string
2983 if (url.startsWith(SCHEME_WTAI_AP)) {
2984 // TODO
2985 return false;
2986 }
2987 }
2988
Dianne Hackborn99189432009-06-17 18:06:18 -07002989 // The "about:" schemes are internal to the browser; don't
2990 // want these to be dispatched to other apps.
2991 if (url.startsWith("about:")) {
2992 return false;
2993 }
2994
2995 Intent intent;
2996
2997 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002998 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07002999 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3000 } catch (URISyntaxException ex) {
3001 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003002 return false;
3003 }
3004
Grace Kloba5b078b52009-06-24 20:23:41 -07003005 // check whether the intent can be resolved. If not, we will see
3006 // whether we can download it from the Market.
3007 if (getPackageManager().resolveActivity(intent, 0) == null) {
3008 String packagename = intent.getPackage();
3009 if (packagename != null) {
3010 intent = new Intent(Intent.ACTION_VIEW, Uri
3011 .parse("market://search?q=pname:" + packagename));
3012 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3013 startActivity(intent);
3014 return true;
3015 } else {
3016 return false;
3017 }
3018 }
3019
Dianne Hackborn99189432009-06-17 18:06:18 -07003020 // sanitize the Intent, ensuring web pages can not bypass browser
3021 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003022 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003023 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003024 try {
3025 if (startActivityIfNeeded(intent, -1)) {
3026 return true;
3027 }
3028 } catch (ActivityNotFoundException ex) {
3029 // ignore the error. If no application can handle the URL,
3030 // eg about:blank, assume the browser can handle it.
3031 }
3032
3033 if (mMenuIsDown) {
3034 openTab(url);
3035 closeOptionsMenu();
3036 return true;
3037 }
3038
3039 return false;
3040 }
3041
3042 /**
3043 * Updates the lock icon. This method is called when we discover another
3044 * resource to be loaded for this page (for example, javascript). While
3045 * we update the icon type, we do not update the lock icon itself until
3046 * we are done loading, it is slightly more secure this way.
3047 */
3048 @Override
3049 public void onLoadResource(WebView view, String url) {
3050 if (url != null && url.length() > 0) {
3051 // It is only if the page claims to be secure
3052 // that we may have to update the lock:
3053 if (mLockIconType == LOCK_ICON_SECURE) {
3054 // If NOT a 'safe' url, change the lock to mixed content!
3055 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3056 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003057 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003058 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3059 " updated lock icon to " + mLockIconType + " due to " + url);
3060 }
3061 }
3062 }
3063 }
3064 }
3065
3066 /**
3067 * Show the dialog, asking the user if they would like to continue after
3068 * an excessive number of HTTP redirects.
3069 */
3070 @Override
3071 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3072 final Message continueMsg) {
3073 new AlertDialog.Builder(BrowserActivity.this)
3074 .setTitle(R.string.browserFrameRedirect)
3075 .setMessage(R.string.browserFrame307Post)
3076 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3077 public void onClick(DialogInterface dialog, int which) {
3078 continueMsg.sendToTarget();
3079 }})
3080 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3081 public void onClick(DialogInterface dialog, int which) {
3082 cancelMsg.sendToTarget();
3083 }})
3084 .setOnCancelListener(new OnCancelListener() {
3085 public void onCancel(DialogInterface dialog) {
3086 cancelMsg.sendToTarget();
3087 }})
3088 .show();
3089 }
3090
Patrick Scotta6555242009-03-24 18:01:26 -07003091 // Container class for the next error dialog that needs to be
3092 // displayed.
3093 class ErrorDialog {
3094 public final int mTitle;
3095 public final String mDescription;
3096 public final int mError;
3097 ErrorDialog(int title, String desc, int error) {
3098 mTitle = title;
3099 mDescription = desc;
3100 mError = error;
3101 }
3102 };
3103
3104 private void processNextError() {
3105 if (mQueuedErrors == null) {
3106 return;
3107 }
3108 // The first one is currently displayed so just remove it.
3109 mQueuedErrors.removeFirst();
3110 if (mQueuedErrors.size() == 0) {
3111 mQueuedErrors = null;
3112 return;
3113 }
3114 showError(mQueuedErrors.getFirst());
3115 }
3116
3117 private DialogInterface.OnDismissListener mDialogListener =
3118 new DialogInterface.OnDismissListener() {
3119 public void onDismiss(DialogInterface d) {
3120 processNextError();
3121 }
3122 };
3123 private LinkedList<ErrorDialog> mQueuedErrors;
3124
3125 private void queueError(int err, String desc) {
3126 if (mQueuedErrors == null) {
3127 mQueuedErrors = new LinkedList<ErrorDialog>();
3128 }
3129 for (ErrorDialog d : mQueuedErrors) {
3130 if (d.mError == err) {
3131 // Already saw a similar error, ignore the new one.
3132 return;
3133 }
3134 }
3135 ErrorDialog errDialog = new ErrorDialog(
3136 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3137 R.string.browserFrameFileErrorLabel :
3138 R.string.browserFrameNetworkErrorLabel,
3139 desc, err);
3140 mQueuedErrors.addLast(errDialog);
3141
3142 // Show the dialog now if the queue was empty.
3143 if (mQueuedErrors.size() == 1) {
3144 showError(errDialog);
3145 }
3146 }
3147
3148 private void showError(ErrorDialog errDialog) {
3149 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3150 .setTitle(errDialog.mTitle)
3151 .setMessage(errDialog.mDescription)
3152 .setPositiveButton(R.string.ok, null)
3153 .create();
3154 d.setOnDismissListener(mDialogListener);
3155 d.show();
3156 }
3157
The Android Open Source Project0c908882009-03-03 19:32:16 -08003158 /**
3159 * Show a dialog informing the user of the network error reported by
3160 * WebCore.
3161 */
3162 @Override
3163 public void onReceivedError(WebView view, int errorCode,
3164 String description, String failingUrl) {
3165 if (errorCode != EventHandler.ERROR_LOOKUP &&
3166 errorCode != EventHandler.ERROR_CONNECT &&
3167 errorCode != EventHandler.ERROR_BAD_URL &&
3168 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3169 errorCode != EventHandler.FILE_ERROR) {
Patrick Scotta6555242009-03-24 18:01:26 -07003170 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003171 }
Patrick Scotta6555242009-03-24 18:01:26 -07003172 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3173 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003174
3175 // We need to reset the title after an error.
3176 resetTitleAndRevertLockIcon();
3177 }
3178
3179 /**
3180 * Check with the user if it is ok to resend POST data as the page they
3181 * are trying to navigate to is the result of a POST.
3182 */
3183 @Override
3184 public void onFormResubmission(WebView view, final Message dontResend,
3185 final Message resend) {
3186 new AlertDialog.Builder(BrowserActivity.this)
3187 .setTitle(R.string.browserFrameFormResubmitLabel)
3188 .setMessage(R.string.browserFrameFormResubmitMessage)
3189 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3190 public void onClick(DialogInterface dialog, int which) {
3191 resend.sendToTarget();
3192 }})
3193 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3194 public void onClick(DialogInterface dialog, int which) {
3195 dontResend.sendToTarget();
3196 }})
3197 .setOnCancelListener(new OnCancelListener() {
3198 public void onCancel(DialogInterface dialog) {
3199 dontResend.sendToTarget();
3200 }})
3201 .show();
3202 }
3203
3204 /**
3205 * Insert the url into the visited history database.
3206 * @param url The url to be inserted.
3207 * @param isReload True if this url is being reloaded.
3208 * FIXME: Not sure what to do when reloading the page.
3209 */
3210 @Override
3211 public void doUpdateVisitedHistory(WebView view, String url,
3212 boolean isReload) {
3213 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3214 return;
3215 }
3216 Browser.updateVisitedHistory(mResolver, url, true);
3217 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3218 }
3219
3220 /**
3221 * Displays SSL error(s) dialog to the user.
3222 */
3223 @Override
3224 public void onReceivedSslError(
3225 final WebView view, final SslErrorHandler handler, final SslError error) {
3226
3227 if (mSettings.showSecurityWarnings()) {
3228 final LayoutInflater factory =
3229 LayoutInflater.from(BrowserActivity.this);
3230 final View warningsView =
3231 factory.inflate(R.layout.ssl_warnings, null);
3232 final LinearLayout placeholder =
3233 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3234
3235 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3236 LinearLayout ll = (LinearLayout)factory
3237 .inflate(R.layout.ssl_warning, null);
3238 ((TextView)ll.findViewById(R.id.warning))
3239 .setText(R.string.ssl_untrusted);
3240 placeholder.addView(ll);
3241 }
3242
3243 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3244 LinearLayout ll = (LinearLayout)factory
3245 .inflate(R.layout.ssl_warning, null);
3246 ((TextView)ll.findViewById(R.id.warning))
3247 .setText(R.string.ssl_mismatch);
3248 placeholder.addView(ll);
3249 }
3250
3251 if (error.hasError(SslError.SSL_EXPIRED)) {
3252 LinearLayout ll = (LinearLayout)factory
3253 .inflate(R.layout.ssl_warning, null);
3254 ((TextView)ll.findViewById(R.id.warning))
3255 .setText(R.string.ssl_expired);
3256 placeholder.addView(ll);
3257 }
3258
3259 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3260 LinearLayout ll = (LinearLayout)factory
3261 .inflate(R.layout.ssl_warning, null);
3262 ((TextView)ll.findViewById(R.id.warning))
3263 .setText(R.string.ssl_not_yet_valid);
3264 placeholder.addView(ll);
3265 }
3266
3267 new AlertDialog.Builder(BrowserActivity.this)
3268 .setTitle(R.string.security_warning)
3269 .setIcon(android.R.drawable.ic_dialog_alert)
3270 .setView(warningsView)
3271 .setPositiveButton(R.string.ssl_continue,
3272 new DialogInterface.OnClickListener() {
3273 public void onClick(DialogInterface dialog, int whichButton) {
3274 handler.proceed();
3275 }
3276 })
3277 .setNeutralButton(R.string.view_certificate,
3278 new DialogInterface.OnClickListener() {
3279 public void onClick(DialogInterface dialog, int whichButton) {
3280 showSSLCertificateOnError(view, handler, error);
3281 }
3282 })
3283 .setNegativeButton(R.string.cancel,
3284 new DialogInterface.OnClickListener() {
3285 public void onClick(DialogInterface dialog, int whichButton) {
3286 handler.cancel();
3287 BrowserActivity.this.resetTitleAndRevertLockIcon();
3288 }
3289 })
3290 .setOnCancelListener(
3291 new DialogInterface.OnCancelListener() {
3292 public void onCancel(DialogInterface dialog) {
3293 handler.cancel();
3294 BrowserActivity.this.resetTitleAndRevertLockIcon();
3295 }
3296 })
3297 .show();
3298 } else {
3299 handler.proceed();
3300 }
3301 }
3302
3303 /**
3304 * Handles an HTTP authentication request.
3305 *
3306 * @param handler The authentication handler
3307 * @param host The host
3308 * @param realm The realm
3309 */
3310 @Override
3311 public void onReceivedHttpAuthRequest(WebView view,
3312 final HttpAuthHandler handler, final String host, final String realm) {
3313 String username = null;
3314 String password = null;
3315
3316 boolean reuseHttpAuthUsernamePassword =
3317 handler.useHttpAuthUsernamePassword();
3318
3319 if (reuseHttpAuthUsernamePassword &&
3320 (mTabControl.getCurrentWebView() != null)) {
3321 String[] credentials =
3322 mTabControl.getCurrentWebView()
3323 .getHttpAuthUsernamePassword(host, realm);
3324 if (credentials != null && credentials.length == 2) {
3325 username = credentials[0];
3326 password = credentials[1];
3327 }
3328 }
3329
3330 if (username != null && password != null) {
3331 handler.proceed(username, password);
3332 } else {
3333 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3334 }
3335 }
3336
3337 @Override
3338 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3339 if (mMenuIsDown) {
3340 // only check shortcut key when MENU is held
3341 return getWindow().isShortcutKey(event.getKeyCode(), event);
3342 } else {
3343 return false;
3344 }
3345 }
3346
3347 @Override
3348 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3349 if (view != mTabControl.getCurrentTopWebView()) {
3350 return;
3351 }
3352 if (event.isDown()) {
3353 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3354 } else {
3355 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3356 }
3357 }
3358 };
3359
3360 //--------------------------------------------------------------------------
3361 // WebChromeClient implementation
3362 //--------------------------------------------------------------------------
3363
3364 /* package */ WebChromeClient getWebChromeClient() {
3365 return mWebChromeClient;
3366 }
3367
3368 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3369 // Helper method to create a new tab or sub window.
3370 private void createWindow(final boolean dialog, final Message msg) {
3371 if (dialog) {
3372 mTabControl.createSubWindow();
3373 final TabControl.Tab t = mTabControl.getCurrentTab();
3374 attachSubWindow(t);
3375 WebView.WebViewTransport transport =
3376 (WebView.WebViewTransport) msg.obj;
3377 transport.setWebView(t.getSubWebView());
3378 msg.sendToTarget();
3379 } else {
3380 final TabControl.Tab parent = mTabControl.getCurrentTab();
3381 // openTabAndShow will dispatch the message after creating the
3382 // new WebView. This will prevent another request from coming
3383 // in during the animation.
Patrick Scott95d601f2009-06-11 10:06:46 -04003384 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003385 parent.addChildTab(mTabControl.getCurrentTab());
3386 WebView.WebViewTransport transport =
3387 (WebView.WebViewTransport) msg.obj;
3388 transport.setWebView(mTabControl.getCurrentWebView());
3389 }
3390 }
3391
3392 @Override
3393 public boolean onCreateWindow(WebView view, final boolean dialog,
3394 final boolean userGesture, final Message resultMsg) {
3395 // Ignore these requests during tab animations or if the tab
3396 // overview is showing.
3397 if (mAnimationCount > 0 || mTabOverview != null) {
3398 return false;
3399 }
3400 // Short-circuit if we can't create any more tabs or sub windows.
3401 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3402 new AlertDialog.Builder(BrowserActivity.this)
3403 .setTitle(R.string.too_many_subwindows_dialog_title)
3404 .setIcon(android.R.drawable.ic_dialog_alert)
3405 .setMessage(R.string.too_many_subwindows_dialog_message)
3406 .setPositiveButton(R.string.ok, null)
3407 .show();
3408 return false;
3409 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3410 new AlertDialog.Builder(BrowserActivity.this)
3411 .setTitle(R.string.too_many_windows_dialog_title)
3412 .setIcon(android.R.drawable.ic_dialog_alert)
3413 .setMessage(R.string.too_many_windows_dialog_message)
3414 .setPositiveButton(R.string.ok, null)
3415 .show();
3416 return false;
3417 }
3418
3419 // Short-circuit if this was a user gesture.
3420 if (userGesture) {
3421 // createWindow will call openTabAndShow for new Windows and
3422 // that will call tabPicker which will increment
3423 // mAnimationCount.
3424 createWindow(dialog, resultMsg);
3425 return true;
3426 }
3427
3428 // Allow the popup and create the appropriate window.
3429 final AlertDialog.OnClickListener allowListener =
3430 new AlertDialog.OnClickListener() {
3431 public void onClick(DialogInterface d,
3432 int which) {
3433 // Same comment as above for setting
3434 // mAnimationCount.
3435 createWindow(dialog, resultMsg);
3436 // Since we incremented mAnimationCount while the
3437 // dialog was up, we have to decrement it here.
3438 mAnimationCount--;
3439 }
3440 };
3441
3442 // Block the popup by returning a null WebView.
3443 final AlertDialog.OnClickListener blockListener =
3444 new AlertDialog.OnClickListener() {
3445 public void onClick(DialogInterface d, int which) {
3446 resultMsg.sendToTarget();
3447 // We are not going to trigger an animation so
3448 // unblock keys and animation requests.
3449 mAnimationCount--;
3450 }
3451 };
3452
3453 // Build a confirmation dialog to display to the user.
3454 final AlertDialog d =
3455 new AlertDialog.Builder(BrowserActivity.this)
3456 .setTitle(R.string.attention)
3457 .setIcon(android.R.drawable.ic_dialog_alert)
3458 .setMessage(R.string.popup_window_attempt)
3459 .setPositiveButton(R.string.allow, allowListener)
3460 .setNegativeButton(R.string.block, blockListener)
3461 .setCancelable(false)
3462 .create();
3463
3464 // Show the confirmation dialog.
3465 d.show();
3466 // We want to increment mAnimationCount here to prevent a
3467 // potential race condition. If the user allows a pop-up from a
3468 // site and that pop-up then triggers another pop-up, it is
3469 // possible to get the BACK key between here and when the dialog
3470 // appears.
3471 mAnimationCount++;
3472 return true;
3473 }
3474
3475 @Override
3476 public void onCloseWindow(WebView window) {
3477 final int currentIndex = mTabControl.getCurrentIndex();
3478 final TabControl.Tab parent =
3479 mTabControl.getCurrentTab().getParentTab();
3480 if (parent != null) {
3481 // JavaScript can only close popup window.
3482 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3483 }
3484 }
3485
3486 @Override
3487 public void onProgressChanged(WebView view, int newProgress) {
3488 // Block progress updates to the title bar while the tab overview
3489 // is animating or being displayed.
3490 if (mAnimationCount == 0 && mTabOverview == null) {
3491 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3492 newProgress * 100);
3493 }
3494
3495 if (newProgress == 100) {
3496 // onProgressChanged() is called for sub-frame too while
3497 // onPageFinished() is only called for the main frame. sync
3498 // cookie and cache promptly here.
3499 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003500 if (mInLoad) {
3501 mInLoad = false;
3502 updateInLoadMenuItems();
3503 }
3504 } else {
3505 // onPageFinished may have already been called but a subframe
3506 // is still loading and updating the progress. Reset mInLoad
3507 // and update the menu items.
3508 if (!mInLoad) {
3509 mInLoad = true;
3510 updateInLoadMenuItems();
3511 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003512 }
3513 }
3514
3515 @Override
3516 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003517 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003518
3519 // here, if url is null, we want to reset the title
3520 setUrlTitle(url, title);
3521
3522 if (url == null ||
3523 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3524 return;
3525 }
3526 if (url.startsWith("http://www.")) {
3527 url = url.substring(11);
3528 } else if (url.startsWith("http://")) {
3529 url = url.substring(4);
3530 }
3531 try {
3532 url = "%" + url;
3533 String [] selArgs = new String[] { url };
3534
3535 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3536 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3537 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3538 Browser.HISTORY_PROJECTION, where, selArgs, null);
3539 if (c.moveToFirst()) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003540 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003541 Log.v(LOGTAG, "updating cursor");
3542 }
3543 // Current implementation of database only has one entry per
3544 // url.
3545 int titleIndex =
3546 c.getColumnIndex(Browser.BookmarkColumns.TITLE);
3547 c.updateString(titleIndex, title);
3548 c.commitUpdates();
3549 }
3550 c.close();
3551 } catch (IllegalStateException e) {
3552 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3553 } catch (SQLiteException ex) {
3554 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3555 }
3556 }
3557
3558 @Override
3559 public void onReceivedIcon(WebView view, Bitmap icon) {
3560 updateIcon(view.getUrl(), icon);
3561 }
3562 };
3563
3564 /**
3565 * Notify the host application a download should be done, or that
3566 * the data should be streamed if a streaming viewer is available.
3567 * @param url The full url to the content that should be downloaded
3568 * @param contentDisposition Content-disposition http header, if
3569 * present.
3570 * @param mimetype The mimetype of the content reported by the server
3571 * @param contentLength The file size reported by the server
3572 */
3573 public void onDownloadStart(String url, String userAgent,
3574 String contentDisposition, String mimetype, long contentLength) {
3575 // if we're dealing wih A/V content that's not explicitly marked
3576 // for download, check if it's streamable.
3577 if (contentDisposition == null
3578 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3579 // query the package manager to see if there's a registered handler
3580 // that matches.
3581 Intent intent = new Intent(Intent.ACTION_VIEW);
3582 intent.setDataAndType(Uri.parse(url), mimetype);
3583 if (getPackageManager().resolveActivity(intent,
3584 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3585 // someone knows how to handle this mime type with this scheme, don't download.
3586 try {
3587 startActivity(intent);
3588 return;
3589 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003590 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003591 Log.d(LOGTAG, "activity not found for " + mimetype
3592 + " over " + Uri.parse(url).getScheme(), ex);
3593 }
3594 // Best behavior is to fall back to a download in this case
3595 }
3596 }
3597 }
3598 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3599 }
3600
3601 /**
3602 * Notify the host application a download should be done, even if there
3603 * is a streaming viewer available for thise type.
3604 * @param url The full url to the content that should be downloaded
3605 * @param contentDisposition Content-disposition http header, if
3606 * present.
3607 * @param mimetype The mimetype of the content reported by the server
3608 * @param contentLength The file size reported by the server
3609 */
3610 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3611 String contentDisposition, String mimetype, long contentLength) {
3612
3613 String filename = URLUtil.guessFileName(url,
3614 contentDisposition, mimetype);
3615
3616 // Check to see if we have an SDCard
3617 String status = Environment.getExternalStorageState();
3618 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3619 int title;
3620 String msg;
3621
3622 // Check to see if the SDCard is busy, same as the music app
3623 if (status.equals(Environment.MEDIA_SHARED)) {
3624 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3625 title = R.string.download_sdcard_busy_dlg_title;
3626 } else {
3627 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3628 title = R.string.download_no_sdcard_dlg_title;
3629 }
3630
3631 new AlertDialog.Builder(this)
3632 .setTitle(title)
3633 .setIcon(android.R.drawable.ic_dialog_alert)
3634 .setMessage(msg)
3635 .setPositiveButton(R.string.ok, null)
3636 .show();
3637 return;
3638 }
3639
3640 // java.net.URI is a lot stricter than KURL so we have to undo
3641 // KURL's percent-encoding and redo the encoding using java.net.URI.
3642 URI uri = null;
3643 try {
3644 // Undo the percent-encoding that KURL may have done.
3645 String newUrl = new String(URLUtil.decode(url.getBytes()));
3646 // Parse the url into pieces
3647 WebAddress w = new WebAddress(newUrl);
3648 String frag = null;
3649 String query = null;
3650 String path = w.mPath;
3651 // Break the path into path, query, and fragment
3652 if (path.length() > 0) {
3653 // Strip the fragment
3654 int idx = path.lastIndexOf('#');
3655 if (idx != -1) {
3656 frag = path.substring(idx + 1);
3657 path = path.substring(0, idx);
3658 }
3659 idx = path.lastIndexOf('?');
3660 if (idx != -1) {
3661 query = path.substring(idx + 1);
3662 path = path.substring(0, idx);
3663 }
3664 }
3665 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3666 query, frag);
3667 } catch (Exception e) {
3668 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3669 return;
3670 }
3671
3672 // XXX: Have to use the old url since the cookies were stored using the
3673 // old percent-encoded url.
3674 String cookies = CookieManager.getInstance().getCookie(url);
3675
3676 ContentValues values = new ContentValues();
3677 values.put(Downloads.URI, uri.toString());
3678 values.put(Downloads.COOKIE_DATA, cookies);
3679 values.put(Downloads.USER_AGENT, userAgent);
3680 values.put(Downloads.NOTIFICATION_PACKAGE,
3681 getPackageName());
3682 values.put(Downloads.NOTIFICATION_CLASS,
3683 BrowserDownloadPage.class.getCanonicalName());
3684 values.put(Downloads.VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3685 values.put(Downloads.MIMETYPE, mimetype);
3686 values.put(Downloads.FILENAME_HINT, filename);
3687 values.put(Downloads.DESCRIPTION, uri.getHost());
3688 if (contentLength > 0) {
3689 values.put(Downloads.TOTAL_BYTES, contentLength);
3690 }
3691 if (mimetype == null) {
3692 // We must have long pressed on a link or image to download it. We
3693 // are not sure of the mimetype in this case, so do a head request
3694 new FetchUrlMimeType(this).execute(values);
3695 } else {
3696 final Uri contentUri =
3697 getContentResolver().insert(Downloads.CONTENT_URI, values);
3698 viewDownloads(contentUri);
3699 }
3700
3701 }
3702
3703 /**
3704 * Resets the lock icon. This method is called when we start a new load and
3705 * know the url to be loaded.
3706 */
3707 private void resetLockIcon(String url) {
3708 // Save the lock-icon state (we revert to it if the load gets cancelled)
3709 saveLockIcon();
3710
3711 mLockIconType = LOCK_ICON_UNSECURE;
3712 if (URLUtil.isHttpsUrl(url)) {
3713 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003714 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003715 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3716 " reset lock icon to " + mLockIconType);
3717 }
3718 }
3719
3720 updateLockIconImage(LOCK_ICON_UNSECURE);
3721 }
3722
3723 /**
3724 * Resets the lock icon. This method is called when the icon needs to be
3725 * reset but we do not know whether we are loading a secure or not secure
3726 * page.
3727 */
3728 private void resetLockIcon() {
3729 // Save the lock-icon state (we revert to it if the load gets cancelled)
3730 saveLockIcon();
3731
3732 mLockIconType = LOCK_ICON_UNSECURE;
3733
Dave Bort31a6d1c2009-04-13 15:56:49 -07003734 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003735 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3736 " reset lock icon to " + mLockIconType);
3737 }
3738
3739 updateLockIconImage(LOCK_ICON_UNSECURE);
3740 }
3741
3742 /**
3743 * Updates the lock-icon image in the title-bar.
3744 */
3745 private void updateLockIconImage(int lockIconType) {
3746 Drawable d = null;
3747 if (lockIconType == LOCK_ICON_SECURE) {
3748 d = mSecLockIcon;
3749 } else if (lockIconType == LOCK_ICON_MIXED) {
3750 d = mMixLockIcon;
3751 }
3752 // If the tab overview is animating or being shown, do not update the
3753 // lock icon.
3754 if (mAnimationCount == 0 && mTabOverview == null) {
3755 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3756 }
3757 }
3758
3759 /**
3760 * Displays a page-info dialog.
3761 * @param tab The tab to show info about
3762 * @param fromShowSSLCertificateOnError The flag that indicates whether
3763 * this dialog was opened from the SSL-certificate-on-error dialog or
3764 * not. This is important, since we need to know whether to return to
3765 * the parent dialog or simply dismiss.
3766 */
3767 private void showPageInfo(final TabControl.Tab tab,
3768 final boolean fromShowSSLCertificateOnError) {
3769 final LayoutInflater factory = LayoutInflater
3770 .from(this);
3771
3772 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3773
3774 final WebView view = tab.getWebView();
3775
3776 String url = null;
3777 String title = null;
3778
3779 if (view == null) {
3780 url = tab.getUrl();
3781 title = tab.getTitle();
3782 } else if (view == mTabControl.getCurrentWebView()) {
3783 // Use the cached title and url if this is the current WebView
3784 url = mUrl;
3785 title = mTitle;
3786 } else {
3787 url = view.getUrl();
3788 title = view.getTitle();
3789 }
3790
3791 if (url == null) {
3792 url = "";
3793 }
3794 if (title == null) {
3795 title = "";
3796 }
3797
3798 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
3799 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
3800
3801 mPageInfoView = tab;
3802 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
3803
3804 AlertDialog.Builder alertDialogBuilder =
3805 new AlertDialog.Builder(this)
3806 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
3807 .setView(pageInfoView)
3808 .setPositiveButton(
3809 R.string.ok,
3810 new DialogInterface.OnClickListener() {
3811 public void onClick(DialogInterface dialog,
3812 int whichButton) {
3813 mPageInfoDialog = null;
3814 mPageInfoView = null;
3815 mPageInfoFromShowSSLCertificateOnError = null;
3816
3817 // if we came here from the SSL error dialog
3818 if (fromShowSSLCertificateOnError) {
3819 // go back to the SSL error dialog
3820 showSSLCertificateOnError(
3821 mSSLCertificateOnErrorView,
3822 mSSLCertificateOnErrorHandler,
3823 mSSLCertificateOnErrorError);
3824 }
3825 }
3826 })
3827 .setOnCancelListener(
3828 new DialogInterface.OnCancelListener() {
3829 public void onCancel(DialogInterface dialog) {
3830 mPageInfoDialog = null;
3831 mPageInfoView = null;
3832 mPageInfoFromShowSSLCertificateOnError = null;
3833
3834 // if we came here from the SSL error dialog
3835 if (fromShowSSLCertificateOnError) {
3836 // go back to the SSL error dialog
3837 showSSLCertificateOnError(
3838 mSSLCertificateOnErrorView,
3839 mSSLCertificateOnErrorHandler,
3840 mSSLCertificateOnErrorError);
3841 }
3842 }
3843 });
3844
3845 // if we have a main top-level page SSL certificate set or a certificate
3846 // error
3847 if (fromShowSSLCertificateOnError ||
3848 (view != null && view.getCertificate() != null)) {
3849 // add a 'View Certificate' button
3850 alertDialogBuilder.setNeutralButton(
3851 R.string.view_certificate,
3852 new DialogInterface.OnClickListener() {
3853 public void onClick(DialogInterface dialog,
3854 int whichButton) {
3855 mPageInfoDialog = null;
3856 mPageInfoView = null;
3857 mPageInfoFromShowSSLCertificateOnError = null;
3858
3859 // if we came here from the SSL error dialog
3860 if (fromShowSSLCertificateOnError) {
3861 // go back to the SSL error dialog
3862 showSSLCertificateOnError(
3863 mSSLCertificateOnErrorView,
3864 mSSLCertificateOnErrorHandler,
3865 mSSLCertificateOnErrorError);
3866 } else {
3867 // otherwise, display the top-most certificate from
3868 // the chain
3869 if (view.getCertificate() != null) {
3870 showSSLCertificate(tab);
3871 }
3872 }
3873 }
3874 });
3875 }
3876
3877 mPageInfoDialog = alertDialogBuilder.show();
3878 }
3879
3880 /**
3881 * Displays the main top-level page SSL certificate dialog
3882 * (accessible from the Page-Info dialog).
3883 * @param tab The tab to show certificate for.
3884 */
3885 private void showSSLCertificate(final TabControl.Tab tab) {
3886 final View certificateView =
3887 inflateCertificateView(tab.getWebView().getCertificate());
3888 if (certificateView == null) {
3889 return;
3890 }
3891
3892 LayoutInflater factory = LayoutInflater.from(this);
3893
3894 final LinearLayout placeholder =
3895 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3896
3897 LinearLayout ll = (LinearLayout) factory.inflate(
3898 R.layout.ssl_success, placeholder);
3899 ((TextView)ll.findViewById(R.id.success))
3900 .setText(R.string.ssl_certificate_is_valid);
3901
3902 mSSLCertificateView = tab;
3903 mSSLCertificateDialog =
3904 new AlertDialog.Builder(this)
3905 .setTitle(R.string.ssl_certificate).setIcon(
3906 R.drawable.ic_dialog_browser_certificate_secure)
3907 .setView(certificateView)
3908 .setPositiveButton(R.string.ok,
3909 new DialogInterface.OnClickListener() {
3910 public void onClick(DialogInterface dialog,
3911 int whichButton) {
3912 mSSLCertificateDialog = null;
3913 mSSLCertificateView = null;
3914
3915 showPageInfo(tab, false);
3916 }
3917 })
3918 .setOnCancelListener(
3919 new DialogInterface.OnCancelListener() {
3920 public void onCancel(DialogInterface dialog) {
3921 mSSLCertificateDialog = null;
3922 mSSLCertificateView = null;
3923
3924 showPageInfo(tab, false);
3925 }
3926 })
3927 .show();
3928 }
3929
3930 /**
3931 * Displays the SSL error certificate dialog.
3932 * @param view The target web-view.
3933 * @param handler The SSL error handler responsible for cancelling the
3934 * connection that resulted in an SSL error or proceeding per user request.
3935 * @param error The SSL error object.
3936 */
3937 private void showSSLCertificateOnError(
3938 final WebView view, final SslErrorHandler handler, final SslError error) {
3939
3940 final View certificateView =
3941 inflateCertificateView(error.getCertificate());
3942 if (certificateView == null) {
3943 return;
3944 }
3945
3946 LayoutInflater factory = LayoutInflater.from(this);
3947
3948 final LinearLayout placeholder =
3949 (LinearLayout)certificateView.findViewById(R.id.placeholder);
3950
3951 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3952 LinearLayout ll = (LinearLayout)factory
3953 .inflate(R.layout.ssl_warning, placeholder);
3954 ((TextView)ll.findViewById(R.id.warning))
3955 .setText(R.string.ssl_untrusted);
3956 }
3957
3958 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3959 LinearLayout ll = (LinearLayout)factory
3960 .inflate(R.layout.ssl_warning, placeholder);
3961 ((TextView)ll.findViewById(R.id.warning))
3962 .setText(R.string.ssl_mismatch);
3963 }
3964
3965 if (error.hasError(SslError.SSL_EXPIRED)) {
3966 LinearLayout ll = (LinearLayout)factory
3967 .inflate(R.layout.ssl_warning, placeholder);
3968 ((TextView)ll.findViewById(R.id.warning))
3969 .setText(R.string.ssl_expired);
3970 }
3971
3972 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3973 LinearLayout ll = (LinearLayout)factory
3974 .inflate(R.layout.ssl_warning, placeholder);
3975 ((TextView)ll.findViewById(R.id.warning))
3976 .setText(R.string.ssl_not_yet_valid);
3977 }
3978
3979 mSSLCertificateOnErrorHandler = handler;
3980 mSSLCertificateOnErrorView = view;
3981 mSSLCertificateOnErrorError = error;
3982 mSSLCertificateOnErrorDialog =
3983 new AlertDialog.Builder(this)
3984 .setTitle(R.string.ssl_certificate).setIcon(
3985 R.drawable.ic_dialog_browser_certificate_partially_secure)
3986 .setView(certificateView)
3987 .setPositiveButton(R.string.ok,
3988 new DialogInterface.OnClickListener() {
3989 public void onClick(DialogInterface dialog,
3990 int whichButton) {
3991 mSSLCertificateOnErrorDialog = null;
3992 mSSLCertificateOnErrorView = null;
3993 mSSLCertificateOnErrorHandler = null;
3994 mSSLCertificateOnErrorError = null;
3995
3996 mWebViewClient.onReceivedSslError(
3997 view, handler, error);
3998 }
3999 })
4000 .setNeutralButton(R.string.page_info_view,
4001 new DialogInterface.OnClickListener() {
4002 public void onClick(DialogInterface dialog,
4003 int whichButton) {
4004 mSSLCertificateOnErrorDialog = null;
4005
4006 // do not clear the dialog state: we will
4007 // need to show the dialog again once the
4008 // user is done exploring the page-info details
4009
4010 showPageInfo(mTabControl.getTabFromView(view),
4011 true);
4012 }
4013 })
4014 .setOnCancelListener(
4015 new DialogInterface.OnCancelListener() {
4016 public void onCancel(DialogInterface dialog) {
4017 mSSLCertificateOnErrorDialog = null;
4018 mSSLCertificateOnErrorView = null;
4019 mSSLCertificateOnErrorHandler = null;
4020 mSSLCertificateOnErrorError = null;
4021
4022 mWebViewClient.onReceivedSslError(
4023 view, handler, error);
4024 }
4025 })
4026 .show();
4027 }
4028
4029 /**
4030 * Inflates the SSL certificate view (helper method).
4031 * @param certificate The SSL certificate.
4032 * @return The resultant certificate view with issued-to, issued-by,
4033 * issued-on, expires-on, and possibly other fields set.
4034 * If the input certificate is null, returns null.
4035 */
4036 private View inflateCertificateView(SslCertificate certificate) {
4037 if (certificate == null) {
4038 return null;
4039 }
4040
4041 LayoutInflater factory = LayoutInflater.from(this);
4042
4043 View certificateView = factory.inflate(
4044 R.layout.ssl_certificate, null);
4045
4046 // issued to:
4047 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4048 if (issuedTo != null) {
4049 ((TextView) certificateView.findViewById(R.id.to_common))
4050 .setText(issuedTo.getCName());
4051 ((TextView) certificateView.findViewById(R.id.to_org))
4052 .setText(issuedTo.getOName());
4053 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4054 .setText(issuedTo.getUName());
4055 }
4056
4057 // issued by:
4058 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4059 if (issuedBy != null) {
4060 ((TextView) certificateView.findViewById(R.id.by_common))
4061 .setText(issuedBy.getCName());
4062 ((TextView) certificateView.findViewById(R.id.by_org))
4063 .setText(issuedBy.getOName());
4064 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4065 .setText(issuedBy.getUName());
4066 }
4067
4068 // issued on:
4069 String issuedOn = reformatCertificateDate(
4070 certificate.getValidNotBefore());
4071 ((TextView) certificateView.findViewById(R.id.issued_on))
4072 .setText(issuedOn);
4073
4074 // expires on:
4075 String expiresOn = reformatCertificateDate(
4076 certificate.getValidNotAfter());
4077 ((TextView) certificateView.findViewById(R.id.expires_on))
4078 .setText(expiresOn);
4079
4080 return certificateView;
4081 }
4082
4083 /**
4084 * Re-formats the certificate date (Date.toString()) string to
4085 * a properly localized date string.
4086 * @return Properly localized version of the certificate date string and
4087 * the original certificate date string if fails to localize.
4088 * If the original string is null, returns an empty string "".
4089 */
4090 private String reformatCertificateDate(String certificateDate) {
4091 String reformattedDate = null;
4092
4093 if (certificateDate != null) {
4094 Date date = null;
4095 try {
4096 date = java.text.DateFormat.getInstance().parse(certificateDate);
4097 } catch (ParseException e) {
4098 date = null;
4099 }
4100
4101 if (date != null) {
4102 reformattedDate =
4103 DateFormat.getDateFormat(this).format(date);
4104 }
4105 }
4106
4107 return reformattedDate != null ? reformattedDate :
4108 (certificateDate != null ? certificateDate : "");
4109 }
4110
4111 /**
4112 * Displays an http-authentication dialog.
4113 */
4114 private void showHttpAuthentication(final HttpAuthHandler handler,
4115 final String host, final String realm, final String title,
4116 final String name, final String password, int focusId) {
4117 LayoutInflater factory = LayoutInflater.from(this);
4118 final View v = factory
4119 .inflate(R.layout.http_authentication, null);
4120 if (name != null) {
4121 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4122 }
4123 if (password != null) {
4124 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4125 }
4126
4127 String titleText = title;
4128 if (titleText == null) {
4129 titleText = getText(R.string.sign_in_to).toString().replace(
4130 "%s1", host).replace("%s2", realm);
4131 }
4132
4133 mHttpAuthHandler = handler;
4134 AlertDialog dialog = new AlertDialog.Builder(this)
4135 .setTitle(titleText)
4136 .setIcon(android.R.drawable.ic_dialog_alert)
4137 .setView(v)
4138 .setPositiveButton(R.string.action,
4139 new DialogInterface.OnClickListener() {
4140 public void onClick(DialogInterface dialog,
4141 int whichButton) {
4142 String nm = ((EditText) v
4143 .findViewById(R.id.username_edit))
4144 .getText().toString();
4145 String pw = ((EditText) v
4146 .findViewById(R.id.password_edit))
4147 .getText().toString();
4148 BrowserActivity.this.setHttpAuthUsernamePassword
4149 (host, realm, nm, pw);
4150 handler.proceed(nm, pw);
4151 mHttpAuthenticationDialog = null;
4152 mHttpAuthHandler = null;
4153 }})
4154 .setNegativeButton(R.string.cancel,
4155 new DialogInterface.OnClickListener() {
4156 public void onClick(DialogInterface dialog,
4157 int whichButton) {
4158 handler.cancel();
4159 BrowserActivity.this.resetTitleAndRevertLockIcon();
4160 mHttpAuthenticationDialog = null;
4161 mHttpAuthHandler = null;
4162 }})
4163 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4164 public void onCancel(DialogInterface dialog) {
4165 handler.cancel();
4166 BrowserActivity.this.resetTitleAndRevertLockIcon();
4167 mHttpAuthenticationDialog = null;
4168 mHttpAuthHandler = null;
4169 }})
4170 .create();
4171 // Make the IME appear when the dialog is displayed if applicable.
4172 dialog.getWindow().setSoftInputMode(
4173 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4174 dialog.show();
4175 if (focusId != 0) {
4176 dialog.findViewById(focusId).requestFocus();
4177 } else {
4178 v.findViewById(R.id.username_edit).requestFocus();
4179 }
4180 mHttpAuthenticationDialog = dialog;
4181 }
4182
4183 public int getProgress() {
4184 WebView w = mTabControl.getCurrentWebView();
4185 if (w != null) {
4186 return w.getProgress();
4187 } else {
4188 return 100;
4189 }
4190 }
4191
4192 /**
4193 * Set HTTP authentication password.
4194 *
4195 * @param host The host for the password
4196 * @param realm The realm for the password
4197 * @param username The username for the password. If it is null, it means
4198 * password can't be saved.
4199 * @param password The password
4200 */
4201 public void setHttpAuthUsernamePassword(String host, String realm,
4202 String username,
4203 String password) {
4204 WebView w = mTabControl.getCurrentWebView();
4205 if (w != null) {
4206 w.setHttpAuthUsernamePassword(host, realm, username, password);
4207 }
4208 }
4209
4210 /**
4211 * connectivity manager says net has come or gone... inform the user
4212 * @param up true if net has come up, false if net has gone down
4213 */
4214 public void onNetworkToggle(boolean up) {
4215 if (up == mIsNetworkUp) {
4216 return;
4217 } else if (up) {
4218 mIsNetworkUp = true;
4219 if (mAlertDialog != null) {
4220 mAlertDialog.cancel();
4221 mAlertDialog = null;
4222 }
4223 } else {
4224 mIsNetworkUp = false;
4225 if (mInLoad && mAlertDialog == null) {
4226 mAlertDialog = new AlertDialog.Builder(this)
4227 .setTitle(R.string.loadSuspendedTitle)
4228 .setMessage(R.string.loadSuspended)
4229 .setPositiveButton(R.string.ok, null)
4230 .show();
4231 }
4232 }
4233 WebView w = mTabControl.getCurrentWebView();
4234 if (w != null) {
4235 w.setNetworkAvailable(up);
4236 }
4237 }
4238
4239 @Override
4240 protected void onActivityResult(int requestCode, int resultCode,
4241 Intent intent) {
4242 switch (requestCode) {
4243 case COMBO_PAGE:
4244 if (resultCode == RESULT_OK && intent != null) {
4245 String data = intent.getAction();
4246 Bundle extras = intent.getExtras();
4247 if (extras != null && extras.getBoolean("new_window", false)) {
4248 openTab(data);
4249 } else {
4250 final TabControl.Tab currentTab =
4251 mTabControl.getCurrentTab();
4252 // If the Window overview is up and we are not in the
4253 // middle of an animation, animate away from it to the
4254 // current tab.
4255 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004256 sendAnimateFromOverview(currentTab, false, new UrlData(data),
The Android Open Source Project0c908882009-03-03 19:32:16 -08004257 TAB_OVERVIEW_DELAY, null);
4258 } else {
4259 dismissSubWindow(currentTab);
4260 if (data != null && data.length() != 0) {
4261 getTopWindow().loadUrl(data);
4262 }
4263 }
4264 }
4265 }
4266 break;
4267 default:
4268 break;
4269 }
4270 getTopWindow().requestFocus();
4271 }
4272
4273 /*
4274 * This method is called as a result of the user selecting the options
4275 * menu to see the download window, or when a download changes state. It
4276 * shows the download window ontop of the current window.
4277 */
4278 /* package */ void viewDownloads(Uri downloadRecord) {
4279 Intent intent = new Intent(this,
4280 BrowserDownloadPage.class);
4281 intent.setData(downloadRecord);
4282 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4283
4284 }
4285
4286 /**
4287 * Handle results from Tab Switcher mTabOverview tool
4288 */
4289 private class TabListener implements ImageGrid.Listener {
4290 public void remove(int position) {
4291 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004292 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004293 throw new AssertionError();
4294 }
4295
4296 // Remember the current tab.
4297 TabControl.Tab current = mTabControl.getCurrentTab();
4298 final TabControl.Tab remove = mTabControl.getTab(position);
4299 mTabControl.removeTab(remove);
4300 // If we removed the current tab, use the tab at position - 1 if
4301 // possible.
4302 if (current == remove) {
4303 // If the user removes the last tab, act like the New Tab item
4304 // was clicked on.
4305 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004306 current = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004307 sendAnimateFromOverview(current, true,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004308 new UrlData(mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004309 } else {
4310 final int index = position > 0 ? (position - 1) : 0;
4311 current = mTabControl.getTab(index);
4312 }
4313 }
4314
4315 // The tab overview could have been dismissed before this method is
4316 // called.
4317 if (mTabOverview != null) {
4318 // Remove the tab and change the index.
4319 mTabOverview.remove(position);
4320 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4321 }
4322
4323 // Only the current tab ensures its WebView is non-null. This
4324 // implies that we are reloading the freed tab.
4325 mTabControl.setCurrentTab(current);
4326 }
4327 public void onClick(int index) {
4328 // Change the tab if necessary.
4329 // Index equals ImageGrid.CANCEL when pressing back from the tab
4330 // overview.
4331 if (index == ImageGrid.CANCEL) {
4332 index = mTabControl.getCurrentIndex();
4333 // The current index is -1 if the current tab was removed.
4334 if (index == -1) {
4335 // Take the last tab as a fallback.
4336 index = mTabControl.getTabCount() - 1;
4337 }
4338 }
4339
The Android Open Source Project0c908882009-03-03 19:32:16 -08004340 // NEW_TAB means that the "New Tab" cell was clicked on.
4341 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004342 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004343 } else {
4344 sendAnimateFromOverview(mTabControl.getTab(index),
Patrick Scott95d601f2009-06-11 10:06:46 -04004345 false, EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004346 }
4347 }
4348 }
4349
4350 // A fake View that draws the WebView's picture with a fast zoom filter.
4351 // The View is used in case the tab is freed during the animation because
4352 // of low memory.
4353 private static class AnimatingView extends View {
4354 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4355 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4356 private static final DrawFilter sZoomFilter =
4357 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4358 private final Picture mPicture;
4359 private final float mScale;
4360 private final int mScrollX;
4361 private final int mScrollY;
4362 final TabControl.Tab mTab;
4363
4364 AnimatingView(Context ctxt, TabControl.Tab t) {
4365 super(ctxt);
4366 mTab = t;
4367 // Use the top window in the animation since the tab overview will
4368 // display the top window in each cell.
4369 final WebView w = t.getTopWindow();
4370 mPicture = w.capturePicture();
4371 mScale = w.getScale() / w.getWidth();
4372 mScrollX = w.getScrollX();
4373 mScrollY = w.getScrollY();
4374 }
4375
4376 @Override
4377 protected void onDraw(Canvas canvas) {
4378 canvas.save();
4379 canvas.drawColor(Color.WHITE);
4380 if (mPicture != null) {
4381 canvas.setDrawFilter(sZoomFilter);
4382 float scale = getWidth() * mScale;
4383 canvas.scale(scale, scale);
4384 canvas.translate(-mScrollX, -mScrollY);
4385 canvas.drawPicture(mPicture);
4386 }
4387 canvas.restore();
4388 }
4389 }
4390
4391 /**
4392 * Open the tab picker. This function will always use the current tab in
4393 * its animation.
4394 * @param stay boolean stating whether the tab picker is to remain open
4395 * (in which case it needs a listener and its menu) or not.
4396 * @param index The index of the tab to show as the selection in the tab
4397 * overview.
4398 * @param remove If true, the tab at index will be removed after the
4399 * animation completes.
4400 */
4401 private void tabPicker(final boolean stay, final int index,
4402 final boolean remove) {
4403 if (mTabOverview != null) {
4404 return;
4405 }
4406
4407 int size = mTabControl.getTabCount();
4408
4409 TabListener l = null;
4410 if (stay) {
4411 l = mTabListener = new TabListener();
4412 }
4413 mTabOverview = new ImageGrid(this, stay, l);
4414
4415 for (int i = 0; i < size; i++) {
4416 final TabControl.Tab t = mTabControl.getTab(i);
4417 mTabControl.populatePickerData(t);
4418 mTabOverview.add(t);
4419 }
4420
4421 // Tell the tab overview to show the current tab, the tab overview will
4422 // handle the "New Tab" case.
4423 int currentIndex = mTabControl.getCurrentIndex();
4424 mTabOverview.setCurrentIndex(currentIndex);
4425
4426 // Attach the tab overview.
4427 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4428
4429 // Create a fake AnimatingView to animate the WebView's picture.
4430 final TabControl.Tab current = mTabControl.getCurrentTab();
4431 final AnimatingView v = new AnimatingView(this, current);
4432 mContentView.addView(v, COVER_SCREEN_PARAMS);
4433 removeTabFromContentView(current);
4434 // Pause timers to get the animation smoother.
4435 current.getWebView().pauseTimers();
4436
4437 // Send a message so the tab picker has a chance to layout and get
4438 // positions for all the cells.
4439 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4440 index, remove ? 1 : 0, v));
4441 // Setting this will indicate that we are animating to the overview. We
4442 // set it here to prevent another request to animate from coming in
4443 // between now and when ANIMATE_TO_OVERVIEW is handled.
4444 mAnimationCount++;
4445 // Always change the title bar to the window overview title while
4446 // animating.
4447 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4448 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4449 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4450 Window.PROGRESS_VISIBILITY_OFF);
4451 setTitle(R.string.tab_picker_title);
4452 // Make the menu empty until the animation completes.
4453 mMenuState = EMPTY_MENU;
4454 }
4455
4456 private void bookmarksOrHistoryPicker(boolean startWithHistory) {
4457 WebView current = mTabControl.getCurrentWebView();
4458 if (current == null) {
4459 return;
4460 }
4461 Intent intent = new Intent(this,
4462 CombinedBookmarkHistoryActivity.class);
4463 String title = current.getTitle();
4464 String url = current.getUrl();
4465 // Just in case the user opens bookmarks before a page finishes loading
4466 // so the current history item, and therefore the page, is null.
4467 if (null == url) {
4468 url = mLastEnteredUrl;
4469 // This can happen.
4470 if (null == url) {
4471 url = mSettings.getHomePage();
4472 }
4473 }
4474 // In case the web page has not yet received its associated title.
4475 if (title == null) {
4476 title = url;
4477 }
4478 intent.putExtra("title", title);
4479 intent.putExtra("url", url);
4480 intent.putExtra("maxTabsOpen",
4481 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4482 if (startWithHistory) {
4483 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4484 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4485 }
4486 startActivityForResult(intent, COMBO_PAGE);
4487 }
4488
4489 // Called when loading from context menu or LOAD_URL message
4490 private void loadURL(WebView view, String url) {
4491 // In case the user enters nothing.
4492 if (url != null && url.length() != 0 && view != null) {
4493 url = smartUrlFilter(url);
4494 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4495 view.loadUrl(url);
4496 }
4497 }
4498 }
4499
4500 private void checkMemory() {
4501 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4502 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4503 .getMemoryInfo(mi);
4504 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4505 // mi.threshold) for now
4506 // if (mi.lowMemory) {
4507 if (mi.availMem < mi.threshold) {
4508 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4509 + (mi.availMem / 1024) + "K threshold="
4510 + (mi.threshold / 1024) + "K");
4511 mTabControl.freeMemory();
4512 }
4513 }
4514
4515 private String smartUrlFilter(Uri inUri) {
4516 if (inUri != null) {
4517 return smartUrlFilter(inUri.toString());
4518 }
4519 return null;
4520 }
4521
4522
4523 // get window count
4524
4525 int getWindowCount(){
4526 if(mTabControl != null){
4527 return mTabControl.getTabCount();
4528 }
4529 return 0;
4530 }
4531
4532 static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
4533 "(?i)" + // switch on case insensitive matching
4534 "(" + // begin group for schema
4535 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004536 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004537 ")" +
4538 "(.*)" );
4539
4540 /**
4541 * Attempts to determine whether user input is a URL or search
4542 * terms. Anything with a space is passed to search.
4543 *
4544 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4545 * "Http://" converts to "http://"
4546 *
4547 * @return Original or modified URL
4548 *
4549 */
4550 String smartUrlFilter(String url) {
4551
4552 String inUrl = url.trim();
4553 boolean hasSpace = inUrl.indexOf(' ') != -1;
4554
4555 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4556 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004557 // force scheme to lowercase
4558 String scheme = matcher.group(1);
4559 String lcScheme = scheme.toLowerCase();
4560 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004561 inUrl = lcScheme + matcher.group(2);
4562 }
4563 if (hasSpace) {
4564 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004565 }
4566 return inUrl;
4567 }
4568 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004569 // FIXME: Is this the correct place to add to searches?
4570 // what if someone else calls this function?
4571 int shortcut = parseUrlShortcut(inUrl);
4572 if (shortcut != SHORTCUT_INVALID) {
4573 Browser.addSearchUrl(mResolver, inUrl);
4574 String query = inUrl.substring(2);
4575 switch (shortcut) {
4576 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004577 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004578 case SHORTCUT_WIKIPEDIA_SEARCH:
4579 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4580 case SHORTCUT_DICTIONARY_SEARCH:
4581 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4582 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004583 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004584 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004585 }
4586 }
4587 } else {
4588 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4589 return URLUtil.guessUrl(inUrl);
4590 }
4591 }
4592
4593 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004594 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004595 }
4596
4597 private final static int LOCK_ICON_UNSECURE = 0;
4598 private final static int LOCK_ICON_SECURE = 1;
4599 private final static int LOCK_ICON_MIXED = 2;
4600
4601 private int mLockIconType = LOCK_ICON_UNSECURE;
4602 private int mPrevLockType = LOCK_ICON_UNSECURE;
4603
4604 private BrowserSettings mSettings;
4605 private TabControl mTabControl;
4606 private ContentResolver mResolver;
4607 private FrameLayout mContentView;
4608 private ImageGrid mTabOverview;
4609
4610 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4611 // view, we should rewrite this.
4612 private int mCurrentMenuState = 0;
4613 private int mMenuState = R.id.MAIN_MENU;
4614 private static final int EMPTY_MENU = -1;
4615 private Menu mMenu;
4616
4617 private FindDialog mFindDialog;
4618 // Used to prevent chording to result in firing two shortcuts immediately
4619 // one after another. Fixes bug 1211714.
4620 boolean mCanChord;
4621
4622 private boolean mInLoad;
4623 private boolean mIsNetworkUp;
4624
4625 private boolean mPageStarted;
4626 private boolean mActivityInPause = true;
4627
4628 private boolean mMenuIsDown;
4629
4630 private final KeyTracker mKeyTracker = new KeyTracker(this);
4631
4632 // As trackball doesn't send repeat down, we have to track it ourselves
4633 private boolean mTrackTrackball;
4634
4635 private static boolean mInTrace;
4636
4637 // Performance probe
4638 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4639 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4640 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4641 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4642 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4643 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4644 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4645 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4646 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4647 };
4648
4649 private long mStart;
4650 private long mProcessStart;
4651 private long mUserStart;
4652 private long mSystemStart;
4653 private long mIdleStart;
4654 private long mIrqStart;
4655
4656 private long mUiStart;
4657
4658 private Drawable mMixLockIcon;
4659 private Drawable mSecLockIcon;
4660 private Drawable mGenericFavicon;
4661
4662 /* hold a ref so we can auto-cancel if necessary */
4663 private AlertDialog mAlertDialog;
4664
4665 // Wait for credentials before loading google.com
4666 private ProgressDialog mCredsDlg;
4667
4668 // The up-to-date URL and title (these can be different from those stored
4669 // in WebView, since it takes some time for the information in WebView to
4670 // get updated)
4671 private String mUrl;
4672 private String mTitle;
4673
4674 // As PageInfo has different style for landscape / portrait, we have
4675 // to re-open it when configuration changed
4676 private AlertDialog mPageInfoDialog;
4677 private TabControl.Tab mPageInfoView;
4678 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4679 // dialog, we should not just dismiss it, but should get back to the
4680 // SSL-certificate-on-error dialog. This flag is used to store this state
4681 private Boolean mPageInfoFromShowSSLCertificateOnError;
4682
4683 // as SSLCertificateOnError has different style for landscape / portrait,
4684 // we have to re-open it when configuration changed
4685 private AlertDialog mSSLCertificateOnErrorDialog;
4686 private WebView mSSLCertificateOnErrorView;
4687 private SslErrorHandler mSSLCertificateOnErrorHandler;
4688 private SslError mSSLCertificateOnErrorError;
4689
4690 // as SSLCertificate has different style for landscape / portrait, we
4691 // have to re-open it when configuration changed
4692 private AlertDialog mSSLCertificateDialog;
4693 private TabControl.Tab mSSLCertificateView;
4694
4695 // as HttpAuthentication has different style for landscape / portrait, we
4696 // have to re-open it when configuration changed
4697 private AlertDialog mHttpAuthenticationDialog;
4698 private HttpAuthHandler mHttpAuthHandler;
4699
4700 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4701 new FrameLayout.LayoutParams(
4702 ViewGroup.LayoutParams.FILL_PARENT,
4703 ViewGroup.LayoutParams.FILL_PARENT);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004704 // Google search
4705 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08004706 // Wikipedia search
4707 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4708 // Dictionary search
4709 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4710 // Google Mobile Local search
4711 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4712
4713 final static String QUERY_PLACE_HOLDER = "%s";
4714
4715 // "source" parameter for Google search through search key
4716 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
4717 // "source" parameter for Google search through goto menu
4718 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
4719 // "source" parameter for Google search through simplily type
4720 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
4721 // "source" parameter for Google search suggested by the browser
4722 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
4723 // "source" parameter for Google search from unknown source
4724 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
4725
4726 private final static String LOGTAG = "browser";
4727
4728 private TabListener mTabListener;
4729
4730 private String mLastEnteredUrl;
4731
4732 private PowerManager.WakeLock mWakeLock;
4733 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
4734
4735 private Toast mStopToast;
4736
4737 // Used during animations to prevent other animations from being triggered.
4738 // A count is used since the animation to and from the Window overview can
4739 // overlap. A count of 0 means no animation where a count of > 0 means
4740 // there are animations in progress.
4741 private int mAnimationCount;
4742
4743 // As the ids are dynamically created, we can't guarantee that they will
4744 // be in sequence, so this static array maps ids to a window number.
4745 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
4746 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
4747 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
4748 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
4749
4750 // monitor platform changes
4751 private IntentFilter mNetworkStateChangedFilter;
4752 private BroadcastReceiver mNetworkStateIntentReceiver;
4753
4754 // activity requestCode
4755 final static int COMBO_PAGE = 1;
4756 final static int DOWNLOAD_PAGE = 2;
4757 final static int PREFERENCES_PAGE = 3;
4758
4759 // the frenquency of checking whether system memory is low
4760 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004761
4762 /**
4763 * A UrlData class to abstract how the content will be set to WebView.
4764 * This base class uses loadUrl to show the content.
4765 */
4766 private static class UrlData {
4767 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07004768 byte[] mPostData;
4769
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004770 UrlData(String url) {
4771 this.mUrl = url;
4772 }
Grace Kloba60e095c2009-06-16 11:50:55 -07004773
4774 void setPostData(byte[] postData) {
4775 mPostData = postData;
4776 }
4777
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004778 boolean isEmpty() {
4779 return mUrl == null || mUrl.length() == 0;
4780 }
4781
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004782 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07004783 if (mPostData != null) {
4784 webView.postUrl(mUrl, mPostData);
4785 } else {
4786 webView.loadUrl(mUrl);
4787 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004788 }
4789 };
4790
4791 /**
4792 * A subclass of UrlData class that can display inlined content using
4793 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
4794 */
4795 private static class InlinedUrlData extends UrlData {
4796 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
4797 super(failUrl);
4798 mInlined = inlined;
4799 mMimeType = mimeType;
4800 mEncoding = encoding;
4801 }
4802 String mMimeType;
4803 String mInlined;
4804 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004805 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004806 boolean isEmpty() {
4807 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
4808 }
4809
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07004810 @Override
4811 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004812 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
4813 }
4814 }
4815
4816 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004817}