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