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