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