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