blob: 0bac3eadc3440a9cfe50366d0ccddca34ea1173e [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()) {
Leon Scroggins64b80f32009-08-07 12:03:34 -0400836 bookmarksOrHistoryPicker(false);
The Android Open Source Project0c908882009-03-03 19:32:16 -0800837 } 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
Leon Scroggins64b80f32009-08-07 12:03:34 -04001593 case R.id.goto_menu_id:
The Android Open Source Project0c908882009-03-03 19:32:16 -08001594 bookmarksOrHistoryPicker(false);
1595 break;
1596
1597 case R.id.windows_menu_id:
1598 if (mTabControl.getTabCount() == 1) {
Leon Scroggins64b80f32009-08-07 12:03:34 -04001599 openTabAndShow(EMPTY_URL_DATA, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001600 } else {
1601 tabPicker(true, mTabControl.getCurrentIndex(), false);
1602 }
1603 break;
1604
1605 case R.id.stop_reload_menu_id:
1606 if (mInLoad) {
1607 stopLoading();
1608 } else {
1609 getTopWindow().reload();
1610 }
1611 break;
1612
1613 case R.id.back_menu_id:
1614 getTopWindow().goBack();
1615 break;
1616
1617 case R.id.forward_menu_id:
1618 getTopWindow().goForward();
1619 break;
1620
1621 case R.id.close_menu_id:
1622 // Close the subwindow if it exists.
1623 if (mTabControl.getCurrentSubWindow() != null) {
1624 dismissSubWindow(mTabControl.getCurrentTab());
1625 break;
1626 }
1627 final int currentIndex = mTabControl.getCurrentIndex();
1628 final TabControl.Tab parent =
1629 mTabControl.getCurrentTab().getParentTab();
1630 int indexToShow = -1;
1631 if (parent != null) {
1632 indexToShow = mTabControl.getTabIndex(parent);
1633 } else {
1634 // Get the last tab in the list. If it is the current tab,
1635 // subtract 1 more.
1636 indexToShow = mTabControl.getTabCount() - 1;
1637 if (currentIndex == indexToShow) {
1638 indexToShow--;
1639 }
1640 }
1641 switchTabs(currentIndex, indexToShow, true);
1642 break;
1643
1644 case R.id.homepage_menu_id:
1645 TabControl.Tab current = mTabControl.getCurrentTab();
1646 if (current != null) {
1647 dismissSubWindow(current);
1648 current.getWebView().loadUrl(mSettings.getHomePage());
1649 }
1650 break;
1651
1652 case R.id.preferences_menu_id:
1653 Intent intent = new Intent(this,
1654 BrowserPreferencesPage.class);
1655 startActivityForResult(intent, PREFERENCES_PAGE);
1656 break;
1657
1658 case R.id.find_menu_id:
1659 if (null == mFindDialog) {
1660 mFindDialog = new FindDialog(this);
1661 }
1662 mFindDialog.setWebView(getTopWindow());
1663 mFindDialog.show();
1664 mMenuState = EMPTY_MENU;
1665 break;
1666
1667 case R.id.select_text_id:
1668 getTopWindow().emulateShiftHeld();
1669 break;
1670 case R.id.page_info_menu_id:
1671 showPageInfo(mTabControl.getCurrentTab(), false);
1672 break;
1673
1674 case R.id.classic_history_menu_id:
1675 bookmarksOrHistoryPicker(true);
1676 break;
1677
1678 case R.id.share_page_menu_id:
1679 Browser.sendString(this, getTopWindow().getUrl());
1680 break;
1681
1682 case R.id.dump_nav_menu_id:
1683 getTopWindow().debugDump();
1684 break;
1685
1686 case R.id.zoom_in_menu_id:
1687 getTopWindow().zoomIn();
1688 break;
1689
1690 case R.id.zoom_out_menu_id:
1691 getTopWindow().zoomOut();
1692 break;
1693
1694 case R.id.view_downloads_menu_id:
1695 viewDownloads(null);
1696 break;
1697
1698 // -- Tab menu
1699 case R.id.view_tab_menu_id:
1700 if (mTabListener != null && mTabOverview != null) {
1701 int pos = mTabOverview.getContextMenuPosition(item);
1702 mTabOverview.setCurrentIndex(pos);
1703 mTabListener.onClick(pos);
1704 }
1705 break;
1706
1707 case R.id.remove_tab_menu_id:
1708 if (mTabListener != null && mTabOverview != null) {
1709 int pos = mTabOverview.getContextMenuPosition(item);
1710 mTabListener.remove(pos);
1711 }
1712 break;
1713
1714 case R.id.new_tab_menu_id:
1715 // No need to check for mTabOverview here since we are not
1716 // dependent on it for a position.
1717 if (mTabListener != null) {
1718 // If the overview happens to be non-null, make the "New
1719 // Tab" cell visible.
1720 if (mTabOverview != null) {
1721 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1722 }
1723 mTabListener.onClick(ImageGrid.NEW_TAB);
1724 }
1725 break;
1726
1727 case R.id.bookmark_tab_menu_id:
1728 if (mTabListener != null && mTabOverview != null) {
1729 int pos = mTabOverview.getContextMenuPosition(item);
1730 TabControl.Tab t = mTabControl.getTab(pos);
1731 // Since we called populatePickerData for all of the
1732 // tabs, getTitle and getUrl will return appropriate
1733 // values.
1734 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1735 t.getUrl());
1736 }
1737 break;
1738
1739 case R.id.history_tab_menu_id:
1740 bookmarksOrHistoryPicker(true);
1741 break;
1742
1743 case R.id.bookmarks_tab_menu_id:
1744 bookmarksOrHistoryPicker(false);
1745 break;
1746
1747 case R.id.properties_tab_menu_id:
1748 if (mTabListener != null && mTabOverview != null) {
1749 int pos = mTabOverview.getContextMenuPosition(item);
1750 showPageInfo(mTabControl.getTab(pos), false);
1751 }
1752 break;
1753
1754 case R.id.window_one_menu_id:
1755 case R.id.window_two_menu_id:
1756 case R.id.window_three_menu_id:
1757 case R.id.window_four_menu_id:
1758 case R.id.window_five_menu_id:
1759 case R.id.window_six_menu_id:
1760 case R.id.window_seven_menu_id:
1761 case R.id.window_eight_menu_id:
1762 {
1763 int menuid = item.getItemId();
1764 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1765 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1766 TabControl.Tab desiredTab = mTabControl.getTab(id);
1767 if (desiredTab != null &&
1768 desiredTab != mTabControl.getCurrentTab()) {
1769 switchTabs(mTabControl.getCurrentIndex(), id, false);
1770 }
1771 break;
1772 }
1773 }
1774 }
1775 break;
1776
1777 default:
1778 if (!super.onOptionsItemSelected(item)) {
1779 return false;
1780 }
1781 // Otherwise fall through.
1782 }
1783 mCanChord = false;
1784 return true;
1785 }
1786
1787 public void closeFind() {
1788 mMenuState = R.id.MAIN_MENU;
1789 }
1790
1791 @Override public boolean onPrepareOptionsMenu(Menu menu)
1792 {
1793 // This happens when the user begins to hold down the menu key, so
1794 // allow them to chord to get a shortcut.
1795 mCanChord = true;
1796 // Note: setVisible will decide whether an item is visible; while
1797 // setEnabled() will decide whether an item is enabled, which also means
1798 // whether the matching shortcut key will function.
1799 super.onPrepareOptionsMenu(menu);
1800 switch (mMenuState) {
1801 case R.id.TAB_MENU:
1802 if (mCurrentMenuState != mMenuState) {
1803 menu.setGroupVisible(R.id.MAIN_MENU, false);
1804 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1805 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1806 menu.setGroupVisible(R.id.TAB_MENU, true);
1807 menu.setGroupEnabled(R.id.TAB_MENU, true);
1808 }
1809 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1810 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1811 tab.setVisible(newT);
1812 tab.setEnabled(newT);
1813 break;
1814 case EMPTY_MENU:
1815 if (mCurrentMenuState != mMenuState) {
1816 menu.setGroupVisible(R.id.MAIN_MENU, false);
1817 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1818 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1819 menu.setGroupVisible(R.id.TAB_MENU, false);
1820 menu.setGroupEnabled(R.id.TAB_MENU, false);
1821 }
1822 break;
1823 default:
1824 if (mCurrentMenuState != mMenuState) {
1825 menu.setGroupVisible(R.id.MAIN_MENU, true);
1826 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1827 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1828 menu.setGroupVisible(R.id.TAB_MENU, false);
1829 menu.setGroupEnabled(R.id.TAB_MENU, false);
1830 }
1831 final WebView w = getTopWindow();
1832 boolean canGoBack = false;
1833 boolean canGoForward = false;
1834 boolean isHome = false;
1835 if (w != null) {
1836 canGoBack = w.canGoBack();
1837 canGoForward = w.canGoForward();
1838 isHome = mSettings.getHomePage().equals(w.getUrl());
1839 }
1840 final MenuItem back = menu.findItem(R.id.back_menu_id);
1841 back.setEnabled(canGoBack);
1842
1843 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1844 home.setEnabled(!isHome);
1845
1846 menu.findItem(R.id.forward_menu_id)
1847 .setEnabled(canGoForward);
1848
1849 // decide whether to show the share link option
1850 PackageManager pm = getPackageManager();
1851 Intent send = new Intent(Intent.ACTION_SEND);
1852 send.setType("text/plain");
1853 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1854 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1855
1856 // If there is only 1 window, the text will be "New window"
1857 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1858 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1859 getString(R.string.view_tabs_condensed) :
1860 getString(R.string.tab_picker_new_tab));
1861
1862 boolean isNavDump = mSettings.isNavDump();
1863 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1864 nav.setVisible(isNavDump);
1865 nav.setEnabled(isNavDump);
1866 break;
1867 }
1868 mCurrentMenuState = mMenuState;
1869 return true;
1870 }
1871
1872 @Override
1873 public void onCreateContextMenu(ContextMenu menu, View v,
1874 ContextMenuInfo menuInfo) {
1875 WebView webview = (WebView) v;
1876 WebView.HitTestResult result = webview.getHitTestResult();
1877 if (result == null) {
1878 return;
1879 }
1880
1881 int type = result.getType();
1882 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1883 Log.w(LOGTAG,
1884 "We should not show context menu when nothing is touched");
1885 return;
1886 }
1887 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1888 // let TextView handles context menu
1889 return;
1890 }
1891
1892 // Note, http://b/issue?id=1106666 is requesting that
1893 // an inflated menu can be used again. This is not available
1894 // yet, so inflate each time (yuk!)
1895 MenuInflater inflater = getMenuInflater();
1896 inflater.inflate(R.menu.browsercontext, menu);
1897
1898 // Show the correct menu group
1899 String extra = result.getExtra();
1900 menu.setGroupVisible(R.id.PHONE_MENU,
1901 type == WebView.HitTestResult.PHONE_TYPE);
1902 menu.setGroupVisible(R.id.EMAIL_MENU,
1903 type == WebView.HitTestResult.EMAIL_TYPE);
1904 menu.setGroupVisible(R.id.GEO_MENU,
1905 type == WebView.HitTestResult.GEO_TYPE);
1906 menu.setGroupVisible(R.id.IMAGE_MENU,
1907 type == WebView.HitTestResult.IMAGE_TYPE
1908 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1909 menu.setGroupVisible(R.id.ANCHOR_MENU,
1910 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1911 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1912
1913 // Setup custom handling depending on the type
1914 switch (type) {
1915 case WebView.HitTestResult.PHONE_TYPE:
1916 menu.setHeaderTitle(Uri.decode(extra));
1917 menu.findItem(R.id.dial_context_menu_id).setIntent(
1918 new Intent(Intent.ACTION_VIEW, Uri
1919 .parse(WebView.SCHEME_TEL + extra)));
1920 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1921 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1922 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1923 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1924 addIntent);
1925 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1926 new Copy(extra));
1927 break;
1928
1929 case WebView.HitTestResult.EMAIL_TYPE:
1930 menu.setHeaderTitle(extra);
1931 menu.findItem(R.id.email_context_menu_id).setIntent(
1932 new Intent(Intent.ACTION_VIEW, Uri
1933 .parse(WebView.SCHEME_MAILTO + extra)));
1934 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1935 new Copy(extra));
1936 break;
1937
1938 case WebView.HitTestResult.GEO_TYPE:
1939 menu.setHeaderTitle(extra);
1940 menu.findItem(R.id.map_context_menu_id).setIntent(
1941 new Intent(Intent.ACTION_VIEW, Uri
1942 .parse(WebView.SCHEME_GEO
1943 + URLEncoder.encode(extra))));
1944 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1945 new Copy(extra));
1946 break;
1947
1948 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1949 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1950 TextView titleView = (TextView) LayoutInflater.from(this)
1951 .inflate(android.R.layout.browser_link_context_header,
1952 null);
1953 titleView.setText(extra);
1954 menu.setHeaderView(titleView);
1955 // decide whether to show the open link in new tab option
1956 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1957 mTabControl.getTabCount() < TabControl.MAX_TABS);
1958 PackageManager pm = getPackageManager();
1959 Intent send = new Intent(Intent.ACTION_SEND);
1960 send.setType("text/plain");
1961 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1962 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1963 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1964 break;
1965 }
1966 // otherwise fall through to handle image part
1967 case WebView.HitTestResult.IMAGE_TYPE:
1968 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1969 menu.setHeaderTitle(extra);
1970 }
1971 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1972 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1973 menu.findItem(R.id.download_context_menu_id).
1974 setOnMenuItemClickListener(new Download(extra));
1975 break;
1976
1977 default:
1978 Log.w(LOGTAG, "We should not get here.");
1979 break;
1980 }
1981 }
1982
The Android Open Source Project0c908882009-03-03 19:32:16 -08001983 // Attach the given tab to the content view.
1984 private void attachTabToContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01001985 // Attach the container that contains the main WebView and any other UI
1986 // associated with the tab.
1987 mContentView.addView(t.getContainer(), COVER_SCREEN_PARAMS);
Ben Murdochbff2d602009-07-01 20:19:05 +01001988
1989 if (mShouldShowErrorConsole) {
1990 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
1991 if (errorConsole.numberOfErrors() == 0) {
1992 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
1993 } else {
1994 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
1995 }
1996
1997 mErrorConsoleContainer.addView(errorConsole,
1998 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
1999 ViewGroup.LayoutParams.WRAP_CONTENT));
2000 }
2001
The Android Open Source Project0c908882009-03-03 19:32:16 -08002002 // Attach the sub window if necessary
2003 attachSubWindow(t);
2004 // Request focus on the top window.
2005 t.getTopWindow().requestFocus();
2006 }
2007
2008 // Attach a sub window to the main WebView of the given tab.
2009 private void attachSubWindow(TabControl.Tab t) {
2010 // If a sub window exists, attach it to the content view.
2011 final WebView subView = t.getSubWebView();
2012 if (subView != null) {
2013 final View container = t.getSubWebViewContainer();
2014 mContentView.addView(container, COVER_SCREEN_PARAMS);
2015 subView.requestFocus();
2016 }
2017 }
2018
2019 // Remove the given tab from the content view.
2020 private void removeTabFromContentView(TabControl.Tab t) {
Steve Block2bc69912009-07-30 14:45:13 +01002021 // Remove the container that contains the main WebView.
2022 mContentView.removeView(t.getContainer());
Ben Murdochbff2d602009-07-01 20:19:05 +01002023
2024 if (mTabControl.getCurrentErrorConsole(false) != null) {
2025 mErrorConsoleContainer.removeView(mTabControl.getCurrentErrorConsole(false));
2026 }
2027
The Android Open Source Project0c908882009-03-03 19:32:16 -08002028 // Remove the sub window if it exists.
2029 if (t.getSubWebView() != null) {
2030 mContentView.removeView(t.getSubWebViewContainer());
2031 }
2032 }
2033
2034 // Remove the sub window if it exists. Also called by TabControl when the
2035 // user clicks the 'X' to dismiss a sub window.
2036 /* package */ void dismissSubWindow(TabControl.Tab t) {
2037 final WebView mainView = t.getWebView();
2038 if (t.getSubWebView() != null) {
2039 // Remove the container view and request focus on the main WebView.
2040 mContentView.removeView(t.getSubWebViewContainer());
2041 mainView.requestFocus();
2042 // Tell the TabControl to dismiss the subwindow. This will destroy
2043 // the WebView.
2044 mTabControl.dismissSubWindow(t);
2045 }
2046 }
2047
2048 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
2049 private void sendAnimateFromOverview(final TabControl.Tab tab,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002050 final boolean newTab, final UrlData urlData, final int delay,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002051 final Message msg) {
2052 // Set the current tab.
2053 mTabControl.setCurrentTab(tab);
2054 // Attach the WebView so it will layout.
2055 attachTabToContentView(tab);
2056 // Set the view to invisibile for now.
2057 tab.getWebView().setVisibility(View.INVISIBLE);
2058 // If there is a sub window, make it invisible too.
2059 if (tab.getSubWebView() != null) {
2060 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
2061 }
2062 // Create our fake animating view.
2063 final AnimatingView view = new AnimatingView(this, tab);
2064 // Attach it to the view system and make in invisible so it will
2065 // layout but not flash white on the screen.
2066 mContentView.addView(view, COVER_SCREEN_PARAMS);
2067 view.setVisibility(View.INVISIBLE);
2068 // Send the animate message.
2069 final HashMap map = new HashMap();
2070 map.put("view", view);
2071 // Load the url after the AnimatingView has captured the picture. This
2072 // prevents any bad layout or bad scale from being used during
2073 // animation.
Leon Scroggins64b80f32009-08-07 12:03:34 -04002074 dismissSubWindow(tab);
2075 if (urlData.isEmpty()) {
2076 bookmarksOrHistoryPicker(false);
2077 } else {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002078 urlData.loadIn(tab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002079 }
2080 map.put("msg", msg);
2081 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2082 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
2083 // Increment the count to indicate that we are in an animation.
2084 mAnimationCount++;
2085 // Remove the listener so we don't get any more tab changes.
2086 mTabOverview.setListener(null);
2087 mTabListener = null;
2088 // Make the menu empty until the animation completes.
2089 mMenuState = EMPTY_MENU;
2090
2091 }
2092
2093 // 500ms animation with 800ms delay
Patrick Scott95d601f2009-06-11 10:06:46 -04002094 private static final int TAB_ANIMATION_DURATION = 200;
2095 private static final int TAB_OVERVIEW_DELAY = 500;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002096
2097 // Called by TabControl when a tab is requesting focus
2098 /* package */ void showTab(TabControl.Tab t) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002099 showTab(t, EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002100 }
2101
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002102 private void showTab(TabControl.Tab t, UrlData urlData) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002103 // Disallow focus change during a tab animation.
2104 if (mAnimationCount > 0) {
2105 return;
2106 }
2107 int delay = 0;
2108 if (mTabOverview == null) {
2109 // Add a delay so the tab overview can be shown before the second
2110 // animation begins.
2111 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2112 tabPicker(false, mTabControl.getTabIndex(t), false);
2113 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002114 sendAnimateFromOverview(t, false, urlData, delay, null);
2115 }
2116
2117 // A wrapper function of {@link #openTabAndShow(UrlData, Message, boolean, String)}
2118 // that accepts url as string.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002119 private TabControl.Tab openTabAndShow(String url, final Message msg,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002120 boolean closeOnExit, String appId) {
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002121 return openTabAndShow(new UrlData(url), msg, closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002122 }
2123
2124 // This method does a ton of stuff. It will attempt to create a new tab
2125 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2126 // url isn't null, it will load the given url. If the tab overview is not
2127 // showing, it will animate to the tab overview, create a new tab and
2128 // animate away from it. After the animation completes, it will dispatch
2129 // the given Message. If the tab overview is already showing (i.e. this
2130 // method is called from TabListener.onClick(), the method will animate
2131 // away from the tab overview.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002132 private TabControl.Tab openTabAndShow(UrlData urlData, final Message msg,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002133 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002134 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
2135 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
2136 if (newTab) {
2137 int delay = 0;
2138 // If the tab overview is up and there are animations, just load
2139 // the url.
2140 if (mTabOverview != null && mAnimationCount > 0) {
Leon Scroggins64b80f32009-08-07 12:03:34 -04002141 if (urlData.isEmpty()) {
2142 bookmarksOrHistoryPicker(false);
2143 } else {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002144 // We should not have a msg here since onCreateWindow
2145 // checks the animation count and every other caller passes
2146 // null.
2147 assert msg == null;
2148 // just dismiss the subwindow and load the given url.
2149 dismissSubWindow(currentTab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002150 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002151 }
2152 } else {
2153 // show mTabOverview if it is not there.
2154 if (mTabOverview == null) {
2155 // We have to delay the animation from the tab picker by the
2156 // length of the tab animation. Add a delay so the tab
2157 // overview can be shown before the second animation begins.
2158 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2159 tabPicker(false, ImageGrid.NEW_TAB, false);
2160 }
2161 // Animate from the Tab overview after any animations have
2162 // finished.
Grace Klobac9181842009-04-14 08:53:22 -07002163 final TabControl.Tab tab = mTabControl.createNewTab(
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002164 closeOnExit, appId, urlData.mUrl);
Grace Klobaec7eb372009-06-16 13:45:56 -07002165 sendAnimateFromOverview(tab, true, urlData, delay, msg);
Grace Klobac9181842009-04-14 08:53:22 -07002166 return tab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002167 }
Leon Scroggins64b80f32009-08-07 12:03:34 -04002168 } else {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002169 // We should not have a msg here.
2170 assert msg == null;
2171 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002172 sendAnimateFromOverview(currentTab, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002173 TAB_OVERVIEW_DELAY, null);
2174 } else {
2175 // Get rid of the subwindow if it exists
2176 dismissSubWindow(currentTab);
Leon Scroggins64b80f32009-08-07 12:03:34 -04002177 if (!urlData.isEmpty()) {
2178 // Load the given url.
2179 urlData.loadIn(currentTab.getWebView());
2180 } else {
2181 bookmarksOrHistoryPicker(false);
2182 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002183 }
2184 }
Grace Klobac9181842009-04-14 08:53:22 -07002185 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002186 }
2187
2188 private Animation createTabAnimation(final AnimatingView view,
2189 final View cell, boolean scaleDown) {
2190 final AnimationSet set = new AnimationSet(true);
2191 final float scaleX = (float) cell.getWidth() / view.getWidth();
2192 final float scaleY = (float) cell.getHeight() / view.getHeight();
2193 if (scaleDown) {
2194 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2195 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2196 cell.getTop()));
2197 } else {
2198 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2199 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2200 cell.getTop(), 0));
2201 }
2202 set.setDuration(TAB_ANIMATION_DURATION);
2203 set.setInterpolator(new DecelerateInterpolator());
2204 return set;
2205 }
2206
2207 // Animate to the tab overview. currentIndex tells us which position to
2208 // animate to and newIndex is the position that should be selected after
2209 // the animation completes.
2210 // If remove is true, after the animation stops, a confirmation dialog will
2211 // be displayed to the user.
2212 private void animateToTabOverview(final int newIndex, final boolean remove,
2213 final AnimatingView view) {
2214 // Find the view in the ImageGrid allowing for the "New Tab" cell.
2215 int position = mTabControl.getTabIndex(view.mTab);
2216 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2217 position++;
2218 }
2219
2220 // Offset the tab position with the first visible position to get a
2221 // number between 0 and 3.
2222 position -= mTabOverview.getFirstVisiblePosition();
2223
2224 // Grab the view that we are going to animate to.
2225 final View v = mTabOverview.getChildAt(position);
2226
2227 final Animation.AnimationListener l =
2228 new Animation.AnimationListener() {
2229 public void onAnimationStart(Animation a) {
Patrick Scottd068f802009-06-22 11:46:06 -04002230 if (mTabOverview != null) {
2231 mTabOverview.requestFocus();
2232 // Clear the listener so we don't trigger a tab
2233 // selection.
2234 mTabOverview.setListener(null);
2235 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002236 }
2237 public void onAnimationRepeat(Animation a) {}
2238 public void onAnimationEnd(Animation a) {
2239 // We are no longer animating so decrement the count.
2240 mAnimationCount--;
2241 // Make the view GONE so that it will not draw between
2242 // now and when the Runnable is handled.
2243 view.setVisibility(View.GONE);
2244 // Post a runnable since we can't modify the view
2245 // hierarchy during this callback.
2246 mHandler.post(new Runnable() {
2247 public void run() {
2248 // Remove the AnimatingView.
2249 mContentView.removeView(view);
2250 if (mTabOverview != null) {
2251 // Make newIndex visible.
2252 mTabOverview.setCurrentIndex(newIndex);
2253 // Restore the listener.
2254 mTabOverview.setListener(mTabListener);
2255 // Change the menu to TAB_MENU if the
2256 // ImageGrid is interactive.
2257 if (mTabOverview.isLive()) {
2258 mMenuState = R.id.TAB_MENU;
2259 mTabOverview.requestFocus();
2260 }
2261 }
2262 // If a remove was requested, remove the tab.
2263 if (remove) {
2264 // During a remove, the current tab has
2265 // already changed. Remember the current one
2266 // here.
2267 final TabControl.Tab currentTab =
2268 mTabControl.getCurrentTab();
2269 // Remove the tab at newIndex from
2270 // TabControl and the tab overview.
2271 final TabControl.Tab tab =
2272 mTabControl.getTab(newIndex);
2273 mTabControl.removeTab(tab);
2274 // Restore the current tab.
2275 if (currentTab != tab) {
2276 mTabControl.setCurrentTab(currentTab);
2277 }
2278 if (mTabOverview != null) {
2279 mTabOverview.remove(newIndex);
2280 // Make the current tab visible.
2281 mTabOverview.setCurrentIndex(
2282 mTabControl.getCurrentIndex());
2283 }
2284 }
2285 }
2286 });
2287 }
2288 };
2289
2290 // Do an animation if there is a view to animate to.
2291 if (v != null) {
2292 // Create our animation
2293 final Animation anim = createTabAnimation(view, v, true);
2294 anim.setAnimationListener(l);
2295 // Start animating
2296 view.startAnimation(anim);
2297 } else {
2298 // If something goes wrong and we didn't find a view to animate to,
2299 // just do everything here.
2300 l.onAnimationStart(null);
2301 l.onAnimationEnd(null);
2302 }
2303 }
2304
2305 // Animate from the tab picker. The index supplied is the index to animate
2306 // from.
2307 private void animateFromTabOverview(final AnimatingView view,
2308 final boolean newTab, final Message msg) {
2309 // firstVisible is the first visible tab on the screen. This helps
2310 // to know which corner of the screen the selected tab is.
2311 int firstVisible = mTabOverview.getFirstVisiblePosition();
2312 // tabPosition is the 0-based index of of the tab being opened
2313 int tabPosition = mTabControl.getTabIndex(view.mTab);
2314 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2315 // Add one to make room for the "New Tab" cell.
2316 tabPosition++;
2317 }
2318 // If this is a new tab, animate from the "New Tab" cell.
2319 if (newTab) {
2320 tabPosition = 0;
2321 }
2322 // Location corresponds to the four corners of the screen.
2323 // A new tab or 0 is upper left, 0 for an old tab is upper
2324 // right, 1 is lower left, and 2 is lower right
2325 int location = tabPosition - firstVisible;
2326
2327 // Find the view at this location.
2328 final View v = mTabOverview.getChildAt(location);
2329
2330 // Wait until the animation completes to replace the AnimatingView.
2331 final Animation.AnimationListener l =
2332 new Animation.AnimationListener() {
2333 public void onAnimationStart(Animation a) {}
2334 public void onAnimationRepeat(Animation a) {}
2335 public void onAnimationEnd(Animation a) {
2336 mHandler.post(new Runnable() {
2337 public void run() {
2338 mContentView.removeView(view);
2339 // Dismiss the tab overview. If the cell at the
2340 // given location is null, set the fade
2341 // parameter to true.
2342 dismissTabOverview(v == null);
2343 TabControl.Tab t =
2344 mTabControl.getCurrentTab();
2345 mMenuState = R.id.MAIN_MENU;
2346 // Resume regular updates.
2347 t.getWebView().resumeTimers();
2348 // Dispatch the message after the animation
2349 // completes.
2350 if (msg != null) {
2351 msg.sendToTarget();
2352 }
2353 // The animation is done and the tab overview is
2354 // gone so allow key events and other animations
2355 // to begin.
2356 mAnimationCount--;
2357 // Reset all the title bar info.
2358 resetTitle();
2359 }
2360 });
2361 }
2362 };
2363
2364 if (v != null) {
2365 final Animation anim = createTabAnimation(view, v, false);
2366 // Set the listener and start animating
2367 anim.setAnimationListener(l);
2368 view.startAnimation(anim);
2369 // Make the view VISIBLE during the animation.
2370 view.setVisibility(View.VISIBLE);
2371 } else {
2372 // Go ahead and do all the cleanup.
2373 l.onAnimationEnd(null);
2374 }
2375 }
2376
2377 // Dismiss the tab overview applying a fade if needed.
2378 private void dismissTabOverview(final boolean fade) {
2379 if (fade) {
2380 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2381 anim.setDuration(500);
2382 anim.startNow();
2383 mTabOverview.startAnimation(anim);
2384 }
2385 // Just in case there was a problem with animating away from the tab
2386 // overview
2387 WebView current = mTabControl.getCurrentWebView();
2388 if (current != null) {
2389 current.setVisibility(View.VISIBLE);
2390 } else {
2391 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2392 }
2393 // Make the sub window container visible.
2394 if (mTabControl.getCurrentSubWindow() != null) {
2395 mTabControl.getCurrentTab().getSubWebViewContainer()
2396 .setVisibility(View.VISIBLE);
2397 }
2398 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002399 // Clear all the data for tab picker so next time it will be
2400 // recreated.
2401 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002402 mTabOverview.clear();
2403 mTabOverview = null;
2404 mTabListener = null;
2405 }
2406
Grace Klobac9181842009-04-14 08:53:22 -07002407 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002408 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002409 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002410 if (t != null) {
2411 t.getWebView().loadUrl(url);
2412 }
Grace Klobac9181842009-04-14 08:53:22 -07002413 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002414 } else {
Grace Klobac9181842009-04-14 08:53:22 -07002415 return openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002416 }
2417 }
2418
2419 private class Copy implements OnMenuItemClickListener {
2420 private CharSequence mText;
2421
2422 public boolean onMenuItemClick(MenuItem item) {
2423 copy(mText);
2424 return true;
2425 }
2426
2427 public Copy(CharSequence toCopy) {
2428 mText = toCopy;
2429 }
2430 }
2431
2432 private class Download implements OnMenuItemClickListener {
2433 private String mText;
2434
2435 public boolean onMenuItemClick(MenuItem item) {
2436 onDownloadStartNoStream(mText, null, null, null, -1);
2437 return true;
2438 }
2439
2440 public Download(String toDownload) {
2441 mText = toDownload;
2442 }
2443 }
2444
2445 private void copy(CharSequence text) {
2446 try {
2447 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2448 if (clip != null) {
2449 clip.setClipboardText(text);
2450 }
2451 } catch (android.os.RemoteException e) {
2452 Log.e(LOGTAG, "Copy failed", e);
2453 }
2454 }
2455
2456 /**
2457 * Resets the browser title-view to whatever it must be (for example, if we
2458 * load a page from history).
2459 */
2460 private void resetTitle() {
2461 resetLockIcon();
2462 resetTitleIconAndProgress();
2463 }
2464
2465 /**
2466 * Resets the browser title-view to whatever it must be
2467 * (for example, if we had a loading error)
2468 * When we have a new page, we call resetTitle, when we
2469 * have to reset the titlebar to whatever it used to be
2470 * (for example, if the user chose to stop loading), we
2471 * call resetTitleAndRevertLockIcon.
2472 */
2473 /* package */ void resetTitleAndRevertLockIcon() {
2474 revertLockIcon();
2475 resetTitleIconAndProgress();
2476 }
2477
2478 /**
2479 * Reset the title, favicon, and progress.
2480 */
2481 private void resetTitleIconAndProgress() {
2482 WebView current = mTabControl.getCurrentWebView();
2483 if (current == null) {
2484 return;
2485 }
2486 resetTitleAndIcon(current);
2487 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002488 mWebChromeClient.onProgressChanged(current, progress);
2489 }
2490
2491 // Reset the title and the icon based on the given item.
2492 private void resetTitleAndIcon(WebView view) {
2493 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2494 if (item != null) {
2495 setUrlTitle(item.getUrl(), item.getTitle());
2496 setFavicon(item.getFavicon());
2497 } else {
2498 setUrlTitle(null, null);
2499 setFavicon(null);
2500 }
2501 }
2502
2503 /**
2504 * Sets a title composed of the URL and the title string.
2505 * @param url The URL of the site being loaded.
2506 * @param title The title of the site being loaded.
2507 */
2508 private void setUrlTitle(String url, String title) {
2509 mUrl = url;
2510 mTitle = title;
2511
2512 // While the tab overview is animating or being shown, block changes
2513 // to the title.
2514 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04002515 if (CUSTOM_BROWSER_BAR) {
2516 mTitleBar.setTitleAndUrl(title, url);
2517 } else {
2518 setTitle(buildUrlTitle(url, title));
2519 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002520 }
2521 }
2522
2523 /**
2524 * Builds and returns the page title, which is some
2525 * combination of the page URL and title.
2526 * @param url The URL of the site being loaded.
2527 * @param title The title of the site being loaded.
2528 * @return The page title.
2529 */
2530 private String buildUrlTitle(String url, String title) {
2531 String urlTitle = "";
2532
2533 if (url != null) {
2534 String titleUrl = buildTitleUrl(url);
2535
2536 if (title != null && 0 < title.length()) {
2537 if (titleUrl != null && 0 < titleUrl.length()) {
2538 urlTitle = titleUrl + ": " + title;
2539 } else {
2540 urlTitle = title;
2541 }
2542 } else {
2543 if (titleUrl != null) {
2544 urlTitle = titleUrl;
2545 }
2546 }
2547 }
2548
2549 return urlTitle;
2550 }
2551
2552 /**
2553 * @param url The URL to build a title version of the URL from.
2554 * @return The title version of the URL or null if fails.
2555 * The title version of the URL can be either the URL hostname,
2556 * or the hostname with an "https://" prefix (for secure URLs),
2557 * or an empty string if, for example, the URL in question is a
2558 * file:// URL with no hostname.
2559 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002560 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002561 String titleUrl = null;
2562
2563 if (url != null) {
2564 try {
2565 // parse the url string
2566 URL urlObj = new URL(url);
2567 if (urlObj != null) {
2568 titleUrl = "";
2569
2570 String protocol = urlObj.getProtocol();
2571 String host = urlObj.getHost();
2572
2573 if (host != null && 0 < host.length()) {
2574 titleUrl = host;
2575 if (protocol != null) {
2576 // if a secure site, add an "https://" prefix!
2577 if (protocol.equalsIgnoreCase("https")) {
2578 titleUrl = protocol + "://" + host;
2579 }
2580 }
2581 }
2582 }
2583 } catch (MalformedURLException e) {}
2584 }
2585
2586 return titleUrl;
2587 }
2588
2589 // Set the favicon in the title bar.
2590 private void setFavicon(Bitmap icon) {
2591 // While the tab overview is animating or being shown, block changes to
2592 // the favicon.
2593 if (mAnimationCount > 0 || mTabOverview != null) {
2594 return;
2595 }
Leon Scroggins81db3662009-06-04 17:45:11 -04002596 if (CUSTOM_BROWSER_BAR) {
2597 Drawable[] array = new Drawable[3];
2598 array[0] = new PaintDrawable(Color.BLACK);
2599 PaintDrawable p = new PaintDrawable(Color.WHITE);
2600 array[1] = p;
2601 if (icon == null) {
2602 array[2] = mGenericFavicon;
2603 } else {
2604 array[2] = new BitmapDrawable(icon);
2605 }
2606 LayerDrawable d = new LayerDrawable(array);
2607 d.setLayerInset(1, 1, 1, 1, 1);
2608 d.setLayerInset(2, 2, 2, 2, 2);
2609 mTitleBar.setFavicon(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002610 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04002611 Drawable[] array = new Drawable[2];
2612 PaintDrawable p = new PaintDrawable(Color.WHITE);
2613 p.setCornerRadius(3f);
2614 array[0] = p;
2615 if (icon == null) {
2616 array[1] = mGenericFavicon;
2617 } else {
2618 array[1] = new BitmapDrawable(icon);
2619 }
2620 LayerDrawable d = new LayerDrawable(array);
2621 d.setLayerInset(1, 2, 2, 2, 2);
2622 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002623 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002624 }
2625
2626 /**
2627 * Saves the current lock-icon state before resetting
2628 * the lock icon. If we have an error, we may need to
2629 * roll back to the previous state.
2630 */
2631 private void saveLockIcon() {
2632 mPrevLockType = mLockIconType;
2633 }
2634
2635 /**
2636 * Reverts the lock-icon state to the last saved state,
2637 * for example, if we had an error, and need to cancel
2638 * the load.
2639 */
2640 private void revertLockIcon() {
2641 mLockIconType = mPrevLockType;
2642
Dave Bort31a6d1c2009-04-13 15:56:49 -07002643 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002644 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2645 " revert lock icon to " + mLockIconType);
2646 }
2647
2648 updateLockIconImage(mLockIconType);
2649 }
2650
2651 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2652 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2653 // Animate to the tab picker, remove the current tab, then
2654 // animate away from the tab picker to the parent WebView.
2655 tabPicker(false, indexFrom, remove);
2656 // Change to the parent tab
2657 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2658 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002659 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002660 } else {
2661 // Increment this here so that no other animations can happen in
2662 // between the end of the tab picker transition and the beginning
2663 // of openTabAndShow. This has a matching decrement in the handler
2664 // of OPEN_TAB_AND_SHOW.
2665 mAnimationCount++;
2666 // Send a message to open a new tab.
2667 mHandler.sendMessageDelayed(
2668 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
Leon Scroggins64b80f32009-08-07 12:03:34 -04002669 null), delay);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002670 }
2671 }
2672
2673 private void goBackOnePageOrQuit() {
2674 TabControl.Tab current = mTabControl.getCurrentTab();
2675 if (current == null) {
2676 /*
2677 * Instead of finishing the activity, simply push this to the back
2678 * of the stack and let ActivityManager to choose the foreground
2679 * activity. As BrowserActivity is singleTask, it will be always the
2680 * root of the task. So we can use either true or false for
2681 * moveTaskToBack().
2682 */
2683 moveTaskToBack(true);
2684 }
2685 WebView w = current.getWebView();
2686 if (w.canGoBack()) {
2687 w.goBack();
2688 } else {
2689 // Check to see if we are closing a window that was created by
2690 // another window. If so, we switch back to that window.
2691 TabControl.Tab parent = current.getParentTab();
2692 if (parent != null) {
2693 switchTabs(mTabControl.getCurrentIndex(),
2694 mTabControl.getTabIndex(parent), true);
2695 } else {
2696 if (current.closeOnExit()) {
2697 if (mTabControl.getTabCount() == 1) {
2698 finish();
2699 return;
2700 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002701 // call pauseWebViewTimers() now, we won't be able to call
2702 // it in onPause() as the WebView won't be valid.
2703 pauseWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002704 removeTabFromContentView(current);
2705 mTabControl.removeTab(current);
2706 }
2707 /*
2708 * Instead of finishing the activity, simply push this to the back
2709 * of the stack and let ActivityManager to choose the foreground
2710 * activity. As BrowserActivity is singleTask, it will be always the
2711 * root of the task. So we can use either true or false for
2712 * moveTaskToBack().
2713 */
2714 moveTaskToBack(true);
2715 }
2716 }
2717 }
2718
2719 public KeyTracker.State onKeyTracker(int keyCode,
2720 KeyEvent event,
2721 KeyTracker.Stage stage,
2722 int duration) {
2723 // if onKeyTracker() is called after activity onStop()
2724 // because of accumulated key events,
2725 // we should ignore it as browser is not active any more.
2726 WebView topWindow = getTopWindow();
Andrei Popescuadc008d2009-06-26 14:11:30 +01002727 if (topWindow == null && mCustomView == null)
The Android Open Source Project0c908882009-03-03 19:32:16 -08002728 return KeyTracker.State.NOT_TRACKING;
2729
2730 if (keyCode == KeyEvent.KEYCODE_BACK) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01002731 // Check if a custom view is currently showing and, if it is, hide it.
2732 if (mCustomView != null) {
2733 mWebChromeClient.onHideCustomView();
2734 return KeyTracker.State.DONE_TRACKING;
2735 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002736 // During animations, block the back key so that other animations
2737 // are not triggered and so that we don't end up destroying all the
2738 // WebViews before finishing the animation.
2739 if (mAnimationCount > 0) {
2740 return KeyTracker.State.DONE_TRACKING;
2741 }
2742 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2743 bookmarksOrHistoryPicker(true);
2744 return KeyTracker.State.DONE_TRACKING;
2745 } else if (stage == KeyTracker.Stage.UP) {
2746 // FIXME: Currently, we do not have a notion of the
2747 // history picker for the subwindow, but maybe we
2748 // should?
2749 WebView subwindow = mTabControl.getCurrentSubWindow();
2750 if (subwindow != null) {
2751 if (subwindow.canGoBack()) {
2752 subwindow.goBack();
2753 } else {
2754 dismissSubWindow(mTabControl.getCurrentTab());
2755 }
2756 } else {
2757 goBackOnePageOrQuit();
2758 }
2759 return KeyTracker.State.DONE_TRACKING;
2760 }
2761 return KeyTracker.State.KEEP_TRACKING;
2762 }
2763 return KeyTracker.State.NOT_TRACKING;
2764 }
2765
2766 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2767 if (keyCode == KeyEvent.KEYCODE_MENU) {
2768 mMenuIsDown = true;
Grace Kloba6ee9c492009-07-13 10:04:34 -07002769 } else if (mMenuIsDown) {
2770 // The default key mode is DEFAULT_KEYS_SEARCH_LOCAL. As the MENU is
2771 // still down, we don't want to trigger the search. Pretend to
2772 // consume the key and do nothing.
2773 return true;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002774 }
2775 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2776 if (!handled) {
2777 switch (keyCode) {
2778 case KeyEvent.KEYCODE_SPACE:
2779 if (event.isShiftPressed()) {
2780 getTopWindow().pageUp(false);
2781 } else {
2782 getTopWindow().pageDown(false);
2783 }
2784 handled = true;
2785 break;
2786
2787 default:
2788 break;
2789 }
2790 }
2791 return handled || super.onKeyDown(keyCode, event);
2792 }
2793
2794 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2795 if (keyCode == KeyEvent.KEYCODE_MENU) {
2796 mMenuIsDown = false;
2797 }
2798 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2799 }
2800
2801 private void stopLoading() {
2802 resetTitleAndRevertLockIcon();
2803 WebView w = getTopWindow();
2804 w.stopLoading();
2805 mWebViewClient.onPageFinished(w, w.getUrl());
2806
2807 cancelStopToast();
2808 mStopToast = Toast
2809 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2810 mStopToast.show();
2811 }
2812
2813 private void cancelStopToast() {
2814 if (mStopToast != null) {
2815 mStopToast.cancel();
2816 mStopToast = null;
2817 }
2818 }
2819
2820 // called by a non-UI thread to post the message
2821 public void postMessage(int what, int arg1, int arg2, Object obj) {
2822 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2823 }
2824
2825 // public message ids
2826 public final static int LOAD_URL = 1001;
2827 public final static int STOP_LOAD = 1002;
2828
2829 // Message Ids
2830 private static final int FOCUS_NODE_HREF = 102;
2831 private static final int CANCEL_CREDS_REQUEST = 103;
2832 private static final int ANIMATE_FROM_OVERVIEW = 104;
2833 private static final int ANIMATE_TO_OVERVIEW = 105;
2834 private static final int OPEN_TAB_AND_SHOW = 106;
Grace Kloba92c18a52009-07-31 23:48:32 -07002835 private static final int RELEASE_WAKELOCK = 107;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002836
2837 // Private handler for handling javascript and saving passwords
2838 private Handler mHandler = new Handler() {
2839
2840 public void handleMessage(Message msg) {
2841 switch (msg.what) {
2842 case ANIMATE_FROM_OVERVIEW:
2843 final HashMap map = (HashMap) msg.obj;
2844 animateFromTabOverview((AnimatingView) map.get("view"),
2845 msg.arg1 == 1, (Message) map.get("msg"));
2846 break;
2847
2848 case ANIMATE_TO_OVERVIEW:
2849 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2850 (AnimatingView) msg.obj);
2851 break;
2852
2853 case OPEN_TAB_AND_SHOW:
2854 // Decrement mAnimationCount before openTabAndShow because
2855 // the method relies on the value being 0 to start the next
2856 // animation.
2857 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002858 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002859 break;
2860
2861 case FOCUS_NODE_HREF:
2862 String url = (String) msg.getData().get("url");
2863 if (url == null || url.length() == 0) {
2864 break;
2865 }
2866 HashMap focusNodeMap = (HashMap) msg.obj;
2867 WebView view = (WebView) focusNodeMap.get("webview");
2868 // Only apply the action if the top window did not change.
2869 if (getTopWindow() != view) {
2870 break;
2871 }
2872 switch (msg.arg1) {
2873 case R.id.open_context_menu_id:
2874 case R.id.view_image_context_menu_id:
2875 loadURL(getTopWindow(), url);
2876 break;
2877 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002878 final TabControl.Tab parent = mTabControl
2879 .getCurrentTab();
2880 final TabControl.Tab newTab = openTab(url);
2881 if (newTab != parent) {
2882 parent.addChildTab(newTab);
2883 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002884 break;
2885 case R.id.bookmark_context_menu_id:
2886 Intent intent = new Intent(BrowserActivity.this,
2887 AddBookmarkPage.class);
2888 intent.putExtra("url", url);
2889 startActivity(intent);
2890 break;
2891 case R.id.share_link_context_menu_id:
2892 Browser.sendString(BrowserActivity.this, url);
2893 break;
2894 case R.id.copy_link_context_menu_id:
2895 copy(url);
2896 break;
2897 case R.id.save_link_context_menu_id:
2898 case R.id.download_context_menu_id:
2899 onDownloadStartNoStream(url, null, null, null, -1);
2900 break;
2901 }
2902 break;
2903
2904 case LOAD_URL:
2905 loadURL(getTopWindow(), (String) msg.obj);
2906 break;
2907
2908 case STOP_LOAD:
2909 stopLoading();
2910 break;
2911
2912 case CANCEL_CREDS_REQUEST:
2913 resumeAfterCredentials();
2914 break;
2915
The Android Open Source Project0c908882009-03-03 19:32:16 -08002916 case RELEASE_WAKELOCK:
2917 if (mWakeLock.isHeld()) {
2918 mWakeLock.release();
2919 }
2920 break;
2921 }
2922 }
2923 };
2924
Leon Scroggins89c6d362009-07-15 16:54:37 -04002925 private void updateScreenshot(WebView view) {
2926 // If this is a bookmarked site, add a screenshot to the database.
2927 // FIXME: When should we update? Every time?
2928 // FIXME: Would like to make sure there is actually something to
2929 // draw, but the API for that (WebViewCore.pictureReady()) is not
2930 // currently accessible here.
Patrick Scott3918d442009-08-04 13:22:29 -04002931 ContentResolver cr = getContentResolver();
2932 final Cursor c = BrowserBookmarksAdapter.queryBookmarksForUrl(
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04002933 cr, view.getOriginalUrl(), view.getUrl(), false);
Patrick Scott3918d442009-08-04 13:22:29 -04002934 if (c != null) {
Leon Scroggins89c6d362009-07-15 16:54:37 -04002935 boolean succeed = c.moveToFirst();
2936 ContentValues values = null;
2937 while (succeed) {
2938 if (values == null) {
2939 final ByteArrayOutputStream os
2940 = new ByteArrayOutputStream();
2941 Picture thumbnail = view.capturePicture();
2942 // Keep width and height in sync with BrowserBookmarksPage
2943 // and bookmark_thumb
2944 Bitmap bm = Bitmap.createBitmap(100, 80,
2945 Bitmap.Config.ARGB_4444);
2946 Canvas canvas = new Canvas(bm);
2947 // May need to tweak these values to determine what is the
2948 // best scale factor
2949 canvas.scale(.5f, .5f);
2950 thumbnail.draw(canvas);
2951 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
2952 values = new ContentValues();
2953 values.put(Browser.BookmarkColumns.THUMBNAIL,
2954 os.toByteArray());
2955 }
2956 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
2957 c.getInt(0)), values, null, null);
2958 succeed = c.moveToNext();
2959 }
2960 c.close();
2961 }
2962 }
2963
The Android Open Source Project0c908882009-03-03 19:32:16 -08002964 // -------------------------------------------------------------------------
2965 // WebViewClient implementation.
2966 //-------------------------------------------------------------------------
2967
2968 // Use in overrideUrlLoading
2969 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2970 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2971 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2972 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2973
2974 /* package */ WebViewClient getWebViewClient() {
2975 return mWebViewClient;
2976 }
2977
Patrick Scott3918d442009-08-04 13:22:29 -04002978 private void updateIcon(WebView view, Bitmap icon) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002979 if (icon != null) {
2980 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
Patrick Scott3918d442009-08-04 13:22:29 -04002981 view, icon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002982 }
2983 setFavicon(icon);
2984 }
2985
2986 private final WebViewClient mWebViewClient = new WebViewClient() {
2987 @Override
2988 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2989 resetLockIcon(url);
2990 setUrlTitle(url, null);
Ben Murdochbff2d602009-07-01 20:19:05 +01002991
2992 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(false);
2993 if (errorConsole != null) {
2994 errorConsole.clearErrorMessages();
2995 if (mShouldShowErrorConsole) {
2996 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
2997 }
2998 }
2999
The Android Open Source Project0c908882009-03-03 19:32:16 -08003000 // Call updateIcon instead of setFavicon so the bookmark
3001 // database can be updated.
Patrick Scott3918d442009-08-04 13:22:29 -04003002 updateIcon(view, favicon);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003003
3004 if (mSettings.isTracing() == true) {
3005 // FIXME: we should save the trace file somewhere other than data.
3006 // I can't use "/tmp" as it competes for system memory.
3007 File file = getDir("browserTrace", 0);
3008 String baseDir = file.getPath();
3009 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
3010 String host;
3011 try {
3012 WebAddress uri = new WebAddress(url);
3013 host = uri.mHost;
3014 } catch (android.net.ParseException ex) {
3015 host = "unknown_host";
3016 }
3017 host = host.replace('.', '_');
3018 baseDir = baseDir + host;
3019 file = new File(baseDir+".data");
3020 if (file.exists() == true) {
3021 file.delete();
3022 }
3023 file = new File(baseDir+".key");
3024 if (file.exists() == true) {
3025 file.delete();
3026 }
3027 mInTrace = true;
3028 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
3029 }
3030
3031 // Performance probe
3032 if (false) {
3033 mStart = SystemClock.uptimeMillis();
3034 mProcessStart = Process.getElapsedCpuTime();
3035 long[] sysCpu = new long[7];
3036 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3037 sysCpu, null)) {
3038 mUserStart = sysCpu[0] + sysCpu[1];
3039 mSystemStart = sysCpu[2];
3040 mIdleStart = sysCpu[3];
3041 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
3042 }
3043 mUiStart = SystemClock.currentThreadTimeMillis();
3044 }
3045
3046 if (!mPageStarted) {
3047 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003048 // if onResume() has been called, resumeWebViewTimers() does
3049 // nothing.
3050 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003051 }
3052
3053 // reset sync timer to avoid sync starts during loading a page
3054 CookieSyncManager.getInstance().resetSync();
3055
3056 mInLoad = true;
3057 updateInLoadMenuItems();
3058 if (!mIsNetworkUp) {
3059 if ( mAlertDialog == null) {
3060 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
3061 .setTitle(R.string.loadSuspendedTitle)
3062 .setMessage(R.string.loadSuspended)
3063 .setPositiveButton(R.string.ok, null)
3064 .show();
3065 }
3066 if (view != null) {
3067 view.setNetworkAvailable(false);
3068 }
3069 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003070 }
3071
3072 @Override
3073 public void onPageFinished(WebView view, String url) {
3074 // Reset the title and icon in case we stopped a provisional
3075 // load.
3076 resetTitleAndIcon(view);
3077
3078 // Update the lock icon image only once we are done loading
3079 updateLockIconImage(mLockIconType);
Leon Scroggins89c6d362009-07-15 16:54:37 -04003080 updateScreenshot(view);
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04003081
The Android Open Source Project0c908882009-03-03 19:32:16 -08003082 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003083 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003084 long[] sysCpu = new long[7];
3085 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3086 sysCpu, null)) {
3087 String uiInfo = "UI thread used "
3088 + (SystemClock.currentThreadTimeMillis() - mUiStart)
3089 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07003090 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003091 Log.d(LOGTAG, uiInfo);
3092 }
3093 //The string that gets written to the log
3094 String performanceString = "It took total "
3095 + (SystemClock.uptimeMillis() - mStart)
3096 + " ms clock time to load the page."
3097 + "\nbrowser process used "
3098 + (Process.getElapsedCpuTime() - mProcessStart)
3099 + " ms, user processes used "
3100 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
3101 + " ms, kernel used "
3102 + (sysCpu[2] - mSystemStart) * 10
3103 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
3104 + " ms and irq took "
3105 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
3106 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003107 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003108 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
3109 }
3110 if (url != null) {
3111 // strip the url to maintain consistency
3112 String newUrl = new String(url);
3113 if (newUrl.startsWith("http://www.")) {
3114 newUrl = newUrl.substring(11);
3115 } else if (newUrl.startsWith("http://")) {
3116 newUrl = newUrl.substring(7);
3117 } else if (newUrl.startsWith("https://www.")) {
3118 newUrl = newUrl.substring(12);
3119 } else if (newUrl.startsWith("https://")) {
3120 newUrl = newUrl.substring(8);
3121 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07003122 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003123 Log.d(LOGTAG, newUrl + " loaded");
3124 }
3125 /*
3126 if (sWhiteList.contains(newUrl)) {
3127 // The string that gets pushed to the statistcs
3128 // service
3129 performanceString = performanceString
3130 + "\nWebpage: "
3131 + newUrl
3132 + "\nCarrier: "
3133 + android.os.SystemProperties
3134 .get("gsm.sim.operator.alpha");
3135 if (mWebView != null
3136 && mWebView.getContext() != null
3137 && mWebView.getContext().getSystemService(
3138 Context.CONNECTIVITY_SERVICE) != null) {
3139 ConnectivityManager cManager =
3140 (ConnectivityManager) mWebView
3141 .getContext().getSystemService(
3142 Context.CONNECTIVITY_SERVICE);
3143 NetworkInfo nInfo = cManager
3144 .getActiveNetworkInfo();
3145 if (nInfo != null) {
3146 performanceString = performanceString
3147 + "\nNetwork Type: "
3148 + nInfo.getType().toString();
3149 }
3150 }
3151 Checkin.logEvent(mResolver,
3152 Checkin.Events.Tag.WEBPAGE_LOAD,
3153 performanceString);
3154 Log.w(LOGTAG, "pushed to the statistics service");
3155 }
3156 */
3157 }
3158 }
3159 }
3160
3161 if (mInTrace) {
3162 mInTrace = false;
3163 Debug.stopMethodTracing();
3164 }
3165
3166 if (mPageStarted) {
3167 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003168 // pauseWebViewTimers() will do nothing and return false if
3169 // onPause() is not called yet.
3170 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003171 if (mWakeLock.isHeld()) {
3172 mHandler.removeMessages(RELEASE_WAKELOCK);
3173 mWakeLock.release();
3174 }
3175 }
3176 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003177 }
3178
3179 // return true if want to hijack the url to let another app to handle it
3180 @Override
3181 public boolean shouldOverrideUrlLoading(WebView view, String url) {
3182 if (url.startsWith(SCHEME_WTAI)) {
3183 // wtai://wp/mc;number
3184 // number=string(phone-number)
3185 if (url.startsWith(SCHEME_WTAI_MC)) {
3186 Intent intent = new Intent(Intent.ACTION_VIEW,
3187 Uri.parse(WebView.SCHEME_TEL +
3188 url.substring(SCHEME_WTAI_MC.length())));
3189 startActivity(intent);
3190 return true;
3191 }
3192 // wtai://wp/sd;dtmf
3193 // dtmf=string(dialstring)
3194 if (url.startsWith(SCHEME_WTAI_SD)) {
3195 // TODO
3196 // only send when there is active voice connection
3197 return false;
3198 }
3199 // wtai://wp/ap;number;name
3200 // number=string(phone-number)
3201 // name=string
3202 if (url.startsWith(SCHEME_WTAI_AP)) {
3203 // TODO
3204 return false;
3205 }
3206 }
3207
Dianne Hackborn99189432009-06-17 18:06:18 -07003208 // The "about:" schemes are internal to the browser; don't
3209 // want these to be dispatched to other apps.
3210 if (url.startsWith("about:")) {
3211 return false;
3212 }
Ben Murdochbff2d602009-07-01 20:19:05 +01003213
Dianne Hackborn99189432009-06-17 18:06:18 -07003214 Intent intent;
Ben Murdochbff2d602009-07-01 20:19:05 +01003215
Dianne Hackborn99189432009-06-17 18:06:18 -07003216 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003217 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003218 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3219 } catch (URISyntaxException ex) {
3220 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003221 return false;
3222 }
3223
Grace Kloba5b078b52009-06-24 20:23:41 -07003224 // check whether the intent can be resolved. If not, we will see
3225 // whether we can download it from the Market.
3226 if (getPackageManager().resolveActivity(intent, 0) == null) {
3227 String packagename = intent.getPackage();
3228 if (packagename != null) {
3229 intent = new Intent(Intent.ACTION_VIEW, Uri
3230 .parse("market://search?q=pname:" + packagename));
3231 intent.addCategory(Intent.CATEGORY_BROWSABLE);
3232 startActivity(intent);
3233 return true;
3234 } else {
3235 return false;
3236 }
3237 }
3238
Dianne Hackborn99189432009-06-17 18:06:18 -07003239 // sanitize the Intent, ensuring web pages can not bypass browser
3240 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003241 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003242 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003243 try {
3244 if (startActivityIfNeeded(intent, -1)) {
3245 return true;
3246 }
3247 } catch (ActivityNotFoundException ex) {
3248 // ignore the error. If no application can handle the URL,
3249 // eg about:blank, assume the browser can handle it.
3250 }
3251
3252 if (mMenuIsDown) {
3253 openTab(url);
3254 closeOptionsMenu();
3255 return true;
3256 }
3257
3258 return false;
3259 }
3260
3261 /**
3262 * Updates the lock icon. This method is called when we discover another
3263 * resource to be loaded for this page (for example, javascript). While
3264 * we update the icon type, we do not update the lock icon itself until
3265 * we are done loading, it is slightly more secure this way.
3266 */
3267 @Override
3268 public void onLoadResource(WebView view, String url) {
3269 if (url != null && url.length() > 0) {
3270 // It is only if the page claims to be secure
3271 // that we may have to update the lock:
3272 if (mLockIconType == LOCK_ICON_SECURE) {
3273 // If NOT a 'safe' url, change the lock to mixed content!
3274 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3275 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003276 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003277 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3278 " updated lock icon to " + mLockIconType + " due to " + url);
3279 }
3280 }
3281 }
3282 }
3283 }
3284
3285 /**
3286 * Show the dialog, asking the user if they would like to continue after
3287 * an excessive number of HTTP redirects.
3288 */
3289 @Override
3290 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3291 final Message continueMsg) {
3292 new AlertDialog.Builder(BrowserActivity.this)
3293 .setTitle(R.string.browserFrameRedirect)
3294 .setMessage(R.string.browserFrame307Post)
3295 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3296 public void onClick(DialogInterface dialog, int which) {
3297 continueMsg.sendToTarget();
3298 }})
3299 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3300 public void onClick(DialogInterface dialog, int which) {
3301 cancelMsg.sendToTarget();
3302 }})
3303 .setOnCancelListener(new OnCancelListener() {
3304 public void onCancel(DialogInterface dialog) {
3305 cancelMsg.sendToTarget();
3306 }})
3307 .show();
3308 }
3309
Patrick Scott37911c72009-03-24 18:02:58 -07003310 // Container class for the next error dialog that needs to be
3311 // displayed.
3312 class ErrorDialog {
3313 public final int mTitle;
3314 public final String mDescription;
3315 public final int mError;
3316 ErrorDialog(int title, String desc, int error) {
3317 mTitle = title;
3318 mDescription = desc;
3319 mError = error;
3320 }
3321 };
3322
3323 private void processNextError() {
3324 if (mQueuedErrors == null) {
3325 return;
3326 }
3327 // The first one is currently displayed so just remove it.
3328 mQueuedErrors.removeFirst();
3329 if (mQueuedErrors.size() == 0) {
3330 mQueuedErrors = null;
3331 return;
3332 }
3333 showError(mQueuedErrors.getFirst());
3334 }
3335
3336 private DialogInterface.OnDismissListener mDialogListener =
3337 new DialogInterface.OnDismissListener() {
3338 public void onDismiss(DialogInterface d) {
3339 processNextError();
3340 }
3341 };
3342 private LinkedList<ErrorDialog> mQueuedErrors;
3343
3344 private void queueError(int err, String desc) {
3345 if (mQueuedErrors == null) {
3346 mQueuedErrors = new LinkedList<ErrorDialog>();
3347 }
3348 for (ErrorDialog d : mQueuedErrors) {
3349 if (d.mError == err) {
3350 // Already saw a similar error, ignore the new one.
3351 return;
3352 }
3353 }
3354 ErrorDialog errDialog = new ErrorDialog(
3355 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3356 R.string.browserFrameFileErrorLabel :
3357 R.string.browserFrameNetworkErrorLabel,
3358 desc, err);
3359 mQueuedErrors.addLast(errDialog);
3360
3361 // Show the dialog now if the queue was empty.
3362 if (mQueuedErrors.size() == 1) {
3363 showError(errDialog);
3364 }
3365 }
3366
3367 private void showError(ErrorDialog errDialog) {
3368 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3369 .setTitle(errDialog.mTitle)
3370 .setMessage(errDialog.mDescription)
3371 .setPositiveButton(R.string.ok, null)
3372 .create();
3373 d.setOnDismissListener(mDialogListener);
3374 d.show();
3375 }
3376
The Android Open Source Project0c908882009-03-03 19:32:16 -08003377 /**
3378 * Show a dialog informing the user of the network error reported by
3379 * WebCore.
3380 */
3381 @Override
3382 public void onReceivedError(WebView view, int errorCode,
3383 String description, String failingUrl) {
3384 if (errorCode != EventHandler.ERROR_LOOKUP &&
3385 errorCode != EventHandler.ERROR_CONNECT &&
3386 errorCode != EventHandler.ERROR_BAD_URL &&
3387 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3388 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07003389 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003390 }
Patrick Scott37911c72009-03-24 18:02:58 -07003391 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3392 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003393
3394 // We need to reset the title after an error.
3395 resetTitleAndRevertLockIcon();
3396 }
3397
3398 /**
3399 * Check with the user if it is ok to resend POST data as the page they
3400 * are trying to navigate to is the result of a POST.
3401 */
3402 @Override
3403 public void onFormResubmission(WebView view, final Message dontResend,
3404 final Message resend) {
3405 new AlertDialog.Builder(BrowserActivity.this)
3406 .setTitle(R.string.browserFrameFormResubmitLabel)
3407 .setMessage(R.string.browserFrameFormResubmitMessage)
3408 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3409 public void onClick(DialogInterface dialog, int which) {
3410 resend.sendToTarget();
3411 }})
3412 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3413 public void onClick(DialogInterface dialog, int which) {
3414 dontResend.sendToTarget();
3415 }})
3416 .setOnCancelListener(new OnCancelListener() {
3417 public void onCancel(DialogInterface dialog) {
3418 dontResend.sendToTarget();
3419 }})
3420 .show();
3421 }
3422
3423 /**
3424 * Insert the url into the visited history database.
3425 * @param url The url to be inserted.
3426 * @param isReload True if this url is being reloaded.
3427 * FIXME: Not sure what to do when reloading the page.
3428 */
3429 @Override
3430 public void doUpdateVisitedHistory(WebView view, String url,
3431 boolean isReload) {
3432 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3433 return;
3434 }
3435 Browser.updateVisitedHistory(mResolver, url, true);
3436 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3437 }
3438
3439 /**
3440 * Displays SSL error(s) dialog to the user.
3441 */
3442 @Override
3443 public void onReceivedSslError(
3444 final WebView view, final SslErrorHandler handler, final SslError error) {
3445
3446 if (mSettings.showSecurityWarnings()) {
3447 final LayoutInflater factory =
3448 LayoutInflater.from(BrowserActivity.this);
3449 final View warningsView =
3450 factory.inflate(R.layout.ssl_warnings, null);
3451 final LinearLayout placeholder =
3452 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3453
3454 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3455 LinearLayout ll = (LinearLayout)factory
3456 .inflate(R.layout.ssl_warning, null);
3457 ((TextView)ll.findViewById(R.id.warning))
3458 .setText(R.string.ssl_untrusted);
3459 placeholder.addView(ll);
3460 }
3461
3462 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3463 LinearLayout ll = (LinearLayout)factory
3464 .inflate(R.layout.ssl_warning, null);
3465 ((TextView)ll.findViewById(R.id.warning))
3466 .setText(R.string.ssl_mismatch);
3467 placeholder.addView(ll);
3468 }
3469
3470 if (error.hasError(SslError.SSL_EXPIRED)) {
3471 LinearLayout ll = (LinearLayout)factory
3472 .inflate(R.layout.ssl_warning, null);
3473 ((TextView)ll.findViewById(R.id.warning))
3474 .setText(R.string.ssl_expired);
3475 placeholder.addView(ll);
3476 }
3477
3478 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3479 LinearLayout ll = (LinearLayout)factory
3480 .inflate(R.layout.ssl_warning, null);
3481 ((TextView)ll.findViewById(R.id.warning))
3482 .setText(R.string.ssl_not_yet_valid);
3483 placeholder.addView(ll);
3484 }
3485
3486 new AlertDialog.Builder(BrowserActivity.this)
3487 .setTitle(R.string.security_warning)
3488 .setIcon(android.R.drawable.ic_dialog_alert)
3489 .setView(warningsView)
3490 .setPositiveButton(R.string.ssl_continue,
3491 new DialogInterface.OnClickListener() {
3492 public void onClick(DialogInterface dialog, int whichButton) {
3493 handler.proceed();
3494 }
3495 })
3496 .setNeutralButton(R.string.view_certificate,
3497 new DialogInterface.OnClickListener() {
3498 public void onClick(DialogInterface dialog, int whichButton) {
3499 showSSLCertificateOnError(view, handler, error);
3500 }
3501 })
3502 .setNegativeButton(R.string.cancel,
3503 new DialogInterface.OnClickListener() {
3504 public void onClick(DialogInterface dialog, int whichButton) {
3505 handler.cancel();
3506 BrowserActivity.this.resetTitleAndRevertLockIcon();
3507 }
3508 })
3509 .setOnCancelListener(
3510 new DialogInterface.OnCancelListener() {
3511 public void onCancel(DialogInterface dialog) {
3512 handler.cancel();
3513 BrowserActivity.this.resetTitleAndRevertLockIcon();
3514 }
3515 })
3516 .show();
3517 } else {
3518 handler.proceed();
3519 }
3520 }
3521
3522 /**
3523 * Handles an HTTP authentication request.
3524 *
3525 * @param handler The authentication handler
3526 * @param host The host
3527 * @param realm The realm
3528 */
3529 @Override
3530 public void onReceivedHttpAuthRequest(WebView view,
3531 final HttpAuthHandler handler, final String host, final String realm) {
3532 String username = null;
3533 String password = null;
3534
3535 boolean reuseHttpAuthUsernamePassword =
3536 handler.useHttpAuthUsernamePassword();
3537
3538 if (reuseHttpAuthUsernamePassword &&
3539 (mTabControl.getCurrentWebView() != null)) {
3540 String[] credentials =
3541 mTabControl.getCurrentWebView()
3542 .getHttpAuthUsernamePassword(host, realm);
3543 if (credentials != null && credentials.length == 2) {
3544 username = credentials[0];
3545 password = credentials[1];
3546 }
3547 }
3548
3549 if (username != null && password != null) {
3550 handler.proceed(username, password);
3551 } else {
3552 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3553 }
3554 }
3555
3556 @Override
3557 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3558 if (mMenuIsDown) {
3559 // only check shortcut key when MENU is held
3560 return getWindow().isShortcutKey(event.getKeyCode(), event);
3561 } else {
3562 return false;
3563 }
3564 }
3565
3566 @Override
3567 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3568 if (view != mTabControl.getCurrentTopWebView()) {
3569 return;
3570 }
3571 if (event.isDown()) {
3572 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3573 } else {
3574 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3575 }
3576 }
3577 };
3578
3579 //--------------------------------------------------------------------------
3580 // WebChromeClient implementation
3581 //--------------------------------------------------------------------------
3582
3583 /* package */ WebChromeClient getWebChromeClient() {
3584 return mWebChromeClient;
3585 }
3586
3587 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3588 // Helper method to create a new tab or sub window.
3589 private void createWindow(final boolean dialog, final Message msg) {
3590 if (dialog) {
3591 mTabControl.createSubWindow();
3592 final TabControl.Tab t = mTabControl.getCurrentTab();
3593 attachSubWindow(t);
3594 WebView.WebViewTransport transport =
3595 (WebView.WebViewTransport) msg.obj;
3596 transport.setWebView(t.getSubWebView());
3597 msg.sendToTarget();
3598 } else {
3599 final TabControl.Tab parent = mTabControl.getCurrentTab();
3600 // openTabAndShow will dispatch the message after creating the
3601 // new WebView. This will prevent another request from coming
3602 // in during the animation.
Patrick Scott1536e732009-06-11 14:50:01 -04003603 final TabControl.Tab newTab =
3604 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003605 if (newTab != parent) {
3606 parent.addChildTab(newTab);
3607 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003608 WebView.WebViewTransport transport =
3609 (WebView.WebViewTransport) msg.obj;
3610 transport.setWebView(mTabControl.getCurrentWebView());
3611 }
3612 }
3613
3614 @Override
3615 public boolean onCreateWindow(WebView view, final boolean dialog,
3616 final boolean userGesture, final Message resultMsg) {
3617 // Ignore these requests during tab animations or if the tab
3618 // overview is showing.
3619 if (mAnimationCount > 0 || mTabOverview != null) {
3620 return false;
3621 }
3622 // Short-circuit if we can't create any more tabs or sub windows.
3623 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3624 new AlertDialog.Builder(BrowserActivity.this)
3625 .setTitle(R.string.too_many_subwindows_dialog_title)
3626 .setIcon(android.R.drawable.ic_dialog_alert)
3627 .setMessage(R.string.too_many_subwindows_dialog_message)
3628 .setPositiveButton(R.string.ok, null)
3629 .show();
3630 return false;
3631 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3632 new AlertDialog.Builder(BrowserActivity.this)
3633 .setTitle(R.string.too_many_windows_dialog_title)
3634 .setIcon(android.R.drawable.ic_dialog_alert)
3635 .setMessage(R.string.too_many_windows_dialog_message)
3636 .setPositiveButton(R.string.ok, null)
3637 .show();
3638 return false;
3639 }
3640
3641 // Short-circuit if this was a user gesture.
3642 if (userGesture) {
3643 // createWindow will call openTabAndShow for new Windows and
3644 // that will call tabPicker which will increment
3645 // mAnimationCount.
3646 createWindow(dialog, resultMsg);
3647 return true;
3648 }
3649
3650 // Allow the popup and create the appropriate window.
3651 final AlertDialog.OnClickListener allowListener =
3652 new AlertDialog.OnClickListener() {
3653 public void onClick(DialogInterface d,
3654 int which) {
3655 // Same comment as above for setting
3656 // mAnimationCount.
3657 createWindow(dialog, resultMsg);
3658 // Since we incremented mAnimationCount while the
3659 // dialog was up, we have to decrement it here.
3660 mAnimationCount--;
3661 }
3662 };
3663
3664 // Block the popup by returning a null WebView.
3665 final AlertDialog.OnClickListener blockListener =
3666 new AlertDialog.OnClickListener() {
3667 public void onClick(DialogInterface d, int which) {
3668 resultMsg.sendToTarget();
3669 // We are not going to trigger an animation so
3670 // unblock keys and animation requests.
3671 mAnimationCount--;
3672 }
3673 };
3674
3675 // Build a confirmation dialog to display to the user.
3676 final AlertDialog d =
3677 new AlertDialog.Builder(BrowserActivity.this)
3678 .setTitle(R.string.attention)
3679 .setIcon(android.R.drawable.ic_dialog_alert)
3680 .setMessage(R.string.popup_window_attempt)
3681 .setPositiveButton(R.string.allow, allowListener)
3682 .setNegativeButton(R.string.block, blockListener)
3683 .setCancelable(false)
3684 .create();
3685
3686 // Show the confirmation dialog.
3687 d.show();
3688 // We want to increment mAnimationCount here to prevent a
3689 // potential race condition. If the user allows a pop-up from a
3690 // site and that pop-up then triggers another pop-up, it is
3691 // possible to get the BACK key between here and when the dialog
3692 // appears.
3693 mAnimationCount++;
3694 return true;
3695 }
3696
3697 @Override
3698 public void onCloseWindow(WebView window) {
3699 final int currentIndex = mTabControl.getCurrentIndex();
3700 final TabControl.Tab parent =
3701 mTabControl.getCurrentTab().getParentTab();
3702 if (parent != null) {
3703 // JavaScript can only close popup window.
3704 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3705 }
3706 }
3707
3708 @Override
3709 public void onProgressChanged(WebView view, int newProgress) {
3710 // Block progress updates to the title bar while the tab overview
3711 // is animating or being displayed.
3712 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003713 if (CUSTOM_BROWSER_BAR) {
3714 mTitleBar.setProgress(newProgress);
3715 } else {
3716 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3717 newProgress * 100);
3718
3719 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003720 }
3721
3722 if (newProgress == 100) {
3723 // onProgressChanged() is called for sub-frame too while
3724 // onPageFinished() is only called for the main frame. sync
3725 // cookie and cache promptly here.
3726 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003727 if (mInLoad) {
3728 mInLoad = false;
3729 updateInLoadMenuItems();
3730 }
3731 } else {
3732 // onPageFinished may have already been called but a subframe
3733 // is still loading and updating the progress. Reset mInLoad
3734 // and update the menu items.
3735 if (!mInLoad) {
3736 mInLoad = true;
3737 updateInLoadMenuItems();
3738 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003739 }
3740 }
3741
3742 @Override
3743 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003744 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003745
3746 // here, if url is null, we want to reset the title
3747 setUrlTitle(url, title);
3748
3749 if (url == null ||
3750 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3751 return;
3752 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003753 // See if we can find the current url in our history database and
3754 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003755 if (url.startsWith("http://www.")) {
3756 url = url.substring(11);
3757 } else if (url.startsWith("http://")) {
3758 url = url.substring(4);
3759 }
3760 try {
3761 url = "%" + url;
3762 String [] selArgs = new String[] { url };
3763
3764 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3765 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3766 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3767 Browser.HISTORY_PROJECTION, where, selArgs, null);
3768 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003769 // Current implementation of database only has one entry per
3770 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003771 ContentValues map = new ContentValues();
3772 map.put(Browser.BookmarkColumns.TITLE, title);
3773 mResolver.update(Browser.BOOKMARKS_URI, map,
3774 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003775 }
3776 c.close();
3777 } catch (IllegalStateException e) {
3778 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3779 } catch (SQLiteException ex) {
3780 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3781 }
3782 }
3783
3784 @Override
3785 public void onReceivedIcon(WebView view, Bitmap icon) {
Patrick Scott3918d442009-08-04 13:22:29 -04003786 updateIcon(view, icon);
3787 }
3788
3789 @Override
3790 public void onReceivedTouchIconUrl(WebView view, String url) {
3791 final ContentResolver cr = getContentResolver();
3792 final Cursor c =
3793 BrowserBookmarksAdapter.queryBookmarksForUrl(cr,
Leon Scrogginsa5d669e2009-08-05 14:07:58 -04003794 view.getOriginalUrl(), view.getUrl(), true);
Patrick Scott3918d442009-08-04 13:22:29 -04003795 if (c != null) {
3796 if (c.getCount() > 0) {
3797 new DownloadTouchIcon(cr, c, view).execute(url);
3798 } else {
3799 c.close();
3800 }
3801 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003802 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003803
Andrei Popescuadc008d2009-06-26 14:11:30 +01003804 @Override
Andrei Popescuc9b55562009-07-07 10:51:15 +01003805 public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
Andrei Popescuadc008d2009-06-26 14:11:30 +01003806 if (mCustomView != null)
3807 return;
3808
3809 // Add the custom view to its container.
3810 mCustomViewContainer.addView(view, COVER_SCREEN_GRAVITY_CENTER);
3811 mCustomView = view;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003812 mCustomViewCallback = callback;
Andrei Popescuadc008d2009-06-26 14:11:30 +01003813 // Save the menu state and set it to empty while the custom
3814 // view is showing.
3815 mOldMenuState = mMenuState;
3816 mMenuState = EMPTY_MENU;
Andrei Popescuc9b55562009-07-07 10:51:15 +01003817 // Hide the content view.
3818 mContentView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003819 // Finally show the custom view container.
Andrei Popescuc9b55562009-07-07 10:51:15 +01003820 mCustomViewContainer.setVisibility(View.VISIBLE);
3821 mCustomViewContainer.bringToFront();
Andrei Popescuadc008d2009-06-26 14:11:30 +01003822 }
3823
3824 @Override
3825 public void onHideCustomView() {
3826 if (mCustomView == null)
3827 return;
3828
Andrei Popescuc9b55562009-07-07 10:51:15 +01003829 // Hide the custom view.
3830 mCustomView.setVisibility(View.GONE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003831 // Remove the custom view from its container.
3832 mCustomViewContainer.removeView(mCustomView);
3833 mCustomView = null;
3834 // Reset the old menu state.
3835 mMenuState = mOldMenuState;
3836 mOldMenuState = EMPTY_MENU;
3837 mCustomViewContainer.setVisibility(View.GONE);
Andrei Popescuc9b55562009-07-07 10:51:15 +01003838 mCustomViewCallback.onCustomViewHidden();
3839 // Show the content view.
3840 mContentView.setVisibility(View.VISIBLE);
Andrei Popescuadc008d2009-06-26 14:11:30 +01003841 }
3842
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003843 /**
Andrei Popescu79e82b72009-07-27 12:01:59 +01003844 * The origin has exceeded its database quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003845 * @param url the URL that exceeded the quota
3846 * @param databaseIdentifier the identifier of the database on
3847 * which the transaction that caused the quota overflow was run
3848 * @param currentQuota the current quota for the origin.
Andrei Popescu79e82b72009-07-27 12:01:59 +01003849 * @param totalUsedQuota is the sum of all origins' quota.
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003850 * @param quotaUpdater The callback to run when a decision to allow or
3851 * deny quota has been made. Don't forget to call this!
3852 */
3853 @Override
3854 public void onExceededDatabaseQuota(String url,
Andrei Popescu79e82b72009-07-27 12:01:59 +01003855 String databaseIdentifier, long currentQuota, long totalUsedQuota,
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003856 WebStorage.QuotaUpdater quotaUpdater) {
Andrei Popescu79e82b72009-07-27 12:01:59 +01003857 mSettings.getWebStorageSizeManager().onExceededDatabaseQuota(
3858 url, databaseIdentifier, currentQuota, totalUsedQuota,
3859 quotaUpdater);
3860 }
3861
3862 /**
3863 * The Application Cache has exceeded its max size.
3864 * @param spaceNeeded is the amount of disk space that would be needed
3865 * in order for the last appcache operation to succeed.
3866 * @param totalUsedQuota is the sum of all origins' quota.
3867 * @param quotaUpdater A callback to inform the WebCore thread that a new
3868 * app cache size is available. This callback must always be executed at
3869 * some point to ensure that the sleeping WebCore thread is woken up.
3870 */
3871 @Override
3872 public void onReachedMaxAppCacheSize(long spaceNeeded,
3873 long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
3874 mSettings.getWebStorageSizeManager().onReachedMaxAppCacheSize(
3875 spaceNeeded, totalUsedQuota, quotaUpdater);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003876 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003877
Steve Block2bc69912009-07-30 14:45:13 +01003878 /**
3879 * Instructs the browser to show a prompt to ask the user to set the
3880 * Geolocation permission state for the specified origin.
3881 * @param origin The origin for which Geolocation permissions are
3882 * requested.
3883 * @param callback The callback to call once the user has set the
3884 * Geolocation permission state.
3885 */
3886 @Override
3887 public void onGeolocationPermissionsShowPrompt(String origin,
3888 GeolocationPermissions.Callback callback) {
3889 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().show(
3890 origin, callback);
3891 }
3892
3893 /**
3894 * Instructs the browser to hide the Geolocation permissions prompt.
3895 */
3896 @Override
3897 public void onGeolocationPermissionsHidePrompt() {
3898 mTabControl.getCurrentTab().getGeolocationPermissionsPrompt().hide();
3899 }
3900
Ben Murdoch7db26342009-06-03 18:21:19 +01003901 /* Adds a JavaScript error message to the system log.
3902 * @param message The error message to report.
3903 * @param lineNumber The line number of the error.
3904 * @param sourceID The name of the source file that caused the error.
3905 */
3906 @Override
3907 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
Ben Murdochbff2d602009-07-01 20:19:05 +01003908 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
3909 errorConsole.addErrorMessage(message, sourceID, lineNumber);
3910 if (mShouldShowErrorConsole &&
3911 errorConsole.getShowState() != ErrorConsoleView.SHOW_MAXIMIZED) {
3912 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
3913 }
3914 Log.w(LOGTAG, "Console: " + message + " " + sourceID + ":" + lineNumber);
Ben Murdoch7db26342009-06-03 18:21:19 +01003915 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003916 };
3917
3918 /**
3919 * Notify the host application a download should be done, or that
3920 * the data should be streamed if a streaming viewer is available.
3921 * @param url The full url to the content that should be downloaded
3922 * @param contentDisposition Content-disposition http header, if
3923 * present.
3924 * @param mimetype The mimetype of the content reported by the server
3925 * @param contentLength The file size reported by the server
3926 */
3927 public void onDownloadStart(String url, String userAgent,
3928 String contentDisposition, String mimetype, long contentLength) {
3929 // if we're dealing wih A/V content that's not explicitly marked
3930 // for download, check if it's streamable.
3931 if (contentDisposition == null
3932 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3933 // query the package manager to see if there's a registered handler
3934 // that matches.
3935 Intent intent = new Intent(Intent.ACTION_VIEW);
3936 intent.setDataAndType(Uri.parse(url), mimetype);
3937 if (getPackageManager().resolveActivity(intent,
3938 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3939 // someone knows how to handle this mime type with this scheme, don't download.
3940 try {
3941 startActivity(intent);
3942 return;
3943 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003944 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003945 Log.d(LOGTAG, "activity not found for " + mimetype
3946 + " over " + Uri.parse(url).getScheme(), ex);
3947 }
3948 // Best behavior is to fall back to a download in this case
3949 }
3950 }
3951 }
3952 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3953 }
3954
3955 /**
3956 * Notify the host application a download should be done, even if there
3957 * is a streaming viewer available for thise type.
3958 * @param url The full url to the content that should be downloaded
3959 * @param contentDisposition Content-disposition http header, if
3960 * present.
3961 * @param mimetype The mimetype of the content reported by the server
3962 * @param contentLength The file size reported by the server
3963 */
3964 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3965 String contentDisposition, String mimetype, long contentLength) {
3966
3967 String filename = URLUtil.guessFileName(url,
3968 contentDisposition, mimetype);
3969
3970 // Check to see if we have an SDCard
3971 String status = Environment.getExternalStorageState();
3972 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3973 int title;
3974 String msg;
3975
3976 // Check to see if the SDCard is busy, same as the music app
3977 if (status.equals(Environment.MEDIA_SHARED)) {
3978 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3979 title = R.string.download_sdcard_busy_dlg_title;
3980 } else {
3981 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3982 title = R.string.download_no_sdcard_dlg_title;
3983 }
3984
3985 new AlertDialog.Builder(this)
3986 .setTitle(title)
3987 .setIcon(android.R.drawable.ic_dialog_alert)
3988 .setMessage(msg)
3989 .setPositiveButton(R.string.ok, null)
3990 .show();
3991 return;
3992 }
3993
3994 // java.net.URI is a lot stricter than KURL so we have to undo
3995 // KURL's percent-encoding and redo the encoding using java.net.URI.
3996 URI uri = null;
3997 try {
3998 // Undo the percent-encoding that KURL may have done.
3999 String newUrl = new String(URLUtil.decode(url.getBytes()));
4000 // Parse the url into pieces
4001 WebAddress w = new WebAddress(newUrl);
4002 String frag = null;
4003 String query = null;
4004 String path = w.mPath;
4005 // Break the path into path, query, and fragment
4006 if (path.length() > 0) {
4007 // Strip the fragment
4008 int idx = path.lastIndexOf('#');
4009 if (idx != -1) {
4010 frag = path.substring(idx + 1);
4011 path = path.substring(0, idx);
4012 }
4013 idx = path.lastIndexOf('?');
4014 if (idx != -1) {
4015 query = path.substring(idx + 1);
4016 path = path.substring(0, idx);
4017 }
4018 }
4019 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
4020 query, frag);
4021 } catch (Exception e) {
4022 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
4023 return;
4024 }
4025
4026 // XXX: Have to use the old url since the cookies were stored using the
4027 // old percent-encoded url.
4028 String cookies = CookieManager.getInstance().getCookie(url);
4029
4030 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004031 values.put(Downloads.COLUMN_URI, uri.toString());
4032 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
4033 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
4034 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08004035 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004036 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08004037 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004038 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
4039 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
4040 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
4041 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004042 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07004043 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004044 }
4045 if (mimetype == null) {
4046 // We must have long pressed on a link or image to download it. We
4047 // are not sure of the mimetype in this case, so do a head request
4048 new FetchUrlMimeType(this).execute(values);
4049 } else {
4050 final Uri contentUri =
4051 getContentResolver().insert(Downloads.CONTENT_URI, values);
4052 viewDownloads(contentUri);
4053 }
4054
4055 }
4056
4057 /**
4058 * Resets the lock icon. This method is called when we start a new load and
4059 * know the url to be loaded.
4060 */
4061 private void resetLockIcon(String url) {
4062 // Save the lock-icon state (we revert to it if the load gets cancelled)
4063 saveLockIcon();
4064
4065 mLockIconType = LOCK_ICON_UNSECURE;
4066 if (URLUtil.isHttpsUrl(url)) {
4067 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07004068 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004069 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4070 " reset lock icon to " + mLockIconType);
4071 }
4072 }
4073
4074 updateLockIconImage(LOCK_ICON_UNSECURE);
4075 }
4076
4077 /**
4078 * Resets the lock icon. This method is called when the icon needs to be
4079 * reset but we do not know whether we are loading a secure or not secure
4080 * page.
4081 */
4082 private void resetLockIcon() {
4083 // Save the lock-icon state (we revert to it if the load gets cancelled)
4084 saveLockIcon();
4085
4086 mLockIconType = LOCK_ICON_UNSECURE;
4087
Dave Bort31a6d1c2009-04-13 15:56:49 -07004088 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004089 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
4090 " reset lock icon to " + mLockIconType);
4091 }
4092
4093 updateLockIconImage(LOCK_ICON_UNSECURE);
4094 }
4095
4096 /**
4097 * Updates the lock-icon image in the title-bar.
4098 */
4099 private void updateLockIconImage(int lockIconType) {
4100 Drawable d = null;
4101 if (lockIconType == LOCK_ICON_SECURE) {
4102 d = mSecLockIcon;
4103 } else if (lockIconType == LOCK_ICON_MIXED) {
4104 d = mMixLockIcon;
4105 }
4106 // If the tab overview is animating or being shown, do not update the
4107 // lock icon.
4108 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04004109 if (CUSTOM_BROWSER_BAR) {
4110 mTitleBar.setLock(d);
4111 } else {
4112 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
4113 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004114 }
4115 }
4116
4117 /**
4118 * Displays a page-info dialog.
4119 * @param tab The tab to show info about
4120 * @param fromShowSSLCertificateOnError The flag that indicates whether
4121 * this dialog was opened from the SSL-certificate-on-error dialog or
4122 * not. This is important, since we need to know whether to return to
4123 * the parent dialog or simply dismiss.
4124 */
4125 private void showPageInfo(final TabControl.Tab tab,
4126 final boolean fromShowSSLCertificateOnError) {
4127 final LayoutInflater factory = LayoutInflater
4128 .from(this);
4129
4130 final View pageInfoView = factory.inflate(R.layout.page_info, null);
4131
4132 final WebView view = tab.getWebView();
4133
4134 String url = null;
4135 String title = null;
4136
4137 if (view == null) {
4138 url = tab.getUrl();
4139 title = tab.getTitle();
4140 } else if (view == mTabControl.getCurrentWebView()) {
4141 // Use the cached title and url if this is the current WebView
4142 url = mUrl;
4143 title = mTitle;
4144 } else {
4145 url = view.getUrl();
4146 title = view.getTitle();
4147 }
4148
4149 if (url == null) {
4150 url = "";
4151 }
4152 if (title == null) {
4153 title = "";
4154 }
4155
4156 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
4157 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
4158
4159 mPageInfoView = tab;
4160 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
4161
4162 AlertDialog.Builder alertDialogBuilder =
4163 new AlertDialog.Builder(this)
4164 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
4165 .setView(pageInfoView)
4166 .setPositiveButton(
4167 R.string.ok,
4168 new DialogInterface.OnClickListener() {
4169 public void onClick(DialogInterface dialog,
4170 int whichButton) {
4171 mPageInfoDialog = null;
4172 mPageInfoView = null;
4173 mPageInfoFromShowSSLCertificateOnError = null;
4174
4175 // if we came here from the SSL error dialog
4176 if (fromShowSSLCertificateOnError) {
4177 // go back to the SSL error dialog
4178 showSSLCertificateOnError(
4179 mSSLCertificateOnErrorView,
4180 mSSLCertificateOnErrorHandler,
4181 mSSLCertificateOnErrorError);
4182 }
4183 }
4184 })
4185 .setOnCancelListener(
4186 new DialogInterface.OnCancelListener() {
4187 public void onCancel(DialogInterface dialog) {
4188 mPageInfoDialog = null;
4189 mPageInfoView = null;
4190 mPageInfoFromShowSSLCertificateOnError = null;
4191
4192 // if we came here from the SSL error dialog
4193 if (fromShowSSLCertificateOnError) {
4194 // go back to the SSL error dialog
4195 showSSLCertificateOnError(
4196 mSSLCertificateOnErrorView,
4197 mSSLCertificateOnErrorHandler,
4198 mSSLCertificateOnErrorError);
4199 }
4200 }
4201 });
4202
4203 // if we have a main top-level page SSL certificate set or a certificate
4204 // error
4205 if (fromShowSSLCertificateOnError ||
4206 (view != null && view.getCertificate() != null)) {
4207 // add a 'View Certificate' button
4208 alertDialogBuilder.setNeutralButton(
4209 R.string.view_certificate,
4210 new DialogInterface.OnClickListener() {
4211 public void onClick(DialogInterface dialog,
4212 int whichButton) {
4213 mPageInfoDialog = null;
4214 mPageInfoView = null;
4215 mPageInfoFromShowSSLCertificateOnError = null;
4216
4217 // if we came here from the SSL error dialog
4218 if (fromShowSSLCertificateOnError) {
4219 // go back to the SSL error dialog
4220 showSSLCertificateOnError(
4221 mSSLCertificateOnErrorView,
4222 mSSLCertificateOnErrorHandler,
4223 mSSLCertificateOnErrorError);
4224 } else {
4225 // otherwise, display the top-most certificate from
4226 // the chain
4227 if (view.getCertificate() != null) {
4228 showSSLCertificate(tab);
4229 }
4230 }
4231 }
4232 });
4233 }
4234
4235 mPageInfoDialog = alertDialogBuilder.show();
4236 }
4237
4238 /**
4239 * Displays the main top-level page SSL certificate dialog
4240 * (accessible from the Page-Info dialog).
4241 * @param tab The tab to show certificate for.
4242 */
4243 private void showSSLCertificate(final TabControl.Tab tab) {
4244 final View certificateView =
4245 inflateCertificateView(tab.getWebView().getCertificate());
4246 if (certificateView == null) {
4247 return;
4248 }
4249
4250 LayoutInflater factory = LayoutInflater.from(this);
4251
4252 final LinearLayout placeholder =
4253 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4254
4255 LinearLayout ll = (LinearLayout) factory.inflate(
4256 R.layout.ssl_success, placeholder);
4257 ((TextView)ll.findViewById(R.id.success))
4258 .setText(R.string.ssl_certificate_is_valid);
4259
4260 mSSLCertificateView = tab;
4261 mSSLCertificateDialog =
4262 new AlertDialog.Builder(this)
4263 .setTitle(R.string.ssl_certificate).setIcon(
4264 R.drawable.ic_dialog_browser_certificate_secure)
4265 .setView(certificateView)
4266 .setPositiveButton(R.string.ok,
4267 new DialogInterface.OnClickListener() {
4268 public void onClick(DialogInterface dialog,
4269 int whichButton) {
4270 mSSLCertificateDialog = null;
4271 mSSLCertificateView = null;
4272
4273 showPageInfo(tab, false);
4274 }
4275 })
4276 .setOnCancelListener(
4277 new DialogInterface.OnCancelListener() {
4278 public void onCancel(DialogInterface dialog) {
4279 mSSLCertificateDialog = null;
4280 mSSLCertificateView = null;
4281
4282 showPageInfo(tab, false);
4283 }
4284 })
4285 .show();
4286 }
4287
4288 /**
4289 * Displays the SSL error certificate dialog.
4290 * @param view The target web-view.
4291 * @param handler The SSL error handler responsible for cancelling the
4292 * connection that resulted in an SSL error or proceeding per user request.
4293 * @param error The SSL error object.
4294 */
4295 private void showSSLCertificateOnError(
4296 final WebView view, final SslErrorHandler handler, final SslError error) {
4297
4298 final View certificateView =
4299 inflateCertificateView(error.getCertificate());
4300 if (certificateView == null) {
4301 return;
4302 }
4303
4304 LayoutInflater factory = LayoutInflater.from(this);
4305
4306 final LinearLayout placeholder =
4307 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4308
4309 if (error.hasError(SslError.SSL_UNTRUSTED)) {
4310 LinearLayout ll = (LinearLayout)factory
4311 .inflate(R.layout.ssl_warning, placeholder);
4312 ((TextView)ll.findViewById(R.id.warning))
4313 .setText(R.string.ssl_untrusted);
4314 }
4315
4316 if (error.hasError(SslError.SSL_IDMISMATCH)) {
4317 LinearLayout ll = (LinearLayout)factory
4318 .inflate(R.layout.ssl_warning, placeholder);
4319 ((TextView)ll.findViewById(R.id.warning))
4320 .setText(R.string.ssl_mismatch);
4321 }
4322
4323 if (error.hasError(SslError.SSL_EXPIRED)) {
4324 LinearLayout ll = (LinearLayout)factory
4325 .inflate(R.layout.ssl_warning, placeholder);
4326 ((TextView)ll.findViewById(R.id.warning))
4327 .setText(R.string.ssl_expired);
4328 }
4329
4330 if (error.hasError(SslError.SSL_NOTYETVALID)) {
4331 LinearLayout ll = (LinearLayout)factory
4332 .inflate(R.layout.ssl_warning, placeholder);
4333 ((TextView)ll.findViewById(R.id.warning))
4334 .setText(R.string.ssl_not_yet_valid);
4335 }
4336
4337 mSSLCertificateOnErrorHandler = handler;
4338 mSSLCertificateOnErrorView = view;
4339 mSSLCertificateOnErrorError = error;
4340 mSSLCertificateOnErrorDialog =
4341 new AlertDialog.Builder(this)
4342 .setTitle(R.string.ssl_certificate).setIcon(
4343 R.drawable.ic_dialog_browser_certificate_partially_secure)
4344 .setView(certificateView)
4345 .setPositiveButton(R.string.ok,
4346 new DialogInterface.OnClickListener() {
4347 public void onClick(DialogInterface dialog,
4348 int whichButton) {
4349 mSSLCertificateOnErrorDialog = null;
4350 mSSLCertificateOnErrorView = null;
4351 mSSLCertificateOnErrorHandler = null;
4352 mSSLCertificateOnErrorError = null;
4353
4354 mWebViewClient.onReceivedSslError(
4355 view, handler, error);
4356 }
4357 })
4358 .setNeutralButton(R.string.page_info_view,
4359 new DialogInterface.OnClickListener() {
4360 public void onClick(DialogInterface dialog,
4361 int whichButton) {
4362 mSSLCertificateOnErrorDialog = null;
4363
4364 // do not clear the dialog state: we will
4365 // need to show the dialog again once the
4366 // user is done exploring the page-info details
4367
4368 showPageInfo(mTabControl.getTabFromView(view),
4369 true);
4370 }
4371 })
4372 .setOnCancelListener(
4373 new DialogInterface.OnCancelListener() {
4374 public void onCancel(DialogInterface dialog) {
4375 mSSLCertificateOnErrorDialog = null;
4376 mSSLCertificateOnErrorView = null;
4377 mSSLCertificateOnErrorHandler = null;
4378 mSSLCertificateOnErrorError = null;
4379
4380 mWebViewClient.onReceivedSslError(
4381 view, handler, error);
4382 }
4383 })
4384 .show();
4385 }
4386
4387 /**
4388 * Inflates the SSL certificate view (helper method).
4389 * @param certificate The SSL certificate.
4390 * @return The resultant certificate view with issued-to, issued-by,
4391 * issued-on, expires-on, and possibly other fields set.
4392 * If the input certificate is null, returns null.
4393 */
4394 private View inflateCertificateView(SslCertificate certificate) {
4395 if (certificate == null) {
4396 return null;
4397 }
4398
4399 LayoutInflater factory = LayoutInflater.from(this);
4400
4401 View certificateView = factory.inflate(
4402 R.layout.ssl_certificate, null);
4403
4404 // issued to:
4405 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4406 if (issuedTo != null) {
4407 ((TextView) certificateView.findViewById(R.id.to_common))
4408 .setText(issuedTo.getCName());
4409 ((TextView) certificateView.findViewById(R.id.to_org))
4410 .setText(issuedTo.getOName());
4411 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4412 .setText(issuedTo.getUName());
4413 }
4414
4415 // issued by:
4416 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4417 if (issuedBy != null) {
4418 ((TextView) certificateView.findViewById(R.id.by_common))
4419 .setText(issuedBy.getCName());
4420 ((TextView) certificateView.findViewById(R.id.by_org))
4421 .setText(issuedBy.getOName());
4422 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4423 .setText(issuedBy.getUName());
4424 }
4425
4426 // issued on:
4427 String issuedOn = reformatCertificateDate(
4428 certificate.getValidNotBefore());
4429 ((TextView) certificateView.findViewById(R.id.issued_on))
4430 .setText(issuedOn);
4431
4432 // expires on:
4433 String expiresOn = reformatCertificateDate(
4434 certificate.getValidNotAfter());
4435 ((TextView) certificateView.findViewById(R.id.expires_on))
4436 .setText(expiresOn);
4437
4438 return certificateView;
4439 }
4440
4441 /**
4442 * Re-formats the certificate date (Date.toString()) string to
4443 * a properly localized date string.
4444 * @return Properly localized version of the certificate date string and
4445 * the original certificate date string if fails to localize.
4446 * If the original string is null, returns an empty string "".
4447 */
4448 private String reformatCertificateDate(String certificateDate) {
4449 String reformattedDate = null;
4450
4451 if (certificateDate != null) {
4452 Date date = null;
4453 try {
4454 date = java.text.DateFormat.getInstance().parse(certificateDate);
4455 } catch (ParseException e) {
4456 date = null;
4457 }
4458
4459 if (date != null) {
4460 reformattedDate =
4461 DateFormat.getDateFormat(this).format(date);
4462 }
4463 }
4464
4465 return reformattedDate != null ? reformattedDate :
4466 (certificateDate != null ? certificateDate : "");
4467 }
4468
4469 /**
4470 * Displays an http-authentication dialog.
4471 */
4472 private void showHttpAuthentication(final HttpAuthHandler handler,
4473 final String host, final String realm, final String title,
4474 final String name, final String password, int focusId) {
4475 LayoutInflater factory = LayoutInflater.from(this);
4476 final View v = factory
4477 .inflate(R.layout.http_authentication, null);
4478 if (name != null) {
4479 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4480 }
4481 if (password != null) {
4482 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4483 }
4484
4485 String titleText = title;
4486 if (titleText == null) {
4487 titleText = getText(R.string.sign_in_to).toString().replace(
4488 "%s1", host).replace("%s2", realm);
4489 }
4490
4491 mHttpAuthHandler = handler;
4492 AlertDialog dialog = new AlertDialog.Builder(this)
4493 .setTitle(titleText)
4494 .setIcon(android.R.drawable.ic_dialog_alert)
4495 .setView(v)
4496 .setPositiveButton(R.string.action,
4497 new DialogInterface.OnClickListener() {
4498 public void onClick(DialogInterface dialog,
4499 int whichButton) {
4500 String nm = ((EditText) v
4501 .findViewById(R.id.username_edit))
4502 .getText().toString();
4503 String pw = ((EditText) v
4504 .findViewById(R.id.password_edit))
4505 .getText().toString();
4506 BrowserActivity.this.setHttpAuthUsernamePassword
4507 (host, realm, nm, pw);
4508 handler.proceed(nm, pw);
4509 mHttpAuthenticationDialog = null;
4510 mHttpAuthHandler = null;
4511 }})
4512 .setNegativeButton(R.string.cancel,
4513 new DialogInterface.OnClickListener() {
4514 public void onClick(DialogInterface dialog,
4515 int whichButton) {
4516 handler.cancel();
4517 BrowserActivity.this.resetTitleAndRevertLockIcon();
4518 mHttpAuthenticationDialog = null;
4519 mHttpAuthHandler = null;
4520 }})
4521 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4522 public void onCancel(DialogInterface dialog) {
4523 handler.cancel();
4524 BrowserActivity.this.resetTitleAndRevertLockIcon();
4525 mHttpAuthenticationDialog = null;
4526 mHttpAuthHandler = null;
4527 }})
4528 .create();
4529 // Make the IME appear when the dialog is displayed if applicable.
4530 dialog.getWindow().setSoftInputMode(
4531 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4532 dialog.show();
4533 if (focusId != 0) {
4534 dialog.findViewById(focusId).requestFocus();
4535 } else {
4536 v.findViewById(R.id.username_edit).requestFocus();
4537 }
4538 mHttpAuthenticationDialog = dialog;
4539 }
4540
4541 public int getProgress() {
4542 WebView w = mTabControl.getCurrentWebView();
4543 if (w != null) {
4544 return w.getProgress();
4545 } else {
4546 return 100;
4547 }
4548 }
4549
4550 /**
4551 * Set HTTP authentication password.
4552 *
4553 * @param host The host for the password
4554 * @param realm The realm for the password
4555 * @param username The username for the password. If it is null, it means
4556 * password can't be saved.
4557 * @param password The password
4558 */
4559 public void setHttpAuthUsernamePassword(String host, String realm,
4560 String username,
4561 String password) {
4562 WebView w = mTabControl.getCurrentWebView();
4563 if (w != null) {
4564 w.setHttpAuthUsernamePassword(host, realm, username, password);
4565 }
4566 }
4567
4568 /**
4569 * connectivity manager says net has come or gone... inform the user
4570 * @param up true if net has come up, false if net has gone down
4571 */
4572 public void onNetworkToggle(boolean up) {
4573 if (up == mIsNetworkUp) {
4574 return;
4575 } else if (up) {
4576 mIsNetworkUp = true;
4577 if (mAlertDialog != null) {
4578 mAlertDialog.cancel();
4579 mAlertDialog = null;
4580 }
4581 } else {
4582 mIsNetworkUp = false;
4583 if (mInLoad && mAlertDialog == null) {
4584 mAlertDialog = new AlertDialog.Builder(this)
4585 .setTitle(R.string.loadSuspendedTitle)
4586 .setMessage(R.string.loadSuspended)
4587 .setPositiveButton(R.string.ok, null)
4588 .show();
4589 }
4590 }
4591 WebView w = mTabControl.getCurrentWebView();
4592 if (w != null) {
4593 w.setNetworkAvailable(up);
4594 }
4595 }
4596
4597 @Override
4598 protected void onActivityResult(int requestCode, int resultCode,
4599 Intent intent) {
4600 switch (requestCode) {
4601 case COMBO_PAGE:
4602 if (resultCode == RESULT_OK && intent != null) {
4603 String data = intent.getAction();
4604 Bundle extras = intent.getExtras();
4605 if (extras != null && extras.getBoolean("new_window", false)) {
Patrick Scottb0e4fc72009-07-14 10:49:22 -04004606 final TabControl.Tab newTab = openTab(data);
4607 if (mSettings.openInBackground() &&
4608 newTab != null && mTabOverview != null) {
4609 mTabControl.populatePickerData(newTab);
4610 mTabControl.setCurrentTab(newTab);
4611 mTabOverview.add(newTab);
4612 mTabOverview.setCurrentIndex(
4613 mTabControl.getCurrentIndex());
4614 sendAnimateFromOverview(newTab, false,
4615 EMPTY_URL_DATA, TAB_OVERVIEW_DELAY, null);
4616 }
Leon Scroggins64b80f32009-08-07 12:03:34 -04004617 } else if (intent.getBooleanExtra("open_search", false)) {
4618 onSearchRequested();
The Android Open Source Project0c908882009-03-03 19:32:16 -08004619 } else {
4620 final TabControl.Tab currentTab =
4621 mTabControl.getCurrentTab();
4622 // If the Window overview is up and we are not in the
4623 // middle of an animation, animate away from it to the
4624 // current tab.
4625 if (mTabOverview != null && mAnimationCount == 0) {
Grace Klobaec7eb372009-06-16 13:45:56 -07004626 sendAnimateFromOverview(currentTab, false,
4627 new UrlData(data), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004628 } else {
4629 dismissSubWindow(currentTab);
4630 if (data != null && data.length() != 0) {
4631 getTopWindow().loadUrl(data);
4632 }
4633 }
4634 }
4635 }
4636 break;
4637 default:
4638 break;
4639 }
4640 getTopWindow().requestFocus();
4641 }
4642
4643 /*
4644 * This method is called as a result of the user selecting the options
4645 * menu to see the download window, or when a download changes state. It
4646 * shows the download window ontop of the current window.
4647 */
4648 /* package */ void viewDownloads(Uri downloadRecord) {
4649 Intent intent = new Intent(this,
4650 BrowserDownloadPage.class);
4651 intent.setData(downloadRecord);
4652 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4653
4654 }
4655
4656 /**
4657 * Handle results from Tab Switcher mTabOverview tool
4658 */
4659 private class TabListener implements ImageGrid.Listener {
4660 public void remove(int position) {
4661 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004662 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004663 throw new AssertionError();
4664 }
4665
4666 // Remember the current tab.
4667 TabControl.Tab current = mTabControl.getCurrentTab();
4668 final TabControl.Tab remove = mTabControl.getTab(position);
4669 mTabControl.removeTab(remove);
4670 // If we removed the current tab, use the tab at position - 1 if
4671 // possible.
4672 if (current == remove) {
4673 // If the user removes the last tab, act like the New Tab item
4674 // was clicked on.
4675 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004676 current = mTabControl.createNewTab();
Leon Scroggins64b80f32009-08-07 12:03:34 -04004677 sendAnimateFromOverview(current, true, EMPTY_URL_DATA,
4678 TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004679 } else {
4680 final int index = position > 0 ? (position - 1) : 0;
4681 current = mTabControl.getTab(index);
4682 }
4683 }
4684
4685 // The tab overview could have been dismissed before this method is
4686 // called.
4687 if (mTabOverview != null) {
4688 // Remove the tab and change the index.
4689 mTabOverview.remove(position);
4690 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4691 }
4692
4693 // Only the current tab ensures its WebView is non-null. This
4694 // implies that we are reloading the freed tab.
4695 mTabControl.setCurrentTab(current);
4696 }
4697 public void onClick(int index) {
4698 // Change the tab if necessary.
4699 // Index equals ImageGrid.CANCEL when pressing back from the tab
4700 // overview.
4701 if (index == ImageGrid.CANCEL) {
4702 index = mTabControl.getCurrentIndex();
4703 // The current index is -1 if the current tab was removed.
4704 if (index == -1) {
4705 // Take the last tab as a fallback.
4706 index = mTabControl.getTabCount() - 1;
4707 }
4708 }
4709
The Android Open Source Project0c908882009-03-03 19:32:16 -08004710 // NEW_TAB means that the "New Tab" cell was clicked on.
4711 if (index == ImageGrid.NEW_TAB) {
Leon Scroggins64b80f32009-08-07 12:03:34 -04004712 openTabAndShow(EMPTY_URL_DATA, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004713 } else {
Grace Klobaec7eb372009-06-16 13:45:56 -07004714 sendAnimateFromOverview(mTabControl.getTab(index), false,
4715 EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004716 }
4717 }
4718 }
4719
4720 // A fake View that draws the WebView's picture with a fast zoom filter.
4721 // The View is used in case the tab is freed during the animation because
4722 // of low memory.
4723 private static class AnimatingView extends View {
4724 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4725 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4726 private static final DrawFilter sZoomFilter =
4727 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4728 private final Picture mPicture;
4729 private final float mScale;
4730 private final int mScrollX;
4731 private final int mScrollY;
4732 final TabControl.Tab mTab;
4733
4734 AnimatingView(Context ctxt, TabControl.Tab t) {
4735 super(ctxt);
4736 mTab = t;
Patrick Scottae641ac2009-04-20 13:51:49 -04004737 if (t != null && t.getTopWindow() != null) {
4738 // Use the top window in the animation since the tab overview
4739 // will display the top window in each cell.
4740 final WebView w = t.getTopWindow();
4741 mPicture = w.capturePicture();
4742 mScale = w.getScale() / w.getWidth();
4743 mScrollX = w.getScrollX();
4744 mScrollY = w.getScrollY();
4745 } else {
4746 mPicture = null;
4747 mScale = 1.0f;
4748 mScrollX = mScrollY = 0;
4749 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004750 }
4751
4752 @Override
4753 protected void onDraw(Canvas canvas) {
4754 canvas.save();
4755 canvas.drawColor(Color.WHITE);
4756 if (mPicture != null) {
4757 canvas.setDrawFilter(sZoomFilter);
4758 float scale = getWidth() * mScale;
4759 canvas.scale(scale, scale);
4760 canvas.translate(-mScrollX, -mScrollY);
4761 canvas.drawPicture(mPicture);
4762 }
4763 canvas.restore();
4764 }
4765 }
4766
4767 /**
4768 * Open the tab picker. This function will always use the current tab in
4769 * its animation.
4770 * @param stay boolean stating whether the tab picker is to remain open
4771 * (in which case it needs a listener and its menu) or not.
4772 * @param index The index of the tab to show as the selection in the tab
4773 * overview.
4774 * @param remove If true, the tab at index will be removed after the
4775 * animation completes.
4776 */
4777 private void tabPicker(final boolean stay, final int index,
4778 final boolean remove) {
4779 if (mTabOverview != null) {
4780 return;
4781 }
4782
4783 int size = mTabControl.getTabCount();
4784
4785 TabListener l = null;
4786 if (stay) {
4787 l = mTabListener = new TabListener();
4788 }
4789 mTabOverview = new ImageGrid(this, stay, l);
4790
4791 for (int i = 0; i < size; i++) {
4792 final TabControl.Tab t = mTabControl.getTab(i);
4793 mTabControl.populatePickerData(t);
4794 mTabOverview.add(t);
4795 }
4796
4797 // Tell the tab overview to show the current tab, the tab overview will
4798 // handle the "New Tab" case.
4799 int currentIndex = mTabControl.getCurrentIndex();
4800 mTabOverview.setCurrentIndex(currentIndex);
4801
4802 // Attach the tab overview.
4803 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4804
4805 // Create a fake AnimatingView to animate the WebView's picture.
4806 final TabControl.Tab current = mTabControl.getCurrentTab();
4807 final AnimatingView v = new AnimatingView(this, current);
4808 mContentView.addView(v, COVER_SCREEN_PARAMS);
4809 removeTabFromContentView(current);
4810 // Pause timers to get the animation smoother.
4811 current.getWebView().pauseTimers();
4812
4813 // Send a message so the tab picker has a chance to layout and get
4814 // positions for all the cells.
4815 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4816 index, remove ? 1 : 0, v));
4817 // Setting this will indicate that we are animating to the overview. We
4818 // set it here to prevent another request to animate from coming in
4819 // between now and when ANIMATE_TO_OVERVIEW is handled.
4820 mAnimationCount++;
4821 // Always change the title bar to the window overview title while
4822 // animating.
Leon Scroggins81db3662009-06-04 17:45:11 -04004823 if (CUSTOM_BROWSER_BAR) {
4824 mTitleBar.setToTabPicker();
4825 } else {
4826 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4827 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4828 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4829 Window.PROGRESS_VISIBILITY_OFF);
4830 setTitle(R.string.tab_picker_title);
4831 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004832 // Make the menu empty until the animation completes.
4833 mMenuState = EMPTY_MENU;
4834 }
4835
Leon Scrogginse4b3bda2009-06-09 15:46:41 -04004836 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004837 WebView current = mTabControl.getCurrentWebView();
4838 if (current == null) {
4839 return;
4840 }
4841 Intent intent = new Intent(this,
4842 CombinedBookmarkHistoryActivity.class);
4843 String title = current.getTitle();
4844 String url = current.getUrl();
4845 // Just in case the user opens bookmarks before a page finishes loading
4846 // so the current history item, and therefore the page, is null.
4847 if (null == url) {
4848 url = mLastEnteredUrl;
4849 // This can happen.
4850 if (null == url) {
4851 url = mSettings.getHomePage();
4852 }
4853 }
4854 // In case the web page has not yet received its associated title.
4855 if (title == null) {
4856 title = url;
4857 }
4858 intent.putExtra("title", title);
4859 intent.putExtra("url", url);
4860 intent.putExtra("maxTabsOpen",
4861 mTabControl.getTabCount() >= TabControl.MAX_TABS);
Patrick Scott3918d442009-08-04 13:22:29 -04004862 intent.putExtra("touch_icon_url", current.getTouchIconUrl());
The Android Open Source Project0c908882009-03-03 19:32:16 -08004863 if (startWithHistory) {
4864 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4865 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4866 }
4867 startActivityForResult(intent, COMBO_PAGE);
4868 }
4869
4870 // Called when loading from context menu or LOAD_URL message
4871 private void loadURL(WebView view, String url) {
4872 // In case the user enters nothing.
4873 if (url != null && url.length() != 0 && view != null) {
4874 url = smartUrlFilter(url);
4875 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4876 view.loadUrl(url);
4877 }
4878 }
4879 }
4880
The Android Open Source Project0c908882009-03-03 19:32:16 -08004881 private String smartUrlFilter(Uri inUri) {
4882 if (inUri != null) {
4883 return smartUrlFilter(inUri.toString());
4884 }
4885 return null;
4886 }
4887
4888
4889 // get window count
4890
4891 int getWindowCount(){
4892 if(mTabControl != null){
4893 return mTabControl.getTabCount();
4894 }
4895 return 0;
4896 }
4897
Feng Qianb34f87a2009-03-24 21:27:26 -07004898 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004899 "(?i)" + // switch on case insensitive matching
4900 "(" + // begin group for schema
4901 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004902 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004903 ")" +
4904 "(.*)" );
4905
4906 /**
4907 * Attempts to determine whether user input is a URL or search
4908 * terms. Anything with a space is passed to search.
4909 *
4910 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4911 * "Http://" converts to "http://"
4912 *
4913 * @return Original or modified URL
4914 *
4915 */
4916 String smartUrlFilter(String url) {
4917
4918 String inUrl = url.trim();
4919 boolean hasSpace = inUrl.indexOf(' ') != -1;
4920
4921 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4922 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004923 // force scheme to lowercase
4924 String scheme = matcher.group(1);
4925 String lcScheme = scheme.toLowerCase();
4926 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004927 inUrl = lcScheme + matcher.group(2);
4928 }
4929 if (hasSpace) {
4930 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004931 }
4932 return inUrl;
4933 }
4934 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004935 // FIXME: Is this the correct place to add to searches?
4936 // what if someone else calls this function?
4937 int shortcut = parseUrlShortcut(inUrl);
4938 if (shortcut != SHORTCUT_INVALID) {
4939 Browser.addSearchUrl(mResolver, inUrl);
4940 String query = inUrl.substring(2);
4941 switch (shortcut) {
4942 case SHORTCUT_GOOGLE_SEARCH:
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004943 return URLUtil.composeSearchUrl(query, QuickSearch_G, QUERY_PLACE_HOLDER);
Satish Sampath565505b2009-05-29 15:37:27 +01004944 case SHORTCUT_WIKIPEDIA_SEARCH:
4945 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4946 case SHORTCUT_DICTIONARY_SEARCH:
4947 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4948 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004949 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004950 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004951 }
4952 }
4953 } else {
4954 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4955 return URLUtil.guessUrl(inUrl);
4956 }
4957 }
4958
4959 Browser.addSearchUrl(mResolver, inUrl);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07004960 return URLUtil.composeSearchUrl(inUrl, QuickSearch_G, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004961 }
4962
Ben Murdochbff2d602009-07-01 20:19:05 +01004963 /* package */ void setShouldShowErrorConsole(boolean flag) {
4964 if (flag == mShouldShowErrorConsole) {
4965 // Nothing to do.
4966 return;
4967 }
4968
4969 mShouldShowErrorConsole = flag;
4970
4971 ErrorConsoleView errorConsole = mTabControl.getCurrentErrorConsole(true);
4972
4973 if (flag) {
4974 // Setting the show state of the console will cause it's the layout to be inflated.
4975 if (errorConsole.numberOfErrors() > 0) {
4976 errorConsole.showConsole(ErrorConsoleView.SHOW_MINIMIZED);
4977 } else {
4978 errorConsole.showConsole(ErrorConsoleView.SHOW_NONE);
4979 }
4980
4981 // Now we can add it to the main view.
4982 mErrorConsoleContainer.addView(errorConsole,
4983 new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
4984 ViewGroup.LayoutParams.WRAP_CONTENT));
4985 } else {
4986 mErrorConsoleContainer.removeView(errorConsole);
4987 }
4988
4989 }
4990
The Android Open Source Project0c908882009-03-03 19:32:16 -08004991 private final static int LOCK_ICON_UNSECURE = 0;
4992 private final static int LOCK_ICON_SECURE = 1;
4993 private final static int LOCK_ICON_MIXED = 2;
4994
4995 private int mLockIconType = LOCK_ICON_UNSECURE;
4996 private int mPrevLockType = LOCK_ICON_UNSECURE;
4997
4998 private BrowserSettings mSettings;
4999 private TabControl mTabControl;
5000 private ContentResolver mResolver;
5001 private FrameLayout mContentView;
5002 private ImageGrid mTabOverview;
Andrei Popescuadc008d2009-06-26 14:11:30 +01005003 private View mCustomView;
5004 private FrameLayout mCustomViewContainer;
Andrei Popescuc9b55562009-07-07 10:51:15 +01005005 private WebChromeClient.CustomViewCallback mCustomViewCallback;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005006
5007 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
5008 // view, we should rewrite this.
5009 private int mCurrentMenuState = 0;
5010 private int mMenuState = R.id.MAIN_MENU;
Andrei Popescuadc008d2009-06-26 14:11:30 +01005011 private int mOldMenuState = EMPTY_MENU;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005012 private static final int EMPTY_MENU = -1;
5013 private Menu mMenu;
5014
5015 private FindDialog mFindDialog;
5016 // Used to prevent chording to result in firing two shortcuts immediately
5017 // one after another. Fixes bug 1211714.
5018 boolean mCanChord;
5019
5020 private boolean mInLoad;
5021 private boolean mIsNetworkUp;
5022
5023 private boolean mPageStarted;
5024 private boolean mActivityInPause = true;
5025
5026 private boolean mMenuIsDown;
5027
5028 private final KeyTracker mKeyTracker = new KeyTracker(this);
5029
5030 // As trackball doesn't send repeat down, we have to track it ourselves
5031 private boolean mTrackTrackball;
5032
5033 private static boolean mInTrace;
5034
5035 // Performance probe
5036 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
5037 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
5038 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
5039 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
5040 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
5041 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
5042 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
5043 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
5044 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
5045 };
5046
5047 private long mStart;
5048 private long mProcessStart;
5049 private long mUserStart;
5050 private long mSystemStart;
5051 private long mIdleStart;
5052 private long mIrqStart;
5053
5054 private long mUiStart;
5055
5056 private Drawable mMixLockIcon;
5057 private Drawable mSecLockIcon;
5058 private Drawable mGenericFavicon;
5059
5060 /* hold a ref so we can auto-cancel if necessary */
5061 private AlertDialog mAlertDialog;
5062
5063 // Wait for credentials before loading google.com
5064 private ProgressDialog mCredsDlg;
5065
5066 // The up-to-date URL and title (these can be different from those stored
5067 // in WebView, since it takes some time for the information in WebView to
5068 // get updated)
5069 private String mUrl;
5070 private String mTitle;
5071
5072 // As PageInfo has different style for landscape / portrait, we have
5073 // to re-open it when configuration changed
5074 private AlertDialog mPageInfoDialog;
5075 private TabControl.Tab mPageInfoView;
5076 // If the Page-Info dialog is launched from the SSL-certificate-on-error
5077 // dialog, we should not just dismiss it, but should get back to the
5078 // SSL-certificate-on-error dialog. This flag is used to store this state
5079 private Boolean mPageInfoFromShowSSLCertificateOnError;
5080
5081 // as SSLCertificateOnError has different style for landscape / portrait,
5082 // we have to re-open it when configuration changed
5083 private AlertDialog mSSLCertificateOnErrorDialog;
5084 private WebView mSSLCertificateOnErrorView;
5085 private SslErrorHandler mSSLCertificateOnErrorHandler;
5086 private SslError mSSLCertificateOnErrorError;
5087
5088 // as SSLCertificate has different style for landscape / portrait, we
5089 // have to re-open it when configuration changed
5090 private AlertDialog mSSLCertificateDialog;
5091 private TabControl.Tab mSSLCertificateView;
5092
5093 // as HttpAuthentication has different style for landscape / portrait, we
5094 // have to re-open it when configuration changed
5095 private AlertDialog mHttpAuthenticationDialog;
5096 private HttpAuthHandler mHttpAuthHandler;
5097
5098 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
5099 new FrameLayout.LayoutParams(
5100 ViewGroup.LayoutParams.FILL_PARENT,
5101 ViewGroup.LayoutParams.FILL_PARENT);
Andrei Popescuadc008d2009-06-26 14:11:30 +01005102 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_GRAVITY_CENTER =
5103 new FrameLayout.LayoutParams(
5104 ViewGroup.LayoutParams.FILL_PARENT,
5105 ViewGroup.LayoutParams.FILL_PARENT,
5106 Gravity.CENTER);
Grace Kloba47fdfdb2009-06-30 11:15:34 -07005107 // Google search
5108 final static String QuickSearch_G = "http://www.google.com/m?q=%s";
The Android Open Source Project0c908882009-03-03 19:32:16 -08005109 // Wikipedia search
5110 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
5111 // Dictionary search
5112 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
5113 // Google Mobile Local search
5114 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
5115
5116 final static String QUERY_PLACE_HOLDER = "%s";
5117
5118 // "source" parameter for Google search through search key
5119 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
5120 // "source" parameter for Google search through goto menu
5121 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
5122 // "source" parameter for Google search through simplily type
5123 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
5124 // "source" parameter for Google search suggested by the browser
5125 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
5126 // "source" parameter for Google search from unknown source
5127 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
5128
5129 private final static String LOGTAG = "browser";
5130
5131 private TabListener mTabListener;
5132
5133 private String mLastEnteredUrl;
5134
5135 private PowerManager.WakeLock mWakeLock;
5136 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5137
5138 private Toast mStopToast;
5139
Leon Scroggins81db3662009-06-04 17:45:11 -04005140 private TitleBar mTitleBar;
5141
Ben Murdochbff2d602009-07-01 20:19:05 +01005142 private LinearLayout mErrorConsoleContainer = null;
5143 private boolean mShouldShowErrorConsole = false;
5144
The Android Open Source Project0c908882009-03-03 19:32:16 -08005145 // Used during animations to prevent other animations from being triggered.
5146 // A count is used since the animation to and from the Window overview can
5147 // overlap. A count of 0 means no animation where a count of > 0 means
5148 // there are animations in progress.
5149 private int mAnimationCount;
5150
5151 // As the ids are dynamically created, we can't guarantee that they will
5152 // be in sequence, so this static array maps ids to a window number.
5153 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
5154 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
5155 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
5156 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
5157
5158 // monitor platform changes
5159 private IntentFilter mNetworkStateChangedFilter;
5160 private BroadcastReceiver mNetworkStateIntentReceiver;
5161
Grace Klobab4da0ad2009-05-14 14:45:40 -07005162 private BroadcastReceiver mPackageInstallationReceiver;
5163
The Android Open Source Project0c908882009-03-03 19:32:16 -08005164 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01005165 final static int COMBO_PAGE = 1;
5166 final static int DOWNLOAD_PAGE = 2;
5167 final static int PREFERENCES_PAGE = 3;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005168
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005169 /**
5170 * A UrlData class to abstract how the content will be set to WebView.
5171 * This base class uses loadUrl to show the content.
5172 */
5173 private static class UrlData {
5174 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07005175 byte[] mPostData;
5176
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005177 UrlData(String url) {
5178 this.mUrl = url;
5179 }
Grace Kloba60e095c2009-06-16 11:50:55 -07005180
5181 void setPostData(byte[] postData) {
5182 mPostData = postData;
5183 }
5184
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005185 boolean isEmpty() {
5186 return mUrl == null || mUrl.length() == 0;
5187 }
5188
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005189 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07005190 if (mPostData != null) {
5191 webView.postUrl(mUrl, mPostData);
5192 } else {
5193 webView.loadUrl(mUrl);
5194 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005195 }
5196 };
5197
5198 /**
5199 * A subclass of UrlData class that can display inlined content using
5200 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
5201 */
5202 private static class InlinedUrlData extends UrlData {
5203 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
5204 super(failUrl);
5205 mInlined = inlined;
5206 mMimeType = mimeType;
5207 mEncoding = encoding;
5208 }
5209 String mMimeType;
5210 String mInlined;
5211 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005212 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005213 boolean isEmpty() {
Ben Murdochbff2d602009-07-01 20:19:05 +01005214 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005215 }
5216
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005217 @Override
5218 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005219 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
5220 }
5221 }
5222
5223 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08005224}