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