blob: d1d8d15b815b471da5752645bddcafc0be867a6b [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 }
975 return handleWebSearchRequest(url);
976 }
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 */
983 private boolean handleWebSearchRequest(String inUrl) {
984 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);
1004 startActivity(intent);
1005
1006 return true;
1007 }
1008
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001009 private UrlData getUrlDataFromIntent(Intent intent) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001010 String url = null;
1011 if (intent != null) {
1012 final String action = intent.getAction();
1013 if (Intent.ACTION_VIEW.equals(action)) {
1014 url = smartUrlFilter(intent.getData());
1015 if (url != null && url.startsWith("content:")) {
1016 /* Append mimetype so webview knows how to display */
1017 String mimeType = intent.resolveType(getContentResolver());
1018 if (mimeType != null) {
1019 url += "?" + mimeType;
1020 }
1021 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001022 if ("inline:".equals(url)) {
1023 return new InlinedUrlData(
1024 intent.getStringExtra(Browser.EXTRA_INLINE_CONTENT),
1025 intent.getType(),
1026 intent.getStringExtra(Browser.EXTRA_INLINE_ENCODING),
1027 intent.getStringExtra(Browser.EXTRA_INLINE_FAILURL));
1028 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001029 } else if (Intent.ACTION_SEARCH.equals(action)
1030 || MediaStore.INTENT_ACTION_MEDIA_SEARCH.equals(action)
1031 || Intent.ACTION_WEB_SEARCH.equals(action)) {
1032 url = intent.getStringExtra(SearchManager.QUERY);
1033 if (url != null) {
1034 mLastEnteredUrl = url;
1035 // Don't add Urls, just search terms.
1036 // Urls will get added when the page is loaded.
1037 if (!Regex.WEB_URL_PATTERN.matcher(url).matches()) {
1038 Browser.updateVisitedHistory(mResolver, url, false);
1039 }
1040 // In general, we shouldn't modify URL from Intent.
1041 // But currently, we get the user-typed URL from search box as well.
1042 url = fixUrl(url);
1043 url = smartUrlFilter(url);
1044 String searchSource = "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&";
1045 if (url.contains(searchSource)) {
1046 String source = null;
1047 final Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA);
1048 if (appData != null) {
1049 source = appData.getString(SearchManager.SOURCE);
1050 }
1051 if (TextUtils.isEmpty(source)) {
1052 source = GOOGLE_SEARCH_SOURCE_UNKNOWN;
1053 }
1054 url = url.replace(searchSource, "&source=android-"+source+"&");
1055 }
1056 }
1057 }
1058 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07001059 return new UrlData(url);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001060 }
1061
Grace Kloba8ca2c792009-05-26 15:41:51 -07001062 byte[] getLocationData(Intent intent) {
1063 byte[] postData = null;
1064 if (intent != null) {
1065 final String action = intent.getAction();
Grace Kloba60e095c2009-06-16 11:50:55 -07001066 if (Intent.ACTION_VIEW.equals(action)
1067 && intent.getBooleanExtra(Browser.EXTRA_APPEND_LOCATION,
1068 false)) {
1069 ContentResolver cr = getContentResolver();
1070 int use = Settings.Gservices.getInt(cr,
1071 Settings.Gservices.USE_LOCATION_FOR_SERVICES, -1);
1072 if (use == -1) {
1073 // TODO: bring up the consent dialog
1074 } else if (use == 1
1075 && Settings.Secure.isLocationProviderEnabled(cr,
1076 LocationManager.NETWORK_PROVIDER)) {
1077 Location location = ((LocationManager) getSystemService(
1078 Context.LOCATION_SERVICE)).getLastKnownLocation(
1079 LocationManager.NETWORK_PROVIDER);
1080 if (location != null) {
1081 StringBuilder str = new StringBuilder(
1082 "action=devloc&sll=");
1083 str.append(location.getLatitude()).append(',').append(
1084 location.getLongitude());
1085 postData = str.toString().getBytes();
1086 }
Grace Kloba8ca2c792009-05-26 15:41:51 -07001087 }
1088 }
1089 }
1090 return postData;
1091 }
1092
The Android Open Source Project0c908882009-03-03 19:32:16 -08001093 /* package */ static String fixUrl(String inUrl) {
1094 if (inUrl.startsWith("http://") || inUrl.startsWith("https://"))
1095 return inUrl;
1096 if (inUrl.startsWith("http:") ||
1097 inUrl.startsWith("https:")) {
1098 if (inUrl.startsWith("http:/") || inUrl.startsWith("https:/")) {
1099 inUrl = inUrl.replaceFirst("/", "//");
1100 } else inUrl = inUrl.replaceFirst(":", "://");
1101 }
1102 return inUrl;
1103 }
1104
1105 /**
1106 * Looking for the pattern like this
1107 *
1108 * *
1109 * * *
1110 * *** * *******
1111 * * *
1112 * * *
1113 * *
1114 */
1115 private final SensorListener mSensorListener = new SensorListener() {
1116 private long mLastGestureTime;
1117 private float[] mPrev = new float[3];
1118 private float[] mPrevDiff = new float[3];
1119 private float[] mDiff = new float[3];
1120 private float[] mRevertDiff = new float[3];
1121
1122 public void onSensorChanged(int sensor, float[] values) {
1123 boolean show = false;
1124 float[] diff = new float[3];
1125
1126 for (int i = 0; i < 3; i++) {
1127 diff[i] = values[i] - mPrev[i];
1128 if (Math.abs(diff[i]) > 1) {
1129 show = true;
1130 }
1131 if ((diff[i] > 1.0 && mDiff[i] < 0.2)
1132 || (diff[i] < -1.0 && mDiff[i] > -0.2)) {
1133 // start track when there is a big move, or revert
1134 mRevertDiff[i] = mDiff[i];
1135 mDiff[i] = 0;
1136 } else if (diff[i] > -0.2 && diff[i] < 0.2) {
1137 // reset when it is flat
1138 mDiff[i] = mRevertDiff[i] = 0;
1139 }
1140 mDiff[i] += diff[i];
1141 mPrevDiff[i] = diff[i];
1142 mPrev[i] = values[i];
1143 }
1144
1145 if (false) {
1146 // only shows if we think the delta is big enough, in an attempt
1147 // to detect "serious" moves left/right or up/down
1148 Log.d("BrowserSensorHack", "sensorChanged " + sensor + " ("
1149 + values[0] + ", " + values[1] + ", " + values[2] + ")"
1150 + " diff(" + diff[0] + " " + diff[1] + " " + diff[2]
1151 + ")");
1152 Log.d("BrowserSensorHack", " mDiff(" + mDiff[0] + " "
1153 + mDiff[1] + " " + mDiff[2] + ")" + " mRevertDiff("
1154 + mRevertDiff[0] + " " + mRevertDiff[1] + " "
1155 + mRevertDiff[2] + ")");
1156 }
1157
1158 long now = android.os.SystemClock.uptimeMillis();
1159 if (now - mLastGestureTime > 1000) {
1160 mLastGestureTime = 0;
1161
1162 float y = mDiff[1];
1163 float z = mDiff[2];
1164 float ay = Math.abs(y);
1165 float az = Math.abs(z);
1166 float ry = mRevertDiff[1];
1167 float rz = mRevertDiff[2];
1168 float ary = Math.abs(ry);
1169 float arz = Math.abs(rz);
1170 boolean gestY = ay > 2.5f && ary > 1.0f && ay > ary;
1171 boolean gestZ = az > 3.5f && arz > 1.0f && az > arz;
1172
1173 if ((gestY || gestZ) && !(gestY && gestZ)) {
1174 WebView view = mTabControl.getCurrentWebView();
1175
1176 if (view != null) {
1177 if (gestZ) {
1178 if (z < 0) {
1179 view.zoomOut();
1180 } else {
1181 view.zoomIn();
1182 }
1183 } else {
1184 view.flingScroll(0, Math.round(y * 100));
1185 }
1186 }
1187 mLastGestureTime = now;
1188 }
1189 }
1190 }
1191
1192 public void onAccuracyChanged(int sensor, int accuracy) {
1193 // TODO Auto-generated method stub
1194
1195 }
1196 };
1197
1198 @Override protected void onResume() {
1199 super.onResume();
Dave Bort31a6d1c2009-04-13 15:56:49 -07001200 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001201 Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
1202 }
1203
1204 if (!mActivityInPause) {
1205 Log.e(LOGTAG, "BrowserActivity is already resumed.");
1206 return;
1207 }
1208
Mike Reed7bfa63b2009-05-28 11:08:32 -04001209 mTabControl.resumeCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001210 mActivityInPause = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001211 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001212
1213 if (mWakeLock.isHeld()) {
1214 mHandler.removeMessages(RELEASE_WAKELOCK);
1215 mWakeLock.release();
1216 }
1217
1218 if (mCredsDlg != null) {
1219 if (!mHandler.hasMessages(CANCEL_CREDS_REQUEST)) {
1220 // In case credential request never comes back
1221 mHandler.sendEmptyMessageDelayed(CANCEL_CREDS_REQUEST, 6000);
1222 }
1223 }
1224
1225 registerReceiver(mNetworkStateIntentReceiver,
1226 mNetworkStateChangedFilter);
1227 WebView.enablePlatformNotifications();
1228
1229 if (mSettings.doFlick()) {
1230 if (mSensorManager == null) {
1231 mSensorManager = (SensorManager) getSystemService(
1232 Context.SENSOR_SERVICE);
1233 }
1234 mSensorManager.registerListener(mSensorListener,
1235 SensorManager.SENSOR_ACCELEROMETER,
1236 SensorManager.SENSOR_DELAY_FASTEST);
1237 } else {
1238 mSensorManager = null;
1239 }
1240 }
1241
1242 /**
1243 * onSaveInstanceState(Bundle map)
1244 * onSaveInstanceState is called right before onStop(). The map contains
1245 * the saved state.
1246 */
1247 @Override protected void onSaveInstanceState(Bundle outState) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001248 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001249 Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
1250 }
1251 // the default implementation requires each view to have an id. As the
1252 // browser handles the state itself and it doesn't use id for the views,
1253 // don't call the default implementation. Otherwise it will trigger the
1254 // warning like this, "couldn't save which view has focus because the
1255 // focused view XXX has no id".
1256
1257 // Save all the tabs
1258 mTabControl.saveState(outState);
1259 }
1260
1261 @Override protected void onPause() {
1262 super.onPause();
1263
1264 if (mActivityInPause) {
1265 Log.e(LOGTAG, "BrowserActivity is already paused.");
1266 return;
1267 }
1268
Mike Reed7bfa63b2009-05-28 11:08:32 -04001269 mTabControl.pauseCurrentTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08001270 mActivityInPause = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04001271 if (mTabControl.getCurrentIndex() >= 0 && !pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001272 mWakeLock.acquire();
1273 mHandler.sendMessageDelayed(mHandler
1274 .obtainMessage(RELEASE_WAKELOCK), WAKELOCK_TIMEOUT);
1275 }
1276
1277 // Clear the credentials toast if it is up
1278 if (mCredsDlg != null && mCredsDlg.isShowing()) {
1279 mCredsDlg.dismiss();
1280 }
1281 mCredsDlg = null;
1282
1283 cancelStopToast();
1284
1285 // unregister network state listener
1286 unregisterReceiver(mNetworkStateIntentReceiver);
1287 WebView.disablePlatformNotifications();
1288
1289 if (mSensorManager != null) {
1290 mSensorManager.unregisterListener(mSensorListener);
1291 }
1292 }
1293
1294 @Override protected void onDestroy() {
Dave Bort31a6d1c2009-04-13 15:56:49 -07001295 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001296 Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
1297 }
1298 super.onDestroy();
1299 // Remove the current tab and sub window
1300 TabControl.Tab t = mTabControl.getCurrentTab();
Patrick Scottfb5e77f2009-04-08 19:17:37 -07001301 if (t != null) {
1302 dismissSubWindow(t);
1303 removeTabFromContentView(t);
1304 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001305 // Destroy all the tabs
1306 mTabControl.destroy();
1307 WebIconDatabase.getInstance().close();
1308 if (mGlsConnection != null) {
1309 unbindService(mGlsConnection);
1310 mGlsConnection = null;
1311 }
1312
1313 //
1314 // stop MASF proxy service
1315 //
1316 //Intent proxyServiceIntent = new Intent();
1317 //proxyServiceIntent.setComponent
1318 // (new ComponentName(
1319 // "com.android.masfproxyservice",
1320 // "com.android.masfproxyservice.MasfProxyService"));
1321 //stopService(proxyServiceIntent);
Grace Klobab4da0ad2009-05-14 14:45:40 -07001322
1323 unregisterReceiver(mPackageInstallationReceiver);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001324 }
1325
1326 @Override
1327 public void onConfigurationChanged(Configuration newConfig) {
1328 super.onConfigurationChanged(newConfig);
1329
1330 if (mPageInfoDialog != null) {
1331 mPageInfoDialog.dismiss();
1332 showPageInfo(
1333 mPageInfoView,
1334 mPageInfoFromShowSSLCertificateOnError.booleanValue());
1335 }
1336 if (mSSLCertificateDialog != null) {
1337 mSSLCertificateDialog.dismiss();
1338 showSSLCertificate(
1339 mSSLCertificateView);
1340 }
1341 if (mSSLCertificateOnErrorDialog != null) {
1342 mSSLCertificateOnErrorDialog.dismiss();
1343 showSSLCertificateOnError(
1344 mSSLCertificateOnErrorView,
1345 mSSLCertificateOnErrorHandler,
1346 mSSLCertificateOnErrorError);
1347 }
1348 if (mHttpAuthenticationDialog != null) {
1349 String title = ((TextView) mHttpAuthenticationDialog
1350 .findViewById(com.android.internal.R.id.alertTitle)).getText()
1351 .toString();
1352 String name = ((TextView) mHttpAuthenticationDialog
1353 .findViewById(R.id.username_edit)).getText().toString();
1354 String password = ((TextView) mHttpAuthenticationDialog
1355 .findViewById(R.id.password_edit)).getText().toString();
1356 int focusId = mHttpAuthenticationDialog.getCurrentFocus()
1357 .getId();
1358 mHttpAuthenticationDialog.dismiss();
1359 showHttpAuthentication(mHttpAuthHandler, null, null, title,
1360 name, password, focusId);
1361 }
1362 if (mFindDialog != null && mFindDialog.isShowing()) {
1363 mFindDialog.onConfigurationChanged(newConfig);
1364 }
1365 }
1366
1367 @Override public void onLowMemory() {
1368 super.onLowMemory();
1369 mTabControl.freeMemory();
1370 }
1371
Mike Reed7bfa63b2009-05-28 11:08:32 -04001372 private boolean resumeWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001373 if ((!mActivityInPause && !mPageStarted) ||
1374 (mActivityInPause && mPageStarted)) {
1375 CookieSyncManager.getInstance().startSync();
1376 WebView w = mTabControl.getCurrentWebView();
1377 if (w != null) {
1378 w.resumeTimers();
1379 }
1380 return true;
1381 } else {
1382 return false;
1383 }
1384 }
1385
Mike Reed7bfa63b2009-05-28 11:08:32 -04001386 private boolean pauseWebViewTimers() {
The Android Open Source Project0c908882009-03-03 19:32:16 -08001387 if (mActivityInPause && !mPageStarted) {
1388 CookieSyncManager.getInstance().stopSync();
1389 WebView w = mTabControl.getCurrentWebView();
1390 if (w != null) {
1391 w.pauseTimers();
1392 }
1393 return true;
1394 } else {
1395 return false;
1396 }
1397 }
1398
1399 /*
1400 * This function is called when we are launching for the first time. We
1401 * are waiting for the login credentials before loading Google home
1402 * pages. This way the user will be logged in straight away.
1403 */
1404 private void waitForCredentials() {
1405 // Show a toast
1406 mCredsDlg = new ProgressDialog(this);
1407 mCredsDlg.setIndeterminate(true);
1408 mCredsDlg.setMessage(getText(R.string.retrieving_creds_dlg_msg));
1409 // If the user cancels the operation, then cancel the Google
1410 // Credentials request.
1411 mCredsDlg.setCancelMessage(mHandler.obtainMessage(CANCEL_CREDS_REQUEST));
1412 mCredsDlg.show();
1413
1414 // We set a timeout for the retrieval of credentials in onResume()
1415 // as that is when we have freed up some CPU time to get
1416 // the login credentials.
1417 }
1418
1419 /*
1420 * If we have received the credentials or we have timed out and we are
1421 * showing the credentials dialog, then it is time to move on.
1422 */
1423 private void resumeAfterCredentials() {
1424 if (mCredsDlg == null) {
1425 return;
1426 }
1427
1428 // Clear the toast
1429 if (mCredsDlg.isShowing()) {
1430 mCredsDlg.dismiss();
1431 }
1432 mCredsDlg = null;
1433
1434 // Clear any pending timeout
1435 mHandler.removeMessages(CANCEL_CREDS_REQUEST);
1436
1437 // Load the page
1438 WebView w = mTabControl.getCurrentWebView();
1439 if (w != null) {
1440 w.loadUrl(mSettings.getHomePage());
1441 }
1442
1443 // Update the settings, need to do this last as it can take a moment
1444 // to persist the settings. In the mean time we could be loading
1445 // content.
1446 mSettings.setLoginInitialized(this);
1447 }
1448
1449 // Open the icon database and retain all the icons for visited sites.
1450 private void retainIconsOnStartup() {
1451 final WebIconDatabase db = WebIconDatabase.getInstance();
1452 db.open(getDir("icons", 0).getPath());
1453 try {
1454 Cursor c = Browser.getAllBookmarks(mResolver);
1455 if (!c.moveToFirst()) {
1456 c.deactivate();
1457 return;
1458 }
1459 int urlIndex = c.getColumnIndex(Browser.BookmarkColumns.URL);
1460 do {
1461 String url = c.getString(urlIndex);
1462 db.retainIconForPageUrl(url);
1463 } while (c.moveToNext());
1464 c.deactivate();
1465 } catch (IllegalStateException e) {
1466 Log.e(LOGTAG, "retainIconsOnStartup", e);
1467 }
1468 }
1469
1470 // Helper method for getting the top window.
1471 WebView getTopWindow() {
1472 return mTabControl.getCurrentTopWebView();
1473 }
1474
1475 @Override
1476 public boolean onCreateOptionsMenu(Menu menu) {
1477 super.onCreateOptionsMenu(menu);
1478
1479 MenuInflater inflater = getMenuInflater();
1480 inflater.inflate(R.menu.browser, menu);
1481 mMenu = menu;
1482 updateInLoadMenuItems();
1483 return true;
1484 }
1485
1486 /**
1487 * As the menu can be open when loading state changes
1488 * we must manually update the state of the stop/reload menu
1489 * item
1490 */
1491 private void updateInLoadMenuItems() {
1492 if (mMenu == null) {
1493 return;
1494 }
1495 MenuItem src = mInLoad ?
1496 mMenu.findItem(R.id.stop_menu_id):
1497 mMenu.findItem(R.id.reload_menu_id);
1498 MenuItem dest = mMenu.findItem(R.id.stop_reload_menu_id);
1499 dest.setIcon(src.getIcon());
1500 dest.setTitle(src.getTitle());
1501 }
1502
1503 @Override
1504 public boolean onContextItemSelected(MenuItem item) {
1505 // chording is not an issue with context menus, but we use the same
1506 // options selector, so set mCanChord to true so we can access them.
1507 mCanChord = true;
1508 int id = item.getItemId();
1509 final WebView webView = getTopWindow();
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001510 if (null == webView) {
1511 return false;
1512 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001513 final HashMap hrefMap = new HashMap();
1514 hrefMap.put("webview", webView);
1515 final Message msg = mHandler.obtainMessage(
1516 FOCUS_NODE_HREF, id, 0, hrefMap);
1517 switch (id) {
1518 // -- Browser context menu
1519 case R.id.open_context_menu_id:
1520 case R.id.open_newtab_context_menu_id:
1521 case R.id.bookmark_context_menu_id:
1522 case R.id.save_link_context_menu_id:
1523 case R.id.share_link_context_menu_id:
1524 case R.id.copy_link_context_menu_id:
1525 webView.requestFocusNodeHref(msg);
1526 break;
1527
1528 default:
1529 // For other context menus
1530 return onOptionsItemSelected(item);
1531 }
1532 mCanChord = false;
1533 return true;
1534 }
1535
1536 private Bundle createGoogleSearchSourceBundle(String source) {
1537 Bundle bundle = new Bundle();
1538 bundle.putString(SearchManager.SOURCE, source);
1539 return bundle;
1540 }
1541
1542 /**
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001543 * Overriding this to insert a local information bundle
The Android Open Source Project0c908882009-03-03 19:32:16 -08001544 */
1545 @Override
1546 public boolean onSearchRequested() {
1547 startSearch(null, false,
The Android Open Source Project4e5f5872009-03-09 11:52:14 -07001548 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_SEARCHKEY), false);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001549 return true;
1550 }
1551
1552 @Override
1553 public void startSearch(String initialQuery, boolean selectInitialQuery,
1554 Bundle appSearchData, boolean globalSearch) {
1555 if (appSearchData == null) {
1556 appSearchData = createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_TYPE);
1557 }
1558 super.startSearch(initialQuery, selectInitialQuery, appSearchData, globalSearch);
1559 }
1560
1561 @Override
1562 public boolean onOptionsItemSelected(MenuItem item) {
1563 if (!mCanChord) {
1564 // The user has already fired a shortcut with this hold down of the
1565 // menu key.
1566 return false;
1567 }
Leon Scroggins0d7ae0e2009-06-05 11:04:45 -04001568 if (null == mTabOverview && null == getTopWindow()) {
1569 return false;
1570 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08001571 switch (item.getItemId()) {
1572 // -- Main menu
1573 case R.id.goto_menu_id: {
1574 String url = getTopWindow().getUrl();
1575 startSearch(mSettings.getHomePage().equals(url) ? null : url, true,
1576 createGoogleSearchSourceBundle(GOOGLE_SEARCH_SOURCE_GOTO), false);
1577 }
1578 break;
1579
1580 case R.id.bookmarks_menu_id:
1581 bookmarksOrHistoryPicker(false);
1582 break;
1583
1584 case R.id.windows_menu_id:
1585 if (mTabControl.getTabCount() == 1) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07001586 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001587 } else {
1588 tabPicker(true, mTabControl.getCurrentIndex(), false);
1589 }
1590 break;
1591
1592 case R.id.stop_reload_menu_id:
1593 if (mInLoad) {
1594 stopLoading();
1595 } else {
1596 getTopWindow().reload();
1597 }
1598 break;
1599
1600 case R.id.back_menu_id:
1601 getTopWindow().goBack();
1602 break;
1603
1604 case R.id.forward_menu_id:
1605 getTopWindow().goForward();
1606 break;
1607
1608 case R.id.close_menu_id:
1609 // Close the subwindow if it exists.
1610 if (mTabControl.getCurrentSubWindow() != null) {
1611 dismissSubWindow(mTabControl.getCurrentTab());
1612 break;
1613 }
1614 final int currentIndex = mTabControl.getCurrentIndex();
1615 final TabControl.Tab parent =
1616 mTabControl.getCurrentTab().getParentTab();
1617 int indexToShow = -1;
1618 if (parent != null) {
1619 indexToShow = mTabControl.getTabIndex(parent);
1620 } else {
1621 // Get the last tab in the list. If it is the current tab,
1622 // subtract 1 more.
1623 indexToShow = mTabControl.getTabCount() - 1;
1624 if (currentIndex == indexToShow) {
1625 indexToShow--;
1626 }
1627 }
1628 switchTabs(currentIndex, indexToShow, true);
1629 break;
1630
1631 case R.id.homepage_menu_id:
1632 TabControl.Tab current = mTabControl.getCurrentTab();
1633 if (current != null) {
1634 dismissSubWindow(current);
1635 current.getWebView().loadUrl(mSettings.getHomePage());
1636 }
1637 break;
1638
1639 case R.id.preferences_menu_id:
1640 Intent intent = new Intent(this,
1641 BrowserPreferencesPage.class);
1642 startActivityForResult(intent, PREFERENCES_PAGE);
1643 break;
1644
1645 case R.id.find_menu_id:
1646 if (null == mFindDialog) {
1647 mFindDialog = new FindDialog(this);
1648 }
1649 mFindDialog.setWebView(getTopWindow());
1650 mFindDialog.show();
1651 mMenuState = EMPTY_MENU;
1652 break;
1653
1654 case R.id.select_text_id:
1655 getTopWindow().emulateShiftHeld();
1656 break;
1657 case R.id.page_info_menu_id:
1658 showPageInfo(mTabControl.getCurrentTab(), false);
1659 break;
1660
1661 case R.id.classic_history_menu_id:
1662 bookmarksOrHistoryPicker(true);
1663 break;
1664
1665 case R.id.share_page_menu_id:
1666 Browser.sendString(this, getTopWindow().getUrl());
1667 break;
1668
1669 case R.id.dump_nav_menu_id:
1670 getTopWindow().debugDump();
1671 break;
1672
1673 case R.id.zoom_in_menu_id:
1674 getTopWindow().zoomIn();
1675 break;
1676
1677 case R.id.zoom_out_menu_id:
1678 getTopWindow().zoomOut();
1679 break;
1680
1681 case R.id.view_downloads_menu_id:
1682 viewDownloads(null);
1683 break;
1684
1685 // -- Tab menu
1686 case R.id.view_tab_menu_id:
1687 if (mTabListener != null && mTabOverview != null) {
1688 int pos = mTabOverview.getContextMenuPosition(item);
1689 mTabOverview.setCurrentIndex(pos);
1690 mTabListener.onClick(pos);
1691 }
1692 break;
1693
1694 case R.id.remove_tab_menu_id:
1695 if (mTabListener != null && mTabOverview != null) {
1696 int pos = mTabOverview.getContextMenuPosition(item);
1697 mTabListener.remove(pos);
1698 }
1699 break;
1700
1701 case R.id.new_tab_menu_id:
1702 // No need to check for mTabOverview here since we are not
1703 // dependent on it for a position.
1704 if (mTabListener != null) {
1705 // If the overview happens to be non-null, make the "New
1706 // Tab" cell visible.
1707 if (mTabOverview != null) {
1708 mTabOverview.setCurrentIndex(ImageGrid.NEW_TAB);
1709 }
1710 mTabListener.onClick(ImageGrid.NEW_TAB);
1711 }
1712 break;
1713
1714 case R.id.bookmark_tab_menu_id:
1715 if (mTabListener != null && mTabOverview != null) {
1716 int pos = mTabOverview.getContextMenuPosition(item);
1717 TabControl.Tab t = mTabControl.getTab(pos);
1718 // Since we called populatePickerData for all of the
1719 // tabs, getTitle and getUrl will return appropriate
1720 // values.
1721 Browser.saveBookmark(BrowserActivity.this, t.getTitle(),
1722 t.getUrl());
1723 }
1724 break;
1725
1726 case R.id.history_tab_menu_id:
1727 bookmarksOrHistoryPicker(true);
1728 break;
1729
1730 case R.id.bookmarks_tab_menu_id:
1731 bookmarksOrHistoryPicker(false);
1732 break;
1733
1734 case R.id.properties_tab_menu_id:
1735 if (mTabListener != null && mTabOverview != null) {
1736 int pos = mTabOverview.getContextMenuPosition(item);
1737 showPageInfo(mTabControl.getTab(pos), false);
1738 }
1739 break;
1740
1741 case R.id.window_one_menu_id:
1742 case R.id.window_two_menu_id:
1743 case R.id.window_three_menu_id:
1744 case R.id.window_four_menu_id:
1745 case R.id.window_five_menu_id:
1746 case R.id.window_six_menu_id:
1747 case R.id.window_seven_menu_id:
1748 case R.id.window_eight_menu_id:
1749 {
1750 int menuid = item.getItemId();
1751 for (int id = 0; id < WINDOW_SHORTCUT_ID_ARRAY.length; id++) {
1752 if (WINDOW_SHORTCUT_ID_ARRAY[id] == menuid) {
1753 TabControl.Tab desiredTab = mTabControl.getTab(id);
1754 if (desiredTab != null &&
1755 desiredTab != mTabControl.getCurrentTab()) {
1756 switchTabs(mTabControl.getCurrentIndex(), id, false);
1757 }
1758 break;
1759 }
1760 }
1761 }
1762 break;
1763
1764 default:
1765 if (!super.onOptionsItemSelected(item)) {
1766 return false;
1767 }
1768 // Otherwise fall through.
1769 }
1770 mCanChord = false;
1771 return true;
1772 }
1773
1774 public void closeFind() {
1775 mMenuState = R.id.MAIN_MENU;
1776 }
1777
1778 @Override public boolean onPrepareOptionsMenu(Menu menu)
1779 {
1780 // This happens when the user begins to hold down the menu key, so
1781 // allow them to chord to get a shortcut.
1782 mCanChord = true;
1783 // Note: setVisible will decide whether an item is visible; while
1784 // setEnabled() will decide whether an item is enabled, which also means
1785 // whether the matching shortcut key will function.
1786 super.onPrepareOptionsMenu(menu);
1787 switch (mMenuState) {
1788 case R.id.TAB_MENU:
1789 if (mCurrentMenuState != mMenuState) {
1790 menu.setGroupVisible(R.id.MAIN_MENU, false);
1791 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1792 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1793 menu.setGroupVisible(R.id.TAB_MENU, true);
1794 menu.setGroupEnabled(R.id.TAB_MENU, true);
1795 }
1796 boolean newT = mTabControl.getTabCount() < TabControl.MAX_TABS;
1797 final MenuItem tab = menu.findItem(R.id.new_tab_menu_id);
1798 tab.setVisible(newT);
1799 tab.setEnabled(newT);
1800 break;
1801 case EMPTY_MENU:
1802 if (mCurrentMenuState != mMenuState) {
1803 menu.setGroupVisible(R.id.MAIN_MENU, false);
1804 menu.setGroupEnabled(R.id.MAIN_MENU, false);
1805 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, false);
1806 menu.setGroupVisible(R.id.TAB_MENU, false);
1807 menu.setGroupEnabled(R.id.TAB_MENU, false);
1808 }
1809 break;
1810 default:
1811 if (mCurrentMenuState != mMenuState) {
1812 menu.setGroupVisible(R.id.MAIN_MENU, true);
1813 menu.setGroupEnabled(R.id.MAIN_MENU, true);
1814 menu.setGroupEnabled(R.id.MAIN_SHORTCUT_MENU, true);
1815 menu.setGroupVisible(R.id.TAB_MENU, false);
1816 menu.setGroupEnabled(R.id.TAB_MENU, false);
1817 }
1818 final WebView w = getTopWindow();
1819 boolean canGoBack = false;
1820 boolean canGoForward = false;
1821 boolean isHome = false;
1822 if (w != null) {
1823 canGoBack = w.canGoBack();
1824 canGoForward = w.canGoForward();
1825 isHome = mSettings.getHomePage().equals(w.getUrl());
1826 }
1827 final MenuItem back = menu.findItem(R.id.back_menu_id);
1828 back.setEnabled(canGoBack);
1829
1830 final MenuItem home = menu.findItem(R.id.homepage_menu_id);
1831 home.setEnabled(!isHome);
1832
1833 menu.findItem(R.id.forward_menu_id)
1834 .setEnabled(canGoForward);
1835
1836 // decide whether to show the share link option
1837 PackageManager pm = getPackageManager();
1838 Intent send = new Intent(Intent.ACTION_SEND);
1839 send.setType("text/plain");
1840 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1841 menu.findItem(R.id.share_page_menu_id).setVisible(ri != null);
1842
1843 // If there is only 1 window, the text will be "New window"
1844 final MenuItem windows = menu.findItem(R.id.windows_menu_id);
1845 windows.setTitleCondensed(mTabControl.getTabCount() > 1 ?
1846 getString(R.string.view_tabs_condensed) :
1847 getString(R.string.tab_picker_new_tab));
1848
1849 boolean isNavDump = mSettings.isNavDump();
1850 final MenuItem nav = menu.findItem(R.id.dump_nav_menu_id);
1851 nav.setVisible(isNavDump);
1852 nav.setEnabled(isNavDump);
1853 break;
1854 }
1855 mCurrentMenuState = mMenuState;
1856 return true;
1857 }
1858
1859 @Override
1860 public void onCreateContextMenu(ContextMenu menu, View v,
1861 ContextMenuInfo menuInfo) {
1862 WebView webview = (WebView) v;
1863 WebView.HitTestResult result = webview.getHitTestResult();
1864 if (result == null) {
1865 return;
1866 }
1867
1868 int type = result.getType();
1869 if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
1870 Log.w(LOGTAG,
1871 "We should not show context menu when nothing is touched");
1872 return;
1873 }
1874 if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {
1875 // let TextView handles context menu
1876 return;
1877 }
1878
1879 // Note, http://b/issue?id=1106666 is requesting that
1880 // an inflated menu can be used again. This is not available
1881 // yet, so inflate each time (yuk!)
1882 MenuInflater inflater = getMenuInflater();
1883 inflater.inflate(R.menu.browsercontext, menu);
1884
1885 // Show the correct menu group
1886 String extra = result.getExtra();
1887 menu.setGroupVisible(R.id.PHONE_MENU,
1888 type == WebView.HitTestResult.PHONE_TYPE);
1889 menu.setGroupVisible(R.id.EMAIL_MENU,
1890 type == WebView.HitTestResult.EMAIL_TYPE);
1891 menu.setGroupVisible(R.id.GEO_MENU,
1892 type == WebView.HitTestResult.GEO_TYPE);
1893 menu.setGroupVisible(R.id.IMAGE_MENU,
1894 type == WebView.HitTestResult.IMAGE_TYPE
1895 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1896 menu.setGroupVisible(R.id.ANCHOR_MENU,
1897 type == WebView.HitTestResult.SRC_ANCHOR_TYPE
1898 || type == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE);
1899
1900 // Setup custom handling depending on the type
1901 switch (type) {
1902 case WebView.HitTestResult.PHONE_TYPE:
1903 menu.setHeaderTitle(Uri.decode(extra));
1904 menu.findItem(R.id.dial_context_menu_id).setIntent(
1905 new Intent(Intent.ACTION_VIEW, Uri
1906 .parse(WebView.SCHEME_TEL + extra)));
1907 Intent addIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
1908 addIntent.putExtra(Insert.PHONE, Uri.decode(extra));
1909 addIntent.setType(Contacts.People.CONTENT_ITEM_TYPE);
1910 menu.findItem(R.id.add_contact_context_menu_id).setIntent(
1911 addIntent);
1912 menu.findItem(R.id.copy_phone_context_menu_id).setOnMenuItemClickListener(
1913 new Copy(extra));
1914 break;
1915
1916 case WebView.HitTestResult.EMAIL_TYPE:
1917 menu.setHeaderTitle(extra);
1918 menu.findItem(R.id.email_context_menu_id).setIntent(
1919 new Intent(Intent.ACTION_VIEW, Uri
1920 .parse(WebView.SCHEME_MAILTO + extra)));
1921 menu.findItem(R.id.copy_mail_context_menu_id).setOnMenuItemClickListener(
1922 new Copy(extra));
1923 break;
1924
1925 case WebView.HitTestResult.GEO_TYPE:
1926 menu.setHeaderTitle(extra);
1927 menu.findItem(R.id.map_context_menu_id).setIntent(
1928 new Intent(Intent.ACTION_VIEW, Uri
1929 .parse(WebView.SCHEME_GEO
1930 + URLEncoder.encode(extra))));
1931 menu.findItem(R.id.copy_geo_context_menu_id).setOnMenuItemClickListener(
1932 new Copy(extra));
1933 break;
1934
1935 case WebView.HitTestResult.SRC_ANCHOR_TYPE:
1936 case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
1937 TextView titleView = (TextView) LayoutInflater.from(this)
1938 .inflate(android.R.layout.browser_link_context_header,
1939 null);
1940 titleView.setText(extra);
1941 menu.setHeaderView(titleView);
1942 // decide whether to show the open link in new tab option
1943 menu.findItem(R.id.open_newtab_context_menu_id).setVisible(
1944 mTabControl.getTabCount() < TabControl.MAX_TABS);
1945 PackageManager pm = getPackageManager();
1946 Intent send = new Intent(Intent.ACTION_SEND);
1947 send.setType("text/plain");
1948 ResolveInfo ri = pm.resolveActivity(send, PackageManager.MATCH_DEFAULT_ONLY);
1949 menu.findItem(R.id.share_link_context_menu_id).setVisible(ri != null);
1950 if (type == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
1951 break;
1952 }
1953 // otherwise fall through to handle image part
1954 case WebView.HitTestResult.IMAGE_TYPE:
1955 if (type == WebView.HitTestResult.IMAGE_TYPE) {
1956 menu.setHeaderTitle(extra);
1957 }
1958 menu.findItem(R.id.view_image_context_menu_id).setIntent(
1959 new Intent(Intent.ACTION_VIEW, Uri.parse(extra)));
1960 menu.findItem(R.id.download_context_menu_id).
1961 setOnMenuItemClickListener(new Download(extra));
1962 break;
1963
1964 default:
1965 Log.w(LOGTAG, "We should not get here.");
1966 break;
1967 }
1968 }
1969
The Android Open Source Project0c908882009-03-03 19:32:16 -08001970 // Attach the given tab to the content view.
1971 private void attachTabToContentView(TabControl.Tab t) {
1972 final WebView main = t.getWebView();
1973 // Attach the main WebView.
1974 mContentView.addView(main, COVER_SCREEN_PARAMS);
The Android Open Source Project0c908882009-03-03 19:32:16 -08001975 // Attach the sub window if necessary
1976 attachSubWindow(t);
1977 // Request focus on the top window.
1978 t.getTopWindow().requestFocus();
1979 }
1980
1981 // Attach a sub window to the main WebView of the given tab.
1982 private void attachSubWindow(TabControl.Tab t) {
1983 // If a sub window exists, attach it to the content view.
1984 final WebView subView = t.getSubWebView();
1985 if (subView != null) {
1986 final View container = t.getSubWebViewContainer();
1987 mContentView.addView(container, COVER_SCREEN_PARAMS);
1988 subView.requestFocus();
1989 }
1990 }
1991
1992 // Remove the given tab from the content view.
1993 private void removeTabFromContentView(TabControl.Tab t) {
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07001994 // Remove the main WebView.
The Android Open Source Project0c908882009-03-03 19:32:16 -08001995 mContentView.removeView(t.getWebView());
1996 // Remove the sub window if it exists.
1997 if (t.getSubWebView() != null) {
1998 mContentView.removeView(t.getSubWebViewContainer());
1999 }
2000 }
2001
2002 // Remove the sub window if it exists. Also called by TabControl when the
2003 // user clicks the 'X' to dismiss a sub window.
2004 /* package */ void dismissSubWindow(TabControl.Tab t) {
2005 final WebView mainView = t.getWebView();
2006 if (t.getSubWebView() != null) {
2007 // Remove the container view and request focus on the main WebView.
2008 mContentView.removeView(t.getSubWebViewContainer());
2009 mainView.requestFocus();
2010 // Tell the TabControl to dismiss the subwindow. This will destroy
2011 // the WebView.
2012 mTabControl.dismissSubWindow(t);
2013 }
2014 }
2015
2016 // Send the ANIMTE_FROM_OVERVIEW message after changing the current tab.
2017 private void sendAnimateFromOverview(final TabControl.Tab tab,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002018 final boolean newTab, final UrlData urlData, final int delay,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002019 final Message msg) {
2020 // Set the current tab.
2021 mTabControl.setCurrentTab(tab);
2022 // Attach the WebView so it will layout.
2023 attachTabToContentView(tab);
2024 // Set the view to invisibile for now.
2025 tab.getWebView().setVisibility(View.INVISIBLE);
2026 // If there is a sub window, make it invisible too.
2027 if (tab.getSubWebView() != null) {
2028 tab.getSubWebViewContainer().setVisibility(View.INVISIBLE);
2029 }
2030 // Create our fake animating view.
2031 final AnimatingView view = new AnimatingView(this, tab);
2032 // Attach it to the view system and make in invisible so it will
2033 // layout but not flash white on the screen.
2034 mContentView.addView(view, COVER_SCREEN_PARAMS);
2035 view.setVisibility(View.INVISIBLE);
2036 // Send the animate message.
2037 final HashMap map = new HashMap();
2038 map.put("view", view);
2039 // Load the url after the AnimatingView has captured the picture. This
2040 // prevents any bad layout or bad scale from being used during
2041 // animation.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002042 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002043 dismissSubWindow(tab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002044 urlData.loadIn(tab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002045 }
2046 map.put("msg", msg);
2047 mHandler.sendMessageDelayed(mHandler.obtainMessage(
2048 ANIMATE_FROM_OVERVIEW, newTab ? 1 : 0, 0, map), delay);
2049 // Increment the count to indicate that we are in an animation.
2050 mAnimationCount++;
2051 // Remove the listener so we don't get any more tab changes.
2052 mTabOverview.setListener(null);
2053 mTabListener = null;
2054 // Make the menu empty until the animation completes.
2055 mMenuState = EMPTY_MENU;
2056
2057 }
2058
2059 // 500ms animation with 800ms delay
Patrick Scott95d601f2009-06-11 10:06:46 -04002060 private static final int TAB_ANIMATION_DURATION = 200;
2061 private static final int TAB_OVERVIEW_DELAY = 500;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002062
2063 // Called by TabControl when a tab is requesting focus
2064 /* package */ void showTab(TabControl.Tab t) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002065 showTab(t, EMPTY_URL_DATA);
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002066 }
2067
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002068 private void showTab(TabControl.Tab t, UrlData urlData) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002069 // Disallow focus change during a tab animation.
2070 if (mAnimationCount > 0) {
2071 return;
2072 }
2073 int delay = 0;
2074 if (mTabOverview == null) {
2075 // Add a delay so the tab overview can be shown before the second
2076 // animation begins.
2077 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2078 tabPicker(false, mTabControl.getTabIndex(t), false);
2079 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002080 sendAnimateFromOverview(t, false, urlData, delay, null);
2081 }
2082
2083 // A wrapper function of {@link #openTabAndShow(UrlData, Message, boolean, String)}
2084 // that accepts url as string.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002085 private TabControl.Tab openTabAndShow(String url, final Message msg,
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002086 boolean closeOnExit, String appId) {
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002087 return openTabAndShow(new UrlData(url), msg, closeOnExit, appId);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002088 }
2089
2090 // This method does a ton of stuff. It will attempt to create a new tab
2091 // if we haven't reached MAX_TABS. Otherwise it uses the current tab. If
2092 // url isn't null, it will load the given url. If the tab overview is not
2093 // showing, it will animate to the tab overview, create a new tab and
2094 // animate away from it. After the animation completes, it will dispatch
2095 // the given Message. If the tab overview is already showing (i.e. this
2096 // method is called from TabListener.onClick(), the method will animate
2097 // away from the tab overview.
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002098 private TabControl.Tab openTabAndShow(UrlData urlData, final Message msg,
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002099 boolean closeOnExit, String appId) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002100 final boolean newTab = mTabControl.getTabCount() != TabControl.MAX_TABS;
2101 final TabControl.Tab currentTab = mTabControl.getCurrentTab();
2102 if (newTab) {
2103 int delay = 0;
2104 // If the tab overview is up and there are animations, just load
2105 // the url.
2106 if (mTabOverview != null && mAnimationCount > 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002107 if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002108 // We should not have a msg here since onCreateWindow
2109 // checks the animation count and every other caller passes
2110 // null.
2111 assert msg == null;
2112 // just dismiss the subwindow and load the given url.
2113 dismissSubWindow(currentTab);
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002114 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002115 }
2116 } else {
2117 // show mTabOverview if it is not there.
2118 if (mTabOverview == null) {
2119 // We have to delay the animation from the tab picker by the
2120 // length of the tab animation. Add a delay so the tab
2121 // overview can be shown before the second animation begins.
2122 delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2123 tabPicker(false, ImageGrid.NEW_TAB, false);
2124 }
2125 // Animate from the Tab overview after any animations have
2126 // finished.
Grace Klobac9181842009-04-14 08:53:22 -07002127 final TabControl.Tab tab = mTabControl.createNewTab(
Mitsuru Oshimaf26aeab2009-06-11 02:53:57 -07002128 closeOnExit, appId, urlData.mUrl);
Grace Klobaec7eb372009-06-16 13:45:56 -07002129 sendAnimateFromOverview(tab, true, urlData, delay, msg);
Grace Klobac9181842009-04-14 08:53:22 -07002130 return tab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002131 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002132 } else if (!urlData.isEmpty()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002133 // We should not have a msg here.
2134 assert msg == null;
2135 if (mTabOverview != null && mAnimationCount == 0) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002136 sendAnimateFromOverview(currentTab, false, urlData,
The Android Open Source Project0c908882009-03-03 19:32:16 -08002137 TAB_OVERVIEW_DELAY, null);
2138 } else {
2139 // Get rid of the subwindow if it exists
2140 dismissSubWindow(currentTab);
2141 // Load the given url.
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07002142 urlData.loadIn(currentTab.getWebView());
The Android Open Source Project0c908882009-03-03 19:32:16 -08002143 }
2144 }
Grace Klobac9181842009-04-14 08:53:22 -07002145 return currentTab;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002146 }
2147
2148 private Animation createTabAnimation(final AnimatingView view,
2149 final View cell, boolean scaleDown) {
2150 final AnimationSet set = new AnimationSet(true);
2151 final float scaleX = (float) cell.getWidth() / view.getWidth();
2152 final float scaleY = (float) cell.getHeight() / view.getHeight();
2153 if (scaleDown) {
2154 set.addAnimation(new ScaleAnimation(1.0f, scaleX, 1.0f, scaleY));
2155 set.addAnimation(new TranslateAnimation(0, cell.getLeft(), 0,
2156 cell.getTop()));
2157 } else {
2158 set.addAnimation(new ScaleAnimation(scaleX, 1.0f, scaleY, 1.0f));
2159 set.addAnimation(new TranslateAnimation(cell.getLeft(), 0,
2160 cell.getTop(), 0));
2161 }
2162 set.setDuration(TAB_ANIMATION_DURATION);
2163 set.setInterpolator(new DecelerateInterpolator());
2164 return set;
2165 }
2166
2167 // Animate to the tab overview. currentIndex tells us which position to
2168 // animate to and newIndex is the position that should be selected after
2169 // the animation completes.
2170 // If remove is true, after the animation stops, a confirmation dialog will
2171 // be displayed to the user.
2172 private void animateToTabOverview(final int newIndex, final boolean remove,
2173 final AnimatingView view) {
2174 // Find the view in the ImageGrid allowing for the "New Tab" cell.
2175 int position = mTabControl.getTabIndex(view.mTab);
2176 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2177 position++;
2178 }
2179
2180 // Offset the tab position with the first visible position to get a
2181 // number between 0 and 3.
2182 position -= mTabOverview.getFirstVisiblePosition();
2183
2184 // Grab the view that we are going to animate to.
2185 final View v = mTabOverview.getChildAt(position);
2186
2187 final Animation.AnimationListener l =
2188 new Animation.AnimationListener() {
2189 public void onAnimationStart(Animation a) {
2190 mTabOverview.requestFocus();
2191 // Clear the listener so we don't trigger a tab
2192 // selection.
2193 mTabOverview.setListener(null);
2194 }
2195 public void onAnimationRepeat(Animation a) {}
2196 public void onAnimationEnd(Animation a) {
2197 // We are no longer animating so decrement the count.
2198 mAnimationCount--;
2199 // Make the view GONE so that it will not draw between
2200 // now and when the Runnable is handled.
2201 view.setVisibility(View.GONE);
2202 // Post a runnable since we can't modify the view
2203 // hierarchy during this callback.
2204 mHandler.post(new Runnable() {
2205 public void run() {
2206 // Remove the AnimatingView.
2207 mContentView.removeView(view);
2208 if (mTabOverview != null) {
2209 // Make newIndex visible.
2210 mTabOverview.setCurrentIndex(newIndex);
2211 // Restore the listener.
2212 mTabOverview.setListener(mTabListener);
2213 // Change the menu to TAB_MENU if the
2214 // ImageGrid is interactive.
2215 if (mTabOverview.isLive()) {
2216 mMenuState = R.id.TAB_MENU;
2217 mTabOverview.requestFocus();
2218 }
2219 }
2220 // If a remove was requested, remove the tab.
2221 if (remove) {
2222 // During a remove, the current tab has
2223 // already changed. Remember the current one
2224 // here.
2225 final TabControl.Tab currentTab =
2226 mTabControl.getCurrentTab();
2227 // Remove the tab at newIndex from
2228 // TabControl and the tab overview.
2229 final TabControl.Tab tab =
2230 mTabControl.getTab(newIndex);
2231 mTabControl.removeTab(tab);
2232 // Restore the current tab.
2233 if (currentTab != tab) {
2234 mTabControl.setCurrentTab(currentTab);
2235 }
2236 if (mTabOverview != null) {
2237 mTabOverview.remove(newIndex);
2238 // Make the current tab visible.
2239 mTabOverview.setCurrentIndex(
2240 mTabControl.getCurrentIndex());
2241 }
2242 }
2243 }
2244 });
2245 }
2246 };
2247
2248 // Do an animation if there is a view to animate to.
2249 if (v != null) {
2250 // Create our animation
2251 final Animation anim = createTabAnimation(view, v, true);
2252 anim.setAnimationListener(l);
2253 // Start animating
2254 view.startAnimation(anim);
2255 } else {
2256 // If something goes wrong and we didn't find a view to animate to,
2257 // just do everything here.
2258 l.onAnimationStart(null);
2259 l.onAnimationEnd(null);
2260 }
2261 }
2262
2263 // Animate from the tab picker. The index supplied is the index to animate
2264 // from.
2265 private void animateFromTabOverview(final AnimatingView view,
2266 final boolean newTab, final Message msg) {
2267 // firstVisible is the first visible tab on the screen. This helps
2268 // to know which corner of the screen the selected tab is.
2269 int firstVisible = mTabOverview.getFirstVisiblePosition();
2270 // tabPosition is the 0-based index of of the tab being opened
2271 int tabPosition = mTabControl.getTabIndex(view.mTab);
2272 if (!((ImageAdapter) mTabOverview.getAdapter()).maxedOut()) {
2273 // Add one to make room for the "New Tab" cell.
2274 tabPosition++;
2275 }
2276 // If this is a new tab, animate from the "New Tab" cell.
2277 if (newTab) {
2278 tabPosition = 0;
2279 }
2280 // Location corresponds to the four corners of the screen.
2281 // A new tab or 0 is upper left, 0 for an old tab is upper
2282 // right, 1 is lower left, and 2 is lower right
2283 int location = tabPosition - firstVisible;
2284
2285 // Find the view at this location.
2286 final View v = mTabOverview.getChildAt(location);
2287
2288 // Wait until the animation completes to replace the AnimatingView.
2289 final Animation.AnimationListener l =
2290 new Animation.AnimationListener() {
2291 public void onAnimationStart(Animation a) {}
2292 public void onAnimationRepeat(Animation a) {}
2293 public void onAnimationEnd(Animation a) {
2294 mHandler.post(new Runnable() {
2295 public void run() {
2296 mContentView.removeView(view);
2297 // Dismiss the tab overview. If the cell at the
2298 // given location is null, set the fade
2299 // parameter to true.
2300 dismissTabOverview(v == null);
2301 TabControl.Tab t =
2302 mTabControl.getCurrentTab();
2303 mMenuState = R.id.MAIN_MENU;
2304 // Resume regular updates.
2305 t.getWebView().resumeTimers();
2306 // Dispatch the message after the animation
2307 // completes.
2308 if (msg != null) {
2309 msg.sendToTarget();
2310 }
2311 // The animation is done and the tab overview is
2312 // gone so allow key events and other animations
2313 // to begin.
2314 mAnimationCount--;
2315 // Reset all the title bar info.
2316 resetTitle();
2317 }
2318 });
2319 }
2320 };
2321
2322 if (v != null) {
2323 final Animation anim = createTabAnimation(view, v, false);
2324 // Set the listener and start animating
2325 anim.setAnimationListener(l);
2326 view.startAnimation(anim);
2327 // Make the view VISIBLE during the animation.
2328 view.setVisibility(View.VISIBLE);
2329 } else {
2330 // Go ahead and do all the cleanup.
2331 l.onAnimationEnd(null);
2332 }
2333 }
2334
2335 // Dismiss the tab overview applying a fade if needed.
2336 private void dismissTabOverview(final boolean fade) {
2337 if (fade) {
2338 AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
2339 anim.setDuration(500);
2340 anim.startNow();
2341 mTabOverview.startAnimation(anim);
2342 }
2343 // Just in case there was a problem with animating away from the tab
2344 // overview
2345 WebView current = mTabControl.getCurrentWebView();
2346 if (current != null) {
2347 current.setVisibility(View.VISIBLE);
2348 } else {
2349 Log.e(LOGTAG, "No current WebView in dismissTabOverview");
2350 }
2351 // Make the sub window container visible.
2352 if (mTabControl.getCurrentSubWindow() != null) {
2353 mTabControl.getCurrentTab().getSubWebViewContainer()
2354 .setVisibility(View.VISIBLE);
2355 }
2356 mContentView.removeView(mTabOverview);
Patrick Scott2ed6edb2009-04-22 10:07:45 -04002357 // Clear all the data for tab picker so next time it will be
2358 // recreated.
2359 mTabControl.wipeAllPickerData();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002360 mTabOverview.clear();
2361 mTabOverview = null;
2362 mTabListener = null;
2363 }
2364
Grace Klobac9181842009-04-14 08:53:22 -07002365 private TabControl.Tab openTab(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002366 if (mSettings.openInBackground()) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002367 TabControl.Tab t = mTabControl.createNewTab();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002368 if (t != null) {
2369 t.getWebView().loadUrl(url);
2370 }
Grace Klobac9181842009-04-14 08:53:22 -07002371 return t;
The Android Open Source Project0c908882009-03-03 19:32:16 -08002372 } else {
Grace Klobac9181842009-04-14 08:53:22 -07002373 return openTabAndShow(url, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002374 }
2375 }
2376
2377 private class Copy implements OnMenuItemClickListener {
2378 private CharSequence mText;
2379
2380 public boolean onMenuItemClick(MenuItem item) {
2381 copy(mText);
2382 return true;
2383 }
2384
2385 public Copy(CharSequence toCopy) {
2386 mText = toCopy;
2387 }
2388 }
2389
2390 private class Download implements OnMenuItemClickListener {
2391 private String mText;
2392
2393 public boolean onMenuItemClick(MenuItem item) {
2394 onDownloadStartNoStream(mText, null, null, null, -1);
2395 return true;
2396 }
2397
2398 public Download(String toDownload) {
2399 mText = toDownload;
2400 }
2401 }
2402
2403 private void copy(CharSequence text) {
2404 try {
2405 IClipboard clip = IClipboard.Stub.asInterface(ServiceManager.getService("clipboard"));
2406 if (clip != null) {
2407 clip.setClipboardText(text);
2408 }
2409 } catch (android.os.RemoteException e) {
2410 Log.e(LOGTAG, "Copy failed", e);
2411 }
2412 }
2413
2414 /**
2415 * Resets the browser title-view to whatever it must be (for example, if we
2416 * load a page from history).
2417 */
2418 private void resetTitle() {
2419 resetLockIcon();
2420 resetTitleIconAndProgress();
2421 }
2422
2423 /**
2424 * Resets the browser title-view to whatever it must be
2425 * (for example, if we had a loading error)
2426 * When we have a new page, we call resetTitle, when we
2427 * have to reset the titlebar to whatever it used to be
2428 * (for example, if the user chose to stop loading), we
2429 * call resetTitleAndRevertLockIcon.
2430 */
2431 /* package */ void resetTitleAndRevertLockIcon() {
2432 revertLockIcon();
2433 resetTitleIconAndProgress();
2434 }
2435
2436 /**
2437 * Reset the title, favicon, and progress.
2438 */
2439 private void resetTitleIconAndProgress() {
2440 WebView current = mTabControl.getCurrentWebView();
2441 if (current == null) {
2442 return;
2443 }
2444 resetTitleAndIcon(current);
2445 int progress = current.getProgress();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002446 mWebChromeClient.onProgressChanged(current, progress);
2447 }
2448
2449 // Reset the title and the icon based on the given item.
2450 private void resetTitleAndIcon(WebView view) {
2451 WebHistoryItem item = view.copyBackForwardList().getCurrentItem();
2452 if (item != null) {
2453 setUrlTitle(item.getUrl(), item.getTitle());
2454 setFavicon(item.getFavicon());
2455 } else {
2456 setUrlTitle(null, null);
2457 setFavicon(null);
2458 }
2459 }
2460
2461 /**
2462 * Sets a title composed of the URL and the title string.
2463 * @param url The URL of the site being loaded.
2464 * @param title The title of the site being loaded.
2465 */
2466 private void setUrlTitle(String url, String title) {
2467 mUrl = url;
2468 mTitle = title;
2469
2470 // While the tab overview is animating or being shown, block changes
2471 // to the title.
2472 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04002473 if (CUSTOM_BROWSER_BAR) {
2474 mTitleBar.setTitleAndUrl(title, url);
2475 } else {
2476 setTitle(buildUrlTitle(url, title));
2477 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002478 }
2479 }
2480
2481 /**
2482 * Builds and returns the page title, which is some
2483 * combination of the page URL and title.
2484 * @param url The URL of the site being loaded.
2485 * @param title The title of the site being loaded.
2486 * @return The page title.
2487 */
2488 private String buildUrlTitle(String url, String title) {
2489 String urlTitle = "";
2490
2491 if (url != null) {
2492 String titleUrl = buildTitleUrl(url);
2493
2494 if (title != null && 0 < title.length()) {
2495 if (titleUrl != null && 0 < titleUrl.length()) {
2496 urlTitle = titleUrl + ": " + title;
2497 } else {
2498 urlTitle = title;
2499 }
2500 } else {
2501 if (titleUrl != null) {
2502 urlTitle = titleUrl;
2503 }
2504 }
2505 }
2506
2507 return urlTitle;
2508 }
2509
2510 /**
2511 * @param url The URL to build a title version of the URL from.
2512 * @return The title version of the URL or null if fails.
2513 * The title version of the URL can be either the URL hostname,
2514 * or the hostname with an "https://" prefix (for secure URLs),
2515 * or an empty string if, for example, the URL in question is a
2516 * file:// URL with no hostname.
2517 */
Leon Scroggins32e14a62009-06-11 10:26:34 -04002518 /* package */ static String buildTitleUrl(String url) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002519 String titleUrl = null;
2520
2521 if (url != null) {
2522 try {
2523 // parse the url string
2524 URL urlObj = new URL(url);
2525 if (urlObj != null) {
2526 titleUrl = "";
2527
2528 String protocol = urlObj.getProtocol();
2529 String host = urlObj.getHost();
2530
2531 if (host != null && 0 < host.length()) {
2532 titleUrl = host;
2533 if (protocol != null) {
2534 // if a secure site, add an "https://" prefix!
2535 if (protocol.equalsIgnoreCase("https")) {
2536 titleUrl = protocol + "://" + host;
2537 }
2538 }
2539 }
2540 }
2541 } catch (MalformedURLException e) {}
2542 }
2543
2544 return titleUrl;
2545 }
2546
2547 // Set the favicon in the title bar.
2548 private void setFavicon(Bitmap icon) {
2549 // While the tab overview is animating or being shown, block changes to
2550 // the favicon.
2551 if (mAnimationCount > 0 || mTabOverview != null) {
2552 return;
2553 }
Leon Scroggins81db3662009-06-04 17:45:11 -04002554 if (CUSTOM_BROWSER_BAR) {
2555 Drawable[] array = new Drawable[3];
2556 array[0] = new PaintDrawable(Color.BLACK);
2557 PaintDrawable p = new PaintDrawable(Color.WHITE);
2558 array[1] = p;
2559 if (icon == null) {
2560 array[2] = mGenericFavicon;
2561 } else {
2562 array[2] = new BitmapDrawable(icon);
2563 }
2564 LayerDrawable d = new LayerDrawable(array);
2565 d.setLayerInset(1, 1, 1, 1, 1);
2566 d.setLayerInset(2, 2, 2, 2, 2);
2567 mTitleBar.setFavicon(d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002568 } else {
Leon Scroggins81db3662009-06-04 17:45:11 -04002569 Drawable[] array = new Drawable[2];
2570 PaintDrawable p = new PaintDrawable(Color.WHITE);
2571 p.setCornerRadius(3f);
2572 array[0] = p;
2573 if (icon == null) {
2574 array[1] = mGenericFavicon;
2575 } else {
2576 array[1] = new BitmapDrawable(icon);
2577 }
2578 LayerDrawable d = new LayerDrawable(array);
2579 d.setLayerInset(1, 2, 2, 2, 2);
2580 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, d);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002581 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002582 }
2583
2584 /**
2585 * Saves the current lock-icon state before resetting
2586 * the lock icon. If we have an error, we may need to
2587 * roll back to the previous state.
2588 */
2589 private void saveLockIcon() {
2590 mPrevLockType = mLockIconType;
2591 }
2592
2593 /**
2594 * Reverts the lock-icon state to the last saved state,
2595 * for example, if we had an error, and need to cancel
2596 * the load.
2597 */
2598 private void revertLockIcon() {
2599 mLockIconType = mPrevLockType;
2600
Dave Bort31a6d1c2009-04-13 15:56:49 -07002601 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08002602 Log.v(LOGTAG, "BrowserActivity.revertLockIcon:" +
2603 " revert lock icon to " + mLockIconType);
2604 }
2605
2606 updateLockIconImage(mLockIconType);
2607 }
2608
2609 private void switchTabs(int indexFrom, int indexToShow, boolean remove) {
2610 int delay = TAB_ANIMATION_DURATION + TAB_OVERVIEW_DELAY;
2611 // Animate to the tab picker, remove the current tab, then
2612 // animate away from the tab picker to the parent WebView.
2613 tabPicker(false, indexFrom, remove);
2614 // Change to the parent tab
2615 final TabControl.Tab tab = mTabControl.getTab(indexToShow);
2616 if (tab != null) {
Patrick Scott95d601f2009-06-11 10:06:46 -04002617 sendAnimateFromOverview(tab, false, EMPTY_URL_DATA, delay, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002618 } else {
2619 // Increment this here so that no other animations can happen in
2620 // between the end of the tab picker transition and the beginning
2621 // of openTabAndShow. This has a matching decrement in the handler
2622 // of OPEN_TAB_AND_SHOW.
2623 mAnimationCount++;
2624 // Send a message to open a new tab.
2625 mHandler.sendMessageDelayed(
2626 mHandler.obtainMessage(OPEN_TAB_AND_SHOW,
2627 mSettings.getHomePage()), delay);
2628 }
2629 }
2630
2631 private void goBackOnePageOrQuit() {
2632 TabControl.Tab current = mTabControl.getCurrentTab();
2633 if (current == null) {
2634 /*
2635 * Instead of finishing the activity, simply push this to the back
2636 * of the stack and let ActivityManager to choose the foreground
2637 * activity. As BrowserActivity is singleTask, it will be always the
2638 * root of the task. So we can use either true or false for
2639 * moveTaskToBack().
2640 */
2641 moveTaskToBack(true);
2642 }
2643 WebView w = current.getWebView();
2644 if (w.canGoBack()) {
2645 w.goBack();
2646 } else {
2647 // Check to see if we are closing a window that was created by
2648 // another window. If so, we switch back to that window.
2649 TabControl.Tab parent = current.getParentTab();
2650 if (parent != null) {
2651 switchTabs(mTabControl.getCurrentIndex(),
2652 mTabControl.getTabIndex(parent), true);
2653 } else {
2654 if (current.closeOnExit()) {
2655 if (mTabControl.getTabCount() == 1) {
2656 finish();
2657 return;
2658 }
Mike Reed7bfa63b2009-05-28 11:08:32 -04002659 // call pauseWebViewTimers() now, we won't be able to call
2660 // it in onPause() as the WebView won't be valid.
2661 pauseWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002662 removeTabFromContentView(current);
2663 mTabControl.removeTab(current);
2664 }
2665 /*
2666 * Instead of finishing the activity, simply push this to the back
2667 * of the stack and let ActivityManager to choose the foreground
2668 * activity. As BrowserActivity is singleTask, it will be always the
2669 * root of the task. So we can use either true or false for
2670 * moveTaskToBack().
2671 */
2672 moveTaskToBack(true);
2673 }
2674 }
2675 }
2676
2677 public KeyTracker.State onKeyTracker(int keyCode,
2678 KeyEvent event,
2679 KeyTracker.Stage stage,
2680 int duration) {
2681 // if onKeyTracker() is called after activity onStop()
2682 // because of accumulated key events,
2683 // we should ignore it as browser is not active any more.
2684 WebView topWindow = getTopWindow();
2685 if (topWindow == null)
2686 return KeyTracker.State.NOT_TRACKING;
2687
2688 if (keyCode == KeyEvent.KEYCODE_BACK) {
2689 // During animations, block the back key so that other animations
2690 // are not triggered and so that we don't end up destroying all the
2691 // WebViews before finishing the animation.
2692 if (mAnimationCount > 0) {
2693 return KeyTracker.State.DONE_TRACKING;
2694 }
2695 if (stage == KeyTracker.Stage.LONG_REPEAT) {
2696 bookmarksOrHistoryPicker(true);
2697 return KeyTracker.State.DONE_TRACKING;
2698 } else if (stage == KeyTracker.Stage.UP) {
2699 // FIXME: Currently, we do not have a notion of the
2700 // history picker for the subwindow, but maybe we
2701 // should?
2702 WebView subwindow = mTabControl.getCurrentSubWindow();
2703 if (subwindow != null) {
2704 if (subwindow.canGoBack()) {
2705 subwindow.goBack();
2706 } else {
2707 dismissSubWindow(mTabControl.getCurrentTab());
2708 }
2709 } else {
2710 goBackOnePageOrQuit();
2711 }
2712 return KeyTracker.State.DONE_TRACKING;
2713 }
2714 return KeyTracker.State.KEEP_TRACKING;
2715 }
2716 return KeyTracker.State.NOT_TRACKING;
2717 }
2718
2719 @Override public boolean onKeyDown(int keyCode, KeyEvent event) {
2720 if (keyCode == KeyEvent.KEYCODE_MENU) {
2721 mMenuIsDown = true;
2722 }
2723 boolean handled = mKeyTracker.doKeyDown(keyCode, event);
2724 if (!handled) {
2725 switch (keyCode) {
2726 case KeyEvent.KEYCODE_SPACE:
2727 if (event.isShiftPressed()) {
2728 getTopWindow().pageUp(false);
2729 } else {
2730 getTopWindow().pageDown(false);
2731 }
2732 handled = true;
2733 break;
2734
2735 default:
2736 break;
2737 }
2738 }
2739 return handled || super.onKeyDown(keyCode, event);
2740 }
2741
2742 @Override public boolean onKeyUp(int keyCode, KeyEvent event) {
2743 if (keyCode == KeyEvent.KEYCODE_MENU) {
2744 mMenuIsDown = false;
2745 }
2746 return mKeyTracker.doKeyUp(keyCode, event) || super.onKeyUp(keyCode, event);
2747 }
2748
2749 private void stopLoading() {
2750 resetTitleAndRevertLockIcon();
2751 WebView w = getTopWindow();
2752 w.stopLoading();
2753 mWebViewClient.onPageFinished(w, w.getUrl());
2754
2755 cancelStopToast();
2756 mStopToast = Toast
2757 .makeText(this, R.string.stopping, Toast.LENGTH_SHORT);
2758 mStopToast.show();
2759 }
2760
2761 private void cancelStopToast() {
2762 if (mStopToast != null) {
2763 mStopToast.cancel();
2764 mStopToast = null;
2765 }
2766 }
2767
2768 // called by a non-UI thread to post the message
2769 public void postMessage(int what, int arg1, int arg2, Object obj) {
2770 mHandler.sendMessage(mHandler.obtainMessage(what, arg1, arg2, obj));
2771 }
2772
2773 // public message ids
2774 public final static int LOAD_URL = 1001;
2775 public final static int STOP_LOAD = 1002;
2776
2777 // Message Ids
2778 private static final int FOCUS_NODE_HREF = 102;
2779 private static final int CANCEL_CREDS_REQUEST = 103;
2780 private static final int ANIMATE_FROM_OVERVIEW = 104;
2781 private static final int ANIMATE_TO_OVERVIEW = 105;
2782 private static final int OPEN_TAB_AND_SHOW = 106;
2783 private static final int CHECK_MEMORY = 107;
2784 private static final int RELEASE_WAKELOCK = 108;
2785
2786 // Private handler for handling javascript and saving passwords
2787 private Handler mHandler = new Handler() {
2788
2789 public void handleMessage(Message msg) {
2790 switch (msg.what) {
2791 case ANIMATE_FROM_OVERVIEW:
2792 final HashMap map = (HashMap) msg.obj;
2793 animateFromTabOverview((AnimatingView) map.get("view"),
2794 msg.arg1 == 1, (Message) map.get("msg"));
2795 break;
2796
2797 case ANIMATE_TO_OVERVIEW:
2798 animateToTabOverview(msg.arg1, msg.arg2 == 1,
2799 (AnimatingView) msg.obj);
2800 break;
2801
2802 case OPEN_TAB_AND_SHOW:
2803 // Decrement mAnimationCount before openTabAndShow because
2804 // the method relies on the value being 0 to start the next
2805 // animation.
2806 mAnimationCount--;
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07002807 openTabAndShow((String) msg.obj, null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08002808 break;
2809
2810 case FOCUS_NODE_HREF:
2811 String url = (String) msg.getData().get("url");
2812 if (url == null || url.length() == 0) {
2813 break;
2814 }
2815 HashMap focusNodeMap = (HashMap) msg.obj;
2816 WebView view = (WebView) focusNodeMap.get("webview");
2817 // Only apply the action if the top window did not change.
2818 if (getTopWindow() != view) {
2819 break;
2820 }
2821 switch (msg.arg1) {
2822 case R.id.open_context_menu_id:
2823 case R.id.view_image_context_menu_id:
2824 loadURL(getTopWindow(), url);
2825 break;
2826 case R.id.open_newtab_context_menu_id:
Grace Klobac9181842009-04-14 08:53:22 -07002827 final TabControl.Tab parent = mTabControl
2828 .getCurrentTab();
2829 final TabControl.Tab newTab = openTab(url);
2830 if (newTab != parent) {
2831 parent.addChildTab(newTab);
2832 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08002833 break;
2834 case R.id.bookmark_context_menu_id:
2835 Intent intent = new Intent(BrowserActivity.this,
2836 AddBookmarkPage.class);
2837 intent.putExtra("url", url);
2838 startActivity(intent);
2839 break;
2840 case R.id.share_link_context_menu_id:
2841 Browser.sendString(BrowserActivity.this, url);
2842 break;
2843 case R.id.copy_link_context_menu_id:
2844 copy(url);
2845 break;
2846 case R.id.save_link_context_menu_id:
2847 case R.id.download_context_menu_id:
2848 onDownloadStartNoStream(url, null, null, null, -1);
2849 break;
2850 }
2851 break;
2852
2853 case LOAD_URL:
2854 loadURL(getTopWindow(), (String) msg.obj);
2855 break;
2856
2857 case STOP_LOAD:
2858 stopLoading();
2859 break;
2860
2861 case CANCEL_CREDS_REQUEST:
2862 resumeAfterCredentials();
2863 break;
2864
2865 case CHECK_MEMORY:
2866 // reschedule to check memory condition
2867 mHandler.removeMessages(CHECK_MEMORY);
2868 mHandler.sendMessageDelayed(mHandler.obtainMessage
2869 (CHECK_MEMORY), CHECK_MEMORY_INTERVAL);
2870 checkMemory();
2871 break;
2872
2873 case RELEASE_WAKELOCK:
2874 if (mWakeLock.isHeld()) {
2875 mWakeLock.release();
2876 }
2877 break;
2878 }
2879 }
2880 };
2881
2882 // -------------------------------------------------------------------------
2883 // WebViewClient implementation.
2884 //-------------------------------------------------------------------------
2885
2886 // Use in overrideUrlLoading
2887 /* package */ final static String SCHEME_WTAI = "wtai://wp/";
2888 /* package */ final static String SCHEME_WTAI_MC = "wtai://wp/mc;";
2889 /* package */ final static String SCHEME_WTAI_SD = "wtai://wp/sd;";
2890 /* package */ final static String SCHEME_WTAI_AP = "wtai://wp/ap;";
2891
2892 /* package */ WebViewClient getWebViewClient() {
2893 return mWebViewClient;
2894 }
2895
2896 private void updateIcon(String url, Bitmap icon) {
2897 if (icon != null) {
2898 BrowserBookmarksAdapter.updateBookmarkFavicon(mResolver,
2899 url, icon);
2900 }
2901 setFavicon(icon);
2902 }
2903
2904 private final WebViewClient mWebViewClient = new WebViewClient() {
2905 @Override
2906 public void onPageStarted(WebView view, String url, Bitmap favicon) {
2907 resetLockIcon(url);
2908 setUrlTitle(url, null);
2909 // Call updateIcon instead of setFavicon so the bookmark
2910 // database can be updated.
2911 updateIcon(url, favicon);
2912
2913 if (mSettings.isTracing() == true) {
2914 // FIXME: we should save the trace file somewhere other than data.
2915 // I can't use "/tmp" as it competes for system memory.
2916 File file = getDir("browserTrace", 0);
2917 String baseDir = file.getPath();
2918 if (!baseDir.endsWith(File.separator)) baseDir += File.separator;
2919 String host;
2920 try {
2921 WebAddress uri = new WebAddress(url);
2922 host = uri.mHost;
2923 } catch (android.net.ParseException ex) {
2924 host = "unknown_host";
2925 }
2926 host = host.replace('.', '_');
2927 baseDir = baseDir + host;
2928 file = new File(baseDir+".data");
2929 if (file.exists() == true) {
2930 file.delete();
2931 }
2932 file = new File(baseDir+".key");
2933 if (file.exists() == true) {
2934 file.delete();
2935 }
2936 mInTrace = true;
2937 Debug.startMethodTracing(baseDir, 8 * 1024 * 1024);
2938 }
2939
2940 // Performance probe
2941 if (false) {
2942 mStart = SystemClock.uptimeMillis();
2943 mProcessStart = Process.getElapsedCpuTime();
2944 long[] sysCpu = new long[7];
2945 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
2946 sysCpu, null)) {
2947 mUserStart = sysCpu[0] + sysCpu[1];
2948 mSystemStart = sysCpu[2];
2949 mIdleStart = sysCpu[3];
2950 mIrqStart = sysCpu[4] + sysCpu[5] + sysCpu[6];
2951 }
2952 mUiStart = SystemClock.currentThreadTimeMillis();
2953 }
2954
2955 if (!mPageStarted) {
2956 mPageStarted = true;
Mike Reed7bfa63b2009-05-28 11:08:32 -04002957 // if onResume() has been called, resumeWebViewTimers() does
2958 // nothing.
2959 resumeWebViewTimers();
The Android Open Source Project0c908882009-03-03 19:32:16 -08002960 }
2961
2962 // reset sync timer to avoid sync starts during loading a page
2963 CookieSyncManager.getInstance().resetSync();
2964
2965 mInLoad = true;
2966 updateInLoadMenuItems();
2967 if (!mIsNetworkUp) {
2968 if ( mAlertDialog == null) {
2969 mAlertDialog = new AlertDialog.Builder(BrowserActivity.this)
2970 .setTitle(R.string.loadSuspendedTitle)
2971 .setMessage(R.string.loadSuspended)
2972 .setPositiveButton(R.string.ok, null)
2973 .show();
2974 }
2975 if (view != null) {
2976 view.setNetworkAvailable(false);
2977 }
2978 }
2979
2980 // schedule to check memory condition
2981 mHandler.sendMessageDelayed(mHandler.obtainMessage(CHECK_MEMORY),
2982 CHECK_MEMORY_INTERVAL);
2983 }
2984
2985 @Override
2986 public void onPageFinished(WebView view, String url) {
2987 // Reset the title and icon in case we stopped a provisional
2988 // load.
2989 resetTitleAndIcon(view);
2990
2991 // Update the lock icon image only once we are done loading
2992 updateLockIconImage(mLockIconType);
2993
Leon Scrogginsb6b7f9e2009-06-18 12:05:28 -04002994 // If this is a bookmarked site, add a screenshot to the database.
2995 // FIXME: When should we update? Every time?
2996 if (url != null) {
2997 // copied from BrowserBookmarksAdapter
2998 int query = url.indexOf('?');
2999 String noQuery = url;
3000 if (query != -1) {
3001 noQuery = url.substring(0, query);
3002 }
3003 String URL = noQuery + '?';
3004 String[] selArgs = new String[] { noQuery, URL };
3005 final String where = "(url == ? OR url GLOB ? || '*') AND bookmark == 1";
3006 final String[] projection = new String[] { Browser.BookmarkColumns._ID };
3007 ContentResolver cr = getContentResolver();
3008 final Cursor c = cr.query(Browser.BOOKMARKS_URI, projection, where, selArgs, null);
3009 boolean succeed = c.moveToFirst();
3010 ContentValues values = null;
3011 while (succeed) {
3012 if (values == null) {
3013 final ByteArrayOutputStream os = new ByteArrayOutputStream();
3014 Picture thumbnail = view.capturePicture();
3015 // Height was arbitrarily chosen
3016 Bitmap bm = Bitmap.createBitmap(100, 100,
3017 Bitmap.Config.ARGB_4444);
3018 Canvas canvas = new Canvas(bm);
3019 // Scale chosen to be about one third, since we want
3020 // roughly three rows/columns for bookmark page
3021 canvas.scale(.3f, .3f);
3022 thumbnail.draw(canvas);
3023 bm.compress(Bitmap.CompressFormat.PNG, 100, os);
3024 values = new ContentValues();
3025 values.put(Browser.BookmarkColumns.THUMBNAIL,
3026 os.toByteArray());
3027 }
3028 cr.update(ContentUris.withAppendedId(Browser.BOOKMARKS_URI,
3029 c.getInt(0)), values, null, null);
3030 succeed = c.moveToNext();
3031 }
3032 c.close();
3033 }
3034
The Android Open Source Project0c908882009-03-03 19:32:16 -08003035 // Performance probe
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003036 if (false) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003037 long[] sysCpu = new long[7];
3038 if (Process.readProcFile("/proc/stat", SYSTEM_CPU_FORMAT, null,
3039 sysCpu, null)) {
3040 String uiInfo = "UI thread used "
3041 + (SystemClock.currentThreadTimeMillis() - mUiStart)
3042 + " ms";
Dave Bort31a6d1c2009-04-13 15:56:49 -07003043 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003044 Log.d(LOGTAG, uiInfo);
3045 }
3046 //The string that gets written to the log
3047 String performanceString = "It took total "
3048 + (SystemClock.uptimeMillis() - mStart)
3049 + " ms clock time to load the page."
3050 + "\nbrowser process used "
3051 + (Process.getElapsedCpuTime() - mProcessStart)
3052 + " ms, user processes used "
3053 + (sysCpu[0] + sysCpu[1] - mUserStart) * 10
3054 + " ms, kernel used "
3055 + (sysCpu[2] - mSystemStart) * 10
3056 + " ms, idle took " + (sysCpu[3] - mIdleStart) * 10
3057 + " ms and irq took "
3058 + (sysCpu[4] + sysCpu[5] + sysCpu[6] - mIrqStart)
3059 * 10 + " ms, " + uiInfo;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003060 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003061 Log.d(LOGTAG, performanceString + "\nWebpage: " + url);
3062 }
3063 if (url != null) {
3064 // strip the url to maintain consistency
3065 String newUrl = new String(url);
3066 if (newUrl.startsWith("http://www.")) {
3067 newUrl = newUrl.substring(11);
3068 } else if (newUrl.startsWith("http://")) {
3069 newUrl = newUrl.substring(7);
3070 } else if (newUrl.startsWith("https://www.")) {
3071 newUrl = newUrl.substring(12);
3072 } else if (newUrl.startsWith("https://")) {
3073 newUrl = newUrl.substring(8);
3074 }
Dave Bort31a6d1c2009-04-13 15:56:49 -07003075 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003076 Log.d(LOGTAG, newUrl + " loaded");
3077 }
3078 /*
3079 if (sWhiteList.contains(newUrl)) {
3080 // The string that gets pushed to the statistcs
3081 // service
3082 performanceString = performanceString
3083 + "\nWebpage: "
3084 + newUrl
3085 + "\nCarrier: "
3086 + android.os.SystemProperties
3087 .get("gsm.sim.operator.alpha");
3088 if (mWebView != null
3089 && mWebView.getContext() != null
3090 && mWebView.getContext().getSystemService(
3091 Context.CONNECTIVITY_SERVICE) != null) {
3092 ConnectivityManager cManager =
3093 (ConnectivityManager) mWebView
3094 .getContext().getSystemService(
3095 Context.CONNECTIVITY_SERVICE);
3096 NetworkInfo nInfo = cManager
3097 .getActiveNetworkInfo();
3098 if (nInfo != null) {
3099 performanceString = performanceString
3100 + "\nNetwork Type: "
3101 + nInfo.getType().toString();
3102 }
3103 }
3104 Checkin.logEvent(mResolver,
3105 Checkin.Events.Tag.WEBPAGE_LOAD,
3106 performanceString);
3107 Log.w(LOGTAG, "pushed to the statistics service");
3108 }
3109 */
3110 }
3111 }
3112 }
3113
3114 if (mInTrace) {
3115 mInTrace = false;
3116 Debug.stopMethodTracing();
3117 }
3118
3119 if (mPageStarted) {
3120 mPageStarted = false;
Mike Reed7bfa63b2009-05-28 11:08:32 -04003121 // pauseWebViewTimers() will do nothing and return false if
3122 // onPause() is not called yet.
3123 if (pauseWebViewTimers()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003124 if (mWakeLock.isHeld()) {
3125 mHandler.removeMessages(RELEASE_WAKELOCK);
3126 mWakeLock.release();
3127 }
3128 }
3129 }
3130
The Android Open Source Project0c908882009-03-03 19:32:16 -08003131 mHandler.removeMessages(CHECK_MEMORY);
3132 checkMemory();
3133 }
3134
3135 // return true if want to hijack the url to let another app to handle it
3136 @Override
3137 public boolean shouldOverrideUrlLoading(WebView view, String url) {
3138 if (url.startsWith(SCHEME_WTAI)) {
3139 // wtai://wp/mc;number
3140 // number=string(phone-number)
3141 if (url.startsWith(SCHEME_WTAI_MC)) {
3142 Intent intent = new Intent(Intent.ACTION_VIEW,
3143 Uri.parse(WebView.SCHEME_TEL +
3144 url.substring(SCHEME_WTAI_MC.length())));
3145 startActivity(intent);
3146 return true;
3147 }
3148 // wtai://wp/sd;dtmf
3149 // dtmf=string(dialstring)
3150 if (url.startsWith(SCHEME_WTAI_SD)) {
3151 // TODO
3152 // only send when there is active voice connection
3153 return false;
3154 }
3155 // wtai://wp/ap;number;name
3156 // number=string(phone-number)
3157 // name=string
3158 if (url.startsWith(SCHEME_WTAI_AP)) {
3159 // TODO
3160 return false;
3161 }
3162 }
3163
Dianne Hackborn99189432009-06-17 18:06:18 -07003164 // The "about:" schemes are internal to the browser; don't
3165 // want these to be dispatched to other apps.
3166 if (url.startsWith("about:")) {
3167 return false;
3168 }
3169
3170 Intent intent;
3171
3172 // perform generic parsing of the URI to turn it into an Intent.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003173 try {
Dianne Hackborn99189432009-06-17 18:06:18 -07003174 intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
3175 } catch (URISyntaxException ex) {
3176 Log.w("Browser", "Bad URI " + url + ": " + ex.getMessage());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003177 return false;
3178 }
3179
Dianne Hackborn99189432009-06-17 18:06:18 -07003180 // sanitize the Intent, ensuring web pages can not bypass browser
3181 // security (only access to BROWSABLE activities).
The Android Open Source Project0c908882009-03-03 19:32:16 -08003182 intent.addCategory(Intent.CATEGORY_BROWSABLE);
Dianne Hackborn99189432009-06-17 18:06:18 -07003183 intent.setComponent(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003184 try {
3185 if (startActivityIfNeeded(intent, -1)) {
3186 return true;
3187 }
3188 } catch (ActivityNotFoundException ex) {
3189 // ignore the error. If no application can handle the URL,
3190 // eg about:blank, assume the browser can handle it.
3191 }
3192
3193 if (mMenuIsDown) {
3194 openTab(url);
3195 closeOptionsMenu();
3196 return true;
3197 }
3198
3199 return false;
3200 }
3201
3202 /**
3203 * Updates the lock icon. This method is called when we discover another
3204 * resource to be loaded for this page (for example, javascript). While
3205 * we update the icon type, we do not update the lock icon itself until
3206 * we are done loading, it is slightly more secure this way.
3207 */
3208 @Override
3209 public void onLoadResource(WebView view, String url) {
3210 if (url != null && url.length() > 0) {
3211 // It is only if the page claims to be secure
3212 // that we may have to update the lock:
3213 if (mLockIconType == LOCK_ICON_SECURE) {
3214 // If NOT a 'safe' url, change the lock to mixed content!
3215 if (!(URLUtil.isHttpsUrl(url) || URLUtil.isDataUrl(url) || URLUtil.isAboutUrl(url))) {
3216 mLockIconType = LOCK_ICON_MIXED;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003217 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003218 Log.v(LOGTAG, "BrowserActivity.updateLockIcon:" +
3219 " updated lock icon to " + mLockIconType + " due to " + url);
3220 }
3221 }
3222 }
3223 }
3224 }
3225
3226 /**
3227 * Show the dialog, asking the user if they would like to continue after
3228 * an excessive number of HTTP redirects.
3229 */
3230 @Override
3231 public void onTooManyRedirects(WebView view, final Message cancelMsg,
3232 final Message continueMsg) {
3233 new AlertDialog.Builder(BrowserActivity.this)
3234 .setTitle(R.string.browserFrameRedirect)
3235 .setMessage(R.string.browserFrame307Post)
3236 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3237 public void onClick(DialogInterface dialog, int which) {
3238 continueMsg.sendToTarget();
3239 }})
3240 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3241 public void onClick(DialogInterface dialog, int which) {
3242 cancelMsg.sendToTarget();
3243 }})
3244 .setOnCancelListener(new OnCancelListener() {
3245 public void onCancel(DialogInterface dialog) {
3246 cancelMsg.sendToTarget();
3247 }})
3248 .show();
3249 }
3250
Patrick Scott37911c72009-03-24 18:02:58 -07003251 // Container class for the next error dialog that needs to be
3252 // displayed.
3253 class ErrorDialog {
3254 public final int mTitle;
3255 public final String mDescription;
3256 public final int mError;
3257 ErrorDialog(int title, String desc, int error) {
3258 mTitle = title;
3259 mDescription = desc;
3260 mError = error;
3261 }
3262 };
3263
3264 private void processNextError() {
3265 if (mQueuedErrors == null) {
3266 return;
3267 }
3268 // The first one is currently displayed so just remove it.
3269 mQueuedErrors.removeFirst();
3270 if (mQueuedErrors.size() == 0) {
3271 mQueuedErrors = null;
3272 return;
3273 }
3274 showError(mQueuedErrors.getFirst());
3275 }
3276
3277 private DialogInterface.OnDismissListener mDialogListener =
3278 new DialogInterface.OnDismissListener() {
3279 public void onDismiss(DialogInterface d) {
3280 processNextError();
3281 }
3282 };
3283 private LinkedList<ErrorDialog> mQueuedErrors;
3284
3285 private void queueError(int err, String desc) {
3286 if (mQueuedErrors == null) {
3287 mQueuedErrors = new LinkedList<ErrorDialog>();
3288 }
3289 for (ErrorDialog d : mQueuedErrors) {
3290 if (d.mError == err) {
3291 // Already saw a similar error, ignore the new one.
3292 return;
3293 }
3294 }
3295 ErrorDialog errDialog = new ErrorDialog(
3296 err == EventHandler.FILE_NOT_FOUND_ERROR ?
3297 R.string.browserFrameFileErrorLabel :
3298 R.string.browserFrameNetworkErrorLabel,
3299 desc, err);
3300 mQueuedErrors.addLast(errDialog);
3301
3302 // Show the dialog now if the queue was empty.
3303 if (mQueuedErrors.size() == 1) {
3304 showError(errDialog);
3305 }
3306 }
3307
3308 private void showError(ErrorDialog errDialog) {
3309 AlertDialog d = new AlertDialog.Builder(BrowserActivity.this)
3310 .setTitle(errDialog.mTitle)
3311 .setMessage(errDialog.mDescription)
3312 .setPositiveButton(R.string.ok, null)
3313 .create();
3314 d.setOnDismissListener(mDialogListener);
3315 d.show();
3316 }
3317
The Android Open Source Project0c908882009-03-03 19:32:16 -08003318 /**
3319 * Show a dialog informing the user of the network error reported by
3320 * WebCore.
3321 */
3322 @Override
3323 public void onReceivedError(WebView view, int errorCode,
3324 String description, String failingUrl) {
3325 if (errorCode != EventHandler.ERROR_LOOKUP &&
3326 errorCode != EventHandler.ERROR_CONNECT &&
3327 errorCode != EventHandler.ERROR_BAD_URL &&
3328 errorCode != EventHandler.ERROR_UNSUPPORTED_SCHEME &&
3329 errorCode != EventHandler.FILE_ERROR) {
Patrick Scott37911c72009-03-24 18:02:58 -07003330 queueError(errorCode, description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003331 }
Patrick Scott37911c72009-03-24 18:02:58 -07003332 Log.e(LOGTAG, "onReceivedError " + errorCode + " " + failingUrl
3333 + " " + description);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003334
3335 // We need to reset the title after an error.
3336 resetTitleAndRevertLockIcon();
3337 }
3338
3339 /**
3340 * Check with the user if it is ok to resend POST data as the page they
3341 * are trying to navigate to is the result of a POST.
3342 */
3343 @Override
3344 public void onFormResubmission(WebView view, final Message dontResend,
3345 final Message resend) {
3346 new AlertDialog.Builder(BrowserActivity.this)
3347 .setTitle(R.string.browserFrameFormResubmitLabel)
3348 .setMessage(R.string.browserFrameFormResubmitMessage)
3349 .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
3350 public void onClick(DialogInterface dialog, int which) {
3351 resend.sendToTarget();
3352 }})
3353 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
3354 public void onClick(DialogInterface dialog, int which) {
3355 dontResend.sendToTarget();
3356 }})
3357 .setOnCancelListener(new OnCancelListener() {
3358 public void onCancel(DialogInterface dialog) {
3359 dontResend.sendToTarget();
3360 }})
3361 .show();
3362 }
3363
3364 /**
3365 * Insert the url into the visited history database.
3366 * @param url The url to be inserted.
3367 * @param isReload True if this url is being reloaded.
3368 * FIXME: Not sure what to do when reloading the page.
3369 */
3370 @Override
3371 public void doUpdateVisitedHistory(WebView view, String url,
3372 boolean isReload) {
3373 if (url.regionMatches(true, 0, "about:", 0, 6)) {
3374 return;
3375 }
3376 Browser.updateVisitedHistory(mResolver, url, true);
3377 WebIconDatabase.getInstance().retainIconForPageUrl(url);
3378 }
3379
3380 /**
3381 * Displays SSL error(s) dialog to the user.
3382 */
3383 @Override
3384 public void onReceivedSslError(
3385 final WebView view, final SslErrorHandler handler, final SslError error) {
3386
3387 if (mSettings.showSecurityWarnings()) {
3388 final LayoutInflater factory =
3389 LayoutInflater.from(BrowserActivity.this);
3390 final View warningsView =
3391 factory.inflate(R.layout.ssl_warnings, null);
3392 final LinearLayout placeholder =
3393 (LinearLayout)warningsView.findViewById(R.id.placeholder);
3394
3395 if (error.hasError(SslError.SSL_UNTRUSTED)) {
3396 LinearLayout ll = (LinearLayout)factory
3397 .inflate(R.layout.ssl_warning, null);
3398 ((TextView)ll.findViewById(R.id.warning))
3399 .setText(R.string.ssl_untrusted);
3400 placeholder.addView(ll);
3401 }
3402
3403 if (error.hasError(SslError.SSL_IDMISMATCH)) {
3404 LinearLayout ll = (LinearLayout)factory
3405 .inflate(R.layout.ssl_warning, null);
3406 ((TextView)ll.findViewById(R.id.warning))
3407 .setText(R.string.ssl_mismatch);
3408 placeholder.addView(ll);
3409 }
3410
3411 if (error.hasError(SslError.SSL_EXPIRED)) {
3412 LinearLayout ll = (LinearLayout)factory
3413 .inflate(R.layout.ssl_warning, null);
3414 ((TextView)ll.findViewById(R.id.warning))
3415 .setText(R.string.ssl_expired);
3416 placeholder.addView(ll);
3417 }
3418
3419 if (error.hasError(SslError.SSL_NOTYETVALID)) {
3420 LinearLayout ll = (LinearLayout)factory
3421 .inflate(R.layout.ssl_warning, null);
3422 ((TextView)ll.findViewById(R.id.warning))
3423 .setText(R.string.ssl_not_yet_valid);
3424 placeholder.addView(ll);
3425 }
3426
3427 new AlertDialog.Builder(BrowserActivity.this)
3428 .setTitle(R.string.security_warning)
3429 .setIcon(android.R.drawable.ic_dialog_alert)
3430 .setView(warningsView)
3431 .setPositiveButton(R.string.ssl_continue,
3432 new DialogInterface.OnClickListener() {
3433 public void onClick(DialogInterface dialog, int whichButton) {
3434 handler.proceed();
3435 }
3436 })
3437 .setNeutralButton(R.string.view_certificate,
3438 new DialogInterface.OnClickListener() {
3439 public void onClick(DialogInterface dialog, int whichButton) {
3440 showSSLCertificateOnError(view, handler, error);
3441 }
3442 })
3443 .setNegativeButton(R.string.cancel,
3444 new DialogInterface.OnClickListener() {
3445 public void onClick(DialogInterface dialog, int whichButton) {
3446 handler.cancel();
3447 BrowserActivity.this.resetTitleAndRevertLockIcon();
3448 }
3449 })
3450 .setOnCancelListener(
3451 new DialogInterface.OnCancelListener() {
3452 public void onCancel(DialogInterface dialog) {
3453 handler.cancel();
3454 BrowserActivity.this.resetTitleAndRevertLockIcon();
3455 }
3456 })
3457 .show();
3458 } else {
3459 handler.proceed();
3460 }
3461 }
3462
3463 /**
3464 * Handles an HTTP authentication request.
3465 *
3466 * @param handler The authentication handler
3467 * @param host The host
3468 * @param realm The realm
3469 */
3470 @Override
3471 public void onReceivedHttpAuthRequest(WebView view,
3472 final HttpAuthHandler handler, final String host, final String realm) {
3473 String username = null;
3474 String password = null;
3475
3476 boolean reuseHttpAuthUsernamePassword =
3477 handler.useHttpAuthUsernamePassword();
3478
3479 if (reuseHttpAuthUsernamePassword &&
3480 (mTabControl.getCurrentWebView() != null)) {
3481 String[] credentials =
3482 mTabControl.getCurrentWebView()
3483 .getHttpAuthUsernamePassword(host, realm);
3484 if (credentials != null && credentials.length == 2) {
3485 username = credentials[0];
3486 password = credentials[1];
3487 }
3488 }
3489
3490 if (username != null && password != null) {
3491 handler.proceed(username, password);
3492 } else {
3493 showHttpAuthentication(handler, host, realm, null, null, null, 0);
3494 }
3495 }
3496
3497 @Override
3498 public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
3499 if (mMenuIsDown) {
3500 // only check shortcut key when MENU is held
3501 return getWindow().isShortcutKey(event.getKeyCode(), event);
3502 } else {
3503 return false;
3504 }
3505 }
3506
3507 @Override
3508 public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
3509 if (view != mTabControl.getCurrentTopWebView()) {
3510 return;
3511 }
3512 if (event.isDown()) {
3513 BrowserActivity.this.onKeyDown(event.getKeyCode(), event);
3514 } else {
3515 BrowserActivity.this.onKeyUp(event.getKeyCode(), event);
3516 }
3517 }
3518 };
3519
3520 //--------------------------------------------------------------------------
3521 // WebChromeClient implementation
3522 //--------------------------------------------------------------------------
3523
3524 /* package */ WebChromeClient getWebChromeClient() {
3525 return mWebChromeClient;
3526 }
3527
3528 private final WebChromeClient mWebChromeClient = new WebChromeClient() {
3529 // Helper method to create a new tab or sub window.
3530 private void createWindow(final boolean dialog, final Message msg) {
3531 if (dialog) {
3532 mTabControl.createSubWindow();
3533 final TabControl.Tab t = mTabControl.getCurrentTab();
3534 attachSubWindow(t);
3535 WebView.WebViewTransport transport =
3536 (WebView.WebViewTransport) msg.obj;
3537 transport.setWebView(t.getSubWebView());
3538 msg.sendToTarget();
3539 } else {
3540 final TabControl.Tab parent = mTabControl.getCurrentTab();
3541 // openTabAndShow will dispatch the message after creating the
3542 // new WebView. This will prevent another request from coming
3543 // in during the animation.
Patrick Scott1536e732009-06-11 14:50:01 -04003544 final TabControl.Tab newTab =
3545 openTabAndShow(EMPTY_URL_DATA, msg, false, null);
Grace Klobac9181842009-04-14 08:53:22 -07003546 if (newTab != parent) {
3547 parent.addChildTab(newTab);
3548 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003549 WebView.WebViewTransport transport =
3550 (WebView.WebViewTransport) msg.obj;
3551 transport.setWebView(mTabControl.getCurrentWebView());
3552 }
3553 }
3554
3555 @Override
3556 public boolean onCreateWindow(WebView view, final boolean dialog,
3557 final boolean userGesture, final Message resultMsg) {
3558 // Ignore these requests during tab animations or if the tab
3559 // overview is showing.
3560 if (mAnimationCount > 0 || mTabOverview != null) {
3561 return false;
3562 }
3563 // Short-circuit if we can't create any more tabs or sub windows.
3564 if (dialog && mTabControl.getCurrentSubWindow() != null) {
3565 new AlertDialog.Builder(BrowserActivity.this)
3566 .setTitle(R.string.too_many_subwindows_dialog_title)
3567 .setIcon(android.R.drawable.ic_dialog_alert)
3568 .setMessage(R.string.too_many_subwindows_dialog_message)
3569 .setPositiveButton(R.string.ok, null)
3570 .show();
3571 return false;
3572 } else if (mTabControl.getTabCount() >= TabControl.MAX_TABS) {
3573 new AlertDialog.Builder(BrowserActivity.this)
3574 .setTitle(R.string.too_many_windows_dialog_title)
3575 .setIcon(android.R.drawable.ic_dialog_alert)
3576 .setMessage(R.string.too_many_windows_dialog_message)
3577 .setPositiveButton(R.string.ok, null)
3578 .show();
3579 return false;
3580 }
3581
3582 // Short-circuit if this was a user gesture.
3583 if (userGesture) {
3584 // createWindow will call openTabAndShow for new Windows and
3585 // that will call tabPicker which will increment
3586 // mAnimationCount.
3587 createWindow(dialog, resultMsg);
3588 return true;
3589 }
3590
3591 // Allow the popup and create the appropriate window.
3592 final AlertDialog.OnClickListener allowListener =
3593 new AlertDialog.OnClickListener() {
3594 public void onClick(DialogInterface d,
3595 int which) {
3596 // Same comment as above for setting
3597 // mAnimationCount.
3598 createWindow(dialog, resultMsg);
3599 // Since we incremented mAnimationCount while the
3600 // dialog was up, we have to decrement it here.
3601 mAnimationCount--;
3602 }
3603 };
3604
3605 // Block the popup by returning a null WebView.
3606 final AlertDialog.OnClickListener blockListener =
3607 new AlertDialog.OnClickListener() {
3608 public void onClick(DialogInterface d, int which) {
3609 resultMsg.sendToTarget();
3610 // We are not going to trigger an animation so
3611 // unblock keys and animation requests.
3612 mAnimationCount--;
3613 }
3614 };
3615
3616 // Build a confirmation dialog to display to the user.
3617 final AlertDialog d =
3618 new AlertDialog.Builder(BrowserActivity.this)
3619 .setTitle(R.string.attention)
3620 .setIcon(android.R.drawable.ic_dialog_alert)
3621 .setMessage(R.string.popup_window_attempt)
3622 .setPositiveButton(R.string.allow, allowListener)
3623 .setNegativeButton(R.string.block, blockListener)
3624 .setCancelable(false)
3625 .create();
3626
3627 // Show the confirmation dialog.
3628 d.show();
3629 // We want to increment mAnimationCount here to prevent a
3630 // potential race condition. If the user allows a pop-up from a
3631 // site and that pop-up then triggers another pop-up, it is
3632 // possible to get the BACK key between here and when the dialog
3633 // appears.
3634 mAnimationCount++;
3635 return true;
3636 }
3637
3638 @Override
3639 public void onCloseWindow(WebView window) {
3640 final int currentIndex = mTabControl.getCurrentIndex();
3641 final TabControl.Tab parent =
3642 mTabControl.getCurrentTab().getParentTab();
3643 if (parent != null) {
3644 // JavaScript can only close popup window.
3645 switchTabs(currentIndex, mTabControl.getTabIndex(parent), true);
3646 }
3647 }
3648
3649 @Override
3650 public void onProgressChanged(WebView view, int newProgress) {
3651 // Block progress updates to the title bar while the tab overview
3652 // is animating or being displayed.
3653 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003654 if (CUSTOM_BROWSER_BAR) {
3655 mTitleBar.setProgress(newProgress);
3656 } else {
3657 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
3658 newProgress * 100);
3659
3660 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003661 }
3662
3663 if (newProgress == 100) {
3664 // onProgressChanged() is called for sub-frame too while
3665 // onPageFinished() is only called for the main frame. sync
3666 // cookie and cache promptly here.
3667 CookieSyncManager.getInstance().sync();
The Android Open Source Projectcb9a0bb2009-03-11 12:11:58 -07003668 if (mInLoad) {
3669 mInLoad = false;
3670 updateInLoadMenuItems();
3671 }
3672 } else {
3673 // onPageFinished may have already been called but a subframe
3674 // is still loading and updating the progress. Reset mInLoad
3675 // and update the menu items.
3676 if (!mInLoad) {
3677 mInLoad = true;
3678 updateInLoadMenuItems();
3679 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003680 }
3681 }
3682
3683 @Override
3684 public void onReceivedTitle(WebView view, String title) {
Patrick Scott598c9cc2009-06-04 11:10:38 -04003685 String url = view.getUrl();
The Android Open Source Project0c908882009-03-03 19:32:16 -08003686
3687 // here, if url is null, we want to reset the title
3688 setUrlTitle(url, title);
3689
3690 if (url == null ||
3691 url.length() >= SQLiteDatabase.SQLITE_MAX_LIKE_PATTERN_LENGTH) {
3692 return;
3693 }
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003694 // See if we can find the current url in our history database and
3695 // add the new title to it.
The Android Open Source Project0c908882009-03-03 19:32:16 -08003696 if (url.startsWith("http://www.")) {
3697 url = url.substring(11);
3698 } else if (url.startsWith("http://")) {
3699 url = url.substring(4);
3700 }
3701 try {
3702 url = "%" + url;
3703 String [] selArgs = new String[] { url };
3704
3705 String where = Browser.BookmarkColumns.URL + " LIKE ? AND "
3706 + Browser.BookmarkColumns.BOOKMARK + " = 0";
3707 Cursor c = mResolver.query(Browser.BOOKMARKS_URI,
3708 Browser.HISTORY_PROJECTION, where, selArgs, null);
3709 if (c.moveToFirst()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003710 // Current implementation of database only has one entry per
3711 // url.
Leon Scrogginsfce182b2009-05-08 13:54:52 -04003712 ContentValues map = new ContentValues();
3713 map.put(Browser.BookmarkColumns.TITLE, title);
3714 mResolver.update(Browser.BOOKMARKS_URI, map,
3715 "_id = " + c.getInt(0), null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003716 }
3717 c.close();
3718 } catch (IllegalStateException e) {
3719 Log.e(LOGTAG, "BrowserActivity onReceived title", e);
3720 } catch (SQLiteException ex) {
3721 Log.e(LOGTAG, "onReceivedTitle() caught SQLiteException: ", ex);
3722 }
3723 }
3724
3725 @Override
3726 public void onReceivedIcon(WebView view, Bitmap icon) {
3727 updateIcon(view.getUrl(), icon);
3728 }
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003729
3730 /**
3731 * The origin has exceeded it's database quota.
3732 * @param url the URL that exceeded the quota
3733 * @param databaseIdentifier the identifier of the database on
3734 * which the transaction that caused the quota overflow was run
3735 * @param currentQuota the current quota for the origin.
3736 * @param quotaUpdater The callback to run when a decision to allow or
3737 * deny quota has been made. Don't forget to call this!
3738 */
3739 @Override
3740 public void onExceededDatabaseQuota(String url,
3741 String databaseIdentifier, long currentQuota,
3742 WebStorage.QuotaUpdater quotaUpdater) {
3743 if(LOGV_ENABLED) {
3744 Log.v(LOGTAG,
3745 "BrowserActivity received onExceededDatabaseQuota for "
3746 + url +
3747 ":"
3748 + databaseIdentifier +
3749 "(current quota: "
3750 + currentQuota +
3751 ")");
3752 }
Nicolas Roard78a98e42009-05-11 13:34:17 +01003753 mWebStorageQuotaUpdater = quotaUpdater;
3754 String DIALOG_PACKAGE = "com.android.browser";
3755 String DIALOG_CLASS = DIALOG_PACKAGE + ".PermissionDialog";
3756 Intent intent = new Intent();
3757 intent.setClassName(DIALOG_PACKAGE, DIALOG_CLASS);
3758 intent.putExtra(PermissionDialog.PARAM_ORIGIN, url);
3759 intent.putExtra(PermissionDialog.PARAM_QUOTA, currentQuota);
3760 startActivityForResult(intent, WEBSTORAGE_QUOTA_DIALOG);
Ben Murdoch092dd5d2009-04-22 12:34:12 +01003761 }
Ben Murdoch7db26342009-06-03 18:21:19 +01003762
3763 /* Adds a JavaScript error message to the system log.
3764 * @param message The error message to report.
3765 * @param lineNumber The line number of the error.
3766 * @param sourceID The name of the source file that caused the error.
3767 */
3768 @Override
3769 public void addMessageToConsole(String message, int lineNumber, String sourceID) {
3770 Log.w(LOGTAG, "Console: " + message + " (" + sourceID + ":" + lineNumber + ")");
3771 }
3772
The Android Open Source Project0c908882009-03-03 19:32:16 -08003773 };
3774
3775 /**
3776 * Notify the host application a download should be done, or that
3777 * the data should be streamed if a streaming viewer is available.
3778 * @param url The full url to the content that should be downloaded
3779 * @param contentDisposition Content-disposition http header, if
3780 * present.
3781 * @param mimetype The mimetype of the content reported by the server
3782 * @param contentLength The file size reported by the server
3783 */
3784 public void onDownloadStart(String url, String userAgent,
3785 String contentDisposition, String mimetype, long contentLength) {
3786 // if we're dealing wih A/V content that's not explicitly marked
3787 // for download, check if it's streamable.
3788 if (contentDisposition == null
3789 || !contentDisposition.regionMatches(true, 0, "attachment", 0, 10)) {
3790 // query the package manager to see if there's a registered handler
3791 // that matches.
3792 Intent intent = new Intent(Intent.ACTION_VIEW);
3793 intent.setDataAndType(Uri.parse(url), mimetype);
3794 if (getPackageManager().resolveActivity(intent,
3795 PackageManager.MATCH_DEFAULT_ONLY) != null) {
3796 // someone knows how to handle this mime type with this scheme, don't download.
3797 try {
3798 startActivity(intent);
3799 return;
3800 } catch (ActivityNotFoundException ex) {
Dave Bort31a6d1c2009-04-13 15:56:49 -07003801 if (LOGD_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003802 Log.d(LOGTAG, "activity not found for " + mimetype
3803 + " over " + Uri.parse(url).getScheme(), ex);
3804 }
3805 // Best behavior is to fall back to a download in this case
3806 }
3807 }
3808 }
3809 onDownloadStartNoStream(url, userAgent, contentDisposition, mimetype, contentLength);
3810 }
3811
3812 /**
3813 * Notify the host application a download should be done, even if there
3814 * is a streaming viewer available for thise type.
3815 * @param url The full url to the content that should be downloaded
3816 * @param contentDisposition Content-disposition http header, if
3817 * present.
3818 * @param mimetype The mimetype of the content reported by the server
3819 * @param contentLength The file size reported by the server
3820 */
3821 /*package */ void onDownloadStartNoStream(String url, String userAgent,
3822 String contentDisposition, String mimetype, long contentLength) {
3823
3824 String filename = URLUtil.guessFileName(url,
3825 contentDisposition, mimetype);
3826
3827 // Check to see if we have an SDCard
3828 String status = Environment.getExternalStorageState();
3829 if (!status.equals(Environment.MEDIA_MOUNTED)) {
3830 int title;
3831 String msg;
3832
3833 // Check to see if the SDCard is busy, same as the music app
3834 if (status.equals(Environment.MEDIA_SHARED)) {
3835 msg = getString(R.string.download_sdcard_busy_dlg_msg);
3836 title = R.string.download_sdcard_busy_dlg_title;
3837 } else {
3838 msg = getString(R.string.download_no_sdcard_dlg_msg, filename);
3839 title = R.string.download_no_sdcard_dlg_title;
3840 }
3841
3842 new AlertDialog.Builder(this)
3843 .setTitle(title)
3844 .setIcon(android.R.drawable.ic_dialog_alert)
3845 .setMessage(msg)
3846 .setPositiveButton(R.string.ok, null)
3847 .show();
3848 return;
3849 }
3850
3851 // java.net.URI is a lot stricter than KURL so we have to undo
3852 // KURL's percent-encoding and redo the encoding using java.net.URI.
3853 URI uri = null;
3854 try {
3855 // Undo the percent-encoding that KURL may have done.
3856 String newUrl = new String(URLUtil.decode(url.getBytes()));
3857 // Parse the url into pieces
3858 WebAddress w = new WebAddress(newUrl);
3859 String frag = null;
3860 String query = null;
3861 String path = w.mPath;
3862 // Break the path into path, query, and fragment
3863 if (path.length() > 0) {
3864 // Strip the fragment
3865 int idx = path.lastIndexOf('#');
3866 if (idx != -1) {
3867 frag = path.substring(idx + 1);
3868 path = path.substring(0, idx);
3869 }
3870 idx = path.lastIndexOf('?');
3871 if (idx != -1) {
3872 query = path.substring(idx + 1);
3873 path = path.substring(0, idx);
3874 }
3875 }
3876 uri = new URI(w.mScheme, w.mAuthInfo, w.mHost, w.mPort, path,
3877 query, frag);
3878 } catch (Exception e) {
3879 Log.e(LOGTAG, "Could not parse url for download: " + url, e);
3880 return;
3881 }
3882
3883 // XXX: Have to use the old url since the cookies were stored using the
3884 // old percent-encoded url.
3885 String cookies = CookieManager.getInstance().getCookie(url);
3886
3887 ContentValues values = new ContentValues();
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003888 values.put(Downloads.COLUMN_URI, uri.toString());
3889 values.put(Downloads.COLUMN_COOKIE_DATA, cookies);
3890 values.put(Downloads.COLUMN_USER_AGENT, userAgent);
3891 values.put(Downloads.COLUMN_NOTIFICATION_PACKAGE,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003892 getPackageName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003893 values.put(Downloads.COLUMN_NOTIFICATION_CLASS,
The Android Open Source Project0c908882009-03-03 19:32:16 -08003894 BrowserDownloadPage.class.getCanonicalName());
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003895 values.put(Downloads.COLUMN_VISIBILITY, Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
3896 values.put(Downloads.COLUMN_MIME_TYPE, mimetype);
3897 values.put(Downloads.COLUMN_FILE_NAME_HINT, filename);
3898 values.put(Downloads.COLUMN_DESCRIPTION, uri.getHost());
The Android Open Source Project0c908882009-03-03 19:32:16 -08003899 if (contentLength > 0) {
Jean-Baptiste Queru3dc09b22009-03-31 16:49:44 -07003900 values.put(Downloads.COLUMN_TOTAL_BYTES, contentLength);
The Android Open Source Project0c908882009-03-03 19:32:16 -08003901 }
3902 if (mimetype == null) {
3903 // We must have long pressed on a link or image to download it. We
3904 // are not sure of the mimetype in this case, so do a head request
3905 new FetchUrlMimeType(this).execute(values);
3906 } else {
3907 final Uri contentUri =
3908 getContentResolver().insert(Downloads.CONTENT_URI, values);
3909 viewDownloads(contentUri);
3910 }
3911
3912 }
3913
3914 /**
3915 * Resets the lock icon. This method is called when we start a new load and
3916 * know the url to be loaded.
3917 */
3918 private void resetLockIcon(String url) {
3919 // Save the lock-icon state (we revert to it if the load gets cancelled)
3920 saveLockIcon();
3921
3922 mLockIconType = LOCK_ICON_UNSECURE;
3923 if (URLUtil.isHttpsUrl(url)) {
3924 mLockIconType = LOCK_ICON_SECURE;
Dave Bort31a6d1c2009-04-13 15:56:49 -07003925 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003926 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3927 " reset lock icon to " + mLockIconType);
3928 }
3929 }
3930
3931 updateLockIconImage(LOCK_ICON_UNSECURE);
3932 }
3933
3934 /**
3935 * Resets the lock icon. This method is called when the icon needs to be
3936 * reset but we do not know whether we are loading a secure or not secure
3937 * page.
3938 */
3939 private void resetLockIcon() {
3940 // Save the lock-icon state (we revert to it if the load gets cancelled)
3941 saveLockIcon();
3942
3943 mLockIconType = LOCK_ICON_UNSECURE;
3944
Dave Bort31a6d1c2009-04-13 15:56:49 -07003945 if (LOGV_ENABLED) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08003946 Log.v(LOGTAG, "BrowserActivity.resetLockIcon:" +
3947 " reset lock icon to " + mLockIconType);
3948 }
3949
3950 updateLockIconImage(LOCK_ICON_UNSECURE);
3951 }
3952
3953 /**
3954 * Updates the lock-icon image in the title-bar.
3955 */
3956 private void updateLockIconImage(int lockIconType) {
3957 Drawable d = null;
3958 if (lockIconType == LOCK_ICON_SECURE) {
3959 d = mSecLockIcon;
3960 } else if (lockIconType == LOCK_ICON_MIXED) {
3961 d = mMixLockIcon;
3962 }
3963 // If the tab overview is animating or being shown, do not update the
3964 // lock icon.
3965 if (mAnimationCount == 0 && mTabOverview == null) {
Leon Scroggins81db3662009-06-04 17:45:11 -04003966 if (CUSTOM_BROWSER_BAR) {
3967 mTitleBar.setLock(d);
3968 } else {
3969 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, d);
3970 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08003971 }
3972 }
3973
3974 /**
3975 * Displays a page-info dialog.
3976 * @param tab The tab to show info about
3977 * @param fromShowSSLCertificateOnError The flag that indicates whether
3978 * this dialog was opened from the SSL-certificate-on-error dialog or
3979 * not. This is important, since we need to know whether to return to
3980 * the parent dialog or simply dismiss.
3981 */
3982 private void showPageInfo(final TabControl.Tab tab,
3983 final boolean fromShowSSLCertificateOnError) {
3984 final LayoutInflater factory = LayoutInflater
3985 .from(this);
3986
3987 final View pageInfoView = factory.inflate(R.layout.page_info, null);
3988
3989 final WebView view = tab.getWebView();
3990
3991 String url = null;
3992 String title = null;
3993
3994 if (view == null) {
3995 url = tab.getUrl();
3996 title = tab.getTitle();
3997 } else if (view == mTabControl.getCurrentWebView()) {
3998 // Use the cached title and url if this is the current WebView
3999 url = mUrl;
4000 title = mTitle;
4001 } else {
4002 url = view.getUrl();
4003 title = view.getTitle();
4004 }
4005
4006 if (url == null) {
4007 url = "";
4008 }
4009 if (title == null) {
4010 title = "";
4011 }
4012
4013 ((TextView) pageInfoView.findViewById(R.id.address)).setText(url);
4014 ((TextView) pageInfoView.findViewById(R.id.title)).setText(title);
4015
4016 mPageInfoView = tab;
4017 mPageInfoFromShowSSLCertificateOnError = new Boolean(fromShowSSLCertificateOnError);
4018
4019 AlertDialog.Builder alertDialogBuilder =
4020 new AlertDialog.Builder(this)
4021 .setTitle(R.string.page_info).setIcon(android.R.drawable.ic_dialog_info)
4022 .setView(pageInfoView)
4023 .setPositiveButton(
4024 R.string.ok,
4025 new DialogInterface.OnClickListener() {
4026 public void onClick(DialogInterface dialog,
4027 int whichButton) {
4028 mPageInfoDialog = null;
4029 mPageInfoView = null;
4030 mPageInfoFromShowSSLCertificateOnError = null;
4031
4032 // if we came here from the SSL error dialog
4033 if (fromShowSSLCertificateOnError) {
4034 // go back to the SSL error dialog
4035 showSSLCertificateOnError(
4036 mSSLCertificateOnErrorView,
4037 mSSLCertificateOnErrorHandler,
4038 mSSLCertificateOnErrorError);
4039 }
4040 }
4041 })
4042 .setOnCancelListener(
4043 new DialogInterface.OnCancelListener() {
4044 public void onCancel(DialogInterface dialog) {
4045 mPageInfoDialog = null;
4046 mPageInfoView = null;
4047 mPageInfoFromShowSSLCertificateOnError = null;
4048
4049 // if we came here from the SSL error dialog
4050 if (fromShowSSLCertificateOnError) {
4051 // go back to the SSL error dialog
4052 showSSLCertificateOnError(
4053 mSSLCertificateOnErrorView,
4054 mSSLCertificateOnErrorHandler,
4055 mSSLCertificateOnErrorError);
4056 }
4057 }
4058 });
4059
4060 // if we have a main top-level page SSL certificate set or a certificate
4061 // error
4062 if (fromShowSSLCertificateOnError ||
4063 (view != null && view.getCertificate() != null)) {
4064 // add a 'View Certificate' button
4065 alertDialogBuilder.setNeutralButton(
4066 R.string.view_certificate,
4067 new DialogInterface.OnClickListener() {
4068 public void onClick(DialogInterface dialog,
4069 int whichButton) {
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 } else {
4082 // otherwise, display the top-most certificate from
4083 // the chain
4084 if (view.getCertificate() != null) {
4085 showSSLCertificate(tab);
4086 }
4087 }
4088 }
4089 });
4090 }
4091
4092 mPageInfoDialog = alertDialogBuilder.show();
4093 }
4094
4095 /**
4096 * Displays the main top-level page SSL certificate dialog
4097 * (accessible from the Page-Info dialog).
4098 * @param tab The tab to show certificate for.
4099 */
4100 private void showSSLCertificate(final TabControl.Tab tab) {
4101 final View certificateView =
4102 inflateCertificateView(tab.getWebView().getCertificate());
4103 if (certificateView == null) {
4104 return;
4105 }
4106
4107 LayoutInflater factory = LayoutInflater.from(this);
4108
4109 final LinearLayout placeholder =
4110 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4111
4112 LinearLayout ll = (LinearLayout) factory.inflate(
4113 R.layout.ssl_success, placeholder);
4114 ((TextView)ll.findViewById(R.id.success))
4115 .setText(R.string.ssl_certificate_is_valid);
4116
4117 mSSLCertificateView = tab;
4118 mSSLCertificateDialog =
4119 new AlertDialog.Builder(this)
4120 .setTitle(R.string.ssl_certificate).setIcon(
4121 R.drawable.ic_dialog_browser_certificate_secure)
4122 .setView(certificateView)
4123 .setPositiveButton(R.string.ok,
4124 new DialogInterface.OnClickListener() {
4125 public void onClick(DialogInterface dialog,
4126 int whichButton) {
4127 mSSLCertificateDialog = null;
4128 mSSLCertificateView = null;
4129
4130 showPageInfo(tab, false);
4131 }
4132 })
4133 .setOnCancelListener(
4134 new DialogInterface.OnCancelListener() {
4135 public void onCancel(DialogInterface dialog) {
4136 mSSLCertificateDialog = null;
4137 mSSLCertificateView = null;
4138
4139 showPageInfo(tab, false);
4140 }
4141 })
4142 .show();
4143 }
4144
4145 /**
4146 * Displays the SSL error certificate dialog.
4147 * @param view The target web-view.
4148 * @param handler The SSL error handler responsible for cancelling the
4149 * connection that resulted in an SSL error or proceeding per user request.
4150 * @param error The SSL error object.
4151 */
4152 private void showSSLCertificateOnError(
4153 final WebView view, final SslErrorHandler handler, final SslError error) {
4154
4155 final View certificateView =
4156 inflateCertificateView(error.getCertificate());
4157 if (certificateView == null) {
4158 return;
4159 }
4160
4161 LayoutInflater factory = LayoutInflater.from(this);
4162
4163 final LinearLayout placeholder =
4164 (LinearLayout)certificateView.findViewById(R.id.placeholder);
4165
4166 if (error.hasError(SslError.SSL_UNTRUSTED)) {
4167 LinearLayout ll = (LinearLayout)factory
4168 .inflate(R.layout.ssl_warning, placeholder);
4169 ((TextView)ll.findViewById(R.id.warning))
4170 .setText(R.string.ssl_untrusted);
4171 }
4172
4173 if (error.hasError(SslError.SSL_IDMISMATCH)) {
4174 LinearLayout ll = (LinearLayout)factory
4175 .inflate(R.layout.ssl_warning, placeholder);
4176 ((TextView)ll.findViewById(R.id.warning))
4177 .setText(R.string.ssl_mismatch);
4178 }
4179
4180 if (error.hasError(SslError.SSL_EXPIRED)) {
4181 LinearLayout ll = (LinearLayout)factory
4182 .inflate(R.layout.ssl_warning, placeholder);
4183 ((TextView)ll.findViewById(R.id.warning))
4184 .setText(R.string.ssl_expired);
4185 }
4186
4187 if (error.hasError(SslError.SSL_NOTYETVALID)) {
4188 LinearLayout ll = (LinearLayout)factory
4189 .inflate(R.layout.ssl_warning, placeholder);
4190 ((TextView)ll.findViewById(R.id.warning))
4191 .setText(R.string.ssl_not_yet_valid);
4192 }
4193
4194 mSSLCertificateOnErrorHandler = handler;
4195 mSSLCertificateOnErrorView = view;
4196 mSSLCertificateOnErrorError = error;
4197 mSSLCertificateOnErrorDialog =
4198 new AlertDialog.Builder(this)
4199 .setTitle(R.string.ssl_certificate).setIcon(
4200 R.drawable.ic_dialog_browser_certificate_partially_secure)
4201 .setView(certificateView)
4202 .setPositiveButton(R.string.ok,
4203 new DialogInterface.OnClickListener() {
4204 public void onClick(DialogInterface dialog,
4205 int whichButton) {
4206 mSSLCertificateOnErrorDialog = null;
4207 mSSLCertificateOnErrorView = null;
4208 mSSLCertificateOnErrorHandler = null;
4209 mSSLCertificateOnErrorError = null;
4210
4211 mWebViewClient.onReceivedSslError(
4212 view, handler, error);
4213 }
4214 })
4215 .setNeutralButton(R.string.page_info_view,
4216 new DialogInterface.OnClickListener() {
4217 public void onClick(DialogInterface dialog,
4218 int whichButton) {
4219 mSSLCertificateOnErrorDialog = null;
4220
4221 // do not clear the dialog state: we will
4222 // need to show the dialog again once the
4223 // user is done exploring the page-info details
4224
4225 showPageInfo(mTabControl.getTabFromView(view),
4226 true);
4227 }
4228 })
4229 .setOnCancelListener(
4230 new DialogInterface.OnCancelListener() {
4231 public void onCancel(DialogInterface dialog) {
4232 mSSLCertificateOnErrorDialog = null;
4233 mSSLCertificateOnErrorView = null;
4234 mSSLCertificateOnErrorHandler = null;
4235 mSSLCertificateOnErrorError = null;
4236
4237 mWebViewClient.onReceivedSslError(
4238 view, handler, error);
4239 }
4240 })
4241 .show();
4242 }
4243
4244 /**
4245 * Inflates the SSL certificate view (helper method).
4246 * @param certificate The SSL certificate.
4247 * @return The resultant certificate view with issued-to, issued-by,
4248 * issued-on, expires-on, and possibly other fields set.
4249 * If the input certificate is null, returns null.
4250 */
4251 private View inflateCertificateView(SslCertificate certificate) {
4252 if (certificate == null) {
4253 return null;
4254 }
4255
4256 LayoutInflater factory = LayoutInflater.from(this);
4257
4258 View certificateView = factory.inflate(
4259 R.layout.ssl_certificate, null);
4260
4261 // issued to:
4262 SslCertificate.DName issuedTo = certificate.getIssuedTo();
4263 if (issuedTo != null) {
4264 ((TextView) certificateView.findViewById(R.id.to_common))
4265 .setText(issuedTo.getCName());
4266 ((TextView) certificateView.findViewById(R.id.to_org))
4267 .setText(issuedTo.getOName());
4268 ((TextView) certificateView.findViewById(R.id.to_org_unit))
4269 .setText(issuedTo.getUName());
4270 }
4271
4272 // issued by:
4273 SslCertificate.DName issuedBy = certificate.getIssuedBy();
4274 if (issuedBy != null) {
4275 ((TextView) certificateView.findViewById(R.id.by_common))
4276 .setText(issuedBy.getCName());
4277 ((TextView) certificateView.findViewById(R.id.by_org))
4278 .setText(issuedBy.getOName());
4279 ((TextView) certificateView.findViewById(R.id.by_org_unit))
4280 .setText(issuedBy.getUName());
4281 }
4282
4283 // issued on:
4284 String issuedOn = reformatCertificateDate(
4285 certificate.getValidNotBefore());
4286 ((TextView) certificateView.findViewById(R.id.issued_on))
4287 .setText(issuedOn);
4288
4289 // expires on:
4290 String expiresOn = reformatCertificateDate(
4291 certificate.getValidNotAfter());
4292 ((TextView) certificateView.findViewById(R.id.expires_on))
4293 .setText(expiresOn);
4294
4295 return certificateView;
4296 }
4297
4298 /**
4299 * Re-formats the certificate date (Date.toString()) string to
4300 * a properly localized date string.
4301 * @return Properly localized version of the certificate date string and
4302 * the original certificate date string if fails to localize.
4303 * If the original string is null, returns an empty string "".
4304 */
4305 private String reformatCertificateDate(String certificateDate) {
4306 String reformattedDate = null;
4307
4308 if (certificateDate != null) {
4309 Date date = null;
4310 try {
4311 date = java.text.DateFormat.getInstance().parse(certificateDate);
4312 } catch (ParseException e) {
4313 date = null;
4314 }
4315
4316 if (date != null) {
4317 reformattedDate =
4318 DateFormat.getDateFormat(this).format(date);
4319 }
4320 }
4321
4322 return reformattedDate != null ? reformattedDate :
4323 (certificateDate != null ? certificateDate : "");
4324 }
4325
4326 /**
4327 * Displays an http-authentication dialog.
4328 */
4329 private void showHttpAuthentication(final HttpAuthHandler handler,
4330 final String host, final String realm, final String title,
4331 final String name, final String password, int focusId) {
4332 LayoutInflater factory = LayoutInflater.from(this);
4333 final View v = factory
4334 .inflate(R.layout.http_authentication, null);
4335 if (name != null) {
4336 ((EditText) v.findViewById(R.id.username_edit)).setText(name);
4337 }
4338 if (password != null) {
4339 ((EditText) v.findViewById(R.id.password_edit)).setText(password);
4340 }
4341
4342 String titleText = title;
4343 if (titleText == null) {
4344 titleText = getText(R.string.sign_in_to).toString().replace(
4345 "%s1", host).replace("%s2", realm);
4346 }
4347
4348 mHttpAuthHandler = handler;
4349 AlertDialog dialog = new AlertDialog.Builder(this)
4350 .setTitle(titleText)
4351 .setIcon(android.R.drawable.ic_dialog_alert)
4352 .setView(v)
4353 .setPositiveButton(R.string.action,
4354 new DialogInterface.OnClickListener() {
4355 public void onClick(DialogInterface dialog,
4356 int whichButton) {
4357 String nm = ((EditText) v
4358 .findViewById(R.id.username_edit))
4359 .getText().toString();
4360 String pw = ((EditText) v
4361 .findViewById(R.id.password_edit))
4362 .getText().toString();
4363 BrowserActivity.this.setHttpAuthUsernamePassword
4364 (host, realm, nm, pw);
4365 handler.proceed(nm, pw);
4366 mHttpAuthenticationDialog = null;
4367 mHttpAuthHandler = null;
4368 }})
4369 .setNegativeButton(R.string.cancel,
4370 new DialogInterface.OnClickListener() {
4371 public void onClick(DialogInterface dialog,
4372 int whichButton) {
4373 handler.cancel();
4374 BrowserActivity.this.resetTitleAndRevertLockIcon();
4375 mHttpAuthenticationDialog = null;
4376 mHttpAuthHandler = null;
4377 }})
4378 .setOnCancelListener(new DialogInterface.OnCancelListener() {
4379 public void onCancel(DialogInterface dialog) {
4380 handler.cancel();
4381 BrowserActivity.this.resetTitleAndRevertLockIcon();
4382 mHttpAuthenticationDialog = null;
4383 mHttpAuthHandler = null;
4384 }})
4385 .create();
4386 // Make the IME appear when the dialog is displayed if applicable.
4387 dialog.getWindow().setSoftInputMode(
4388 WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
4389 dialog.show();
4390 if (focusId != 0) {
4391 dialog.findViewById(focusId).requestFocus();
4392 } else {
4393 v.findViewById(R.id.username_edit).requestFocus();
4394 }
4395 mHttpAuthenticationDialog = dialog;
4396 }
4397
4398 public int getProgress() {
4399 WebView w = mTabControl.getCurrentWebView();
4400 if (w != null) {
4401 return w.getProgress();
4402 } else {
4403 return 100;
4404 }
4405 }
4406
4407 /**
4408 * Set HTTP authentication password.
4409 *
4410 * @param host The host for the password
4411 * @param realm The realm for the password
4412 * @param username The username for the password. If it is null, it means
4413 * password can't be saved.
4414 * @param password The password
4415 */
4416 public void setHttpAuthUsernamePassword(String host, String realm,
4417 String username,
4418 String password) {
4419 WebView w = mTabControl.getCurrentWebView();
4420 if (w != null) {
4421 w.setHttpAuthUsernamePassword(host, realm, username, password);
4422 }
4423 }
4424
4425 /**
4426 * connectivity manager says net has come or gone... inform the user
4427 * @param up true if net has come up, false if net has gone down
4428 */
4429 public void onNetworkToggle(boolean up) {
4430 if (up == mIsNetworkUp) {
4431 return;
4432 } else if (up) {
4433 mIsNetworkUp = true;
4434 if (mAlertDialog != null) {
4435 mAlertDialog.cancel();
4436 mAlertDialog = null;
4437 }
4438 } else {
4439 mIsNetworkUp = false;
4440 if (mInLoad && mAlertDialog == null) {
4441 mAlertDialog = new AlertDialog.Builder(this)
4442 .setTitle(R.string.loadSuspendedTitle)
4443 .setMessage(R.string.loadSuspended)
4444 .setPositiveButton(R.string.ok, null)
4445 .show();
4446 }
4447 }
4448 WebView w = mTabControl.getCurrentWebView();
4449 if (w != null) {
4450 w.setNetworkAvailable(up);
4451 }
4452 }
4453
4454 @Override
4455 protected void onActivityResult(int requestCode, int resultCode,
4456 Intent intent) {
4457 switch (requestCode) {
4458 case COMBO_PAGE:
4459 if (resultCode == RESULT_OK && intent != null) {
4460 String data = intent.getAction();
4461 Bundle extras = intent.getExtras();
4462 if (extras != null && extras.getBoolean("new_window", false)) {
4463 openTab(data);
4464 } else {
4465 final TabControl.Tab currentTab =
4466 mTabControl.getCurrentTab();
4467 // If the Window overview is up and we are not in the
4468 // middle of an animation, animate away from it to the
4469 // current tab.
4470 if (mTabOverview != null && mAnimationCount == 0) {
Grace Klobaec7eb372009-06-16 13:45:56 -07004471 sendAnimateFromOverview(currentTab, false,
4472 new UrlData(data), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004473 } else {
4474 dismissSubWindow(currentTab);
4475 if (data != null && data.length() != 0) {
4476 getTopWindow().loadUrl(data);
4477 }
4478 }
4479 }
4480 }
4481 break;
Nicolas Roard78a98e42009-05-11 13:34:17 +01004482 case WEBSTORAGE_QUOTA_DIALOG:
4483 long currentQuota = 0;
4484 if (resultCode == RESULT_OK && intent != null) {
4485 currentQuota = intent.getLongExtra(
4486 PermissionDialog.PARAM_QUOTA, currentQuota);
4487 }
4488 mWebStorageQuotaUpdater.updateQuota(currentQuota);
4489 break;
The Android Open Source Project0c908882009-03-03 19:32:16 -08004490 default:
4491 break;
4492 }
4493 getTopWindow().requestFocus();
4494 }
4495
4496 /*
4497 * This method is called as a result of the user selecting the options
4498 * menu to see the download window, or when a download changes state. It
4499 * shows the download window ontop of the current window.
4500 */
4501 /* package */ void viewDownloads(Uri downloadRecord) {
4502 Intent intent = new Intent(this,
4503 BrowserDownloadPage.class);
4504 intent.setData(downloadRecord);
4505 startActivityForResult(intent, this.DOWNLOAD_PAGE);
4506
4507 }
4508
4509 /**
4510 * Handle results from Tab Switcher mTabOverview tool
4511 */
4512 private class TabListener implements ImageGrid.Listener {
4513 public void remove(int position) {
4514 // Note: Remove is not enabled if we have only one tab.
Dave Bort31a6d1c2009-04-13 15:56:49 -07004515 if (DEBUG && mTabControl.getTabCount() == 1) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004516 throw new AssertionError();
4517 }
4518
4519 // Remember the current tab.
4520 TabControl.Tab current = mTabControl.getCurrentTab();
4521 final TabControl.Tab remove = mTabControl.getTab(position);
4522 mTabControl.removeTab(remove);
4523 // If we removed the current tab, use the tab at position - 1 if
4524 // possible.
4525 if (current == remove) {
4526 // If the user removes the last tab, act like the New Tab item
4527 // was clicked on.
4528 if (mTabControl.getTabCount() == 0) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004529 current = mTabControl.createNewTab();
Grace Klobaec7eb372009-06-16 13:45:56 -07004530 sendAnimateFromOverview(current, true, new UrlData(
4531 mSettings.getHomePage()), TAB_OVERVIEW_DELAY, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004532 } else {
4533 final int index = position > 0 ? (position - 1) : 0;
4534 current = mTabControl.getTab(index);
4535 }
4536 }
4537
4538 // The tab overview could have been dismissed before this method is
4539 // called.
4540 if (mTabOverview != null) {
4541 // Remove the tab and change the index.
4542 mTabOverview.remove(position);
4543 mTabOverview.setCurrentIndex(mTabControl.getTabIndex(current));
4544 }
4545
4546 // Only the current tab ensures its WebView is non-null. This
4547 // implies that we are reloading the freed tab.
4548 mTabControl.setCurrentTab(current);
4549 }
4550 public void onClick(int index) {
4551 // Change the tab if necessary.
4552 // Index equals ImageGrid.CANCEL when pressing back from the tab
4553 // overview.
4554 if (index == ImageGrid.CANCEL) {
4555 index = mTabControl.getCurrentIndex();
4556 // The current index is -1 if the current tab was removed.
4557 if (index == -1) {
4558 // Take the last tab as a fallback.
4559 index = mTabControl.getTabCount() - 1;
4560 }
4561 }
4562
The Android Open Source Project0c908882009-03-03 19:32:16 -08004563 // NEW_TAB means that the "New Tab" cell was clicked on.
4564 if (index == ImageGrid.NEW_TAB) {
The Android Open Source Projectf59ec872009-03-13 13:04:24 -07004565 openTabAndShow(mSettings.getHomePage(), null, false, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004566 } else {
Grace Klobaec7eb372009-06-16 13:45:56 -07004567 sendAnimateFromOverview(mTabControl.getTab(index), false,
4568 EMPTY_URL_DATA, 0, null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004569 }
4570 }
4571 }
4572
4573 // A fake View that draws the WebView's picture with a fast zoom filter.
4574 // The View is used in case the tab is freed during the animation because
4575 // of low memory.
4576 private static class AnimatingView extends View {
4577 private static final int ZOOM_BITS = Paint.FILTER_BITMAP_FLAG |
4578 Paint.DITHER_FLAG | Paint.SUBPIXEL_TEXT_FLAG;
4579 private static final DrawFilter sZoomFilter =
4580 new PaintFlagsDrawFilter(ZOOM_BITS, Paint.LINEAR_TEXT_FLAG);
4581 private final Picture mPicture;
4582 private final float mScale;
4583 private final int mScrollX;
4584 private final int mScrollY;
4585 final TabControl.Tab mTab;
4586
4587 AnimatingView(Context ctxt, TabControl.Tab t) {
4588 super(ctxt);
4589 mTab = t;
Patrick Scottae641ac2009-04-20 13:51:49 -04004590 if (t != null && t.getTopWindow() != null) {
4591 // Use the top window in the animation since the tab overview
4592 // will display the top window in each cell.
4593 final WebView w = t.getTopWindow();
4594 mPicture = w.capturePicture();
4595 mScale = w.getScale() / w.getWidth();
4596 mScrollX = w.getScrollX();
4597 mScrollY = w.getScrollY();
4598 } else {
4599 mPicture = null;
4600 mScale = 1.0f;
4601 mScrollX = mScrollY = 0;
4602 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004603 }
4604
4605 @Override
4606 protected void onDraw(Canvas canvas) {
4607 canvas.save();
4608 canvas.drawColor(Color.WHITE);
4609 if (mPicture != null) {
4610 canvas.setDrawFilter(sZoomFilter);
4611 float scale = getWidth() * mScale;
4612 canvas.scale(scale, scale);
4613 canvas.translate(-mScrollX, -mScrollY);
4614 canvas.drawPicture(mPicture);
4615 }
4616 canvas.restore();
4617 }
4618 }
4619
4620 /**
4621 * Open the tab picker. This function will always use the current tab in
4622 * its animation.
4623 * @param stay boolean stating whether the tab picker is to remain open
4624 * (in which case it needs a listener and its menu) or not.
4625 * @param index The index of the tab to show as the selection in the tab
4626 * overview.
4627 * @param remove If true, the tab at index will be removed after the
4628 * animation completes.
4629 */
4630 private void tabPicker(final boolean stay, final int index,
4631 final boolean remove) {
4632 if (mTabOverview != null) {
4633 return;
4634 }
4635
4636 int size = mTabControl.getTabCount();
4637
4638 TabListener l = null;
4639 if (stay) {
4640 l = mTabListener = new TabListener();
4641 }
4642 mTabOverview = new ImageGrid(this, stay, l);
4643
4644 for (int i = 0; i < size; i++) {
4645 final TabControl.Tab t = mTabControl.getTab(i);
4646 mTabControl.populatePickerData(t);
4647 mTabOverview.add(t);
4648 }
4649
4650 // Tell the tab overview to show the current tab, the tab overview will
4651 // handle the "New Tab" case.
4652 int currentIndex = mTabControl.getCurrentIndex();
4653 mTabOverview.setCurrentIndex(currentIndex);
4654
4655 // Attach the tab overview.
4656 mContentView.addView(mTabOverview, COVER_SCREEN_PARAMS);
4657
4658 // Create a fake AnimatingView to animate the WebView's picture.
4659 final TabControl.Tab current = mTabControl.getCurrentTab();
4660 final AnimatingView v = new AnimatingView(this, current);
4661 mContentView.addView(v, COVER_SCREEN_PARAMS);
4662 removeTabFromContentView(current);
4663 // Pause timers to get the animation smoother.
4664 current.getWebView().pauseTimers();
4665
4666 // Send a message so the tab picker has a chance to layout and get
4667 // positions for all the cells.
4668 mHandler.sendMessage(mHandler.obtainMessage(ANIMATE_TO_OVERVIEW,
4669 index, remove ? 1 : 0, v));
4670 // Setting this will indicate that we are animating to the overview. We
4671 // set it here to prevent another request to animate from coming in
4672 // between now and when ANIMATE_TO_OVERVIEW is handled.
4673 mAnimationCount++;
4674 // Always change the title bar to the window overview title while
4675 // animating.
Leon Scroggins81db3662009-06-04 17:45:11 -04004676 if (CUSTOM_BROWSER_BAR) {
4677 mTitleBar.setToTabPicker();
4678 } else {
4679 getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON, null);
4680 getWindow().setFeatureDrawable(Window.FEATURE_RIGHT_ICON, null);
4681 getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
4682 Window.PROGRESS_VISIBILITY_OFF);
4683 setTitle(R.string.tab_picker_title);
4684 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004685 // Make the menu empty until the animation completes.
4686 mMenuState = EMPTY_MENU;
4687 }
4688
Leon Scrogginse4b3bda2009-06-09 15:46:41 -04004689 /* package */ void bookmarksOrHistoryPicker(boolean startWithHistory) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004690 WebView current = mTabControl.getCurrentWebView();
4691 if (current == null) {
4692 return;
4693 }
4694 Intent intent = new Intent(this,
4695 CombinedBookmarkHistoryActivity.class);
4696 String title = current.getTitle();
4697 String url = current.getUrl();
4698 // Just in case the user opens bookmarks before a page finishes loading
4699 // so the current history item, and therefore the page, is null.
4700 if (null == url) {
4701 url = mLastEnteredUrl;
4702 // This can happen.
4703 if (null == url) {
4704 url = mSettings.getHomePage();
4705 }
4706 }
4707 // In case the web page has not yet received its associated title.
4708 if (title == null) {
4709 title = url;
4710 }
4711 intent.putExtra("title", title);
4712 intent.putExtra("url", url);
4713 intent.putExtra("maxTabsOpen",
4714 mTabControl.getTabCount() >= TabControl.MAX_TABS);
4715 if (startWithHistory) {
4716 intent.putExtra(CombinedBookmarkHistoryActivity.STARTING_TAB,
4717 CombinedBookmarkHistoryActivity.HISTORY_TAB);
4718 }
4719 startActivityForResult(intent, COMBO_PAGE);
4720 }
4721
4722 // Called when loading from context menu or LOAD_URL message
4723 private void loadURL(WebView view, String url) {
4724 // In case the user enters nothing.
4725 if (url != null && url.length() != 0 && view != null) {
4726 url = smartUrlFilter(url);
4727 if (!mWebViewClient.shouldOverrideUrlLoading(view, url)) {
4728 view.loadUrl(url);
4729 }
4730 }
4731 }
4732
4733 private void checkMemory() {
4734 ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
4735 ((ActivityManager) getSystemService(ACTIVITY_SERVICE))
4736 .getMemoryInfo(mi);
4737 // FIXME: mi.lowMemory is too aggressive, use (mi.availMem <
4738 // mi.threshold) for now
4739 // if (mi.lowMemory) {
4740 if (mi.availMem < mi.threshold) {
4741 Log.w(LOGTAG, "Browser is freeing memory now because: available="
4742 + (mi.availMem / 1024) + "K threshold="
4743 + (mi.threshold / 1024) + "K");
4744 mTabControl.freeMemory();
4745 }
4746 }
4747
4748 private String smartUrlFilter(Uri inUri) {
4749 if (inUri != null) {
4750 return smartUrlFilter(inUri.toString());
4751 }
4752 return null;
4753 }
4754
4755
4756 // get window count
4757
4758 int getWindowCount(){
4759 if(mTabControl != null){
4760 return mTabControl.getTabCount();
4761 }
4762 return 0;
4763 }
4764
Feng Qianb34f87a2009-03-24 21:27:26 -07004765 protected static final Pattern ACCEPTED_URI_SCHEMA = Pattern.compile(
The Android Open Source Project0c908882009-03-03 19:32:16 -08004766 "(?i)" + // switch on case insensitive matching
4767 "(" + // begin group for schema
4768 "(?:http|https|file):\\/\\/" +
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07004769 "|(?:inline|data|about|content|javascript):" +
The Android Open Source Project0c908882009-03-03 19:32:16 -08004770 ")" +
4771 "(.*)" );
4772
4773 /**
4774 * Attempts to determine whether user input is a URL or search
4775 * terms. Anything with a space is passed to search.
4776 *
4777 * Converts to lowercase any mistakenly uppercased schema (i.e.,
4778 * "Http://" converts to "http://"
4779 *
4780 * @return Original or modified URL
4781 *
4782 */
4783 String smartUrlFilter(String url) {
4784
4785 String inUrl = url.trim();
4786 boolean hasSpace = inUrl.indexOf(' ') != -1;
4787
4788 Matcher matcher = ACCEPTED_URI_SCHEMA.matcher(inUrl);
4789 if (matcher.matches()) {
The Android Open Source Project0c908882009-03-03 19:32:16 -08004790 // force scheme to lowercase
4791 String scheme = matcher.group(1);
4792 String lcScheme = scheme.toLowerCase();
4793 if (!lcScheme.equals(scheme)) {
Mitsuru Oshima123ecfb2009-05-18 19:11:14 -07004794 inUrl = lcScheme + matcher.group(2);
4795 }
4796 if (hasSpace) {
4797 inUrl = inUrl.replace(" ", "%20");
The Android Open Source Project0c908882009-03-03 19:32:16 -08004798 }
4799 return inUrl;
4800 }
4801 if (hasSpace) {
Satish Sampath565505b2009-05-29 15:37:27 +01004802 // FIXME: Is this the correct place to add to searches?
4803 // what if someone else calls this function?
4804 int shortcut = parseUrlShortcut(inUrl);
4805 if (shortcut != SHORTCUT_INVALID) {
4806 Browser.addSearchUrl(mResolver, inUrl);
4807 String query = inUrl.substring(2);
4808 switch (shortcut) {
4809 case SHORTCUT_GOOGLE_SEARCH:
4810 return composeSearchUrl(query);
4811 case SHORTCUT_WIKIPEDIA_SEARCH:
4812 return URLUtil.composeSearchUrl(query, QuickSearch_W, QUERY_PLACE_HOLDER);
4813 case SHORTCUT_DICTIONARY_SEARCH:
4814 return URLUtil.composeSearchUrl(query, QuickSearch_D, QUERY_PLACE_HOLDER);
4815 case SHORTCUT_GOOGLE_MOBILE_LOCAL_SEARCH:
The Android Open Source Project0c908882009-03-03 19:32:16 -08004816 // FIXME: we need location in this case
Satish Sampath565505b2009-05-29 15:37:27 +01004817 return URLUtil.composeSearchUrl(query, QuickSearch_L, QUERY_PLACE_HOLDER);
The Android Open Source Project0c908882009-03-03 19:32:16 -08004818 }
4819 }
4820 } else {
4821 if (Regex.WEB_URL_PATTERN.matcher(inUrl).matches()) {
4822 return URLUtil.guessUrl(inUrl);
4823 }
4824 }
4825
4826 Browser.addSearchUrl(mResolver, inUrl);
4827 return composeSearchUrl(inUrl);
4828 }
4829
4830 /* package */ String composeSearchUrl(String search) {
4831 return URLUtil.composeSearchUrl(search, QuickSearch_G,
4832 QUERY_PLACE_HOLDER);
4833 }
4834
4835 /* package */void setBaseSearchUrl(String url) {
4836 if (url == null || url.length() == 0) {
4837 /*
4838 * get the google search url based on the SIM. Default is US. NOTE:
4839 * This code uses resources to optionally select the search Uri,
4840 * based on the MCC value from the SIM. The default string will most
4841 * likely be fine. It is parameterized to accept info from the
4842 * Locale, the language code is the first parameter (%1$s) and the
4843 * country code is the second (%2$s). This code must function in the
4844 * same way as a similar lookup in
4845 * com.android.googlesearch.SuggestionProvider#onCreate(). If you
4846 * change either of these functions, change them both. (The same is
4847 * true for the underlying resource strings, which are stored in
4848 * mcc-specific xml files.)
4849 */
4850 Locale l = Locale.getDefault();
Bill Napiere9651c32009-05-05 13:16:30 -07004851 String language = l.getLanguage();
4852 String country = l.getCountry().toLowerCase();
4853 // Chinese and Portuguese have two langauge variants.
4854 if ("zh".equals(language)) {
4855 if ("cn".equals(country)) {
4856 language = "zh-CN";
4857 } else if ("tw".equals(country)) {
4858 language = "zh-TW";
4859 }
4860 } else if ("pt".equals(language)) {
4861 if ("br".equals(country)) {
4862 language = "pt-BR";
4863 } else if ("pt".equals(country)) {
4864 language = "pt-PT";
4865 }
4866 }
The Android Open Source Project0c908882009-03-03 19:32:16 -08004867 QuickSearch_G = getResources().getString(
Bill Napiere9651c32009-05-05 13:16:30 -07004868 R.string.google_search_base,
4869 language,
4870 country)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004871 + "client=ms-"
Ramanan Rajeswarandd4f4292009-03-24 20:41:19 -07004872 + Partner.getString(this.getContentResolver(), Partner.CLIENT_ID)
The Android Open Source Project0c908882009-03-03 19:32:16 -08004873 + "&source=android-" + GOOGLE_SEARCH_SOURCE_SUGGEST + "&q=%s";
4874 } else {
4875 QuickSearch_G = url;
4876 }
4877 }
4878
4879 private final static int LOCK_ICON_UNSECURE = 0;
4880 private final static int LOCK_ICON_SECURE = 1;
4881 private final static int LOCK_ICON_MIXED = 2;
4882
4883 private int mLockIconType = LOCK_ICON_UNSECURE;
4884 private int mPrevLockType = LOCK_ICON_UNSECURE;
4885
4886 private BrowserSettings mSettings;
4887 private TabControl mTabControl;
4888 private ContentResolver mResolver;
4889 private FrameLayout mContentView;
4890 private ImageGrid mTabOverview;
4891
4892 // FIXME, temp address onPrepareMenu performance problem. When we move everything out of
4893 // view, we should rewrite this.
4894 private int mCurrentMenuState = 0;
4895 private int mMenuState = R.id.MAIN_MENU;
4896 private static final int EMPTY_MENU = -1;
4897 private Menu mMenu;
4898
4899 private FindDialog mFindDialog;
4900 // Used to prevent chording to result in firing two shortcuts immediately
4901 // one after another. Fixes bug 1211714.
4902 boolean mCanChord;
4903
4904 private boolean mInLoad;
4905 private boolean mIsNetworkUp;
4906
4907 private boolean mPageStarted;
4908 private boolean mActivityInPause = true;
4909
4910 private boolean mMenuIsDown;
4911
4912 private final KeyTracker mKeyTracker = new KeyTracker(this);
4913
4914 // As trackball doesn't send repeat down, we have to track it ourselves
4915 private boolean mTrackTrackball;
4916
4917 private static boolean mInTrace;
4918
4919 // Performance probe
4920 private static final int[] SYSTEM_CPU_FORMAT = new int[] {
4921 Process.PROC_SPACE_TERM | Process.PROC_COMBINE,
4922 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 1: user time
4923 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 2: nice time
4924 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 3: sys time
4925 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 4: idle time
4926 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 5: iowait time
4927 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG, // 6: irq time
4928 Process.PROC_SPACE_TERM | Process.PROC_OUT_LONG // 7: softirq time
4929 };
4930
4931 private long mStart;
4932 private long mProcessStart;
4933 private long mUserStart;
4934 private long mSystemStart;
4935 private long mIdleStart;
4936 private long mIrqStart;
4937
4938 private long mUiStart;
4939
4940 private Drawable mMixLockIcon;
4941 private Drawable mSecLockIcon;
4942 private Drawable mGenericFavicon;
4943
4944 /* hold a ref so we can auto-cancel if necessary */
4945 private AlertDialog mAlertDialog;
4946
4947 // Wait for credentials before loading google.com
4948 private ProgressDialog mCredsDlg;
4949
4950 // The up-to-date URL and title (these can be different from those stored
4951 // in WebView, since it takes some time for the information in WebView to
4952 // get updated)
4953 private String mUrl;
4954 private String mTitle;
4955
4956 // As PageInfo has different style for landscape / portrait, we have
4957 // to re-open it when configuration changed
4958 private AlertDialog mPageInfoDialog;
4959 private TabControl.Tab mPageInfoView;
4960 // If the Page-Info dialog is launched from the SSL-certificate-on-error
4961 // dialog, we should not just dismiss it, but should get back to the
4962 // SSL-certificate-on-error dialog. This flag is used to store this state
4963 private Boolean mPageInfoFromShowSSLCertificateOnError;
4964
4965 // as SSLCertificateOnError has different style for landscape / portrait,
4966 // we have to re-open it when configuration changed
4967 private AlertDialog mSSLCertificateOnErrorDialog;
4968 private WebView mSSLCertificateOnErrorView;
4969 private SslErrorHandler mSSLCertificateOnErrorHandler;
4970 private SslError mSSLCertificateOnErrorError;
4971
4972 // as SSLCertificate has different style for landscape / portrait, we
4973 // have to re-open it when configuration changed
4974 private AlertDialog mSSLCertificateDialog;
4975 private TabControl.Tab mSSLCertificateView;
4976
4977 // as HttpAuthentication has different style for landscape / portrait, we
4978 // have to re-open it when configuration changed
4979 private AlertDialog mHttpAuthenticationDialog;
4980 private HttpAuthHandler mHttpAuthHandler;
4981
4982 /*package*/ static final FrameLayout.LayoutParams COVER_SCREEN_PARAMS =
4983 new FrameLayout.LayoutParams(
4984 ViewGroup.LayoutParams.FILL_PARENT,
4985 ViewGroup.LayoutParams.FILL_PARENT);
4986 // We may provide UI to customize these
4987 // Google search from the browser
4988 static String QuickSearch_G;
4989 // Wikipedia search
4990 final static String QuickSearch_W = "http://en.wikipedia.org/w/index.php?search=%s&go=Go";
4991 // Dictionary search
4992 final static String QuickSearch_D = "http://dictionary.reference.com/search?q=%s";
4993 // Google Mobile Local search
4994 final static String QuickSearch_L = "http://www.google.com/m/search?site=local&q=%s&near=mountain+view";
4995
4996 final static String QUERY_PLACE_HOLDER = "%s";
4997
4998 // "source" parameter for Google search through search key
4999 final static String GOOGLE_SEARCH_SOURCE_SEARCHKEY = "browser-key";
5000 // "source" parameter for Google search through goto menu
5001 final static String GOOGLE_SEARCH_SOURCE_GOTO = "browser-goto";
5002 // "source" parameter for Google search through simplily type
5003 final static String GOOGLE_SEARCH_SOURCE_TYPE = "browser-type";
5004 // "source" parameter for Google search suggested by the browser
5005 final static String GOOGLE_SEARCH_SOURCE_SUGGEST = "browser-suggest";
5006 // "source" parameter for Google search from unknown source
5007 final static String GOOGLE_SEARCH_SOURCE_UNKNOWN = "unknown";
5008
5009 private final static String LOGTAG = "browser";
5010
5011 private TabListener mTabListener;
5012
5013 private String mLastEnteredUrl;
5014
5015 private PowerManager.WakeLock mWakeLock;
5016 private final static int WAKELOCK_TIMEOUT = 5 * 60 * 1000; // 5 minutes
5017
5018 private Toast mStopToast;
5019
Leon Scroggins81db3662009-06-04 17:45:11 -04005020 private TitleBar mTitleBar;
5021
The Android Open Source Project0c908882009-03-03 19:32:16 -08005022 // Used during animations to prevent other animations from being triggered.
5023 // A count is used since the animation to and from the Window overview can
5024 // overlap. A count of 0 means no animation where a count of > 0 means
5025 // there are animations in progress.
5026 private int mAnimationCount;
5027
5028 // As the ids are dynamically created, we can't guarantee that they will
5029 // be in sequence, so this static array maps ids to a window number.
5030 final static private int[] WINDOW_SHORTCUT_ID_ARRAY =
5031 { R.id.window_one_menu_id, R.id.window_two_menu_id, R.id.window_three_menu_id,
5032 R.id.window_four_menu_id, R.id.window_five_menu_id, R.id.window_six_menu_id,
5033 R.id.window_seven_menu_id, R.id.window_eight_menu_id };
5034
5035 // monitor platform changes
5036 private IntentFilter mNetworkStateChangedFilter;
5037 private BroadcastReceiver mNetworkStateIntentReceiver;
5038
Grace Klobab4da0ad2009-05-14 14:45:40 -07005039 private BroadcastReceiver mPackageInstallationReceiver;
5040
The Android Open Source Project0c908882009-03-03 19:32:16 -08005041 // activity requestCode
Nicolas Roard78a98e42009-05-11 13:34:17 +01005042 final static int COMBO_PAGE = 1;
5043 final static int DOWNLOAD_PAGE = 2;
5044 final static int PREFERENCES_PAGE = 3;
5045 final static int WEBSTORAGE_QUOTA_DIALOG = 4;
The Android Open Source Project0c908882009-03-03 19:32:16 -08005046
5047 // the frenquency of checking whether system memory is low
5048 final static int CHECK_MEMORY_INTERVAL = 30000; // 30 seconds
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005049
5050 /**
5051 * A UrlData class to abstract how the content will be set to WebView.
5052 * This base class uses loadUrl to show the content.
5053 */
5054 private static class UrlData {
5055 String mUrl;
Grace Kloba60e095c2009-06-16 11:50:55 -07005056 byte[] mPostData;
5057
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005058 UrlData(String url) {
5059 this.mUrl = url;
5060 }
Grace Kloba60e095c2009-06-16 11:50:55 -07005061
5062 void setPostData(byte[] postData) {
5063 mPostData = postData;
5064 }
5065
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005066 boolean isEmpty() {
5067 return mUrl == null || mUrl.length() == 0;
5068 }
5069
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005070 public void loadIn(WebView webView) {
Grace Kloba60e095c2009-06-16 11:50:55 -07005071 if (mPostData != null) {
5072 webView.postUrl(mUrl, mPostData);
5073 } else {
5074 webView.loadUrl(mUrl);
5075 }
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005076 }
5077 };
5078
5079 /**
5080 * A subclass of UrlData class that can display inlined content using
5081 * {@link WebView#loadDataWithBaseURL(String, String, String, String, String)}.
5082 */
5083 private static class InlinedUrlData extends UrlData {
5084 InlinedUrlData(String inlined, String mimeType, String encoding, String failUrl) {
5085 super(failUrl);
5086 mInlined = inlined;
5087 mMimeType = mimeType;
5088 mEncoding = encoding;
5089 }
5090 String mMimeType;
5091 String mInlined;
5092 String mEncoding;
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005093 @Override
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005094 boolean isEmpty() {
5095 return mInlined == null || mInlined.length() == 0 || super.isEmpty();
5096 }
5097
Mitsuru Oshima7944b7d2009-06-16 16:34:51 -07005098 @Override
5099 public void loadIn(WebView webView) {
Mitsuru Oshima25ad8ab2009-06-10 16:26:07 -07005100 webView.loadDataWithBaseURL(null, mInlined, mMimeType, mEncoding, mUrl);
5101 }
5102 }
5103
5104 private static final UrlData EMPTY_URL_DATA = new UrlData(null);
The Android Open Source Project0c908882009-03-03 19:32:16 -08005105}