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