blob: 585b8ff341168f3fb7df1214e6e77e4bcdd291b1 [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
Leon Scroggins89c6d362009-07-15 16:54:37 -04002881 private void updateScreenshot(WebView view) {
2882 // If this is a bookmarked site, add a screenshot to the database.
2883 // FIXME: When should we update? Every time?
2884 // FIXME: Would like to make sure there is actually something to
2885 // draw, but the API for that (WebViewCore.pictureReady()) is not
2886 // currently accessible here.
2887 String original = view.getOriginalUrl();
2888 if (original != null) {
2889 // copied from BrowserBookmarksAdapter
2890 int query = original.indexOf('?');
2891 String noQuery = original;
2892 if (query != -1) {
2893 noQuery = original.substring(0, query);
2894 }
2895 String URL = noQuery + '?';
2896 String[] selArgs = new String[] { noQuery, URL };
2897 final String where
2898 = "(url == ? OR url GLOB ? || '*') AND bookmark == 1";
2899 final String[] projection
2900 = new String[] { Browser.BookmarkColumns._ID };
2901 ContentResolver cr = getContentResolver();
2902 final Cursor c = cr.query(Browser.BOOKMARKS_URI, projection,
2903 where, selArgs, null);
2904 boolean succeed = c.moveToFirst();
2905 ContentValues values = null;
2906 while (succeed) {
2907 if (values == null) {
2908 final ByteArrayOutputStream os
2909 = new ByteArrayOutputStream();
2910 Picture thumbnail = view.capturePicture();
2911 // Keep width and height in sync with BrowserBookmarksPage
2912 // and bookmark_thumb
2913 Bitmap bm = Bitmap.createBitmap(100, 80,
2914 Bitmap.Config.ARGB_4444);
2915 Canvas canvas = new Canvas(bm);
2916 // May need to tweak these values to determine what is the
2917 // best scale factor
2918 canvas.scale(.5f, .5f);
2919 thumbnail.draw(canvas);
2920 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2921 values = new ContentValues();
2922 values.put(Browser.BookmarkColumns.THUMBNAIL,
2923 os.toByteArray());
2924 }
2925 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2926 c.getInt(0)), values, null, null);
2927 succeed = c.moveToNext();
2928 }
2929 c.close();
2930 }
2931 }
2932
The Android Open Source Project0c908882009-03-03 19:32:16 -08002933 // -------------------------------------------------------------------------
2934 // WebViewClient implementation.
2935 //-------------------------------------------------------------------------
2936
2937 // Use in overrideUrlLoading
2938 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2939 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2940 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2941 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2942
2943 /* package */ WebViewClient getWebViewClient() {
2944 return mWebViewClient;
2945 }
2946
2947 private void updateIcon(String url, Bitmap icon) {
2948 if (icon != null) {
2949 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2950 url, icon);
2951 }
2952 setFavicon(icon);
2953 }
2954
2955 private final WebViewClient mWebViewClient = new WebViewClient() {
2956 @Override
2957 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2958 resetLockIcon(url);
2959 setUrlTitle(url, null);
2960 // Call updateIcon instead of setFavicon so the bookmark
2961 // database can be updated.
2962 updateIcon(url, favicon);
2963
2964 if (mSettings.isTracing() == true) {
2965 // FIXME: we should save the trace file somewhere other than data.
2966 // I can't use "/tmp" as it competes for system memory.
2967 File file = getDir("browserTrace", 0);
2968 String baseDir = file.getPath();
2969 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2970 String host;
2971 try {
2972 WebAddress uri = new WebAddress(url);
2973 host = uri.mHost;
2974 } catch (android.net.ParseException ex) {
2975 host = "unknown_host";
2976 }
2977 host = host.replace('.', '_');
2978 baseDir = baseDir + host;
2979 file = new File(baseDir+".data");
2980 if (file.exists() == true) {
2981 file.delete();
2982 }
2983 file = new File(baseDir+".key");
2984 if (file.exists() == true) {
2985 file.delete();
2986 }
2987 mInTrace = true;
2988 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2989 }
2990
2991 // Performance probe
2992 if (false) {
2993 mStart = SystemClock.uptimeMillis();
2994 mProcessStart = Process.getElapsedCpuTime();
2995 long[] sysCpu = new long[7];
2996 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2997 sysCpu, null)) {
2998 mUserStart = sysCpu[0] + sysCpu[1];
2999 mSystemStart = sysCpu[2];
3000 mIdleStart = sysCpu[3];
3001 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
3002 }
3003 mUiStart = SystemClock.currentThreadTimeMillis();
3004 }
3005
3006 if (!mPageStarted) {
3007 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003008 // if onResume() has been called, resumeWebViewTimers() does
3009 // nothing.
3010 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003011 }
3012
3013 // reset sync timer to avoid sync starts during loading a page
3014 CookieSyncManager.getInstance().resetSync();
3015
3016 mInLoad = true;
3017 updateInLoadMenuItems();
3018 if (!mIsNetworkUp) {
3019 if ( mAlertDialog == null) {
3020 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
3021 .setTitle(R.string.loadSuspendedTitle)
3022 .setMessage(R.string.loadSuspended)
3023 .setPositiveButton(R.string.ok, null)
3024 .show();
3025 }
3026 if (view != null) {
3027 view.setNetworkAvailable(false);
3028 }
3029 }
3030
3031 // schedule to check memory condition
3032 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
3033 CHECK_MEMORY_INTERVAL);
3034 }
3035
3036 @Override
3037 public void onPageFinished(WebView view, String url) {
3038 // Reset the title and icon in case we stopped a provisional
3039 // load.
3040 resetTitleAndIcon(view);
3041
3042 // Update the lock icon image only once we are done loading
3043 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04003044 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04003045
The Android Open Source Project0c908882009-03-03 19:32:16 -08003046 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003047 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003048 long[] sysCpu = new long[7];
3049 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3050 sysCpu, null)) {
3051 String uiInfo = "UI thread used "
3052 + (SystemClock.currentThreadTimeMillis() - mUiStart)
3053 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07003054 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003055 Log.d(LOGTAG, uiInfo);
3056 }
3057 //The string that gets written to the log
3058 String performanceString = "It took total "
3059 + (SystemClock.uptimeMillis() - mStart)
3060 + " ms clock time to load the page."
3061 + "\nbrowser process used "
3062 + (Process.getElapsedCpuTime() - mProcessStart)
3063 + " ms, user processes used "
3064 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
3065 + " ms, kernel used "
3066 + (sysCpu[2] - mSystemStart) * 10
3067 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
3068 + " ms and irq took "
3069 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
3070 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003071 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003072 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
3073 }
3074 if (url != null) {
3075 // strip the url to maintain consistency
3076 String newUrl = new String(url);
3077 if (newUrl.startsWith("http://www.")) {
3078 newUrl = newUrl.substring(11);
3079 } else if (newUrl.startsWith("http://")) {
3080 newUrl = newUrl.substring(7);
3081 } else if (newUrl.startsWith("https://www.")) {
3082 newUrl = newUrl.substring(12);
3083 } else if (newUrl.startsWith("https://")) {
3084 newUrl = newUrl.substring(8);
3085 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07003086 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003087 Log.d(LOGTAG, newUrl + " loaded");
3088 }
3089 /*
3090 if (sWhiteList.contains(newUrl)) {
3091 // The string that gets pushed to the statistcs
3092 // service
3093 performanceString = performanceString
3094 + "\nWebpage: "
3095 + newUrl
3096 + "\nCarrier: "
3097 + android.os.SystemProperties
3098 .get("gsm.sim.operator.alpha");
3099 if (mWebView != null
3100 && mWebView.getContext() != null
3101 && mWebView.getContext().getSystemService(
3102 Context.CONNECTIVITY_SERVICE) != null) {
3103 ConnectivityManager cManager =
3104 (ConnectivityManager) mWebView
3105 .getContext().getSystemService(
3106 Context.CONNECTIVITY_SERVICE);
3107 NetworkInfo nInfo = cManager
3108 .getActiveNetworkInfo();
3109 if (nInfo != null) {
3110 performanceString = performanceString
3111 + "\nNetwork Type: "
3112 + nInfo.getType().toString();
3113 }
3114 }
3115 Checkin.logEvent(mResolver,
3116 Checkin.Events.Tag.WEBPAGE_LOAD,
3117 performanceString);
3118 Log.w(LOGTAG, "pushed to the statistics service");
3119 }
3120 */
3121 }
3122 }
3123 }
3124
3125 if (mInTrace) {
3126 mInTrace = false;
3127 Debug.stopMethodTracing();
3128 }
3129
3130 if (mPageStarted) {
3131 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003132 // pauseWebViewTimers() will do nothing and return false if
3133 // onPause() is not called yet.
3134 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003135 if (mWakeLock.isHeld()) {
3136 mHandler.removeMessages(RELEASE_WAKELOCK);
3137 mWakeLock.release();
3138 }
3139 }
3140 }
3141
The Android Open Source Project0c908882009-03-03 19:32:16 -08003142 mHandler.removeMessages(CHECK_MEMORY);
3143 checkMemory();
3144 }
3145
3146 // return true if want to hijack the url to let another app to handle it
3147 @Override
3148 public boolean shouldOverrideUrlLoading(WebView view, String url) {
3149 if (url.startsWith(SCHEME_WTAI)) {
3150 // wtai://wp/mc;number
3151 // number=string(phone-number)
3152 if (url.startsWith(SCHEME_WTAI_MC)) {
3153 Intent intent = new Intent(Intent.ACTION_VIEW,
3154 Uri.parse(WebView.SCHEME_TEL +
3155 url.substring(SCHEME_WTAI_MC.length())));
3156 startActivity(intent);
3157 return true;
3158 }
3159 // wtai://wp/sd;dtmf
3160 // dtmf=string(dialstring)
3161 if (url.startsWith(SCHEME_WTAI_SD)) {
3162 // TODO
3163 // only send when there is active voice connection
3164 return false;
3165 }
3166 // wtai://wp/ap;number;name
3167 // number=string(phone-number)
3168 // name=string
3169 if (url.startsWith(SCHEME_WTAI_AP)) {
3170 // TODO
3171 return false;
3172 }
3173 }
3174
Dianne Hackborn99189432009-06-17 18:06:18 -07003175 // The "about:" schemes are internal to the browser; don't
3176 // want these to be dispatched to other apps.
3177 if (url.startsWith("about:")) {
3178 return false;
3179 }
3180
3181 Intent intent;
3182
3183 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003184 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003185 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3186 } catch (URISyntaxException ex) {
3187 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003188 return false;
3189 }
3190
Grace Kloba5b078b52009-06-24 20:23:41 -07003191 // check whether the intent can be resolved. If not, we will see
3192 // whether we can download it from the Market.
3193 if (getPackageManager().resolveActivity(intent, 0) == null) {
3194 String packagename = intent.getPackage();
3195 if (packagename != null) {
3196 intent = new Intent(Intent.ACTION_VIEW, Uri
3197 .parse("market://search?q=pname:" + packagename));
3198 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3199 startActivity(intent);
3200 return true;
3201 } else {
3202 return false;
3203 }
3204 }
3205
Dianne Hackborn99189432009-06-17 18:06:18 -07003206 // sanitize the Intent, ensuring web pages can not bypass browser
3207 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003208 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003209 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003210 try {
3211 if (startActivityIfNeeded(intent, -1)) {
3212 return true;
3213 }
3214 } catch (ActivityNotFoundException ex) {
3215 // ignore the error. If no application can handle the URL,
3216 // eg about:blank, assume the browser can handle it.
3217 }
3218
3219 if (mMenuIsDown) {
3220 openTab(url);
3221 closeOptionsMenu();
3222 return true;
3223 }
3224
3225 return false;
3226 }
3227
3228 /**
3229 * Updates the lock icon. This method is called when we discover another
3230 * resource to be loaded for this page (for example, javascript). While
3231 * we update the icon type, we do not update the lock icon itself until
3232 * we are done loading, it is slightly more secure this way.
3233 */
3234 @Override
3235 public void onLoadResource(WebView view, String url) {
3236 if (url != null && url.length() > 0) {
3237 // It is only if the page claims to be secure
3238 // that we may have to update the lock:
3239 if (mLockIconType == LOCK_ICON_SECURE) {
3240 // If NOT a 'safe' url, change the lock to mixed content!
3241 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3242 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003243 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003244 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3245 " updated lock icon to " + mLockIconType + " due to " + url);
3246 }
3247 }
3248 }
3249 }
3250 }
3251
3252 /**
3253 * Show the dialog, asking the user if they would like to continue after
3254 * an excessive number of HTTP redirects.
3255 */
3256 @Override
3257 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3258 final Message continueMsg) {
3259 new AlertDialog.Builder(BrowserActivity.this)
3260 .setTitle(R.string.browserFrameRedirect)
3261 .setMessage(R.string.browserFrame307Post)
3262 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3263 public void onClick(DialogInterface dialog, int which) {
3264 continueMsg.sendToTarget();
3265 }})
3266 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3267 public void onClick(DialogInterface dialog, int which) {
3268 cancelMsg.sendToTarget();
3269 }})
3270 .setOnCancelListener(new OnCancelListener() {
3271 public void onCancel(DialogInterface dialog) {
3272 cancelMsg.sendToTarget();
3273 }})
3274 .show();
3275 }
3276
Patrick Scott37911c72009-03-24 18:02:58 -07003277 // Container class for the next error dialog that needs to be
3278 // displayed.
3279 class ErrorDialog {
3280 public final int mTitle;
3281 public final String mDescription;
3282 public final int mError;
3283 ErrorDialog(int title, String desc, int error) {
3284 mTitle = title;
3285 mDescription = desc;
3286 mError = error;
3287 }
3288 };
3289
3290 private void processNextError() {
3291 if (mQueuedErrors == null) {
3292 return;
3293 }
3294 // The first one is currently displayed so just remove it.
3295 mQueuedErrors.removeFirst();
3296 if (mQueuedErrors.size() == 0) {
3297 mQueuedErrors = null;
3298 return;
3299 }
3300 showError(mQueuedErrors.getFirst());
3301 }
3302
3303 private DialogInterface.OnDismissListener mDialogListener =
3304 new DialogInterface.OnDismissListener() {
3305 public void onDismiss(DialogInterface d) {
3306 processNextError();
3307 }
3308 };
3309 private LinkedList<ErrorDialog> mQueuedErrors;
3310
3311 private void queueError(int err, String desc) {
3312 if (mQueuedErrors == null) {
3313 mQueuedErrors = new LinkedList<ErrorDialog>();
3314 }
3315 for (ErrorDialog d : mQueuedErrors) {
3316 if (d.mError == err) {
3317 // Already saw a similar error, ignore the new one.
3318 return;
3319 }
3320 }
3321 ErrorDialog errDialog = new ErrorDialog(
3322 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3323 R.string.browserFrameFileErrorLabel :
3324 R.string.browserFrameNetworkErrorLabel,
3325 desc, err);
3326 mQueuedErrors.addLast(errDialog);
3327
3328 // Show the dialog now if the queue was empty.
3329 if (mQueuedErrors.size() == 1) {
3330 showError(errDialog);
3331 }
3332 }
3333
3334 private void showError(ErrorDialog errDialog) {
3335 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3336 .setTitle(errDialog.mTitle)
3337 .setMessage(errDialog.mDescription)
3338 .setPositiveButton(R.string.ok, null)
3339 .create();
3340 d.setOnDismissListener(mDialogListener);
3341 d.show();
3342 }
3343
The Android Open Source Project0c908882009-03-03 19:32:16 -08003344 /**
3345 * Show a dialog informing the user of the network error reported by
3346 * WebCore.
3347 */
3348 @Override
3349 public void onReceivedError(WebView view, int errorCode,
3350 String description, String failingUrl) {
3351 if (errorCode != EventHandler.ERROR_LOOKUP &&
3352 errorCode != EventHandler.ERROR_CONNECT &&
3353 errorCode != EventHandler.ERROR_BAD_URL &&
3354 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3355 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07003356 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003357 }
Patrick Scott37911c72009-03-24 18:02:58 -07003358 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3359 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003360
3361 // We need to reset the title after an error.
3362 resetTitleAndRevertLockIcon();
3363 }
3364
3365 /**
3366 * Check with the user if it is ok to resend POST data as the page they
3367 * are trying to navigate to is the result of a POST.
3368 */
3369 @Override
3370 public void onFormResubmission(WebView view, final Message dontResend,
3371 final Message resend) {
3372 new AlertDialog.Builder(BrowserActivity.this)
3373 .setTitle(R.string.browserFrameFormResubmitLabel)
3374 .setMessage(R.string.browserFrameFormResubmitMessage)
3375 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3376 public void onClick(DialogInterface dialog, int which) {
3377 resend.sendToTarget();
3378 }})
3379 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3380 public void onClick(DialogInterface dialog, int which) {
3381 dontResend.sendToTarget();
3382 }})
3383 .setOnCancelListener(new OnCancelListener() {
3384 public void onCancel(DialogInterface dialog) {
3385 dontResend.sendToTarget();
3386 }})
3387 .show();
3388 }
3389
3390 /**
3391 * Insert the url into the visited history database.
3392 * @param url The url to be inserted.
3393 * @param isReload True if this url is being reloaded.
3394 * FIXME: Not sure what to do when reloading the page.
3395 */
3396 @Override
3397 public void doUpdateVisitedHistory(WebView view, String url,
3398 boolean isReload) {
3399 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3400 return;
3401 }
3402 Browser.updateVisitedHistory(mResolver, url, true);
3403 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3404 }
3405
3406 /**
3407 * Displays SSL error(s) dialog to the user.
3408 */
3409 @Override
3410 public void onReceivedSslError(
3411 final WebView view, final SslErrorHandler handler, final SslError error) {
3412
3413 if (mSettings.showSecurityWarnings()) {
3414 final LayoutInflater factory =
3415 LayoutInflater.from(BrowserActivity.this);
3416 final View warningsView =
3417 factory.inflate(R.layout.ssl_warnings, null);
3418 final LinearLayout placeholder =
3419 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3420
3421 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3422 LinearLayout ll = (LinearLayout)factory
3423 .inflate(R.layout.ssl_warning, null);
3424 ((TextView)ll.findViewById(R.id.warning))
3425 .setText(R.string.ssl_untrusted);
3426 placeholder.addView(ll);
3427 }
3428
3429 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3430 LinearLayout ll = (LinearLayout)factory
3431 .inflate(R.layout.ssl_warning, null);
3432 ((TextView)ll.findViewById(R.id.warning))
3433 .setText(R.string.ssl_mismatch);
3434 placeholder.addView(ll);
3435 }
3436
3437 if (error.hasError(SslError.SSL_EXPIRED)) {
3438 LinearLayout ll = (LinearLayout)factory
3439 .inflate(R.layout.ssl_warning, null);
3440 ((TextView)ll.findViewById(R.id.warning))
3441 .setText(R.string.ssl_expired);
3442 placeholder.addView(ll);
3443 }
3444
3445 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3446 LinearLayout ll = (LinearLayout)factory
3447 .inflate(R.layout.ssl_warning, null);
3448 ((TextView)ll.findViewById(R.id.warning))
3449 .setText(R.string.ssl_not_yet_valid);
3450 placeholder.addView(ll);
3451 }
3452
3453 new AlertDialog.Builder(BrowserActivity.this)
3454 .setTitle(R.string.security_warning)
3455 .setIcon(android.R.drawable.ic_dialog_alert)
3456 .setView(warningsView)
3457 .setPositiveButton(R.string.ssl_continue,
3458 new DialogInterface.OnClickListener() {
3459 public void onClick(DialogInterface dialog, int whichButton) {
3460 handler.proceed();
3461 }
3462 })
3463 .setNeutralButton(R.string.view_certificate,
3464 new DialogInterface.OnClickListener() {
3465 public void onClick(DialogInterface dialog, int whichButton) {
3466 showSSLCertificateOnError(view, handler, error);
3467 }
3468 })
3469 .setNegativeButton(R.string.cancel,
3470 new DialogInterface.OnClickListener() {
3471 public void onClick(DialogInterface dialog, int whichButton) {
3472 handler.cancel();
3473 BrowserActivity.this.resetTitleAndRevertLockIcon();
3474 }
3475 })
3476 .setOnCancelListener(
3477 new DialogInterface.OnCancelListener() {
3478 public void onCancel(DialogInterface dialog) {
3479 handler.cancel();
3480 BrowserActivity.this.resetTitleAndRevertLockIcon();
3481 }
3482 })
3483 .show();
3484 } else {
3485 handler.proceed();
3486 }
3487 }
3488
3489 /**
3490 * Handles an HTTP authentication request.
3491 *
3492 * @param handler The authentication handler
3493 * @param host The host
3494 * @param realm The realm
3495 */
3496 @Override
3497 public void onReceivedHttpAuthRequest(WebView view,
3498 final HttpAuthHandler handler, final String host, final String realm) {
3499 String username = null;
3500 String password = null;
3501
3502 boolean reuseHttpAuthUsernamePassword =
3503 handler.useHttpAuthUsernamePassword();
3504
3505 if (reuseHttpAuthUsernamePassword &&
3506 (mTabControl.getCurrentWebView() != null)) {
3507 String[] credentials =
3508 mTabControl.getCurrentWebView()
3509 .getHttpAuthUsernamePassword(host, realm);
3510 if (credentials != null && credentials.length == 2) {
3511 username = credentials[0];
3512 password = credentials[1];
3513 }
3514 }
3515
3516 if (username != null && password != null) {
3517 handler.proceed(username, password);
3518 } else {
3519 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3520 }
3521 }
3522
3523 @Override
3524 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3525 if (mMenuIsDown) {
3526 // only check shortcut key when MENU is held
3527 return getWindow().isShortcutKey(event.getKeyCode(), event);
3528 } else {
3529 return false;
3530 }
3531 }
3532
3533 @Override
3534 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3535 if (view != mTabControl.getCurrentTopWebView()) {
3536 return;
3537 }
3538 if (event.isDown()) {
3539 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3540 } else {
3541 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3542 }
3543 }
3544 };
3545
3546 //--------------------------------------------------------------------------
3547 // WebChromeClient implementation
3548 //--------------------------------------------------------------------------
3549
3550 /* package */ WebChromeClient getWebChromeClient() {
3551 return mWebChromeClient;
3552 }
3553
3554 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3555 // Helper method to create a new tab or sub window.
3556 private void createWindow(final boolean dialog, final Message msg) {
3557 if (dialog) {
3558 mTabControl.createSubWindow();
3559 final TabControl.Tab t = mTabControl.getCurrentTab();
3560 attachSubWindow(t);
3561 WebView.WebViewTransport transport =
3562 (WebView.WebViewTransport) msg.obj;
3563 transport.setWebView(t.getSubWebView());
3564 msg.sendToTarget();
3565 } else {
3566 final TabControl.Tab parent = mTabControl.getCurrentTab();
3567 // openTabAndShow will dispatch the message after creating the
3568 // new WebView. This will prevent another request from coming
3569 // in during the animation.
Patrick Scott1536e732009-06-11 14:50:01 -04003570 final TabControl.Tab newTab =
3571 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003572 if (newTab != parent) {
3573 parent.addChildTab(newTab);
3574 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003575 WebView.WebViewTransport transport =
3576 (WebView.WebViewTransport) msg.obj;
3577 transport.setWebView(mTabControl.getCurrentWebView());
3578 }
3579 }
3580
3581 @Override
3582 public boolean onCreateWindow(WebView view, final boolean dialog,
3583 final boolean userGesture, final Message resultMsg) {
3584 // Ignore these requests during tab animations or if the tab
3585 // overview is showing.
3586 if (mAnimationCount > 0 || mTabOverview != null) {
3587 return false;
3588 }
3589 // Short-circuit if we can't create any more tabs or sub windows.
3590 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3591 new AlertDialog.Builder(BrowserActivity.this)
3592 .setTitle(R.string.too_many_subwindows_dialog_title)
3593 .setIcon(android.R.drawable.ic_dialog_alert)
3594 .setMessage(R.string.too_many_subwindows_dialog_message)
3595 .setPositiveButton(R.string.ok, null)
3596 .show();
3597 return false;
3598 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3599 new AlertDialog.Builder(BrowserActivity.this)
3600 .setTitle(R.string.too_many_windows_dialog_title)
3601 .setIcon(android.R.drawable.ic_dialog_alert)
3602 .setMessage(R.string.too_many_windows_dialog_message)
3603 .setPositiveButton(R.string.ok, null)
3604 .show();
3605 return false;
3606 }
3607
3608 // Short-circuit if this was a user gesture.
3609 if (userGesture) {
3610 // createWindow will call openTabAndShow for new Windows and
3611 // that will call tabPicker which will increment
3612 // mAnimationCount.
3613 createWindow(dialog, resultMsg);
3614 return true;
3615 }
3616
3617 // Allow the popup and create the appropriate window.
3618 final AlertDialog.OnClickListener allowListener =
3619 new AlertDialog.OnClickListener() {
3620 public void onClick(DialogInterface d,
3621 int which) {
3622 // Same comment as above for setting
3623 // mAnimationCount.
3624 createWindow(dialog, resultMsg);
3625 // Since we incremented mAnimationCount while the
3626 // dialog was up, we have to decrement it here.
3627 mAnimationCount--;
3628 }
3629 };
3630
3631 // Block the popup by returning a null WebView.
3632 final AlertDialog.OnClickListener blockListener =
3633 new AlertDialog.OnClickListener() {
3634 public void onClick(DialogInterface d, int which) {
3635 resultMsg.sendToTarget();
3636 // We are not going to trigger an animation so
3637 // unblock keys and animation requests.
3638 mAnimationCount--;
3639 }
3640 };
3641
3642 // Build a confirmation dialog to display to the user.
3643 final AlertDialog d =
3644 new AlertDialog.Builder(BrowserActivity.this)
3645 .setTitle(R.string.attention)
3646 .setIcon(android.R.drawable.ic_dialog_alert)
3647 .setMessage(R.string.popup_window_attempt)
3648 .setPositiveButton(R.string.allow, allowListener)
3649 .setNegativeButton(R.string.block, blockListener)
3650 .setCancelable(false)
3651 .create();
3652
3653 // Show the confirmation dialog.
3654 d.show();
3655 // We want to increment mAnimationCount here to prevent a
3656 // potential race condition. If the user allows a pop-up from a
3657 // site and that pop-up then triggers another pop-up, it is
3658 // possible to get the BACK key between here and when the dialog
3659 // appears.
3660 mAnimationCount++;
3661 return true;
3662 }
3663
3664 @Override
3665 public void onCloseWindow(WebView window) {
3666 final int currentIndex = mTabControl.getCurrentIndex();
3667 final TabControl.Tab parent =
3668 mTabControl.getCurrentTab().getParentTab();
3669 if (parent != null) {
3670 // JavaScript can only close popup window.
3671 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3672 }
3673 }
3674
3675 @Override
3676 public void onProgressChanged(WebView view, int newProgress) {
3677 // Block progress updates to the title bar while the tab overview
3678 // is animating or being displayed.
3679 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003680 if (CUSTOM_BROWSER_BAR) {
3681 mTitleBar.setProgress(newProgress);
3682 } else {
3683 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3684 newProgress * 100);
3685
3686 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003687 }
3688
3689 if (newProgress == 100) {
3690 // onProgressChanged() is called for sub-frame too while
3691 // onPageFinished() is only called for the main frame. sync
3692 // cookie and cache promptly here.
3693 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003694 if (mInLoad) {
3695 mInLoad = false;
3696 updateInLoadMenuItems();
3697 }
3698 } else {
3699 // onPageFinished may have already been called but a subframe
3700 // is still loading and updating the progress. Reset mInLoad
3701 // and update the menu items.
3702 if (!mInLoad) {
3703 mInLoad = true;
3704 updateInLoadMenuItems();
3705 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003706 }
3707 }
3708
3709 @Override
3710 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003711 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003712
3713 // here, if url is null, we want to reset the title
3714 setUrlTitle(url, title);
3715
3716 if (url == null ||
3717 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3718 return;
3719 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003720 // See if we can find the current url in our history database and
3721 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003722 if (url.startsWith("http://www.")) {
3723 url = url.substring(11);
3724 } else if (url.startsWith("http://")) {
3725 url = url.substring(4);
3726 }
3727 try {
3728 url = "%" + url;
3729 String [] selArgs = new String[] { url };
3730
3731 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3732 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3733 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3734 Browser.HISTORY_PROJECTION, where, selArgs, null);
3735 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003736 // Current implementation of database only has one entry per
3737 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003738 ContentValues map = new ContentValues();
3739 map.put(Browser.BookmarkColumns.TITLE, title);
3740 mResolver.update(Browser.BOOKMARKS_URI, map,
3741 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003742 }
3743 c.close();
3744 } catch (IllegalStateException e) {
3745 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3746 } catch (SQLiteException ex) {
3747 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3748 }
3749 }
3750
3751 @Override
3752 public void onReceivedIcon(WebView view, Bitmap icon) {
3753 updateIcon(view.getUrl(), icon);
3754 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003755
Andrei Popescuadc008d2009-06-26 14:11:30 +01003756 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003757 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003758 if (mCustomView != null)
3759 return;
3760
3761 // Add the custom view to its container.
3762 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3763 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003764 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003765 // Save the menu state and set it to empty while the custom
3766 // view is showing.
3767 mOldMenuState = mMenuState;
3768 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003769 // Hide the content view.
3770 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003771 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003772 mCustomViewContainer.setVisibility(View.VISIBLE);
3773 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003774 }
3775
3776 @Override
3777 public void onHideCustomView() {
3778 if (mCustomView == null)
3779 return;
3780
Andrei Popescuc9b55562009-07-07 10:51:15 +01003781 // Hide the custom view.
3782 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003783 // Remove the custom view from its container.
3784 mCustomViewContainer.removeView(mCustomView);
3785 mCustomView = null;
3786 // Reset the old menu state.
3787 mMenuState = mOldMenuState;
3788 mOldMenuState = EMPTY_MENU;
3789 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003790 mCustomViewCallback.onCustomViewHidden();
3791 // Show the content view.
3792 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003793 }
3794
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003795 /**
3796 * The origin has exceeded it's database quota.
3797 * @param url the URL that exceeded the quota
3798 * @param databaseIdentifier the identifier of the database on
3799 * which the transaction that caused the quota overflow was run
3800 * @param currentQuota the current quota for the origin.
3801 * @param quotaUpdater The callback to run when a decision to allow or
3802 * deny quota has been made. Don't forget to call this!
3803 */
3804 @Override
3805 public void onExceededDatabaseQuota(String url,
3806 String databaseIdentifier, long currentQuota,
3807 WebStorage.QuotaUpdater quotaUpdater) {
3808 if(LOGV_ENABLED) {
3809 Log.v(LOGTAG,
3810 "BrowserActivity received onExceededDatabaseQuota for "
3811 + url +
3812 ":"
3813 + databaseIdentifier +
3814 "(current quota: "
3815 + currentQuota +
3816 ")");
3817 }
Nicolas Roard78a98e42009-05-11 13:34:17 +01003818 mWebStorageQuotaUpdater = quotaUpdater;
3819 String DIALOG_PACKAGE = "com.android.browser";
3820 String DIALOG_CLASS = DIALOG_PACKAGE + ".PermissionDialog";
3821 Intent intent = new Intent();
3822 intent.setClassName(DIALOG_PACKAGE, DIALOG_CLASS);
3823 intent.putExtra(PermissionDialog.PARAM_ORIGIN, url);
3824 intent.putExtra(PermissionDialog.PARAM_QUOTA, currentQuota);
3825 startActivityForResult(intent, WEBSTORAGE_QUOTA_DIALOG);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003826 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003827
3828 /* Adds a JavaScript error message to the system log.
3829 * @param message The error message to report.
3830 * @param lineNumber The line number of the error.
3831 * @param sourceID The name of the source file that caused the error.
3832 */
3833 @Override
3834 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3835 Log.w(LOGTAG, "Console: " + message + " (" + sourceID + ":" + lineNumber + ")");
3836 }
3837
The Android Open Source Project0c908882009-03-03 19:32:16 -08003838 };
3839
3840 /**
3841 * Notify the host application a download should be done, or that
3842 * the data should be streamed if a streaming viewer is available.
3843 * @param url The full url to the content that should be downloaded
3844 * @param contentDisposition Content-disposition http header, if
3845 * present.
3846 * @param mimetype The mimetype of the content reported by the server
3847 * @param contentLength The file size reported by the server
3848 */
3849 public void onDownloadStart(String url, String userAgent,
3850 String contentDisposition, String mimetype, long contentLength) {
3851 // if we're dealing wih A/V content that's not explicitly marked
3852 // for download, check if it's streamable.
3853 if (contentDisposition == null
3854 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3855 // query the package manager to see if there's a registered handler
3856 // that matches.
3857 Intent intent = new Intent(Intent.ACTION_VIEW);
3858 intent.setDataAndType(Uri.parse(url), mimetype);
3859 if (getPackageManager().resolveActivity(intent,
3860 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3861 // someone knows how to handle this mime type with this scheme, don't download.
3862 try {
3863 startActivity(intent);
3864 return;
3865 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003866 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003867 Log.d(LOGTAG, "activity not found for " + mimetype
3868 + " over " + Uri.parse(url).getScheme(), ex);
3869 }
3870 // Best behavior is to fall back to a download in this case
3871 }
3872 }
3873 }
3874 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3875 }
3876
3877 /**
3878 * Notify the host application a download should be done, even if there
3879 * is a streaming viewer available for thise type.
3880 * @param url The full url to the content that should be downloaded
3881 * @param contentDisposition Content-disposition http header, if
3882 * present.
3883 * @param mimetype The mimetype of the content reported by the server
3884 * @param contentLength The file size reported by the server
3885 */
3886 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3887 String contentDisposition, String mimetype, long contentLength) {
3888
3889 String filename = URLUtil.guessFileName(url,
3890 contentDisposition, mimetype);
3891
3892 // Check to see if we have an SDCard
3893 String status = Environment.getExternalStorageState();
3894 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3895 int title;
3896 String msg;
3897
3898 // Check to see if the SDCard is busy, same as the music app
3899 if (status.equals(Environment.MEDIA_SHARED)) {
3900 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3901 title = R.string.download_sdcard_busy_dlg_title;
3902 } else {
3903 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3904 title = R.string.download_no_sdcard_dlg_title;
3905 }
3906
3907 new AlertDialog.Builder(this)
3908 .setTitle(title)
3909 .setIcon(android.R.drawable.ic_dialog_alert)
3910 .setMessage(msg)
3911 .setPositiveButton(R.string.ok, null)
3912 .show();
3913 return;
3914 }
3915
3916 // java.net.URI is a lot stricter than KURL so we have to undo
3917 // KURL's percent-encoding and redo the encoding using java.net.URI.
3918 URI uri = null;
3919 try {
3920 // Undo the percent-encoding that KURL may have done.
3921 String newUrl = new String(URLUtil.decode(url.getBytes()));
3922 // Parse the url into pieces
3923 WebAddress w = new WebAddress(newUrl);
3924 String frag = null;
3925 String query = null;
3926 String path = w.mPath;
3927 // Break the path into path, query, and fragment
3928 if (path.length() > 0) {
3929 // Strip the fragment
3930 int idx = path.lastIndexOf('#');
3931 if (idx != -1) {
3932 frag = path.substring(idx + 1);
3933 path = path.substring(0, idx);
3934 }
3935 idx = path.lastIndexOf('?');
3936 if (idx != -1) {
3937 query = path.substring(idx + 1);
3938 path = path.substring(0, idx);
3939 }
3940 }
3941 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3942 query, frag);
3943 } catch (Exception e) {
3944 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3945 return;
3946 }
3947
3948 // XXX: Have to use the old url since the cookies were stored using the
3949 // old percent-encoded url.
3950 String cookies = CookieManager.getInstance().getCookie(url);
3951
3952 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003953 values.put(Downloads.COLUMN_URI, uri.toString());
3954 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3955 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3956 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003957 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003958 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003959 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003960 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3961 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3962 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3963 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003964 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003965 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003966 }
3967 if (mimetype == null) {
3968 // We must have long pressed on a link or image to download it. We
3969 // are not sure of the mimetype in this case, so do a head request
3970 new FetchUrlMimeType(this).execute(values);
3971 } else {
3972 final Uri contentUri =
3973 getContentResolver().insert(Downloads.CONTENT_URI, values);
3974 viewDownloads(contentUri);
3975 }
3976
3977 }
3978
3979 /**
3980 * Resets the lock icon. This method is called when we start a new load and
3981 * know the url to be loaded.
3982 */
3983 private void resetLockIcon(String url) {
3984 // Save the lock-icon state (we revert to it if the load gets cancelled)
3985 saveLockIcon();
3986
3987 mLockIconType = LOCK_ICON_UNSECURE;
3988 if (URLUtil.isHttpsUrl(url)) {
3989 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003990 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003991 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3992 " reset lock icon to " + mLockIconType);
3993 }
3994 }
3995
3996 updateLockIconImage(LOCK_ICON_UNSECURE);
3997 }
3998
3999 /**
4000 * Resets the lock icon. This method is called when the icon needs to be
4001 * reset but we do not know whether we are loading a secure or not secure
4002 * page.
4003 */
4004 private void resetLockIcon() {
4005 // Save the lock-icon state (we revert to it if the load gets cancelled)
4006 saveLockIcon();
4007
4008 mLockIconType = LOCK_ICON_UNSECURE;
4009
Dave Bort31a6d1c2009-04-13 15:56:49 -07004010 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004011 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4012 " reset lock icon to " + mLockIconType);
4013 }
4014
4015 updateLockIconImage(LOCK_ICON_UNSECURE);
4016 }
4017
4018 /**
4019 * Updates the lock-icon image in the title-bar.
4020 */
4021 private void updateLockIconImage(int lockIconType) {
4022 Drawable d = null;
4023 if (lockIconType == LOCK_ICON_SECURE) {
4024 d = mSecLockIcon;
4025 } else if (lockIconType == LOCK_ICON_MIXED) {
4026 d = mMixLockIcon;
4027 }
4028 // If the tab overview is animating or being shown, do not update the
4029 // lock icon.
4030 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04004031 if (CUSTOM_BROWSER_BAR) {
4032 mTitleBar.setLock(d);
4033 } else {
4034 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
4035 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004036 }
4037 }
4038
4039 /**
4040 * Displays a page-info dialog.
4041 * @param tab The tab to show info about
4042 * @param fromShowSSLCertificateOnError The flag that indicates whether
4043 * this dialog was opened from the SSL-certificate-on-error dialog or
4044 * not. This is important, since we need to know whether to return to
4045 * the parent dialog or simply dismiss.
4046 */
4047 private void showPageInfo(final TabControl.Tab tab,
4048 final boolean fromShowSSLCertificateOnError) {
4049 final LayoutInflater factory = LayoutInflater
4050 .from(this);
4051
4052 final View pageInfoView = factory.inflate(R.layout.page_info, null);
4053
4054 final WebView view = tab.getWebView();
4055
4056 String url = null;
4057 String title = null;
4058
4059 if (view == null) {
4060 url = tab.getUrl();
4061 title = tab.getTitle();
4062 } else if (view == mTabControl.getCurrentWebView()) {
4063 // Use the cached title and url if this is the current WebView
4064 url = mUrl;
4065 title = mTitle;
4066 } else {
4067 url = view.getUrl();
4068 title = view.getTitle();
4069 }
4070
4071 if (url == null) {
4072 url = "";
4073 }
4074 if (title == null) {
4075 title = "";
4076 }
4077
4078 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
4079 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
4080
4081 mPageInfoView = tab;
4082 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
4083
4084 AlertDialog.Builder alertDialogBuilder =
4085 new AlertDialog.Builder(this)
4086 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
4087 .setView(pageInfoView)
4088 .setPositiveButton(
4089 R.string.ok,
4090 new DialogInterface.OnClickListener() {
4091 public void onClick(DialogInterface dialog,
4092 int whichButton) {
4093 mPageInfoDialog = null;
4094 mPageInfoView = null;
4095 mPageInfoFromShowSSLCertificateOnError = null;
4096
4097 // if we came here from the SSL error dialog
4098 if (fromShowSSLCertificateOnError) {
4099 // go back to the SSL error dialog
4100 showSSLCertificateOnError(
4101 mSSLCertificateOnErrorView,
4102 mSSLCertificateOnErrorHandler,
4103 mSSLCertificateOnErrorError);
4104 }
4105 }
4106 })
4107 .setOnCancelListener(
4108 new DialogInterface.OnCancelListener() {
4109 public void onCancel(DialogInterface dialog) {
4110 mPageInfoDialog = null;
4111 mPageInfoView = null;
4112 mPageInfoFromShowSSLCertificateOnError = null;
4113
4114 // if we came here from the SSL error dialog
4115 if (fromShowSSLCertificateOnError) {
4116 // go back to the SSL error dialog
4117 showSSLCertificateOnError(
4118 mSSLCertificateOnErrorView,
4119 mSSLCertificateOnErrorHandler,
4120 mSSLCertificateOnErrorError);
4121 }
4122 }
4123 });
4124
4125 // if we have a main top-level page SSL certificate set or a certificate
4126 // error
4127 if (fromShowSSLCertificateOnError ||
4128 (view != null && view.getCertificate() != null)) {
4129 // add a 'View Certificate' button
4130 alertDialogBuilder.setNeutralButton(
4131 R.string.view_certificate,
4132 new DialogInterface.OnClickListener() {
4133 public void onClick(DialogInterface dialog,
4134 int whichButton) {
4135 mPageInfoDialog = null;
4136 mPageInfoView = null;
4137 mPageInfoFromShowSSLCertificateOnError = null;
4138
4139 // if we came here from the SSL error dialog
4140 if (fromShowSSLCertificateOnError) {
4141 // go back to the SSL error dialog
4142 showSSLCertificateOnError(
4143 mSSLCertificateOnErrorView,
4144 mSSLCertificateOnErrorHandler,
4145 mSSLCertificateOnErrorError);
4146 } else {
4147 // otherwise, display the top-most certificate from
4148 // the chain
4149 if (view.getCertificate() != null) {
4150 showSSLCertificate(tab);
4151 }
4152 }
4153 }
4154 });
4155 }
4156
4157 mPageInfoDialog = alertDialogBuilder.show();
4158 }
4159
4160 /**
4161 * Displays the main top-level page SSL certificate dialog
4162 * (accessible from the Page-Info dialog).
4163 * @param tab The tab to show certificate for.
4164 */
4165 private void showSSLCertificate(final TabControl.Tab tab) {
4166 final View certificateView =
4167 inflateCertificateView(tab.getWebView().getCertificate());
4168 if (certificateView == null) {
4169 return;
4170 }
4171
4172 LayoutInflater factory = LayoutInflater.from(this);
4173
4174 final LinearLayout placeholder =
4175 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4176
4177 LinearLayout ll = (LinearLayout) factory.inflate(
4178 R.layout.ssl_success, placeholder);
4179 ((TextView)ll.findViewById(R.id.success))
4180 .setText(R.string.ssl_certificate_is_valid);
4181
4182 mSSLCertificateView = tab;
4183 mSSLCertificateDialog =
4184 new AlertDialog.Builder(this)
4185 .setTitle(R.string.ssl_certificate).setIcon(
4186 R.drawable.ic_dialog_browser_certificate_secure)
4187 .setView(certificateView)
4188 .setPositiveButton(R.string.ok,
4189 new DialogInterface.OnClickListener() {
4190 public void onClick(DialogInterface dialog,
4191 int whichButton) {
4192 mSSLCertificateDialog = null;
4193 mSSLCertificateView = null;
4194
4195 showPageInfo(tab, false);
4196 }
4197 })
4198 .setOnCancelListener(
4199 new DialogInterface.OnCancelListener() {
4200 public void onCancel(DialogInterface dialog) {
4201 mSSLCertificateDialog = null;
4202 mSSLCertificateView = null;
4203
4204 showPageInfo(tab, false);
4205 }
4206 })
4207 .show();
4208 }
4209
4210 /**
4211 * Displays the SSL error certificate dialog.
4212 * @param view The target web-view.
4213 * @param handler The SSL error handler responsible for cancelling the
4214 * connection that resulted in an SSL error or proceeding per user request.
4215 * @param error The SSL error object.
4216 */
4217 private void showSSLCertificateOnError(
4218 final WebView view, final SslErrorHandler handler, final SslError error) {
4219
4220 final View certificateView =
4221 inflateCertificateView(error.getCertificate());
4222 if (certificateView == null) {
4223 return;
4224 }
4225
4226 LayoutInflater factory = LayoutInflater.from(this);
4227
4228 final LinearLayout placeholder =
4229 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4230
4231 if (error.hasError(SslError.SSL_UNTRUSTED)) {
4232 LinearLayout ll = (LinearLayout)factory
4233 .inflate(R.layout.ssl_warning, placeholder);
4234 ((TextView)ll.findViewById(R.id.warning))
4235 .setText(R.string.ssl_untrusted);
4236 }
4237
4238 if (error.hasError(SslError.SSL_IDMISMATCH)) {
4239 LinearLayout ll = (LinearLayout)factory
4240 .inflate(R.layout.ssl_warning, placeholder);
4241 ((TextView)ll.findViewById(R.id.warning))
4242 .setText(R.string.ssl_mismatch);
4243 }
4244
4245 if (error.hasError(SslError.SSL_EXPIRED)) {
4246 LinearLayout ll = (LinearLayout)factory
4247 .inflate(R.layout.ssl_warning, placeholder);
4248 ((TextView)ll.findViewById(R.id.warning))
4249 .setText(R.string.ssl_expired);
4250 }
4251
4252 if (error.hasError(SslError.SSL_NOTYETVALID)) {
4253 LinearLayout ll = (LinearLayout)factory
4254 .inflate(R.layout.ssl_warning, placeholder);
4255 ((TextView)ll.findViewById(R.id.warning))
4256 .setText(R.string.ssl_not_yet_valid);
4257 }
4258
4259 mSSLCertificateOnErrorHandler = handler;
4260 mSSLCertificateOnErrorView = view;
4261 mSSLCertificateOnErrorError = error;
4262 mSSLCertificateOnErrorDialog =
4263 new AlertDialog.Builder(this)
4264 .setTitle(R.string.ssl_certificate).setIcon(
4265 R.drawable.ic_dialog_browser_certificate_partially_secure)
4266 .setView(certificateView)
4267 .setPositiveButton(R.string.ok,
4268 new DialogInterface.OnClickListener() {
4269 public void onClick(DialogInterface dialog,
4270 int whichButton) {
4271 mSSLCertificateOnErrorDialog = null;
4272 mSSLCertificateOnErrorView = null;
4273 mSSLCertificateOnErrorHandler = null;
4274 mSSLCertificateOnErrorError = null;
4275
4276 mWebViewClient.onReceivedSslError(
4277 view, handler, error);
4278 }
4279 })
4280 .setNeutralButton(R.string.page_info_view,
4281 new DialogInterface.OnClickListener() {
4282 public void onClick(DialogInterface dialog,
4283 int whichButton) {
4284 mSSLCertificateOnErrorDialog = null;
4285
4286 // do not clear the dialog state: we will
4287 // need to show the dialog again once the
4288 // user is done exploring the page-info details
4289
4290 showPageInfo(mTabControl.getTabFromView(view),
4291 true);
4292 }
4293 })
4294 .setOnCancelListener(
4295 new DialogInterface.OnCancelListener() {
4296 public void onCancel(DialogInterface dialog) {
4297 mSSLCertificateOnErrorDialog = null;
4298 mSSLCertificateOnErrorView = null;
4299 mSSLCertificateOnErrorHandler = null;
4300 mSSLCertificateOnErrorError = null;
4301
4302 mWebViewClient.onReceivedSslError(
4303 view, handler, error);
4304 }
4305 })
4306 .show();
4307 }
4308
4309 /**
4310 * Inflates the SSL certificate view (helper method).
4311 * @param certificate The SSL certificate.
4312 * @return The resultant certificate view with issued-to, issued-by,
4313 * issued-on, expires-on, and possibly other fields set.
4314 * If the input certificate is null, returns null.
4315 */
4316 private View inflateCertificateView(SslCertificate certificate) {
4317 if (certificate == null) {
4318 return null;
4319 }
4320
4321 LayoutInflater factory = LayoutInflater.from(this);
4322
4323 View certificateView = factory.inflate(
4324 R.layout.ssl_certificate, null);
4325
4326 // issued to:
4327 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4328 if (issuedTo != null) {
4329 ((TextView) certificateView.findViewById(R.id.to_common))
4330 .setText(issuedTo.getCName());
4331 ((TextView) certificateView.findViewById(R.id.to_org))
4332 .setText(issuedTo.getOName());
4333 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4334 .setText(issuedTo.getUName());
4335 }
4336
4337 // issued by:
4338 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4339 if (issuedBy != null) {
4340 ((TextView) certificateView.findViewById(R.id.by_common))
4341 .setText(issuedBy.getCName());
4342 ((TextView) certificateView.findViewById(R.id.by_org))
4343 .setText(issuedBy.getOName());
4344 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4345 .setText(issuedBy.getUName());
4346 }
4347
4348 // issued on:
4349 String issuedOn = reformatCertificateDate(
4350 certificate.getValidNotBefore());
4351 ((TextView) certificateView.findViewById(R.id.issued_on))
4352 .setText(issuedOn);
4353
4354 // expires on:
4355 String expiresOn = reformatCertificateDate(
4356 certificate.getValidNotAfter());
4357 ((TextView) certificateView.findViewById(R.id.expires_on))
4358 .setText(expiresOn);
4359
4360 return certificateView;
4361 }
4362
4363 /**
4364 * Re-formats the certificate date (Date.toString()) string to
4365 * a properly localized date string.
4366 * @return Properly localized version of the certificate date string and
4367 * the original certificate date string if fails to localize.
4368 * If the original string is null, returns an empty string "".
4369 */
4370 private String reformatCertificateDate(String certificateDate) {
4371 String reformattedDate = null;
4372
4373 if (certificateDate != null) {
4374 Date date = null;
4375 try {
4376 date = java.text.DateFormat.getInstance().parse(certificateDate);
4377 } catch (ParseException e) {
4378 date = null;
4379 }
4380
4381 if (date != null) {
4382 reformattedDate =
4383 DateFormat.getDateFormat(this).format(date);
4384 }
4385 }
4386
4387 return reformattedDate != null ? reformattedDate :
4388 (certificateDate != null ? certificateDate : "");
4389 }
4390
4391 /**
4392 * Displays an http-authentication dialog.
4393 */
4394 private void showHttpAuthentication(final HttpAuthHandler handler,
4395 final String host, final String realm, final String title,
4396 final String name, final String password, int focusId) {
4397 LayoutInflater factory = LayoutInflater.from(this);
4398 final View v = factory
4399 .inflate(R.layout.http_authentication, null);
4400 if (name != null) {
4401 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4402 }
4403 if (password != null) {
4404 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4405 }
4406
4407 String titleText = title;
4408 if (titleText == null) {
4409 titleText = getText(R.string.sign_in_to).toString().replace(
4410 "%s1", host).replace("%s2", realm);
4411 }
4412
4413 mHttpAuthHandler = handler;
4414 AlertDialog dialog = new AlertDialog.Builder(this)
4415 .setTitle(titleText)
4416 .setIcon(android.R.drawable.ic_dialog_alert)
4417 .setView(v)
4418 .setPositiveButton(R.string.action,
4419 new DialogInterface.OnClickListener() {
4420 public void onClick(DialogInterface dialog,
4421 int whichButton) {
4422 String nm = ((EditText) v
4423 .findViewById(R.id.username_edit))
4424 .getText().toString();
4425 String pw = ((EditText) v
4426 .findViewById(R.id.password_edit))
4427 .getText().toString();
4428 BrowserActivity.this.setHttpAuthUsernamePassword
4429 (host, realm, nm, pw);
4430 handler.proceed(nm, pw);
4431 mHttpAuthenticationDialog = null;
4432 mHttpAuthHandler = null;
4433 }})
4434 .setNegativeButton(R.string.cancel,
4435 new DialogInterface.OnClickListener() {
4436 public void onClick(DialogInterface dialog,
4437 int whichButton) {
4438 handler.cancel();
4439 BrowserActivity.this.resetTitleAndRevertLockIcon();
4440 mHttpAuthenticationDialog = null;
4441 mHttpAuthHandler = null;
4442 }})
4443 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4444 public void onCancel(DialogInterface dialog) {
4445 handler.cancel();
4446 BrowserActivity.this.resetTitleAndRevertLockIcon();
4447 mHttpAuthenticationDialog = null;
4448 mHttpAuthHandler = null;
4449 }})
4450 .create();
4451 // Make the IME appear when the dialog is displayed if applicable.
4452 dialog.getWindow().setSoftInputMode(
4453 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4454 dialog.show();
4455 if (focusId != 0) {
4456 dialog.findViewById(focusId).requestFocus();
4457 } else {
4458 v.findViewById(R.id.username_edit).requestFocus();
4459 }
4460 mHttpAuthenticationDialog = dialog;
4461 }
4462
4463 public int getProgress() {
4464 WebView w = mTabControl.getCurrentWebView();
4465 if (w != null) {
4466 return w.getProgress();
4467 } else {
4468 return 100;
4469 }
4470 }
4471
4472 /**
4473 * Set HTTP authentication password.
4474 *
4475 * @param host The host for the password
4476 * @param realm The realm for the password
4477 * @param username The username for the password. If it is null, it means
4478 * password can't be saved.
4479 * @param password The password
4480 */
4481 public void setHttpAuthUsernamePassword(String host, String realm,
4482 String username,
4483 String password) {
4484 WebView w = mTabControl.getCurrentWebView();
4485 if (w != null) {
4486 w.setHttpAuthUsernamePassword(host, realm, username, password);
4487 }
4488 }
4489
4490 /**
4491 * connectivity manager says net has come or gone... inform the user
4492 * @param up true if net has come up, false if net has gone down
4493 */
4494 public void onNetworkToggle(boolean up) {
4495 if (up == mIsNetworkUp) {
4496 return;
4497 } else if (up) {
4498 mIsNetworkUp = true;
4499 if (mAlertDialog != null) {
4500 mAlertDialog.cancel();
4501 mAlertDialog = null;
4502 }
4503 } else {
4504 mIsNetworkUp = false;
4505 if (mInLoad && mAlertDialog == null) {
4506 mAlertDialog = new AlertDialog.Builder(this)
4507 .setTitle(R.string.loadSuspendedTitle)
4508 .setMessage(R.string.loadSuspended)
4509 .setPositiveButton(R.string.ok, null)
4510 .show();
4511 }
4512 }
4513 WebView w = mTabControl.getCurrentWebView();
4514 if (w != null) {
4515 w.setNetworkAvailable(up);
4516 }
4517 }
4518
4519 @Override
4520 protected void onActivityResult(int requestCode, int resultCode,
4521 Intent intent) {
4522 switch (requestCode) {
4523 case COMBO_PAGE:
4524 if (resultCode == RESULT_OK && intent != null) {
4525 String data = intent.getAction();
4526 Bundle extras = intent.getExtras();
4527 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04004528 final TabControl.Tab newTab = openTab(data);
4529 if (mSettings.openInBackground() &&
4530 newTab != null && mTabOverview != null) {
4531 mTabControl.populatePickerData(newTab);
4532 mTabControl.setCurrentTab(newTab);
4533 mTabOverview.add(newTab);
4534 mTabOverview.setCurrentIndex(
4535 mTabControl.getCurrentIndex());
4536 sendAnimateFromOverview(newTab, false,
4537 EMPTY_URL_DATA, TAB_OVERVIEW_DELAY, null);
4538 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004539 } else {
4540 final TabControl.Tab currentTab =
4541 mTabControl.getCurrentTab();
4542 // If the Window overview is up and we are not in the
4543 // middle of an animation, animate away from it to the
4544 // current tab.
4545 if (mTabOverview != null && mAnimationCount == 0) {
Grace Klobaec7eb372009-06-16 13:45:56 -07004546 sendAnimateFromOverview(currentTab, false,
4547 new UrlData(data), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004548 } else {
4549 dismissSubWindow(currentTab);
4550 if (data != null && data.length() != 0) {
4551 getTopWindow().loadUrl(data);
4552 }
4553 }
4554 }
4555 }
4556 break;
Nicolas Roard78a98e42009-05-11 13:34:17 +01004557 case WEBSTORAGE_QUOTA_DIALOG:
4558 long currentQuota = 0;
4559 if (resultCode == RESULT_OK && intent != null) {
4560 currentQuota = intent.getLongExtra(
4561 PermissionDialog.PARAM_QUOTA, currentQuota);
4562 }
4563 mWebStorageQuotaUpdater.updateQuota(currentQuota);
4564 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004565 default:
4566 break;
4567 }
4568 getTopWindow().requestFocus();
4569 }
4570
4571 /*
4572 * This method is called as a result of the user selecting the options
4573 * menu to see the download window, or when a download changes state. It
4574 * shows the download window ontop of the current window.
4575 */
4576 /* package */ void viewDownloads(Uri downloadRecord) {
4577 Intent intent = new Intent(this,
4578 BrowserDownloadPage.class);
4579 intent.setData(downloadRecord);
4580 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4581
4582 }
4583
4584 /**
4585 * Handle results from Tab Switcher mTabOverview tool
4586 */
4587 private class TabListener implements ImageGrid.Listener {
4588 public void remove(int position) {
4589 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004590 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004591 throw new AssertionError();
4592 }
4593
4594 // Remember the current tab.
4595 TabControl.Tab current = mTabControl.getCurrentTab();
4596 final TabControl.Tab remove = mTabControl.getTab(position);
4597 mTabControl.removeTab(remove);
4598 // If we removed the current tab, use the tab at position - 1 if
4599 // possible.
4600 if (current == remove) {
4601 // If the user removes the last tab, act like the New Tab item
4602 // was clicked on.
4603 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004604 current = mTabControl.createNewTab();
Grace Klobaec7eb372009-06-16 13:45:56 -07004605 sendAnimateFromOverview(current, true, new UrlData(
4606 mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004607 } else {
4608 final int index = position > 0 ? (position - 1) : 0;
4609 current = mTabControl.getTab(index);
4610 }
4611 }
4612
4613 // The tab overview could have been dismissed before this method is
4614 // called.
4615 if (mTabOverview != null) {
4616 // Remove the tab and change the index.
4617 mTabOverview.remove(position);
4618 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4619 }
4620
4621 // Only the current tab ensures its WebView is non-null. This
4622 // implies that we are reloading the freed tab.
4623 mTabControl.setCurrentTab(current);
4624 }
4625 public void onClick(int index) {
4626 // Change the tab if necessary.
4627 // Index equals ImageGrid.CANCEL when pressing back from the tab
4628 // overview.
4629 if (index == ImageGrid.CANCEL) {
4630 index = mTabControl.getCurrentIndex();
4631 // The current index is -1 if the current tab was removed.
4632 if (index == -1) {
4633 // Take the last tab as a fallback.
4634 index = mTabControl.getTabCount() - 1;
4635 }
4636 }
4637
The Android Open Source Project0c908882009-03-03 19:32:16 -08004638 // NEW_TAB means that the "New Tab" cell was clicked on.
4639 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004640 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004641 } else {
Grace Klobaec7eb372009-06-16 13:45:56 -07004642 sendAnimateFromOverview(mTabControl.getTab(index), false,
4643 EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004644 }
4645 }
4646 }
4647
4648 // A fake View that draws the WebView's picture with a fast zoom filter.
4649 // The View is used in case the tab is freed during the animation because
4650 // of low memory.
4651 private static class AnimatingView extends View {
4652 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4653 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4654 private static final DrawFilter sZoomFilter =
4655 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4656 private final Picture mPicture;
4657 private final float mScale;
4658 private final int mScrollX;
4659 private final int mScrollY;
4660 final TabControl.Tab mTab;
4661
4662 AnimatingView(Context ctxt, TabControl.Tab t) {
4663 super(ctxt);
4664 mTab = t;
Patrick Scottae641ac2009-04-20 13:51:49 -04004665 if (t != null && t.getTopWindow() != null) {
4666 // Use the top window in the animation since the tab overview
4667 // will display the top window in each cell.
4668 final WebView w = t.getTopWindow();
4669 mPicture = w.capturePicture();
4670 mScale = w.getScale() / w.getWidth();
4671 mScrollX = w.getScrollX();
4672 mScrollY = w.getScrollY();
4673 } else {
4674 mPicture = null;
4675 mScale = 1.0f;
4676 mScrollX = mScrollY = 0;
4677 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004678 }
4679
4680 @Override
4681 protected void onDraw(Canvas canvas) {
4682 canvas.save();
4683 canvas.drawColor(Color.WHITE);
4684 if (mPicture != null) {
4685 canvas.setDrawFilter(sZoomFilter);
4686 float scale = getWidth() * mScale;
4687 canvas.scale(scale, scale);
4688 canvas.translate(-mScrollX, -mScrollY);
4689 canvas.drawPicture(mPicture);
4690 }
4691 canvas.restore();
4692 }
4693 }
4694
4695 /**
4696 * Open the tab picker. This function will always use the current tab in
4697 * its animation.
4698 * @param stay boolean stating whether the tab picker is to remain open
4699 * (in which case it needs a listener and its menu) or not.
4700 * @param index The index of the tab to show as the selection in the tab
4701 * overview.
4702 * @param remove If true, the tab at index will be removed after the
4703 * animation completes.
4704 */
4705 private void tabPicker(final boolean stay, final int index,
4706 final boolean remove) {
4707 if (mTabOverview != null) {
4708 return;
4709 }
4710
4711 int size = mTabControl.getTabCount();
4712
4713 TabListener l = null;
4714 if (stay) {
4715 l = mTabListener = new TabListener();
4716 }
4717 mTabOverview = new ImageGrid(this, stay, l);
4718
4719 for (int i = 0; i < size; i++) {
4720 final TabControl.Tab t = mTabControl.getTab(i);
4721 mTabControl.populatePickerData(t);
4722 mTabOverview.add(t);
4723 }
4724
4725 // Tell the tab overview to show the current tab, the tab overview will
4726 // handle the "New Tab" case.
4727 int currentIndex = mTabControl.getCurrentIndex();
4728 mTabOverview.setCurrentIndex(currentIndex);
4729
4730 // Attach the tab overview.
4731 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4732
4733 // Create a fake AnimatingView to animate the WebView's picture.
4734 final TabControl.Tab current = mTabControl.getCurrentTab();
4735 final AnimatingView v = new AnimatingView(this, current);
4736 mContentView.addView(v, COVER_SCREEN_PARAMS);
4737 removeTabFromContentView(current);
4738 // Pause timers to get the animation smoother.
4739 current.getWebView().pauseTimers();
4740
4741 // Send a message so the tab picker has a chance to layout and get
4742 // positions for all the cells.
4743 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4744 index, remove ? 1 : 0, v));
4745 // Setting this will indicate that we are animating to the overview. We
4746 // set it here to prevent another request to animate from coming in
4747 // between now and when ANIMATE_TO_OVERVIEW is handled.
4748 mAnimationCount++;
4749 // Always change the title bar to the window overview title while
4750 // animating.
Leon Scroggins81db3662009-06-04 17:45:11 -04004751 if (CUSTOM_BROWSER_BAR) {
4752 mTitleBar.setToTabPicker();
4753 } else {
4754 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4755 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4756 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4757 Window.PROGRESS_VISIBILITY_OFF);
4758 setTitle(R.string.tab_picker_title);
4759 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004760 // Make the menu empty until the animation completes.
4761 mMenuState = EMPTY_MENU;
4762 }
4763
Leon Scrogginse4b3bda2009-06-09 15:46:41 -04004764 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004765 WebView current = mTabControl.getCurrentWebView();
4766 if (current == null) {
4767 return;
4768 }
4769 Intent intent = new Intent(this,
4770 CombinedBookmarkHistoryActivity.class);
4771 String title = current.getTitle();
4772 String url = current.getUrl();
4773 // Just in case the user opens bookmarks before a page finishes loading
4774 // so the current history item, and therefore the page, is null.
4775 if (null == url) {
4776 url = mLastEnteredUrl;
4777 // This can happen.
4778 if (null == url) {
4779 url = mSettings.getHomePage();
4780 }
4781 }
4782 // In case the web page has not yet received its associated title.
4783 if (title == null) {
4784 title = url;
4785 }
4786 intent.putExtra("title", title);
4787 intent.putExtra("url", url);
4788 intent.putExtra("maxTabsOpen",
4789 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4790 if (startWithHistory) {
4791 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4792 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4793 }
4794 startActivityForResult(intent, COMBO_PAGE);
4795 }
4796
4797 // Called when loading from context menu or LOAD_URL message
4798 private void loadURL(WebView view, String url) {
4799 // In case the user enters nothing.
4800 if (url != null && url.length() != 0 && view != null) {
4801 url = smartUrlFilter(url);
4802 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4803 view.loadUrl(url);
4804 }
4805 }
4806 }
4807
4808 private void checkMemory() {
4809 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4810 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4811 .getMemoryInfo(mi);
4812 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4813 // mi.threshold) for now
4814 // if (mi.lowMemory) {
4815 if (mi.availMem < mi.threshold) {
4816 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4817 + (mi.availMem / 1024) + "K threshold="
4818 + (mi.threshold / 1024) + "K");
4819 mTabControl.freeMemory();
4820 }
4821 }
4822
4823 private String smartUrlFilter(Uri inUri) {
4824 if (inUri != null) {
4825 return smartUrlFilter(inUri.toString());
4826 }
4827 return null;
4828 }
4829
4830
4831 // get window count
4832
4833 int getWindowCount(){
4834 if(mTabControl != null){
4835 return mTabControl.getTabCount();
4836 }
4837 return 0;
4838 }
4839
Feng Qianb34f87a2009-03-24 21:27:26 -07004840 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004841 "(?i)" + // switch on case insensitive matching
4842 "(" + // begin group for schema
4843 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004844 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004845 ")" +
4846 "(.*)" );
4847
4848 /**
4849 * Attempts to determine whether user input is a URL or search
4850 * terms. Anything with a space is passed to search.
4851 *
4852 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4853 * "Http://" converts to "http://"
4854 *
4855 * @return Original or modified URL
4856 *
4857 */
4858 String smartUrlFilter(String url) {
4859
4860 String inUrl = url.trim();
4861 boolean hasSpace = inUrl.indexOf(' ') != -1;
4862
4863 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4864 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004865 // force scheme to lowercase
4866 String scheme = matcher.group(1);
4867 String lcScheme = scheme.toLowerCase();
4868 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004869 inUrl = lcScheme + matcher.group(2);
4870 }
4871 if (hasSpace) {
4872 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004873 }
4874 return inUrl;
4875 }
4876 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004877 // FIXME: Is this the correct place to add to searches?
4878 // what if someone else calls this function?
4879 int shortcut = parseUrlShortcut(inUrl);
4880 if (shortcut != SHORTCUT_INVALID) {
4881 Browser.addSearchUrl(mResolver, inUrl);
4882 String query = inUrl.substring(2);
4883 switch (shortcut) {
4884 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004885 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004886 case SHORTCUT_WIKIPEDIA_SEARCH:
4887 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4888 case SHORTCUT_DICTIONARY_SEARCH:
4889 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4890 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004891 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004892 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004893 }
4894 }
4895 } else {
4896 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4897 return URLUtil.guessUrl(inUrl);
4898 }
4899 }
4900
4901 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004902 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004903 }
4904
4905 private final static int LOCK_ICON_UNSECURE = 0;
4906 private final static int LOCK_ICON_SECURE = 1;
4907 private final static int LOCK_ICON_MIXED = 2;
4908
4909 private int mLockIconType = LOCK_ICON_UNSECURE;
4910 private int mPrevLockType = LOCK_ICON_UNSECURE;
4911
4912 private BrowserSettings mSettings;
4913 private TabControl mTabControl;
4914 private ContentResolver mResolver;
4915 private FrameLayout mContentView;
4916 private ImageGrid mTabOverview;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004917 private View mCustomView;
4918 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01004919 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004920
4921 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4922 // view, we should rewrite this.
4923 private int mCurrentMenuState = 0;
4924 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01004925 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004926 private static final int EMPTY_MENU = -1;
4927 private Menu mMenu;
4928
4929 private FindDialog mFindDialog;
4930 // Used to prevent chording to result in firing two shortcuts immediately
4931 // one after another. Fixes bug 1211714.
4932 boolean mCanChord;
4933
4934 private boolean mInLoad;
4935 private boolean mIsNetworkUp;
4936
4937 private boolean mPageStarted;
4938 private boolean mActivityInPause = true;
4939
4940 private boolean mMenuIsDown;
4941
4942 private final KeyTracker mKeyTracker = new KeyTracker(this);
4943
4944 // As trackball doesn't send repeat down, we have to track it ourselves
4945 private boolean mTrackTrackball;
4946
4947 private static boolean mInTrace;
4948
4949 // Performance probe
4950 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4951 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4952 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4953 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4954 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4955 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4956 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4957 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4958 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4959 };
4960
4961 private long mStart;
4962 private long mProcessStart;
4963 private long mUserStart;
4964 private long mSystemStart;
4965 private long mIdleStart;
4966 private long mIrqStart;
4967
4968 private long mUiStart;
4969
4970 private Drawable mMixLockIcon;
4971 private Drawable mSecLockIcon;
4972 private Drawable mGenericFavicon;
4973
4974 /* hold a ref so we can auto-cancel if necessary */
4975 private AlertDialog mAlertDialog;
4976
4977 // Wait for credentials before loading google.com
4978 private ProgressDialog mCredsDlg;
4979
4980 // The up-to-date URL and title (these can be different from those stored
4981 // in WebView, since it takes some time for the information in WebView to
4982 // get updated)
4983 private String mUrl;
4984 private String mTitle;
4985
4986 // As PageInfo has different style for landscape / portrait, we have
4987 // to re-open it when configuration changed
4988 private AlertDialog mPageInfoDialog;
4989 private TabControl.Tab mPageInfoView;
4990 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4991 // dialog, we should not just dismiss it, but should get back to the
4992 // SSL-certificate-on-error dialog. This flag is used to store this state
4993 private Boolean mPageInfoFromShowSSLCertificateOnError;
4994
4995 // as SSLCertificateOnError has different style for landscape / portrait,
4996 // we have to re-open it when configuration changed
4997 private AlertDialog mSSLCertificateOnErrorDialog;
4998 private WebView mSSLCertificateOnErrorView;
4999 private SslErrorHandler mSSLCertificateOnErrorHandler;
5000 private SslError mSSLCertificateOnErrorError;
5001
5002 // as SSLCertificate has different style for landscape / portrait, we
5003 // have to re-open it when configuration changed
5004 private AlertDialog mSSLCertificateDialog;
5005 private TabControl.Tab mSSLCertificateView;
5006
5007 // as HttpAuthentication has different style for landscape / portrait, we
5008 // have to re-open it when configuration changed
5009 private AlertDialog mHttpAuthenticationDialog;
5010 private HttpAuthHandler mHttpAuthHandler;
5011
5012 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
5013 new FrameLayout.LayoutParams(
5014 ViewGroup.LayoutParams.FILL_PARENT,
5015 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01005016 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
5017 new FrameLayout.LayoutParams(
5018 ViewGroup.LayoutParams.FILL_PARENT,
5019 ViewGroup.LayoutParams.FILL_PARENT,
5020 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07005021 // Google search
5022 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08005023 // Wikipedia search
5024 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
5025 // Dictionary search
5026 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
5027 // Google Mobile Local search
5028 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
5029
5030 final static String QUERY_PLACE_HOLDER = "%s";
5031
5032 // "source" parameter for Google search through search key
5033 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
5034 // "source" parameter for Google search through goto menu
5035 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
5036 // "source" parameter for Google search through simplily type
5037 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
5038 // "source" parameter for Google search suggested by the browser
5039 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
5040 // "source" parameter for Google search from unknown source
5041 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
5042
5043 private final static String LOGTAG = "browser";
5044
5045 private TabListener mTabListener;
5046
5047 private String mLastEnteredUrl;
5048
5049 private PowerManager.WakeLock mWakeLock;
5050 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5051
5052 private Toast mStopToast;
5053
Leon Scroggins81db3662009-06-04 17:45:11 -04005054 private TitleBar mTitleBar;
5055
The Android Open Source Project0c908882009-03-03 19:32:16 -08005056 // Used during animations to prevent other animations from being triggered.
5057 // A count is used since the animation to and from the Window overview can
5058 // overlap. A count of 0 means no animation where a count of > 0 means
5059 // there are animations in progress.
5060 private int mAnimationCount;
5061
5062 // As the ids are dynamically created, we can't guarantee that they will
5063 // be in sequence, so this static array maps ids to a window number.
5064 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
5065 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
5066 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
5067 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
5068
5069 // monitor platform changes
5070 private IntentFilter mNetworkStateChangedFilter;
5071 private BroadcastReceiver mNetworkStateIntentReceiver;
5072
Grace Klobab4da0ad2009-05-14 14:45:40 -07005073 private BroadcastReceiver mPackageInstallationReceiver;
5074
The Android Open Source Project0c908882009-03-03 19:32:16 -08005075 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01005076 final static int COMBO_PAGE = 1;
5077 final static int DOWNLOAD_PAGE = 2;
5078 final static int PREFERENCES_PAGE = 3;
5079 final static int WEBSTORAGE_QUOTA_DIALOG = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005080
5081 // the frenquency of checking whether system memory is low
5082 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005083
5084 /**
5085 * A UrlData class to abstract how the content will be set to WebView.
5086 * This base class uses loadUrl to show the content.
5087 */
5088 private static class UrlData {
5089 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07005090 byte[] mPostData;
5091
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005092 UrlData(String url) {
5093 this.mUrl = url;
5094 }
Grace Kloba60e095c2009-06-16 11:50:55 -07005095
5096 void setPostData(byte[] postData) {
5097 mPostData = postData;
5098 }
5099
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005100 boolean isEmpty() {
5101 return mUrl == null || mUrl.length() == 0;
5102 }
5103
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005104 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07005105 if (mPostData != null) {
5106 webView.postUrl(mUrl, mPostData);
5107 } else {
5108 webView.loadUrl(mUrl);
5109 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005110 }
5111 };
5112
5113 /**
5114 * A subclass of UrlData class that can display inlined content using
5115 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
5116 */
5117 private static class InlinedUrlData extends UrlData {
5118 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
5119 super(failUrl);
5120 mInlined = inlined;
5121 mMimeType = mimeType;
5122 mEncoding = encoding;
5123 }
5124 String mMimeType;
5125 String mInlined;
5126 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005127 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005128 boolean isEmpty() {
5129 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
5130 }
5131
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005132 @Override
5133 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005134 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
5135 }
5136 }
5137
5138 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08005139}