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