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