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