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