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