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