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