blob: 1c2c6af3f3eb04dc52a2de5c09eae69449da697c [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 }
Feng Qianb3c02da2009-06-29 15:58:08 -0700786 // Read JavaScript flags if it exists.
787 String jsFlags = mSettings.getJsFlags();
788 if (jsFlags.trim().length() != 0) {
789 mTabControl.getCurrentWebView().setJsFlags(jsFlags);
790 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800791
792 /* enables registration for changes in network status from
793 http stack */
794 mNetworkStateChangedFilter = new IntentFilter();
795 mNetworkStateChangedFilter.addAction(
796 ConnectivityManager.CONNECTIVITY_ACTION);
797 mNetworkStateIntentReceiver = new BroadcastReceiver() {
798 @Override
799 public void onReceive(Context context, Intent intent) {
800 if (intent.getAction().equals(
801 ConnectivityManager.CONNECTIVITY_ACTION)) {
802 boolean down = intent.getBooleanExtra(
803 ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
804 onNetworkToggle(!down);
805 }
806 }
807 };
Grace Klobab4da0ad2009-05-14 14:45:40 -0700808
809 IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);
810 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
811 filter.addDataScheme("package");
812 mPackageInstallationReceiver = new BroadcastReceiver() {
813 @Override
814 public void onReceive(Context context, Intent intent) {
815 final String action = intent.getAction();
816 final String packageName = intent.getData()
817 .getSchemeSpecificPart();
818 final boolean replacing = intent.getBooleanExtra(
819 Intent.EXTRA_REPLACING, false);
820 if (Intent.ACTION_PACKAGE_REMOVED.equals(action) && replacing) {
821 // if it is replacing, refreshPlugins() when adding
822 return;
823 }
824 PackageManager pm = BrowserActivity.this.getPackageManager();
825 PackageInfo pkgInfo = null;
826 try {
827 pkgInfo = pm.getPackageInfo(packageName,
828 PackageManager.GET_PERMISSIONS);
829 } catch (PackageManager.NameNotFoundException e) {
830 return;
831 }
832 if (pkgInfo != null) {
833 String permissions[] = pkgInfo.requestedPermissions;
834 if (permissions == null) {
835 return;
836 }
837 boolean permissionOk = false;
838 for (String permit : permissions) {
839 if (PluginManager.PLUGIN_PERMISSION.equals(permit)) {
840 permissionOk = true;
841 break;
842 }
843 }
844 if (permissionOk) {
845 PluginManager.getInstance(BrowserActivity.this)
846 .refreshPlugins(
847 Intent.ACTION_PACKAGE_ADDED
848 .equals(action));
849 }
850 }
851 }
852 };
853 registerReceiver(mPackageInstallationReceiver, filter);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800854 }
855
856 @Override
857 protected void onNewIntent(Intent intent) {
858 TabControl.Tab current = mTabControl.getCurrentTab();
859 // When a tab is closed on exit, the current tab index is set to -1.
860 // Reset before proceed as Browser requires the current tab to be set.
861 if (current == null) {
862 // Try to reset the tab in case the index was incorrect.
863 current = mTabControl.getTab(0);
864 if (current == null) {
865 // No tabs at all so just ignore this intent.
866 return;
867 }
868 mTabControl.setCurrentTab(current);
869 attachTabToContentView(current);
870 resetTitleAndIcon(current.getWebView());
871 }
872 final String action = intent.getAction();
873 final int flags = intent.getFlags();
874 if (Intent.ACTION_MAIN.equals(action) ||
875 (flags & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) != 0) {
876 // just resume the browser
877 return;
878 }
879 if (Intent.ACTION_VIEW.equals(action)
880 || Intent.ACTION_SEARCH.equals(action)
881 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
882 || Intent.ACTION_WEB_SEARCH.equals(action)) {
Satish Sampath565505b2009-05-29 15:37:27 +0100883 // If this was a search request (e.g. search query directly typed into the address bar),
884 // pass it on to the default web search provider.
885 if (handleWebSearchIntent(intent)) {
886 return;
887 }
888
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700889 UrlData urlData = getUrlDataFromIntent(intent);
890 if (urlData.isEmpty()) {
891 urlData = new UrlData(mSettings.getHomePage());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800892 }
Grace Kloba60e095c2009-06-16 11:50:55 -0700893 urlData.setPostData(getLocationData(intent));
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700894
The Android Open Source Project0c908882009-03-03 19:32:16 -0800895 if (Intent.ACTION_VIEW.equals(action) &&
896 (flags & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700897 final String appId =
898 intent.getStringExtra(Browser.EXTRA_APPLICATION_ID);
899 final TabControl.Tab appTab = mTabControl.getTabFromId(appId);
900 if (appTab != null) {
901 Log.i(LOGTAG, "Reusing tab for " + appId);
902 // Dismiss the subwindow if applicable.
903 dismissSubWindow(appTab);
904 // Since we might kill the WebView, remove it from the
905 // content view first.
906 removeTabFromContentView(appTab);
907 // Recreate the main WebView after destroying the old one.
908 // If the WebView has the same original url and is on that
909 // page, it can be reused.
910 boolean needsLoad =
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700911 mTabControl.recreateWebView(appTab, urlData.mUrl);
912
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700913 if (current != appTab) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700914 showTab(appTab, needsLoad ? urlData : EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700915 } else {
916 if (mTabOverview != null && mAnimationCount == 0) {
917 sendAnimateFromOverview(appTab, false,
Grace Klobaec7eb372009-06-16 13:45:56 -0700918 needsLoad ? urlData : EMPTY_URL_DATA,
Grace Kloba8ca2c792009-05-26 15:41:51 -0700919 TAB_OVERVIEW_DELAY, null);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700920 } else {
921 // If the tab was the current tab, we have to attach
922 // it to the view system again.
923 attachTabToContentView(appTab);
924 if (needsLoad) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700925 urlData.loadIn(appTab.getWebView());
The Android Open Source Projectf59ec872009-03-13 13:04:24 -0700926 }
927 }
928 }
929 return;
930 }
The Android Open Source Project0c908882009-03-03 19:32:16 -0800931 // if FLAG_ACTIVITY_BROUGHT_TO_FRONT flag is on, the url will be
932 // opened in a new tab unless we have reached MAX_TABS. Then the
933 // url will be opened in the current tab. If a new tab is
934 // created, it will have "true" for exit on close.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700935 openTabAndShow(urlData, null, true, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800936 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700937 if ("about:debug".equals(urlData.mUrl)) {
The Android Open Source Project0c908882009-03-03 19:32:16 -0800938 mSettings.toggleDebugSettings();
939 return;
940 }
941 // If the Window overview is up and we are not in the midst of
942 // an animation, animate away from the Window overview.
943 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700944 sendAnimateFromOverview(current, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -0800945 TAB_OVERVIEW_DELAY, null);
946 } else {
947 // Get rid of the subwindow if it exists
948 dismissSubWindow(current);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -0700949 urlData.loadIn(current.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -0800950 }
951 }
952 }
953 }
954
Satish Sampath565505b2009-05-29 15:37:27 +0100955 private int parseUrlShortcut(String url) {
956 if (url == null) return SHORTCUT_INVALID;
957
958 // FIXME: quick search, need to be customized by setting
959 if (url.length() > 2 && url.charAt(1) == ' ') {
960 switch (url.charAt(0)) {
961 case 'g': return SHORTCUT_GOOGLE_SEARCH;
962 case 'w': return SHORTCUT_WIKIPEDIA_SEARCH;
963 case 'd': return SHORTCUT_DICTIONARY_SEARCH;
964 case 'l': return SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH;
965 }
966 }
967 return SHORTCUT_INVALID;
968 }
969
970 /**
971 * Launches the default web search activity with the query parameters if the given intent's data
972 * are identified as plain search terms and not URLs/shortcuts.
973 * @return true if the intent was handled and web search activity was launched, false if not.
974 */
975 private boolean handleWebSearchIntent(Intent intent) {
976 if (intent == null) return false;
977
978 String url = null;
979 final String action = intent.getAction();
980 if (Intent.ACTION_VIEW.equals(action)) {
981 url = intent.getData().toString();
982 } else if (Intent.ACTION_SEARCH.equals(action)
983 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
984 || Intent.ACTION_WEB_SEARCH.equals(action)) {
985 url = intent.getStringExtra(SearchManager.QUERY);
986 }
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100987 return handleWebSearchRequest(url, intent.getBundleExtra(SearchManager.APP_DATA));
Satish Sampath565505b2009-05-29 15:37:27 +0100988 }
989
990 /**
991 * Launches the default web search activity with the query parameters if the given url string
992 * was identified as plain search terms and not URL/shortcut.
993 * @return true if the request was handled and web search activity was launched, false if not.
994 */
Satish Sampath15e9f2d2009-06-23 22:29:49 +0100995 private boolean handleWebSearchRequest(String inUrl, Bundle appData) {
Satish Sampath565505b2009-05-29 15:37:27 +0100996 if (inUrl == null) return false;
997
998 // In general, we shouldn't modify URL from Intent.
999 // But currently, we get the user-typed URL from search box as well.
1000 String url = fixUrl(inUrl).trim();
1001
1002 // URLs and site specific search shortcuts are handled by the regular flow of control, so
1003 // return early.
1004 if (Regex.WEB_URL_PATTERN.matcher(url).matches()
Satish Sampathbc5b9f32009-06-04 18:21:40 +01001005 || ACCEPTED_URI_SCHEMA.matcher(url).matches()
Satish Sampath565505b2009-05-29 15:37:27 +01001006 || parseUrlShortcut(url) != SHORTCUT_INVALID) {
1007 return false;
1008 }
1009
1010 Browser.updateVisitedHistory(mResolver, url, false);
1011 Browser.addSearchUrl(mResolver, url);
1012
1013 Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
1014 intent.addCategory(Intent.CATEGORY_DEFAULT);
1015 intent.putExtra(SearchManager.QUERY, url);
Satish Sampath15e9f2d2009-06-23 22:29:49 +01001016 if (appData != null) {
1017 intent.putExtra(SearchManager.APP_DATA, appData);
1018 }
Satish Sampath565505b2009-05-29 15:37:27 +01001019 startActivity(intent);
1020
1021 return true;
1022 }
1023
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001024 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001025 String url = null;
1026 if (intent != null) {
1027 final String action = intent.getAction();
1028 if (Intent.ACTION_VIEW.equals(action)) {
1029 url = smartUrlFilter(intent.getData());
1030 if (url != null && url.startsWith("content:")) {
1031 /* Append mimetype so webview knows how to display */
1032 String mimeType = intent.resolveType(getContentResolver());
1033 if (mimeType != null) {
1034 url += "?" + mimeType;
1035 }
1036 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001037 if ("inline:".equals(url)) {
1038 return new InlinedUrlData(
1039 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
1040 intent.getType(),
1041 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
1042 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
1043 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001044 } else if (Intent.ACTION_SEARCH.equals(action)
1045 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
1046 || Intent.ACTION_WEB_SEARCH.equals(action)) {
1047 url = intent.getStringExtra(SearchManager.QUERY);
1048 if (url != null) {
1049 mLastEnteredUrl = url;
1050 // Don't add Urls, just search terms.
1051 // Urls will get added when the page is loaded.
1052 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
1053 Browser.updateVisitedHistory(mResolver, url, false);
1054 }
1055 // In general, we shouldn't modify URL from Intent.
1056 // But currently, we get the user-typed URL from search box as well.
1057 url = fixUrl(url);
1058 url = smartUrlFilter(url);
1059 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
1060 if (url.contains(searchSource)) {
1061 String source = null;
1062 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
1063 if (appData != null) {
1064 source = appData.getString(SearchManager.SOURCE);
1065 }
1066 if (TextUtils.isEmpty(source)) {
1067 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
1068 }
1069 url = url.replace(searchSource, "&source=android-"+source+"&");
1070 }
1071 }
1072 }
1073 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001074 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001075 }
1076
Grace Kloba8ca2c792009-05-26 15:41:51 -07001077 byte[] getLocationData(Intent intent) {
1078 byte[] postData = null;
1079 if (intent != null) {
1080 final String action = intent.getAction();
Grace Kloba60e095c2009-06-16 11:50:55 -07001081 if (Intent.ACTION_VIEW.equals(action)
1082 && intent.getBooleanExtra(Browser.EXTRA_APPEND_LOCATION,
1083 false)) {
1084 ContentResolver cr = getContentResolver();
Grace Kloba2595f142009-06-22 12:18:15 -07001085 int use = Settings.Secure.getInt(cr,
1086 Settings.Secure.USE_LOCATION_FOR_SERVICES, -1);
Grace Kloba60e095c2009-06-16 11:50:55 -07001087 if (use == -1) {
Grace Kloba2595f142009-06-22 12:18:15 -07001088 // bring up the consent dialog if it is undefined. And we
1089 // will not send the location info for this query.
1090 Intent consent = new Intent(
1091 Settings.ACTION_SECURITY_SETTINGS);
1092 consent.putExtra("SHOW_USE_LOCATION", true);
1093 startActivity(consent);
Grace Kloba60e095c2009-06-16 11:50:55 -07001094 } else if (use == 1
1095 && Settings.Secure.isLocationProviderEnabled(cr,
1096 LocationManager.NETWORK_PROVIDER)) {
1097 Location location = ((LocationManager) getSystemService(
1098 Context.LOCATION_SERVICE)).getLastKnownLocation(
1099 LocationManager.NETWORK_PROVIDER);
1100 if (location != null) {
1101 StringBuilder str = new StringBuilder(
1102 "action=devloc&sll=");
1103 str.append(location.getLatitude()).append(',').append(
1104 location.getLongitude());
1105 postData = str.toString().getBytes();
1106 }
Grace Kloba8ca2c792009-05-26 15:41:51 -07001107 }
1108 }
1109 }
1110 return postData;
1111 }
1112
The Android Open Source Project0c908882009-03-03 19:32:16 -08001113 /* package */ static String fixUrl(String inUrl) {
1114 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
1115 return inUrl;
1116 if (inUrl.startsWith("http:") ||
1117 inUrl.startsWith("https:")) {
1118 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
1119 inUrl = inUrl.replaceFirst("/", "//");
1120 } else inUrl = inUrl.replaceFirst(":", "://");
1121 }
1122 return inUrl;
1123 }
1124
1125 /**
1126 * Looking for the pattern like this
1127 *
1128 * *
1129 * * *
1130 * *** * *******
1131 * * *
1132 * * *
1133 * *
1134 */
1135 private final SensorListener mSensorListener = new SensorListener() {
1136 private long mLastGestureTime;
1137 private float[] mPrev = new float[3];
1138 private float[] mPrevDiff = new float[3];
1139 private float[] mDiff = new float[3];
1140 private float[] mRevertDiff = new float[3];
1141
1142 public void onSensorChanged(int sensor, float[] values) {
1143 boolean show = false;
1144 float[] diff = new float[3];
1145
1146 for (int i = 0; i < 3; i++) {
1147 diff[i] = values[i] - mPrev[i];
1148 if (Math.abs(diff[i]) > 1) {
1149 show = true;
1150 }
1151 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
1152 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
1153 // start track when there is a big move, or revert
1154 mRevertDiff[i] = mDiff[i];
1155 mDiff[i] = 0;
1156 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
1157 // reset when it is flat
1158 mDiff[i] = mRevertDiff[i] = 0;
1159 }
1160 mDiff[i] += diff[i];
1161 mPrevDiff[i] = diff[i];
1162 mPrev[i] = values[i];
1163 }
1164
1165 if (false) {
1166 // only shows if we think the delta is big enough, in an attempt
1167 // to detect "serious" moves left/right or up/down
1168 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
1169 + values[0] + ", " + values[1] + ", " + values[2] + ")"
1170 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
1171 + ")");
1172 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
1173 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
1174 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
1175 + mRevertDiff[2] + ")");
1176 }
1177
1178 long now = android.os.SystemClock.uptimeMillis();
1179 if (now - mLastGestureTime > 1000) {
1180 mLastGestureTime = 0;
1181
1182 float y = mDiff[1];
1183 float z = mDiff[2];
1184 float ay = Math.abs(y);
1185 float az = Math.abs(z);
1186 float ry = mRevertDiff[1];
1187 float rz = mRevertDiff[2];
1188 float ary = Math.abs(ry);
1189 float arz = Math.abs(rz);
1190 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
1191 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
1192
1193 if ((gestY || gestZ) && !(gestY && gestZ)) {
1194 WebView view = mTabControl.getCurrentWebView();
1195
1196 if (view != null) {
1197 if (gestZ) {
1198 if (z < 0) {
1199 view.zoomOut();
1200 } else {
1201 view.zoomIn();
1202 }
1203 } else {
1204 view.flingScroll(0, Math.round(y * 100));
1205 }
1206 }
1207 mLastGestureTime = now;
1208 }
1209 }
1210 }
1211
1212 public void onAccuracyChanged(int sensor, int accuracy) {
1213 // TODO Auto-generated method stub
1214
1215 }
1216 };
1217
1218 @Override protected void onResume() {
1219 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -07001220 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001221 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
1222 }
1223
1224 if (!mActivityInPause) {
1225 Log.e(LOGTAG, "BrowserActivity is already resumed.");
1226 return;
1227 }
1228
Mike Reed7bfa63b2009-05-28 11:08:32 -04001229 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001230 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001231 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001232
1233 if (mWakeLock.isHeld()) {
1234 mHandler.removeMessages(RELEASE_WAKELOCK);
1235 mWakeLock.release();
1236 }
1237
1238 if (mCredsDlg != null) {
1239 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
1240 // In case credential request never comes back
1241 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
1242 }
1243 }
1244
1245 registerReceiver(mNetworkStateIntentReceiver,
1246 mNetworkStateChangedFilter);
1247 WebView.enablePlatformNotifications();
1248
1249 if (mSettings.doFlick()) {
1250 if (mSensorManager == null) {
1251 mSensorManager = (SensorManager) getSystemService(
1252 Context.SENSOR_SERVICE);
1253 }
1254 mSensorManager.registerListener(mSensorListener,
1255 SensorManager.SENSOR_ACCELEROMETER,
1256 SensorManager.SENSOR_DELAY_FASTEST);
1257 } else {
1258 mSensorManager = null;
1259 }
1260 }
1261
1262 /**
1263 * onSaveInstanceState(Bundle map)
1264 * onSaveInstanceState is called right before onStop(). The map contains
1265 * the saved state.
1266 */
1267 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001268 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001269 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1270 }
1271 // the default implementation requires each view to have an id. As the
1272 // browser handles the state itself and it doesn't use id for the views,
1273 // don't call the default implementation. Otherwise it will trigger the
1274 // warning like this, "couldn't save which view has focus because the
1275 // focused view XXX has no id".
1276
1277 // Save all the tabs
1278 mTabControl.saveState(outState);
1279 }
1280
1281 @Override protected void onPause() {
1282 super.onPause();
1283
1284 if (mActivityInPause) {
1285 Log.e(LOGTAG, "BrowserActivity is already paused.");
1286 return;
1287 }
1288
Mike Reed7bfa63b2009-05-28 11:08:32 -04001289 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001290 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001291 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001292 mWakeLock.acquire();
1293 mHandler.sendMessageDelayed(mHandler
1294 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1295 }
1296
1297 // Clear the credentials toast if it is up
1298 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1299 mCredsDlg.dismiss();
1300 }
1301 mCredsDlg = null;
1302
1303 cancelStopToast();
1304
1305 // unregister network state listener
1306 unregisterReceiver(mNetworkStateIntentReceiver);
1307 WebView.disablePlatformNotifications();
1308
1309 if (mSensorManager != null) {
1310 mSensorManager.unregisterListener(mSensorListener);
1311 }
1312 }
1313
1314 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001315 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001316 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1317 }
1318 super.onDestroy();
1319 // Remove the current tab and sub window
1320 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001321 if (t != null) {
1322 dismissSubWindow(t);
1323 removeTabFromContentView(t);
1324 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001325 // Destroy all the tabs
1326 mTabControl.destroy();
1327 WebIconDatabase.getInstance().close();
1328 if (mGlsConnection != null) {
1329 unbindService(mGlsConnection);
1330 mGlsConnection = null;
1331 }
1332
1333 //
1334 // stop MASF proxy service
1335 //
1336 //Intent proxyServiceIntent = new Intent();
1337 //proxyServiceIntent.setComponent
1338 // (new ComponentName(
1339 // "com.android.masfproxyservice",
1340 // "com.android.masfproxyservice.MasfProxyService"));
1341 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001342
1343 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001344 }
1345
1346 @Override
1347 public void onConfigurationChanged(Configuration newConfig) {
1348 super.onConfigurationChanged(newConfig);
1349
1350 if (mPageInfoDialog != null) {
1351 mPageInfoDialog.dismiss();
1352 showPageInfo(
1353 mPageInfoView,
1354 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1355 }
1356 if (mSSLCertificateDialog != null) {
1357 mSSLCertificateDialog.dismiss();
1358 showSSLCertificate(
1359 mSSLCertificateView);
1360 }
1361 if (mSSLCertificateOnErrorDialog != null) {
1362 mSSLCertificateOnErrorDialog.dismiss();
1363 showSSLCertificateOnError(
1364 mSSLCertificateOnErrorView,
1365 mSSLCertificateOnErrorHandler,
1366 mSSLCertificateOnErrorError);
1367 }
1368 if (mHttpAuthenticationDialog != null) {
1369 String title = ((TextView) mHttpAuthenticationDialog
1370 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1371 .toString();
1372 String name = ((TextView) mHttpAuthenticationDialog
1373 .findViewById(R.id.username_edit)).getText().toString();
1374 String password = ((TextView) mHttpAuthenticationDialog
1375 .findViewById(R.id.password_edit)).getText().toString();
1376 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1377 .getId();
1378 mHttpAuthenticationDialog.dismiss();
1379 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1380 name, password, focusId);
1381 }
1382 if (mFindDialog != null && mFindDialog.isShowing()) {
1383 mFindDialog.onConfigurationChanged(newConfig);
1384 }
1385 }
1386
1387 @Override public void onLowMemory() {
1388 super.onLowMemory();
1389 mTabControl.freeMemory();
1390 }
1391
Mike Reed7bfa63b2009-05-28 11:08:32 -04001392 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001393 if ((!mActivityInPause && !mPageStarted) ||
1394 (mActivityInPause && mPageStarted)) {
1395 CookieSyncManager.getInstance().startSync();
1396 WebView w = mTabControl.getCurrentWebView();
1397 if (w != null) {
1398 w.resumeTimers();
1399 }
1400 return true;
1401 } else {
1402 return false;
1403 }
1404 }
1405
Mike Reed7bfa63b2009-05-28 11:08:32 -04001406 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001407 if (mActivityInPause && !mPageStarted) {
1408 CookieSyncManager.getInstance().stopSync();
1409 WebView w = mTabControl.getCurrentWebView();
1410 if (w != null) {
1411 w.pauseTimers();
1412 }
1413 return true;
1414 } else {
1415 return false;
1416 }
1417 }
1418
1419 /*
1420 * This function is called when we are launching for the first time. We
1421 * are waiting for the login credentials before loading Google home
1422 * pages. This way the user will be logged in straight away.
1423 */
1424 private void waitForCredentials() {
1425 // Show a toast
1426 mCredsDlg = new ProgressDialog(this);
1427 mCredsDlg.setIndeterminate(true);
1428 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1429 // If the user cancels the operation, then cancel the Google
1430 // Credentials request.
1431 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1432 mCredsDlg.show();
1433
1434 // We set a timeout for the retrieval of credentials in onResume()
1435 // as that is when we have freed up some CPU time to get
1436 // the login credentials.
1437 }
1438
1439 /*
1440 * If we have received the credentials or we have timed out and we are
1441 * showing the credentials dialog, then it is time to move on.
1442 */
1443 private void resumeAfterCredentials() {
1444 if (mCredsDlg == null) {
1445 return;
1446 }
1447
1448 // Clear the toast
1449 if (mCredsDlg.isShowing()) {
1450 mCredsDlg.dismiss();
1451 }
1452 mCredsDlg = null;
1453
1454 // Clear any pending timeout
1455 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1456
1457 // Load the page
1458 WebView w = mTabControl.getCurrentWebView();
1459 if (w != null) {
1460 w.loadUrl(mSettings.getHomePage());
1461 }
1462
1463 // Update the settings, need to do this last as it can take a moment
1464 // to persist the settings. In the mean time we could be loading
1465 // content.
1466 mSettings.setLoginInitialized(this);
1467 }
1468
1469 // Open the icon database and retain all the icons for visited sites.
1470 private void retainIconsOnStartup() {
1471 final WebIconDatabase db = WebIconDatabase.getInstance();
1472 db.open(getDir("icons", 0).getPath());
1473 try {
1474 Cursor c = Browser.getAllBookmarks(mResolver);
1475 if (!c.moveToFirst()) {
1476 c.deactivate();
1477 return;
1478 }
1479 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1480 do {
1481 String url = c.getString(urlIndex);
1482 db.retainIconForPageUrl(url);
1483 } while (c.moveToNext());
1484 c.deactivate();
1485 } catch (IllegalStateException e) {
1486 Log.e(LOGTAG, "retainIconsOnStartup", e);
1487 }
1488 }
1489
1490 // Helper method for getting the top window.
1491 WebView getTopWindow() {
1492 return mTabControl.getCurrentTopWebView();
1493 }
1494
1495 @Override
1496 public boolean onCreateOptionsMenu(Menu menu) {
1497 super.onCreateOptionsMenu(menu);
1498
1499 MenuInflater inflater = getMenuInflater();
1500 inflater.inflate(R.menu.browser, menu);
1501 mMenu = menu;
1502 updateInLoadMenuItems();
1503 return true;
1504 }
1505
1506 /**
1507 * As the menu can be open when loading state changes
1508 * we must manually update the state of the stop/reload menu
1509 * item
1510 */
1511 private void updateInLoadMenuItems() {
1512 if (mMenu == null) {
1513 return;
1514 }
1515 MenuItem src = mInLoad ?
1516 mMenu.findItem(R.id.stop_menu_id):
1517 mMenu.findItem(R.id.reload_menu_id);
1518 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1519 dest.setIcon(src.getIcon());
1520 dest.setTitle(src.getTitle());
1521 }
1522
1523 @Override
1524 public boolean onContextItemSelected(MenuItem item) {
1525 // chording is not an issue with context menus, but we use the same
1526 // options selector, so set mCanChord to true so we can access them.
1527 mCanChord = true;
1528 int id = item.getItemId();
1529 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001530 if (null == webView) {
1531 return false;
1532 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001533 final HashMap hrefMap = new HashMap();
1534 hrefMap.put("webview", webView);
1535 final Message msg = mHandler.obtainMessage(
1536 FOCUS_NODE_HREF, id, 0, hrefMap);
1537 switch (id) {
1538 // -- Browser context menu
1539 case R.id.open_context_menu_id:
1540 case R.id.open_newtab_context_menu_id:
1541 case R.id.bookmark_context_menu_id:
1542 case R.id.save_link_context_menu_id:
1543 case R.id.share_link_context_menu_id:
1544 case R.id.copy_link_context_menu_id:
1545 webView.requestFocusNodeHref(msg);
1546 break;
1547
1548 default:
1549 // For other context menus
1550 return onOptionsItemSelected(item);
1551 }
1552 mCanChord = false;
1553 return true;
1554 }
1555
1556 private Bundle createGoogleSearchSourceBundle(String source) {
1557 Bundle bundle = new Bundle();
1558 bundle.putString(SearchManager.SOURCE, source);
1559 return bundle;
1560 }
1561
1562 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001563 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001564 */
1565 @Override
1566 public boolean onSearchRequested() {
1567 startSearch(null, false,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001568 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001569 return true;
1570 }
1571
1572 @Override
1573 public void startSearch(String initialQuery, boolean selectInitialQuery,
1574 Bundle appSearchData, boolean globalSearch) {
1575 if (appSearchData == null) {
1576 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1577 }
1578 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1579 }
1580
1581 @Override
1582 public boolean onOptionsItemSelected(MenuItem item) {
1583 if (!mCanChord) {
1584 // The user has already fired a shortcut with this hold down of the
1585 // menu key.
1586 return false;
1587 }
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001588 if (null == mTabOverview && null == getTopWindow()) {
1589 return false;
1590 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001591 switch (item.getItemId()) {
1592 // -- Main menu
1593 case R.id.goto_menu_id: {
1594 String url = getTopWindow().getUrl();
1595 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1596 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
1597 }
1598 break;
1599
1600 case R.id.bookmarks_menu_id:
1601 bookmarksOrHistoryPicker(false);
1602 break;
1603
1604 case R.id.windows_menu_id:
1605 if (mTabControl.getTabCount() == 1) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001606 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001607 } else {
1608 tabPicker(true, mTabControl.getCurrentIndex(), false);
1609 }
1610 break;
1611
1612 case R.id.stop_reload_menu_id:
1613 if (mInLoad) {
1614 stopLoading();
1615 } else {
1616 getTopWindow().reload();
1617 }
1618 break;
1619
1620 case R.id.back_menu_id:
1621 getTopWindow().goBack();
1622 break;
1623
1624 case R.id.forward_menu_id:
1625 getTopWindow().goForward();
1626 break;
1627
1628 case R.id.close_menu_id:
1629 // Close the subwindow if it exists.
1630 if (mTabControl.getCurrentSubWindow() != null) {
1631 dismissSubWindow(mTabControl.getCurrentTab());
1632 break;
1633 }
1634 final int currentIndex = mTabControl.getCurrentIndex();
1635 final TabControl.Tab parent =
1636 mTabControl.getCurrentTab().getParentTab();
1637 int indexToShow = -1;
1638 if (parent != null) {
1639 indexToShow = mTabControl.getTabIndex(parent);
1640 } else {
1641 // Get the last tab in the list. If it is the current tab,
1642 // subtract 1 more.
1643 indexToShow = mTabControl.getTabCount() - 1;
1644 if (currentIndex == indexToShow) {
1645 indexToShow--;
1646 }
1647 }
1648 switchTabs(currentIndex, indexToShow, true);
1649 break;
1650
1651 case R.id.homepage_menu_id:
1652 TabControl.Tab current = mTabControl.getCurrentTab();
1653 if (current != null) {
1654 dismissSubWindow(current);
1655 current.getWebView().loadUrl(mSettings.getHomePage());
1656 }
1657 break;
1658
1659 case R.id.preferences_menu_id:
1660 Intent intent = new Intent(this,
1661 BrowserPreferencesPage.class);
1662 startActivityForResult(intent, PREFERENCES_PAGE);
1663 break;
1664
1665 case R.id.find_menu_id:
1666 if (null == mFindDialog) {
1667 mFindDialog = new FindDialog(this);
1668 }
1669 mFindDialog.setWebView(getTopWindow());
1670 mFindDialog.show();
1671 mMenuState = EMPTY_MENU;
1672 break;
1673
1674 case R.id.select_text_id:
1675 getTopWindow().emulateShiftHeld();
1676 break;
1677 case R.id.page_info_menu_id:
1678 showPageInfo(mTabControl.getCurrentTab(), false);
1679 break;
1680
1681 case R.id.classic_history_menu_id:
1682 bookmarksOrHistoryPicker(true);
1683 break;
1684
1685 case R.id.share_page_menu_id:
1686 Browser.sendString(this, getTopWindow().getUrl());
1687 break;
1688
1689 case R.id.dump_nav_menu_id:
1690 getTopWindow().debugDump();
1691 break;
1692
1693 case R.id.zoom_in_menu_id:
1694 getTopWindow().zoomIn();
1695 break;
1696
1697 case R.id.zoom_out_menu_id:
1698 getTopWindow().zoomOut();
1699 break;
1700
1701 case R.id.view_downloads_menu_id:
1702 viewDownloads(null);
1703 break;
1704
1705 // -- Tab menu
1706 case R.id.view_tab_menu_id:
1707 if (mTabListener != null && mTabOverview != null) {
1708 int pos = mTabOverview.getContextMenuPosition(item);
1709 mTabOverview.setCurrentIndex(pos);
1710 mTabListener.onClick(pos);
1711 }
1712 break;
1713
1714 case R.id.remove_tab_menu_id:
1715 if (mTabListener != null && mTabOverview != null) {
1716 int pos = mTabOverview.getContextMenuPosition(item);
1717 mTabListener.remove(pos);
1718 }
1719 break;
1720
1721 case R.id.new_tab_menu_id:
1722 // No need to check for mTabOverview here since we are not
1723 // dependent on it for a position.
1724 if (mTabListener != null) {
1725 // If the overview happens to be non-null, make the "New
1726 // Tab" cell visible.
1727 if (mTabOverview != null) {
1728 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1729 }
1730 mTabListener.onClick(ImageGrid.NEW_TAB);
1731 }
1732 break;
1733
1734 case R.id.bookmark_tab_menu_id:
1735 if (mTabListener != null && mTabOverview != null) {
1736 int pos = mTabOverview.getContextMenuPosition(item);
1737 TabControl.Tab t = mTabControl.getTab(pos);
1738 // Since we called populatePickerData for all of the
1739 // tabs, getTitle and getUrl will return appropriate
1740 // values.
1741 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1742 t.getUrl());
1743 }
1744 break;
1745
1746 case R.id.history_tab_menu_id:
1747 bookmarksOrHistoryPicker(true);
1748 break;
1749
1750 case R.id.bookmarks_tab_menu_id:
1751 bookmarksOrHistoryPicker(false);
1752 break;
1753
1754 case R.id.properties_tab_menu_id:
1755 if (mTabListener != null && mTabOverview != null) {
1756 int pos = mTabOverview.getContextMenuPosition(item);
1757 showPageInfo(mTabControl.getTab(pos), false);
1758 }
1759 break;
1760
1761 case R.id.window_one_menu_id:
1762 case R.id.window_two_menu_id:
1763 case R.id.window_three_menu_id:
1764 case R.id.window_four_menu_id:
1765 case R.id.window_five_menu_id:
1766 case R.id.window_six_menu_id:
1767 case R.id.window_seven_menu_id:
1768 case R.id.window_eight_menu_id:
1769 {
1770 int menuid = item.getItemId();
1771 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1772 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1773 TabControl.Tab desiredTab = mTabControl.getTab(id);
1774 if (desiredTab != null &&
1775 desiredTab != mTabControl.getCurrentTab()) {
1776 switchTabs(mTabControl.getCurrentIndex(), id, false);
1777 }
1778 break;
1779 }
1780 }
1781 }
1782 break;
1783
1784 default:
1785 if (!super.onOptionsItemSelected(item)) {
1786 return false;
1787 }
1788 // Otherwise fall through.
1789 }
1790 mCanChord = false;
1791 return true;
1792 }
1793
1794 public void closeFind() {
1795 mMenuState = R.id.MAIN_MENU;
1796 }
1797
1798 @Override public boolean onPrepareOptionsMenu(Menu menu)
1799 {
1800 // This happens when the user begins to hold down the menu key, so
1801 // allow them to chord to get a shortcut.
1802 mCanChord = true;
1803 // Note: setVisible will decide whether an item is visible; while
1804 // setEnabled() will decide whether an item is enabled, which also means
1805 // whether the matching shortcut key will function.
1806 super.onPrepareOptionsMenu(menu);
1807 switch (mMenuState) {
1808 case R.id.TAB_MENU:
1809 if (mCurrentMenuState != mMenuState) {
1810 menu.setGroupVisible(R.id.MAIN_MENU, false);
1811 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1812 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1813 menu.setGroupVisible(R.id.TAB_MENU, true);
1814 menu.setGroupEnabled(R.id.TAB_MENU, true);
1815 }
1816 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1817 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1818 tab.setVisible(newT);
1819 tab.setEnabled(newT);
1820 break;
1821 case EMPTY_MENU:
1822 if (mCurrentMenuState != mMenuState) {
1823 menu.setGroupVisible(R.id.MAIN_MENU, false);
1824 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1825 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1826 menu.setGroupVisible(R.id.TAB_MENU, false);
1827 menu.setGroupEnabled(R.id.TAB_MENU, false);
1828 }
1829 break;
1830 default:
1831 if (mCurrentMenuState != mMenuState) {
1832 menu.setGroupVisible(R.id.MAIN_MENU, true);
1833 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1834 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1835 menu.setGroupVisible(R.id.TAB_MENU, false);
1836 menu.setGroupEnabled(R.id.TAB_MENU, false);
1837 }
1838 final WebView w = getTopWindow();
1839 boolean canGoBack = false;
1840 boolean canGoForward = false;
1841 boolean isHome = false;
1842 if (w != null) {
1843 canGoBack = w.canGoBack();
1844 canGoForward = w.canGoForward();
1845 isHome = mSettings.getHomePage().equals(w.getUrl());
1846 }
1847 final MenuItem back = menu.findItem(R.id.back_menu_id);
1848 back.setEnabled(canGoBack);
1849
1850 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1851 home.setEnabled(!isHome);
1852
1853 menu.findItem(R.id.forward_menu_id)
1854 .setEnabled(canGoForward);
1855
1856 // decide whether to show the share link option
1857 PackageManager pm = getPackageManager();
1858 Intent send = new Intent(Intent.ACTION_SEND);
1859 send.setType("text/plain");
1860 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1861 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1862
1863 // If there is only 1 window, the text will be "New window"
1864 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1865 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1866 getString(R.string.view_tabs_condensed) :
1867 getString(R.string.tab_picker_new_tab));
1868
1869 boolean isNavDump = mSettings.isNavDump();
1870 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1871 nav.setVisible(isNavDump);
1872 nav.setEnabled(isNavDump);
1873 break;
1874 }
1875 mCurrentMenuState = mMenuState;
1876 return true;
1877 }
1878
1879 @Override
1880 public void onCreateContextMenu(ContextMenu menu, View v,
1881 ContextMenuInfo menuInfo) {
1882 WebView webview = (WebView) v;
1883 WebView.HitTestResult result = webview.getHitTestResult();
1884 if (result == null) {
1885 return;
1886 }
1887
1888 int type = result.getType();
1889 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1890 Log.w(LOGTAG,
1891 "We should not show context menu when nothing is touched");
1892 return;
1893 }
1894 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1895 // let TextView handles context menu
1896 return;
1897 }
1898
1899 // Note, http://b/issue?id=1106666 is requesting that
1900 // an inflated menu can be used again. This is not available
1901 // yet, so inflate each time (yuk!)
1902 MenuInflater inflater = getMenuInflater();
1903 inflater.inflate(R.menu.browsercontext, menu);
1904
1905 // Show the correct menu group
1906 String extra = result.getExtra();
1907 menu.setGroupVisible(R.id.PHONE_MENU,
1908 type == WebView.HitTestResult.PHONE_TYPE);
1909 menu.setGroupVisible(R.id.EMAIL_MENU,
1910 type == WebView.HitTestResult.EMAIL_TYPE);
1911 menu.setGroupVisible(R.id.GEO_MENU,
1912 type == WebView.HitTestResult.GEO_TYPE);
1913 menu.setGroupVisible(R.id.IMAGE_MENU,
1914 type == WebView.HitTestResult.IMAGE_TYPE
1915 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1916 menu.setGroupVisible(R.id.ANCHOR_MENU,
1917 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1918 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1919
1920 // Setup custom handling depending on the type
1921 switch (type) {
1922 case WebView.HitTestResult.PHONE_TYPE:
1923 menu.setHeaderTitle(Uri.decode(extra));
1924 menu.findItem(R.id.dial_context_menu_id).setIntent(
1925 new Intent(Intent.ACTION_VIEW, Uri
1926 .parse(WebView.SCHEME_TEL + extra)));
1927 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1928 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1929 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1930 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1931 addIntent);
1932 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1933 new Copy(extra));
1934 break;
1935
1936 case WebView.HitTestResult.EMAIL_TYPE:
1937 menu.setHeaderTitle(extra);
1938 menu.findItem(R.id.email_context_menu_id).setIntent(
1939 new Intent(Intent.ACTION_VIEW, Uri
1940 .parse(WebView.SCHEME_MAILTO + extra)));
1941 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1942 new Copy(extra));
1943 break;
1944
1945 case WebView.HitTestResult.GEO_TYPE:
1946 menu.setHeaderTitle(extra);
1947 menu.findItem(R.id.map_context_menu_id).setIntent(
1948 new Intent(Intent.ACTION_VIEW, Uri
1949 .parse(WebView.SCHEME_GEO
1950 + URLEncoder.encode(extra))));
1951 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1952 new Copy(extra));
1953 break;
1954
1955 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1956 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1957 TextView titleView = (TextView) LayoutInflater.from(this)
1958 .inflate(android.R.layout.browser_link_context_header,
1959 null);
1960 titleView.setText(extra);
1961 menu.setHeaderView(titleView);
1962 // decide whether to show the open link in new tab option
1963 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1964 mTabControl.getTabCount() < TabControl.MAX_TABS);
1965 PackageManager pm = getPackageManager();
1966 Intent send = new Intent(Intent.ACTION_SEND);
1967 send.setType("text/plain");
1968 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1969 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1970 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1971 break;
1972 }
1973 // otherwise fall through to handle image part
1974 case WebView.HitTestResult.IMAGE_TYPE:
1975 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1976 menu.setHeaderTitle(extra);
1977 }
1978 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1979 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1980 menu.findItem(R.id.download_context_menu_id).
1981 setOnMenuItemClickListener(new Download(extra));
1982 break;
1983
1984 default:
1985 Log.w(LOGTAG, "We should not get here.");
1986 break;
1987 }
1988 }
1989
The Android Open Source Project0c908882009-03-03 19:32:16 -08001990 // Attach the given tab to the content view.
1991 private void attachTabToContentView(TabControl.Tab t) {
1992 final WebView main = t.getWebView();
1993 // Attach the main WebView.
1994 mContentView.addView(main, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001995 // Attach the sub window if necessary
1996 attachSubWindow(t);
1997 // Request focus on the top window.
1998 t.getTopWindow().requestFocus();
1999 }
2000
2001 // Attach a sub window to the main WebView of the given tab.
2002 private void attachSubWindow(TabControl.Tab t) {
2003 // If a sub window exists, attach it to the content view.
2004 final WebView subView = t.getSubWebView();
2005 if (subView != null) {
2006 final View container = t.getSubWebViewContainer();
2007 mContentView.addView(container, COVER_SCREEN_PARAMS);
2008 subView.requestFocus();
2009 }
2010 }
2011
2012 // Remove the given tab from the content view.
2013 private void removeTabFromContentView(TabControl.Tab t) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07002014 // Remove the main WebView.
The Android Open Source Project0c908882009-03-03 19:32:16 -08002015 mContentView.removeView(t.getWebView());
2016 // Remove the sub window if it exists.
2017 if (t.getSubWebView() != null) {
2018 mContentView.removeView(t.getSubWebViewContainer());
2019 }
2020 }
2021
2022 // Remove the sub window if it exists. Also called by TabControl when the
2023 // user clicks the 'X' to dismiss a sub window.
2024 /* package */ void dismissSubWindow(TabControl.Tab t) {
2025 final WebView mainView = t.getWebView();
2026 if (t.getSubWebView() != null) {
2027 // Remove the container view and request focus on the main WebView.
2028 mContentView.removeView(t.getSubWebViewContainer());
2029 mainView.requestFocus();
2030 // Tell the TabControl to dismiss the subwindow. This will destroy
2031 // the WebView.
2032 mTabControl.dismissSubWindow(t);
2033 }
2034 }
2035
2036 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
2037 private void sendAnimateFromOverview(final TabControl.Tab tab,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002038 final boolean newTab, final UrlData urlData, final int delay,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002039 final Message msg) {
2040 // Set the current tab.
2041 mTabControl.setCurrentTab(tab);
2042 // Attach the WebView so it will layout.
2043 attachTabToContentView(tab);
2044 // Set the view to invisibile for now.
2045 tab.getWebView().setVisibility(View.INVISIBLE);
2046 // If there is a sub window, make it invisible too.
2047 if (tab.getSubWebView() != null) {
2048 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
2049 }
2050 // Create our fake animating view.
2051 final AnimatingView view = new AnimatingView(this, tab);
2052 // Attach it to the view system and make in invisible so it will
2053 // layout but not flash white on the screen.
2054 mContentView.addView(view, COVER_SCREEN_PARAMS);
2055 view.setVisibility(View.INVISIBLE);
2056 // Send the animate message.
2057 final HashMap map = new HashMap();
2058 map.put("view", view);
2059 // Load the url after the AnimatingView has captured the picture. This
2060 // prevents any bad layout or bad scale from being used during
2061 // animation.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002062 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002063 dismissSubWindow(tab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002064 urlData.loadIn(tab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002065 }
2066 map.put("msg", msg);
2067 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2068 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
2069 // Increment the count to indicate that we are in an animation.
2070 mAnimationCount++;
2071 // Remove the listener so we don't get any more tab changes.
2072 mTabOverview.setListener(null);
2073 mTabListener = null;
2074 // Make the menu empty until the animation completes.
2075 mMenuState = EMPTY_MENU;
2076
2077 }
2078
2079 // 500ms animation with 800ms delay
Patrick Scott95d601f2009-06-11 10:06:46 -04002080 private static final int TAB_ANIMATION_DURATION = 200;
2081 private static final int TAB_OVERVIEW_DELAY = 500;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002082
2083 // Called by TabControl when a tab is requesting focus
2084 /* package */ void showTab(TabControl.Tab t) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002085 showTab(t, EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002086 }
2087
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002088 private void showTab(TabControl.Tab t, UrlData urlData) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002089 // Disallow focus change during a tab animation.
2090 if (mAnimationCount > 0) {
2091 return;
2092 }
2093 int delay = 0;
2094 if (mTabOverview == null) {
2095 // Add a delay so the tab overview can be shown before the second
2096 // animation begins.
2097 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2098 tabPicker(false, mTabControl.getTabIndex(t), false);
2099 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002100 sendAnimateFromOverview(t, false, urlData, delay, null);
2101 }
2102
2103 // A wrapper function of {@link #openTabAndShow(UrlData, Message, boolean, String)}
2104 // that accepts url as string.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002105 private TabControl.Tab openTabAndShow(String url, final Message msg,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002106 boolean closeOnExit, String appId) {
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002107 return openTabAndShow(new UrlData(url), msg, closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 }
2109
2110 // This method does a ton of stuff. It will attempt to create a new tab
2111 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2112 // url isn't null, it will load the given url. If the tab overview is not
2113 // showing, it will animate to the tab overview, create a new tab and
2114 // animate away from it. After the animation completes, it will dispatch
2115 // the given Message. If the tab overview is already showing (i.e. this
2116 // method is called from TabListener.onClick(), the method will animate
2117 // away from the tab overview.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002118 private TabControl.Tab openTabAndShow(UrlData urlData, final Message msg,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002119 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002120 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
2121 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
2122 if (newTab) {
2123 int delay = 0;
2124 // If the tab overview is up and there are animations, just load
2125 // the url.
2126 if (mTabOverview != null && mAnimationCount > 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002127 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002128 // We should not have a msg here since onCreateWindow
2129 // checks the animation count and every other caller passes
2130 // null.
2131 assert msg == null;
2132 // just dismiss the subwindow and load the given url.
2133 dismissSubWindow(currentTab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002134 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002135 }
2136 } else {
2137 // show mTabOverview if it is not there.
2138 if (mTabOverview == null) {
2139 // We have to delay the animation from the tab picker by the
2140 // length of the tab animation. Add a delay so the tab
2141 // overview can be shown before the second animation begins.
2142 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2143 tabPicker(false, ImageGrid.NEW_TAB, false);
2144 }
2145 // Animate from the Tab overview after any animations have
2146 // finished.
Grace Klobac9181842009-04-14 08:53:22 -07002147 final TabControl.Tab tab = mTabControl.createNewTab(
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002148 closeOnExit, appId, urlData.mUrl);
Grace Klobaec7eb372009-06-16 13:45:56 -07002149 sendAnimateFromOverview(tab, true, urlData, delay, msg);
Grace Klobac9181842009-04-14 08:53:22 -07002150 return tab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002152 } else if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002153 // We should not have a msg here.
2154 assert msg == null;
2155 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002156 sendAnimateFromOverview(currentTab, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002157 TAB_OVERVIEW_DELAY, null);
2158 } else {
2159 // Get rid of the subwindow if it exists
2160 dismissSubWindow(currentTab);
2161 // Load the given url.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002162 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002163 }
2164 }
Grace Klobac9181842009-04-14 08:53:22 -07002165 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002166 }
2167
2168 private Animation createTabAnimation(final AnimatingView view,
2169 final View cell, boolean scaleDown) {
2170 final AnimationSet set = new AnimationSet(true);
2171 final float scaleX = (float) cell.getWidth() / view.getWidth();
2172 final float scaleY = (float) cell.getHeight() / view.getHeight();
2173 if (scaleDown) {
2174 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2175 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2176 cell.getTop()));
2177 } else {
2178 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2179 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2180 cell.getTop(), 0));
2181 }
2182 set.setDuration(TAB_ANIMATION_DURATION);
2183 set.setInterpolator(new DecelerateInterpolator());
2184 return set;
2185 }
2186
2187 // Animate to the tab overview. currentIndex tells us which position to
2188 // animate to and newIndex is the position that should be selected after
2189 // the animation completes.
2190 // If remove is true, after the animation stops, a confirmation dialog will
2191 // be displayed to the user.
2192 private void animateToTabOverview(final int newIndex, final boolean remove,
2193 final AnimatingView view) {
2194 // Find the view in the ImageGrid allowing for the "New Tab" cell.
2195 int position = mTabControl.getTabIndex(view.mTab);
2196 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2197 position++;
2198 }
2199
2200 // Offset the tab position with the first visible position to get a
2201 // number between 0 and 3.
2202 position -= mTabOverview.getFirstVisiblePosition();
2203
2204 // Grab the view that we are going to animate to.
2205 final View v = mTabOverview.getChildAt(position);
2206
2207 final Animation.AnimationListener l =
2208 new Animation.AnimationListener() {
2209 public void onAnimationStart(Animation a) {
Patrick Scottd068f802009-06-22 11:46:06 -04002210 if (mTabOverview != null) {
2211 mTabOverview.requestFocus();
2212 // Clear the listener so we don't trigger a tab
2213 // selection.
2214 mTabOverview.setListener(null);
2215 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002216 }
2217 public void onAnimationRepeat(Animation a) {}
2218 public void onAnimationEnd(Animation a) {
2219 // We are no longer animating so decrement the count.
2220 mAnimationCount--;
2221 // Make the view GONE so that it will not draw between
2222 // now and when the Runnable is handled.
2223 view.setVisibility(View.GONE);
2224 // Post a runnable since we can't modify the view
2225 // hierarchy during this callback.
2226 mHandler.post(new Runnable() {
2227 public void run() {
2228 // Remove the AnimatingView.
2229 mContentView.removeView(view);
2230 if (mTabOverview != null) {
2231 // Make newIndex visible.
2232 mTabOverview.setCurrentIndex(newIndex);
2233 // Restore the listener.
2234 mTabOverview.setListener(mTabListener);
2235 // Change the menu to TAB_MENU if the
2236 // ImageGrid is interactive.
2237 if (mTabOverview.isLive()) {
2238 mMenuState = R.id.TAB_MENU;
2239 mTabOverview.requestFocus();
2240 }
2241 }
2242 // If a remove was requested, remove the tab.
2243 if (remove) {
2244 // During a remove, the current tab has
2245 // already changed. Remember the current one
2246 // here.
2247 final TabControl.Tab currentTab =
2248 mTabControl.getCurrentTab();
2249 // Remove the tab at newIndex from
2250 // TabControl and the tab overview.
2251 final TabControl.Tab tab =
2252 mTabControl.getTab(newIndex);
2253 mTabControl.removeTab(tab);
2254 // Restore the current tab.
2255 if (currentTab != tab) {
2256 mTabControl.setCurrentTab(currentTab);
2257 }
2258 if (mTabOverview != null) {
2259 mTabOverview.remove(newIndex);
2260 // Make the current tab visible.
2261 mTabOverview.setCurrentIndex(
2262 mTabControl.getCurrentIndex());
2263 }
2264 }
2265 }
2266 });
2267 }
2268 };
2269
2270 // Do an animation if there is a view to animate to.
2271 if (v != null) {
2272 // Create our animation
2273 final Animation anim = createTabAnimation(view, v, true);
2274 anim.setAnimationListener(l);
2275 // Start animating
2276 view.startAnimation(anim);
2277 } else {
2278 // If something goes wrong and we didn't find a view to animate to,
2279 // just do everything here.
2280 l.onAnimationStart(null);
2281 l.onAnimationEnd(null);
2282 }
2283 }
2284
2285 // Animate from the tab picker. The index supplied is the index to animate
2286 // from.
2287 private void animateFromTabOverview(final AnimatingView view,
2288 final boolean newTab, final Message msg) {
2289 // firstVisible is the first visible tab on the screen. This helps
2290 // to know which corner of the screen the selected tab is.
2291 int firstVisible = mTabOverview.getFirstVisiblePosition();
2292 // tabPosition is the 0-based index of of the tab being opened
2293 int tabPosition = mTabControl.getTabIndex(view.mTab);
2294 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2295 // Add one to make room for the "New Tab" cell.
2296 tabPosition++;
2297 }
2298 // If this is a new tab, animate from the "New Tab" cell.
2299 if (newTab) {
2300 tabPosition = 0;
2301 }
2302 // Location corresponds to the four corners of the screen.
2303 // A new tab or 0 is upper left, 0 for an old tab is upper
2304 // right, 1 is lower left, and 2 is lower right
2305 int location = tabPosition - firstVisible;
2306
2307 // Find the view at this location.
2308 final View v = mTabOverview.getChildAt(location);
2309
2310 // Wait until the animation completes to replace the AnimatingView.
2311 final Animation.AnimationListener l =
2312 new Animation.AnimationListener() {
2313 public void onAnimationStart(Animation a) {}
2314 public void onAnimationRepeat(Animation a) {}
2315 public void onAnimationEnd(Animation a) {
2316 mHandler.post(new Runnable() {
2317 public void run() {
2318 mContentView.removeView(view);
2319 // Dismiss the tab overview. If the cell at the
2320 // given location is null, set the fade
2321 // parameter to true.
2322 dismissTabOverview(v == null);
2323 TabControl.Tab t =
2324 mTabControl.getCurrentTab();
2325 mMenuState = R.id.MAIN_MENU;
2326 // Resume regular updates.
2327 t.getWebView().resumeTimers();
2328 // Dispatch the message after the animation
2329 // completes.
2330 if (msg != null) {
2331 msg.sendToTarget();
2332 }
2333 // The animation is done and the tab overview is
2334 // gone so allow key events and other animations
2335 // to begin.
2336 mAnimationCount--;
2337 // Reset all the title bar info.
2338 resetTitle();
2339 }
2340 });
2341 }
2342 };
2343
2344 if (v != null) {
2345 final Animation anim = createTabAnimation(view, v, false);
2346 // Set the listener and start animating
2347 anim.setAnimationListener(l);
2348 view.startAnimation(anim);
2349 // Make the view VISIBLE during the animation.
2350 view.setVisibility(View.VISIBLE);
2351 } else {
2352 // Go ahead and do all the cleanup.
2353 l.onAnimationEnd(null);
2354 }
2355 }
2356
2357 // Dismiss the tab overview applying a fade if needed.
2358 private void dismissTabOverview(final boolean fade) {
2359 if (fade) {
2360 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2361 anim.setDuration(500);
2362 anim.startNow();
2363 mTabOverview.startAnimation(anim);
2364 }
2365 // Just in case there was a problem with animating away from the tab
2366 // overview
2367 WebView current = mTabControl.getCurrentWebView();
2368 if (current != null) {
2369 current.setVisibility(View.VISIBLE);
2370 } else {
2371 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2372 }
2373 // Make the sub window container visible.
2374 if (mTabControl.getCurrentSubWindow() != null) {
2375 mTabControl.getCurrentTab().getSubWebViewContainer()
2376 .setVisibility(View.VISIBLE);
2377 }
2378 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002379 // Clear all the data for tab picker so next time it will be
2380 // recreated.
2381 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002382 mTabOverview.clear();
2383 mTabOverview = null;
2384 mTabListener = null;
2385 }
2386
Grace Klobac9181842009-04-14 08:53:22 -07002387 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002388 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002389 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002390 if (t != null) {
2391 t.getWebView().loadUrl(url);
2392 }
Grace Klobac9181842009-04-14 08:53:22 -07002393 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002394 } else {
Grace Klobac9181842009-04-14 08:53:22 -07002395 return openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002396 }
2397 }
2398
2399 private class Copy implements OnMenuItemClickListener {
2400 private CharSequence mText;
2401
2402 public boolean onMenuItemClick(MenuItem item) {
2403 copy(mText);
2404 return true;
2405 }
2406
2407 public Copy(CharSequence toCopy) {
2408 mText = toCopy;
2409 }
2410 }
2411
2412 private class Download implements OnMenuItemClickListener {
2413 private String mText;
2414
2415 public boolean onMenuItemClick(MenuItem item) {
2416 onDownloadStartNoStream(mText, null, null, null, -1);
2417 return true;
2418 }
2419
2420 public Download(String toDownload) {
2421 mText = toDownload;
2422 }
2423 }
2424
2425 private void copy(CharSequence text) {
2426 try {
2427 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2428 if (clip != null) {
2429 clip.setClipboardText(text);
2430 }
2431 } catch (android.os.RemoteException e) {
2432 Log.e(LOGTAG, "Copy failed", e);
2433 }
2434 }
2435
2436 /**
2437 * Resets the browser title-view to whatever it must be (for example, if we
2438 * load a page from history).
2439 */
2440 private void resetTitle() {
2441 resetLockIcon();
2442 resetTitleIconAndProgress();
2443 }
2444
2445 /**
2446 * Resets the browser title-view to whatever it must be
2447 * (for example, if we had a loading error)
2448 * When we have a new page, we call resetTitle, when we
2449 * have to reset the titlebar to whatever it used to be
2450 * (for example, if the user chose to stop loading), we
2451 * call resetTitleAndRevertLockIcon.
2452 */
2453 /* package */ void resetTitleAndRevertLockIcon() {
2454 revertLockIcon();
2455 resetTitleIconAndProgress();
2456 }
2457
2458 /**
2459 * Reset the title, favicon, and progress.
2460 */
2461 private void resetTitleIconAndProgress() {
2462 WebView current = mTabControl.getCurrentWebView();
2463 if (current == null) {
2464 return;
2465 }
2466 resetTitleAndIcon(current);
2467 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002468 mWebChromeClient.onProgressChanged(current, progress);
2469 }
2470
2471 // Reset the title and the icon based on the given item.
2472 private void resetTitleAndIcon(WebView view) {
2473 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2474 if (item != null) {
2475 setUrlTitle(item.getUrl(), item.getTitle());
2476 setFavicon(item.getFavicon());
2477 } else {
2478 setUrlTitle(null, null);
2479 setFavicon(null);
2480 }
2481 }
2482
2483 /**
2484 * Sets a title composed of the URL and the title string.
2485 * @param url The URL of the site being loaded.
2486 * @param title The title of the site being loaded.
2487 */
2488 private void setUrlTitle(String url, String title) {
2489 mUrl = url;
2490 mTitle = title;
2491
2492 // While the tab overview is animating or being shown, block changes
2493 // to the title.
2494 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04002495 if (CUSTOM_BROWSER_BAR) {
2496 mTitleBar.setTitleAndUrl(title, url);
2497 } else {
2498 setTitle(buildUrlTitle(url, title));
2499 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002500 }
2501 }
2502
2503 /**
2504 * Builds and returns the page title, which is some
2505 * combination of the page URL and title.
2506 * @param url The URL of the site being loaded.
2507 * @param title The title of the site being loaded.
2508 * @return The page title.
2509 */
2510 private String buildUrlTitle(String url, String title) {
2511 String urlTitle = "";
2512
2513 if (url != null) {
2514 String titleUrl = buildTitleUrl(url);
2515
2516 if (title != null && 0 < title.length()) {
2517 if (titleUrl != null && 0 < titleUrl.length()) {
2518 urlTitle = titleUrl + ": " + title;
2519 } else {
2520 urlTitle = title;
2521 }
2522 } else {
2523 if (titleUrl != null) {
2524 urlTitle = titleUrl;
2525 }
2526 }
2527 }
2528
2529 return urlTitle;
2530 }
2531
2532 /**
2533 * @param url The URL to build a title version of the URL from.
2534 * @return The title version of the URL or null if fails.
2535 * The title version of the URL can be either the URL hostname,
2536 * or the hostname with an "https://" prefix (for secure URLs),
2537 * or an empty string if, for example, the URL in question is a
2538 * file:// URL with no hostname.
2539 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002540 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002541 String titleUrl = null;
2542
2543 if (url != null) {
2544 try {
2545 // parse the url string
2546 URL urlObj = new URL(url);
2547 if (urlObj != null) {
2548 titleUrl = "";
2549
2550 String protocol = urlObj.getProtocol();
2551 String host = urlObj.getHost();
2552
2553 if (host != null && 0 < host.length()) {
2554 titleUrl = host;
2555 if (protocol != null) {
2556 // if a secure site, add an "https://" prefix!
2557 if (protocol.equalsIgnoreCase("https")) {
2558 titleUrl = protocol + "://" + host;
2559 }
2560 }
2561 }
2562 }
2563 } catch (MalformedURLException e) {}
2564 }
2565
2566 return titleUrl;
2567 }
2568
2569 // Set the favicon in the title bar.
2570 private void setFavicon(Bitmap icon) {
2571 // While the tab overview is animating or being shown, block changes to
2572 // the favicon.
2573 if (mAnimationCount > 0 || mTabOverview != null) {
2574 return;
2575 }
Leon Scroggins81db3662009-06-04 17:45:11 -04002576 if (CUSTOM_BROWSER_BAR) {
2577 Drawable[] array = new Drawable[3];
2578 array[0] = new PaintDrawable(Color.BLACK);
2579 PaintDrawable p = new PaintDrawable(Color.WHITE);
2580 array[1] = p;
2581 if (icon == null) {
2582 array[2] = mGenericFavicon;
2583 } else {
2584 array[2] = new BitmapDrawable(icon);
2585 }
2586 LayerDrawable d = new LayerDrawable(array);
2587 d.setLayerInset(1, 1, 1, 1, 1);
2588 d.setLayerInset(2, 2, 2, 2, 2);
2589 mTitleBar.setFavicon(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002590 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04002591 Drawable[] array = new Drawable[2];
2592 PaintDrawable p = new PaintDrawable(Color.WHITE);
2593 p.setCornerRadius(3f);
2594 array[0] = p;
2595 if (icon == null) {
2596 array[1] = mGenericFavicon;
2597 } else {
2598 array[1] = new BitmapDrawable(icon);
2599 }
2600 LayerDrawable d = new LayerDrawable(array);
2601 d.setLayerInset(1, 2, 2, 2, 2);
2602 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002603 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002604 }
2605
2606 /**
2607 * Saves the current lock-icon state before resetting
2608 * the lock icon. If we have an error, we may need to
2609 * roll back to the previous state.
2610 */
2611 private void saveLockIcon() {
2612 mPrevLockType = mLockIconType;
2613 }
2614
2615 /**
2616 * Reverts the lock-icon state to the last saved state,
2617 * for example, if we had an error, and need to cancel
2618 * the load.
2619 */
2620 private void revertLockIcon() {
2621 mLockIconType = mPrevLockType;
2622
Dave Bort31a6d1c2009-04-13 15:56:49 -07002623 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002624 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2625 " revert lock icon to " + mLockIconType);
2626 }
2627
2628 updateLockIconImage(mLockIconType);
2629 }
2630
2631 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2632 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2633 // Animate to the tab picker, remove the current tab, then
2634 // animate away from the tab picker to the parent WebView.
2635 tabPicker(false, indexFrom, remove);
2636 // Change to the parent tab
2637 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2638 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002639 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002640 } else {
2641 // Increment this here so that no other animations can happen in
2642 // between the end of the tab picker transition and the beginning
2643 // of openTabAndShow. This has a matching decrement in the handler
2644 // of OPEN_TAB_AND_SHOW.
2645 mAnimationCount++;
2646 // Send a message to open a new tab.
2647 mHandler.sendMessageDelayed(
2648 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2649 mSettings.getHomePage()), delay);
2650 }
2651 }
2652
2653 private void goBackOnePageOrQuit() {
2654 TabControl.Tab current = mTabControl.getCurrentTab();
2655 if (current == null) {
2656 /*
2657 * Instead of finishing the activity, simply push this to the back
2658 * of the stack and let ActivityManager to choose the foreground
2659 * activity. As BrowserActivity is singleTask, it will be always the
2660 * root of the task. So we can use either true or false for
2661 * moveTaskToBack().
2662 */
2663 moveTaskToBack(true);
2664 }
2665 WebView w = current.getWebView();
2666 if (w.canGoBack()) {
2667 w.goBack();
2668 } else {
2669 // Check to see if we are closing a window that was created by
2670 // another window. If so, we switch back to that window.
2671 TabControl.Tab parent = current.getParentTab();
2672 if (parent != null) {
2673 switchTabs(mTabControl.getCurrentIndex(),
2674 mTabControl.getTabIndex(parent), true);
2675 } else {
2676 if (current.closeOnExit()) {
2677 if (mTabControl.getTabCount() == 1) {
2678 finish();
2679 return;
2680 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002681 // call pauseWebViewTimers() now, we won't be able to call
2682 // it in onPause() as the WebView won't be valid.
2683 pauseWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002684 removeTabFromContentView(current);
2685 mTabControl.removeTab(current);
2686 }
2687 /*
2688 * Instead of finishing the activity, simply push this to the back
2689 * of the stack and let ActivityManager to choose the foreground
2690 * activity. As BrowserActivity is singleTask, it will be always the
2691 * root of the task. So we can use either true or false for
2692 * moveTaskToBack().
2693 */
2694 moveTaskToBack(true);
2695 }
2696 }
2697 }
2698
2699 public KeyTracker.State onKeyTracker(int keyCode,
2700 KeyEvent event,
2701 KeyTracker.Stage stage,
2702 int duration) {
2703 // if onKeyTracker() is called after activity onStop()
2704 // because of accumulated key events,
2705 // we should ignore it as browser is not active any more.
2706 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002707 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002708 return KeyTracker.State.NOT_TRACKING;
2709
2710 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002711 // Check if a custom view is currently showing and, if it is, hide it.
2712 if (mCustomView != null) {
2713 mWebChromeClient.onHideCustomView();
2714 return KeyTracker.State.DONE_TRACKING;
2715 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002716 // During animations, block the back key so that other animations
2717 // are not triggered and so that we don't end up destroying all the
2718 // WebViews before finishing the animation.
2719 if (mAnimationCount > 0) {
2720 return KeyTracker.State.DONE_TRACKING;
2721 }
2722 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2723 bookmarksOrHistoryPicker(true);
2724 return KeyTracker.State.DONE_TRACKING;
2725 } else if (stage == KeyTracker.Stage.UP) {
2726 // FIXME: Currently, we do not have a notion of the
2727 // history picker for the subwindow, but maybe we
2728 // should?
2729 WebView subwindow = mTabControl.getCurrentSubWindow();
2730 if (subwindow != null) {
2731 if (subwindow.canGoBack()) {
2732 subwindow.goBack();
2733 } else {
2734 dismissSubWindow(mTabControl.getCurrentTab());
2735 }
2736 } else {
2737 goBackOnePageOrQuit();
2738 }
2739 return KeyTracker.State.DONE_TRACKING;
2740 }
2741 return KeyTracker.State.KEEP_TRACKING;
2742 }
2743 return KeyTracker.State.NOT_TRACKING;
2744 }
2745
2746 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2747 if (keyCode == KeyEvent.KEYCODE_MENU) {
2748 mMenuIsDown = true;
2749 }
2750 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2751 if (!handled) {
2752 switch (keyCode) {
2753 case KeyEvent.KEYCODE_SPACE:
2754 if (event.isShiftPressed()) {
2755 getTopWindow().pageUp(false);
2756 } else {
2757 getTopWindow().pageDown(false);
2758 }
2759 handled = true;
2760 break;
2761
2762 default:
2763 break;
2764 }
2765 }
2766 return handled || super.onKeyDown(keyCode, event);
2767 }
2768
2769 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2770 if (keyCode == KeyEvent.KEYCODE_MENU) {
2771 mMenuIsDown = false;
2772 }
2773 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2774 }
2775
2776 private void stopLoading() {
2777 resetTitleAndRevertLockIcon();
2778 WebView w = getTopWindow();
2779 w.stopLoading();
2780 mWebViewClient.onPageFinished(w, w.getUrl());
2781
2782 cancelStopToast();
2783 mStopToast = Toast
2784 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2785 mStopToast.show();
2786 }
2787
2788 private void cancelStopToast() {
2789 if (mStopToast != null) {
2790 mStopToast.cancel();
2791 mStopToast = null;
2792 }
2793 }
2794
2795 // called by a non-UI thread to post the message
2796 public void postMessage(int what, int arg1, int arg2, Object obj) {
2797 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2798 }
2799
2800 // public message ids
2801 public final static int LOAD_URL = 1001;
2802 public final static int STOP_LOAD = 1002;
2803
2804 // Message Ids
2805 private static final int FOCUS_NODE_HREF = 102;
2806 private static final int CANCEL_CREDS_REQUEST = 103;
2807 private static final int ANIMATE_FROM_OVERVIEW = 104;
2808 private static final int ANIMATE_TO_OVERVIEW = 105;
2809 private static final int OPEN_TAB_AND_SHOW = 106;
2810 private static final int CHECK_MEMORY = 107;
2811 private static final int RELEASE_WAKELOCK = 108;
2812
2813 // Private handler for handling javascript and saving passwords
2814 private Handler mHandler = new Handler() {
2815
2816 public void handleMessage(Message msg) {
2817 switch (msg.what) {
2818 case ANIMATE_FROM_OVERVIEW:
2819 final HashMap map = (HashMap) msg.obj;
2820 animateFromTabOverview((AnimatingView) map.get("view"),
2821 msg.arg1 == 1, (Message) map.get("msg"));
2822 break;
2823
2824 case ANIMATE_TO_OVERVIEW:
2825 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2826 (AnimatingView) msg.obj);
2827 break;
2828
2829 case OPEN_TAB_AND_SHOW:
2830 // Decrement mAnimationCount before openTabAndShow because
2831 // the method relies on the value being 0 to start the next
2832 // animation.
2833 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002834 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002835 break;
2836
2837 case FOCUS_NODE_HREF:
2838 String url = (String) msg.getData().get("url");
2839 if (url == null || url.length() == 0) {
2840 break;
2841 }
2842 HashMap focusNodeMap = (HashMap) msg.obj;
2843 WebView view = (WebView) focusNodeMap.get("webview");
2844 // Only apply the action if the top window did not change.
2845 if (getTopWindow() != view) {
2846 break;
2847 }
2848 switch (msg.arg1) {
2849 case R.id.open_context_menu_id:
2850 case R.id.view_image_context_menu_id:
2851 loadURL(getTopWindow(), url);
2852 break;
2853 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002854 final TabControl.Tab parent = mTabControl
2855 .getCurrentTab();
2856 final TabControl.Tab newTab = openTab(url);
2857 if (newTab != parent) {
2858 parent.addChildTab(newTab);
2859 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002860 break;
2861 case R.id.bookmark_context_menu_id:
2862 Intent intent = new Intent(BrowserActivity.this,
2863 AddBookmarkPage.class);
2864 intent.putExtra("url", url);
2865 startActivity(intent);
2866 break;
2867 case R.id.share_link_context_menu_id:
2868 Browser.sendString(BrowserActivity.this, url);
2869 break;
2870 case R.id.copy_link_context_menu_id:
2871 copy(url);
2872 break;
2873 case R.id.save_link_context_menu_id:
2874 case R.id.download_context_menu_id:
2875 onDownloadStartNoStream(url, null, null, null, -1);
2876 break;
2877 }
2878 break;
2879
2880 case LOAD_URL:
2881 loadURL(getTopWindow(), (String) msg.obj);
2882 break;
2883
2884 case STOP_LOAD:
2885 stopLoading();
2886 break;
2887
2888 case CANCEL_CREDS_REQUEST:
2889 resumeAfterCredentials();
2890 break;
2891
2892 case CHECK_MEMORY:
2893 // reschedule to check memory condition
2894 mHandler.removeMessages(CHECK_MEMORY);
2895 mHandler.sendMessageDelayed(mHandler.obtainMessage
2896 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2897 checkMemory();
2898 break;
2899
2900 case RELEASE_WAKELOCK:
2901 if (mWakeLock.isHeld()) {
2902 mWakeLock.release();
2903 }
2904 break;
2905 }
2906 }
2907 };
2908
2909 // -------------------------------------------------------------------------
2910 // WebViewClient implementation.
2911 //-------------------------------------------------------------------------
2912
2913 // Use in overrideUrlLoading
2914 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2915 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2916 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2917 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2918
2919 /* package */ WebViewClient getWebViewClient() {
2920 return mWebViewClient;
2921 }
2922
2923 private void updateIcon(String url, Bitmap icon) {
2924 if (icon != null) {
2925 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2926 url, icon);
2927 }
2928 setFavicon(icon);
2929 }
2930
2931 private final WebViewClient mWebViewClient = new WebViewClient() {
2932 @Override
2933 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2934 resetLockIcon(url);
2935 setUrlTitle(url, null);
2936 // Call updateIcon instead of setFavicon so the bookmark
2937 // database can be updated.
2938 updateIcon(url, favicon);
2939
2940 if (mSettings.isTracing() == true) {
2941 // FIXME: we should save the trace file somewhere other than data.
2942 // I can't use "/tmp" as it competes for system memory.
2943 File file = getDir("browserTrace", 0);
2944 String baseDir = file.getPath();
2945 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2946 String host;
2947 try {
2948 WebAddress uri = new WebAddress(url);
2949 host = uri.mHost;
2950 } catch (android.net.ParseException ex) {
2951 host = "unknown_host";
2952 }
2953 host = host.replace('.', '_');
2954 baseDir = baseDir + host;
2955 file = new File(baseDir+".data");
2956 if (file.exists() == true) {
2957 file.delete();
2958 }
2959 file = new File(baseDir+".key");
2960 if (file.exists() == true) {
2961 file.delete();
2962 }
2963 mInTrace = true;
2964 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2965 }
2966
2967 // Performance probe
2968 if (false) {
2969 mStart = SystemClock.uptimeMillis();
2970 mProcessStart = Process.getElapsedCpuTime();
2971 long[] sysCpu = new long[7];
2972 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2973 sysCpu, null)) {
2974 mUserStart = sysCpu[0] + sysCpu[1];
2975 mSystemStart = sysCpu[2];
2976 mIdleStart = sysCpu[3];
2977 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2978 }
2979 mUiStart = SystemClock.currentThreadTimeMillis();
2980 }
2981
2982 if (!mPageStarted) {
2983 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002984 // if onResume() has been called, resumeWebViewTimers() does
2985 // nothing.
2986 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002987 }
2988
2989 // reset sync timer to avoid sync starts during loading a page
2990 CookieSyncManager.getInstance().resetSync();
2991
2992 mInLoad = true;
2993 updateInLoadMenuItems();
2994 if (!mIsNetworkUp) {
2995 if ( mAlertDialog == null) {
2996 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2997 .setTitle(R.string.loadSuspendedTitle)
2998 .setMessage(R.string.loadSuspended)
2999 .setPositiveButton(R.string.ok, null)
3000 .show();
3001 }
3002 if (view != null) {
3003 view.setNetworkAvailable(false);
3004 }
3005 }
3006
3007 // schedule to check memory condition
3008 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
3009 CHECK_MEMORY_INTERVAL);
3010 }
3011
3012 @Override
3013 public void onPageFinished(WebView view, String url) {
3014 // Reset the title and icon in case we stopped a provisional
3015 // load.
3016 resetTitleAndIcon(view);
3017
3018 // Update the lock icon image only once we are done loading
3019 updateLockIconImage(mLockIconType);
3020
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04003021 // If this is a bookmarked site, add a screenshot to the database.
3022 // FIXME: When should we update? Every time?
3023 if (url != null) {
3024 // copied from BrowserBookmarksAdapter
3025 int query = url.indexOf('?');
3026 String noQuery = url;
3027 if (query != -1) {
3028 noQuery = url.substring(0, query);
3029 }
3030 String URL = noQuery + '?';
3031 String[] selArgs = new String[] { noQuery, URL };
3032 final String where = "(url == ? OR url GLOB ? || '*') AND bookmark == 1";
3033 final String[] projection = new String[] { Browser.BookmarkColumns._ID };
3034 ContentResolver cr = getContentResolver();
3035 final Cursor c = cr.query(Browser.BOOKMARKS_URI, projection, where, selArgs, null);
3036 boolean succeed = c.moveToFirst();
3037 ContentValues values = null;
3038 while (succeed) {
3039 if (values == null) {
3040 final ByteArrayOutputStream os = new ByteArrayOutputStream();
3041 Picture thumbnail = view.capturePicture();
3042 // Height was arbitrarily chosen
3043 Bitmap bm = Bitmap.createBitmap(100, 100,
3044 Bitmap.Config.ARGB_4444);
3045 Canvas canvas = new Canvas(bm);
3046 // Scale chosen to be about one third, since we want
3047 // roughly three rows/columns for bookmark page
3048 canvas.scale(.3f, .3f);
3049 thumbnail.draw(canvas);
3050 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
3051 values = new ContentValues();
3052 values.put(Browser.BookmarkColumns.THUMBNAIL,
3053 os.toByteArray());
3054 }
3055 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
3056 c.getInt(0)), values, null, null);
3057 succeed = c.moveToNext();
3058 }
3059 c.close();
3060 }
3061
The Android Open Source Project0c908882009-03-03 19:32:16 -08003062 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003063 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003064 long[] sysCpu = new long[7];
3065 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3066 sysCpu, null)) {
3067 String uiInfo = "UI thread used "
3068 + (SystemClock.currentThreadTimeMillis() - mUiStart)
3069 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07003070 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003071 Log.d(LOGTAG, uiInfo);
3072 }
3073 //The string that gets written to the log
3074 String performanceString = "It took total "
3075 + (SystemClock.uptimeMillis() - mStart)
3076 + " ms clock time to load the page."
3077 + "\nbrowser process used "
3078 + (Process.getElapsedCpuTime() - mProcessStart)
3079 + " ms, user processes used "
3080 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
3081 + " ms, kernel used "
3082 + (sysCpu[2] - mSystemStart) * 10
3083 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
3084 + " ms and irq took "
3085 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
3086 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003087 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003088 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
3089 }
3090 if (url != null) {
3091 // strip the url to maintain consistency
3092 String newUrl = new String(url);
3093 if (newUrl.startsWith("http://www.")) {
3094 newUrl = newUrl.substring(11);
3095 } else if (newUrl.startsWith("http://")) {
3096 newUrl = newUrl.substring(7);
3097 } else if (newUrl.startsWith("https://www.")) {
3098 newUrl = newUrl.substring(12);
3099 } else if (newUrl.startsWith("https://")) {
3100 newUrl = newUrl.substring(8);
3101 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07003102 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003103 Log.d(LOGTAG, newUrl + " loaded");
3104 }
3105 /*
3106 if (sWhiteList.contains(newUrl)) {
3107 // The string that gets pushed to the statistcs
3108 // service
3109 performanceString = performanceString
3110 + "\nWebpage: "
3111 + newUrl
3112 + "\nCarrier: "
3113 + android.os.SystemProperties
3114 .get("gsm.sim.operator.alpha");
3115 if (mWebView != null
3116 && mWebView.getContext() != null
3117 && mWebView.getContext().getSystemService(
3118 Context.CONNECTIVITY_SERVICE) != null) {
3119 ConnectivityManager cManager =
3120 (ConnectivityManager) mWebView
3121 .getContext().getSystemService(
3122 Context.CONNECTIVITY_SERVICE);
3123 NetworkInfo nInfo = cManager
3124 .getActiveNetworkInfo();
3125 if (nInfo != null) {
3126 performanceString = performanceString
3127 + "\nNetwork Type: "
3128 + nInfo.getType().toString();
3129 }
3130 }
3131 Checkin.logEvent(mResolver,
3132 Checkin.Events.Tag.WEBPAGE_LOAD,
3133 performanceString);
3134 Log.w(LOGTAG, "pushed to the statistics service");
3135 }
3136 */
3137 }
3138 }
3139 }
3140
3141 if (mInTrace) {
3142 mInTrace = false;
3143 Debug.stopMethodTracing();
3144 }
3145
3146 if (mPageStarted) {
3147 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003148 // pauseWebViewTimers() will do nothing and return false if
3149 // onPause() is not called yet.
3150 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003151 if (mWakeLock.isHeld()) {
3152 mHandler.removeMessages(RELEASE_WAKELOCK);
3153 mWakeLock.release();
3154 }
3155 }
3156 }
3157
The Android Open Source Project0c908882009-03-03 19:32:16 -08003158 mHandler.removeMessages(CHECK_MEMORY);
3159 checkMemory();
3160 }
3161
3162 // return true if want to hijack the url to let another app to handle it
3163 @Override
3164 public boolean shouldOverrideUrlLoading(WebView view, String url) {
3165 if (url.startsWith(SCHEME_WTAI)) {
3166 // wtai://wp/mc;number
3167 // number=string(phone-number)
3168 if (url.startsWith(SCHEME_WTAI_MC)) {
3169 Intent intent = new Intent(Intent.ACTION_VIEW,
3170 Uri.parse(WebView.SCHEME_TEL +
3171 url.substring(SCHEME_WTAI_MC.length())));
3172 startActivity(intent);
3173 return true;
3174 }
3175 // wtai://wp/sd;dtmf
3176 // dtmf=string(dialstring)
3177 if (url.startsWith(SCHEME_WTAI_SD)) {
3178 // TODO
3179 // only send when there is active voice connection
3180 return false;
3181 }
3182 // wtai://wp/ap;number;name
3183 // number=string(phone-number)
3184 // name=string
3185 if (url.startsWith(SCHEME_WTAI_AP)) {
3186 // TODO
3187 return false;
3188 }
3189 }
3190
Dianne Hackborn99189432009-06-17 18:06:18 -07003191 // The "about:" schemes are internal to the browser; don't
3192 // want these to be dispatched to other apps.
3193 if (url.startsWith("about:")) {
3194 return false;
3195 }
3196
3197 Intent intent;
3198
3199 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003200 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003201 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3202 } catch (URISyntaxException ex) {
3203 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003204 return false;
3205 }
3206
Grace Kloba5b078b52009-06-24 20:23:41 -07003207 // check whether the intent can be resolved. If not, we will see
3208 // whether we can download it from the Market.
3209 if (getPackageManager().resolveActivity(intent, 0) == null) {
3210 String packagename = intent.getPackage();
3211 if (packagename != null) {
3212 intent = new Intent(Intent.ACTION_VIEW, Uri
3213 .parse("market://search?q=pname:" + packagename));
3214 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3215 startActivity(intent);
3216 return true;
3217 } else {
3218 return false;
3219 }
3220 }
3221
Dianne Hackborn99189432009-06-17 18:06:18 -07003222 // sanitize the Intent, ensuring web pages can not bypass browser
3223 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003224 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003225 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003226 try {
3227 if (startActivityIfNeeded(intent, -1)) {
3228 return true;
3229 }
3230 } catch (ActivityNotFoundException ex) {
3231 // ignore the error. If no application can handle the URL,
3232 // eg about:blank, assume the browser can handle it.
3233 }
3234
3235 if (mMenuIsDown) {
3236 openTab(url);
3237 closeOptionsMenu();
3238 return true;
3239 }
3240
3241 return false;
3242 }
3243
3244 /**
3245 * Updates the lock icon. This method is called when we discover another
3246 * resource to be loaded for this page (for example, javascript). While
3247 * we update the icon type, we do not update the lock icon itself until
3248 * we are done loading, it is slightly more secure this way.
3249 */
3250 @Override
3251 public void onLoadResource(WebView view, String url) {
3252 if (url != null && url.length() > 0) {
3253 // It is only if the page claims to be secure
3254 // that we may have to update the lock:
3255 if (mLockIconType == LOCK_ICON_SECURE) {
3256 // If NOT a 'safe' url, change the lock to mixed content!
3257 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3258 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003259 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003260 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3261 " updated lock icon to " + mLockIconType + " due to " + url);
3262 }
3263 }
3264 }
3265 }
3266 }
3267
3268 /**
3269 * Show the dialog, asking the user if they would like to continue after
3270 * an excessive number of HTTP redirects.
3271 */
3272 @Override
3273 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3274 final Message continueMsg) {
3275 new AlertDialog.Builder(BrowserActivity.this)
3276 .setTitle(R.string.browserFrameRedirect)
3277 .setMessage(R.string.browserFrame307Post)
3278 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3279 public void onClick(DialogInterface dialog, int which) {
3280 continueMsg.sendToTarget();
3281 }})
3282 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3283 public void onClick(DialogInterface dialog, int which) {
3284 cancelMsg.sendToTarget();
3285 }})
3286 .setOnCancelListener(new OnCancelListener() {
3287 public void onCancel(DialogInterface dialog) {
3288 cancelMsg.sendToTarget();
3289 }})
3290 .show();
3291 }
3292
Patrick Scott37911c72009-03-24 18:02:58 -07003293 // Container class for the next error dialog that needs to be
3294 // displayed.
3295 class ErrorDialog {
3296 public final int mTitle;
3297 public final String mDescription;
3298 public final int mError;
3299 ErrorDialog(int title, String desc, int error) {
3300 mTitle = title;
3301 mDescription = desc;
3302 mError = error;
3303 }
3304 };
3305
3306 private void processNextError() {
3307 if (mQueuedErrors == null) {
3308 return;
3309 }
3310 // The first one is currently displayed so just remove it.
3311 mQueuedErrors.removeFirst();
3312 if (mQueuedErrors.size() == 0) {
3313 mQueuedErrors = null;
3314 return;
3315 }
3316 showError(mQueuedErrors.getFirst());
3317 }
3318
3319 private DialogInterface.OnDismissListener mDialogListener =
3320 new DialogInterface.OnDismissListener() {
3321 public void onDismiss(DialogInterface d) {
3322 processNextError();
3323 }
3324 };
3325 private LinkedList<ErrorDialog> mQueuedErrors;
3326
3327 private void queueError(int err, String desc) {
3328 if (mQueuedErrors == null) {
3329 mQueuedErrors = new LinkedList<ErrorDialog>();
3330 }
3331 for (ErrorDialog d : mQueuedErrors) {
3332 if (d.mError == err) {
3333 // Already saw a similar error, ignore the new one.
3334 return;
3335 }
3336 }
3337 ErrorDialog errDialog = new ErrorDialog(
3338 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3339 R.string.browserFrameFileErrorLabel :
3340 R.string.browserFrameNetworkErrorLabel,
3341 desc, err);
3342 mQueuedErrors.addLast(errDialog);
3343
3344 // Show the dialog now if the queue was empty.
3345 if (mQueuedErrors.size() == 1) {
3346 showError(errDialog);
3347 }
3348 }
3349
3350 private void showError(ErrorDialog errDialog) {
3351 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3352 .setTitle(errDialog.mTitle)
3353 .setMessage(errDialog.mDescription)
3354 .setPositiveButton(R.string.ok, null)
3355 .create();
3356 d.setOnDismissListener(mDialogListener);
3357 d.show();
3358 }
3359
The Android Open Source Project0c908882009-03-03 19:32:16 -08003360 /**
3361 * Show a dialog informing the user of the network error reported by
3362 * WebCore.
3363 */
3364 @Override
3365 public void onReceivedError(WebView view, int errorCode,
3366 String description, String failingUrl) {
3367 if (errorCode != EventHandler.ERROR_LOOKUP &&
3368 errorCode != EventHandler.ERROR_CONNECT &&
3369 errorCode != EventHandler.ERROR_BAD_URL &&
3370 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3371 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07003372 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003373 }
Patrick Scott37911c72009-03-24 18:02:58 -07003374 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3375 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003376
3377 // We need to reset the title after an error.
3378 resetTitleAndRevertLockIcon();
3379 }
3380
3381 /**
3382 * Check with the user if it is ok to resend POST data as the page they
3383 * are trying to navigate to is the result of a POST.
3384 */
3385 @Override
3386 public void onFormResubmission(WebView view, final Message dontResend,
3387 final Message resend) {
3388 new AlertDialog.Builder(BrowserActivity.this)
3389 .setTitle(R.string.browserFrameFormResubmitLabel)
3390 .setMessage(R.string.browserFrameFormResubmitMessage)
3391 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3392 public void onClick(DialogInterface dialog, int which) {
3393 resend.sendToTarget();
3394 }})
3395 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3396 public void onClick(DialogInterface dialog, int which) {
3397 dontResend.sendToTarget();
3398 }})
3399 .setOnCancelListener(new OnCancelListener() {
3400 public void onCancel(DialogInterface dialog) {
3401 dontResend.sendToTarget();
3402 }})
3403 .show();
3404 }
3405
3406 /**
3407 * Insert the url into the visited history database.
3408 * @param url The url to be inserted.
3409 * @param isReload True if this url is being reloaded.
3410 * FIXME: Not sure what to do when reloading the page.
3411 */
3412 @Override
3413 public void doUpdateVisitedHistory(WebView view, String url,
3414 boolean isReload) {
3415 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3416 return;
3417 }
3418 Browser.updateVisitedHistory(mResolver, url, true);
3419 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3420 }
3421
3422 /**
3423 * Displays SSL error(s) dialog to the user.
3424 */
3425 @Override
3426 public void onReceivedSslError(
3427 final WebView view, final SslErrorHandler handler, final SslError error) {
3428
3429 if (mSettings.showSecurityWarnings()) {
3430 final LayoutInflater factory =
3431 LayoutInflater.from(BrowserActivity.this);
3432 final View warningsView =
3433 factory.inflate(R.layout.ssl_warnings, null);
3434 final LinearLayout placeholder =
3435 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3436
3437 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3438 LinearLayout ll = (LinearLayout)factory
3439 .inflate(R.layout.ssl_warning, null);
3440 ((TextView)ll.findViewById(R.id.warning))
3441 .setText(R.string.ssl_untrusted);
3442 placeholder.addView(ll);
3443 }
3444
3445 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3446 LinearLayout ll = (LinearLayout)factory
3447 .inflate(R.layout.ssl_warning, null);
3448 ((TextView)ll.findViewById(R.id.warning))
3449 .setText(R.string.ssl_mismatch);
3450 placeholder.addView(ll);
3451 }
3452
3453 if (error.hasError(SslError.SSL_EXPIRED)) {
3454 LinearLayout ll = (LinearLayout)factory
3455 .inflate(R.layout.ssl_warning, null);
3456 ((TextView)ll.findViewById(R.id.warning))
3457 .setText(R.string.ssl_expired);
3458 placeholder.addView(ll);
3459 }
3460
3461 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3462 LinearLayout ll = (LinearLayout)factory
3463 .inflate(R.layout.ssl_warning, null);
3464 ((TextView)ll.findViewById(R.id.warning))
3465 .setText(R.string.ssl_not_yet_valid);
3466 placeholder.addView(ll);
3467 }
3468
3469 new AlertDialog.Builder(BrowserActivity.this)
3470 .setTitle(R.string.security_warning)
3471 .setIcon(android.R.drawable.ic_dialog_alert)
3472 .setView(warningsView)
3473 .setPositiveButton(R.string.ssl_continue,
3474 new DialogInterface.OnClickListener() {
3475 public void onClick(DialogInterface dialog, int whichButton) {
3476 handler.proceed();
3477 }
3478 })
3479 .setNeutralButton(R.string.view_certificate,
3480 new DialogInterface.OnClickListener() {
3481 public void onClick(DialogInterface dialog, int whichButton) {
3482 showSSLCertificateOnError(view, handler, error);
3483 }
3484 })
3485 .setNegativeButton(R.string.cancel,
3486 new DialogInterface.OnClickListener() {
3487 public void onClick(DialogInterface dialog, int whichButton) {
3488 handler.cancel();
3489 BrowserActivity.this.resetTitleAndRevertLockIcon();
3490 }
3491 })
3492 .setOnCancelListener(
3493 new DialogInterface.OnCancelListener() {
3494 public void onCancel(DialogInterface dialog) {
3495 handler.cancel();
3496 BrowserActivity.this.resetTitleAndRevertLockIcon();
3497 }
3498 })
3499 .show();
3500 } else {
3501 handler.proceed();
3502 }
3503 }
3504
3505 /**
3506 * Handles an HTTP authentication request.
3507 *
3508 * @param handler The authentication handler
3509 * @param host The host
3510 * @param realm The realm
3511 */
3512 @Override
3513 public void onReceivedHttpAuthRequest(WebView view,
3514 final HttpAuthHandler handler, final String host, final String realm) {
3515 String username = null;
3516 String password = null;
3517
3518 boolean reuseHttpAuthUsernamePassword =
3519 handler.useHttpAuthUsernamePassword();
3520
3521 if (reuseHttpAuthUsernamePassword &&
3522 (mTabControl.getCurrentWebView() != null)) {
3523 String[] credentials =
3524 mTabControl.getCurrentWebView()
3525 .getHttpAuthUsernamePassword(host, realm);
3526 if (credentials != null && credentials.length == 2) {
3527 username = credentials[0];
3528 password = credentials[1];
3529 }
3530 }
3531
3532 if (username != null && password != null) {
3533 handler.proceed(username, password);
3534 } else {
3535 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3536 }
3537 }
3538
3539 @Override
3540 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3541 if (mMenuIsDown) {
3542 // only check shortcut key when MENU is held
3543 return getWindow().isShortcutKey(event.getKeyCode(), event);
3544 } else {
3545 return false;
3546 }
3547 }
3548
3549 @Override
3550 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3551 if (view != mTabControl.getCurrentTopWebView()) {
3552 return;
3553 }
3554 if (event.isDown()) {
3555 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3556 } else {
3557 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3558 }
3559 }
3560 };
3561
3562 //--------------------------------------------------------------------------
3563 // WebChromeClient implementation
3564 //--------------------------------------------------------------------------
3565
3566 /* package */ WebChromeClient getWebChromeClient() {
3567 return mWebChromeClient;
3568 }
3569
3570 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3571 // Helper method to create a new tab or sub window.
3572 private void createWindow(final boolean dialog, final Message msg) {
3573 if (dialog) {
3574 mTabControl.createSubWindow();
3575 final TabControl.Tab t = mTabControl.getCurrentTab();
3576 attachSubWindow(t);
3577 WebView.WebViewTransport transport =
3578 (WebView.WebViewTransport) msg.obj;
3579 transport.setWebView(t.getSubWebView());
3580 msg.sendToTarget();
3581 } else {
3582 final TabControl.Tab parent = mTabControl.getCurrentTab();
3583 // openTabAndShow will dispatch the message after creating the
3584 // new WebView. This will prevent another request from coming
3585 // in during the animation.
Patrick Scott1536e732009-06-11 14:50:01 -04003586 final TabControl.Tab newTab =
3587 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003588 if (newTab != parent) {
3589 parent.addChildTab(newTab);
3590 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003591 WebView.WebViewTransport transport =
3592 (WebView.WebViewTransport) msg.obj;
3593 transport.setWebView(mTabControl.getCurrentWebView());
3594 }
3595 }
3596
3597 @Override
3598 public boolean onCreateWindow(WebView view, final boolean dialog,
3599 final boolean userGesture, final Message resultMsg) {
3600 // Ignore these requests during tab animations or if the tab
3601 // overview is showing.
3602 if (mAnimationCount > 0 || mTabOverview != null) {
3603 return false;
3604 }
3605 // Short-circuit if we can't create any more tabs or sub windows.
3606 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3607 new AlertDialog.Builder(BrowserActivity.this)
3608 .setTitle(R.string.too_many_subwindows_dialog_title)
3609 .setIcon(android.R.drawable.ic_dialog_alert)
3610 .setMessage(R.string.too_many_subwindows_dialog_message)
3611 .setPositiveButton(R.string.ok, null)
3612 .show();
3613 return false;
3614 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3615 new AlertDialog.Builder(BrowserActivity.this)
3616 .setTitle(R.string.too_many_windows_dialog_title)
3617 .setIcon(android.R.drawable.ic_dialog_alert)
3618 .setMessage(R.string.too_many_windows_dialog_message)
3619 .setPositiveButton(R.string.ok, null)
3620 .show();
3621 return false;
3622 }
3623
3624 // Short-circuit if this was a user gesture.
3625 if (userGesture) {
3626 // createWindow will call openTabAndShow for new Windows and
3627 // that will call tabPicker which will increment
3628 // mAnimationCount.
3629 createWindow(dialog, resultMsg);
3630 return true;
3631 }
3632
3633 // Allow the popup and create the appropriate window.
3634 final AlertDialog.OnClickListener allowListener =
3635 new AlertDialog.OnClickListener() {
3636 public void onClick(DialogInterface d,
3637 int which) {
3638 // Same comment as above for setting
3639 // mAnimationCount.
3640 createWindow(dialog, resultMsg);
3641 // Since we incremented mAnimationCount while the
3642 // dialog was up, we have to decrement it here.
3643 mAnimationCount--;
3644 }
3645 };
3646
3647 // Block the popup by returning a null WebView.
3648 final AlertDialog.OnClickListener blockListener =
3649 new AlertDialog.OnClickListener() {
3650 public void onClick(DialogInterface d, int which) {
3651 resultMsg.sendToTarget();
3652 // We are not going to trigger an animation so
3653 // unblock keys and animation requests.
3654 mAnimationCount--;
3655 }
3656 };
3657
3658 // Build a confirmation dialog to display to the user.
3659 final AlertDialog d =
3660 new AlertDialog.Builder(BrowserActivity.this)
3661 .setTitle(R.string.attention)
3662 .setIcon(android.R.drawable.ic_dialog_alert)
3663 .setMessage(R.string.popup_window_attempt)
3664 .setPositiveButton(R.string.allow, allowListener)
3665 .setNegativeButton(R.string.block, blockListener)
3666 .setCancelable(false)
3667 .create();
3668
3669 // Show the confirmation dialog.
3670 d.show();
3671 // We want to increment mAnimationCount here to prevent a
3672 // potential race condition. If the user allows a pop-up from a
3673 // site and that pop-up then triggers another pop-up, it is
3674 // possible to get the BACK key between here and when the dialog
3675 // appears.
3676 mAnimationCount++;
3677 return true;
3678 }
3679
3680 @Override
3681 public void onCloseWindow(WebView window) {
3682 final int currentIndex = mTabControl.getCurrentIndex();
3683 final TabControl.Tab parent =
3684 mTabControl.getCurrentTab().getParentTab();
3685 if (parent != null) {
3686 // JavaScript can only close popup window.
3687 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3688 }
3689 }
3690
3691 @Override
3692 public void onProgressChanged(WebView view, int newProgress) {
3693 // Block progress updates to the title bar while the tab overview
3694 // is animating or being displayed.
3695 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003696 if (CUSTOM_BROWSER_BAR) {
3697 mTitleBar.setProgress(newProgress);
3698 } else {
3699 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3700 newProgress * 100);
3701
3702 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003703 }
3704
3705 if (newProgress == 100) {
3706 // onProgressChanged() is called for sub-frame too while
3707 // onPageFinished() is only called for the main frame. sync
3708 // cookie and cache promptly here.
3709 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003710 if (mInLoad) {
3711 mInLoad = false;
3712 updateInLoadMenuItems();
3713 }
3714 } else {
3715 // onPageFinished may have already been called but a subframe
3716 // is still loading and updating the progress. Reset mInLoad
3717 // and update the menu items.
3718 if (!mInLoad) {
3719 mInLoad = true;
3720 updateInLoadMenuItems();
3721 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003722 }
3723 }
3724
3725 @Override
3726 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003727 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003728
3729 // here, if url is null, we want to reset the title
3730 setUrlTitle(url, title);
3731
3732 if (url == null ||
3733 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3734 return;
3735 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003736 // See if we can find the current url in our history database and
3737 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003738 if (url.startsWith("http://www.")) {
3739 url = url.substring(11);
3740 } else if (url.startsWith("http://")) {
3741 url = url.substring(4);
3742 }
3743 try {
3744 url = "%" + url;
3745 String [] selArgs = new String[] { url };
3746
3747 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3748 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3749 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3750 Browser.HISTORY_PROJECTION, where, selArgs, null);
3751 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003752 // Current implementation of database only has one entry per
3753 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003754 ContentValues map = new ContentValues();
3755 map.put(Browser.BookmarkColumns.TITLE, title);
3756 mResolver.update(Browser.BOOKMARKS_URI, map,
3757 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003758 }
3759 c.close();
3760 } catch (IllegalStateException e) {
3761 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3762 } catch (SQLiteException ex) {
3763 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3764 }
3765 }
3766
3767 @Override
3768 public void onReceivedIcon(WebView view, Bitmap icon) {
3769 updateIcon(view.getUrl(), icon);
3770 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003771
Andrei Popescuadc008d2009-06-26 14:11:30 +01003772 @Override
3773 public void onShowCustomView(View view) {
3774 if (mCustomView != null)
3775 return;
3776
3777 // Add the custom view to its container.
3778 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3779 mCustomView = view;
3780 // Save the menu state and set it to empty while the custom
3781 // view is showing.
3782 mOldMenuState = mMenuState;
3783 mMenuState = EMPTY_MENU;
3784 // Finally show the custom view container.
3785 mCustomViewContainer.setVisibility(View.VISIBLE);
3786 mCustomViewContainer.bringToFront();
3787 }
3788
3789 @Override
3790 public void onHideCustomView() {
3791 if (mCustomView == null)
3792 return;
3793
3794 // Remove the custom view from its container.
3795 mCustomViewContainer.removeView(mCustomView);
3796 mCustomView = null;
3797 // Reset the old menu state.
3798 mMenuState = mOldMenuState;
3799 mOldMenuState = EMPTY_MENU;
3800 mCustomViewContainer.setVisibility(View.GONE);
3801 }
3802
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003803 /**
3804 * The origin has exceeded it's database quota.
3805 * @param url the URL that exceeded the quota
3806 * @param databaseIdentifier the identifier of the database on
3807 * which the transaction that caused the quota overflow was run
3808 * @param currentQuota the current quota for the origin.
3809 * @param quotaUpdater The callback to run when a decision to allow or
3810 * deny quota has been made. Don't forget to call this!
3811 */
3812 @Override
3813 public void onExceededDatabaseQuota(String url,
3814 String databaseIdentifier, long currentQuota,
3815 WebStorage.QuotaUpdater quotaUpdater) {
3816 if(LOGV_ENABLED) {
3817 Log.v(LOGTAG,
3818 "BrowserActivity received onExceededDatabaseQuota for "
3819 + url +
3820 ":"
3821 + databaseIdentifier +
3822 "(current quota: "
3823 + currentQuota +
3824 ")");
3825 }
Nicolas Roard78a98e42009-05-11 13:34:17 +01003826 mWebStorageQuotaUpdater = quotaUpdater;
3827 String DIALOG_PACKAGE = "com.android.browser";
3828 String DIALOG_CLASS = DIALOG_PACKAGE + ".PermissionDialog";
3829 Intent intent = new Intent();
3830 intent.setClassName(DIALOG_PACKAGE, DIALOG_CLASS);
3831 intent.putExtra(PermissionDialog.PARAM_ORIGIN, url);
3832 intent.putExtra(PermissionDialog.PARAM_QUOTA, currentQuota);
3833 startActivityForResult(intent, WEBSTORAGE_QUOTA_DIALOG);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003834 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003835
3836 /* Adds a JavaScript error message to the system log.
3837 * @param message The error message to report.
3838 * @param lineNumber The line number of the error.
3839 * @param sourceID The name of the source file that caused the error.
3840 */
3841 @Override
3842 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3843 Log.w(LOGTAG, "Console: " + message + " (" + sourceID + ":" + lineNumber + ")");
3844 }
3845
The Android Open Source Project0c908882009-03-03 19:32:16 -08003846 };
3847
3848 /**
3849 * Notify the host application a download should be done, or that
3850 * the data should be streamed if a streaming viewer is available.
3851 * @param url The full url to the content that should be downloaded
3852 * @param contentDisposition Content-disposition http header, if
3853 * present.
3854 * @param mimetype The mimetype of the content reported by the server
3855 * @param contentLength The file size reported by the server
3856 */
3857 public void onDownloadStart(String url, String userAgent,
3858 String contentDisposition, String mimetype, long contentLength) {
3859 // if we're dealing wih A/V content that's not explicitly marked
3860 // for download, check if it's streamable.
3861 if (contentDisposition == null
3862 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3863 // query the package manager to see if there's a registered handler
3864 // that matches.
3865 Intent intent = new Intent(Intent.ACTION_VIEW);
3866 intent.setDataAndType(Uri.parse(url), mimetype);
3867 if (getPackageManager().resolveActivity(intent,
3868 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3869 // someone knows how to handle this mime type with this scheme, don't download.
3870 try {
3871 startActivity(intent);
3872 return;
3873 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003874 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003875 Log.d(LOGTAG, "activity not found for " + mimetype
3876 + " over " + Uri.parse(url).getScheme(), ex);
3877 }
3878 // Best behavior is to fall back to a download in this case
3879 }
3880 }
3881 }
3882 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3883 }
3884
3885 /**
3886 * Notify the host application a download should be done, even if there
3887 * is a streaming viewer available for thise type.
3888 * @param url The full url to the content that should be downloaded
3889 * @param contentDisposition Content-disposition http header, if
3890 * present.
3891 * @param mimetype The mimetype of the content reported by the server
3892 * @param contentLength The file size reported by the server
3893 */
3894 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3895 String contentDisposition, String mimetype, long contentLength) {
3896
3897 String filename = URLUtil.guessFileName(url,
3898 contentDisposition, mimetype);
3899
3900 // Check to see if we have an SDCard
3901 String status = Environment.getExternalStorageState();
3902 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3903 int title;
3904 String msg;
3905
3906 // Check to see if the SDCard is busy, same as the music app
3907 if (status.equals(Environment.MEDIA_SHARED)) {
3908 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3909 title = R.string.download_sdcard_busy_dlg_title;
3910 } else {
3911 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3912 title = R.string.download_no_sdcard_dlg_title;
3913 }
3914
3915 new AlertDialog.Builder(this)
3916 .setTitle(title)
3917 .setIcon(android.R.drawable.ic_dialog_alert)
3918 .setMessage(msg)
3919 .setPositiveButton(R.string.ok, null)
3920 .show();
3921 return;
3922 }
3923
3924 // java.net.URI is a lot stricter than KURL so we have to undo
3925 // KURL's percent-encoding and redo the encoding using java.net.URI.
3926 URI uri = null;
3927 try {
3928 // Undo the percent-encoding that KURL may have done.
3929 String newUrl = new String(URLUtil.decode(url.getBytes()));
3930 // Parse the url into pieces
3931 WebAddress w = new WebAddress(newUrl);
3932 String frag = null;
3933 String query = null;
3934 String path = w.mPath;
3935 // Break the path into path, query, and fragment
3936 if (path.length() > 0) {
3937 // Strip the fragment
3938 int idx = path.lastIndexOf('#');
3939 if (idx != -1) {
3940 frag = path.substring(idx + 1);
3941 path = path.substring(0, idx);
3942 }
3943 idx = path.lastIndexOf('?');
3944 if (idx != -1) {
3945 query = path.substring(idx + 1);
3946 path = path.substring(0, idx);
3947 }
3948 }
3949 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3950 query, frag);
3951 } catch (Exception e) {
3952 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3953 return;
3954 }
3955
3956 // XXX: Have to use the old url since the cookies were stored using the
3957 // old percent-encoded url.
3958 String cookies = CookieManager.getInstance().getCookie(url);
3959
3960 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003961 values.put(Downloads.COLUMN_URI, uri.toString());
3962 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3963 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3964 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003965 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003966 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003967 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003968 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3969 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3970 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3971 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003972 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003973 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003974 }
3975 if (mimetype == null) {
3976 // We must have long pressed on a link or image to download it. We
3977 // are not sure of the mimetype in this case, so do a head request
3978 new FetchUrlMimeType(this).execute(values);
3979 } else {
3980 final Uri contentUri =
3981 getContentResolver().insert(Downloads.CONTENT_URI, values);
3982 viewDownloads(contentUri);
3983 }
3984
3985 }
3986
3987 /**
3988 * Resets the lock icon. This method is called when we start a new load and
3989 * know the url to be loaded.
3990 */
3991 private void resetLockIcon(String url) {
3992 // Save the lock-icon state (we revert to it if the load gets cancelled)
3993 saveLockIcon();
3994
3995 mLockIconType = LOCK_ICON_UNSECURE;
3996 if (URLUtil.isHttpsUrl(url)) {
3997 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003998 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003999 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4000 " reset lock icon to " + mLockIconType);
4001 }
4002 }
4003
4004 updateLockIconImage(LOCK_ICON_UNSECURE);
4005 }
4006
4007 /**
4008 * Resets the lock icon. This method is called when the icon needs to be
4009 * reset but we do not know whether we are loading a secure or not secure
4010 * page.
4011 */
4012 private void resetLockIcon() {
4013 // Save the lock-icon state (we revert to it if the load gets cancelled)
4014 saveLockIcon();
4015
4016 mLockIconType = LOCK_ICON_UNSECURE;
4017
Dave Bort31a6d1c2009-04-13 15:56:49 -07004018 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004019 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4020 " reset lock icon to " + mLockIconType);
4021 }
4022
4023 updateLockIconImage(LOCK_ICON_UNSECURE);
4024 }
4025
4026 /**
4027 * Updates the lock-icon image in the title-bar.
4028 */
4029 private void updateLockIconImage(int lockIconType) {
4030 Drawable d = null;
4031 if (lockIconType == LOCK_ICON_SECURE) {
4032 d = mSecLockIcon;
4033 } else if (lockIconType == LOCK_ICON_MIXED) {
4034 d = mMixLockIcon;
4035 }
4036 // If the tab overview is animating or being shown, do not update the
4037 // lock icon.
4038 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04004039 if (CUSTOM_BROWSER_BAR) {
4040 mTitleBar.setLock(d);
4041 } else {
4042 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
4043 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004044 }
4045 }
4046
4047 /**
4048 * Displays a page-info dialog.
4049 * @param tab The tab to show info about
4050 * @param fromShowSSLCertificateOnError The flag that indicates whether
4051 * this dialog was opened from the SSL-certificate-on-error dialog or
4052 * not. This is important, since we need to know whether to return to
4053 * the parent dialog or simply dismiss.
4054 */
4055 private void showPageInfo(final TabControl.Tab tab,
4056 final boolean fromShowSSLCertificateOnError) {
4057 final LayoutInflater factory = LayoutInflater
4058 .from(this);
4059
4060 final View pageInfoView = factory.inflate(R.layout.page_info, null);
4061
4062 final WebView view = tab.getWebView();
4063
4064 String url = null;
4065 String title = null;
4066
4067 if (view == null) {
4068 url = tab.getUrl();
4069 title = tab.getTitle();
4070 } else if (view == mTabControl.getCurrentWebView()) {
4071 // Use the cached title and url if this is the current WebView
4072 url = mUrl;
4073 title = mTitle;
4074 } else {
4075 url = view.getUrl();
4076 title = view.getTitle();
4077 }
4078
4079 if (url == null) {
4080 url = "";
4081 }
4082 if (title == null) {
4083 title = "";
4084 }
4085
4086 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
4087 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
4088
4089 mPageInfoView = tab;
4090 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
4091
4092 AlertDialog.Builder alertDialogBuilder =
4093 new AlertDialog.Builder(this)
4094 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
4095 .setView(pageInfoView)
4096 .setPositiveButton(
4097 R.string.ok,
4098 new DialogInterface.OnClickListener() {
4099 public void onClick(DialogInterface dialog,
4100 int whichButton) {
4101 mPageInfoDialog = null;
4102 mPageInfoView = null;
4103 mPageInfoFromShowSSLCertificateOnError = null;
4104
4105 // if we came here from the SSL error dialog
4106 if (fromShowSSLCertificateOnError) {
4107 // go back to the SSL error dialog
4108 showSSLCertificateOnError(
4109 mSSLCertificateOnErrorView,
4110 mSSLCertificateOnErrorHandler,
4111 mSSLCertificateOnErrorError);
4112 }
4113 }
4114 })
4115 .setOnCancelListener(
4116 new DialogInterface.OnCancelListener() {
4117 public void onCancel(DialogInterface dialog) {
4118 mPageInfoDialog = null;
4119 mPageInfoView = null;
4120 mPageInfoFromShowSSLCertificateOnError = null;
4121
4122 // if we came here from the SSL error dialog
4123 if (fromShowSSLCertificateOnError) {
4124 // go back to the SSL error dialog
4125 showSSLCertificateOnError(
4126 mSSLCertificateOnErrorView,
4127 mSSLCertificateOnErrorHandler,
4128 mSSLCertificateOnErrorError);
4129 }
4130 }
4131 });
4132
4133 // if we have a main top-level page SSL certificate set or a certificate
4134 // error
4135 if (fromShowSSLCertificateOnError ||
4136 (view != null && view.getCertificate() != null)) {
4137 // add a 'View Certificate' button
4138 alertDialogBuilder.setNeutralButton(
4139 R.string.view_certificate,
4140 new DialogInterface.OnClickListener() {
4141 public void onClick(DialogInterface dialog,
4142 int whichButton) {
4143 mPageInfoDialog = null;
4144 mPageInfoView = null;
4145 mPageInfoFromShowSSLCertificateOnError = null;
4146
4147 // if we came here from the SSL error dialog
4148 if (fromShowSSLCertificateOnError) {
4149 // go back to the SSL error dialog
4150 showSSLCertificateOnError(
4151 mSSLCertificateOnErrorView,
4152 mSSLCertificateOnErrorHandler,
4153 mSSLCertificateOnErrorError);
4154 } else {
4155 // otherwise, display the top-most certificate from
4156 // the chain
4157 if (view.getCertificate() != null) {
4158 showSSLCertificate(tab);
4159 }
4160 }
4161 }
4162 });
4163 }
4164
4165 mPageInfoDialog = alertDialogBuilder.show();
4166 }
4167
4168 /**
4169 * Displays the main top-level page SSL certificate dialog
4170 * (accessible from the Page-Info dialog).
4171 * @param tab The tab to show certificate for.
4172 */
4173 private void showSSLCertificate(final TabControl.Tab tab) {
4174 final View certificateView =
4175 inflateCertificateView(tab.getWebView().getCertificate());
4176 if (certificateView == null) {
4177 return;
4178 }
4179
4180 LayoutInflater factory = LayoutInflater.from(this);
4181
4182 final LinearLayout placeholder =
4183 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4184
4185 LinearLayout ll = (LinearLayout) factory.inflate(
4186 R.layout.ssl_success, placeholder);
4187 ((TextView)ll.findViewById(R.id.success))
4188 .setText(R.string.ssl_certificate_is_valid);
4189
4190 mSSLCertificateView = tab;
4191 mSSLCertificateDialog =
4192 new AlertDialog.Builder(this)
4193 .setTitle(R.string.ssl_certificate).setIcon(
4194 R.drawable.ic_dialog_browser_certificate_secure)
4195 .setView(certificateView)
4196 .setPositiveButton(R.string.ok,
4197 new DialogInterface.OnClickListener() {
4198 public void onClick(DialogInterface dialog,
4199 int whichButton) {
4200 mSSLCertificateDialog = null;
4201 mSSLCertificateView = null;
4202
4203 showPageInfo(tab, false);
4204 }
4205 })
4206 .setOnCancelListener(
4207 new DialogInterface.OnCancelListener() {
4208 public void onCancel(DialogInterface dialog) {
4209 mSSLCertificateDialog = null;
4210 mSSLCertificateView = null;
4211
4212 showPageInfo(tab, false);
4213 }
4214 })
4215 .show();
4216 }
4217
4218 /**
4219 * Displays the SSL error certificate dialog.
4220 * @param view The target web-view.
4221 * @param handler The SSL error handler responsible for cancelling the
4222 * connection that resulted in an SSL error or proceeding per user request.
4223 * @param error The SSL error object.
4224 */
4225 private void showSSLCertificateOnError(
4226 final WebView view, final SslErrorHandler handler, final SslError error) {
4227
4228 final View certificateView =
4229 inflateCertificateView(error.getCertificate());
4230 if (certificateView == null) {
4231 return;
4232 }
4233
4234 LayoutInflater factory = LayoutInflater.from(this);
4235
4236 final LinearLayout placeholder =
4237 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4238
4239 if (error.hasError(SslError.SSL_UNTRUSTED)) {
4240 LinearLayout ll = (LinearLayout)factory
4241 .inflate(R.layout.ssl_warning, placeholder);
4242 ((TextView)ll.findViewById(R.id.warning))
4243 .setText(R.string.ssl_untrusted);
4244 }
4245
4246 if (error.hasError(SslError.SSL_IDMISMATCH)) {
4247 LinearLayout ll = (LinearLayout)factory
4248 .inflate(R.layout.ssl_warning, placeholder);
4249 ((TextView)ll.findViewById(R.id.warning))
4250 .setText(R.string.ssl_mismatch);
4251 }
4252
4253 if (error.hasError(SslError.SSL_EXPIRED)) {
4254 LinearLayout ll = (LinearLayout)factory
4255 .inflate(R.layout.ssl_warning, placeholder);
4256 ((TextView)ll.findViewById(R.id.warning))
4257 .setText(R.string.ssl_expired);
4258 }
4259
4260 if (error.hasError(SslError.SSL_NOTYETVALID)) {
4261 LinearLayout ll = (LinearLayout)factory
4262 .inflate(R.layout.ssl_warning, placeholder);
4263 ((TextView)ll.findViewById(R.id.warning))
4264 .setText(R.string.ssl_not_yet_valid);
4265 }
4266
4267 mSSLCertificateOnErrorHandler = handler;
4268 mSSLCertificateOnErrorView = view;
4269 mSSLCertificateOnErrorError = error;
4270 mSSLCertificateOnErrorDialog =
4271 new AlertDialog.Builder(this)
4272 .setTitle(R.string.ssl_certificate).setIcon(
4273 R.drawable.ic_dialog_browser_certificate_partially_secure)
4274 .setView(certificateView)
4275 .setPositiveButton(R.string.ok,
4276 new DialogInterface.OnClickListener() {
4277 public void onClick(DialogInterface dialog,
4278 int whichButton) {
4279 mSSLCertificateOnErrorDialog = null;
4280 mSSLCertificateOnErrorView = null;
4281 mSSLCertificateOnErrorHandler = null;
4282 mSSLCertificateOnErrorError = null;
4283
4284 mWebViewClient.onReceivedSslError(
4285 view, handler, error);
4286 }
4287 })
4288 .setNeutralButton(R.string.page_info_view,
4289 new DialogInterface.OnClickListener() {
4290 public void onClick(DialogInterface dialog,
4291 int whichButton) {
4292 mSSLCertificateOnErrorDialog = null;
4293
4294 // do not clear the dialog state: we will
4295 // need to show the dialog again once the
4296 // user is done exploring the page-info details
4297
4298 showPageInfo(mTabControl.getTabFromView(view),
4299 true);
4300 }
4301 })
4302 .setOnCancelListener(
4303 new DialogInterface.OnCancelListener() {
4304 public void onCancel(DialogInterface dialog) {
4305 mSSLCertificateOnErrorDialog = null;
4306 mSSLCertificateOnErrorView = null;
4307 mSSLCertificateOnErrorHandler = null;
4308 mSSLCertificateOnErrorError = null;
4309
4310 mWebViewClient.onReceivedSslError(
4311 view, handler, error);
4312 }
4313 })
4314 .show();
4315 }
4316
4317 /**
4318 * Inflates the SSL certificate view (helper method).
4319 * @param certificate The SSL certificate.
4320 * @return The resultant certificate view with issued-to, issued-by,
4321 * issued-on, expires-on, and possibly other fields set.
4322 * If the input certificate is null, returns null.
4323 */
4324 private View inflateCertificateView(SslCertificate certificate) {
4325 if (certificate == null) {
4326 return null;
4327 }
4328
4329 LayoutInflater factory = LayoutInflater.from(this);
4330
4331 View certificateView = factory.inflate(
4332 R.layout.ssl_certificate, null);
4333
4334 // issued to:
4335 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4336 if (issuedTo != null) {
4337 ((TextView) certificateView.findViewById(R.id.to_common))
4338 .setText(issuedTo.getCName());
4339 ((TextView) certificateView.findViewById(R.id.to_org))
4340 .setText(issuedTo.getOName());
4341 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4342 .setText(issuedTo.getUName());
4343 }
4344
4345 // issued by:
4346 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4347 if (issuedBy != null) {
4348 ((TextView) certificateView.findViewById(R.id.by_common))
4349 .setText(issuedBy.getCName());
4350 ((TextView) certificateView.findViewById(R.id.by_org))
4351 .setText(issuedBy.getOName());
4352 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4353 .setText(issuedBy.getUName());
4354 }
4355
4356 // issued on:
4357 String issuedOn = reformatCertificateDate(
4358 certificate.getValidNotBefore());
4359 ((TextView) certificateView.findViewById(R.id.issued_on))
4360 .setText(issuedOn);
4361
4362 // expires on:
4363 String expiresOn = reformatCertificateDate(
4364 certificate.getValidNotAfter());
4365 ((TextView) certificateView.findViewById(R.id.expires_on))
4366 .setText(expiresOn);
4367
4368 return certificateView;
4369 }
4370
4371 /**
4372 * Re-formats the certificate date (Date.toString()) string to
4373 * a properly localized date string.
4374 * @return Properly localized version of the certificate date string and
4375 * the original certificate date string if fails to localize.
4376 * If the original string is null, returns an empty string "".
4377 */
4378 private String reformatCertificateDate(String certificateDate) {
4379 String reformattedDate = null;
4380
4381 if (certificateDate != null) {
4382 Date date = null;
4383 try {
4384 date = java.text.DateFormat.getInstance().parse(certificateDate);
4385 } catch (ParseException e) {
4386 date = null;
4387 }
4388
4389 if (date != null) {
4390 reformattedDate =
4391 DateFormat.getDateFormat(this).format(date);
4392 }
4393 }
4394
4395 return reformattedDate != null ? reformattedDate :
4396 (certificateDate != null ? certificateDate : "");
4397 }
4398
4399 /**
4400 * Displays an http-authentication dialog.
4401 */
4402 private void showHttpAuthentication(final HttpAuthHandler handler,
4403 final String host, final String realm, final String title,
4404 final String name, final String password, int focusId) {
4405 LayoutInflater factory = LayoutInflater.from(this);
4406 final View v = factory
4407 .inflate(R.layout.http_authentication, null);
4408 if (name != null) {
4409 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4410 }
4411 if (password != null) {
4412 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4413 }
4414
4415 String titleText = title;
4416 if (titleText == null) {
4417 titleText = getText(R.string.sign_in_to).toString().replace(
4418 "%s1", host).replace("%s2", realm);
4419 }
4420
4421 mHttpAuthHandler = handler;
4422 AlertDialog dialog = new AlertDialog.Builder(this)
4423 .setTitle(titleText)
4424 .setIcon(android.R.drawable.ic_dialog_alert)
4425 .setView(v)
4426 .setPositiveButton(R.string.action,
4427 new DialogInterface.OnClickListener() {
4428 public void onClick(DialogInterface dialog,
4429 int whichButton) {
4430 String nm = ((EditText) v
4431 .findViewById(R.id.username_edit))
4432 .getText().toString();
4433 String pw = ((EditText) v
4434 .findViewById(R.id.password_edit))
4435 .getText().toString();
4436 BrowserActivity.this.setHttpAuthUsernamePassword
4437 (host, realm, nm, pw);
4438 handler.proceed(nm, pw);
4439 mHttpAuthenticationDialog = null;
4440 mHttpAuthHandler = null;
4441 }})
4442 .setNegativeButton(R.string.cancel,
4443 new DialogInterface.OnClickListener() {
4444 public void onClick(DialogInterface dialog,
4445 int whichButton) {
4446 handler.cancel();
4447 BrowserActivity.this.resetTitleAndRevertLockIcon();
4448 mHttpAuthenticationDialog = null;
4449 mHttpAuthHandler = null;
4450 }})
4451 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4452 public void onCancel(DialogInterface dialog) {
4453 handler.cancel();
4454 BrowserActivity.this.resetTitleAndRevertLockIcon();
4455 mHttpAuthenticationDialog = null;
4456 mHttpAuthHandler = null;
4457 }})
4458 .create();
4459 // Make the IME appear when the dialog is displayed if applicable.
4460 dialog.getWindow().setSoftInputMode(
4461 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4462 dialog.show();
4463 if (focusId != 0) {
4464 dialog.findViewById(focusId).requestFocus();
4465 } else {
4466 v.findViewById(R.id.username_edit).requestFocus();
4467 }
4468 mHttpAuthenticationDialog = dialog;
4469 }
4470
4471 public int getProgress() {
4472 WebView w = mTabControl.getCurrentWebView();
4473 if (w != null) {
4474 return w.getProgress();
4475 } else {
4476 return 100;
4477 }
4478 }
4479
4480 /**
4481 * Set HTTP authentication password.
4482 *
4483 * @param host The host for the password
4484 * @param realm The realm for the password
4485 * @param username The username for the password. If it is null, it means
4486 * password can't be saved.
4487 * @param password The password
4488 */
4489 public void setHttpAuthUsernamePassword(String host, String realm,
4490 String username,
4491 String password) {
4492 WebView w = mTabControl.getCurrentWebView();
4493 if (w != null) {
4494 w.setHttpAuthUsernamePassword(host, realm, username, password);
4495 }
4496 }
4497
4498 /**
4499 * connectivity manager says net has come or gone... inform the user
4500 * @param up true if net has come up, false if net has gone down
4501 */
4502 public void onNetworkToggle(boolean up) {
4503 if (up == mIsNetworkUp) {
4504 return;
4505 } else if (up) {
4506 mIsNetworkUp = true;
4507 if (mAlertDialog != null) {
4508 mAlertDialog.cancel();
4509 mAlertDialog = null;
4510 }
4511 } else {
4512 mIsNetworkUp = false;
4513 if (mInLoad && mAlertDialog == null) {
4514 mAlertDialog = new AlertDialog.Builder(this)
4515 .setTitle(R.string.loadSuspendedTitle)
4516 .setMessage(R.string.loadSuspended)
4517 .setPositiveButton(R.string.ok, null)
4518 .show();
4519 }
4520 }
4521 WebView w = mTabControl.getCurrentWebView();
4522 if (w != null) {
4523 w.setNetworkAvailable(up);
4524 }
4525 }
4526
4527 @Override
4528 protected void onActivityResult(int requestCode, int resultCode,
4529 Intent intent) {
4530 switch (requestCode) {
4531 case COMBO_PAGE:
4532 if (resultCode == RESULT_OK && intent != null) {
4533 String data = intent.getAction();
4534 Bundle extras = intent.getExtras();
4535 if (extras != null && extras.getBoolean("new_window", false)) {
4536 openTab(data);
4537 } else {
4538 final TabControl.Tab currentTab =
4539 mTabControl.getCurrentTab();
4540 // If the Window overview is up and we are not in the
4541 // middle of an animation, animate away from it to the
4542 // current tab.
4543 if (mTabOverview != null && mAnimationCount == 0) {
Grace Klobaec7eb372009-06-16 13:45:56 -07004544 sendAnimateFromOverview(currentTab, false,
4545 new UrlData(data), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004546 } else {
4547 dismissSubWindow(currentTab);
4548 if (data != null && data.length() != 0) {
4549 getTopWindow().loadUrl(data);
4550 }
4551 }
4552 }
4553 }
4554 break;
Nicolas Roard78a98e42009-05-11 13:34:17 +01004555 case WEBSTORAGE_QUOTA_DIALOG:
4556 long currentQuota = 0;
4557 if (resultCode == RESULT_OK && intent != null) {
4558 currentQuota = intent.getLongExtra(
4559 PermissionDialog.PARAM_QUOTA, currentQuota);
4560 }
4561 mWebStorageQuotaUpdater.updateQuota(currentQuota);
4562 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004563 default:
4564 break;
4565 }
4566 getTopWindow().requestFocus();
4567 }
4568
4569 /*
4570 * This method is called as a result of the user selecting the options
4571 * menu to see the download window, or when a download changes state. It
4572 * shows the download window ontop of the current window.
4573 */
4574 /* package */ void viewDownloads(Uri downloadRecord) {
4575 Intent intent = new Intent(this,
4576 BrowserDownloadPage.class);
4577 intent.setData(downloadRecord);
4578 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4579
4580 }
4581
4582 /**
4583 * Handle results from Tab Switcher mTabOverview tool
4584 */
4585 private class TabListener implements ImageGrid.Listener {
4586 public void remove(int position) {
4587 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004588 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004589 throw new AssertionError();
4590 }
4591
4592 // Remember the current tab.
4593 TabControl.Tab current = mTabControl.getCurrentTab();
4594 final TabControl.Tab remove = mTabControl.getTab(position);
4595 mTabControl.removeTab(remove);
4596 // If we removed the current tab, use the tab at position - 1 if
4597 // possible.
4598 if (current == remove) {
4599 // If the user removes the last tab, act like the New Tab item
4600 // was clicked on.
4601 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004602 current = mTabControl.createNewTab();
Grace Klobaec7eb372009-06-16 13:45:56 -07004603 sendAnimateFromOverview(current, true, new UrlData(
4604 mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004605 } else {
4606 final int index = position > 0 ? (position - 1) : 0;
4607 current = mTabControl.getTab(index);
4608 }
4609 }
4610
4611 // The tab overview could have been dismissed before this method is
4612 // called.
4613 if (mTabOverview != null) {
4614 // Remove the tab and change the index.
4615 mTabOverview.remove(position);
4616 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4617 }
4618
4619 // Only the current tab ensures its WebView is non-null. This
4620 // implies that we are reloading the freed tab.
4621 mTabControl.setCurrentTab(current);
4622 }
4623 public void onClick(int index) {
4624 // Change the tab if necessary.
4625 // Index equals ImageGrid.CANCEL when pressing back from the tab
4626 // overview.
4627 if (index == ImageGrid.CANCEL) {
4628 index = mTabControl.getCurrentIndex();
4629 // The current index is -1 if the current tab was removed.
4630 if (index == -1) {
4631 // Take the last tab as a fallback.
4632 index = mTabControl.getTabCount() - 1;
4633 }
4634 }
4635
The Android Open Source Project0c908882009-03-03 19:32:16 -08004636 // NEW_TAB means that the "New Tab" cell was clicked on.
4637 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004638 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004639 } else {
Grace Klobaec7eb372009-06-16 13:45:56 -07004640 sendAnimateFromOverview(mTabControl.getTab(index), false,
4641 EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004642 }
4643 }
4644 }
4645
4646 // A fake View that draws the WebView's picture with a fast zoom filter.
4647 // The View is used in case the tab is freed during the animation because
4648 // of low memory.
4649 private static class AnimatingView extends View {
4650 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4651 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4652 private static final DrawFilter sZoomFilter =
4653 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4654 private final Picture mPicture;
4655 private final float mScale;
4656 private final int mScrollX;
4657 private final int mScrollY;
4658 final TabControl.Tab mTab;
4659
4660 AnimatingView(Context ctxt, TabControl.Tab t) {
4661 super(ctxt);
4662 mTab = t;
Patrick Scottae641ac2009-04-20 13:51:49 -04004663 if (t != null && t.getTopWindow() != null) {
4664 // Use the top window in the animation since the tab overview
4665 // will display the top window in each cell.
4666 final WebView w = t.getTopWindow();
4667 mPicture = w.capturePicture();
4668 mScale = w.getScale() / w.getWidth();
4669 mScrollX = w.getScrollX();
4670 mScrollY = w.getScrollY();
4671 } else {
4672 mPicture = null;
4673 mScale = 1.0f;
4674 mScrollX = mScrollY = 0;
4675 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004676 }
4677
4678 @Override
4679 protected void onDraw(Canvas canvas) {
4680 canvas.save();
4681 canvas.drawColor(Color.WHITE);
4682 if (mPicture != null) {
4683 canvas.setDrawFilter(sZoomFilter);
4684 float scale = getWidth() * mScale;
4685 canvas.scale(scale, scale);
4686 canvas.translate(-mScrollX, -mScrollY);
4687 canvas.drawPicture(mPicture);
4688 }
4689 canvas.restore();
4690 }
4691 }
4692
4693 /**
4694 * Open the tab picker. This function will always use the current tab in
4695 * its animation.
4696 * @param stay boolean stating whether the tab picker is to remain open
4697 * (in which case it needs a listener and its menu) or not.
4698 * @param index The index of the tab to show as the selection in the tab
4699 * overview.
4700 * @param remove If true, the tab at index will be removed after the
4701 * animation completes.
4702 */
4703 private void tabPicker(final boolean stay, final int index,
4704 final boolean remove) {
4705 if (mTabOverview != null) {
4706 return;
4707 }
4708
4709 int size = mTabControl.getTabCount();
4710
4711 TabListener l = null;
4712 if (stay) {
4713 l = mTabListener = new TabListener();
4714 }
4715 mTabOverview = new ImageGrid(this, stay, l);
4716
4717 for (int i = 0; i < size; i++) {
4718 final TabControl.Tab t = mTabControl.getTab(i);
4719 mTabControl.populatePickerData(t);
4720 mTabOverview.add(t);
4721 }
4722
4723 // Tell the tab overview to show the current tab, the tab overview will
4724 // handle the "New Tab" case.
4725 int currentIndex = mTabControl.getCurrentIndex();
4726 mTabOverview.setCurrentIndex(currentIndex);
4727
4728 // Attach the tab overview.
4729 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4730
4731 // Create a fake AnimatingView to animate the WebView's picture.
4732 final TabControl.Tab current = mTabControl.getCurrentTab();
4733 final AnimatingView v = new AnimatingView(this, current);
4734 mContentView.addView(v, COVER_SCREEN_PARAMS);
4735 removeTabFromContentView(current);
4736 // Pause timers to get the animation smoother.
4737 current.getWebView().pauseTimers();
4738
4739 // Send a message so the tab picker has a chance to layout and get
4740 // positions for all the cells.
4741 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4742 index, remove ? 1 : 0, v));
4743 // Setting this will indicate that we are animating to the overview. We
4744 // set it here to prevent another request to animate from coming in
4745 // between now and when ANIMATE_TO_OVERVIEW is handled.
4746 mAnimationCount++;
4747 // Always change the title bar to the window overview title while
4748 // animating.
Leon Scroggins81db3662009-06-04 17:45:11 -04004749 if (CUSTOM_BROWSER_BAR) {
4750 mTitleBar.setToTabPicker();
4751 } else {
4752 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4753 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4754 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4755 Window.PROGRESS_VISIBILITY_OFF);
4756 setTitle(R.string.tab_picker_title);
4757 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004758 // Make the menu empty until the animation completes.
4759 mMenuState = EMPTY_MENU;
4760 }
4761
Leon Scrogginse4b3bda2009-06-09 15:46:41 -04004762 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004763 WebView current = mTabControl.getCurrentWebView();
4764 if (current == null) {
4765 return;
4766 }
4767 Intent intent = new Intent(this,
4768 CombinedBookmarkHistoryActivity.class);
4769 String title = current.getTitle();
4770 String url = current.getUrl();
4771 // Just in case the user opens bookmarks before a page finishes loading
4772 // so the current history item, and therefore the page, is null.
4773 if (null == url) {
4774 url = mLastEnteredUrl;
4775 // This can happen.
4776 if (null == url) {
4777 url = mSettings.getHomePage();
4778 }
4779 }
4780 // In case the web page has not yet received its associated title.
4781 if (title == null) {
4782 title = url;
4783 }
4784 intent.putExtra("title", title);
4785 intent.putExtra("url", url);
4786 intent.putExtra("maxTabsOpen",
4787 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4788 if (startWithHistory) {
4789 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4790 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4791 }
4792 startActivityForResult(intent, COMBO_PAGE);
4793 }
4794
4795 // Called when loading from context menu or LOAD_URL message
4796 private void loadURL(WebView view, String url) {
4797 // In case the user enters nothing.
4798 if (url != null && url.length() != 0 && view != null) {
4799 url = smartUrlFilter(url);
4800 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4801 view.loadUrl(url);
4802 }
4803 }
4804 }
4805
4806 private void checkMemory() {
4807 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4808 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4809 .getMemoryInfo(mi);
4810 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4811 // mi.threshold) for now
4812 // if (mi.lowMemory) {
4813 if (mi.availMem < mi.threshold) {
4814 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4815 + (mi.availMem / 1024) + "K threshold="
4816 + (mi.threshold / 1024) + "K");
4817 mTabControl.freeMemory();
4818 }
4819 }
4820
4821 private String smartUrlFilter(Uri inUri) {
4822 if (inUri != null) {
4823 return smartUrlFilter(inUri.toString());
4824 }
4825 return null;
4826 }
4827
4828
4829 // get window count
4830
4831 int getWindowCount(){
4832 if(mTabControl != null){
4833 return mTabControl.getTabCount();
4834 }
4835 return 0;
4836 }
4837
Feng Qianb34f87a2009-03-24 21:27:26 -07004838 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004839 "(?i)" + // switch on case insensitive matching
4840 "(" + // begin group for schema
4841 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004842 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004843 ")" +
4844 "(.*)" );
4845
4846 /**
4847 * Attempts to determine whether user input is a URL or search
4848 * terms. Anything with a space is passed to search.
4849 *
4850 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4851 * "Http://" converts to "http://"
4852 *
4853 * @return Original or modified URL
4854 *
4855 */
4856 String smartUrlFilter(String url) {
4857
4858 String inUrl = url.trim();
4859 boolean hasSpace = inUrl.indexOf(' ') != -1;
4860
4861 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4862 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004863 // force scheme to lowercase
4864 String scheme = matcher.group(1);
4865 String lcScheme = scheme.toLowerCase();
4866 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004867 inUrl = lcScheme + matcher.group(2);
4868 }
4869 if (hasSpace) {
4870 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004871 }
4872 return inUrl;
4873 }
4874 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004875 // FIXME: Is this the correct place to add to searches?
4876 // what if someone else calls this function?
4877 int shortcut = parseUrlShortcut(inUrl);
4878 if (shortcut != SHORTCUT_INVALID) {
4879 Browser.addSearchUrl(mResolver, inUrl);
4880 String query = inUrl.substring(2);
4881 switch (shortcut) {
4882 case SHORTCUT_GOOGLE_SEARCH:
4883 return composeSearchUrl(query);
4884 case SHORTCUT_WIKIPEDIA_SEARCH:
4885 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4886 case SHORTCUT_DICTIONARY_SEARCH:
4887 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4888 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004889 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004890 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004891 }
4892 }
4893 } else {
4894 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4895 return URLUtil.guessUrl(inUrl);
4896 }
4897 }
4898
4899 Browser.addSearchUrl(mResolver, inUrl);
4900 return composeSearchUrl(inUrl);
4901 }
4902
4903 /* package */ String composeSearchUrl(String search) {
4904 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4905 QUERY_PLACE_HOLDER);
4906 }
4907
4908 /* package */void setBaseSearchUrl(String url) {
4909 if (url == null || url.length() == 0) {
4910 /*
4911 * get the google search url based on the SIM. Default is US. NOTE:
4912 * This code uses resources to optionally select the search Uri,
4913 * based on the MCC value from the SIM. The default string will most
4914 * likely be fine. It is parameterized to accept info from the
4915 * Locale, the language code is the first parameter (%1$s) and the
4916 * country code is the second (%2$s). This code must function in the
4917 * same way as a similar lookup in
4918 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4919 * change either of these functions, change them both. (The same is
4920 * true for the underlying resource strings, which are stored in
4921 * mcc-specific xml files.)
4922 */
4923 Locale l = Locale.getDefault();
Bill Napiere9651c32009-05-05 13:16:30 -07004924 String language = l.getLanguage();
4925 String country = l.getCountry().toLowerCase();
4926 // Chinese and Portuguese have two langauge variants.
4927 if ("zh".equals(language)) {
4928 if ("cn".equals(country)) {
4929 language = "zh-CN";
4930 } else if ("tw".equals(country)) {
4931 language = "zh-TW";
4932 }
4933 } else if ("pt".equals(language)) {
4934 if ("br".equals(country)) {
4935 language = "pt-BR";
4936 } else if ("pt".equals(country)) {
4937 language = "pt-PT";
4938 }
4939 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004940 QuickSearch_G = getResources().getString(
Bill Napiere9651c32009-05-05 13:16:30 -07004941 R.string.google_search_base,
4942 language,
4943 country)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004944 + "client=ms-"
Ramanan Rajeswarandd4f4292009-03-24 20:41:19 -07004945 + Partner.getString(this.getContentResolver(), Partner.CLIENT_ID)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004946 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4947 } else {
4948 QuickSearch_G = url;
4949 }
4950 }
4951
4952 private final static int LOCK_ICON_UNSECURE = 0;
4953 private final static int LOCK_ICON_SECURE = 1;
4954 private final static int LOCK_ICON_MIXED = 2;
4955
4956 private int mLockIconType = LOCK_ICON_UNSECURE;
4957 private int mPrevLockType = LOCK_ICON_UNSECURE;
4958
4959 private BrowserSettings mSettings;
4960 private TabControl mTabControl;
4961 private ContentResolver mResolver;
4962 private FrameLayout mContentView;
4963 private ImageGrid mTabOverview;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004964 private View mCustomView;
4965 private FrameLayout mCustomViewContainer;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004966
4967 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4968 // view, we should rewrite this.
4969 private int mCurrentMenuState = 0;
4970 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004971 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004972 private static final int EMPTY_MENU = -1;
4973 private Menu mMenu;
4974
4975 private FindDialog mFindDialog;
4976 // Used to prevent chording to result in firing two shortcuts immediately
4977 // one after another. Fixes bug 1211714.
4978 boolean mCanChord;
4979
4980 private boolean mInLoad;
4981 private boolean mIsNetworkUp;
4982
4983 private boolean mPageStarted;
4984 private boolean mActivityInPause = true;
4985
4986 private boolean mMenuIsDown;
4987
4988 private final KeyTracker mKeyTracker = new KeyTracker(this);
4989
4990 // As trackball doesn't send repeat down, we have to track it ourselves
4991 private boolean mTrackTrackball;
4992
4993 private static boolean mInTrace;
4994
4995 // Performance probe
4996 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4997 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4998 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4999 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
5000 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
5001 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
5002 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
5003 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
5004 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
5005 };
5006
5007 private long mStart;
5008 private long mProcessStart;
5009 private long mUserStart;
5010 private long mSystemStart;
5011 private long mIdleStart;
5012 private long mIrqStart;
5013
5014 private long mUiStart;
5015
5016 private Drawable mMixLockIcon;
5017 private Drawable mSecLockIcon;
5018 private Drawable mGenericFavicon;
5019
5020 /* hold a ref so we can auto-cancel if necessary */
5021 private AlertDialog mAlertDialog;
5022
5023 // Wait for credentials before loading google.com
5024 private ProgressDialog mCredsDlg;
5025
5026 // The up-to-date URL and title (these can be different from those stored
5027 // in WebView, since it takes some time for the information in WebView to
5028 // get updated)
5029 private String mUrl;
5030 private String mTitle;
5031
5032 // As PageInfo has different style for landscape / portrait, we have
5033 // to re-open it when configuration changed
5034 private AlertDialog mPageInfoDialog;
5035 private TabControl.Tab mPageInfoView;
5036 // If the Page-Info dialog is launched from the SSL-certificate-on-error
5037 // dialog, we should not just dismiss it, but should get back to the
5038 // SSL-certificate-on-error dialog. This flag is used to store this state
5039 private Boolean mPageInfoFromShowSSLCertificateOnError;
5040
5041 // as SSLCertificateOnError has different style for landscape / portrait,
5042 // we have to re-open it when configuration changed
5043 private AlertDialog mSSLCertificateOnErrorDialog;
5044 private WebView mSSLCertificateOnErrorView;
5045 private SslErrorHandler mSSLCertificateOnErrorHandler;
5046 private SslError mSSLCertificateOnErrorError;
5047
5048 // as SSLCertificate has different style for landscape / portrait, we
5049 // have to re-open it when configuration changed
5050 private AlertDialog mSSLCertificateDialog;
5051 private TabControl.Tab mSSLCertificateView;
5052
5053 // as HttpAuthentication has different style for landscape / portrait, we
5054 // have to re-open it when configuration changed
5055 private AlertDialog mHttpAuthenticationDialog;
5056 private HttpAuthHandler mHttpAuthHandler;
5057
5058 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
5059 new FrameLayout.LayoutParams(
5060 ViewGroup.LayoutParams.FILL_PARENT,
5061 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01005062 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
5063 new FrameLayout.LayoutParams(
5064 ViewGroup.LayoutParams.FILL_PARENT,
5065 ViewGroup.LayoutParams.FILL_PARENT,
5066 Gravity.CENTER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08005067 // We may provide UI to customize these
5068 // Google search from the browser
5069 static String QuickSearch_G;
5070 // Wikipedia search
5071 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
5072 // Dictionary search
5073 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
5074 // Google Mobile Local search
5075 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
5076
5077 final static String QUERY_PLACE_HOLDER = "%s";
5078
5079 // "source" parameter for Google search through search key
5080 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
5081 // "source" parameter for Google search through goto menu
5082 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
5083 // "source" parameter for Google search through simplily type
5084 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
5085 // "source" parameter for Google search suggested by the browser
5086 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
5087 // "source" parameter for Google search from unknown source
5088 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
5089
5090 private final static String LOGTAG = "browser";
5091
5092 private TabListener mTabListener;
5093
5094 private String mLastEnteredUrl;
5095
5096 private PowerManager.WakeLock mWakeLock;
5097 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5098
5099 private Toast mStopToast;
5100
Leon Scroggins81db3662009-06-04 17:45:11 -04005101 private TitleBar mTitleBar;
5102
The Android Open Source Project0c908882009-03-03 19:32:16 -08005103 // Used during animations to prevent other animations from being triggered.
5104 // A count is used since the animation to and from the Window overview can
5105 // overlap. A count of 0 means no animation where a count of > 0 means
5106 // there are animations in progress.
5107 private int mAnimationCount;
5108
5109 // As the ids are dynamically created, we can't guarantee that they will
5110 // be in sequence, so this static array maps ids to a window number.
5111 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
5112 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
5113 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
5114 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
5115
5116 // monitor platform changes
5117 private IntentFilter mNetworkStateChangedFilter;
5118 private BroadcastReceiver mNetworkStateIntentReceiver;
5119
Grace Klobab4da0ad2009-05-14 14:45:40 -07005120 private BroadcastReceiver mPackageInstallationReceiver;
5121
The Android Open Source Project0c908882009-03-03 19:32:16 -08005122 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01005123 final static int COMBO_PAGE = 1;
5124 final static int DOWNLOAD_PAGE = 2;
5125 final static int PREFERENCES_PAGE = 3;
5126 final static int WEBSTORAGE_QUOTA_DIALOG = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005127
5128 // the frenquency of checking whether system memory is low
5129 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005130
5131 /**
5132 * A UrlData class to abstract how the content will be set to WebView.
5133 * This base class uses loadUrl to show the content.
5134 */
5135 private static class UrlData {
5136 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07005137 byte[] mPostData;
5138
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005139 UrlData(String url) {
5140 this.mUrl = url;
5141 }
Grace Kloba60e095c2009-06-16 11:50:55 -07005142
5143 void setPostData(byte[] postData) {
5144 mPostData = postData;
5145 }
5146
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005147 boolean isEmpty() {
5148 return mUrl == null || mUrl.length() == 0;
5149 }
5150
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005151 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07005152 if (mPostData != null) {
5153 webView.postUrl(mUrl, mPostData);
5154 } else {
5155 webView.loadUrl(mUrl);
5156 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005157 }
5158 };
5159
5160 /**
5161 * A subclass of UrlData class that can display inlined content using
5162 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
5163 */
5164 private static class InlinedUrlData extends UrlData {
5165 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
5166 super(failUrl);
5167 mInlined = inlined;
5168 mMimeType = mimeType;
5169 mEncoding = encoding;
5170 }
5171 String mMimeType;
5172 String mInlined;
5173 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005174 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005175 boolean isEmpty() {
5176 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
5177 }
5178
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005179 @Override
5180 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005181 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
5182 }
5183 }
5184
5185 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08005186}