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