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