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